id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_186_4 | /*
* ECDSA implemenation
* (C) 2007 Manuel Hartl, FlexSecure GmbH
* 2007 Falko Strenzke, FlexSecure GmbH
* 2008-2010,2015,2016,2018 Jack Lloyd
* 2016 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/ecdsa.h>
#include <botan/internal/pk_ops_impl.h>
#include <botan/internal/point_mul.h>
#include <botan/keypair.h>
#include <botan/reducer.h>
#include <botan/emsa.h>
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
#include <botan/rfc6979.h>
#endif
#if defined(BOTAN_HAS_BEARSSL)
#include <botan/internal/bearssl.h>
#endif
#if defined(BOTAN_HAS_OPENSSL)
#include <botan/internal/openssl.h>
#endif
namespace Botan {
bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng,
bool strong) const
{
if(!public_point().on_the_curve())
return false;
if(!strong)
return true;
return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-256)");
}
namespace {
/**
* ECDSA signature operation
*/
class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA
{
public:
ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,
const std::string& emsa) :
PK_Ops::Signature_with_EMSA(emsa),
m_group(ecdsa.domain()),
m_x(ecdsa.private_value())
{
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
m_rfc6979_hash = hash_for_emsa(emsa);
#endif
}
size_t max_input_bits() const override { return m_group.get_order_bits(); }
secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng) override;
private:
const EC_Group m_group;
const BigInt& m_x;
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
std::string m_rfc6979_hash;
#endif
std::vector<BigInt> m_ws;
};
secure_vector<uint8_t>
ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
BigInt m(msg, msg_len, m_group.get_order_bits());
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);
#else
const BigInt k = m_group.random_scalar(rng);
#endif
const BigInt k_inv = m_group.inverse_mod_order(k);
const BigInt r = m_group.mod_order(
m_group.blinded_base_point_multiply_x(k, rng, m_ws));
const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);
const BigInt s = m_group.multiply_mod_order(k_inv, xrm);
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("During ECDSA signature generated zero r/s");
return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());
}
/**
* ECDSA verification operation
*/
class ECDSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA
{
public:
ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa,
const std::string& emsa) :
PK_Ops::Verification_with_EMSA(emsa),
m_group(ecdsa.domain()),
m_gy_mul(m_group.get_base_point(), ecdsa.public_point())
{
}
size_t max_input_bits() const override { return m_group.get_order_bits(); }
bool with_recovery() const override { return false; }
bool verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len) override;
private:
const EC_Group m_group;
const PointGFp_Multi_Point_Precompute m_gy_mul;
};
bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len)
{
if(sig_len != m_group.get_order_bytes() * 2)
return false;
const BigInt e(msg, msg_len, m_group.get_order_bits());
const BigInt r(sig, sig_len / 2);
const BigInt s(sig + sig_len / 2, sig_len / 2);
if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())
return false;
const BigInt w = m_group.inverse_mod_order(s);
const BigInt u1 = m_group.multiply_mod_order(e, w);
const BigInt u2 = m_group.multiply_mod_order(r, w);
const PointGFp R = m_gy_mul.multi_exp(u1, u2);
if(R.is_zero())
return false;
const BigInt v = m_group.mod_order(R.get_affine_x());
return (v == r);
}
}
std::unique_ptr<PK_Ops::Verification>
ECDSA_PublicKey::create_verification_op(const std::string& params,
const std::string& provider) const
{
#if defined(BOTAN_HAS_BEARSSL)
if(provider == "bearssl" || provider.empty())
{
try
{
return make_bearssl_ecdsa_ver_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "bearssl")
throw;
}
}
#endif
#if defined(BOTAN_HAS_OPENSSL)
if(provider == "openssl" || provider.empty())
{
try
{
return make_openssl_ecdsa_ver_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "openssl")
throw;
}
}
#endif
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Verification>(new ECDSA_Verification_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
}
std::unique_ptr<PK_Ops::Signature>
ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
const std::string& params,
const std::string& provider) const
{
#if defined(BOTAN_HAS_BEARSSL)
if(provider == "bearssl" || provider.empty())
{
try
{
return make_bearssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "bearssl")
throw;
}
}
#endif
#if defined(BOTAN_HAS_OPENSSL)
if(provider == "openssl" || provider.empty())
{
try
{
return make_openssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "openssl")
throw;
}
}
#endif
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_186_4 |
crossvul-cpp_data_bad_1810_1 | /****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
*/
#include <cassert>
#include <cstring>
#include "ebml/EbmlElement.h"
#include "ebml/EbmlMaster.h"
#include "ebml/EbmlStream.h"
#include "ebml/EbmlVoid.h"
#include "ebml/EbmlDummy.h"
#include "ebml/EbmlContexts.h"
START_LIBEBML_NAMESPACE
/*!
\todo handle more than CodedSize of 5
*/
int CodedSizeLength(uint64 Length, unsigned int SizeLength, bool bSizeFinite)
{
unsigned int CodedSize;
if (bSizeFinite) {
// prepare the head of the size (000...01xxxxxx)
// optimal size
if (Length < 127) // 2^7 - 1
CodedSize = 1;
else if (Length < 16383) // 2^14 - 1
CodedSize = 2;
else if (Length < 2097151L) // 2^21 - 1
CodedSize = 3;
else if (Length < 268435455L) // 2^28 - 1
CodedSize = 4;
else CodedSize = 5;
} else {
if (Length <= 127) // 2^7 - 1
CodedSize = 1;
else if (Length <= 16383) // 2^14 - 1
CodedSize = 2;
else if (Length <= 2097151L) // 2^21 - 1
CodedSize = 3;
else if (Length <= 268435455L) // 2^28 - 1
CodedSize = 4;
else CodedSize = 5;
}
if (SizeLength > 0 && CodedSize < SizeLength) {
// defined size
CodedSize = SizeLength;
}
return CodedSize;
}
/*!
\todo handle more than CodedSize of 5
*/
int CodedSizeLengthSigned(int64 Length, unsigned int SizeLength)
{
unsigned int CodedSize;
// prepare the head of the size (000...01xxxxxx)
// optimal size
if (Length > -64 && Length < 64) // 2^6
CodedSize = 1;
else if (Length > -8192 && Length < 8192) // 2^13
CodedSize = 2;
else if (Length > -1048576L && Length < 1048576L) // 2^20
CodedSize = 3;
else if (Length > -134217728L && Length < 134217728L) // 2^27
CodedSize = 4;
else CodedSize = 5;
if (SizeLength > 0 && CodedSize < SizeLength) {
// defined size
CodedSize = SizeLength;
}
return CodedSize;
}
int CodedValueLength(uint64 Length, int CodedSize, binary * OutBuffer)
{
int _SizeMask = 0xFF;
OutBuffer[0] = 1 << (8 - CodedSize);
for (int i=1; i<CodedSize; i++) {
OutBuffer[CodedSize-i] = Length & 0xFF;
Length >>= 8;
_SizeMask >>= 1;
}
// first one use a OR with the "EBML size head"
OutBuffer[0] |= Length & 0xFF & _SizeMask;
return CodedSize;
}
int CodedValueLengthSigned(int64 Length, int CodedSize, binary * OutBuffer)
{
if (Length > -64 && Length < 64) // 2^6
Length += 63;
else if (Length > -8192 && Length < 8192) // 2^13
Length += 8191;
else if (Length > -1048576L && Length < 1048576L) // 2^20
Length += 1048575L;
else if (Length > -134217728L && Length < 134217728L) // 2^27
Length += 134217727L;
return CodedValueLength(Length, CodedSize, OutBuffer);
}
uint64 ReadCodedSizeValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)
{
binary SizeBitMask = 1 << 7;
uint64 Result = 0x7F;
unsigned int SizeIdx, PossibleSizeLength = 0;
binary PossibleSize[8];
memset(PossibleSize, 0, 8);
SizeUnknown = 0x7F; // the last bit is discarded when computing the size
for (SizeIdx = 0; SizeIdx < BufferSize && SizeIdx < 8; SizeIdx++) {
if (InBuffer[0] & (SizeBitMask >> SizeIdx)) {
// ID found
PossibleSizeLength = SizeIdx + 1;
SizeBitMask >>= SizeIdx;
for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) {
PossibleSize[SizeIdx] = InBuffer[SizeIdx];
}
for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) {
Result <<= 7;
Result |= 0xFF;
}
Result = 0;
Result |= PossibleSize[0] & ~SizeBitMask;
for (unsigned int i = 1; i<PossibleSizeLength; i++) {
Result <<= 8;
Result |= PossibleSize[i];
}
BufferSize = PossibleSizeLength;
return Result;
}
SizeUnknown <<= 7;
SizeUnknown |= 0xFF;
}
BufferSize = 0;
return 0;
}
int64 ReadCodedSizeSignedValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)
{
int64 Result = ReadCodedSizeValue(InBuffer, BufferSize, SizeUnknown);
if (BufferSize != 0) {
switch (BufferSize) {
case 1:
Result -= 63;
break;
case 2:
Result -= 8191;
break;
case 3:
Result -= 1048575L;
break;
case 4:
Result -= 134217727L;
break;
}
}
return Result;
}
EbmlCallbacks::EbmlCallbacks(EbmlElement & (*Creator)(), const EbmlId & aGlobalId, const char * aDebugName, const EbmlSemanticContext & aContext)
:Create(Creator)
,GlobalId(aGlobalId)
,DebugName(aDebugName)
,Context(aContext)
{
assert((Create!=NULL) || !strcmp(aDebugName, "DummyElement"));
}
const EbmlSemantic & EbmlSemanticContext::GetSemantic(size_t i) const
{
assert(i<Size);
if (i<Size)
return MyTable[i];
else
return *(EbmlSemantic*)NULL;
}
EbmlElement::EbmlElement(uint64 aDefaultSize, bool bValueSet)
:DefaultSize(aDefaultSize)
,SizeLength(0) ///< write optimal size by default
,bSizeIsFinite(true)
,ElementPosition(0)
,SizePosition(0)
,bValueIsSet(bValueSet)
,DefaultIsSet(false)
,bLocked(false)
{
Size = DefaultSize;
}
EbmlElement::EbmlElement(const EbmlElement & ElementToClone)
:Size(ElementToClone.Size)
,DefaultSize(ElementToClone.DefaultSize)
,SizeLength(ElementToClone.SizeLength)
,bSizeIsFinite(ElementToClone.bSizeIsFinite)
,ElementPosition(ElementToClone.ElementPosition)
,SizePosition(ElementToClone.SizePosition)
,bValueIsSet(ElementToClone.bValueIsSet)
,DefaultIsSet(ElementToClone.DefaultIsSet)
,bLocked(ElementToClone.bLocked)
{
}
EbmlElement::~EbmlElement()
{
assert(!bLocked);
}
/*!
\todo this method is deprecated and should be called FindThisID
\todo replace the new RawElement with the appropriate class (when known)
*/
EbmlElement * EbmlElement::FindNextID(IOCallback & DataStream, const EbmlCallbacks & ClassInfos, uint64 MaxDataSize)
{
binary PossibleId[4];
int PossibleID_Length = 0;
binary PossibleSize[8]; // we don't support size stored in more than 64 bits
uint32 PossibleSizeLength = 0;
uint64 SizeUnknown;
uint64 SizeFound;
bool bElementFound = false;
binary BitMask;
uint64 aElementPosition, aSizePosition;
while (!bElementFound) {
// read ID
aElementPosition = DataStream.getFilePointer();
uint32 ReadSize = 0;
BitMask = 1 << 7;
while (1) {
ReadSize += DataStream.read(&PossibleId[PossibleID_Length], 1);
if (ReadSize == uint32(PossibleID_Length)) {
return NULL; // no more data ?
}
if (++PossibleID_Length > 4) {
return NULL; // we don't support element IDs over class D
}
if (PossibleId[0] & BitMask) {
// this is the last octet of the ID
// check wether that's the one we're looking for
/* if (PossibleID == EBML_INFO_ID(ClassInfos)) {
break;
} else {
/// \todo This element should be skipped (use a context ?)
}*/
bElementFound = true; /// \todo not exactly the one we're looking for
break;
}
BitMask >>= 1;
}
// read the data size
aSizePosition = DataStream.getFilePointer();
uint32 _SizeLength;
do {
if (PossibleSizeLength >= 8)
// Size is larger than 8 bytes
return NULL;
ReadSize += DataStream.read(&PossibleSize[PossibleSizeLength++], 1);
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleSize[0], _SizeLength, SizeUnknown);
} while (_SizeLength == 0);
}
EbmlElement *Result = NULL;
EbmlId PossibleID(PossibleId, PossibleID_Length);
if (PossibleID == EBML_INFO_ID(ClassInfos)) {
// the element is the one expected
Result = &EBML_INFO_CREATE(ClassInfos);
} else {
/// \todo find the element in the context
Result = new (std::nothrow) EbmlDummy(PossibleID);
if(Result == NULL)
return NULL;
}
Result->SetSizeLength(PossibleSizeLength);
Result->Size = SizeFound;
if (!Result->ValidateSize() || (SizeFound != SizeUnknown && MaxDataSize < Result->Size)) {
delete Result;
return NULL;
}
// check if the size is not all 1s
if (SizeFound == SizeUnknown) {
// Size of this element is unknown
// only possible for Master elements
if (!Result->SetSizeInfinite()) {
/// \todo the element is not allowed to be infinite
delete Result;
return NULL;
}
} else Result->SetSizeInfinite(false);
Result->ElementPosition = aElementPosition;
Result->SizePosition = aSizePosition;
return Result;
}
/*!
\todo replace the new RawElement with the appropriate class (when known)
\todo skip data for Dummy elements when they are not allowed
\todo better check of the size checking for upper elements (using a list of size for each level)
\param LowLevel Will be returned with the level of the element found compared to the context given
*/
EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel,
uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel)
{
int PossibleID_Length = 0;
binary PossibleIdNSize[16];
int PossibleSizeLength;
uint64 SizeUnknown;
int ReadIndex = 0; // trick for the algo, start index at 0
uint32 ReadSize = 0;
uint64 SizeFound;
int SizeIdx;
bool bFound;
int UpperLevel_original = UpperLevel;
do {
// read a potential ID
do {
assert(ReadIndex < 16);
// build the ID with the current Read Buffer
bFound = false;
binary IdBitMask = 1 << 7;
for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) {
if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) {
// ID found
PossibleID_Length = SizeIdx + 1;
IdBitMask >>= SizeIdx;
bFound = true;
break;
}
}
if (bFound) {
break;
}
if (ReadIndex >= 4) {
// ID not found
// shift left the read octets
memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex);
}
if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {
return NULL; // no more data ?
}
ReadSize++;
} while (!bFound && MaxDataSize > ReadSize);
SizeIdx = ReadIndex;
ReadIndex -= PossibleID_Length;
// read the data size
uint32 _SizeLength;
PossibleSizeLength = ReadIndex;
while (1) {
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown);
if (_SizeLength != 0) {
bFound = true;
break;
}
if (PossibleSizeLength >= 8) {
bFound = false;
break;
}
if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) {
return NULL; // no more data ?
}
ReadSize++;
PossibleSizeLength++;
}
if (bFound) {
// find the element in the context and use the correct creator
EbmlId PossibleID(PossibleIdNSize, PossibleID_Length);
EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel);
///< \todo continue is misplaced
if (Result != NULL) {
if (AllowDummyElt || !Result->IsDummy()) {
Result->SetSizeLength(_SizeLength);
Result->Size = SizeFound;
// UpperLevel values
// -1 : global element
// 0 : child
// 1 : same level
// + : further parent
if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) {
if (SizeFound == SizeUnknown) {
Result->SetSizeInfinite();
}
Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID);
Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID);
// place the file at the beggining of the data
DataStream.setFilePointer(Result->SizePosition + _SizeLength);
return Result;
}
}
delete Result;
}
}
// recover all the data in the buffer minus one byte
ReadIndex = SizeIdx - 1;
memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex);
UpperLevel = UpperLevel_original;
} while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length );
return NULL;
}
/*!
\todo what happens if we are in a upper element with a known size ?
*/
EbmlElement * EbmlElement::SkipData(EbmlStream & DataStream, const EbmlSemanticContext & Context, EbmlElement * TestReadElt, bool AllowDummyElt)
{
EbmlElement * Result = NULL;
if (bSizeIsFinite) {
assert(TestReadElt == NULL);
assert(ElementPosition < SizePosition);
DataStream.I_O().setFilePointer(SizePosition + CodedSizeLength(Size, SizeLength, bSizeIsFinite) + Size, seek_beginning);
// DataStream.I_O().setFilePointer(Size, seek_current);
} else {
/////////////////////////////////////////////////
// read elements until an upper element is found
/////////////////////////////////////////////////
bool bEndFound = false;
while (!bEndFound && Result == NULL) {
// read an element
/// \todo 0xFF... and true should be configurable
// EbmlElement * NewElt;
if (TestReadElt == NULL) {
int bUpperElement = 0; // trick to call FindNextID correctly
Result = DataStream.FindNextElement(Context, bUpperElement, 0xFFFFFFFFL, AllowDummyElt);
} else {
Result = TestReadElt;
TestReadElt = NULL;
}
if (Result != NULL) {
unsigned int EltIndex;
// data known in this Master's context
for (EltIndex = 0; EltIndex < EBML_CTX_SIZE(Context); EltIndex++) {
if (EbmlId(*Result) == EBML_CTX_IDX_ID(Context,EltIndex)) {
// skip the data with its own context
Result = Result->SkipData(DataStream, EBML_SEM_CONTEXT(EBML_CTX_IDX(Context,EltIndex)), NULL);
break; // let's go to the next ID
}
}
if (EltIndex >= EBML_CTX_SIZE(Context)) {
if (EBML_CTX_PARENT(Context) != NULL) {
Result = SkipData(DataStream, *EBML_CTX_PARENT(Context), Result);
} else {
assert(Context.GetGlobalContext != NULL);
if (Context != Context.GetGlobalContext()) {
Result = SkipData(DataStream, Context.GetGlobalContext(), Result);
} else {
bEndFound = true;
}
}
}
} else {
bEndFound = true;
}
}
}
return Result;
}
EbmlElement *EbmlElement::CreateElementUsingContext(const EbmlId & aID, const EbmlSemanticContext & Context,
int & LowLevel, bool IsGlobalContext, bool bAllowDummy, unsigned int MaxLowerLevel)
{
unsigned int ContextIndex;
EbmlElement *Result = NULL;
// elements at the current level
for (ContextIndex = 0; ContextIndex < EBML_CTX_SIZE(Context); ContextIndex++) {
if (aID == EBML_CTX_IDX_ID(Context,ContextIndex)) {
return &EBML_SEM_CREATE(EBML_CTX_IDX(Context,ContextIndex));
}
}
// global elements
assert(Context.GetGlobalContext != NULL); // global should always exist, at least the EBML ones
const EbmlSemanticContext & tstContext = Context.GetGlobalContext();
if (tstContext != Context) {
LowLevel--;
MaxLowerLevel--;
// recursive is good, but be carefull...
Result = CreateElementUsingContext(aID, tstContext, LowLevel, true, bAllowDummy, MaxLowerLevel);
if (Result != NULL) {
return Result;
}
LowLevel++;
MaxLowerLevel++;
} else {
return NULL;
}
// parent elements
if (EBML_CTX_MASTER(Context) != NULL && aID == EBML_INFO_ID(*EBML_CTX_MASTER(Context))) {
LowLevel++; // already one level up (same as context)
return &EBML_INFO_CREATE(*EBML_CTX_MASTER(Context));
}
// check wether it's not part of an upper context
if (EBML_CTX_PARENT(Context) != NULL) {
LowLevel++;
MaxLowerLevel++;
return CreateElementUsingContext(aID, *EBML_CTX_PARENT(Context), LowLevel, IsGlobalContext, bAllowDummy, MaxLowerLevel);
}
if (!IsGlobalContext && bAllowDummy) {
LowLevel = 0;
Result = new (std::nothrow) EbmlDummy(aID);
}
return Result;
}
/*!
\todo verify that the size written is the same as the data written
*/
filepos_t EbmlElement::Render(IOCallback & output, bool bWithDefault, bool bKeepPosition, bool bForceRender)
{
assert(bValueIsSet || (bWithDefault && DefaultISset())); // an element is been rendered without a value set !!!
// it may be a mandatory element without a default value
if (!bWithDefault && IsDefaultValue()) {
return 0;
}
#if defined(LIBEBML_DEBUG)
uint64 SupposedSize = UpdateSize(bWithDefault, bForceRender);
#endif // LIBEBML_DEBUG
filepos_t result = RenderHead(output, bForceRender, bWithDefault, bKeepPosition);
uint64 WrittenSize = RenderData(output, bForceRender, bWithDefault);
#if defined(LIBEBML_DEBUG)
if (static_cast<int64>(SupposedSize) != (0-1))
assert(WrittenSize == SupposedSize);
#endif // LIBEBML_DEBUG
result += WrittenSize;
return result;
}
/*!
\todo store the position of the Size writing for elements with unknown size
\todo handle exceptions on errors
\todo handle CodeSize bigger than 5 bytes
*/
filepos_t EbmlElement::RenderHead(IOCallback & output, bool bForceRender, bool bWithDefault, bool bKeepPosition)
{
if (EBML_ID_LENGTH((const EbmlId&)*this) <= 0 || EBML_ID_LENGTH((const EbmlId&)*this) > 4)
return 0;
UpdateSize(bWithDefault, bForceRender);
return MakeRenderHead(output, bKeepPosition);
}
filepos_t EbmlElement::MakeRenderHead(IOCallback & output, bool bKeepPosition)
{
binary FinalHead[4+8]; // Class D + 64 bits coded size
unsigned int FinalHeadSize;
FinalHeadSize = EBML_ID_LENGTH((const EbmlId&)*this);
EbmlId(*this).Fill(FinalHead);
int CodedSize = CodedSizeLength(Size, SizeLength, bSizeIsFinite);
CodedValueLength(Size, CodedSize, &FinalHead[FinalHeadSize]);
FinalHeadSize += CodedSize;
output.writeFully(FinalHead, FinalHeadSize);
if (!bKeepPosition) {
ElementPosition = output.getFilePointer() - FinalHeadSize;
SizePosition = ElementPosition + EBML_ID_LENGTH((const EbmlId&)*this);
}
return FinalHeadSize;
}
uint64 EbmlElement::ElementSize(bool bWithDefault) const
{
if (!bWithDefault && IsDefaultValue())
return 0; // won't be saved
return Size + EBML_ID_LENGTH((const EbmlId&)*this) + CodedSizeLength(Size, SizeLength, bSizeIsFinite);
}
bool EbmlElement::IsSmallerThan(const EbmlElement *Cmp) const
{
return EbmlId(*this) == EbmlId(*Cmp);
}
bool EbmlElement::CompareElements(const EbmlElement *A, const EbmlElement *B)
{
if (EbmlId(*A) == EbmlId(*B))
return A->IsSmallerThan(B);
else
return false;
}
void EbmlElement::Read(EbmlStream & inDataStream, const EbmlSemanticContext & /* Context */, int & /* UpperEltFound */, EbmlElement * & /* FoundElt */, bool /* AllowDummyElt */, ScopeMode ReadFully)
{
ReadData(inDataStream.I_O(), ReadFully);
}
bool EbmlElement::ForceSize(uint64 NewSize)
{
if (bSizeIsFinite) {
return false;
}
int OldSizeLen = CodedSizeLength(Size, SizeLength, bSizeIsFinite);
uint64 OldSize = Size;
Size = NewSize;
if (CodedSizeLength(Size, SizeLength, bSizeIsFinite) == OldSizeLen) {
bSizeIsFinite = true;
return true;
}
Size = OldSize;
return false;
}
filepos_t EbmlElement::OverwriteHead(IOCallback & output, bool bKeepPosition)
{
if (ElementPosition == 0) {
return 0; // the element has not been written
}
uint64 CurrentPosition = output.getFilePointer();
output.setFilePointer(GetElementPosition());
filepos_t Result = MakeRenderHead(output, bKeepPosition);
output.setFilePointer(CurrentPosition);
return Result;
}
uint64 EbmlElement::VoidMe(IOCallback & output, bool bWithDefault)
{
if (ElementPosition == 0) {
return 0; // the element has not been written
}
EbmlVoid Dummy;
return Dummy.Overwrite(*this, output, bWithDefault);
}
END_LIBEBML_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1810_1 |
crossvul-cpp_data_good_1650_2 | /*
Copyright (C) 2003 - 2015 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
// Include files for opendir(3), readdir(3), etc.
// These files may vary from platform to platform,
// since these functions are NOT ANSI-conforming functions.
// They may have to be altered to port to new platforms
//for mkdir
#include <sys/stat.h>
#ifdef _WIN32
#include "filesystem_win32.ii"
#include <cctype>
#else /* !_WIN32 */
#include <unistd.h>
#include <dirent.h>
#include <libgen.h>
#endif /* !_WIN32 */
// for getenv
#include <cerrno>
#include <fstream>
#include <iomanip>
#include <set>
#include <boost/algorithm/string.hpp>
// for strerror
#include <cstring>
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "scoped_resource.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "version.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace {
const mode_t AccessMode = 00770;
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFBase.h>
#endif
namespace filesystem {
void get_files_in_dir(const std::string &directory,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum)
{
// If we have a path to find directories in,
// then convert relative pathnames to be rooted
// on the wesnoth path
if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
std::string dir = game_config::path + "/" + directory;
if(is_directory(dir)) {
get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
return;
}
}
struct stat st;
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
std::string maincfg;
if (directory.empty() || directory[directory.size()-1] == '/')
maincfg = directory + maincfg_filename;
else
maincfg = (directory + "/") + maincfg_filename;
if (::stat(maincfg.c_str(), &st) != -1) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(maincfg);
else
files->push_back(maincfg_filename);
}
return;
}
}
DIR* dir = opendir(directory.c_str());
if(dir == NULL) {
// Probably not a directory, let the caller deal with it.
return;
}
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] == '.')
continue;
#ifdef __APPLE__
// HFS Mac OS X decomposes filenames using combining unicode characters.
// Try to get the precomposed form.
char macname[MAXNAMLEN+1];
CFStringRef cstr = CFStringCreateWithCString(NULL,
entry->d_name,
kCFStringEncodingUTF8);
CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
0, cstr);
CFStringNormalize(mut_str, kCFStringNormalizationFormC);
CFStringGetCString(mut_str,
macname,sizeof(macname)-1,
kCFStringEncodingUTF8);
CFRelease(cstr);
CFRelease(mut_str);
const std::string basename = macname;
#else
// generic Unix
const std::string basename = entry->d_name;
#endif /* !APPLE */
std::string fullname;
if (directory.empty() || directory[directory.size()-1] == '/')
fullname = directory + basename;
else
fullname = directory + "/" + basename;
if (::stat(fullname.c_str(), &st) != -1) {
if (S_ISREG(st.st_mode)) {
if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
continue;
}
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(fullname);
else
files->push_back(basename);
}
if (checksum != NULL) {
if(st.st_mtime > checksum->modified) {
checksum->modified = st.st_mtime;
}
checksum->sum_size += st.st_size;
checksum->nfiles++;
}
} else if (S_ISDIR(st.st_mode)) {
if (filter == SKIP_MEDIA_DIR
&& (basename == "images"|| basename == "sounds"))
continue;
if (reorder == DO_REORDER &&
::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
S_ISREG(st.st_mode)) {
LOG_FS << "_main.cfg found : ";
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH) {
files->push_back(fullname + "/" + maincfg_filename);
LOG_FS << fullname << "/" << maincfg_filename << '\n';
} else {
files->push_back(basename + "/" + maincfg_filename);
LOG_FS << basename << "/" << maincfg_filename << '\n';
}
} else {
// Show what I consider strange
LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory " << std::endl;
}
} else if (dirs != NULL) {
if (mode == ENTIRE_FILE_PATH)
dirs->push_back(fullname);
else
dirs->push_back(basename);
}
}
}
}
closedir(dir);
if(files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
unsigned int foundit = 0;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
// If _initial.cfg needs to be moved (it was found, but not at index 0).
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; --i)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
std::string get_dir(const std::string& dir_path)
{
DIR* dir = opendir(dir_path.c_str());
if(dir == NULL) {
const int res = mkdir(dir_path.c_str(),AccessMode);
if(res == 0) {
dir = opendir(dir_path.c_str());
} else {
ERR_FS << "could not open or create directory: " << dir_path << std::endl;
}
}
if(dir == NULL)
return "";
closedir(dir);
return dir_path;
}
bool make_directory(const std::string& path)
{
return (mkdir(path.c_str(),AccessMode) == 0);
}
// This deletes a directory with no hidden files and subdirectories.
// Also deletes a single file.
bool delete_directory(const std::string& path, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
errno = 0;
if(remove((*i).c_str()) != 0) {
LOG_FS << "remove(" << (*i) << "): " << strerror(errno) << std::endl;
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
if(!delete_directory(*j))
ret = false;
}
}
errno = 0;
#ifdef _WIN32
// remove() doesn't delete directories on windows.
int (*remove)(const char*);
if(is_directory(path))
remove = rmdir;
else
remove = ::remove;
#endif
if(remove(path.c_str()) != 0) {
LOG_FS << "remove(" << path << "): " << strerror(errno) << std::endl;
ret = false;
}
return ret;
}
bool delete_file(const std::string& path)
{
bool ret = true;
if(remove(path.c_str()) != 0 && errno != ENOENT) {
ERR_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
std::string get_cwd()
{
char buf[1024];
const char* const res = getcwd(buf,sizeof(buf));
if(res != NULL) {
std::string str(res);
#ifdef _WIN32
std::replace(str.begin(),str.end(),'\\','/');
#endif
return str;
} else {
return "";
}
}
std::string get_exe_dir()
{
#ifndef _WIN32
char buf[1024];
size_t path_size = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if(path_size == static_cast<size_t>(-1))
return std::string();
buf[path_size] = 0;
return std::string(dirname(buf));
#else
return get_cwd();
#endif
}
bool create_directory_if_missing(const std::string& dirname)
{
if(is_directory(dirname)) {
DBG_FS << "directory " << dirname << " exists, not creating" << std::endl;
return true;
} else if(file_exists(dirname)) {
ERR_FS << "cannot create directory " << dirname << "; file exists" << std::endl;
return false;
}
DBG_FS << "creating missing directory " << dirname << '\n';
return make_directory(dirname);
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
DBG_FS<<"creating recursive directory: "<<dirname<<'\n';
if (is_directory(dirname) == false && dirname.empty() == false)
{
std::string tmp_dirname = dirname;
// remove trailing slashes or backslashes
while ((tmp_dirname[tmp_dirname.size()-1] == '/' ||
tmp_dirname[tmp_dirname.size()-1] == '\\') &&
!tmp_dirname.empty())
{
tmp_dirname.erase(tmp_dirname.size()-1);
}
// create the first non-existing directory
size_t pos = tmp_dirname.rfind("/");
// we get the most right directory and *skip* it
// we are creating it when we get back here
if (tmp_dirname.rfind('\\') != std::string::npos &&
tmp_dirname.rfind('\\') > pos )
pos = tmp_dirname.rfind('\\');
if (pos != std::string::npos)
create_directory_if_missing_recursive(tmp_dirname.substr(0,pos));
return create_directory_if_missing(tmp_dirname);
}
return create_directory_if_missing(dirname);
}
static std::string user_data_dir, user_config_dir, cache_dir;
static void setup_user_data_dir();
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
void set_user_data_dir(std::string path)
{
#ifdef _WIN32
if(path.empty()) {
user_data_dir = get_cwd() + "/userdata";
} else if (path.size() > 2 && path[1] == ':') {
//allow absolute path override
user_data_dir = path;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathA;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathA = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathA"));
if(SHGetSpecialFolderPathA) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents" << std::endl;
char my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathA(NULL, my_documents_path, 5, 1)) {
std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path + "/" + path;
} else {
WRN_FS << "SHGetSpecialFolderPath failed" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (path.empty()) path = PREFERENCES_DIR;
#endif
std::string path2 = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (path.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
path = path2;
goto other;
}
user_data_dir = home_str;
user_data_dir += "/.local/share";
} else user_data_dir = xdg_data;
user_data_dir += "/wesnoth/";
user_data_dir += get_version_path_suffix();
create_directory_if_missing_recursive(user_data_dir);
} else {
other:
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + "/" + path;
}
#else
if (path.empty()) path = path2;
const char* home_str = getenv("HOME");
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + std::string("/") + path;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
void set_user_config_dir(std::string path)
{
user_config_dir = path;
create_directory_if_missing(user_config_dir);
}
static void setup_user_data_dir()
{
#ifdef _WIN32
_mkdir(user_data_dir.c_str());
_mkdir((user_data_dir + "/editor").c_str());
_mkdir((user_data_dir + "/editor/maps").c_str());
_mkdir((user_data_dir + "/editor/scenarios").c_str());
_mkdir((user_data_dir + "/data").c_str());
_mkdir((user_data_dir + "/data/add-ons").c_str());
_mkdir((user_data_dir + "/saves").c_str());
_mkdir((user_data_dir + "/persist").c_str());
#else
const std::string& dir_path = user_data_dir;
const bool res = create_directory_if_missing(dir_path);
// probe read permissions (if we could make the directory)
DIR* const dir = res ? opendir(dir_path.c_str()) : NULL;
if(dir == NULL) {
ERR_FS << "could not open or create preferences directory at " << dir_path << std::endl;
return;
}
closedir(dir);
// Create user data and add-on directories
create_directory_if_missing(dir_path + "/editor");
create_directory_if_missing(dir_path + "/editor/maps");
create_directory_if_missing(dir_path + "/editor/scenarios");
create_directory_if_missing(dir_path + "/data");
create_directory_if_missing(dir_path + "/data/add-ons");
create_directory_if_missing(dir_path + "/saves");
create_directory_if_missing(dir_path + "/persist");
#endif
}
std::string get_user_data_dir()
{
// ensure setup gets called only once per session
// FIXME: this is okay and optimized, but how should we react
// if the user deletes a dir while we are running?
if (user_data_dir.empty())
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
std::string path;
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_dir();
return user_config_dir;
}
path = xdg_config;
path += "/.config";
} else path = xdg_config;
path += "/wesnoth";
set_user_config_dir(path);
#else
user_config_dir = get_user_data_dir();
#endif
}
return user_config_dir;
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_dir() + "/cache");
return cache_dir;
}
cache_dir = xdg_cache;
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
return cache_dir;
}
static std::string read_stream(std::istream& s)
{
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading." << std::endl;
if (fname.empty())
{
ERR_FS << "Trying to open file with empty name." << std::endl;
std::ifstream *s = new std::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
std::ifstream *s = new std::ifstream(fname.c_str(),std::ios_base::binary);
if (s->is_open()) {
return s;
}
if (treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading." << std::endl;
} else {
LOG_FS << "Could not open '" << fname << "' for reading." << std::endl;
}
return s;
}
std::string read_file(const std::string &fname)
{
scoped_istream s = istream_file(fname);
return read_stream(*s);
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing." << std::endl;
return new std::ofstream(fname.c_str(), std::ios_base::binary);
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
//const util::scoped_resource<FILE*,close_FILE> file(fopen(fname.c_str(),"wb"));
const util::scoped_FILE file(fopen(fname.c_str(),"wb"));
if(file.get() == NULL) {
throw io_exception("Could not open file for writing: '" + fname + "'");
}
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
const size_t res = fwrite(buf,1,bytes,file.get());
if(res != bytes) {
throw io_exception("Error writing to file: '" + fname + "'");
}
}
}
static bool is_directory_internal(const std::string& fname)
{
#ifdef _WIN32
_finddata_t info;
const long handle = _findfirst((fname + "/*").c_str(),&info);
if(handle >= 0) {
_findclose(handle);
return true;
} else {
return false;
}
#else
struct stat dir_stat;
if(::stat(fname.c_str(), &dir_stat) == -1) {
return false;
}
return S_ISDIR(dir_stat.st_mode);
#endif
}
bool is_directory(const std::string& fname)
{
if(fname.empty()) {
return false;
}
if(fname[0] != '/' && !game_config::path.empty()) {
if(is_directory_internal(game_config::path + "/" + fname))
return true;
}
return is_directory_internal(fname);
}
bool file_exists(const std::string& name)
{
#ifdef _WIN32
struct stat st;
return (::stat(name.c_str(), &st) == 0);
#else
struct stat st;
return (::stat(name.c_str(), &st) != -1);
#endif
}
time_t file_modified_time(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return 0;
return buf.st_mtime;
}
/**
* Returns true if the file ends with '.gz'.
*
* @param filename The name to test.
*/
bool is_gzip_file(const std::string& filename)
{
return (filename.length() > 3
&& filename.substr(filename.length() - 3) == ".gz");
}
/**
* Returns true if the file ends with '.bz2'.
*
* @param filename The name to test.
*/
bool is_bzip2_file(const std::string& filename)
{
return (filename.length() > 4
&& filename.substr(filename.length() - 4) == ".bz2");
}
int file_size(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return -1;
return buf.st_size;
}
int dir_size(const std::string& path)
{
std::vector<std::string> files, dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH);
int res = 0;
BOOST_FOREACH(const std::string& file_path, files)
{
res += file_size(file_path);
}
BOOST_FOREACH(const std::string& dir_path, dirs)
{
// FIXME: this could result in infinite recursion with symlinks!!
res += dir_size(dir_path);
}
return res;
}
std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return file;
if(pos >= file.size()-1)
return "";
return file.substr(pos+1);
}
std::string directory_name(const std::string& file)
// Analogous to POSIX dirname(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return "";
return file.substr(0,pos+1);
}
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'" << std::endl;
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths" << std::endl;
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
// Some parts of Wesnoth enjoy putting ".." inside filenames. This is
// bad and should be fixed. But in the meantime, deal with them in a dumb way.
std::string::size_type pos = filename.rfind("../");
if (pos != std::string::npos) {
std::string nf = filename.substr(pos + 3);
LOG_FS << "Illegal path '" << filename << "' replaced by '" << nf << "'" << std::endl;
return get_binary_file_location(type, nf);
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if(file_exists(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if (is_directory(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
if (looks_like_pbl(filename)) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
}
std::string get_short_wml_path(const std::string &filename)
{
std::string match = get_user_data_dir() + "/data/";
if (filename.find(match) == 0) {
return "~" + filename.substr(match.size());
}
match = game_config::path + "/data/";
if (filename.find(match) == 0) {
return filename.substr(match.size());
}
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
std::string full_path = get_binary_file_location("images", filename);
if(!full_path.empty()) {
std::string match = get_user_data_dir() + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
match = game_config::path + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
}
return full_path;
}
std::string get_program_invocation(const std::string& program_name) {
#ifdef DEBUG
#ifdef _WIN32
const char *program_suffix = "-debug.exe";
#else
const char *program_suffix = "-debug";
#endif
#else
#ifdef _WIN32
const char *program_suffix = ".exe";
#else
const char *program_suffix = "";
#endif
#endif
const std::string real_program_name(program_name + program_suffix);
if(game_config::wesnoth_program_dir.empty()) return real_program_name;
#ifdef _WIN32
return game_config::wesnoth_program_dir + "\\" + real_program_name;
#else
return game_config::wesnoth_program_dir + "/" + real_program_name;
#endif
}
bool is_path_sep(char c)
{
#ifdef _WIN32
if (c == '/' || c == '\\') return true;
#else
if (c == '/') return true;
#endif
return false;
}
std::string normalize_path(const std::string &p1)
{
if (p1.empty()) return p1;
std::string p2;
#ifdef _WIN32
if (p1.size() >= 2 && p1[1] == ':')
// Windows relative paths with explicit drive name are not handled.
p2 = p1;
else
#endif
if (!is_path_sep(p1[0]))
p2 = get_cwd() + "/" + p1;
else
p2 = p1;
#ifdef _WIN32
std::string drive;
if (p2.size() >= 2 && p2[1] == ':') {
drive = p2.substr(0, 2);
p2.erase(0, 2);
}
#endif
std::vector<std::string> components(1);
for (int i = 0, i_end = p2.size(); i <= i_end; ++i)
{
std::string &last = components[components.size() - 1];
char c = p2.c_str()[i];
if (is_path_sep(c) || c == 0)
{
if (last == ".")
last.clear();
else if (last == "..")
{
if (components.size() >= 2) {
components.pop_back();
components[components.size() - 1].clear();
} else
last.clear();
}
else if (!last.empty())
components.push_back(std::string());
}
else
last += c;
}
std::ostringstream p4;
components.pop_back();
#ifdef _WIN32
p4 << drive;
#endif
BOOST_FOREACH(const std::string &s, components)
{
p4 << '/' << s;
}
DBG_FS << "Normalizing '" << p2 << "' to '" << p4.str() << "'" << std::endl;
return p4.str();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1650_2 |
crossvul-cpp_data_bad_1809_1 | /****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Jory Stone <jcsston @ toughguy.net>
*/
#include <cassert>
#if __GNUC__ == 2 && ! defined ( __OpenBSD__ )
#include <wchar.h>
#endif
#include "ebml/EbmlUnicodeString.h"
START_LIBEBML_NAMESPACE
// ===================== UTFstring class ===================
UTFstring::UTFstring()
:_Length(0)
,_Data(NULL)
{}
UTFstring::UTFstring(const wchar_t * _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf;
}
UTFstring::UTFstring(std::wstring const &_aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring::~UTFstring()
{
delete [] _Data;
}
UTFstring::UTFstring(const UTFstring & _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring & UTFstring::operator=(const UTFstring & _aBuf)
{
*this = _aBuf.c_str();
return *this;
}
UTFstring::operator const wchar_t*() const {return _Data;}
UTFstring & UTFstring::operator=(const wchar_t * _aBuf)
{
delete [] _Data;
if (_aBuf == NULL) {
_Data = new wchar_t[1];
_Data[0] = 0;
UpdateFromUCS2();
return *this;
}
size_t aLen;
for (aLen=0; _aBuf[aLen] != 0; aLen++);
_Length = aLen;
_Data = new wchar_t[_Length+1];
for (aLen=0; _aBuf[aLen] != 0; aLen++) {
_Data[aLen] = _aBuf[aLen];
}
_Data[aLen] = 0;
UpdateFromUCS2();
return *this;
}
UTFstring & UTFstring::operator=(wchar_t _aChar)
{
delete [] _Data;
_Data = new wchar_t[2];
_Length = 1;
_Data[0] = _aChar;
_Data[1] = 0;
UpdateFromUCS2();
return *this;
}
bool UTFstring::operator==(const UTFstring& _aStr) const
{
if ((_Data == NULL) && (_aStr._Data == NULL))
return true;
if ((_Data == NULL) || (_aStr._Data == NULL))
return false;
return wcscmp_internal(_Data, _aStr._Data);
}
void UTFstring::SetUTF8(const std::string & _aStr)
{
UTF8string = _aStr;
UpdateFromUTF8();
}
/*!
\see RFC 2279
*/
void UTFstring::UpdateFromUTF8()
{
delete [] _Data;
// find the size of the final UCS-2 string
size_t i;
for (_Length=0, i=0; i<UTF8string.length(); _Length++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80)
i++;
else if ((lead >> 5) == 0x6)
i += 2;
else if ((lead >> 4) == 0xe)
i += 3;
else if ((lead >> 3) == 0x1e)
i += 4;
else
// Invalid size?
break;
}
_Data = new wchar_t[_Length+1];
size_t j;
for (j=0, i=0; i<UTF8string.length(); j++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80) {
_Data[j] = lead;
i++;
} else if ((lead >> 5) == 0x6) {
_Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);
i += 2;
} else if ((lead >> 4) == 0xe) {
_Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);
i += 3;
} else if ((lead >> 3) == 0x1e) {
_Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);
i += 4;
} else
// Invalid char?
break;
}
_Data[j] = 0;
}
void UTFstring::UpdateFromUCS2()
{
// find the size of the final UTF-8 string
size_t i,Size=0;
for (i=0; i<_Length; i++) {
if (_Data[i] < 0x80) {
Size++;
} else if (_Data[i] < 0x800) {
Size += 2;
} else {
Size += 3;
}
}
std::string::value_type *tmpStr = new std::string::value_type[Size+1];
for (i=0, Size=0; i<_Length; i++) {
if (_Data[i] < 0x80) {
tmpStr[Size++] = _Data[i];
} else if (_Data[i] < 0x800) {
tmpStr[Size++] = 0xC0 | (_Data[i] >> 6);
tmpStr[Size++] = 0x80 | (_Data[i] & 0x3F);
} else {
tmpStr[Size++] = 0xE0 | (_Data[i] >> 12);
tmpStr[Size++] = 0x80 | ((_Data[i] >> 6) & 0x3F);
tmpStr[Size++] = 0x80 | (_Data[i] & 0x3F);
}
}
tmpStr[Size] = 0;
UTF8string = tmpStr; // implicit conversion
delete [] tmpStr;
}
bool UTFstring::wcscmp_internal(const wchar_t *str1, const wchar_t *str2)
{
size_t Index=0;
while (str1[Index] == str2[Index] && str1[Index] != 0) {
Index++;
}
return (str1[Index] == str2[Index]);
}
// ===================== EbmlUnicodeString class ===================
EbmlUnicodeString::EbmlUnicodeString()
:EbmlElement(0, false)
{
SetDefaultSize(0);
}
EbmlUnicodeString::EbmlUnicodeString(const UTFstring & aDefaultValue)
:EbmlElement(0, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultSize(0);
SetDefaultIsSet();
}
EbmlUnicodeString::EbmlUnicodeString(const EbmlUnicodeString & ElementToClone)
:EbmlElement(ElementToClone)
,Value(ElementToClone.Value)
,DefaultValue(ElementToClone.DefaultValue)
{
}
void EbmlUnicodeString::SetDefaultValue(UTFstring & aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
const UTFstring & EbmlUnicodeString::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
/*!
\note limited to UCS-2
\todo handle exception on errors
*/
filepos_t EbmlUnicodeString::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
uint32 Result = Value.GetUTF8().length();
if (Result != 0) {
output.writeFully(Value.GetUTF8().c_str(), Result);
}
if (Result < GetDefaultSize()) {
// pad the rest with 0
binary *Pad = new (std::nothrow) binary[GetDefaultSize() - Result];
if (Pad != NULL) {
memset(Pad, 0x00, GetDefaultSize() - Result);
output.writeFully(Pad, GetDefaultSize() - Result);
Result = GetDefaultSize();
delete [] Pad;
}
}
return Result;
}
EbmlUnicodeString::operator const UTFstring &() const {return Value;}
EbmlUnicodeString & EbmlUnicodeString::operator=(const UTFstring & NewString)
{
Value = NewString;
SetValueIsSet();
return *this;
}
EbmlUnicodeString &EbmlUnicodeString::SetValue(UTFstring const &NewValue) {
return *this = NewValue;
}
EbmlUnicodeString &EbmlUnicodeString::SetValueUTF8(std::string const &NewValue) {
UTFstring NewValueUTFstring;
NewValueUTFstring.SetUTF8(NewValue);
return *this = NewValueUTFstring;
}
UTFstring EbmlUnicodeString::GetValue() const {
return Value;
}
std::string EbmlUnicodeString::GetValueUTF8() const {
return Value.GetUTF8();
}
/*!
\note limited to UCS-2
*/
uint64 EbmlUnicodeString::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
SetSize_(Value.GetUTF8().length());
if (GetSize() < GetDefaultSize())
SetSize_(GetDefaultSize());
return GetSize();
}
/*!
\note limited to UCS-2
*/
filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully != SCOPE_NO_DATA) {
if (GetSize() == 0) {
Value = UTFstring::value_type(0);
SetValueIsSet();
} else {
char *Buffer = new (std::nothrow) char[GetSize()+1];
if (Buffer == NULL) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
} else {
input.readFully(Buffer, GetSize());
if (Buffer[GetSize()-1] != 0) {
Buffer[GetSize()] = 0;
}
Value.SetUTF8(Buffer); // implicit conversion to std::string
delete [] Buffer;
SetValueIsSet();
}
}
}
return GetSize();
}
END_LIBEBML_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1809_1 |
crossvul-cpp_data_good_1649_2 | /* $Id$ */
/*
Copyright (C) 2003 - 2012 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
#include "filesystem.hpp"
#include "serialization/unicode.hpp"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/system/windows_error.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <set>
using boost::uintmax_t;
#ifdef _WIN32
#include <boost/locale.hpp>
#include <windows.h>
#endif /* !_WIN32 */
#include "config.hpp"
#include "game_config.hpp"
#include "log.hpp"
#include "util.hpp"
#include "version.hpp"
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace bfs = boost::filesystem;
using boost::filesystem::path;
using boost::system::error_code;
namespace {
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
namespace {
//only used by windows but put outside the ifdef to let it check by ci build.
class customcodecvt : public std::codecvt<wchar_t /*intern*/, char /*extern*/, std::mbstate_t>
{
private:
//private static helper things
template<typename char_t_to>
struct customcodecvt_do_conversion_writer
{
customcodecvt_do_conversion_writer(char_t_to*& _to_next, char_t_to* _to_end) :
to_next(_to_next),
to_end(_to_end)
{}
char_t_to*& to_next;
char_t_to* to_end;
bool can_push(size_t count)
{
return static_cast<size_t>(to_end - to_next) > count;
}
void push(char_t_to val)
{
assert(to_next != to_end);
*to_next++ = val;
}
};
template<typename char_t_from , typename char_t_to>
static void customcodecvt_do_conversion( std::mbstate_t& /*state*/,
const char_t_from* from,
const char_t_from* from_end,
const char_t_from*& from_next,
char_t_to* to,
char_t_to* to_end,
char_t_to*& to_next )
{
typedef typename ucs4_convert_impl::convert_impl<char_t_from>::type impl_type_from;
typedef typename ucs4_convert_impl::convert_impl<char_t_to>::type impl_type_to;
from_next = from;
to_next = to;
customcodecvt_do_conversion_writer<char_t_to> writer(to_next, to_end);
while(from_next != from_end)
{
impl_type_to::write(writer, impl_type_from::read(from_next, from_end));
}
}
public:
//Not used by boost filesystem
int do_encoding() const throw() { return 0; }
//Not used by boost filesystem
bool do_always_noconv() const throw() { return false; }
int do_length( std::mbstate_t& /*state*/,
const char* /*from*/,
const char* /*from_end*/,
std::size_t /*max*/ ) const
{
//Not used by boost filesystem
throw "Not supported";
}
std::codecvt_base::result unshift( std::mbstate_t& /*state*/,
char* /*to*/,
char* /*to_end*/,
char*& /*to_next*/) const
{
//Not used by boost filesystem
throw "Not supported";
}
//there are still some methods which could be implemented but arent because boost filesystem won't use them.
std::codecvt_base::result do_in( std::mbstate_t& state,
const char* from,
const char* from_end,
const char*& from_next,
wchar_t* to,
wchar_t* to_end,
wchar_t*& to_next ) const
{
try
{
customcodecvt_do_conversion<char, wchar_t>(state, from, from_end, from_next, to, to_end, to_next);
}
catch(...)
{
ERR_FS << "Invalid UTF-8 string'" << std::string(from, from_end) << "' " << std::endl;
return std::codecvt_base::error;
}
return std::codecvt_base::ok;
}
std::codecvt_base::result do_out( std::mbstate_t& state,
const wchar_t* from,
const wchar_t* from_end,
const wchar_t*& from_next,
char* to,
char* to_end,
char*& to_next ) const
{
try
{
customcodecvt_do_conversion<wchar_t, char>(state, from, from_end, from_next, to, to_end, to_next);
}
catch(...)
{
ERR_FS << "Invalid UTF-16 string" << std::endl;
return std::codecvt_base::error;
}
return std::codecvt_base::ok;
}
};
#ifdef _WIN32
class static_runner {
public:
static_runner() {
// Boost uses the current locale to generate a UTF-8 one
std::locale utf8_loc = boost::locale::generator().generate("");
// use a custom locale becasue we want to use out log.hpp functions in case of an invalid string.
utf8_loc = std::locale(utf8_loc, new customcodecvt());
boost::filesystem::path::imbue(utf8_loc);
}
};
static static_runner static_bfs_path_imbuer;
#endif
}
namespace filesystem {
static void push_if_exists(std::vector<std::string> *vec, const path &file, bool full) {
if (vec != NULL) {
if (full)
vec->push_back(file.generic_string());
else
vec->push_back(file.filename().generic_string());
}
}
static inline bool error_except_not_found(const error_code &ec)
{
return (ec
&& ec.value() != boost::system::errc::no_such_file_or_directory
#ifdef _WIN32
&& ec.value() != boost::system::windows_error::path_not_found
#endif /*_WIN32*/
);
}
static bool is_directory_internal(const path &fpath)
{
error_code ec;
bool is_dir = bfs::is_directory(fpath, ec);
if (error_except_not_found(ec)) {
LOG_FS << "Failed to check if " << fpath.string() << " is a directory: " << ec.message() << '\n';
}
return is_dir;
}
static bool file_exists(const path &fpath)
{
error_code ec;
bool exists = bfs::exists(fpath, ec);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to check existence of file " << fpath.string() << ": " << ec.message() << '\n';
}
return exists;
}
static path get_dir(const path &dirpath)
{
bool is_dir = is_directory_internal(dirpath);
if (!is_dir) {
error_code ec;
bfs::create_directory(dirpath, ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
}
// This is probably redundant
is_dir = is_directory_internal(dirpath);
}
if (!is_dir) {
ERR_FS << "Could not open or create directory " << dirpath.string() << '\n';
return std::string();
}
return dirpath;
}
static bool create_directory_if_missing(const path &dirpath)
{
error_code ec;
bfs::file_status fs = bfs::status(dirpath, ec);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
return false;
} else if (bfs::is_directory(fs)) {
DBG_FS << "directory " << dirpath.string() << " exists, not creating\n";
return true;
} else if (bfs::exists(fs)) {
ERR_FS << "cannot create directory " << dirpath.string() << "; file exists\n";
return false;
}
bool created = bfs::create_directory(dirpath, ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
}
return created;
}
static bool create_directory_if_missing_recursive(const path& dirpath)
{
DBG_FS << "creating recursive directory: " << dirpath.string() << '\n';
if (dirpath.empty())
return false;
error_code ec;
bfs::file_status fs = bfs::status(dirpath);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
return false;
} else if (bfs::is_directory(fs)) {
return true;
} else if (bfs::exists(fs)) {
return false;
}
if (!dirpath.has_parent_path() || create_directory_if_missing_recursive(dirpath.parent_path())) {
return create_directory_if_missing(dirpath);
} else {
ERR_FS << "Could not create parents to " << dirpath.string() << '\n';
return false;
}
}
void get_files_in_dir(const std::string &dir,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum) {
if(path(dir).is_relative() && !game_config::path.empty()) {
path absolute_dir(game_config::path);
absolute_dir /= dir;
if(is_directory_internal(absolute_dir)) {
get_files_in_dir(absolute_dir.string(), files, dirs, mode, filter, reorder, checksum);
return;
}
}
const path dirpath(dir);
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << dir << '\n';
const path maincfg = dirpath / maincfg_filename;
if (file_exists(maincfg)) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
push_if_exists(files, maincfg, mode == ENTIRE_FILE_PATH);
return;
}
}
error_code ec;
bfs::directory_iterator di(dirpath, ec);
bfs::directory_iterator end;
if (ec) {
// Probably not a directory, let the caller deal with it.
return;
}
for(; di != end; ++di) {
bfs::file_status st = di->status(ec);
if (ec) {
LOG_FS << "Failed to get file status of " << di->path().string() << ": " << ec.message() << '\n';
continue;
}
if (st.type() == bfs::regular_file) {
{
std::string basename = di->path().filename().string();
if (filter == SKIP_PBL_FILES && looks_like_pbl(basename))
continue;
if(!basename.empty() && basename[0] == '.' )
continue;
}
push_if_exists(files, di->path(), mode == ENTIRE_FILE_PATH);
if (checksum != NULL) {
std::time_t mtime = bfs::last_write_time(di->path(), ec);
if (ec) {
LOG_FS << "Failed to read modification time of " << di->path().string() << ": " << ec.message() << '\n';
} else if (mtime > checksum->modified) {
checksum->modified = mtime;
}
uintmax_t size = bfs::file_size(di->path(), ec);
if (ec) {
LOG_FS << "Failed to read filesize of " << di->path().string() << ": " << ec.message() << '\n';
} else {
checksum->sum_size += size;
}
checksum->nfiles++;
}
} else if (st.type() == bfs::directory_file) {
std::string basename = di->path().filename().string();
if(!basename.empty() && basename[0] == '.' )
continue;
if (filter == SKIP_MEDIA_DIR
&& (basename == "images" || basename == "sounds"))
continue;
const path inner_main(di->path() / maincfg_filename);
bfs::file_status main_st = bfs::status(inner_main, ec);
if (error_except_not_found(ec)) {
LOG_FS << "Failed to get file status of " << inner_main.string() << ": " << ec.message() << '\n';
} else if (reorder == DO_REORDER && main_st.type() == bfs::regular_file) {
LOG_FS << "_main.cfg found : " << (mode == ENTIRE_FILE_PATH ? inner_main.string() : inner_main.filename().string()) << '\n';
push_if_exists(files, inner_main, mode == ENTIRE_FILE_PATH);
} else {
push_if_exists(dirs, di->path(), mode == ENTIRE_FILE_PATH);
}
}
}
if (files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
int foundit = -1;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; i--)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_dir(const std::string &dir)
{
return get_dir(path(dir)).string();
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
static path user_data_dir, user_config_dir, cache_dir;
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
static void setup_user_data_dir()
{
if (!create_directory_if_missing_recursive(user_data_dir)) {
ERR_FS << "could not open or create user data directory at " << user_data_dir.string() << '\n';
return;
}
// TODO: this may not print the error message if the directory exists but we don't have the proper permissions
// Create user data and add-on directories
create_directory_if_missing(user_data_dir / "editor");
create_directory_if_missing(user_data_dir / "editor" / "maps");
create_directory_if_missing(user_data_dir / "editor" / "scenarios");
create_directory_if_missing(user_data_dir / "data");
create_directory_if_missing(user_data_dir / "data" / "add-ons");
create_directory_if_missing(user_data_dir / "saves");
create_directory_if_missing(user_data_dir / "persist");
}
void set_user_data_dir(std::string newprefdir)
{
#ifdef _WIN32
if(newprefdir.empty()) {
user_data_dir = path(get_cwd()) / "userdata";
} else if (newprefdir.size() > 2 && newprefdir[1] == ':') {
//allow absolute path override
user_data_dir = newprefdir;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPWSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathW;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathW = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathW"));
if(SHGetSpecialFolderPathW) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents\n";
wchar_t my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathW(NULL, my_documents_path, 5, 1)) {
path mygames_path = path(my_documents_path) / "My Games";
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path / newprefdir;
} else {
WRN_FS << "SHGetSpecialFolderPath failed\n";
user_data_dir = path(get_cwd()) / newprefdir;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function\n";
user_data_dir = path(get_cwd()) / newprefdir;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (newprefdir.empty()) newprefdir = PREFERENCES_DIR;
#endif
std::string backupprefdir = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (newprefdir.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
newprefdir = backupprefdir;
goto other;
}
user_data_dir = home_str;
user_data_dir /= ".local/share";
} else user_data_dir = xdg_data;
user_data_dir /= "wesnoth";
user_data_dir /= get_version_path_suffix();
} else {
other:
path home = home_str ? home_str : ".";
if (newprefdir[0] == '/')
user_data_dir = newprefdir;
else
user_data_dir = home / newprefdir;
}
#else
if (newprefdir.empty()) newprefdir = backupprefdir;
const char* home_str = getenv("HOME");
path home = home_str ? home_str : ".";
if (newprefdir[0] == '/')
user_data_dir = newprefdir;
else
user_data_dir = home / newprefdir;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
static void set_user_config_path(path newconfig)
{
user_config_dir = newconfig;
if (!create_directory_if_missing_recursive(user_config_dir)) {
ERR_FS << "could not open or create user config directory at " << user_config_dir.string() << '\n';
}
}
void set_user_config_dir(std::string newconfigdir)
{
set_user_config_path(newconfigdir);
}
static const path &get_user_data_path()
{
// TODO:
// This function is called frequently. The file_exists call may slow things down a lot.
if (user_data_dir.empty() || !file_exists(user_data_dir))
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_path();
return user_config_dir.string();
}
user_config_dir = xdg_config;
user_config_dir /= ".config";
} else user_config_dir = xdg_config;
user_config_dir /= "wesnoth";
set_user_config_path(user_config_dir);
#else
user_config_dir = get_user_data_path();
#endif
}
return user_config_dir.string();
}
std::string get_user_data_dir()
{
return get_user_data_path().string();
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_path() / "cache");
return cache_dir.string();
}
cache_dir = xdg_cache;
cache_dir /= ".cache";
} else cache_dir = xdg_cache;
cache_dir /= "wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_path() / "cache");
#endif
}
return cache_dir.string();
}
std::string get_cwd()
{
error_code ec;
path cwd = bfs::current_path(ec);
if (ec) {
ERR_FS << "Failed to get current directory: " << ec.message() << '\n';
return "";
}
return cwd.generic_string();
}
std::string get_exe_dir()
{
#ifndef _WIN32
path self_exe("/proc/self/exe");
error_code ec;
path exe = bfs::read_symlink(self_exe, ec);
if (ec) {
return std::string();
}
return exe.parent_path().string();
#else
return get_cwd();
#endif
}
bool make_directory(const std::string& dirname)
{
error_code ec;
bool created = bfs::create_directory(path(dirname), ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirname << ": " << ec.message() << '\n';
}
return created;
}
bool delete_directory(const std::string& dirname, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
error_code ec;
get_files_in_dir(dirname, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
bfs::remove(path(*i), ec);
if (ec) {
LOG_FS << "remove(" << (*i) << "): " << ec.message() << '\n';
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
//TODO: this does not preserve any other PBL files
// filesystem.cpp does this too, so this might be intentional
if(!delete_directory(*j))
ret = false;
}
}
if (ret) {
bfs::remove(path(dirname), ec);
if (ec) {
LOG_FS << "remove(" << dirname << "): " << ec.message() << '\n';
ret = false;
}
}
return ret;
}
bool delete_file(const std::string &filename)
{
error_code ec;
bool ret = bfs::remove(path(filename), ec);
if (ec) {
ERR_FS << "Could not delete file " << filename << ": " << ec.message() << '\n';
}
return ret;
}
std::string read_file(const std::string &fname)
{
scoped_istream is = istream_file(fname);
std::stringstream ss;
ss << is->rdbuf();
return ss.str();
}
#if BOOST_VERSION < 1048000
//boost iostream < 1.48 expects boost filesystem v2 paths. This is an adapter
struct iostream_path
{
template<typename stringtype>
iostream_path(const stringtype& s)
: path_(s)
{
}
typedef bfs::path::string_type external_string_type;
external_string_type external_file_string() const
{
return path_.native();
}
bfs::path path_;
};
#else
typedef bfs::path iostream_path;
#endif
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading.\n";
if (fname.empty()) {
ERR_FS << "Trying to open file with empty name.\n";
bfs::ifstream *s = new bfs::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
//mingw doesn't support std::basic_ifstream::basic_ifstream(const wchar_t* fname)
//that why boost::filesystem::fstream.hpp doesnt work with mingw.
try
{
boost::iostreams::file_descriptor_source fd(iostream_path(fname), std::ios_base::binary);
//TODO: has this still use ?
if (!fd.is_open() && treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading.\n";
}
return new boost::iostreams::stream<boost::iostreams::file_descriptor_source>(fd, 4096, 0);
}
catch(const std::exception ex)
{
if(treat_failure_as_error)
{
ERR_FS << "Could not open '" << fname << "' for reading.\n";
}
bfs::ifstream *s = new bfs::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing.\n";
#if 1
try
{
boost::iostreams::file_descriptor_sink fd(iostream_path(fname), std::ios_base::binary);
return new boost::iostreams::stream<boost::iostreams::file_descriptor_sink>(fd, 4096, 0);
}
catch(BOOST_IOSTREAMS_FAILURE& e)
{
throw filesystem::io_exception(e.what());
}
#else
return new bfs::ofstream(path(fname), std::ios_base::binary);
#endif
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
scoped_ostream os = ostream_file(fname);
os->exceptions(std::ios_base::goodbit);
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
os->write(buf, bytes);
if (os->bad())
throw io_exception("Error writing to file: '" + fname + "'");
}
}
bool create_directory_if_missing(const std::string& dirname)
{
return create_directory_if_missing(path(dirname));
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
return create_directory_if_missing_recursive(path(dirname));
}
bool is_directory(const std::string& fname)
{
return is_directory_internal(path(fname));
}
bool file_exists(const std::string& name)
{
return file_exists(path(name));
}
time_t file_modified_time(const std::string& fname)
{
error_code ec;
std::time_t mtime = bfs::last_write_time(path(fname), ec);
if (ec) {
LOG_FS << "Failed to read modification time of " << fname << ": " << ec.message() << '\n';
}
return mtime;
}
bool is_gzip_file(const std::string& filename)
{
return path(filename).extension() == ".gz";
}
bool is_bzip2_file(const std::string& filename)
{
return path(filename).extension() == ".bz2";
}
int file_size(const std::string& fname)
{
error_code ec;
uintmax_t size = bfs::file_size(path(fname), ec);
if (ec) {
LOG_FS << "Failed to read filesize of " << fname << ": " << ec.message() << '\n';
return -1;
} else if (size > INT_MAX)
return INT_MAX;
else
return size;
}
int dir_size(const std::string& pname)
{
bfs::path p(pname);
uintmax_t size_sum = 0;
error_code ec;
for ( bfs::recursive_directory_iterator i(p), end; i != end && !ec; ++i ) {
if(bfs::is_regular_file(i->path())) {
size_sum += bfs::file_size(i->path(), ec);
}
}
if (ec) {
LOG_FS << "Failed to read directorysize of " << pname << ": " << ec.message() << '\n';
return -1;
}
else if (size_sum > INT_MAX)
return INT_MAX;
else
return size_sum;
}
std::string base_name(const std::string& file)
{
return path(file).filename().string();
}
std::string directory_name(const std::string& file)
{
return path(file).parent_path().string();
}
bool is_path_sep(char c)
{
static const path sep = path("/").make_preferred();
const std::string s = std::string(1, c);
return sep == path(s).make_preferred();
}
std::string normalize_path(const std::string &fpath)
{
if (fpath.empty()) {
return fpath;
}
return bfs::absolute(fpath).string();
}
/**
* The paths manager is responsible for recording the various paths
* that binary files may be located at.
* It should be passed a config object which holds binary path information.
* This is in the format
*@verbatim
* [binary_path]
* path=<path>
* [/binary_path]
* Binaries will be searched for in [wesnoth-path]/data/<path>/images/
*@endverbatim
*/
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'\n";
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
static bool is_legal_file(const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'.\n";
if (filename.empty()) {
LOG_FS << " invalid filename\n";
return false;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n";
return false;
}
if (ends_with(filename, ".pbl")) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return false;
}
return true;
}
/**
* Returns a vector with all possible paths to a given type of binary,
* e.g. 'images', 'sounds', etc,
*/
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths\n";
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
// We define ".." as "remove everything before" this is needed becasue
// on the one hand allowing ".." would be a security risk but
// especialy for terrains the c++ engine puts a hardcoded "terrain/" before filename
// and there would be no way to "escape" from "terrain/" otherwise. This is not the
// best solution but we cannot remove it without another solution (subtypes maybe?).
// using 'for' instead 'if' to allow putting delcaration and check into the brackets
for(std::string::size_type pos = filename.rfind("../"); pos != std::string::npos;)
return get_binary_file_location(type, filename.substr(pos + 3));
if (!is_legal_file(filename))
return std::string();
BOOST_FOREACH(const std::string &bp, get_binary_paths(type))
{
path bpath(bp);
bpath /= filename;
DBG_FS << " checking '" << bp << "'\n";
if (file_exists(bpath)) {
DBG_FS << " found at '" << bpath.string() << "'\n";
return bpath.string();
}
}
DBG_FS << " not found\n";
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
if (!is_legal_file(filename))
return std::string();
BOOST_FOREACH(const std::string &bp, get_binary_paths(type))
{
path bpath(bp);
bpath /= filename;
DBG_FS << " checking '" << bp << "'\n";
if (is_directory_internal(bpath)) {
DBG_FS << " found at '" << bpath.string() << "'\n";
return bpath.string();
}
}
DBG_FS << " not found\n";
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
if (!is_legal_file(filename))
return std::string();
assert(game_config::path.empty() == false);
path fpath(filename);
path result;
if (filename[0] == '~')
{
result /= get_user_data_path() / "data" / filename.substr(1);
DBG_FS << " trying '" << result.string() << "'\n";
} else if (*fpath.begin() == ".") {
if (!current_dir.empty()) {
result /= path(current_dir);
} else {
result /= path(game_config::path) / "data";
}
result /= filename;
} else if (!game_config::path.empty()) {
result /= path(game_config::path) / "data" / filename;
}
if (result.empty() || !file_exists(result)) {
DBG_FS << " not found\n";
result.clear();
} else
DBG_FS << " found: '" << result.string() << "'\n";
return result.string();
}
static path subtract_path(const path &full, const path &prefix)
{
path::iterator fi = full.begin()
, fe = full.end()
, pi = prefix.begin()
, pe = prefix.end();
while (fi != fe && pi != pe && *fi == *pi) {
++fi;
++pi;
}
path rest;
if (pi == pe)
while (fi != fe) {
rest /= *fi;
++fi;
}
return rest;
}
std::string get_short_wml_path(const std::string &filename)
{
path full_path(filename);
path partial = subtract_path(full_path, get_user_data_path() / "data");
if (!partial.empty())
return "~" + partial.string();
partial = subtract_path(full_path, path(game_config::path) / "data");
if (!partial.empty())
return partial.string();
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
path full_path(get_binary_file_location("images", filename));
if (full_path.empty())
return full_path.string();
path partial = subtract_path(full_path, get_user_data_path());
if (!partial.empty())
return partial.string();
partial = subtract_path(full_path, game_config::path);
if (!partial.empty())
return partial.string();
return full_path.string();
}
std::string get_program_invocation(const std::string &program_name)
{
const std::string real_program_name(program_name
#ifdef DEBUG
+ "-debug"
#endif
#ifdef _WIN32
+ ".exe"
#endif
);
return (path(game_config::wesnoth_program_dir) / real_program_name).string();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1649_2 |
crossvul-cpp_data_good_1387_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/fastcgi/fastcgi-server.h"
#include "hphp/runtime/server/http-server.h"
namespace HPHP {
////////////////////////////////////////////////////////////////////////////////
bool FastCGIAcceptor::canAccept(const folly::SocketAddress& /*address*/) {
// TODO: Support server IP whitelist.
auto const cons = m_server->getLibEventConnectionCount();
return (RuntimeOption::ServerConnectionLimit == 0 ||
cons < RuntimeOption::ServerConnectionLimit);
}
void FastCGIAcceptor::onNewConnection(
folly::AsyncTransportWrapper::UniquePtr sock,
const folly::SocketAddress* peerAddress,
const std::string& /*nextProtocolName*/,
SecureTransportType /*secureProtocolType*/,
const ::wangle::TransportInfo& /*tinfo*/) {
folly::SocketAddress localAddress;
try {
sock->getLocalAddress(&localAddress);
} catch (std::system_error& e) {
// If getSockName fails it's bad news; abort the connection
return;
}
// Will delete itself when it gets a closing callback
auto session = new FastCGISession(
m_server->getEventBaseManager()->getExistingEventBase(),
m_server->getDispatcher(),
std::move(sock),
localAddress,
*peerAddress
);
// NB: ~ManagedConnection will call removeConnection() before the session
// destroys itself.
Acceptor::addConnection(session);
};
void FastCGIAcceptor::onConnectionsDrained() {
m_server->onConnectionsDrained();
}
////////////////////////////////////////////////////////////////////////////////
FastCGIServer::FastCGIServer(const std::string &address,
int port,
int workers,
bool useFileSocket)
: Server(address, port),
m_worker(&m_eventBaseManager),
m_dispatcher(workers, workers,
RuntimeOption::ServerThreadDropCacheTimeoutSeconds,
RuntimeOption::ServerThreadDropStack,
this,
RuntimeOption::ServerThreadJobLIFOSwitchThreshold,
RuntimeOption::ServerThreadJobMaxQueuingMilliSeconds,
RequestPriority::k_numPriorities) {
folly::SocketAddress sock_addr;
if (useFileSocket) {
sock_addr.setFromPath(address);
} else if (address.empty()) {
sock_addr.setFromHostPort("localhost", port);
assert(sock_addr.isLoopbackAddress());
} else {
sock_addr.setFromHostPort(address, port);
}
m_socketConfig.bindAddress = sock_addr;
m_socketConfig.acceptBacklog = RuntimeOption::ServerBacklog;
std::chrono::seconds timeout;
if (RuntimeOption::ConnectionTimeoutSeconds >= 0) {
timeout = std::chrono::seconds(RuntimeOption::ConnectionTimeoutSeconds);
} else {
// default to 2 minutes
timeout = std::chrono::seconds(120);
}
m_socketConfig.connectionIdleTimeout = timeout;
}
void FastCGIServer::start() {
// It's not safe to call this function more than once
m_socket.reset(new folly::AsyncServerSocket(m_worker.getEventBase()));
try {
m_socket->bind(m_socketConfig.bindAddress);
} catch (const std::system_error& ex) {
Logger::Error(std::string(ex.what()));
if (m_socketConfig.bindAddress.getFamily() == AF_UNIX) {
throw FailedToListenException(m_socketConfig.bindAddress.getPath());
}
throw FailedToListenException(m_socketConfig.bindAddress.getAddressStr(),
m_socketConfig.bindAddress.getPort());
}
if (m_socketConfig.bindAddress.getFamily() == AF_UNIX) {
auto path = m_socketConfig.bindAddress.getPath();
chmod(path.c_str(), 0760);
}
m_acceptor.reset(new FastCGIAcceptor(m_socketConfig, this));
m_acceptor->init(m_socket.get(), m_worker.getEventBase());
m_worker.getEventBase()->runInEventBaseThread([&] {
if (!m_socket) {
// Someone called stop before we got here. With the exception of a
// second call to start being made this should be safe as any place
// we mutate m_socket is done within the event base.
return;
}
m_socket->listen(m_socketConfig.acceptBacklog);
m_socket->startAccepting();
});
setStatus(RunStatus::RUNNING);
folly::AsyncTimeout::attachEventBase(m_worker.getEventBase());
m_worker.start();
m_dispatcher.start();
}
void FastCGIServer::waitForEnd() {
// When m_worker stops the server has stopped accepting new requests, there
// may be pedning vm jobs. wait() is always safe to call regardless of thread
m_worker.wait();
}
void FastCGIServer::stop() {
if (getStatus() != RunStatus::RUNNING) return; // nothing to do
setStatus(RunStatus::STOPPING);
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DRAIN_READS);
m_worker.getEventBase()->runInEventBaseThread([&] {
// Shutdown the server socket. Unfortunately, we will drop all unaccepted
// connections; there is no way to do a partial shutdown of a server socket
m_socket->stopAccepting();
if (RuntimeOption::ServerGracefulShutdownWait > 0) {
// Gracefully drain any incomplete requests. We cannot go offline until
// they are finished as we own their dispatcher and event base.
if (m_acceptor) {
m_acceptor->drainAllConnections();
}
std::chrono::seconds s(RuntimeOption::ServerGracefulShutdownWait);
std::chrono::milliseconds m(s);
scheduleTimeout(m);
} else {
// Drop all connections. We cannot shutdown until they stop because we
// own their dispatcher and event base.
if (m_acceptor) {
m_acceptor->forceStop();
}
terminateServer();
}
});
}
void FastCGIServer::onConnectionsDrained() {
// NOTE: called from FastCGIAcceptor::onConnectionsDrained()
cancelTimeout();
terminateServer();
}
void FastCGIServer::timeoutExpired() noexcept {
// Acceptor failed to drain connections on time; drop them so that we can
// shutdown.
if (m_acceptor) {
m_acceptor->forceStop();
}
terminateServer();
}
void FastCGIServer::terminateServer() {
if (getStatus() != RunStatus::STOPPING) {
setStatus(RunStatus::STOPPING);
}
// Wait for the server socket thread to stop running
m_worker.stopWhenIdle();
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DRAIN_DISPATCHER);
// Wait for VMs to shutdown
m_dispatcher.stop();
setStatus(RunStatus::STOPPED);
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DONE);
// Notify HttpServer that we've shutdown
for (auto listener: m_listeners) {
listener->serverStopped(this);
}
}
////////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1387_0 |
crossvul-cpp_data_good_1649_1 | /*
Copyright (C) 2003 - 2015 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
// Include files for opendir(3), readdir(3), etc.
// These files may vary from platform to platform,
// since these functions are NOT ANSI-conforming functions.
// They may have to be altered to port to new platforms
//for mkdir
#include <sys/stat.h>
#ifdef _WIN32
#include "filesystem_win32.ii"
#include <cctype>
#else /* !_WIN32 */
#include <unistd.h>
#include <dirent.h>
#include <libgen.h>
#endif /* !_WIN32 */
// for getenv
#include <cerrno>
#include <fstream>
#include <iomanip>
#include <set>
#include <boost/algorithm/string.hpp>
// for strerror
#include <cstring>
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "scoped_resource.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "version.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace {
const mode_t AccessMode = 00770;
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFBase.h>
#endif
namespace filesystem {
void get_files_in_dir(const std::string &directory,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum)
{
// If we have a path to find directories in,
// then convert relative pathnames to be rooted
// on the wesnoth path
if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
std::string dir = game_config::path + "/" + directory;
if(is_directory(dir)) {
get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
return;
}
}
struct stat st;
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
std::string maincfg;
if (directory.empty() || directory[directory.size()-1] == '/')
maincfg = directory + maincfg_filename;
else
maincfg = (directory + "/") + maincfg_filename;
if (::stat(maincfg.c_str(), &st) != -1) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(maincfg);
else
files->push_back(maincfg_filename);
}
return;
}
}
DIR* dir = opendir(directory.c_str());
if(dir == NULL) {
// Probably not a directory, let the caller deal with it.
return;
}
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] == '.')
continue;
#ifdef __APPLE__
// HFS Mac OS X decomposes filenames using combining unicode characters.
// Try to get the precomposed form.
char macname[MAXNAMLEN+1];
CFStringRef cstr = CFStringCreateWithCString(NULL,
entry->d_name,
kCFStringEncodingUTF8);
CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
0, cstr);
CFStringNormalize(mut_str, kCFStringNormalizationFormC);
CFStringGetCString(mut_str,
macname,sizeof(macname)-1,
kCFStringEncodingUTF8);
CFRelease(cstr);
CFRelease(mut_str);
const std::string basename = macname;
#else
// generic Unix
const std::string basename = entry->d_name;
#endif /* !APPLE */
std::string fullname;
if (directory.empty() || directory[directory.size()-1] == '/')
fullname = directory + basename;
else
fullname = directory + "/" + basename;
if (::stat(fullname.c_str(), &st) != -1) {
if (S_ISREG(st.st_mode)) {
if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
continue;
}
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(fullname);
else
files->push_back(basename);
}
if (checksum != NULL) {
if(st.st_mtime > checksum->modified) {
checksum->modified = st.st_mtime;
}
checksum->sum_size += st.st_size;
checksum->nfiles++;
}
} else if (S_ISDIR(st.st_mode)) {
if (filter == SKIP_MEDIA_DIR
&& (basename == "images"|| basename == "sounds"))
continue;
if (reorder == DO_REORDER &&
::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
S_ISREG(st.st_mode)) {
LOG_FS << "_main.cfg found : ";
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH) {
files->push_back(fullname + "/" + maincfg_filename);
LOG_FS << fullname << "/" << maincfg_filename << '\n';
} else {
files->push_back(basename + "/" + maincfg_filename);
LOG_FS << basename << "/" << maincfg_filename << '\n';
}
} else {
// Show what I consider strange
LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory " << std::endl;
}
} else if (dirs != NULL) {
if (mode == ENTIRE_FILE_PATH)
dirs->push_back(fullname);
else
dirs->push_back(basename);
}
}
}
}
closedir(dir);
if(files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
unsigned int foundit = 0;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
// If _initial.cfg needs to be moved (it was found, but not at index 0).
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; --i)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
std::string get_dir(const std::string& dir_path)
{
DIR* dir = opendir(dir_path.c_str());
if(dir == NULL) {
const int res = mkdir(dir_path.c_str(),AccessMode);
if(res == 0) {
dir = opendir(dir_path.c_str());
} else {
ERR_FS << "could not open or create directory: " << dir_path << std::endl;
}
}
if(dir == NULL)
return "";
closedir(dir);
return dir_path;
}
bool make_directory(const std::string& path)
{
return (mkdir(path.c_str(),AccessMode) == 0);
}
// This deletes a directory with no hidden files and subdirectories.
// Also deletes a single file.
bool delete_directory(const std::string& path, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
errno = 0;
if(remove((*i).c_str()) != 0) {
LOG_FS << "remove(" << (*i) << "): " << strerror(errno) << std::endl;
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
if(!delete_directory(*j))
ret = false;
}
}
errno = 0;
#ifdef _WIN32
// remove() doesn't delete directories on windows.
int (*remove)(const char*);
if(is_directory(path))
remove = rmdir;
else
remove = ::remove;
#endif
if(remove(path.c_str()) != 0) {
LOG_FS << "remove(" << path << "): " << strerror(errno) << std::endl;
ret = false;
}
return ret;
}
bool delete_file(const std::string& path)
{
bool ret = true;
if(remove(path.c_str()) != 0 && errno != ENOENT) {
ERR_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
std::string get_cwd()
{
char buf[1024];
const char* const res = getcwd(buf,sizeof(buf));
if(res != NULL) {
std::string str(res);
#ifdef _WIN32
std::replace(str.begin(),str.end(),'\\','/');
#endif
return str;
} else {
return "";
}
}
std::string get_exe_dir()
{
#ifndef _WIN32
char buf[1024];
size_t path_size = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if(path_size == static_cast<size_t>(-1))
return std::string();
buf[path_size] = 0;
return std::string(dirname(buf));
#else
return get_cwd();
#endif
}
bool create_directory_if_missing(const std::string& dirname)
{
if(is_directory(dirname)) {
DBG_FS << "directory " << dirname << " exists, not creating" << std::endl;
return true;
} else if(file_exists(dirname)) {
ERR_FS << "cannot create directory " << dirname << "; file exists" << std::endl;
return false;
}
DBG_FS << "creating missing directory " << dirname << '\n';
return make_directory(dirname);
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
DBG_FS<<"creating recursive directory: "<<dirname<<'\n';
if (is_directory(dirname) == false && dirname.empty() == false)
{
std::string tmp_dirname = dirname;
// remove trailing slashes or backslashes
while ((tmp_dirname[tmp_dirname.size()-1] == '/' ||
tmp_dirname[tmp_dirname.size()-1] == '\\') &&
!tmp_dirname.empty())
{
tmp_dirname.erase(tmp_dirname.size()-1);
}
// create the first non-existing directory
size_t pos = tmp_dirname.rfind("/");
// we get the most right directory and *skip* it
// we are creating it when we get back here
if (tmp_dirname.rfind('\\') != std::string::npos &&
tmp_dirname.rfind('\\') > pos )
pos = tmp_dirname.rfind('\\');
if (pos != std::string::npos)
create_directory_if_missing_recursive(tmp_dirname.substr(0,pos));
return create_directory_if_missing(tmp_dirname);
}
return create_directory_if_missing(dirname);
}
static std::string user_data_dir, user_config_dir, cache_dir;
static void setup_user_data_dir();
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
void set_user_data_dir(std::string path)
{
#ifdef _WIN32
if(path.empty()) {
user_data_dir = get_cwd() + "/userdata";
} else if (path.size() > 2 && path[1] == ':') {
//allow absolute path override
user_data_dir = path;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathA;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathA = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathA"));
if(SHGetSpecialFolderPathA) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents" << std::endl;
char my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathA(NULL, my_documents_path, 5, 1)) {
std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path + "/" + path;
} else {
WRN_FS << "SHGetSpecialFolderPath failed" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (path.empty()) path = PREFERENCES_DIR;
#endif
std::string path2 = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (path.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
path = path2;
goto other;
}
user_data_dir = home_str;
user_data_dir += "/.local/share";
} else user_data_dir = xdg_data;
user_data_dir += "/wesnoth/";
user_data_dir += get_version_path_suffix();
create_directory_if_missing_recursive(user_data_dir);
} else {
other:
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + "/" + path;
}
#else
if (path.empty()) path = path2;
const char* home_str = getenv("HOME");
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + std::string("/") + path;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
void set_user_config_dir(std::string path)
{
user_config_dir = path;
create_directory_if_missing(user_config_dir);
}
static void setup_user_data_dir()
{
#ifdef _WIN32
_mkdir(user_data_dir.c_str());
_mkdir((user_data_dir + "/editor").c_str());
_mkdir((user_data_dir + "/editor/maps").c_str());
_mkdir((user_data_dir + "/editor/scenarios").c_str());
_mkdir((user_data_dir + "/data").c_str());
_mkdir((user_data_dir + "/data/add-ons").c_str());
_mkdir((user_data_dir + "/saves").c_str());
_mkdir((user_data_dir + "/persist").c_str());
#else
const std::string& dir_path = user_data_dir;
const bool res = create_directory_if_missing(dir_path);
// probe read permissions (if we could make the directory)
DIR* const dir = res ? opendir(dir_path.c_str()) : NULL;
if(dir == NULL) {
ERR_FS << "could not open or create preferences directory at " << dir_path << std::endl;
return;
}
closedir(dir);
// Create user data and add-on directories
create_directory_if_missing(dir_path + "/editor");
create_directory_if_missing(dir_path + "/editor/maps");
create_directory_if_missing(dir_path + "/editor/scenarios");
create_directory_if_missing(dir_path + "/data");
create_directory_if_missing(dir_path + "/data/add-ons");
create_directory_if_missing(dir_path + "/saves");
create_directory_if_missing(dir_path + "/persist");
#endif
}
std::string get_user_data_dir()
{
// ensure setup gets called only once per session
// FIXME: this is okay and optimized, but how should we react
// if the user deletes a dir while we are running?
if (user_data_dir.empty())
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
std::string path;
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_dir();
return user_config_dir;
}
path = xdg_config;
path += "/.config";
} else path = xdg_config;
path += "/wesnoth";
set_user_config_dir(path);
#else
user_config_dir = get_user_data_dir();
#endif
}
return user_config_dir;
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_dir() + "/cache");
return cache_dir;
}
cache_dir = xdg_cache;
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
return cache_dir;
}
static std::string read_stream(std::istream& s)
{
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading." << std::endl;
if (fname.empty())
{
ERR_FS << "Trying to open file with empty name." << std::endl;
std::ifstream *s = new std::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
std::ifstream *s = new std::ifstream(fname.c_str(),std::ios_base::binary);
if (s->is_open()) {
return s;
}
if (treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading." << std::endl;
} else {
LOG_FS << "Could not open '" << fname << "' for reading." << std::endl;
}
return s;
}
std::string read_file(const std::string &fname)
{
scoped_istream s = istream_file(fname);
return read_stream(*s);
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing." << std::endl;
return new std::ofstream(fname.c_str(), std::ios_base::binary);
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
//const util::scoped_resource<FILE*,close_FILE> file(fopen(fname.c_str(),"wb"));
const util::scoped_FILE file(fopen(fname.c_str(),"wb"));
if(file.get() == NULL) {
throw io_exception("Could not open file for writing: '" + fname + "'");
}
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
const size_t res = fwrite(buf,1,bytes,file.get());
if(res != bytes) {
throw io_exception("Error writing to file: '" + fname + "'");
}
}
}
static bool is_directory_internal(const std::string& fname)
{
#ifdef _WIN32
_finddata_t info;
const long handle = _findfirst((fname + "/*").c_str(),&info);
if(handle >= 0) {
_findclose(handle);
return true;
} else {
return false;
}
#else
struct stat dir_stat;
if(::stat(fname.c_str(), &dir_stat) == -1) {
return false;
}
return S_ISDIR(dir_stat.st_mode);
#endif
}
bool is_directory(const std::string& fname)
{
if(fname.empty()) {
return false;
}
if(fname[0] != '/' && !game_config::path.empty()) {
if(is_directory_internal(game_config::path + "/" + fname))
return true;
}
return is_directory_internal(fname);
}
bool file_exists(const std::string& name)
{
#ifdef _WIN32
struct stat st;
return (::stat(name.c_str(), &st) == 0);
#else
struct stat st;
return (::stat(name.c_str(), &st) != -1);
#endif
}
time_t file_modified_time(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return 0;
return buf.st_mtime;
}
/**
* Returns true if the file ends with '.gz'.
*
* @param filename The name to test.
*/
bool is_gzip_file(const std::string& filename)
{
return (filename.length() > 3
&& filename.substr(filename.length() - 3) == ".gz");
}
/**
* Returns true if the file ends with '.bz2'.
*
* @param filename The name to test.
*/
bool is_bzip2_file(const std::string& filename)
{
return (filename.length() > 4
&& filename.substr(filename.length() - 4) == ".bz2");
}
int file_size(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return -1;
return buf.st_size;
}
int dir_size(const std::string& path)
{
std::vector<std::string> files, dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH);
int res = 0;
BOOST_FOREACH(const std::string& file_path, files)
{
res += file_size(file_path);
}
BOOST_FOREACH(const std::string& dir_path, dirs)
{
// FIXME: this could result in infinite recursion with symlinks!!
res += dir_size(dir_path);
}
return res;
}
std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return file;
if(pos >= file.size()-1)
return "";
return file.substr(pos+1);
}
std::string directory_name(const std::string& file)
// Analogous to POSIX dirname(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return "";
return file.substr(0,pos+1);
}
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'" << std::endl;
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths" << std::endl;
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
// Some parts of Wesnoth enjoy putting ".." inside filenames. This is
// bad and should be fixed. But in the meantime, deal with them in a dumb way.
std::string::size_type pos = filename.rfind("../");
if (pos != std::string::npos) {
std::string nf = filename.substr(pos + 3);
LOG_FS << "Illegal path '" << filename << "' replaced by '" << nf << "'" << std::endl;
return get_binary_file_location(type, nf);
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if(file_exists(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if (is_directory(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
if (ends_with(filename, ".pbl")) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
}
std::string get_short_wml_path(const std::string &filename)
{
std::string match = get_user_data_dir() + "/data/";
if (filename.find(match) == 0) {
return "~" + filename.substr(match.size());
}
match = game_config::path + "/data/";
if (filename.find(match) == 0) {
return filename.substr(match.size());
}
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
std::string full_path = get_binary_file_location("images", filename);
if(!full_path.empty()) {
std::string match = get_user_data_dir() + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
match = game_config::path + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
}
return full_path;
}
std::string get_program_invocation(const std::string& program_name) {
#ifdef DEBUG
#ifdef _WIN32
const char *program_suffix = "-debug.exe";
#else
const char *program_suffix = "-debug";
#endif
#else
#ifdef _WIN32
const char *program_suffix = ".exe";
#else
const char *program_suffix = "";
#endif
#endif
const std::string real_program_name(program_name + program_suffix);
if(game_config::wesnoth_program_dir.empty()) return real_program_name;
#ifdef _WIN32
return game_config::wesnoth_program_dir + "\\" + real_program_name;
#else
return game_config::wesnoth_program_dir + "/" + real_program_name;
#endif
}
bool is_path_sep(char c)
{
#ifdef _WIN32
if (c == '/' || c == '\\') return true;
#else
if (c == '/') return true;
#endif
return false;
}
std::string normalize_path(const std::string &p1)
{
if (p1.empty()) return p1;
std::string p2;
#ifdef _WIN32
if (p1.size() >= 2 && p1[1] == ':')
// Windows relative paths with explicit drive name are not handled.
p2 = p1;
else
#endif
if (!is_path_sep(p1[0]))
p2 = get_cwd() + "/" + p1;
else
p2 = p1;
#ifdef _WIN32
std::string drive;
if (p2.size() >= 2 && p2[1] == ':') {
drive = p2.substr(0, 2);
p2.erase(0, 2);
}
#endif
std::vector<std::string> components(1);
for (int i = 0, i_end = p2.size(); i <= i_end; ++i)
{
std::string &last = components[components.size() - 1];
char c = p2.c_str()[i];
if (is_path_sep(c) || c == 0)
{
if (last == ".")
last.clear();
else if (last == "..")
{
if (components.size() >= 2) {
components.pop_back();
components[components.size() - 1].clear();
} else
last.clear();
}
else if (!last.empty())
components.push_back(std::string());
}
else
last += c;
}
std::ostringstream p4;
components.pop_back();
#ifdef _WIN32
p4 << drive;
#endif
BOOST_FOREACH(const std::string &s, components)
{
p4 << '/' << s;
}
DBG_FS << "Normalizing '" << p2 << "' to '" << p4.str() << "'" << std::endl;
return p4.str();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1649_1 |
crossvul-cpp_data_good_186_4 | /*
* ECDSA implemenation
* (C) 2007 Manuel Hartl, FlexSecure GmbH
* 2007 Falko Strenzke, FlexSecure GmbH
* 2008-2010,2015,2016,2018 Jack Lloyd
* 2016 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/ecdsa.h>
#include <botan/internal/pk_ops_impl.h>
#include <botan/internal/point_mul.h>
#include <botan/keypair.h>
#include <botan/reducer.h>
#include <botan/emsa.h>
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
#include <botan/rfc6979.h>
#endif
#if defined(BOTAN_HAS_BEARSSL)
#include <botan/internal/bearssl.h>
#endif
#if defined(BOTAN_HAS_OPENSSL)
#include <botan/internal/openssl.h>
#endif
namespace Botan {
bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng,
bool strong) const
{
if(!public_point().on_the_curve())
return false;
if(!strong)
return true;
return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-256)");
}
namespace {
/**
* ECDSA signature operation
*/
class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA
{
public:
ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,
const std::string& emsa,
RandomNumberGenerator& rng) :
PK_Ops::Signature_with_EMSA(emsa),
m_group(ecdsa.domain()),
m_x(ecdsa.private_value())
{
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
m_rfc6979_hash = hash_for_emsa(emsa);
#endif
m_b = m_group.random_scalar(rng);
m_b_inv = m_group.inverse_mod_order(m_b);
}
size_t max_input_bits() const override { return m_group.get_order_bits(); }
secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng) override;
private:
const EC_Group m_group;
const BigInt& m_x;
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
std::string m_rfc6979_hash;
#endif
std::vector<BigInt> m_ws;
BigInt m_b, m_b_inv;
};
secure_vector<uint8_t>
ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
BigInt m(msg, msg_len, m_group.get_order_bits());
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);
#else
const BigInt k = m_group.random_scalar(rng);
#endif
const BigInt r = m_group.mod_order(
m_group.blinded_base_point_multiply_x(k, rng, m_ws));
const BigInt k_inv = m_group.inverse_mod_order(k);
/*
* Blind the input message and compute x*r+m as (x*r*b + m*b)/b
*/
m_b = m_group.square_mod_order(m_b);
m_b_inv = m_group.square_mod_order(m_b_inv);
m = m_group.multiply_mod_order(m_b, m);
const BigInt xr = m_group.multiply_mod_order(m_x, m_b, r);
const BigInt s = m_group.multiply_mod_order(k_inv, xr + m, m_b_inv);
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("During ECDSA signature generated zero r/s");
return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());
}
/**
* ECDSA verification operation
*/
class ECDSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA
{
public:
ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa,
const std::string& emsa) :
PK_Ops::Verification_with_EMSA(emsa),
m_group(ecdsa.domain()),
m_gy_mul(m_group.get_base_point(), ecdsa.public_point())
{
}
size_t max_input_bits() const override { return m_group.get_order_bits(); }
bool with_recovery() const override { return false; }
bool verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len) override;
private:
const EC_Group m_group;
const PointGFp_Multi_Point_Precompute m_gy_mul;
};
bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len)
{
if(sig_len != m_group.get_order_bytes() * 2)
return false;
const BigInt e(msg, msg_len, m_group.get_order_bits());
const BigInt r(sig, sig_len / 2);
const BigInt s(sig + sig_len / 2, sig_len / 2);
if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())
return false;
const BigInt w = m_group.inverse_mod_order(s);
const BigInt u1 = m_group.multiply_mod_order(m_group.mod_order(e), w);
const BigInt u2 = m_group.multiply_mod_order(r, w);
const PointGFp R = m_gy_mul.multi_exp(u1, u2);
if(R.is_zero())
return false;
const BigInt v = m_group.mod_order(R.get_affine_x());
return (v == r);
}
}
std::unique_ptr<PK_Ops::Verification>
ECDSA_PublicKey::create_verification_op(const std::string& params,
const std::string& provider) const
{
#if defined(BOTAN_HAS_BEARSSL)
if(provider == "bearssl" || provider.empty())
{
try
{
return make_bearssl_ecdsa_ver_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "bearssl")
throw;
}
}
#endif
#if defined(BOTAN_HAS_OPENSSL)
if(provider == "openssl" || provider.empty())
{
try
{
return make_openssl_ecdsa_ver_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "openssl")
throw;
}
}
#endif
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Verification>(new ECDSA_Verification_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
}
std::unique_ptr<PK_Ops::Signature>
ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
const std::string& params,
const std::string& provider) const
{
#if defined(BOTAN_HAS_BEARSSL)
if(provider == "bearssl" || provider.empty())
{
try
{
return make_bearssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "bearssl")
throw;
}
}
#endif
#if defined(BOTAN_HAS_OPENSSL)
if(provider == "openssl" || provider.empty())
{
try
{
return make_openssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "openssl")
throw;
}
}
#endif
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params, rng));
throw Provider_Not_Found(algo_name(), provider);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_186_4 |
crossvul-cpp_data_bad_1649_1 | /*
Copyright (C) 2003 - 2015 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
// Include files for opendir(3), readdir(3), etc.
// These files may vary from platform to platform,
// since these functions are NOT ANSI-conforming functions.
// They may have to be altered to port to new platforms
//for mkdir
#include <sys/stat.h>
#ifdef _WIN32
#include "filesystem_win32.ii"
#include <cctype>
#else /* !_WIN32 */
#include <unistd.h>
#include <dirent.h>
#include <libgen.h>
#endif /* !_WIN32 */
// for getenv
#include <cerrno>
#include <fstream>
#include <iomanip>
#include <set>
#include <boost/algorithm/string.hpp>
// for strerror
#include <cstring>
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "scoped_resource.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "version.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace {
const mode_t AccessMode = 00770;
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFBase.h>
#endif
namespace filesystem {
void get_files_in_dir(const std::string &directory,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum)
{
// If we have a path to find directories in,
// then convert relative pathnames to be rooted
// on the wesnoth path
if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
std::string dir = game_config::path + "/" + directory;
if(is_directory(dir)) {
get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
return;
}
}
struct stat st;
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
std::string maincfg;
if (directory.empty() || directory[directory.size()-1] == '/')
maincfg = directory + maincfg_filename;
else
maincfg = (directory + "/") + maincfg_filename;
if (::stat(maincfg.c_str(), &st) != -1) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(maincfg);
else
files->push_back(maincfg_filename);
}
return;
}
}
DIR* dir = opendir(directory.c_str());
if(dir == NULL) {
// Probably not a directory, let the caller deal with it.
return;
}
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] == '.')
continue;
#ifdef __APPLE__
// HFS Mac OS X decomposes filenames using combining unicode characters.
// Try to get the precomposed form.
char macname[MAXNAMLEN+1];
CFStringRef cstr = CFStringCreateWithCString(NULL,
entry->d_name,
kCFStringEncodingUTF8);
CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
0, cstr);
CFStringNormalize(mut_str, kCFStringNormalizationFormC);
CFStringGetCString(mut_str,
macname,sizeof(macname)-1,
kCFStringEncodingUTF8);
CFRelease(cstr);
CFRelease(mut_str);
const std::string basename = macname;
#else
// generic Unix
const std::string basename = entry->d_name;
#endif /* !APPLE */
std::string fullname;
if (directory.empty() || directory[directory.size()-1] == '/')
fullname = directory + basename;
else
fullname = directory + "/" + basename;
if (::stat(fullname.c_str(), &st) != -1) {
if (S_ISREG(st.st_mode)) {
if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
continue;
}
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(fullname);
else
files->push_back(basename);
}
if (checksum != NULL) {
if(st.st_mtime > checksum->modified) {
checksum->modified = st.st_mtime;
}
checksum->sum_size += st.st_size;
checksum->nfiles++;
}
} else if (S_ISDIR(st.st_mode)) {
if (filter == SKIP_MEDIA_DIR
&& (basename == "images"|| basename == "sounds"))
continue;
if (reorder == DO_REORDER &&
::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
S_ISREG(st.st_mode)) {
LOG_FS << "_main.cfg found : ";
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH) {
files->push_back(fullname + "/" + maincfg_filename);
LOG_FS << fullname << "/" << maincfg_filename << '\n';
} else {
files->push_back(basename + "/" + maincfg_filename);
LOG_FS << basename << "/" << maincfg_filename << '\n';
}
} else {
// Show what I consider strange
LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory " << std::endl;
}
} else if (dirs != NULL) {
if (mode == ENTIRE_FILE_PATH)
dirs->push_back(fullname);
else
dirs->push_back(basename);
}
}
}
}
closedir(dir);
if(files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
unsigned int foundit = 0;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
// If _initial.cfg needs to be moved (it was found, but not at index 0).
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; --i)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
std::string get_dir(const std::string& dir_path)
{
DIR* dir = opendir(dir_path.c_str());
if(dir == NULL) {
const int res = mkdir(dir_path.c_str(),AccessMode);
if(res == 0) {
dir = opendir(dir_path.c_str());
} else {
ERR_FS << "could not open or create directory: " << dir_path << std::endl;
}
}
if(dir == NULL)
return "";
closedir(dir);
return dir_path;
}
bool make_directory(const std::string& path)
{
return (mkdir(path.c_str(),AccessMode) == 0);
}
// This deletes a directory with no hidden files and subdirectories.
// Also deletes a single file.
bool delete_directory(const std::string& path, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
errno = 0;
if(remove((*i).c_str()) != 0) {
LOG_FS << "remove(" << (*i) << "): " << strerror(errno) << std::endl;
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
if(!delete_directory(*j))
ret = false;
}
}
errno = 0;
#ifdef _WIN32
// remove() doesn't delete directories on windows.
int (*remove)(const char*);
if(is_directory(path))
remove = rmdir;
else
remove = ::remove;
#endif
if(remove(path.c_str()) != 0) {
LOG_FS << "remove(" << path << "): " << strerror(errno) << std::endl;
ret = false;
}
return ret;
}
bool delete_file(const std::string& path)
{
bool ret = true;
if(remove(path.c_str()) != 0 && errno != ENOENT) {
ERR_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
std::string get_cwd()
{
char buf[1024];
const char* const res = getcwd(buf,sizeof(buf));
if(res != NULL) {
std::string str(res);
#ifdef _WIN32
std::replace(str.begin(),str.end(),'\\','/');
#endif
return str;
} else {
return "";
}
}
std::string get_exe_dir()
{
#ifndef _WIN32
char buf[1024];
size_t path_size = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if(path_size == static_cast<size_t>(-1))
return std::string();
buf[path_size] = 0;
return std::string(dirname(buf));
#else
return get_cwd();
#endif
}
bool create_directory_if_missing(const std::string& dirname)
{
if(is_directory(dirname)) {
DBG_FS << "directory " << dirname << " exists, not creating" << std::endl;
return true;
} else if(file_exists(dirname)) {
ERR_FS << "cannot create directory " << dirname << "; file exists" << std::endl;
return false;
}
DBG_FS << "creating missing directory " << dirname << '\n';
return make_directory(dirname);
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
DBG_FS<<"creating recursive directory: "<<dirname<<'\n';
if (is_directory(dirname) == false && dirname.empty() == false)
{
std::string tmp_dirname = dirname;
// remove trailing slashes or backslashes
while ((tmp_dirname[tmp_dirname.size()-1] == '/' ||
tmp_dirname[tmp_dirname.size()-1] == '\\') &&
!tmp_dirname.empty())
{
tmp_dirname.erase(tmp_dirname.size()-1);
}
// create the first non-existing directory
size_t pos = tmp_dirname.rfind("/");
// we get the most right directory and *skip* it
// we are creating it when we get back here
if (tmp_dirname.rfind('\\') != std::string::npos &&
tmp_dirname.rfind('\\') > pos )
pos = tmp_dirname.rfind('\\');
if (pos != std::string::npos)
create_directory_if_missing_recursive(tmp_dirname.substr(0,pos));
return create_directory_if_missing(tmp_dirname);
}
return create_directory_if_missing(dirname);
}
static std::string user_data_dir, user_config_dir, cache_dir;
static void setup_user_data_dir();
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
void set_user_data_dir(std::string path)
{
#ifdef _WIN32
if(path.empty()) {
user_data_dir = get_cwd() + "/userdata";
} else if (path.size() > 2 && path[1] == ':') {
//allow absolute path override
user_data_dir = path;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathA;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathA = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathA"));
if(SHGetSpecialFolderPathA) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents" << std::endl;
char my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathA(NULL, my_documents_path, 5, 1)) {
std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path + "/" + path;
} else {
WRN_FS << "SHGetSpecialFolderPath failed" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (path.empty()) path = PREFERENCES_DIR;
#endif
std::string path2 = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (path.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
path = path2;
goto other;
}
user_data_dir = home_str;
user_data_dir += "/.local/share";
} else user_data_dir = xdg_data;
user_data_dir += "/wesnoth/";
user_data_dir += get_version_path_suffix();
create_directory_if_missing_recursive(user_data_dir);
} else {
other:
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + "/" + path;
}
#else
if (path.empty()) path = path2;
const char* home_str = getenv("HOME");
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + std::string("/") + path;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
void set_user_config_dir(std::string path)
{
user_config_dir = path;
create_directory_if_missing(user_config_dir);
}
static void setup_user_data_dir()
{
#ifdef _WIN32
_mkdir(user_data_dir.c_str());
_mkdir((user_data_dir + "/editor").c_str());
_mkdir((user_data_dir + "/editor/maps").c_str());
_mkdir((user_data_dir + "/editor/scenarios").c_str());
_mkdir((user_data_dir + "/data").c_str());
_mkdir((user_data_dir + "/data/add-ons").c_str());
_mkdir((user_data_dir + "/saves").c_str());
_mkdir((user_data_dir + "/persist").c_str());
#else
const std::string& dir_path = user_data_dir;
const bool res = create_directory_if_missing(dir_path);
// probe read permissions (if we could make the directory)
DIR* const dir = res ? opendir(dir_path.c_str()) : NULL;
if(dir == NULL) {
ERR_FS << "could not open or create preferences directory at " << dir_path << std::endl;
return;
}
closedir(dir);
// Create user data and add-on directories
create_directory_if_missing(dir_path + "/editor");
create_directory_if_missing(dir_path + "/editor/maps");
create_directory_if_missing(dir_path + "/editor/scenarios");
create_directory_if_missing(dir_path + "/data");
create_directory_if_missing(dir_path + "/data/add-ons");
create_directory_if_missing(dir_path + "/saves");
create_directory_if_missing(dir_path + "/persist");
#endif
}
std::string get_user_data_dir()
{
// ensure setup gets called only once per session
// FIXME: this is okay and optimized, but how should we react
// if the user deletes a dir while we are running?
if (user_data_dir.empty())
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
std::string path;
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_dir();
return user_config_dir;
}
path = xdg_config;
path += "/.config";
} else path = xdg_config;
path += "/wesnoth";
set_user_config_dir(path);
#else
user_config_dir = get_user_data_dir();
#endif
}
return user_config_dir;
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_dir() + "/cache");
return cache_dir;
}
cache_dir = xdg_cache;
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
return cache_dir;
}
static std::string read_stream(std::istream& s)
{
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading." << std::endl;
if (fname.empty())
{
ERR_FS << "Trying to open file with empty name." << std::endl;
std::ifstream *s = new std::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
std::ifstream *s = new std::ifstream(fname.c_str(),std::ios_base::binary);
if (s->is_open()) {
return s;
}
if (treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading." << std::endl;
} else {
LOG_FS << "Could not open '" << fname << "' for reading." << std::endl;
}
return s;
}
std::string read_file(const std::string &fname)
{
scoped_istream s = istream_file(fname);
return read_stream(*s);
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing." << std::endl;
return new std::ofstream(fname.c_str(), std::ios_base::binary);
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
//const util::scoped_resource<FILE*,close_FILE> file(fopen(fname.c_str(),"wb"));
const util::scoped_FILE file(fopen(fname.c_str(),"wb"));
if(file.get() == NULL) {
throw io_exception("Could not open file for writing: '" + fname + "'");
}
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
const size_t res = fwrite(buf,1,bytes,file.get());
if(res != bytes) {
throw io_exception("Error writing to file: '" + fname + "'");
}
}
}
static bool is_directory_internal(const std::string& fname)
{
#ifdef _WIN32
_finddata_t info;
const long handle = _findfirst((fname + "/*").c_str(),&info);
if(handle >= 0) {
_findclose(handle);
return true;
} else {
return false;
}
#else
struct stat dir_stat;
if(::stat(fname.c_str(), &dir_stat) == -1) {
return false;
}
return S_ISDIR(dir_stat.st_mode);
#endif
}
bool is_directory(const std::string& fname)
{
if(fname.empty()) {
return false;
}
if(fname[0] != '/' && !game_config::path.empty()) {
if(is_directory_internal(game_config::path + "/" + fname))
return true;
}
return is_directory_internal(fname);
}
bool file_exists(const std::string& name)
{
#ifdef _WIN32
struct stat st;
return (::stat(name.c_str(), &st) == 0);
#else
struct stat st;
return (::stat(name.c_str(), &st) != -1);
#endif
}
time_t file_modified_time(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return 0;
return buf.st_mtime;
}
/**
* Returns true if the file ends with '.gz'.
*
* @param filename The name to test.
*/
bool is_gzip_file(const std::string& filename)
{
return (filename.length() > 3
&& filename.substr(filename.length() - 3) == ".gz");
}
/**
* Returns true if the file ends with '.bz2'.
*
* @param filename The name to test.
*/
bool is_bzip2_file(const std::string& filename)
{
return (filename.length() > 4
&& filename.substr(filename.length() - 4) == ".bz2");
}
int file_size(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return -1;
return buf.st_size;
}
int dir_size(const std::string& path)
{
std::vector<std::string> files, dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH);
int res = 0;
BOOST_FOREACH(const std::string& file_path, files)
{
res += file_size(file_path);
}
BOOST_FOREACH(const std::string& dir_path, dirs)
{
// FIXME: this could result in infinite recursion with symlinks!!
res += dir_size(dir_path);
}
return res;
}
std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return file;
if(pos >= file.size()-1)
return "";
return file.substr(pos+1);
}
std::string directory_name(const std::string& file)
// Analogous to POSIX dirname(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return "";
return file.substr(0,pos+1);
}
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'" << std::endl;
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths" << std::endl;
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
// Some parts of Wesnoth enjoy putting ".." inside filenames. This is
// bad and should be fixed. But in the meantime, deal with them in a dumb way.
std::string::size_type pos = filename.rfind("../");
if (pos != std::string::npos) {
std::string nf = filename.substr(pos + 3);
LOG_FS << "Illegal path '" << filename << "' replaced by '" << nf << "'" << std::endl;
return get_binary_file_location(type, nf);
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if(file_exists(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if (is_directory(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
}
std::string get_short_wml_path(const std::string &filename)
{
std::string match = get_user_data_dir() + "/data/";
if (filename.find(match) == 0) {
return "~" + filename.substr(match.size());
}
match = game_config::path + "/data/";
if (filename.find(match) == 0) {
return filename.substr(match.size());
}
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
std::string full_path = get_binary_file_location("images", filename);
if(!full_path.empty()) {
std::string match = get_user_data_dir() + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
match = game_config::path + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
}
return full_path;
}
std::string get_program_invocation(const std::string& program_name) {
#ifdef DEBUG
#ifdef _WIN32
const char *program_suffix = "-debug.exe";
#else
const char *program_suffix = "-debug";
#endif
#else
#ifdef _WIN32
const char *program_suffix = ".exe";
#else
const char *program_suffix = "";
#endif
#endif
const std::string real_program_name(program_name + program_suffix);
if(game_config::wesnoth_program_dir.empty()) return real_program_name;
#ifdef _WIN32
return game_config::wesnoth_program_dir + "\\" + real_program_name;
#else
return game_config::wesnoth_program_dir + "/" + real_program_name;
#endif
}
bool is_path_sep(char c)
{
#ifdef _WIN32
if (c == '/' || c == '\\') return true;
#else
if (c == '/') return true;
#endif
return false;
}
std::string normalize_path(const std::string &p1)
{
if (p1.empty()) return p1;
std::string p2;
#ifdef _WIN32
if (p1.size() >= 2 && p1[1] == ':')
// Windows relative paths with explicit drive name are not handled.
p2 = p1;
else
#endif
if (!is_path_sep(p1[0]))
p2 = get_cwd() + "/" + p1;
else
p2 = p1;
#ifdef _WIN32
std::string drive;
if (p2.size() >= 2 && p2[1] == ':') {
drive = p2.substr(0, 2);
p2.erase(0, 2);
}
#endif
std::vector<std::string> components(1);
for (int i = 0, i_end = p2.size(); i <= i_end; ++i)
{
std::string &last = components[components.size() - 1];
char c = p2.c_str()[i];
if (is_path_sep(c) || c == 0)
{
if (last == ".")
last.clear();
else if (last == "..")
{
if (components.size() >= 2) {
components.pop_back();
components[components.size() - 1].clear();
} else
last.clear();
}
else if (!last.empty())
components.push_back(std::string());
}
else
last += c;
}
std::ostringstream p4;
components.pop_back();
#ifdef _WIN32
p4 << drive;
#endif
BOOST_FOREACH(const std::string &s, components)
{
p4 << '/' << s;
}
DBG_FS << "Normalizing '" << p2 << "' to '" << p4.str() << "'" << std::endl;
return p4.str();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1649_1 |
crossvul-cpp_data_good_1512_0 | // rw.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "rw.h"
#include "nbtheory.h"
#include "asn.h"
#ifndef CRYPTOPP_IMPORTS
NAMESPACE_BEGIN(CryptoPP)
void RWFunction::BERDecode(BufferedTransformation &bt)
{
BERSequenceDecoder seq(bt);
m_n.BERDecode(seq);
seq.MessageEnd();
}
void RWFunction::DEREncode(BufferedTransformation &bt) const
{
DERSequenceEncoder seq(bt);
m_n.DEREncode(seq);
seq.MessageEnd();
}
Integer RWFunction::ApplyFunction(const Integer &in) const
{
DoQuickSanityCheck();
Integer out = in.Squared()%m_n;
const word r = 12;
// this code was written to handle both r = 6 and r = 12,
// but now only r = 12 is used in P1363
const word r2 = r/2;
const word r3a = (16 + 5 - r) % 16; // n%16 could be 5 or 13
const word r3b = (16 + 13 - r) % 16;
const word r4 = (8 + 5 - r/2) % 8; // n%8 == 5
switch (out % 16)
{
case r:
break;
case r2:
case r2+8:
out <<= 1;
break;
case r3a:
case r3b:
out.Negate();
out += m_n;
break;
case r4:
case r4+8:
out.Negate();
out += m_n;
out <<= 1;
break;
default:
out = Integer::Zero();
}
return out;
}
bool RWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
bool pass = true;
pass = pass && m_n > Integer::One() && m_n%8 == 5;
return pass;
}
bool RWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
return GetValueHelper(this, name, valueType, pValue).Assignable()
CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
;
}
void RWFunction::AssignFrom(const NameValuePairs &source)
{
AssignFromHelper(this, source)
CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
;
}
// *****************************************************************************
// private key operations:
// generate a random private key
void InvertibleRWFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
{
int modulusSize = 2048;
alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize);
if (modulusSize < 16)
throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small");
AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize);
m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8)));
m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8)));
m_n = m_p * m_q;
m_u = m_q.InverseMod(m_p);
}
void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
{
BERSequenceDecoder seq(bt);
m_n.BERDecode(seq);
m_p.BERDecode(seq);
m_q.BERDecode(seq);
m_u.BERDecode(seq);
seq.MessageEnd();
}
void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
{
DERSequenceEncoder seq(bt);
m_n.DEREncode(seq);
m_p.DEREncode(seq);
m_q.DEREncode(seq);
m_u.DEREncode(seq);
seq.MessageEnd();
}
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
{
DoQuickSanityCheck();
ModularArithmetic modn(m_n);
Integer r, rInv;
// do this in a loop for people using small numbers for testing
do {
r.Randomize(rng, Integer::One(), m_n - Integer::One());
// Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
// Squaring to satisfy Jacobi requirements suggested by JPM.
r = modn.Square(r);
rInv = modn.MultiplicativeInverse(r);
} while (rInv.IsZero());
Integer re = modn.Square(r);
re = modn.Multiply(re, x); // blind
Integer cp=re%m_p, cq=re%m_q;
if (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)
{
cp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;
cq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;
}
#pragma omp parallel
#pragma omp sections
{
#pragma omp section
cp = ModularSquareRoot(cp, m_p);
#pragma omp section
cq = ModularSquareRoot(cq, m_q);
}
Integer y = CRT(cq, m_q, cp, m_p, m_u);
y = modn.Multiply(y, rInv); // unblind
y = STDMIN(y, m_n-y);
if (ApplyFunction(y) != x) // check
throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");
return y;
}
bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
bool pass = RWFunction::Validate(rng, level);
pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
pass = pass && m_u.IsPositive() && m_u < m_p;
if (level >= 1)
{
pass = pass && m_p * m_q == m_n;
pass = pass && m_u * m_q % m_p == 1;
}
if (level >= 2)
pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
return pass;
}
bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
;
}
void InvertibleRWFunction::AssignFrom(const NameValuePairs &source)
{
AssignFromHelper<RWFunction>(this, source)
CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
;
}
NAMESPACE_END
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1512_0 |
crossvul-cpp_data_bad_5850_0 | /*
* Copyright (C) 2003-2005 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tnt/messageheaderparser.h>
#include <tnt/httperror.h>
#include <tnt/http.h>
#include <cctype>
#include <cxxtools/log.h>
namespace tnt
{
namespace
{
std::string chartoprint(char ch)
{
const static char hex[] = "0123456789abcdef";
if (std::isprint(ch))
return std::string(1, '\'') + ch + '\'';
else
return std::string("'\\x") + hex[ch >> 4] + hex[ch & 0xf] + '\'';
}
}
log_define("tntnet.messageheader.parser")
#define SET_STATE(new_state) state = &Parser::new_state
bool Messageheader::Parser::state_0(char ch)
{
if (ch >= 33 && ch <= 126 && ch != ':')
{
fieldnamePtr = headerdataPtr;
checkHeaderspace(1);
*headerdataPtr++ = ch;
SET_STATE(state_fieldname);
}
else if (ch == '\n')
return true;
else if (ch == '\r')
SET_STATE(state_cr);
else if (!std::isspace(ch))
{
log_warn("invalid character " << chartoprint(ch));
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_cr(char ch)
{
if (ch != '\n')
{
log_warn("invalid character " << chartoprint(ch) << " in state-cr");
failedFlag = true;
}
return true;
}
bool Messageheader::Parser::state_fieldname(char ch)
{
if (ch == ':') // Field-name:
{
checkHeaderspace(2);
*headerdataPtr++ = ch;
*headerdataPtr++ = '\0';
fieldbodyPtr = headerdataPtr;
SET_STATE(state_fieldbody0);
}
else if (ch >= 33 && ch <= 126)
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
else if (std::isspace(ch))
{
checkHeaderspace(2);
*headerdataPtr++ = ':';
*headerdataPtr++ = '\0';
fieldbodyPtr = headerdataPtr;
SET_STATE(state_fieldnamespace);
}
else
{
log_warn("invalid character " << chartoprint(ch) << " in fieldname");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldnamespace(char ch)
{
if (ch == ':') // "Field-name :"
SET_STATE(state_fieldbody0);
else if (!std::isspace(ch))
{
log_warn("invalid character " << chartoprint(ch) << " in fieldname-space");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldbody0(char ch)
{
if (ch == '\r')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_cr);
}
else if (ch == '\n')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_crlf);
}
else if (!std::isspace(ch))
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
SET_STATE(state_fieldbody);
}
return false;
}
bool Messageheader::Parser::state_fieldbody(char ch)
{
if (ch == '\r')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_cr);
}
else if (ch == '\n')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_crlf);
}
else
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
return false;
}
bool Messageheader::Parser::state_fieldbody_cr(char ch)
{
if (ch == '\n')
SET_STATE(state_fieldbody_crlf);
else
{
log_warn("invalid character " << chartoprint(ch) << " in fieldbody-cr");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldbody_crlf(char ch)
{
if (ch == '\r')
SET_STATE(state_end_cr);
else if (ch == '\n')
{
log_debug("header " << fieldnamePtr << ": " << fieldbodyPtr);
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK:
case END: return true;
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
}
return true;
}
else if (std::isspace(ch))
{
// continuation line
checkHeaderspace(1);
*(headerdataPtr - 1) = '\n';
*headerdataPtr++ = ch;
SET_STATE(state_fieldbody);
}
else if (ch >= 33 && ch <= 126)
{
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK: SET_STATE(state_fieldname);
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
case END: return true;
break;
}
fieldnamePtr = headerdataPtr;
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
return false;
}
bool Messageheader::Parser::state_end_cr(char ch)
{
if (ch == '\n')
{
if (header.onField(fieldnamePtr, fieldbodyPtr) == FAIL)
{
log_warn("invalid header " << fieldnamePtr << ' ' << fieldbodyPtr);
failedFlag = true;
}
*headerdataPtr = '\0';
return true;
}
else
{
log_warn("invalid character " << chartoprint(ch) << " in end-cr");
failedFlag = true;
return true;
}
return false;
}
void Messageheader::Parser::checkHeaderspace(unsigned chars) const
{
if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata))
throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large");
}
void Messageheader::Parser::reset()
{
failedFlag = false;
headerdataPtr = header.rawdata;
SET_STATE(state_0);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_5850_0 |
crossvul-cpp_data_bad_2112_0 | /* Copyright (C) 2006 - 2014 Jan Kundrát <jkt@flaska.net>
This file is part of the Trojita Qt IMAP e-mail client,
http://trojita.flaska.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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "OpenConnectionTask.h"
#include <QTimer>
#include "Common/ConnectionId.h"
#include "Common/InvokeMethod.h"
#include "Imap/Model/ItemRoles.h"
#include "Imap/Model/TaskPresentationModel.h"
#include "Imap/Tasks/EnableTask.h"
#include "Imap/Tasks/IdTask.h"
#include "Streams/SocketFactory.h"
#include "Streams/TrojitaZlibStatus.h"
namespace Imap
{
namespace Mailbox
{
OpenConnectionTask::OpenConnectionTask(Model *model) :
ImapTask(model)
{
// Offline mode shall be checked by the caller who decides to create the connection
Q_ASSERT(model->networkPolicy() != NETWORK_OFFLINE);
parser = new Parser(model, model->m_socketFactory->create(), Common::ConnectionId::next());
ParserState parserState(parser);
connect(parser, SIGNAL(responseReceived(Imap::Parser *)), model, SLOT(responseReceived(Imap::Parser*)), Qt::QueuedConnection);
connect(parser, SIGNAL(connectionStateChanged(Imap::Parser *,Imap::ConnectionState)), model, SLOT(handleSocketStateChanged(Imap::Parser *,Imap::ConnectionState)));
connect(parser, SIGNAL(lineReceived(Imap::Parser *,QByteArray)), model, SLOT(slotParserLineReceived(Imap::Parser *,QByteArray)));
connect(parser, SIGNAL(lineSent(Imap::Parser *,QByteArray)), model, SLOT(slotParserLineSent(Imap::Parser *,QByteArray)));
model->m_parsers[ parser ] = parserState;
model->m_taskModel->slotParserCreated(parser);
markAsActiveTask();
}
OpenConnectionTask::OpenConnectionTask(Model *model, void *dummy):
ImapTask(model)
{
Q_UNUSED(dummy);
}
QString OpenConnectionTask::debugIdentification() const
{
if (parser)
return QString::fromUtf8("OpenConnectionTask: %1").arg(Imap::connectionStateToString(model->accessParser(parser).connState));
else
return QLatin1String("OpenConnectionTask: no parser");
}
void OpenConnectionTask::perform()
{
// nothing should happen here
}
/** @short Decide what to do next based on the received response and the current state of the connection
CONN_STATE_NONE:
CONN_STATE_HOST_LOOKUP:
CONN_STATE_CONNECTING:
- not allowed
CONN_STATE_CONNECTED_PRETLS_PRECAPS:
-> CONN_STATE_AUTHENTICATED iff "* PREAUTH [CAPABILITIES ...]"
- done
-> CONN_STATE_POSTAUTH_PRECAPS iff "* PREAUTH"
- requesting capabilities
-> CONN_STATE_TLS if "* OK [CAPABILITIES ...]"
- calling STARTTLS
-> CONN_STATE_CONNECTED_PRETLS if caps not known
- asking for capabilities
-> CONN_STATE_LOGIN iff capabilities are provided and LOGINDISABLED is not there and configuration doesn't want STARTTLS
- trying to LOGIN.
-> CONN_STATE_LOGOUT if the initial greeting asks us to leave
- fail
CONN_STATE_CONNECTED_PRETLS: checks result of the capability command
-> CONN_STATE_STARTTLS
- calling STARTTLS
-> CONN_STATE_LOGIN
- calling login
-> fail
CONN_STATE_STARTTLS: checks result of STARTTLS command
-> CONN_STATE_ESTABLISHED_PRECAPS
- asking for capabilities
-> fail
CONN_STATE_ESTABLISHED_PRECAPS: checks for the result of capabilities
-> CONN_STATE_LOGIN
-> fail
CONN_STATE_POSTAUTH_PRECAPS: checks result of the capability command
*/
bool OpenConnectionTask::handleStateHelper(const Imap::Responses::State *const resp)
{
if (_dead) {
_failed("Asked to die");
return true;
}
using namespace Imap::Responses;
if (model->accessParser(parser).connState == CONN_STATE_CONNECTED_PRETLS_PRECAPS) {
if (!resp->tag.isEmpty()) {
throw Imap::UnexpectedResponseReceived("Waiting for initial OK/BYE/PREAUTH, but got tagged response instead", *resp);
}
} else if (model->accessParser(parser).connState > CONN_STATE_CONNECTED_PRETLS_PRECAPS) {
if (resp->tag.isEmpty()) {
return false;
}
}
switch (model->accessParser(parser).connState) {
case CONN_STATE_AUTHENTICATED:
case CONN_STATE_SELECTING:
case CONN_STATE_SYNCING:
case CONN_STATE_SELECTED:
case CONN_STATE_FETCHING_PART:
case CONN_STATE_FETCHING_MSG_METADATA:
case CONN_STATE_LOGOUT:
{
QByteArray message = "No response expected by the OpenConnectionTask in state " +
Imap::connectionStateToString(model->accessParser(parser).connState).toUtf8();
// These shall not ever be reached by this code
throw Imap::UnexpectedResponseReceived(message.constData(), *resp);
}
case CONN_STATE_NONE:
case CONN_STATE_HOST_LOOKUP:
case CONN_STATE_CONNECTING:
// Looks like the corresponding stateChanged() signal could be delayed, at least with QProcess-based sockets
case CONN_STATE_CONNECTED_PRETLS_PRECAPS:
// We're connected now -- this is our initial state.
{
switch (resp->kind) {
case PREAUTH:
// Cool, we're already authenticated. Now, let's see if we have to issue CAPABILITY or if we already know that
if (model->accessParser(parser).capabilitiesFresh) {
// We're alsmost done here, apart from compression
if (TROJITA_COMPRESS_DEFLATE && model->accessParser(parser).capabilities.contains(QLatin1String("COMPRESS=DEFLATE"))) {
compressCmd = parser->compressDeflate();
model->changeConnectionState(parser, CONN_STATE_COMPRESS_DEFLATE);
} else {
// really done
model->changeConnectionState(parser, CONN_STATE_AUTHENTICATED);
onComplete();
}
} else {
model->changeConnectionState(parser, CONN_STATE_POSTAUTH_PRECAPS);
capabilityCmd = parser->capability();
}
return true;
case OK:
if (!model->accessParser(parser).capabilitiesFresh) {
model->changeConnectionState(parser, CONN_STATE_CONNECTED_PRETLS);
capabilityCmd = parser->capability();
} else {
startTlsOrLoginNow();
}
return true;
case BYE:
logout(tr("Server has closed the connection"));
return true;
case BAD:
model->changeConnectionState(parser, CONN_STATE_LOGOUT);
// If it was an ALERT, we've already warned the user
if (resp->respCode != ALERT) {
emit model->alertReceived(tr("The server replied with the following BAD response:\n%1").arg(resp->message));
}
logout(tr("Server has greeted us with a BAD response"));
return true;
default:
throw Imap::UnexpectedResponseReceived("Waiting for initial OK/BYE/BAD/PREAUTH, but got this instead", *resp);
}
break;
}
case CONN_STATE_CONNECTED_PRETLS:
// We've asked for capabilities upon the initial interaction
{
bool wasCaps = checkCapabilitiesResult(resp);
if (wasCaps && !_finished) {
startTlsOrLoginNow();
}
return wasCaps;
}
case CONN_STATE_STARTTLS_ISSUED:
{
if (resp->tag == startTlsCmd) {
if (resp->kind == OK) {
model->changeConnectionState(parser, CONN_STATE_STARTTLS_HANDSHAKE);
if (!model->m_startTls) {
// The model was not configured to perform STARTTLS, but we still did that for some reason.
// As suggested by Mike Cardwell on the trojita ML (http://article.gmane.org/gmane.mail.trojita.general/299),
// it makes sense to make this settings permanent, so that a user is not tricked into revealing their
// password when a MITM removes the LOGINDISABLED in future.
EMIT_LATER_NOARG(model, requireStartTlsInFuture);
}
} else {
logout(tr("STARTTLS failed: %1").arg(resp->message));
}
return true;
}
return false;
}
case CONN_STATE_SSL_HANDSHAKE:
case CONN_STATE_STARTTLS_HANDSHAKE:
// nothing should really arrive at this point; the Parser is expected to wait for encryption and only after that
// send the data
Q_ASSERT(false);
return false;
case CONN_STATE_STARTTLS_VERIFYING:
case CONN_STATE_SSL_VERIFYING:
{
// We're waiting for a decision based on a policy, so we do not really expect any network IO at this point
// FIXME: an assert(false) here?
qDebug() << "OpenConnectionTask: ignoring response, we're still waiting for SSL policy decision";
return false;
}
case CONN_STATE_ESTABLISHED_PRECAPS:
// Connection is established and we're waiting for updated capabilities
{
bool wasCaps = checkCapabilitiesResult(resp);
if (wasCaps && !_finished) {
if (model->accessParser(parser).capabilities.contains(QLatin1String("LOGINDISABLED"))) {
logout(tr("Capabilities still contain LOGINDISABLED even after STARTTLS"));
} else {
model->changeConnectionState(parser, CONN_STATE_LOGIN);
askForAuth();
}
}
return wasCaps;
}
case CONN_STATE_LOGIN:
// Check the result of the LOGIN command
{
if (resp->tag == loginCmd) {
loginCmd.clear();
// The LOGIN command is finished
if (resp->kind == OK) {
if (resp->respCode == CAPABILITIES || model->accessParser(parser).capabilitiesFresh) {
// Capabilities are already known
if (TROJITA_COMPRESS_DEFLATE && model->accessParser(parser).capabilities.contains(QLatin1String("COMPRESS=DEFLATE"))) {
compressCmd = parser->compressDeflate();
model->changeConnectionState(parser, CONN_STATE_COMPRESS_DEFLATE);
} else {
model->changeConnectionState(parser, CONN_STATE_AUTHENTICATED);
onComplete();
}
} else {
// Got to ask for the capabilities
model->changeConnectionState(parser, CONN_STATE_POSTAUTH_PRECAPS);
capabilityCmd = parser->capability();
}
} else {
// Login failed
QString message;
switch (resp->respCode) {
case Responses::UNAVAILABLE:
message = tr("Temporary failure because a subsystem is down.");
break;
case Responses::AUTHENTICATIONFAILED:
message = tr("Authentication failed. This often happens due to bad password or wrong user name.");
break;
case Responses::AUTHORIZATIONFAILED:
message = tr("Authentication succeeded in using the authentication identity, "
"but the server cannot or will not allow the authentication "
"identity to act as the requested authorization identity.");
break;
case Responses::EXPIRED:
message = tr("Either authentication succeeded or the server no longer had the "
"necessary data; either way, access is no longer permitted using "
"that passphrase. You should get a new passphrase.");
break;
case Responses::PRIVACYREQUIRED:
message = tr("The operation is not permitted due to a lack of privacy.");
break;
case Responses::CONTACTADMIN:
message = tr("You should contact the system administrator or support desk.");
break;
default:
break;
}
if (message.isEmpty()) {
message = tr("Login failed: %1").arg(resp->message);
} else {
message = tr("%1\n\n%2").arg(message, resp->message);
}
EMIT_LATER(model, authAttemptFailed, Q_ARG(QString, message));
model->m_imapPassword.clear();
model->m_hasImapPassword = false;
if (model->accessParser(parser).connState == CONN_STATE_LOGOUT) {
// The server has closed the conenction
_failed(QLatin1String("Connection closed after a failed login"));
return true;
}
askForAuth();
}
return true;
}
return false;
}
case CONN_STATE_POSTAUTH_PRECAPS:
{
bool wasCaps = checkCapabilitiesResult(resp);
if (wasCaps && !_finished) {
model->changeConnectionState(parser, CONN_STATE_AUTHENTICATED);
onComplete();
}
return wasCaps;
}
case CONN_STATE_COMPRESS_DEFLATE:
if (resp->tag == compressCmd) {
model->changeConnectionState(parser, CONN_STATE_AUTHENTICATED);
onComplete();
return true;
} else {
return false;
}
break;
}
// Required catch-all for OpenSuSE's build service (Tumbleweed, 2012-04-03)
Q_ASSERT(false);
return false;
}
/** @short Either call STARTTLS or go ahead and try to LOGIN */
void OpenConnectionTask::startTlsOrLoginNow()
{
if (model->m_startTls || model->accessParser(parser).capabilities.contains(QLatin1String("LOGINDISABLED"))) {
// Should run STARTTLS later and already have the capabilities
Q_ASSERT(model->accessParser(parser).capabilitiesFresh);
if (!model->accessParser(parser).capabilities.contains(QLatin1String("STARTTLS"))) {
logout(tr("Server does not support STARTTLS"));
} else {
startTlsCmd = parser->startTls();
model->changeConnectionState(parser, CONN_STATE_STARTTLS_ISSUED);
}
} else {
// We're requested to authenticate even without STARTTLS
Q_ASSERT(!model->accessParser(parser).capabilities.contains(QLatin1String("LOGINDISABLED")));
model->changeConnectionState(parser, CONN_STATE_LOGIN);
askForAuth();
}
}
bool OpenConnectionTask::checkCapabilitiesResult(const Responses::State *const resp)
{
if (resp->tag.isEmpty())
return false;
if (resp->tag == capabilityCmd) {
if (!model->accessParser(parser).capabilitiesFresh) {
logout(tr("Server did not provide useful capabilities"));
return true;
}
if (resp->kind != Responses::OK) {
logout(tr("CAPABILITIES command has failed"));
}
return true;
}
return false;
}
void OpenConnectionTask::onComplete()
{
// Optionally issue the ID command
if (model->accessParser(parser).capabilities.contains(QLatin1String("ID"))) {
Imap::Mailbox::ImapTask *task = model->m_taskFactory->createIdTask(model, this);
task->perform();
}
// Optionally enable QRESYNC
if (model->accessParser(parser).capabilities.contains(QLatin1String("QRESYNC")) &&
model->accessParser(parser).capabilities.contains(QLatin1String("ENABLE"))) {
Imap::Mailbox::ImapTask *task = model->m_taskFactory->createEnableTask(model, this,
QList<QByteArray>() << QByteArray("QRESYNC"));
task->perform();
}
// But do terminate this task
_completed();
}
void OpenConnectionTask::logout(const QString &message)
{
_failed(message);
model->setNetworkPolicy(NETWORK_OFFLINE);
}
void OpenConnectionTask::askForAuth()
{
if (model->m_hasImapPassword) {
Q_ASSERT(loginCmd.isEmpty());
loginCmd = parser->login(model->m_imapUser, model->m_imapPassword);
model->accessParser(parser).capabilitiesFresh = false;
} else {
EMIT_LATER_NOARG(model, authRequested);
}
}
void OpenConnectionTask::authCredentialsNowAvailable()
{
if (model->accessParser(parser).connState == CONN_STATE_LOGIN && loginCmd.isEmpty()) {
if (model->m_hasImapPassword) {
loginCmd = parser->login(model->m_imapUser, model->m_imapPassword);
model->accessParser(parser).capabilitiesFresh = false;
} else {
logout(tr("No credentials available"));
}
}
}
QVariant OpenConnectionTask::taskData(const int role) const
{
return role == RoleTaskCompactName ? QVariant(tr("Connecting to mail server")) : QVariant();
}
QList<QSslCertificate> OpenConnectionTask::sslCertificateChain() const
{
return m_sslChain;
}
QList<QSslError> OpenConnectionTask::sslErrors() const
{
return m_sslErrors;
}
void OpenConnectionTask::sslConnectionPolicyDecided(bool ok)
{
switch (model->accessParser(parser).connState) {
case CONN_STATE_SSL_VERIFYING:
if (ok) {
model->changeConnectionState(parser, CONN_STATE_CONNECTED_PRETLS_PRECAPS);
} else {
logout(tr("The security state of the SSL connection got rejected"));
}
break;
case CONN_STATE_STARTTLS_VERIFYING:
if (ok) {
model->changeConnectionState(parser, CONN_STATE_ESTABLISHED_PRECAPS);
model->accessParser(parser).capabilitiesFresh = false;
capabilityCmd = parser->capability();
} else {
logout(tr("The security state of the connection after a STARTTLS operation got rejected"));
}
break;
default:
Q_ASSERT(false);
}
parser->unfreezeAfterEncryption();
}
bool OpenConnectionTask::handleSocketEncryptedResponse(const Responses::SocketEncryptedResponse *const resp)
{
switch (model->accessParser(parser).connState) {
case CONN_STATE_SSL_HANDSHAKE:
model->changeConnectionState(parser, CONN_STATE_SSL_VERIFYING);
m_sslChain = resp->sslChain;
m_sslErrors = resp->sslErrors;
model->processSslErrors(this);
return true;
case CONN_STATE_STARTTLS_HANDSHAKE:
model->changeConnectionState(parser, CONN_STATE_STARTTLS_VERIFYING);
m_sslChain = resp->sslChain;
m_sslErrors = resp->sslErrors;
model->processSslErrors(this);
return true;
default:
qDebug() << model->accessParser(parser).connState;
return false;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_2112_0 |
crossvul-cpp_data_good_5850_0 | /*
* Copyright (C) 2003-2005 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tnt/messageheaderparser.h>
#include <tnt/httperror.h>
#include <tnt/http.h>
#include <cctype>
#include <cxxtools/log.h>
namespace tnt
{
namespace
{
std::string chartoprint(char ch)
{
const static char hex[] = "0123456789abcdef";
if (std::isprint(ch))
return std::string(1, '\'') + ch + '\'';
else
return std::string("'\\x") + hex[ch >> 4] + hex[ch & 0xf] + '\'';
}
}
log_define("tntnet.messageheader.parser")
#define SET_STATE(new_state) state = &Parser::new_state
bool Messageheader::Parser::state_0(char ch)
{
if (ch >= 33 && ch <= 126 && ch != ':')
{
fieldnamePtr = headerdataPtr;
checkHeaderspace(1);
*headerdataPtr++ = ch;
SET_STATE(state_fieldname);
}
else if (ch == '\n')
return true;
else if (ch == '\r')
SET_STATE(state_cr);
else if (!std::isspace(ch))
{
log_warn("invalid character " << chartoprint(ch));
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_cr(char ch)
{
if (ch != '\n')
{
log_warn("invalid character " << chartoprint(ch) << " in state-cr");
failedFlag = true;
}
return true;
}
bool Messageheader::Parser::state_fieldname(char ch)
{
if (ch == ':') // Field-name:
{
checkHeaderspace(2);
*headerdataPtr++ = ch;
*headerdataPtr++ = '\0';
fieldbodyPtr = headerdataPtr;
SET_STATE(state_fieldbody0);
}
else if (ch >= 33 && ch <= 126)
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
else if (std::isspace(ch))
{
checkHeaderspace(2);
*headerdataPtr++ = ':';
*headerdataPtr++ = '\0';
fieldbodyPtr = headerdataPtr;
SET_STATE(state_fieldnamespace);
}
else
{
log_warn("invalid character " << chartoprint(ch) << " in fieldname");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldnamespace(char ch)
{
if (ch == ':') // "Field-name :"
SET_STATE(state_fieldbody0);
else if (!std::isspace(ch))
{
log_warn("invalid character " << chartoprint(ch) << " in fieldname-space");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldbody0(char ch)
{
if (ch == '\r')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_cr);
}
else if (ch == '\n')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_crlf);
}
else if (!std::isspace(ch))
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
SET_STATE(state_fieldbody);
}
return false;
}
bool Messageheader::Parser::state_fieldbody(char ch)
{
if (ch == '\r')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_cr);
}
else if (ch == '\n')
{
checkHeaderspace(1);
*headerdataPtr++ = '\0';
SET_STATE(state_fieldbody_crlf);
}
else
{
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
return false;
}
bool Messageheader::Parser::state_fieldbody_cr(char ch)
{
if (ch == '\n')
SET_STATE(state_fieldbody_crlf);
else
{
log_warn("invalid character " << chartoprint(ch) << " in fieldbody-cr");
failedFlag = true;
return true;
}
return false;
}
bool Messageheader::Parser::state_fieldbody_crlf(char ch)
{
if (ch == '\r')
SET_STATE(state_end_cr);
else if (ch == '\n')
{
log_debug("header " << fieldnamePtr << ": " << fieldbodyPtr);
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK:
case END: return true;
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
}
*headerdataPtr = '\0';
return true;
}
else if (std::isspace(ch))
{
// continuation line
checkHeaderspace(1);
*(headerdataPtr - 1) = '\n';
*headerdataPtr++ = ch;
SET_STATE(state_fieldbody);
}
else if (ch >= 33 && ch <= 126)
{
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK: SET_STATE(state_fieldname);
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
case END: return true;
break;
}
fieldnamePtr = headerdataPtr;
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
return false;
}
bool Messageheader::Parser::state_end_cr(char ch)
{
if (ch == '\n')
{
if (header.onField(fieldnamePtr, fieldbodyPtr) == FAIL)
{
log_warn("invalid header " << fieldnamePtr << ' ' << fieldbodyPtr);
failedFlag = true;
}
*headerdataPtr = '\0';
return true;
}
else
{
log_warn("invalid character " << chartoprint(ch) << " in end-cr");
failedFlag = true;
return true;
}
return false;
}
void Messageheader::Parser::checkHeaderspace(unsigned chars) const
{
if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata))
{
header.rawdata[sizeof(header.rawdata) - 1] = '\0';
throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large");
}
}
void Messageheader::Parser::reset()
{
failedFlag = false;
headerdataPtr = header.rawdata;
SET_STATE(state_0);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_5850_0 |
crossvul-cpp_data_good_5212_1 | /* linenoise.c -- guerrilla line editing library against the idea that a
*
* Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* line editing lib needs to be 20,000 lines of C code.
*
* You can find the latest source code at:
*
* http://github.com/antirez/linenoise
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* References:
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
*
* Todo list:
* - Switch to gets() if $TERM is something we can't support.
* - Filter bogus Ctrl+<char> combinations.
* - Win32 support
*
* Bloat:
* - Completion?
* - History search like Ctrl+r in readline?
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* CHA (Cursor Horizontal Absolute)
* Sequence: ESC [ n G
* Effect: moves cursor to column n (1 based)
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (Cursor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward of n chars
*
* The following are used to clear the screen: ESC [ H ESC [ 2 J
* This is actually composed of two sequences:
*
* cursorhome
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED2 (Clear entire screen)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
*/
#ifdef _WIN32
#include <conio.h>
#include <io.h>
#include <windows.h>
#define strcasecmp _stricmp
#define strdup _strdup
#define isatty _isatty
#define write _write
#define STDIN_FILENO 0
#else /* _WIN32 */
#include <cctype>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <wctype.h>
#endif /* _WIN32 */
#include "linenoise.h"
#include "linenoise_utf8.h"
#include "mk_wcwidth.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::unique_ptr;
using linenoise_utf8::UChar8;
using linenoise_utf8::UChar32;
using linenoise_utf8::copyString8to32;
using linenoise_utf8::copyString32;
using linenoise_utf8::copyString32to8;
using linenoise_utf8::strlen32;
using linenoise_utf8::strncmp32;
using linenoise_utf8::write32;
using linenoise_utf8::Utf8String;
using linenoise_utf8::Utf32String;
struct linenoiseCompletions {
vector<Utf32String> completionStrings;
};
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE 4096
// make control-characters more readable
#define ctrlChar(upperCaseASCII) (upperCaseASCII - 0x40)
/**
* Recompute widths of all characters in a UChar32 buffer
* @param text input buffer of Unicode characters
* @param widths output buffer of character widths
* @param charCount number of characters in buffer
*/
static void recomputeCharacterWidths(const UChar32* text, char* widths, int charCount) {
for (int i = 0; i < charCount; ++i) {
widths[i] = mk_wcwidth(text[i]);
}
}
/**
* Calculate a new screen position given a starting position, screen width and character count
* @param x initial x position (zero-based)
* @param y initial y position (zero-based)
* @param screenColumns screen column count
* @param charCount character positions to advance
* @param xOut returned x position (zero-based)
* @param yOut returned y position (zero-based)
*/
static void calculateScreenPosition(
int x, int y, int screenColumns, int charCount, int& xOut, int& yOut) {
xOut = x;
yOut = y;
int charsRemaining = charCount;
while (charsRemaining > 0) {
int charsThisRow =
(x + charsRemaining < screenColumns) ? charsRemaining : screenColumns - x;
xOut = x + charsThisRow;
yOut = y;
charsRemaining -= charsThisRow;
x = 0;
++y;
}
if (xOut == screenColumns) { // we have to special-case line wrap
xOut = 0;
++yOut;
}
}
/**
* Calculate a column width using mk_wcswidth()
* @param buf32 text to calculate
* @param len length of text to calculate
*/
static int calculateColumnPosition(UChar32* buf32, int len) {
int width = mk_wcswidth(reinterpret_cast<const int*>(buf32), len);
if (width == -1)
return len;
else
return width;
}
static bool isControlChar(UChar32 testChar) {
return (testChar < ' ') || // C0 controls
(testChar >= 0x7F && testChar <= 0x9F); // DEL and C1 controls
}
struct PromptBase { // a convenience struct for grouping prompt info
Utf32String promptText; // our copy of the prompt text, edited
char* promptCharWidths; // character widths from mk_wcwidth()
int promptChars; // chars in promptText
int promptExtraLines; // extra lines (beyond 1) occupied by prompt
int promptIndentation; // column offset to end of prompt
int promptLastLinePosition; // index into promptText where last line begins
int promptPreviousInputLen; // promptChars of previous input line, for clearing
int promptCursorRowOffset; // where the cursor is relative to the start of the prompt
int promptScreenColumns; // width of screen in columns
int promptPreviousLen; // help erasing
int promptErrorCode; // error code (invalid UTF-8) or zero
PromptBase() : promptPreviousInputLen(0) {}
};
struct PromptInfo : public PromptBase {
PromptInfo(const UChar8* textPtr, int columns) {
promptExtraLines = 0;
promptLastLinePosition = 0;
promptPreviousLen = 0;
promptScreenColumns = columns;
Utf32String tempUnicode(textPtr);
// strip control characters from the prompt -- we do allow newline
UChar32* pIn = tempUnicode.get();
UChar32* pOut = pIn;
while (*pIn) {
UChar32 c = *pIn;
if ('\n' == c || !isControlChar(c)) {
*pOut = c;
++pOut;
}
++pIn;
}
*pOut = 0;
promptChars = pOut - tempUnicode.get();
promptText = tempUnicode;
int x = 0;
for (int i = 0; i < promptChars; ++i) {
UChar32 c = promptText[i];
if ('\n' == c) {
x = 0;
++promptExtraLines;
promptLastLinePosition = i + 1;
} else {
++x;
if (x >= promptScreenColumns) {
x = 0;
++promptExtraLines;
promptLastLinePosition = i + 1;
}
}
}
promptIndentation = promptChars - promptLastLinePosition;
promptCursorRowOffset = promptExtraLines;
}
};
// Used with DynamicPrompt (history search)
//
static const Utf32String forwardSearchBasePrompt(reinterpret_cast<const UChar8*>("(i-search)`"));
static const Utf32String reverseSearchBasePrompt(
reinterpret_cast<const UChar8*>("(reverse-i-search)`"));
static const Utf32String endSearchBasePrompt(reinterpret_cast<const UChar8*>("': "));
static Utf32String previousSearchText; // remembered across invocations of linenoise()
// changing prompt for "(reverse-i-search)`text':" etc.
//
struct DynamicPrompt : public PromptBase {
Utf32String searchText; // text we are searching for
char* searchCharWidths; // character widths from mk_wcwidth()
int searchTextLen; // chars in searchText
int direction; // current search direction, 1=forward, -1=reverse
DynamicPrompt(PromptBase& pi, int initialDirection)
: searchTextLen(0), direction(initialDirection) {
promptScreenColumns = pi.promptScreenColumns;
promptCursorRowOffset = 0;
Utf32String emptyString(1);
searchText = emptyString;
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars = promptStartLength + endSearchBasePrompt.length();
promptLastLinePosition =
promptChars; // TODO fix this, we are asssuming that the history prompt won't wrap (!)
promptPreviousLen = promptChars;
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(), sizeof(UChar32) * promptStartLength);
memcpy(&tempUnicode[promptStartLength],
endSearchBasePrompt.get(),
sizeof(UChar32) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
calculateScreenPosition(
0, 0, pi.promptScreenColumns, promptChars, promptIndentation, promptExtraLines);
}
void updateSearchPrompt(void) {
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars = promptStartLength + searchTextLen + endSearchBasePrompt.length();
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(), sizeof(UChar32) * promptStartLength);
memcpy(&tempUnicode[promptStartLength], searchText.get(), sizeof(UChar32) * searchTextLen);
size_t endIndex = promptStartLength + searchTextLen;
memcpy(&tempUnicode[endIndex],
endSearchBasePrompt.get(),
sizeof(UChar32) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
}
void updateSearchText(const UChar32* textPtr) {
Utf32String tempUnicode(textPtr);
searchTextLen = tempUnicode.chars();
searchText = tempUnicode;
updateSearchPrompt();
}
};
class KillRing {
static const int capacity = 10;
int size;
int index;
char indexToSlot[10];
vector<Utf32String> theRing;
public:
enum action { actionOther, actionKill, actionYank };
action lastAction;
size_t lastYankSize;
KillRing() : size(0), index(0), lastAction(actionOther) {
theRing.reserve(capacity);
}
void kill(const UChar32* text, int textLen, bool forward) {
if (textLen == 0) {
return;
}
Utf32String killedText(text, textLen);
if (lastAction == actionKill && size > 0) {
int slot = indexToSlot[0];
int currentLen = theRing[slot].length();
int resultLen = currentLen + textLen;
Utf32String temp(resultLen + 1);
if (forward) {
memcpy(temp.get(), theRing[slot].get(), currentLen * sizeof(UChar32));
memcpy(&temp[currentLen], killedText.get(), textLen * sizeof(UChar32));
} else {
memcpy(temp.get(), killedText.get(), textLen * sizeof(UChar32));
memcpy(&temp[textLen], theRing[slot].get(), currentLen * sizeof(UChar32));
}
temp[resultLen] = 0;
temp.initFromBuffer();
theRing[slot] = temp;
} else {
if (size < capacity) {
if (size > 0) {
memmove(&indexToSlot[1], &indexToSlot[0], size);
}
indexToSlot[0] = size;
size++;
theRing.push_back(killedText);
} else {
int slot = indexToSlot[capacity - 1];
theRing[slot] = killedText;
memmove(&indexToSlot[1], &indexToSlot[0], capacity - 1);
indexToSlot[0] = slot;
}
index = 0;
}
}
Utf32String* yank() {
return (size > 0) ? &theRing[indexToSlot[index]] : 0;
}
Utf32String* yankPop() {
if (size == 0) {
return 0;
}
++index;
if (index == size) {
index = 0;
}
return &theRing[indexToSlot[index]];
}
};
class InputBuffer {
UChar32* buf32; // input buffer
char* charWidths; // character widths from mk_wcwidth()
int buflen; // buffer size in characters
int len; // length of text in input buffer
int pos; // character position in buffer ( 0 <= pos <= len )
void clearScreen(PromptBase& pi);
int incrementalHistorySearch(PromptBase& pi, int startChar);
int completeLine(PromptBase& pi);
void refreshLine(PromptBase& pi);
public:
InputBuffer(UChar32* buffer, char* widthArray, int bufferLen)
: buf32(buffer), charWidths(widthArray), buflen(bufferLen - 1), len(0), pos(0) {
buf32[0] = 0;
}
void preloadBuffer(const UChar8* preloadText) {
size_t ucharCount;
int errorCode;
copyString8to32(buf32, preloadText, buflen + 1, ucharCount, errorCode);
recomputeCharacterWidths(buf32, charWidths, ucharCount);
len = ucharCount;
pos = ucharCount;
}
int getInputLine(PromptBase& pi);
int length(void) const {
return len;
}
};
// Special codes for keyboard input:
//
// Between Windows and the various Linux "terminal" programs, there is some
// pretty diverse behavior in the "scan codes" and escape sequences we are
// presented with. So ... we'll translate them all into our own pidgin
// pseudocode, trying to stay out of the way of UTF-8 and international
// characters. Here's the general plan.
//
// "User input keystrokes" (key chords, whatever) will be encoded as a single value.
// The low 21 bits are reserved for Unicode characters. Popular function-type keys
// get their own codes in the range 0x10200000 to (if needed) 0x1FE00000, currently
// just arrow keys, Home, End and Delete. Keypresses with Ctrl get ORed with
// 0x20000000, with Alt get ORed with 0x40000000. So, Ctrl+Alt+Home is encoded
// as 0x20000000 + 0x40000000 + 0x10A00000 == 0x70A00000. To keep things complicated,
// the Alt key is equivalent to prefixing the keystroke with ESC, so ESC followed by
// D is treated the same as Alt + D ... we'll just use Emacs terminology and call
// this "Meta". So, we will encode both ESC followed by D and Alt held down while D
// is pressed the same, as Meta-D, encoded as 0x40000064.
//
// Here are the definitions of our component constants:
//
// Maximum unsigned 32-bit value = 0xFFFFFFFF; // For reference, max 32-bit value
// Highest allocated Unicode char = 0x001FFFFF; // For reference, max Unicode value
static const int META = 0x40000000; // Meta key combination
static const int CTRL = 0x20000000; // Ctrl key combination
static const int SPECIAL_KEY = 0x10000000; // Common bit for all special keys
static const int UP_ARROW_KEY = 0x10200000; // Special keys
static const int DOWN_ARROW_KEY = 0x10400000;
static const int RIGHT_ARROW_KEY = 0x10600000;
static const int LEFT_ARROW_KEY = 0x10800000;
static const int HOME_KEY = 0x10A00000;
static const int END_KEY = 0x10C00000;
static const int DELETE_KEY = 0x10E00000;
static const int PAGE_UP_KEY = 0x11000000;
static const int PAGE_DOWN_KEY = 0x11200000;
static const char* unsupported_term[] = {"dumb", "cons25", "emacs", NULL};
static linenoiseCompletionCallback* completionCallback = NULL;
#ifdef _WIN32
static HANDLE console_in, console_out;
static DWORD oldMode;
static WORD oldDisplayAttribute;
#else
static struct termios orig_termios; /* in order to restore at exit */
#endif
static KillRing killRing;
static int rawmode = 0; /* for atexit() function to check if restore is needed*/
static int atexit_registered = 0; /* register atexit just 1 time */
static int historyMaxLen = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int historyLen = 0;
static int historyIndex = 0;
static UChar8** history = NULL;
// used to emulate Windows command prompt on down-arrow after a recall
// we use -2 as our "not set" value because we add 1 to the previous index on down-arrow,
// and zero is a valid index (so -1 is a valid "previous index")
static int historyPreviousIndex = -2;
static bool historyRecallMostRecent = false;
static void linenoiseAtExit(void);
static bool isUnsupportedTerm(void) {
char* term = getenv("TERM");
if (term == NULL)
return false;
for (int j = 0; unsupported_term[j]; ++j)
if (!strcasecmp(term, unsupported_term[j])) {
return true;
}
return false;
}
static void beep() {
fprintf(stderr, "\x7"); // ctrl-G == bell/beep
fflush(stderr);
}
void linenoiseHistoryFree(void) {
if (history) {
for (int j = 0; j < historyLen; ++j)
free(history[j]);
historyLen = 0;
free(history);
history = 0;
}
}
static int enableRawMode(void) {
#ifdef _WIN32
if (!console_in) {
console_in = GetStdHandle(STD_INPUT_HANDLE);
console_out = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(console_in, &oldMode);
SetConsoleMode(console_in,
oldMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT));
}
return 0;
#else
struct termios raw;
if (!isatty(0))
goto fatal;
if (!atexit_registered) {
atexit(linenoiseAtExit);
atexit_registered = 1;
}
if (tcgetattr(0, &orig_termios) == -1)
goto fatal;
raw = orig_termios; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
// this is wrong, we don't want raw output, it turns newlines into straight linefeeds
// raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - echoing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
if (tcsetattr(0, TCSADRAIN, &raw) < 0)
goto fatal;
rawmode = 1;
return 0;
fatal:
errno = ENOTTY;
return -1;
#endif
}
static void disableRawMode(void) {
#ifdef _WIN32
SetConsoleMode(console_in, oldMode);
console_in = 0;
console_out = 0;
#else
if (rawmode && tcsetattr(0, TCSADRAIN, &orig_termios) != -1)
rawmode = 0;
#endif
}
// At exit we'll try to fix the terminal to the initial conditions
static void linenoiseAtExit(void) {
disableRawMode();
}
static int getScreenColumns(void) {
int cols;
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &inf);
cols = inf.dwSize.X;
#else
struct winsize ws;
cols = (ioctl(1, TIOCGWINSZ, &ws) == -1) ? 80 : ws.ws_col;
#endif
// cols is 0 in certain circumstances like inside debugger, which creates further issues
return (cols > 0) ? cols : 80;
}
static int getScreenRows(void) {
int rows;
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &inf);
rows = 1 + inf.srWindow.Bottom - inf.srWindow.Top;
#else
struct winsize ws;
rows = (ioctl(1, TIOCGWINSZ, &ws) == -1) ? 24 : ws.ws_row;
#endif
return (rows > 0) ? rows : 24;
}
static void setDisplayAttribute(bool enhancedDisplay) {
#ifdef _WIN32
if (enhancedDisplay) {
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
oldDisplayAttribute = inf.wAttributes;
BYTE oldLowByte = oldDisplayAttribute & 0xFF;
BYTE newLowByte;
switch (oldLowByte) {
case 0x07:
// newLowByte = FOREGROUND_BLUE | FOREGROUND_INTENSITY; // too dim
// newLowByte = FOREGROUND_BLUE; // even dimmer
newLowByte =
FOREGROUND_BLUE | FOREGROUND_GREEN; // most similar to xterm appearance
break;
case 0x70:
newLowByte = BACKGROUND_BLUE | BACKGROUND_INTENSITY;
break;
default:
newLowByte = oldLowByte ^ 0xFF; // default to inverse video
break;
}
inf.wAttributes = (inf.wAttributes & 0xFF00) | newLowByte;
SetConsoleTextAttribute(console_out, inf.wAttributes);
} else {
SetConsoleTextAttribute(console_out, oldDisplayAttribute);
}
#else
if (enhancedDisplay) {
if (write(1, "\x1b[1;34m", 7) == -1)
return; /* bright blue (visible with both B&W bg) */
} else {
if (write(1, "\x1b[0m", 4) == -1)
return; /* reset */
}
#endif
}
/**
* Display the dynamic incremental search prompt and the current user input line.
* @param pi PromptBase struct holding information about the prompt and our screen position
* @param buf32 input buffer to be displayed
* @param len count of characters in the buffer
* @param pos current cursor position within the buffer (0 <= pos <= len)
*/
static void dynamicRefresh(PromptBase& pi, UChar32* buf32, int len, int pos) {
// calculate the position of the end of the prompt
int xEndOfPrompt, yEndOfPrompt;
calculateScreenPosition(
0, 0, pi.promptScreenColumns, pi.promptChars, xEndOfPrompt, yEndOfPrompt);
pi.promptIndentation = xEndOfPrompt;
// calculate the position of the end of the input line
int xEndOfInput, yEndOfInput;
calculateScreenPosition(xEndOfPrompt,
yEndOfPrompt,
pi.promptScreenColumns,
calculateColumnPosition(buf32, len),
xEndOfInput,
yEndOfInput);
// calculate the desired position of the cursor
int xCursorPos, yCursorPos;
calculateScreenPosition(xEndOfPrompt,
yEndOfPrompt,
pi.promptScreenColumns,
calculateColumnPosition(buf32, pos),
xCursorPos,
yCursorPos);
#ifdef _WIN32
// position at the start of the prompt, clear to end of previous input
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = 0;
inf.dwCursorPosition.Y -= pi.promptCursorRowOffset /*- pi.promptExtraLines*/;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
DWORD count;
FillConsoleOutputCharacterA(console_out,
' ',
pi.promptPreviousLen + pi.promptPreviousInputLen,
inf.dwCursorPosition,
&count);
pi.promptPreviousLen = pi.promptIndentation;
pi.promptPreviousInputLen = len;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
// display the input line
if (write32(1, buf32, len) == -1)
return;
// position the cursor
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = xCursorPos; // 0-based on Win32
inf.dwCursorPosition.Y -= yEndOfInput - yCursorPos;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
#else // _WIN32
char seq[64];
int cursorRowMovement = pi.promptCursorRowOffset - pi.promptExtraLines;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position at the start of the prompt, clear to end of screen
snprintf(seq, sizeof seq, "\x1b[1G\x1b[J"); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
// display the input line
if (write32(1, buf32, len) == -1)
return;
// we have to generate our own newline on line wrap
if (xEndOfInput == 0 && yEndOfInput > 0)
if (write(1, "\n", 1) == -1)
return;
// position the cursor
cursorRowMovement = yEndOfInput - yCursorPos;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position the cursor within the line
snprintf(seq, sizeof seq, "\x1b[%dG", xCursorPos + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines + yCursorPos; // remember row for next pass
}
/**
* Refresh the user's input line: the prompt is already onscreen and is not redrawn here
* @param pi PromptBase struct holding information about the prompt and our screen position
*/
void InputBuffer::refreshLine(PromptBase& pi) {
// check for a matching brace/bracket/paren, remember its position if found
int highlight = -1;
if (pos < len) {
/* this scans for a brace matching buf32[pos] to highlight */
int scanDirection = 0;
if (strchr("}])", buf32[pos]))
scanDirection = -1; /* backwards */
else if (strchr("{[(", buf32[pos]))
scanDirection = 1; /* forwards */
if (scanDirection) {
int unmatched = scanDirection;
for (int i = pos + scanDirection; i >= 0 && i < len; i += scanDirection) {
/* TODO: the right thing when inside a string */
if (strchr("}])", buf32[i]))
--unmatched;
else if (strchr("{[(", buf32[i]))
++unmatched;
if (unmatched == 0) {
highlight = i;
break;
}
}
}
}
// calculate the position of the end of the input line
int xEndOfInput, yEndOfInput;
calculateScreenPosition(pi.promptIndentation,
0,
pi.promptScreenColumns,
calculateColumnPosition(buf32, len),
xEndOfInput,
yEndOfInput);
// calculate the desired position of the cursor
int xCursorPos, yCursorPos;
calculateScreenPosition(pi.promptIndentation,
0,
pi.promptScreenColumns,
calculateColumnPosition(buf32, pos),
xCursorPos,
yCursorPos);
#ifdef _WIN32
// position at the end of the prompt, clear to end of previous input
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = pi.promptIndentation; // 0-based on Win32
inf.dwCursorPosition.Y -= pi.promptCursorRowOffset - pi.promptExtraLines;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
DWORD count;
if (len < pi.promptPreviousInputLen)
FillConsoleOutputCharacterA(
console_out, ' ', pi.promptPreviousInputLen, inf.dwCursorPosition, &count);
pi.promptPreviousInputLen = len;
// display the input line
if (highlight == -1) {
if (write32(1, buf32, len) == -1)
return;
} else {
if (write32(1, buf32, highlight) == -1)
return;
setDisplayAttribute(true); /* bright blue (visible with both B&W bg) */
if (write32(1, &buf32[highlight], 1) == -1)
return;
setDisplayAttribute(false);
if (write32(1, buf32 + highlight + 1, len - highlight - 1) == -1)
return;
}
// position the cursor
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = xCursorPos; // 0-based on Win32
inf.dwCursorPosition.Y -= yEndOfInput - yCursorPos;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
#else // _WIN32
char seq[64];
int cursorRowMovement = pi.promptCursorRowOffset - pi.promptExtraLines;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position at the end of the prompt, clear to end of screen
snprintf(seq, sizeof seq, "\x1b[%dG\x1b[J", pi.promptIndentation + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
if (highlight == -1) { // write unhighlighted text
if (write32(1, buf32, len) == -1)
return;
} else { // highlight the matching brace/bracket/parenthesis
if (write32(1, buf32, highlight) == -1)
return;
setDisplayAttribute(true);
if (write32(1, &buf32[highlight], 1) == -1)
return;
setDisplayAttribute(false);
if (write32(1, buf32 + highlight + 1, len - highlight - 1) == -1)
return;
}
// we have to generate our own newline on line wrap
if (xEndOfInput == 0 && yEndOfInput > 0)
if (write(1, "\n", 1) == -1)
return;
// position the cursor
cursorRowMovement = yEndOfInput - yCursorPos;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position the cursor within the line
snprintf(seq, sizeof seq, "\x1b[%dG", xCursorPos + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines + yCursorPos; // remember row for next pass
}
#ifndef _WIN32
/**
* Read a UTF-8 sequence from the non-Windows keyboard and return the Unicode (UChar32) character it
* encodes
*
* @return UChar32 Unicode character
*/
static UChar32 readUnicodeCharacter(void) {
static UChar8 utf8String[5];
static size_t utf8Count = 0;
while (true) {
UChar8 c;
if (read(0, &c, 1) <= 0)
return 0;
if (c <= 0x7F) { // short circuit ASCII
utf8Count = 0;
return c;
} else if (utf8Count < sizeof(utf8String) - 1) {
utf8String[utf8Count++] = c;
utf8String[utf8Count] = 0;
UChar32 unicodeChar[2];
size_t ucharCount;
int errorCode;
copyString8to32(unicodeChar, utf8String, 2, ucharCount, errorCode);
if (ucharCount && errorCode == 0) {
utf8Count = 0;
return unicodeChar[0];
}
} else {
utf8Count = 0; // this shouldn't happen: got four bytes but no UTF-8 character
}
}
}
namespace EscapeSequenceProcessing { // move these out of global namespace
// This chunk of code does parsing of the escape sequences sent by various Linux terminals.
//
// It handles arrow keys, Home, End and Delete keys by interpreting the sequences sent by
// gnome terminal, xterm, rxvt, konsole, aterm and yakuake including the Alt and Ctrl key
// combinations that are understood by linenoise.
//
// The parsing uses tables, a bunch of intermediate dispatch routines and a doDispatch
// loop that reads the tables and sends control to "deeper" routines to continue the
// parsing. The starting call to doDispatch( c, initialDispatch ) will eventually return
// either a character (with optional CTRL and META bits set), or -1 if parsing fails, or
// zero if an attempt to read from the keyboard fails.
//
// This is rather sloppy escape sequence processing, since we're not paying attention to what the
// actual TERM is set to and are processing all key sequences for all terminals, but it works with
// the most common keystrokes on the most common terminals. It's intricate, but the nested 'if'
// statements required to do it directly would be worse. This way has the advantage of allowing
// changes and extensions without having to touch a lot of code.
// This is a typedef for the routine called by doDispatch(). It takes the current character
// as input, does any required processing including reading more characters and calling other
// dispatch routines, then eventually returns the final (possibly extended or special) character.
//
typedef UChar32 (*CharacterDispatchRoutine)(UChar32);
// This structure is used by doDispatch() to hold a list of characters to test for and
// a list of routines to call if the character matches. The dispatch routine list is one
// longer than the character list; the final entry is used if no character matches.
//
struct CharacterDispatch {
unsigned int len; // length of the chars list
const char* chars; // chars to test
CharacterDispatchRoutine* dispatch; // array of routines to call
};
// This dispatch routine is given a dispatch table and then farms work out to routines
// listed in the table based on the character it is called with. The dispatch routines can
// read more input characters to decide what should eventually be returned. Eventually,
// a called routine returns either a character or -1 to indicate parsing failure.
//
static UChar32 doDispatch(UChar32 c, CharacterDispatch& dispatchTable) {
for (unsigned int i = 0; i < dispatchTable.len; ++i) {
if (static_cast<unsigned char>(dispatchTable.chars[i]) == c) {
return dispatchTable.dispatch[i](c);
}
}
return dispatchTable.dispatch[dispatchTable.len](c);
}
static UChar32 thisKeyMetaCtrl = 0; // holds pre-set Meta and/or Ctrl modifiers
// Final dispatch routines -- return something
//
static UChar32 normalKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | c;
}
static UChar32 upArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | UP_ARROW_KEY;
}
static UChar32 downArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | DOWN_ARROW_KEY;
}
static UChar32 rightArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | RIGHT_ARROW_KEY;
}
static UChar32 leftArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | LEFT_ARROW_KEY;
}
static UChar32 homeKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | HOME_KEY;
}
static UChar32 endKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | END_KEY;
}
static UChar32 pageUpKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | PAGE_UP_KEY;
}
static UChar32 pageDownKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | PAGE_DOWN_KEY;
}
static UChar32 deleteCharRoutine(UChar32 c) {
return thisKeyMetaCtrl | ctrlChar('H');
} // key labeled Backspace
static UChar32 deleteKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | DELETE_KEY;
} // key labeled Delete
static UChar32 ctrlUpArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | UP_ARROW_KEY;
}
static UChar32 ctrlDownArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | DOWN_ARROW_KEY;
}
static UChar32 ctrlRightArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | RIGHT_ARROW_KEY;
}
static UChar32 ctrlLeftArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | LEFT_ARROW_KEY;
}
static UChar32 escFailureRoutine(UChar32 c) {
beep();
return -1;
}
// Handle ESC [ 1 ; 3 (or 5) <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket1Semicolon3or5Routines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket1Semicolon3or5Dispatch = {
4, "ABCD", escLeftBracket1Semicolon3or5Routines};
// Handle ESC [ 1 ; <more stuff> escape sequences
//
static UChar32 escLeftBracket1Semicolon3Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
thisKeyMetaCtrl |= META;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static UChar32 escLeftBracket1Semicolon5Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
thisKeyMetaCtrl |= CTRL;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static CharacterDispatchRoutine escLeftBracket1SemicolonRoutines[] = {
escLeftBracket1Semicolon3Routine, escLeftBracket1Semicolon5Routine, escFailureRoutine};
static CharacterDispatch escLeftBracket1SemicolonDispatch = {
2, "35", escLeftBracket1SemicolonRoutines};
// Handle ESC [ 1 <more stuff> escape sequences
//
static UChar32 escLeftBracket1SemicolonRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket1SemicolonDispatch);
}
static CharacterDispatchRoutine escLeftBracket1Routines[] = {
homeKeyRoutine, escLeftBracket1SemicolonRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Dispatch = {2, "~;", escLeftBracket1Routines};
// Handle ESC [ 3 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket3Routines[] = {deleteKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket3Dispatch = {1, "~", escLeftBracket3Routines};
// Handle ESC [ 4 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket4Routines[] = {endKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket4Dispatch = {1, "~", escLeftBracket4Routines};
// Handle ESC [ 5 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket5Routines[] = {pageUpKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket5Dispatch = {1, "~", escLeftBracket5Routines};
// Handle ESC [ 6 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket6Routines[] = {pageDownKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket6Dispatch = {1, "~", escLeftBracket6Routines};
// Handle ESC [ 7 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket7Routines[] = {homeKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket7Dispatch = {1, "~", escLeftBracket7Routines};
// Handle ESC [ 8 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket8Routines[] = {endKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket8Dispatch = {1, "~", escLeftBracket8Routines};
// Handle ESC [ <digit> escape sequences
//
static UChar32 escLeftBracket0Routine(UChar32 c) {
return escFailureRoutine(c);
}
static UChar32 escLeftBracket1Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket1Dispatch);
}
static UChar32 escLeftBracket2Routine(UChar32 c) {
return escFailureRoutine(c); // Insert key, unused
}
static UChar32 escLeftBracket3Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket3Dispatch);
}
static UChar32 escLeftBracket4Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket4Dispatch);
}
static UChar32 escLeftBracket5Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket5Dispatch);
}
static UChar32 escLeftBracket6Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket6Dispatch);
}
static UChar32 escLeftBracket7Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket7Dispatch);
}
static UChar32 escLeftBracket8Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket8Dispatch);
}
static UChar32 escLeftBracket9Routine(UChar32 c) {
return escFailureRoutine(c);
}
// Handle ESC [ <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracketRoutines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
homeKeyRoutine,
endKeyRoutine,
escLeftBracket0Routine,
escLeftBracket1Routine,
escLeftBracket2Routine,
escLeftBracket3Routine,
escLeftBracket4Routine,
escLeftBracket5Routine,
escLeftBracket6Routine,
escLeftBracket7Routine,
escLeftBracket8Routine,
escLeftBracket9Routine,
escFailureRoutine};
static CharacterDispatch escLeftBracketDispatch = {16, "ABCDHF0123456789", escLeftBracketRoutines};
// Handle ESC O <char> escape sequences
//
static CharacterDispatchRoutine escORoutines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
homeKeyRoutine,
endKeyRoutine,
ctrlUpArrowKeyRoutine,
ctrlDownArrowKeyRoutine,
ctrlRightArrowKeyRoutine,
ctrlLeftArrowKeyRoutine,
escFailureRoutine};
static CharacterDispatch escODispatch = {10, "ABCDHFabcd", escORoutines};
// Initial ESC dispatch -- could be a Meta prefix or the start of an escape sequence
//
static UChar32 escLeftBracketRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracketDispatch);
}
static UChar32 escORoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escODispatch);
}
static UChar32 setMetaRoutine(UChar32 c); // need forward reference
static CharacterDispatchRoutine escRoutines[] = {
escLeftBracketRoutine, escORoutine, setMetaRoutine};
static CharacterDispatch escDispatch = {2, "[O", escRoutines};
// Initial dispatch -- we are not in the middle of anything yet
//
static UChar32 escRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escDispatch);
}
static CharacterDispatchRoutine initialRoutines[] = {
escRoutine, deleteCharRoutine, normalKeyRoutine};
static CharacterDispatch initialDispatch = {2, "\x1B\x7F", initialRoutines};
// Special handling for the ESC key because it does double duty
//
static UChar32 setMetaRoutine(UChar32 c) {
thisKeyMetaCtrl = META;
if (c == 0x1B) { // another ESC, stay in ESC processing mode
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escDispatch);
}
return doDispatch(c, initialDispatch);
}
} // namespace EscapeSequenceProcessing // move these out of global namespace
#endif // #ifndef _WIN32
// linenoiseReadChar -- read a keystroke or keychord from the keyboard, and translate it
// into an encoded "keystroke". When convenient, extended keys are translated into their
// simpler Emacs keystrokes, so an unmodified "left arrow" becomes Ctrl-B.
//
// A return value of zero means "no input available", and a return value of -1 means "invalid key".
//
static UChar32 linenoiseReadChar(void) {
#ifdef _WIN32
INPUT_RECORD rec;
DWORD count;
int modifierKeys = 0;
bool escSeen = false;
while (true) {
ReadConsoleInputW(console_in, &rec, 1, &count);
#if 0 // helper for debugging keystrokes, display info in the debug "Output" window in the debugger
{
if ( rec.EventType == KEY_EVENT ) {
//if ( rec.Event.KeyEvent.uChar.UnicodeChar ) {
char buf[1024];
sprintf(
buf,
"Unicode character 0x%04X, repeat count %d, virtual keycode 0x%04X, "
"virtual scancode 0x%04X, key %s%s%s%s%s\n",
rec.Event.KeyEvent.uChar.UnicodeChar,
rec.Event.KeyEvent.wRepeatCount,
rec.Event.KeyEvent.wVirtualKeyCode,
rec.Event.KeyEvent.wVirtualScanCode,
rec.Event.KeyEvent.bKeyDown ? "down" : "up",
(rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) ?
" L-Ctrl" : "",
(rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED) ?
" R-Ctrl" : "",
(rec.Event.KeyEvent.dwControlKeyState & LEFT_ALT_PRESSED) ?
" L-Alt" : "",
(rec.Event.KeyEvent.dwControlKeyState & RIGHT_ALT_PRESSED) ?
" R-Alt" : ""
);
OutputDebugStringA( buf );
//}
}
}
#endif
if (rec.EventType != KEY_EVENT) {
continue;
}
// Windows provides for entry of characters that are not on your keyboard by sending the
// Unicode characters as a "key up" with virtual keycode 0x12 (VK_MENU == Alt key) ...
// accept these characters, otherwise only process characters on "key down"
if (!rec.Event.KeyEvent.bKeyDown && rec.Event.KeyEvent.wVirtualKeyCode != VK_MENU) {
continue;
}
modifierKeys = 0;
// AltGr is encoded as ( LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED ), so don't treat this
// combination as either CTRL or META we just turn off those two bits, so it is still
// possible to combine CTRL and/or META with an AltGr key by using right-Ctrl and/or
// left-Alt
if ((rec.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED)) ==
(LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED)) {
rec.Event.KeyEvent.dwControlKeyState &= ~(LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED);
}
if (rec.Event.KeyEvent.dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) {
modifierKeys |= CTRL;
}
if (rec.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) {
modifierKeys |= META;
}
if (escSeen) {
modifierKeys |= META;
}
if (rec.Event.KeyEvent.uChar.UnicodeChar == 0) {
switch (rec.Event.KeyEvent.wVirtualKeyCode) {
case VK_LEFT:
return modifierKeys | LEFT_ARROW_KEY;
case VK_RIGHT:
return modifierKeys | RIGHT_ARROW_KEY;
case VK_UP:
return modifierKeys | UP_ARROW_KEY;
case VK_DOWN:
return modifierKeys | DOWN_ARROW_KEY;
case VK_DELETE:
return modifierKeys | DELETE_KEY;
case VK_HOME:
return modifierKeys | HOME_KEY;
case VK_END:
return modifierKeys | END_KEY;
case VK_PRIOR:
return modifierKeys | PAGE_UP_KEY;
case VK_NEXT:
return modifierKeys | PAGE_DOWN_KEY;
default:
continue; // in raw mode, ReadConsoleInput shows shift, ctrl ...
} // ... ignore them
} else if (rec.Event.KeyEvent.uChar.UnicodeChar ==
ctrlChar('[')) { // ESC, set flag for later
escSeen = true;
continue;
} else {
// we got a real character, return it
return modifierKeys | rec.Event.KeyEvent.uChar.UnicodeChar;
}
}
#else
UChar32 c;
c = readUnicodeCharacter();
if (c == 0)
return 0;
// If _DEBUG_LINUX_KEYBOARD is set, then ctrl-^ puts us into a keyboard debugging mode
// where we print out decimal and decoded values for whatever the "terminal" program
// gives us on different keystrokes. Hit ctrl-C to exit this mode.
//
#define _DEBUG_LINUX_KEYBOARD
#if defined(_DEBUG_LINUX_KEYBOARD)
if (c == ctrlChar('^')) { // ctrl-^, special debug mode, prints all keys hit, ctrl-C to get out
printf("\nEntering keyboard debugging mode (on ctrl-^), press ctrl-C to exit this mode\n");
while (true) {
unsigned char keys[10];
int ret = read(0, keys, 10);
if (ret <= 0) {
printf("\nret: %d\n", ret);
}
for (int i = 0; i < ret; ++i) {
UChar32 key = static_cast<UChar32>(keys[i]);
char* friendlyTextPtr;
char friendlyTextBuf[10];
const char* prefixText = (key < 0x80) ? "" : "0x80+";
UChar32 keyCopy = (key < 0x80) ? key : key - 0x80;
if (keyCopy >= '!' && keyCopy <= '~') { // printable
friendlyTextBuf[0] = '\'';
friendlyTextBuf[1] = keyCopy;
friendlyTextBuf[2] = '\'';
friendlyTextBuf[3] = 0;
friendlyTextPtr = friendlyTextBuf;
} else if (keyCopy == ' ') {
friendlyTextPtr = const_cast<char*>("space");
} else if (keyCopy == 27) {
friendlyTextPtr = const_cast<char*>("ESC");
} else if (keyCopy == 0) {
friendlyTextPtr = const_cast<char*>("NUL");
} else if (keyCopy == 127) {
friendlyTextPtr = const_cast<char*>("DEL");
} else {
friendlyTextBuf[0] = '^';
friendlyTextBuf[1] = keyCopy + 0x40;
friendlyTextBuf[2] = 0;
friendlyTextPtr = friendlyTextBuf;
}
printf("%d x%02X (%s%s) ", key, key, prefixText, friendlyTextPtr);
}
printf("\x1b[1G\n"); // go to first column of new line
// drop out of this loop on ctrl-C
if (keys[0] == ctrlChar('C')) {
printf("Leaving keyboard debugging mode (on ctrl-C)\n");
fflush(stdout);
return -2;
}
}
}
#endif // _DEBUG_LINUX_KEYBOARD
EscapeSequenceProcessing::thisKeyMetaCtrl = 0; // no modifiers yet at initialDispatch
return EscapeSequenceProcessing::doDispatch(c, EscapeSequenceProcessing::initialDispatch);
#endif // #_WIN32
}
/**
* Free memory used in a recent command completion session
*
* @param lc pointer to a linenoiseCompletions struct
*/
static void freeCompletions(linenoiseCompletions* lc) {
lc->completionStrings.clear();
}
/**
* convert {CTRL + 'A'}, {CTRL + 'a'} and {CTRL + ctrlChar( 'A' )} into ctrlChar( 'A' )
* leave META alone
*
* @param c character to clean up
* @return cleaned-up character
*/
static int cleanupCtrl(int c) {
if (c & CTRL) {
int d = c & 0x1FF;
if (d >= 'a' && d <= 'z') {
c = (c + ('a' - ctrlChar('A'))) & ~CTRL;
}
if (d >= 'A' && d <= 'Z') {
c = (c + ('A' - ctrlChar('A'))) & ~CTRL;
}
if (d >= ctrlChar('A') && d <= ctrlChar('Z')) {
c = c & ~CTRL;
}
}
return c;
}
// break characters that may precede items to be completed
static const char breakChars[] = " =+-/\\*?\"'`&<>;|@{([])}";
// maximum number of completions to display without asking
static const size_t completionCountCutoff = 100;
/**
* Handle command completion, using a completionCallback() routine to provide possible substitutions
* This routine handles the mechanics of updating the user's input buffer with possible replacement
* of text as the user selects a proposed completion string, or cancels the completion attempt.
* @param pi PromptBase struct holding information about the prompt and our screen position
*/
int InputBuffer::completeLine(PromptBase& pi) {
linenoiseCompletions lc;
char c = 0;
// completionCallback() expects a parsable entity, so find the previous break character and
// extract a copy to parse. we also handle the case where tab is hit while not at end-of-line.
int startIndex = pos;
while (--startIndex >= 0) {
if (strchr(breakChars, buf32[startIndex])) {
break;
}
}
++startIndex;
int itemLength = pos - startIndex;
Utf32String unicodeCopy(&buf32[startIndex], itemLength);
Utf8String parseItem(unicodeCopy);
// get a list of completions
completionCallback(reinterpret_cast<char*>(parseItem.get()), &lc);
// if no completions, we are done
if (lc.completionStrings.size() == 0) {
beep();
freeCompletions(&lc);
return 0;
}
// at least one completion
int longestCommonPrefix = 0;
int displayLength = 0;
if (lc.completionStrings.size() == 1) {
longestCommonPrefix = lc.completionStrings[0].length();
} else {
bool keepGoing = true;
while (keepGoing) {
for (size_t j = 0; j < lc.completionStrings.size() - 1; ++j) {
char c1 = lc.completionStrings[j][longestCommonPrefix];
char c2 = lc.completionStrings[j + 1][longestCommonPrefix];
if ((0 == c1) || (0 == c2) || (c1 != c2)) {
keepGoing = false;
break;
}
}
if (keepGoing) {
++longestCommonPrefix;
}
}
}
if (lc.completionStrings.size() != 1) { // beep if ambiguous
beep();
}
// if we can extend the item, extend it and return to main loop
if (longestCommonPrefix > itemLength) {
displayLength = len + longestCommonPrefix - itemLength;
if (displayLength > buflen) {
longestCommonPrefix -= displayLength - buflen; // don't overflow buffer
displayLength = buflen; // truncate the insertion
beep(); // and make a noise
}
Utf32String displayText(displayLength + 1);
memcpy(displayText.get(), buf32, sizeof(UChar32) * startIndex);
memcpy(&displayText[startIndex],
&lc.completionStrings[0][0],
sizeof(UChar32) * longestCommonPrefix);
int tailIndex = startIndex + longestCommonPrefix;
memcpy(&displayText[tailIndex],
&buf32[pos],
sizeof(UChar32) * (displayLength - tailIndex + 1));
copyString32(buf32, displayText.get(), buflen + 1);
pos = startIndex + longestCommonPrefix;
len = displayLength;
refreshLine(pi);
return 0;
}
// we can't complete any further, wait for second tab
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
// if any character other than tab, pass it to the main loop
if (c != ctrlChar('I')) {
freeCompletions(&lc);
return c;
}
// we got a second tab, maybe show list of possible completions
bool showCompletions = true;
bool onNewLine = false;
if (lc.completionStrings.size() > completionCountCutoff) {
int savePos = pos; // move cursor to EOL to avoid overwriting the command line
pos = len;
refreshLine(pi);
pos = savePos;
printf("\nDisplay all %u possibilities? (y or n)",
static_cast<unsigned int>(lc.completionStrings.size()));
fflush(stdout);
onNewLine = true;
while (c != 'y' && c != 'Y' && c != 'n' && c != 'N' && c != ctrlChar('C')) {
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
}
switch (c) {
case 'n':
case 'N':
showCompletions = false;
freeCompletions(&lc);
break;
case ctrlChar('C'):
showCompletions = false;
freeCompletions(&lc);
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
c = 0;
break;
}
}
// if showing the list, do it the way readline does it
bool stopList = false;
if (showCompletions) {
int longestCompletion = 0;
for (size_t j = 0; j < lc.completionStrings.size(); ++j) {
itemLength = lc.completionStrings[j].length();
if (itemLength > longestCompletion) {
longestCompletion = itemLength;
}
}
longestCompletion += 2;
int columnCount = pi.promptScreenColumns / longestCompletion;
if (columnCount < 1) {
columnCount = 1;
}
if (!onNewLine) { // skip this if we showed "Display all %d possibilities?"
int savePos = pos; // move cursor to EOL to avoid overwriting the command line
pos = len;
refreshLine(pi);
pos = savePos;
}
size_t pauseRow = getScreenRows() - 1;
size_t rowCount = (lc.completionStrings.size() + columnCount - 1) / columnCount;
for (size_t row = 0; row < rowCount; ++row) {
if (row == pauseRow) {
printf("\n--More--");
fflush(stdout);
c = 0;
bool doBeep = false;
while (c != ' ' && c != '\r' && c != '\n' && c != 'y' && c != 'Y' && c != 'n' &&
c != 'N' && c != 'q' && c != 'Q' && c != ctrlChar('C')) {
if (doBeep) {
beep();
}
doBeep = true;
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
}
switch (c) {
case ' ':
case 'y':
case 'Y':
printf("\r \r");
pauseRow += getScreenRows() - 1;
break;
case '\r':
case '\n':
printf("\r \r");
++pauseRow;
break;
case 'n':
case 'N':
case 'q':
case 'Q':
printf("\r \r");
stopList = true;
break;
case ctrlChar('C'):
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
stopList = true;
break;
}
} else {
printf("\n");
}
if (stopList) {
break;
}
for (int column = 0; column < columnCount; ++column) {
size_t index = (column * rowCount) + row;
if (index < lc.completionStrings.size()) {
itemLength = lc.completionStrings[index].length();
fflush(stdout);
if (write32(1, lc.completionStrings[index].get(), itemLength) == -1)
return -1;
if (((column + 1) * rowCount) + row < lc.completionStrings.size()) {
for (int k = itemLength; k < longestCompletion; ++k) {
printf(" ");
}
}
}
}
}
fflush(stdout);
freeCompletions(&lc);
}
// display the prompt on a new line, then redisplay the input buffer
if (!stopList || c == ctrlChar('C')) {
if (write(1, "\n", 1) == -1)
return 0;
}
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return 0;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return 0;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines;
refreshLine(pi);
return 0;
}
/**
* Clear the screen ONLY (no redisplay of anything)
*/
void linenoiseClearScreen(void) {
#ifdef _WIN32
COORD coord = {0, 0};
CONSOLE_SCREEN_BUFFER_INFO inf;
HANDLE screenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(screenHandle, &inf);
SetConsoleCursorPosition(screenHandle, coord);
DWORD count;
FillConsoleOutputCharacterA(screenHandle, ' ', inf.dwSize.X * inf.dwSize.Y, coord, &count);
#else
if (write(1, "\x1b[H\x1b[2J", 7) <= 0)
return;
#endif
}
void InputBuffer::clearScreen(PromptBase& pi) {
linenoiseClearScreen();
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines;
refreshLine(pi);
}
/**
* Incremental history search -- take over the prompt and keyboard as the user types a search
* string, deletes characters from it, changes direction, and either accepts the found line (for
* execution orediting) or cancels.
* @param pi PromptBase struct holding information about the (old, static) prompt and our
* screen position
* @param startChar the character that began the search, used to set the initial direction
*/
int InputBuffer::incrementalHistorySearch(PromptBase& pi, int startChar) {
size_t bufferSize;
size_t ucharCount;
int errorCode;
// if not already recalling, add the current line to the history list so we don't have to
// special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
bufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[bufferSize]);
copyString32to8(tempBuffer.get(), buf32, bufferSize);
history[historyLen - 1] =
reinterpret_cast<UChar8*>(strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
int historyLineLength = len;
int historyLinePosition = pos;
UChar32 emptyBuffer[1];
char emptyWidths[1];
InputBuffer empty(emptyBuffer, emptyWidths, 1);
empty.refreshLine(pi); // erase the old input first
DynamicPrompt dp(pi, (startChar == ctrlChar('R')) ? -1 : 1);
dp.promptPreviousLen = pi.promptPreviousLen;
dp.promptPreviousInputLen = pi.promptPreviousInputLen;
dynamicRefresh(
dp, buf32, historyLineLength, historyLinePosition); // draw user's text with our prompt
// loop until we get an exit character
int c;
bool keepLooping = true;
bool useSearchedLine = true;
bool searchAgain = false;
UChar32* activeHistoryLine = 0;
while (keepLooping) {
c = linenoiseReadChar();
c = cleanupCtrl(c); // convert CTRL + <char> into normal ctrl
switch (c) {
// these characters keep the selected text but do not execute it
case ctrlChar('A'): // ctrl-A, move cursor to start of line
case HOME_KEY:
case ctrlChar('B'): // ctrl-B, move cursor left by one character
case LEFT_ARROW_KEY:
case META + 'b': // meta-B, move cursor left by one word
case META + 'B':
case CTRL + LEFT_ARROW_KEY:
case META + LEFT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
case ctrlChar('D'):
case META + 'd': // meta-D, kill word to right of cursor
case META + 'D':
case ctrlChar('E'): // ctrl-E, move cursor to end of line
case END_KEY:
case ctrlChar('F'): // ctrl-F, move cursor right by one character
case RIGHT_ARROW_KEY:
case META + 'f': // meta-F, move cursor right by one word
case META + 'F':
case CTRL + RIGHT_ARROW_KEY:
case META + RIGHT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
case META + ctrlChar('H'):
case ctrlChar('J'):
case ctrlChar('K'): // ctrl-K, kill from cursor to end of line
case ctrlChar('M'):
case ctrlChar('N'): // ctrl-N, recall next line in history
case ctrlChar('P'): // ctrl-P, recall previous line in history
case DOWN_ARROW_KEY:
case UP_ARROW_KEY:
case ctrlChar('T'): // ctrl-T, transpose characters
case ctrlChar('U'): // ctrl-U, kill all characters to the left of the cursor
case ctrlChar('W'):
case META + 'y': // meta-Y, "yank-pop", rotate popped text
case META + 'Y':
case 127:
case DELETE_KEY:
case META + '<': // start of history
case PAGE_UP_KEY:
case META + '>': // end of history
case PAGE_DOWN_KEY:
keepLooping = false;
break;
// these characters revert the input line to its previous state
case ctrlChar('C'): // ctrl-C, abort this line
case ctrlChar('G'):
case ctrlChar('L'): // ctrl-L, clear screen and redisplay line
keepLooping = false;
useSearchedLine = false;
if (c != ctrlChar('L')) {
c = -1; // ctrl-C and ctrl-G just abort the search and do nothing else
}
break;
// these characters stay in search mode and update the display
case ctrlChar('S'):
case ctrlChar('R'):
if (dp.searchTextLen == 0) { // if no current search text, recall previous text
if (previousSearchText.length()) {
dp.updateSearchText(previousSearchText.get());
}
}
if ((dp.direction == 1 && c == ctrlChar('R')) ||
(dp.direction == -1 && c == ctrlChar('S'))) {
dp.direction = 0 - dp.direction; // reverse direction
dp.updateSearchPrompt(); // change the prompt
} else {
searchAgain = true; // same direction, search again
}
break;
// job control is its own thing
#ifndef _WIN32
case ctrlChar('Z'): // ctrl-Z, job control
disableRawMode(); // Returning to Linux (whatever) shell, leave raw mode
raise(SIGSTOP); // Break out in mid-line
enableRawMode(); // Back from Linux shell, re-enter raw mode
{
bufferSize = historyLineLength + 1;
unique_ptr<UChar32[]> tempUnicode(new UChar32[bufferSize]);
copyString8to32(tempUnicode.get(),
history[historyIndex],
bufferSize,
ucharCount,
errorCode);
dynamicRefresh(dp, tempUnicode.get(), historyLineLength, historyLinePosition);
}
continue;
break;
#endif
// these characters update the search string, and hence the selected input line
case ctrlChar('H'): // backspace/ctrl-H, delete char to left of cursor
if (dp.searchTextLen > 0) {
unique_ptr<UChar32[]> tempUnicode(new UChar32[dp.searchTextLen]);
--dp.searchTextLen;
dp.searchText[dp.searchTextLen] = 0;
copyString32(tempUnicode.get(), dp.searchText.get(), dp.searchTextLen + 1);
dp.updateSearchText(tempUnicode.get());
} else {
beep();
}
break;
case ctrlChar('Y'): // ctrl-Y, yank killed text
break;
default:
if (!isControlChar(c) && c <= 0x0010FFFF) { // not an action character
unique_ptr<UChar32[]> tempUnicode(new UChar32[dp.searchTextLen + 2]);
copyString32(tempUnicode.get(), dp.searchText.get(), dp.searchTextLen + 2);
tempUnicode[dp.searchTextLen] = c;
tempUnicode[dp.searchTextLen + 1] = 0;
dp.updateSearchText(tempUnicode.get());
} else {
beep();
}
} // switch
// if we are staying in search mode, search now
if (keepLooping) {
bufferSize = historyLineLength + 1;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(
activeHistoryLine, history[historyIndex], bufferSize, ucharCount, errorCode);
if (dp.searchTextLen > 0) {
bool found = false;
int historySearchIndex = historyIndex;
int lineLength = ucharCount;
int lineSearchPos = historyLinePosition;
if (searchAgain) {
lineSearchPos += dp.direction;
}
searchAgain = false;
while (true) {
while ((dp.direction > 0) ? (lineSearchPos < lineLength)
: (lineSearchPos >= 0)) {
if (strncmp32(dp.searchText.get(),
&activeHistoryLine[lineSearchPos],
dp.searchTextLen) == 0) {
found = true;
break;
}
lineSearchPos += dp.direction;
}
if (found) {
historyIndex = historySearchIndex;
historyLineLength = lineLength;
historyLinePosition = lineSearchPos;
break;
} else if ((dp.direction > 0) ? (historySearchIndex < historyLen - 1)
: (historySearchIndex > 0)) {
historySearchIndex += dp.direction;
bufferSize =
strlen(reinterpret_cast<char*>(history[historySearchIndex])) + 1;
delete[] activeHistoryLine;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(activeHistoryLine,
history[historySearchIndex],
bufferSize,
ucharCount,
errorCode);
lineLength = ucharCount;
lineSearchPos = (dp.direction > 0) ? 0 : (lineLength - dp.searchTextLen);
} else {
beep();
break;
}
}; // while
}
if (activeHistoryLine) {
delete[] activeHistoryLine;
}
bufferSize = historyLineLength + 1;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(
activeHistoryLine, history[historyIndex], bufferSize, ucharCount, errorCode);
dynamicRefresh(dp,
activeHistoryLine,
historyLineLength,
historyLinePosition); // draw user's text with our prompt
}
} // while
// leaving history search, restore previous prompt, maybe make searched line current
PromptBase pb;
pb.promptChars = pi.promptIndentation;
Utf32String tempUnicode(pb.promptChars + 1);
copyString32(tempUnicode.get(), &pi.promptText[pi.promptLastLinePosition], pb.promptChars + 1);
tempUnicode.initFromBuffer();
pb.promptText = tempUnicode;
pb.promptExtraLines = 0;
pb.promptIndentation = pi.promptIndentation;
pb.promptLastLinePosition = 0;
pb.promptPreviousInputLen = historyLineLength;
pb.promptCursorRowOffset = dp.promptCursorRowOffset;
pb.promptScreenColumns = pi.promptScreenColumns;
pb.promptPreviousLen = dp.promptChars;
if (useSearchedLine && activeHistoryLine) {
historyRecallMostRecent = true;
copyString32(buf32, activeHistoryLine, buflen + 1);
len = historyLineLength;
pos = historyLinePosition;
}
if (activeHistoryLine) {
delete[] activeHistoryLine;
}
dynamicRefresh(pb, buf32, len, pos); // redraw the original prompt with current input
pi.promptPreviousInputLen = len;
pi.promptCursorRowOffset = pi.promptExtraLines + pb.promptCursorRowOffset;
previousSearchText = dp.searchText; // save search text for possible reuse on ctrl-R ctrl-R
return c; // pass a character or -1 back to main loop
}
static bool isCharacterAlphanumeric(UChar32 testChar) {
return iswalnum(testChar);
}
int InputBuffer::getInputLine(PromptBase& pi) {
// The latest history entry is always our current buffer
if (len > 0) {
size_t bufferSize = sizeof(UChar32) * len + 1;
unique_ptr<char[]> tempBuffer(new char[bufferSize]);
copyString32to8(reinterpret_cast<UChar8*>(tempBuffer.get()), buf32, bufferSize);
linenoiseHistoryAdd(tempBuffer.get());
} else {
linenoiseHistoryAdd("");
}
historyIndex = historyLen - 1;
historyRecallMostRecent = false;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return -1;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return -1;
#endif
// the cursor starts out at the end of the prompt
pi.promptCursorRowOffset = pi.promptExtraLines;
// kill and yank start in "other" mode
killRing.lastAction = KillRing::actionOther;
// when history search returns control to us, we execute its terminating keystroke
int terminatingKeystroke = -1;
// if there is already text in the buffer, display it first
if (len > 0) {
refreshLine(pi);
}
// loop collecting characters, respond to line editing characters
while (true) {
int c;
if (terminatingKeystroke == -1) {
c = linenoiseReadChar(); // get a new keystroke
} else {
c = terminatingKeystroke; // use the terminating keystroke from search
terminatingKeystroke = -1; // clear it once we've used it
}
c = cleanupCtrl(c); // convert CTRL + <char> into normal ctrl
if (c == 0) {
return len;
}
if (c == -1) {
refreshLine(pi);
continue;
}
if (c == -2) {
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return -1;
refreshLine(pi);
continue;
}
// ctrl-I/tab, command completion, needs to be before switch statement
if (c == ctrlChar('I') && completionCallback) {
if (pos == 0) // SERVER-4967 -- in earlier versions, you could paste previous output
continue; // back into the shell ... this output may have leading tabs.
// This hack (i.e. what the old code did) prevents command completion
// on an empty line but lets users paste text with leading tabs.
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
// completeLine does the actual completion and replacement
c = completeLine(pi);
if (c < 0) // return on error
return len;
if (c == 0) // read next character when 0
continue;
// deliberate fall-through here, so we use the terminating character
}
switch (c) {
case ctrlChar('A'): // ctrl-A, move cursor to start of line
case HOME_KEY:
killRing.lastAction = KillRing::actionOther;
pos = 0;
refreshLine(pi);
break;
case ctrlChar('B'): // ctrl-B, move cursor left by one character
case LEFT_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
--pos;
refreshLine(pi);
}
break;
case META + 'b': // meta-B, move cursor left by one word
case META + 'B':
case CTRL + LEFT_ARROW_KEY:
case META + LEFT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
while (pos > 0 && !isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
while (pos > 0 && isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
refreshLine(pi);
}
break;
case ctrlChar('C'): // ctrl-C, abort this line
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
errno = EAGAIN;
--historyLen;
free(history[historyLen]);
// we need one last refresh with the cursor at the end of the line
// so we don't display the next prompt over the previous input line
pos = len; // pass len as pos for EOL
refreshLine(pi);
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
return -1;
case META + 'c': // meta-C, give word initial Cap
case META + 'C':
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
if (pos < len) {
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
if (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'a' && buf32[pos] <= 'z') {
buf32[pos] += 'A' - 'a';
}
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'A' && buf32[pos] <= 'Z') {
buf32[pos] += 'a' - 'A';
}
++pos;
}
refreshLine(pi);
}
break;
// ctrl-D, delete the character under the cursor
// on an empty line, exit the shell
case ctrlChar('D'):
killRing.lastAction = KillRing::actionOther;
if (len > 0 && pos < len) {
historyRecallMostRecent = false;
memmove(buf32 + pos, buf32 + pos + 1, sizeof(UChar32) * (len - pos));
--len;
refreshLine(pi);
} else if (len == 0) {
--historyLen;
free(history[historyLen]);
return -1;
}
break;
case META + 'd': // meta-D, kill word to right of cursor
case META + 'D':
if (pos < len) {
historyRecallMostRecent = false;
int endingPos = pos;
while (endingPos < len && !isCharacterAlphanumeric(buf32[endingPos])) {
++endingPos;
}
while (endingPos < len && isCharacterAlphanumeric(buf32[endingPos])) {
++endingPos;
}
killRing.kill(&buf32[pos], endingPos - pos, true);
memmove(
buf32 + pos, buf32 + endingPos, sizeof(UChar32) * (len - endingPos + 1));
len -= endingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('E'): // ctrl-E, move cursor to end of line
case END_KEY:
killRing.lastAction = KillRing::actionOther;
pos = len;
refreshLine(pi);
break;
case ctrlChar('F'): // ctrl-F, move cursor right by one character
case RIGHT_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
++pos;
refreshLine(pi);
}
break;
case META + 'f': // meta-F, move cursor right by one word
case META + 'F':
case CTRL + RIGHT_ARROW_KEY:
case META + RIGHT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
refreshLine(pi);
}
break;
case ctrlChar('H'): // backspace/ctrl-H, delete char to left of cursor
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
historyRecallMostRecent = false;
memmove(buf32 + pos - 1, buf32 + pos, sizeof(UChar32) * (1 + len - pos));
--pos;
--len;
refreshLine(pi);
}
break;
// meta-Backspace, kill word to left of cursor
case META + ctrlChar('H'):
if (pos > 0) {
historyRecallMostRecent = false;
int startingPos = pos;
while (pos > 0 && !isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
while (pos > 0 && isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
killRing.kill(&buf32[pos], startingPos - pos, false);
memmove(buf32 + pos,
buf32 + startingPos,
sizeof(UChar32) * (len - startingPos + 1));
len -= startingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('J'): // ctrl-J/linefeed/newline, accept line
case ctrlChar('M'): // ctrl-M/return/enter
killRing.lastAction = KillRing::actionOther;
// we need one last refresh with the cursor at the end of the line
// so we don't display the next prompt over the previous input line
pos = len; // pass len as pos for EOL
refreshLine(pi);
historyPreviousIndex = historyRecallMostRecent ? historyIndex : -2;
--historyLen;
free(history[historyLen]);
return len;
case ctrlChar('K'): // ctrl-K, kill from cursor to end of line
killRing.kill(&buf32[pos], len - pos, true);
buf32[pos] = '\0';
len = pos;
refreshLine(pi);
killRing.lastAction = KillRing::actionKill;
historyRecallMostRecent = false;
break;
case ctrlChar('L'): // ctrl-L, clear screen and redisplay line
clearScreen(pi);
break;
case META + 'l': // meta-L, lowercase word
case META + 'L':
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
historyRecallMostRecent = false;
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'A' && buf32[pos] <= 'Z') {
buf32[pos] += 'a' - 'A';
}
++pos;
}
refreshLine(pi);
}
break;
case ctrlChar('N'): // ctrl-N, recall next line in history
case ctrlChar('P'): // ctrl-P, recall previous line in history
case DOWN_ARROW_KEY:
case UP_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
// if not already recalling, add the current line to the history list so we don't
// have to special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
size_t tempBufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[tempBufferSize]);
copyString32to8(tempBuffer.get(), buf32, tempBufferSize);
history[historyLen - 1] = reinterpret_cast<UChar8*>(
strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
if (historyLen > 1) {
if (c == UP_ARROW_KEY) {
c = ctrlChar('P');
}
if (historyPreviousIndex != -2 && c != ctrlChar('P')) {
historyIndex = 1 + historyPreviousIndex; // emulate Windows down-arrow
} else {
historyIndex += (c == ctrlChar('P')) ? -1 : 1;
}
historyPreviousIndex = -2;
if (historyIndex < 0) {
historyIndex = 0;
break;
} else if (historyIndex >= historyLen) {
historyIndex = historyLen - 1;
break;
}
historyRecallMostRecent = true;
size_t ucharCount;
int errorCode;
copyString8to32(buf32, history[historyIndex], buflen, ucharCount, errorCode);
len = pos = ucharCount;
refreshLine(pi);
}
break;
case ctrlChar('R'): // ctrl-R, reverse history search
case ctrlChar('S'): // ctrl-S, forward history search
terminatingKeystroke = incrementalHistorySearch(pi, c);
break;
case ctrlChar('T'): // ctrl-T, transpose characters
killRing.lastAction = KillRing::actionOther;
if (pos > 0 && len > 1) {
historyRecallMostRecent = false;
size_t leftCharPos = (pos == len) ? pos - 2 : pos - 1;
char aux = buf32[leftCharPos];
buf32[leftCharPos] = buf32[leftCharPos + 1];
buf32[leftCharPos + 1] = aux;
if (pos != len)
++pos;
refreshLine(pi);
}
break;
case ctrlChar('U'): // ctrl-U, kill all characters to the left of the cursor
if (pos > 0) {
historyRecallMostRecent = false;
killRing.kill(&buf32[0], pos, false);
len -= pos;
memmove(buf32, buf32 + pos, sizeof(UChar32) * (len + 1));
pos = 0;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case META + 'u': // meta-U, uppercase word
case META + 'U':
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
historyRecallMostRecent = false;
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'a' && buf32[pos] <= 'z') {
buf32[pos] += 'A' - 'a';
}
++pos;
}
refreshLine(pi);
}
break;
// ctrl-W, kill to whitespace (not word) to left of cursor
case ctrlChar('W'):
if (pos > 0) {
historyRecallMostRecent = false;
int startingPos = pos;
while (pos > 0 && buf32[pos - 1] == ' ') {
--pos;
}
while (pos > 0 && buf32[pos - 1] != ' ') {
--pos;
}
killRing.kill(&buf32[pos], startingPos - pos, false);
memmove(buf32 + pos,
buf32 + startingPos,
sizeof(UChar32) * (len - startingPos + 1));
len -= startingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('Y'): // ctrl-Y, yank killed text
historyRecallMostRecent = false;
{
Utf32String* restoredText = killRing.yank();
if (restoredText) {
bool truncated = false;
size_t ucharCount = restoredText->length();
if (ucharCount > static_cast<size_t>(buflen - len)) {
ucharCount = buflen - len;
truncated = true;
}
memmove(buf32 + pos + ucharCount,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
memmove(buf32 + pos, restoredText->get(), sizeof(UChar32) * ucharCount);
pos += ucharCount;
len += ucharCount;
refreshLine(pi);
killRing.lastAction = KillRing::actionYank;
killRing.lastYankSize = ucharCount;
if (truncated) {
beep();
}
} else {
beep();
}
}
break;
case META + 'y': // meta-Y, "yank-pop", rotate popped text
case META + 'Y':
if (killRing.lastAction == KillRing::actionYank) {
historyRecallMostRecent = false;
Utf32String* restoredText = killRing.yankPop();
if (restoredText) {
bool truncated = false;
size_t ucharCount = restoredText->length();
if (ucharCount >
static_cast<size_t>(killRing.lastYankSize + buflen - len)) {
ucharCount = killRing.lastYankSize + buflen - len;
truncated = true;
}
if (ucharCount > killRing.lastYankSize) {
memmove(buf32 + pos + ucharCount - killRing.lastYankSize,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
memmove(buf32 + pos - killRing.lastYankSize,
restoredText->get(),
sizeof(UChar32) * ucharCount);
} else {
memmove(buf32 + pos - killRing.lastYankSize,
restoredText->get(),
sizeof(UChar32) * ucharCount);
memmove(buf32 + pos + ucharCount - killRing.lastYankSize,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
}
pos += ucharCount - killRing.lastYankSize;
len += ucharCount - killRing.lastYankSize;
killRing.lastYankSize = ucharCount;
refreshLine(pi);
if (truncated) {
beep();
}
break;
}
}
beep();
break;
#ifndef _WIN32
case ctrlChar('Z'): // ctrl-Z, job control
disableRawMode(); // Returning to Linux (whatever) shell, leave raw mode
raise(SIGSTOP); // Break out in mid-line
enableRawMode(); // Back from Linux shell, re-enter raw mode
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
break; // Redraw prompt
refreshLine(pi); // Refresh the line
break;
#endif
// DEL, delete the character under the cursor
case 127:
case DELETE_KEY:
killRing.lastAction = KillRing::actionOther;
if (len > 0 && pos < len) {
historyRecallMostRecent = false;
memmove(buf32 + pos, buf32 + pos + 1, sizeof(UChar32) * (len - pos));
--len;
refreshLine(pi);
}
break;
case META + '<': // meta-<, beginning of history
case PAGE_UP_KEY: // Page Up, beginning of history
case META + '>': // meta->, end of history
case PAGE_DOWN_KEY: // Page Down, end of history
killRing.lastAction = KillRing::actionOther;
// if not already recalling, add the current line to the history list so we don't
// have to special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
size_t tempBufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[tempBufferSize]);
copyString32to8(tempBuffer.get(), buf32, tempBufferSize);
history[historyLen - 1] = reinterpret_cast<UChar8*>(
strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
if (historyLen > 1) {
historyIndex = (c == META + '<' || c == PAGE_UP_KEY) ? 0 : historyLen - 1;
historyPreviousIndex = -2;
historyRecallMostRecent = true;
size_t ucharCount;
int errorCode;
copyString8to32(buf32, history[historyIndex], buflen, ucharCount, errorCode);
len = pos = ucharCount;
refreshLine(pi);
}
break;
// not one of our special characters, maybe insert it in the buffer
default:
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
if (c & (META | CTRL)) { // beep on unknown Ctrl and/or Meta keys
beep();
break;
}
if (len < buflen) {
if (isControlChar(c)) { // don't insert control characters
beep();
break;
}
if (len == pos) { // at end of buffer
buf32[pos] = c;
++pos;
++len;
buf32[len] = '\0';
int inputLen = calculateColumnPosition(buf32, len);
if (pi.promptIndentation + inputLen < pi.promptScreenColumns) {
if (inputLen > pi.promptPreviousInputLen)
pi.promptPreviousInputLen = inputLen;
/* Avoid a full update of the line in the
* trivial case. */
if (write32(1, reinterpret_cast<UChar32*>(&c), 1) == -1)
return -1;
} else {
refreshLine(pi);
}
} else { // not at end of buffer, have to move characters to our right
memmove(buf32 + pos + 1, buf32 + pos, sizeof(UChar32) * (len - pos));
buf32[pos] = c;
++len;
++pos;
buf32[len] = '\0';
refreshLine(pi);
}
} else {
beep(); // buffer is full, beep on new characters
}
break;
}
}
return len;
}
string preloadedBufferContents; // used with linenoisePreloadBuffer
string preloadErrorMessage;
/**
* linenoisePreloadBuffer provides text to be inserted into the command buffer
*
* the provided text will be processed to be usable and will be used to preload
* the input buffer on the next call to linenoise()
*
* @param preloadText text to begin with on the next call to linenoise()
*/
void linenoisePreloadBuffer(const char* preloadText) {
if (!preloadText) {
return;
}
int bufferSize = strlen(preloadText) + 1;
unique_ptr<char[]> tempBuffer(new char[bufferSize]);
strncpy(&tempBuffer[0], preloadText, bufferSize);
// remove characters that won't display correctly
char* pIn = &tempBuffer[0];
char* pOut = pIn;
bool controlsStripped = false;
bool whitespaceSeen = false;
while (*pIn) {
unsigned char c = *pIn++; // we need unsigned so chars 0x80 and above are allowed
if ('\r' == c) { // silently skip CR
continue;
}
if ('\n' == c || '\t' == c) { // note newline or tab
whitespaceSeen = true;
continue;
}
if (isControlChar(c)) { // remove other control characters, flag for message
controlsStripped = true;
*pOut++ = ' ';
continue;
}
if (whitespaceSeen) { // convert whitespace to a single space
*pOut++ = ' ';
whitespaceSeen = false;
}
*pOut++ = c;
}
*pOut = 0;
int processedLength = pOut - tempBuffer.get();
bool lineTruncated = false;
if (processedLength > (LINENOISE_MAX_LINE - 1)) {
lineTruncated = true;
tempBuffer[LINENOISE_MAX_LINE - 1] = 0;
}
preloadedBufferContents = tempBuffer.get();
if (controlsStripped) {
preloadErrorMessage += " [Edited line: control characters were converted to spaces]\n";
}
if (lineTruncated) {
preloadErrorMessage += " [Edited line: the line length was reduced from ";
char buf[128];
snprintf(buf, sizeof(buf), "%d to %d]\n", processedLength, (LINENOISE_MAX_LINE - 1));
preloadErrorMessage += buf;
}
}
/**
* linenoise is a readline replacement.
*
* call it with a prompt to display and it will return a line of input from the user
*
* @param prompt text of prompt to display to the user
* @return the returned string belongs to the caller on return and must be freed to prevent
* memory leaks
*/
char* linenoise(const char* prompt) {
if (isatty(STDIN_FILENO)) { // input is from a terminal
UChar32 buf32[LINENOISE_MAX_LINE];
char charWidths[LINENOISE_MAX_LINE];
if (!preloadErrorMessage.empty()) {
printf("%s", preloadErrorMessage.c_str());
fflush(stdout);
preloadErrorMessage.clear();
}
PromptInfo pi(reinterpret_cast<const UChar8*>(prompt), getScreenColumns());
if (isUnsupportedTerm()) {
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return 0;
fflush(stdout);
if (preloadedBufferContents.empty()) {
unique_ptr<char[]> buf8(new char[LINENOISE_MAX_LINE]);
if (fgets(buf8.get(), LINENOISE_MAX_LINE, stdin) == NULL) {
return NULL;
}
size_t len = strlen(buf8.get());
while (len && (buf8[len - 1] == '\n' || buf8[len - 1] == '\r')) {
--len;
buf8[len] = '\0';
}
return strdup(buf8.get()); // caller must free buffer
} else {
char* buf8 = strdup(preloadedBufferContents.c_str());
preloadedBufferContents.clear();
return buf8; // caller must free buffer
}
} else {
if (enableRawMode() == -1) {
return NULL;
}
InputBuffer ib(buf32, charWidths, LINENOISE_MAX_LINE);
if (!preloadedBufferContents.empty()) {
ib.preloadBuffer(reinterpret_cast<const UChar8*>(preloadedBufferContents.c_str()));
preloadedBufferContents.clear();
}
int count = ib.getInputLine(pi);
disableRawMode();
printf("\n");
if (count == -1) {
return NULL;
}
size_t bufferSize = sizeof(UChar32) * ib.length() + 1;
unique_ptr<UChar8[]> buf8(new UChar8[bufferSize]);
copyString32to8(buf8.get(), buf32, bufferSize);
return strdup(reinterpret_cast<char*>(buf8.get())); // caller must free buffer
}
} else { // input not from a terminal, we should work with piped input, i.e. redirected stdin
unique_ptr<char[]> buf8(new char[LINENOISE_MAX_LINE]);
if (fgets(buf8.get(), LINENOISE_MAX_LINE, stdin) == NULL) {
return NULL;
}
// if fgets() gave us the newline, remove it
int count = strlen(buf8.get());
if (count > 0 && buf8[count - 1] == '\n') {
--count;
buf8[count] = '\0';
}
return strdup(buf8.get()); // caller must free buffer
}
}
/* Register a callback function to be called for tab-completion. */
void linenoiseSetCompletionCallback(linenoiseCompletionCallback* fn) {
completionCallback = fn;
}
void linenoiseAddCompletion(linenoiseCompletions* lc, const char* str) {
lc->completionStrings.push_back(Utf32String(reinterpret_cast<const UChar8*>(str)));
}
int linenoiseHistoryAdd(const char* line) {
if (historyMaxLen == 0) {
return 0;
}
if (history == NULL) {
history = reinterpret_cast<UChar8**>(malloc(sizeof(UChar8*) * historyMaxLen));
if (history == NULL) {
return 0;
}
memset(history, 0, (sizeof(char*) * historyMaxLen));
}
UChar8* linecopy = reinterpret_cast<UChar8*>(strdup(line));
if (!linecopy) {
return 0;
}
if (historyLen == historyMaxLen) {
free(history[0]);
memmove(history, history + 1, sizeof(char*) * (historyMaxLen - 1));
--historyLen;
if (--historyPreviousIndex < -1) {
historyPreviousIndex = -2;
}
}
// convert newlines in multi-line code to spaces before storing
UChar8* p = linecopy;
while (*p) {
if (*p == '\n') {
*p = ' ';
}
++p;
}
history[historyLen] = linecopy;
++historyLen;
return 1;
}
int linenoiseHistorySetMaxLen(int len) {
if (len < 1) {
return 0;
}
if (history) {
int tocopy = historyLen;
UChar8** newHistory = reinterpret_cast<UChar8**>(malloc(sizeof(UChar8*) * len));
if (newHistory == NULL) {
return 0;
}
if (len < tocopy) {
tocopy = len;
}
memcpy(newHistory, history + historyMaxLen - tocopy, sizeof(UChar8*) * tocopy);
free(history);
history = newHistory;
}
historyMaxLen = len;
if (historyLen > historyMaxLen) {
historyLen = historyMaxLen;
}
return 1;
}
/* Save the history in the specified file. On success 0 is returned
* otherwise -1 is returned. */
int linenoiseHistorySave(const char* filename) {
FILE* fp;
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
int fd = open(filename, O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
// report errno somehow?
return -1;
}
fp = fdopen(fd, "wt");
#else
fp = fopen(filename, "wt");
#endif // _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
if (fp == NULL) {
return -1;
}
for (int j = 0; j < historyLen; ++j) {
if (history[j][0] != '\0') {
fprintf(fp, "%s\n", history[j]);
}
}
fclose(fp); // Also causes fd to be closed.
return 0;
}
/* Load the history from the specified file. If the file does not exist
* zero is returned and no operation is performed.
*
* If the file exists and the operation succeeded 0 is returned, otherwise
* on error -1 is returned. */
int linenoiseHistoryLoad(const char* filename) {
FILE* fp = fopen(filename, "rt");
if (fp == NULL) {
return -1;
}
char buf[LINENOISE_MAX_LINE];
while (fgets(buf, LINENOISE_MAX_LINE, fp) != NULL) {
char* p = strchr(buf, '\r');
if (!p) {
p = strchr(buf, '\n');
}
if (p) {
*p = '\0';
}
if (p != buf) {
linenoiseHistoryAdd(buf);
}
}
fclose(fp);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_5212_1 |
crossvul-cpp_data_bad_2264_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/ext_hash.h"
#include <algorithm>
#include <memory>
#include "hphp/runtime/ext/ext_file.h"
#include "hphp/runtime/ext/ext_string.h"
#include "hphp/runtime/ext/hash/hash_md.h"
#include "hphp/runtime/ext/hash/hash_sha.h"
#include "hphp/runtime/ext/hash/hash_ripemd.h"
#include "hphp/runtime/ext/hash/hash_whirlpool.h"
#include "hphp/runtime/ext/hash/hash_tiger.h"
#include "hphp/runtime/ext/hash/hash_snefru.h"
#include "hphp/runtime/ext/hash/hash_gost.h"
#include "hphp/runtime/ext/hash/hash_adler32.h"
#include "hphp/runtime/ext/hash/hash_crc32.h"
#include "hphp/runtime/ext/hash/hash_haval.h"
#include "hphp/runtime/ext/hash/hash_fnv1.h"
#include "hphp/runtime/ext/hash/hash_furc.h"
#include "hphp/runtime/ext/hash/hash_murmur.h"
#include "hphp/system/constants.h"
#if defined(HPHP_OSS)
#define furc_hash furc_hash_internal
#else
#include "mcrouter/lib/fbi/hash.h" // @nolint
#endif
namespace HPHP {
static class HashExtension : public Extension {
public:
HashExtension() : Extension("hash", "1.0") { }
virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) {
HHVM_FE(hash);
HHVM_FE(hash_algos);
HHVM_FE(hash_file);
HHVM_FE(hash_final);
HHVM_FE(hash_init);
HHVM_FE(hash_update);
HHVM_FE(hash_copy);
HHVM_FE(hash_equals);
HHVM_FE(furchash_hphp_ext);
HHVM_FE(hphp_murmurhash);
}
} s_hash_extension;
///////////////////////////////////////////////////////////////////////////////
// hash engines
static HashEngineMap HashEngines;
using HashEnginePtr = std::shared_ptr<HashEngine>;
class HashEngineMapInitializer {
public:
HashEngineMapInitializer() {
HashEngines["md2"] = HashEnginePtr(new hash_md2());
HashEngines["md4"] = HashEnginePtr(new hash_md4());
HashEngines["md5"] = HashEnginePtr(new hash_md5());
HashEngines["sha1"] = HashEnginePtr(new hash_sha1());
HashEngines["sha224"] = HashEnginePtr(new hash_sha224());
HashEngines["sha256"] = HashEnginePtr(new hash_sha256());
HashEngines["sha384"] = HashEnginePtr(new hash_sha384());
HashEngines["sha512"] = HashEnginePtr(new hash_sha512());
HashEngines["ripemd128"] = HashEnginePtr(new hash_ripemd128());
HashEngines["ripemd160"] = HashEnginePtr(new hash_ripemd160());
HashEngines["ripemd256"] = HashEnginePtr(new hash_ripemd256());
HashEngines["ripemd320"] = HashEnginePtr(new hash_ripemd320());
HashEngines["whirlpool"] = HashEnginePtr(new hash_whirlpool());
#ifdef FACEBOOK
// The original version of tiger got the endianness backwards
// This fb-specific version remains for backward compatibility
HashEngines["tiger128,3-fb"]
= HashEnginePtr(new hash_tiger(true, 128, true));
#endif
HashEngines["tiger128,3"] = HashEnginePtr(new hash_tiger(true, 128));
HashEngines["tiger160,3"] = HashEnginePtr(new hash_tiger(true, 160));
HashEngines["tiger192,3"] = HashEnginePtr(new hash_tiger(true, 192));
HashEngines["tiger128,4"] = HashEnginePtr(new hash_tiger(false, 128));
HashEngines["tiger160,4"] = HashEnginePtr(new hash_tiger(false, 160));
HashEngines["tiger192,4"] = HashEnginePtr(new hash_tiger(false, 192));
HashEngines["snefru"] = HashEnginePtr(new hash_snefru());
HashEngines["gost"] = HashEnginePtr(new hash_gost());
#ifdef FACEBOOK
// Temporarily leave adler32 algo inverting its hash output
// to retain BC pending conversion of user code to correct endianness
// sgolemon(2014-01-30)
HashEngines["adler32-fb"] = HashEnginePtr(new hash_adler32(true));
HashEngines["adler32"] = HashEnginePtr(new hash_adler32(true));
#else
HashEngines["adler32"] = HashEnginePtr(new hash_adler32());
#endif
HashEngines["crc32"] = HashEnginePtr(new hash_crc32(false));
HashEngines["crc32b"] = HashEnginePtr(new hash_crc32(true));
HashEngines["haval128,3"] = HashEnginePtr(new hash_haval(3,128));
HashEngines["haval160,3"] = HashEnginePtr(new hash_haval(3,160));
HashEngines["haval192,3"] = HashEnginePtr(new hash_haval(3,192));
HashEngines["haval224,3"] = HashEnginePtr(new hash_haval(3,224));
HashEngines["haval256,3"] = HashEnginePtr(new hash_haval(3,256));
HashEngines["haval128,4"] = HashEnginePtr(new hash_haval(4,128));
HashEngines["haval160,4"] = HashEnginePtr(new hash_haval(4,160));
HashEngines["haval192,4"] = HashEnginePtr(new hash_haval(4,192));
HashEngines["haval224,4"] = HashEnginePtr(new hash_haval(4,224));
HashEngines["haval256,4"] = HashEnginePtr(new hash_haval(4,256));
HashEngines["haval128,5"] = HashEnginePtr(new hash_haval(5,128));
HashEngines["haval160,5"] = HashEnginePtr(new hash_haval(5,160));
HashEngines["haval192,5"] = HashEnginePtr(new hash_haval(5,192));
HashEngines["haval224,5"] = HashEnginePtr(new hash_haval(5,224));
HashEngines["haval256,5"] = HashEnginePtr(new hash_haval(5,256));
HashEngines["fnv132"] = HashEnginePtr(new hash_fnv132(false));
HashEngines["fnv1a32"] = HashEnginePtr(new hash_fnv132(true));
HashEngines["fnv164"] = HashEnginePtr(new hash_fnv164(false));
HashEngines["fnv1a64"] = HashEnginePtr(new hash_fnv164(true));
}
};
static HashEngineMapInitializer s_engine_initializer;
///////////////////////////////////////////////////////////////////////////////
// hash context
class HashContext : public SweepableResourceData {
public:
CLASSNAME_IS("Hash Context")
// overriding ResourceData
virtual const String& o_getClassNameHook() const { return classnameof(); }
HashContext(HashEnginePtr ops_, void *context_, int options_)
: ops(ops_), context(context_), options(options_), key(nullptr) {
}
explicit HashContext(const HashContext* ctx) {
assert(ctx->ops);
assert(ctx->ops->context_size >= 0);
ops = ctx->ops;
context = malloc(ops->context_size);
ops->hash_copy(context, ctx->context);
options = ctx->options;
key = ctx->key ? strdup(ctx->key) : nullptr;
}
~HashContext() {
HashContext::sweep();
}
void sweep() FOLLY_OVERRIDE {
/* Just in case the algo has internally allocated resources */
if (context) {
assert(ops->digest_size >= 0);
unsigned char dummy[ops->digest_size];
ops->hash_final(dummy, context);
free(context);
}
free(key);
}
HashEnginePtr ops;
void *context;
int options;
char *key;
};
///////////////////////////////////////////////////////////////////////////////
// hash functions
Array HHVM_FUNCTION(hash_algos) {
Array ret;
for (HashEngineMap::const_iterator iter = HashEngines.begin();
iter != HashEngines.end(); ++iter) {
ret.append(String(iter->first));
}
return ret;
}
static HashEnginePtr php_hash_fetch_ops(const String& algo) {
HashEngineMap::const_iterator iter =
HashEngines.find(f_strtolower(algo).data());
if (iter == HashEngines.end()) {
return HashEnginePtr();
}
return iter->second;
}
static Variant php_hash_do_hash(const String& algo, const String& data,
bool isfilename,
bool raw_output) {
HashEnginePtr ops = php_hash_fetch_ops(algo);
if (!ops) {
raise_warning("Unknown hashing algorithm: %s", algo.data());
return false;
}
Variant f;
if (isfilename) {
f = f_fopen(data, "rb");
if (same(f, false)) {
return false;
}
}
void *context = malloc(ops->context_size);
ops->hash_init(context);
if (isfilename) {
for (Variant chunk = f_fread(f.toResource(), 1024);
!is_empty_string(chunk);
chunk = f_fread(f.toResource(), 1024)) {
String schunk = chunk.toString();
ops->hash_update(context, (unsigned char *)schunk.data(), schunk.size());
}
} else {
ops->hash_update(context, (unsigned char *)data.data(), data.size());
}
String raw = String(ops->digest_size, ReserveString);
char *digest = raw.bufferSlice().ptr;
ops->hash_final((unsigned char *)digest, context);
free(context);
raw.setSize(ops->digest_size);
if (raw_output) {
return raw;
}
return f_bin2hex(raw);
}
Variant HHVM_FUNCTION(hash, const String& algo, const String& data,
bool raw_output /* = false */) {
return php_hash_do_hash(algo, data, false, raw_output);
}
Variant HHVM_FUNCTION(hash_file, const String& algo, const String& filename,
bool raw_output /* = false */) {
if (filename.size() != strlen(filename.data())) {
raise_warning(
"hash_file() expects parameter 2 to be a valid path, string given"
);
return null_variant;
}
return php_hash_do_hash(algo, filename, true, raw_output);
}
static char *prepare_hmac_key(HashEnginePtr ops, void *context,
const String& key) {
char *K = (char*)malloc(ops->block_size);
memset(K, 0, ops->block_size);
if (key.size() > ops->block_size) {
/* Reduce the key first */
ops->hash_update(context, (unsigned char *)key.data(), key.size());
ops->hash_final((unsigned char *)K, context);
/* Make the context ready to start over */
ops->hash_init(context);
} else {
memcpy(K, key.data(), key.size());
}
/* XOR ipad */
for (int i = 0; i < ops->block_size; i++) {
K[i] ^= 0x36;
}
ops->hash_update(context, (unsigned char *)K, ops->block_size);
return K;
}
static void finalize_hmac_key(char *K, HashEnginePtr ops, void *context,
char *digest) {
/* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
for (int i = 0; i < ops->block_size; i++) {
K[i] ^= 0x6A;
}
/* Feed this result into the outter hash */
ops->hash_init(context);
ops->hash_update(context, (unsigned char *)K, ops->block_size);
ops->hash_update(context, (unsigned char *)digest, ops->digest_size);
ops->hash_final((unsigned char *)digest, context);
/* Zero the key */
memset(K, 0, ops->block_size);
free(K);
}
Variant HHVM_FUNCTION(hash_init, const String& algo,
int64_t options /* = 0 */,
const String& key /* = null_string */) {
HashEnginePtr ops = php_hash_fetch_ops(algo);
if (!ops) {
raise_warning("Unknown hashing algorithm: %s", algo.data());
return false;
}
if ((options & k_HASH_HMAC) && key.empty()) {
raise_warning("HMAC requested without a key");
return false;
}
void *context = malloc(ops->context_size);
ops->hash_init(context);
const auto hash = new HashContext(ops, context, options);
if (options & k_HASH_HMAC) {
hash->key = prepare_hmac_key(ops, context, key);
}
return Resource(hash);
}
bool HHVM_FUNCTION(hash_update, const Resource& context, const String& data) {
HashContext *hash = context.getTyped<HashContext>();
hash->ops->hash_update(hash->context, (unsigned char *)data.data(),
data.size());
return true;
}
Variant HHVM_FUNCTION(hash_final, const Resource& context,
bool raw_output /* = false */) {
HashContext *hash = context.getTyped<HashContext>();
if (hash->context == nullptr) {
raise_warning(
"hash_final(): supplied resource is not a valid Hash Context resource"
);
return false;
}
String raw = String(hash->ops->digest_size, ReserveString);
char *digest = raw.bufferSlice().ptr;
hash->ops->hash_final((unsigned char *)digest, hash->context);
if (hash->options & k_HASH_HMAC) {
finalize_hmac_key(hash->key, hash->ops, hash->context, digest);
hash->key = NULL;
}
free(hash->context);
hash->context = NULL;
raw.setSize(hash->ops->digest_size);
if (raw_output) {
return raw;
}
return f_bin2hex(raw);
}
Resource HHVM_FUNCTION(hash_copy, const Resource& context) {
HashContext *oldhash = context.getTyped<HashContext>();
auto const hash = new HashContext(oldhash);
return Resource(hash);
}
/**
* It is important that the run time of this function is dependent
* only on the length of the user-supplied string.
*
* The only branch in the code below *should* result in non-branching
* machine code.
*
* Do not try to optimize this function.
*/
bool HHVM_FUNCTION(hash_equals, const Variant& known, const Variant& user) {
if (!known.isString()) {
raise_warning(
"hash_equals(): Expected known_string to be a string, %s given",
getDataTypeString(known.getType()).c_str()
);
return false;
}
if (!user.isString()) {
raise_warning(
"hash_equals(): Expected user_string to be a string, %s given",
getDataTypeString(user.getType()).c_str()
);
return false;
}
String known_str = known.toString();
String user_str = user.toString();
const auto known_len = known_str.size();
const auto known_limit = known_len - 1;
const auto user_len = user_str.size();
int64_t result = known_len ^ user_len;
int64_t ki = 0;
for (int64_t ui = 0; ui < user_len; ++ui) {
result |= user_str[ui] ^ known_str[ki];
if (ki < known_limit) {
++ki;
}
}
return (result == 0);
}
int64_t HHVM_FUNCTION(furchash_hphp_ext, const String& key,
int64_t len, int64_t nPart) {
len = std::max<int64_t>(std::min<int64_t>(len, key.size()), 0);
return furc_hash(key.data(), len, nPart);
}
int64_t HHVM_FUNCTION(hphp_murmurhash, const String& key,
int64_t len, int64_t seed) {
len = std::max<int64_t>(std::min<int64_t>(len, key.size()), 0);
return murmur_hash_64A(key.data(), len, seed);
}
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_2264_0 |
crossvul-cpp_data_good_2487_0 | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeLibraryPch.h"
#include "Types/PathTypeHandler.h"
#include "Types/SpreadArgument.h"
namespace Js
{
// Make sure EmptySegment points to read-only memory.
// Can't do this the easy way because SparseArraySegment has a constructor...
static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
// col0 : allocation bucket
// col1 : No. of missing items to set during initialization depending on bucket.
// col2 : allocation size for elements in given bucket.
// col1 and col2 is calculated at runtime
uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
{ 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
{ 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
{ 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
};
#if defined(_M_X64_OR_ARM64)
const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{2, 0, 0},
{6, 0, 0},
{8, 0, 0},
};
uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{4, 0, 0},
{6, 0, 0},
{8, 0, 0},
};
#else
const Var JavascriptArray::MissingItem = (Var)0x80000002;
uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{ 3, 0, 0 },
{ 7, 0, 0 },
{ 8, 0, 0 },
};
uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{ 4, 0, 0 },
{ 8, 0, 0 },
};
#endif
const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
// Allocate enough space for 4 inline property slots and 16 inline element slots
const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
SegmentBTree::SegmentBTree()
: segmentCount(0),
segments(NULL),
keys(NULL),
children(NULL)
{
}
uint32 SegmentBTree::GetLazyCrossOverLimit()
{
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.DisableArrayBTree)
{
return Js::JavascriptArray::InvalidIndex;
}
else if (Js::Configuration::Global.flags.ForceArrayBTree)
{
return ARRAY_CROSSOVER_FOR_VALIDATE;
}
#endif
#ifdef VALIDATE_ARRAY
if (Js::Configuration::Global.flags.ArrayValidate)
{
return ARRAY_CROSSOVER_FOR_VALIDATE;
}
#endif
return SegmentBTree::MinDegree * 3;
}
BOOL SegmentBTree::IsLeaf() const
{
return children == NULL;
}
BOOL SegmentBTree::IsFullNode() const
{
return segmentCount == MaxKeys;
}
void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
{
uint32 i = 0;
for(; i < node->segmentCount; i++)
{
Assert(node->keys[i] == node->segments[i]->left);
if (itemIndex < node->keys[i])
{
break;
}
}
// i indicates the 1st segment in the node past any matching segment.
// the i'th child is the children to the 'left' of the i'th segment.
// If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
if (matches)
{
// Find prev segment
if (node->IsLeaf())
{
if (i > 1)
{
// Previous is either sibling or set in a parent
prev = node->segments[i-2];
}
}
else
{
// prev is the right most leaf in children[i-1] tree
SegmentBTree* child = &node->children[i - 1];
while (!child->IsLeaf())
{
child = &child->children[child->segmentCount];
}
prev = child->segments[child->segmentCount - 1];
}
// Return the matching segment
matchOrNext = node->segments[i-1];
}
else // itemIndex in between segment i-1 and i
{
if (i > 0)
{
// Store in previous in case a match or next is the first segment in a child.
prev = node->segments[i-1];
}
if (node->IsLeaf())
{
matchOrNext = (i == 0 ? node->segments[0] : prev->next);
}
else
{
InternalFind(node->children + i, itemIndex, prev, matchOrNext);
}
}
}
void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
{
prev = matchOrNext = NULL;
InternalFind(this, itemIndex, prev, matchOrNext);
Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
}
void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
{
if (IsFullNode())
{
SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
children[0] = *this;
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
this->segmentCount = 0;
this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
this->children = children;
// This split is the only way the tree gets deeper
SplitChild(recycler, this, 0, &children[0]);
}
InsertNonFullNode(recycler, this, newSeg);
}
void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
{
// Find old segment
uint32 itemIndex = originalKey;
uint32 i = 0;
for(; i < segmentCount; i++)
{
Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
if (itemIndex < keys[i])
{
break;
}
}
// i is 1 past any match
if (i > 0)
{
if (oldSeg == segments[i-1])
{
segments[i-1] = newSeg;
keys[i-1] = newSeg->left;
return;
}
}
Assert(!IsLeaf());
children[i].SwapSegment(originalKey, oldSeg, newSeg);
}
void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
{
// Split child in two, move it's median key up to parent, and put the result of the split
// on either side of the key moved up into parent
Assert(child != NULL);
Assert(parent != NULL);
Assert(!parent->IsFullNode());
Assert(child->IsFullNode());
SegmentBTree newNode;
newNode.segmentCount = MinKeys;
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
// Move the keys above the median into the new node
for(uint32 i = 0; i < MinKeys; i++)
{
newNode.segments[i] = child->segments[i+MinDegree];
newNode.keys[i] = child->keys[i+MinDegree];
// Do not leave false positive references around in the b-tree
child->segments[i+MinDegree] = NULL;
}
// If children exist move those as well.
if (!child->IsLeaf())
{
newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
for(uint32 j = 0; j < MinDegree; j++)
{
newNode.children[j] = child->children[j+MinDegree];
// Do not leave false positive references around in the b-tree
child->children[j+MinDegree].segments = NULL;
child->children[j+MinDegree].children = NULL;
}
}
child->segmentCount = MinKeys;
// Make room for the new child in parent
for(uint32 j = parent->segmentCount; j > iChild; j--)
{
parent->children[j+1] = parent->children[j];
}
// Copy the contents of the new node into the correct place in the parent's child array
parent->children[iChild+1] = newNode;
// Move the keys to make room for the median key
for(uint32 k = parent->segmentCount; k > iChild; k--)
{
parent->segments[k] = parent->segments[k-1];
parent->keys[k] = parent->keys[k-1];
}
// Move the median key into the proper place in the parent node
parent->segments[iChild] = child->segments[MinKeys];
parent->keys[iChild] = child->keys[MinKeys];
// Do not leave false positive references around in the b-tree
child->segments[MinKeys] = NULL;
parent->segmentCount++;
}
void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
{
Assert(!node->IsFullNode());
AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
Assert(newSeg != NULL);
if (node->IsLeaf())
{
// Move the keys
uint32 i = node->segmentCount - 1;
while( (i != -1) && (newSeg->left < node->keys[i]))
{
node->segments[i+1] = node->segments[i];
node->keys[i+1] = node->keys[i];
i--;
}
if (!node->segments)
{
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
}
node->segments[i + 1] = newSeg;
node->keys[i + 1] = newSeg->left;
node->segmentCount++;
}
else
{
// find the correct child node
uint32 i = node->segmentCount-1;
while((i != -1) && (newSeg->left < node->keys[i]))
{
i--;
}
i++;
// Make room if full
if(node->children[i].IsFullNode())
{
// This split doesn't make the tree any deeper as node already has children.
SplitChild(recycler, node, i, node->children+i);
Assert(node->keys[i] == node->segments[i]->left);
if (newSeg->left > node->keys[i])
{
i++;
}
}
InsertNonFullNode(recycler, node->children+i, newSeg);
}
}
inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
{
if (IsThrowTypeError(operationSucceeded))
{
ThrowTypeErrorOnFailure();
}
}
inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
{
JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
}
inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
{
return !operationSucceeded;
}
// Make sure EmptySegment points to read-only memory.
// Can't do this the easy way because SparseArraySegment has a constructor...
JavascriptArray::JavascriptArray(DynamicType * type)
: ArrayObject(type, false, 0)
{
Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
}
JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
: ArrayObject(type, false, length)
{
Assert(JavascriptArray::Is(type->GetTypeId()));
Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
}
JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
: ArrayObject(type, false, length)
{
Assert(type->GetTypeId() == TypeIds_Array);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
: ArrayObject(type, false)
{
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
head->size = size;
Var fill = Js::JavascriptArray::MissingItem;
for (uint i = 0; i < size; i++)
{
((SparseArraySegment<Var>*)head)->elements[i] = fill;
}
}
JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
: JavascriptNativeArray(type)
{
Assert(type->GetTypeId() == TypeIds_NativeIntArray);
this->length = length;
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
: JavascriptNativeArray(type)
{
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
head->size = size;
((SparseArraySegment<int32>*)head)->FillSegmentBuffer(0, size);
}
JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
: JavascriptNativeArray(type)
{
Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
this->length = length;
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
: JavascriptNativeArray(type)
{
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
head->size = size;
((SparseArraySegment<double>*)head)->FillSegmentBuffer(0, size);
}
bool JavascriptArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptArray::Is(typeId);
}
bool JavascriptArray::Is(TypeId typeId)
{
return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
}
bool JavascriptArray::IsVarArray(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptArray::IsVarArray(typeId);
}
bool JavascriptArray::IsVarArray(TypeId typeId)
{
return typeId == TypeIds_Array;
}
template<typename T>
bool JavascriptArray::IsMissingItemAt(uint32 index) const
{
SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)this->head;
return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
}
bool JavascriptArray::IsMissingItem(uint32 index)
{
if (this->length <= index)
{
return false;
}
bool isIntArray = false, isFloatArray = false;
this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
if (isIntArray)
{
return IsMissingItemAt<int32>(index);
}
else if (isFloatArray)
{
return IsMissingItemAt<double>(index);
}
else
{
return IsMissingItemAt<Var>(index);
}
}
JavascriptArray* JavascriptArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
}
// Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
{
AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
}
// Check if a Var is a direct-accessible (fast path) JavascriptArray.
bool JavascriptArray::IsDirectAccessArray(Var aValue)
{
return RecyclableObject::Is(aValue) &&
(VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
}
DynamicObjectFlags JavascriptArray::GetFlags() const
{
return GetArrayFlags();
}
DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
{
return GetArrayFlags_Unchecked();
}
void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
{
SetArrayFlags(flags);
}
DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetArrayType();
}
JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
{
bool isObjectWithArray;
TypeId arrayTypeId;
return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
}
JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
const Var var,
bool *const isObjectWithArrayRef,
TypeId *const arrayTypeIdRef)
{
// This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
// (see Lowerer::GenerateArrayTest) to minimize bailouts.
Assert(var);
Assert(isObjectWithArrayRef);
Assert(arrayTypeIdRef);
*isObjectWithArrayRef = false;
*arrayTypeIdRef = TypeIds_Undefined;
if(!RecyclableObject::Is(var))
{
return nullptr;
}
JavascriptArray *array = nullptr;
INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
if(vtable == VirtualTableInfo<DynamicObject>::Address)
{
ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
if(!array)
{
return nullptr;
}
*isObjectWithArrayRef = true;
vtable = VirtualTableInfoBase::GetVirtualTable(array);
}
if(vtable == VirtualTableInfo<JavascriptArray>::Address)
{
*arrayTypeIdRef = TypeIds_Array;
}
else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
{
*arrayTypeIdRef = TypeIds_NativeIntArray;
}
else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
{
*arrayTypeIdRef = TypeIds_NativeFloatArray;
}
else
{
return nullptr;
}
if(!array)
{
array = FromVar(var);
}
return array;
}
const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
{
// This is a helper function used by jitted code
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
return array ? array->head : nullptr;
}
uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
{
// This is a helper function used by jitted code
return headSegment ? headSegment->length : 0;
}
bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
const SparseArraySegmentBase *const headSegmentBeforeOperation,
const uint32 headSegmentLengthBeforeOperation,
const Var varAfterOperation)
{
// This is a helper function used by jitted code
Assert(varAfterOperation);
if(!headSegmentBeforeOperation)
{
return false;
}
const SparseArraySegmentBase *const headSegmentAfterOperation =
Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
return
headSegmentAfterOperation != headSegmentBeforeOperation ||
headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
}
uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
{
// This is a helper function used by jitted code
bool isObjectWithArray;
TypeId arrayTypeId;
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
return array && !isObjectWithArray ? array->GetLength() : 0;
}
bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
{
// This is a helper function used by jitted code
return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
}
DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
{
// This is a helper function used by jitted code
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
}
bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
const DynamicObjectFlags flagsBeforeOperation,
const Var varAfterOperation)
{
// This is a helper function used by jitted code
Assert(varAfterOperation);
return
!!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
!(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
}
bool JavascriptArray::HasNoMissingValues() const
{
return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
}
bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
{
return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
}
void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
{
SetFlags(
hasNoMissingValues
? GetFlags() | DynamicObjectFlags::HasNoMissingValues
: GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
}
template<class T>
bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
{
Assert(index < head->length);
return SparseArraySegment<T>::IsMissingItem(&static_cast<SparseArraySegment<T> *>(head)->elements[index]);
}
bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<Var>(index);
}
#if ENABLE_COPYONACCESS_ARRAY
void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
{
Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
#if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
{
Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
Output::Flush();
}
#endif
newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
this->SetHeadAndLastUsedSegment(newSeg);
VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
{
arrayInfo->isNotCopyOnAccessArray = 1;
}
}
uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
{
if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
{
return Js::JavascriptArray::InvalidIndex;
}
else if (index == Js::JavascriptArray::InvalidIndex)
{
return 0;
}
else
{
return index + 1;
}
}
BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
{
Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
{
return FALSE;
}
else
{
*outVal = seg->elements[index];
return TRUE;
}
}
#endif
bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<int32>(index);
}
bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<double>(index);
}
template<typename T>
void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const T& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
{
RecyclableObject* prototype = srcArray->GetPrototype();
while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
T n = dstIndex + (index - start);
dstArray->DirectSetItemAt(n, value);
count++;
});
prototype = prototype->GetPrototype();
}
}
template<>
void JavascriptArray::InternalFillFromPrototype<uint32>(JavascriptArray *dstArray, const uint32& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
{
RecyclableObject* prototype = srcArray->GetPrototype();
while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
uint32 n = dstIndex + (index - start);
dstArray->SetItem(n, value, PropertyOperation_None);
count++;
});
prototype = prototype->GetPrototype();
}
}
/* static */
bool JavascriptArray::HasInlineHeadSegment(uint32 length)
{
return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
}
Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
}
Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(elementCount <= head->length);
js_memcpy_s(head->elements, sizeof(Var) * head->length, elements, sizeof(Var) * elementCount);
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return arr;
}
Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
array->SetHasNoMissingValues(false);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)array->head;
head->FillSegmentBuffer(0, elementCount);
return array;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
return arr;
}
#endif
Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
{
uint32 count = ints->count;
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
}
return arr;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
// Called only to create array literals: size is known.
uint32 count = ints->count;
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary *lib = scriptContext->GetLibrary();
FunctionBody *functionBody = weakFuncRef->Get();
if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
{
Assert(lib->cacheForCopyOnAccessArraySegments);
arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
}
else
#endif
{
arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
SparseArraySegment<int32> *head = static_cast<SparseArraySegment<int32>*>(arr->head);
Assert(count > 0 && count == head->length);
js_memcpy_s(head->elements, sizeof(int32)* head->length, ints->elements, sizeof(int32)* count);
}
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
head->elements[i] = (double)ints->elements[i];
}
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return OP_NewScIntArray(ints, scriptContext);
}
#endif
Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
{
uint32 count = doubles->count;
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
double dval = doubles->elements[i];
int32 ival;
if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
{
head->elements[i] = TaggedInt::ToVarUnchecked(ival);
}
else
{
head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
}
}
return arr;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
// Called only to create array literals: size is known.
if (arrayInfo->IsNativeFloatArray())
{
arrayInfo->SetIsNotNativeIntArray();
uint32 count = doubles->count;
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
Assert(count > 0 && count == head->length);
js_memcpy_s(head->elements, sizeof(double) * head->length, doubles->elements, sizeof(double) * count);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return OP_NewScFltArray(doubles, scriptContext);
}
Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
Assert(JavascriptFunction::Is(function) &&
JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
Assert(callInfo.Count >= 2);
ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(elementCount);
}
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(uvalue);
}
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
}
pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
#endif
Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
{
// Call to new Array(), possibly under another name.
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
// SkipDefaultNewObject function flag should have prevented the default object
// being created, except when call true a host dispatch.
const CallInfo &callInfo = args.Info;
Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
|| JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
ScriptContext* scriptContext = function->GetScriptContext();
JavascriptArray* pNew = nullptr;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
return isCtorSuperCall ?
JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
pNew;
}
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = CreateArrayFromConstructor(function, 1, scriptContext);
JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
// If we were passed an uninitialized JavascriptArray as the this argument,
// we need to set the length. We must do this _after_ setting the first
// element as the array may have side effects such as a setter for property
// named '0' which would make the previous length of the array observable.
// If we weren't passed a JavascriptArray as the this argument, this is no-op.
pNew->SetLength(1);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return isCtorSuperCall ?
JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
pNew;
}
JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
{
JavascriptLibrary* library = constructor->GetLibrary();
// Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
// Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
// This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
// constructor.
return library->CreateArray(length);
}
JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
{
JavascriptLibrary* library = constructor->GetLibrary();
return library->CreateArray();
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
Assert(JavascriptFunction::Is(function) &&
JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return scriptContext->GetLibrary()->CreateArray();
}
#endif
Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
{
Assert(!PHASE_OFF1(NativeArrayPhase));
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
const CallInfo &callInfo = args.Info;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
return function->GetLibrary()->CreateNativeIntArray();
}
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
{
Assert(!PHASE_OFF1(NativeArrayPhase));
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
const CallInfo &callInfo = args.Info;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
return function->GetLibrary()->CreateNativeFloatArray();
}
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
bool isTaggedInt = TaggedInt::Is(item);
bool isTaggedIntMissingValue = false;
#ifdef _M_AMD64
if (isTaggedInt)
{
int32 iValue = TaggedInt::ToInt32(item);
isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
}
#endif
if (isTaggedInt && !isTaggedIntMissingValue)
{
// This is taggedInt case and we verified that item is not missing value in AMD64.
this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
}
else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
{
double dvalue = JavascriptNumber::GetValue(item);
int32 ivalue;
if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
{
this->DirectSetItemAt(i, ivalue);
}
else
{
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeIntArray();
}
#endif
if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
{
// Avoid shrinking the number of elements in the head segment. We can still create a new
// array here, so go ahead.
JavascriptNativeFloatArray *fArr =
this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
}
JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
fArr->DirectSetItemAt(i, dvalue);
#if ENABLE_PROFILE_INFO
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
#else
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
#endif
}
}
else
{
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeArray();
}
#endif
#pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
{
// Avoid shrinking the number of elements in the head segment. We can still create a new
// array here, so go ahead.
JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
return arr->JavascriptArray::FillFromArgs(length, 0, args);
}
JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
#if ENABLE_PROFILE_INFO
return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
#else
return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
#endif
}
}
return this;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
if (TaggedInt::Is(item))
{
this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
{
this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
}
else
{
JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeArray();
}
return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
#else
return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
#endif
}
}
return this;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint32 i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
this->DirectSetItemAt(i, item);
}
return this;
}
DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetNativeIntArrayType();
}
#if ENABLE_COPYONACCESS_ARRAY
DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
}
#endif
JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(intArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Float array"));
Output::Flush();
}
#endif
arrayInfo->SetIsNotNativeIntArray();
}
#endif
// Grow the segments
ScriptContext *scriptContext = intArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = intArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
int i;
int32 ival;
// The old segment will have size/2 and length capped by the new size.
seg->size >>= 1;
if (seg == intArray->head || seg->length > (seg->size >>= 1))
{
// Some live elements are being pushed out of this segment, so allocate a new one.
SparseArraySegment<double> *newSeg =
SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
Assert(newSeg != nullptr);
Assert((prevSeg == nullptr) == (seg == intArray->head));
newSeg->next = nextSeg;
intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
if (intArray->GetLastUsedSegment() == seg)
{
intArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = intArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
// Fill the new segment with the overflow.
for (i = 0; (uint)i < newSeg->length; i++)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
if (ival == JavascriptNativeIntArray::MissingItem)
{
continue;
}
newSeg->elements[i] = (double)ival;
}
}
else
{
// Now convert the contents that will remain in the old segment.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
}
else
{
((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
}
}
prevSeg = seg;
}
}
if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
{
intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
else
{
if (intArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
}
else
{
intArray->ChangeType();
}
}
intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
}
if (CrossSite::IsCrossSiteObjectTyped(intArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
}
return (JavascriptNativeFloatArray*)intArray;
}
/*
* JavascriptArray::ChangeArrayTypeToNativeArray<double>
* - Converts the Var Array's type to NativeFloat.
* - Sets the VirtualTable to "JavascriptNativeFloatArray"
*/
template<>
void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
{
varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
else
{
if (varArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
}
else
{
varArray->ChangeType();
}
}
varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
}
if (CrossSite::IsCrossSiteObjectTyped(varArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
}
else
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
}
}
/*
* JavascriptArray::ChangeArrayTypeToNativeArray<int32>
* - Converts the Var Array's type to NativeInt.
* - Sets the VirtualTable to "JavascriptNativeIntArray"
*/
template<>
void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
{
varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
}
else
{
if (varArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
}
else
{
varArray->ChangeType();
}
}
varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
}
if (CrossSite::IsCrossSiteObjectTyped(varArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
}
else
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
}
}
template<>
int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
{
return JavascriptConversion::ToInt32(ival, scriptContext);
}
template <>
double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
{
return JavascriptConversion::ToNumber(ival, scriptContext);
}
/*
* JavascriptArray::ConvertToNativeArrayInPlace
* In place conversion of all Var elements to Native Int/Double elements in an array.
* We do not update the DynamicProfileInfo of the array here.
*/
template<typename NativeArrayType, typename T>
NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
ScriptContext *scriptContext = varArray->GetScriptContext();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = varArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
int i;
Var ival;
uint32 growFactor = sizeof(Var) / sizeof(T);
AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
// Now convert the contents that will remain in the old segment.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<Var>*)seg)->elements[i];
if (ival == JavascriptArray::MissingItem)
{
((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
}
else
{
((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
}
}
prevSeg = seg;
}
// Update the type of the Array
ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
return (NativeArrayType*)varArray;
}
JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
#endif
ScriptContext *scriptContext = intArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = intArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
int i;
int32 ival;
// Shrink?
uint32 growFactor = sizeof(Var) / sizeof(int32);
if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size /= growFactor))) ||
(seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
{
// Some live elements are being pushed out of this segment, so allocate a new one.
// And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
SparseArraySegment<Var> *newSeg =
SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
AnalysisAssert(newSeg);
Assert((prevSeg == nullptr) == (seg == intArray->head));
newSeg->next = nextSeg;
intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
if (intArray->GetLastUsedSegment() == seg)
{
intArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = intArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
// Fill the new segment with the overflow.
for (i = 0; (uint)i < newSeg->length; i++)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
continue;
}
newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
}
}
else
{
// Now convert the contents that will remain in the old segment.
// Walk backward in case we're growing the element size.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
}
else
{
((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
}
}
prevSeg = seg;
}
}
if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
{
intArray->type = scriptContext->GetLibrary()->GetArrayType();
}
else
{
if (intArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
}
else
{
intArray->ChangeType();
}
}
intArray->GetType()->SetTypeId(TypeIds_Array);
}
if (CrossSite::IsCrossSiteObjectTyped(intArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
}
return intArray;
}
JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(intArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Var array"));
Output::Flush();
}
#endif
arrayInfo->SetIsNotNativeArray();
}
#endif
intArray->ClearArrayCallSiteIndex();
return ConvertToVarArray(intArray);
}
DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
/*
* JavascriptNativeFloatArray::ConvertToVarArray
* This function only converts all Float elements to Var elements in an array.
* DynamicProfileInfo of the array is not updated in this function.
*/
JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
{
// We can't be growing the size of the element.
Assert(sizeof(double) >= sizeof(Var));
uint32 shrinkFactor = sizeof(double) / sizeof(Var);
ScriptContext *scriptContext = fArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = fArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
if (seg->size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
SparseArraySegment<Var> *newSeg;
if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
{
// The old segment is not scanned by the recycler, so we need a new one to hold vars.
newSeg =
SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
Assert((prevSeg == nullptr) == (seg == fArray->head));
newSeg->next = nextSeg;
fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
if (fArray->GetLastUsedSegment() == seg)
{
fArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = fArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
}
else
{
newSeg = (SparseArraySegment<Var>*)seg;
prevSeg = seg;
if (shrinkFactor != 1)
{
uint32 newSize = seg->size * shrinkFactor;
uint32 limit;
if (seg->next)
{
limit = seg->next->left;
}
else
{
limit = JavascriptArray::MaxArrayLength;
}
seg->size = min(newSize, limit - seg->left);
}
}
uint32 i;
for (i = 0; i < seg->length; i++)
{
if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
{
if (seg == newSeg)
{
newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
}
Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
}
else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
{
newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
}
else
{
int32 ival;
double dval = ((SparseArraySegment<double>*)seg)->elements[i];
if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
{
newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
}
else
{
newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
}
}
}
if (seg == newSeg && shrinkFactor != 1)
{
// Fill the remaining slots.
newSeg->FillSegmentBuffer(i, seg->size);
}
}
if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
{
fArray->type = scriptContext->GetLibrary()->GetArrayType();
}
else
{
if (fArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
}
else
{
fArray->ChangeType();
}
}
fArray->GetType()->SetTypeId(TypeIds_Array);
}
if (CrossSite::IsCrossSiteObjectTyped(fArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
}
return fArray;
}
JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(fArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Float array to Var array"));
Output::Flush();
}
#endif
if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
{
Assert(!arrayInfo->IsNativeIntArray());
}
arrayInfo->SetIsNotNativeArray();
}
#endif
fArray->ClearArrayCallSiteIndex();
return ConvertToVarArray(fArray);
}
// Convert Var to index in the Array.
// Note: Spec calls out a few rules for these parameters:
// 1. if (arg > length) { return length; }
// clamp to length, not length-1
// 2. if (arg < 0) { return max(0, length + arg); }
// treat negative arg as index from the end of the array (with -1 mapping to length-1)
// Effectively, this function will return a value between 0 and length, inclusive.
int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
{
int64 index;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue < 0)
{
index = max<int64>(0, length + intValue);
}
else
{
index = intValue;
}
if (index > length)
{
index = length;
}
}
else
{
double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
// Handle the Number.POSITIVE_INFINITY case
if (doubleValue > length)
{
return length;
}
index = NumberUtilities::TryToInt64(doubleValue);
if (index < 0)
{
index = max<int64>(0, index + length);
}
}
return index;
}
TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
{
int32 iValue;
double dValue;
TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
if (typeId == TypeIds_NativeIntArray)
{
arr->SetArrayLiteralItem(index, iValue);
}
else if (typeId == TypeIds_NativeFloatArray)
{
arr->SetArrayLiteralItem(index, dValue);
}
else
{
arr->SetArrayLiteralItem(index, value);
}
return typeId;
}
TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
{
double dValue;
TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
if (typeId == TypeIds_NativeFloatArray)
{
arr->SetArrayLiteralItem(index, dValue);
}
else
{
arr->SetArrayLiteralItem(index, value);
}
return typeId;
}
template<typename T>
void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
{
SparseArraySegment<T> * segment = (SparseArraySegment<T>*)this->head;
Assert(segment->left == 0);
Assert(index < segment->length);
segment->elements[index] = value;
}
void JavascriptNativeIntArray::SetIsPrototype()
{
// Force the array to be non-native to simplify inspection, filling from proto, etc.
ToVarArray(this);
__super::SetIsPrototype();
}
void JavascriptNativeFloatArray::SetIsPrototype()
{
// Force the array to be non-native to simplify inspection, filling from proto, etc.
ToVarArray(this);
__super::SetIsPrototype();
}
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
{
RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
if (weakRef)
{
FunctionBody *functionBody = weakRef->Get();
if (functionBody)
{
if (functionBody->HasDynamicProfileInfo())
{
Js::ProfileId profileId = this->GetArrayCallSiteIndex();
if (profileId < functionBody->GetProfiledArrayCallSiteCount())
{
return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
}
}
}
else
{
this->ClearArrayCallSiteIndex();
}
}
return nullptr;
}
void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
{
Assert(weakRef);
FunctionBody *functionBody = weakRef->Get();
if (functionBody && functionBody->HasDynamicProfileInfo())
{
ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
Assert(index < functionBody->GetProfiledArrayCallSiteCount());
SetArrayCallSite(index, weakRef);
}
}
void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
{
if (baseArray->weakRefToFuncBody)
{
if (baseArray->weakRefToFuncBody->Get())
{
SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
}
else
{
baseArray->ClearArrayCallSiteIndex();
}
}
}
#endif
Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
{
if (JavascriptNativeIntArray::Is(this))
{
return this->FindMinOrMax<int32, false>(scriptContext, findMax);
}
else
{
return this->FindMinOrMax<double, true>(scriptContext, findMax);
}
}
template <typename T, bool checkNaNAndNegZero>
Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
{
AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
uint len = this->GetLength();
Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
uint headSegLen = headSegment->length;
Assert(headSegLen == len);
if (headSegment->next == nullptr)
{
T currentRes = headSegment->elements[0];
for (uint i = 0; i < headSegLen; i++)
{
T compare = headSegment->elements[i];
if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
{
return scriptContext->GetLibrary()->GetNaN();
}
if (findMax ? currentRes < compare : currentRes > compare ||
(checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
{
currentRes = compare;
}
}
return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
}
else
{
AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
Throw::FatalInternalError();
}
}
SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
{
return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot->lastUsedSegment : segmentUnion.lastUsedSegment);
}
void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
{
Assert(!HasSegmentMap());
this->head = this->segmentUnion.lastUsedSegment = segment;
}
void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
{
if (HasSegmentMap())
{
this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
}
else
{
this->segmentUnion.lastUsedSegment = segment;
}
}
bool JavascriptArray::HasSegmentMap() const
{
return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
}
SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
{
return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
}
void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
{
Assert(!HasSegmentMap());
SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
segmentUnion.segmentBTreeRoot = segmentMap;
segmentMap->lastUsedSegment = lastUsedSeg;
}
void JavascriptArray::ClearSegmentMap()
{
if (HasSegmentMap())
{
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
segmentUnion.segmentBTreeRoot = nullptr;
segmentUnion.lastUsedSegment = lastUsedSeg;
}
}
SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
{
Recycler* recycler = GetRecycler();
SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
{
tmpSegmentMap->Add(recycler, current);
return false;
});
// There could be OOM during building segment map. Save to array only after its successful completion.
SetSegmentMap(tmpSegmentMap);
return tmpSegmentMap;
}
void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
{
SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
if (savedSegmentMap)
{
//
// We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
// array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
// if adding segment succeeds.
//
ClearSegmentMap();
savedSegmentMap->Add(recycler, seg);
SetSegmentMap(savedSegmentMap);
}
}
void JavascriptArray::InvalidateLastUsedSegment()
{
this->SetLastUsedSegment(this->head);
}
DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
{
DescriptorFlags flags;
if (GetSetterBuiltIns(propertyId, info, &flags))
{
return flags;
}
return __super::GetSetter(propertyId, setterValue, info, requestContext);
}
DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
{
DescriptorFlags flags;
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
{
return flags;
}
return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
}
bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
{
if (propertyId == PropertyIds::length)
{
PropertyValueInfo::SetNoCache(info, this);
*descriptorFlags = WritableData;
return true;
}
return false;
}
SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
{
SparseArraySegmentBase *seg = nullptr;
SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
{
seg = lastUsedSeg;
if(index - lastUsedSeg->left < lastUsedSeg->size)
{
return seg;
}
}
SegmentBTreeRoot * segmentMap = GetSegmentMap();
if(!useSegmentMap || !segmentMap)
{
return seg ? seg : this->head;
}
if(seg)
{
// If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
// segment map, as it is likely to hit
SparseArraySegmentBase *const nextSeg = seg->next;
if(nextSeg)
{
if(index < nextSeg->left)
{
return seg;
}
else if(index - nextSeg->left < nextSeg->size)
{
return nextSeg;
}
}
}
SparseArraySegmentBase *matchOrNextSeg;
segmentMap->Find(index, seg, matchOrNextSeg);
return seg ? seg : matchOrNextSeg;
}
uint32 JavascriptArray::GetNextIndex(uint32 index) const
{
if (JavascriptNativeIntArray::Is((Var)this))
{
return this->GetNextIndexHelper<int32>(index);
}
else if (JavascriptNativeFloatArray::Is((Var)this))
{
return this->GetNextIndexHelper<double>(index);
}
return this->GetNextIndexHelper<Var>(index);
}
template<typename T>
uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
{
AssertMsg(this->head, "array head should never be null");
uint candidateIndex;
if (index == JavascriptArray::InvalidIndex)
{
candidateIndex = head->left;
}
else
{
candidateIndex = index + 1;
}
SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
while (current != nullptr)
{
if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
{
for (uint i = candidateIndex - current->left; i < current->length; i++)
{
if (!SparseArraySegment<T>::IsMissingItem(¤t->elements[i]))
{
return i + current->left;
}
}
}
current = (SparseArraySegment<T>*)current->next;
if (current != NULL)
{
if (candidateIndex < current->left)
{
candidateIndex = current->left;
}
}
}
return JavascriptArray::InvalidIndex;
}
// If new length > length, we just reset the length
// If new length < length, we need to remove the rest of the elements and segment
void JavascriptArray::SetLength(uint32 newLength)
{
if (newLength == length)
return;
if (head == EmptySegment)
{
// Do nothing to the segment.
}
else if (newLength == 0)
{
this->ClearElements(head, 0);
head->length = 0;
head->next = nullptr;
SetHasNoMissingValues();
ClearSegmentMap();
this->InvalidateLastUsedSegment();
}
else if (newLength < length)
{
// _ _ 2 3 _ _ 6 7 _ _
// SetLength(0)
// 0 <= left -> set *prev = null
// SetLength(2)
// 2 <= left -> set *prev = null
// SetLength(3)
// 3 !<= left; 3 <= right -> truncate to length - 1
// SetLength(5)
// 5 <=
SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
SparseArraySegmentBase** prev = &head;
while(next != nullptr)
{
if (newLength <= next->left)
{
ClearSegmentMap(); // truncate segments, null out segmentMap
*prev = nullptr;
break;
}
else if (newLength <= (next->left + next->length))
{
if (next->next)
{
ClearSegmentMap(); // Will truncate segments, null out segmentMap
}
uint32 newSegmentLength = newLength - next->left;
this->ClearElements(next, newSegmentLength);
next->next = nullptr;
next->length = newSegmentLength;
break;
}
else
{
prev = &next->next;
next = next->next;
}
}
this->InvalidateLastUsedSegment();
}
this->length = newLength;
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
}
BOOL JavascriptArray::SetLength(Var newLength)
{
ScriptContext *scriptContext;
if(TaggedInt::Is(newLength))
{
int32 lenValue = TaggedInt::ToInt32(newLength);
if (lenValue < 0)
{
scriptContext = GetScriptContext();
if (scriptContext->GetThreadContext()->RecordImplicitException())
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
else
{
this->SetLength(lenValue);
}
return TRUE;
}
scriptContext = GetScriptContext();
uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
if (dblValue == uintValue)
{
this->SetLength(uintValue);
}
else
{
ThreadContext* threadContext = scriptContext->GetThreadContext();
ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
{
// We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
// Do nothing and let the jitted code bail out.
return TRUE;
}
if (threadContext->RecordImplicitException())
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
return TRUE;
}
void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
Var JavascriptArray::DirectGetItem(uint32 index)
{
SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
{
return seg->elements[offset];
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
{
return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
int32 value = 0;
return this->DirectGetItemAt(index, &value) ? WritableData : None;
}
Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
{
SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
{
return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
{
PropertyRecord const * propertyRecord;
scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
}
BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
if (this->DirectGetItemAt(index, outVal))
{
return TRUE;
}
ScriptContext* requestContext = type->GetScriptContext();
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
//
// Link prev and current. If prev is NULL, make current the head segment.
//
void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
{
if (prev)
{
prev->next = current;
}
else
{
Assert(current);
head = current;
}
}
template<typename T>
BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
{
if (itemIndex >= length)
{
return true;
}
SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
while(next != nullptr && next->left <= itemIndex)
{
uint32 limit = next->left + next->length;
if (itemIndex < limit)
{
next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
if(itemIndex - next->left == next->length - 1)
{
--next->length;
}
else if(next == head)
{
SetHasNoMissingValues(false);
}
break;
}
next = (SparseArraySegment<T>*)next->next;
}
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
return true;
}
template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
{
return idxDest.ToNumber(scriptContext);
}
template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
{
// Note this is only for setting Array length which is a uint32
return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
}
template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
{
return JavascriptNumber::ToVar(idxDest, scriptContext);
}
void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
{
if (!succeeded)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
}
}
void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
{
if (!succeeded)
{
uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
}
}
BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
{
return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
}
BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
{
ScriptContext* scriptContext = pDestObj->GetScriptContext();
if (idxDest.IsSmallIndex())
{
return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
}
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
}
template<typename T>
void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest, BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength)
{
// This never gets called.
Throw::InternalError();
}
//
// Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
//
template<typename T>
void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest, BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength)
{
JavascriptArray* pDestArray = nullptr;
if (JavascriptArray::Is(pDestObj))
{
pDestArray = JavascriptArray::FromVar(pDestObj);
}
T idxDest = startIdxDest;
for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
BOOL spreadable = false;
if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
{
// firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
// we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
// want to do the work a second time as soon as we record the length we clear the flag.
spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem);
if (!spreadable)
{
JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
++idxDest;
continue;
}
}
if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
&& BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex()) // Fast path
{
if (JavascriptNativeIntArray::Is(aItem))
{
JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
CopyNativeIntArrayElementsToVar(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else if (JavascriptNativeFloatArray::Is(aItem))
{
JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
CopyNativeFloatArrayElementsToVar(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else
{
JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
CopyArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
}
else
{
// Flatten if other array or remote array (marked with TypeIds_Array)
if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
{
//CONSIDER: enumerating remote array instead of walking all indices
BigIndex length;
if (firstPromotedItemIsSpreadable)
{
firstPromotedItemIsSpreadable = false;
length = firstPromotedItemLength;
}
else if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
// we can cast to uin64 without fear of converting negative numbers to large positive ones
// from int64 because ToLength makes negative lengths 0
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
}
if (PromoteToBigIndex(length,idxDest))
{
// This is a special case for spreadable objects. We do not pre-calculate the length
// in EntryConcat like we do with Arrays because a getProperty on an object Length
// is observable. The result is we have to check for overflows separately for
// spreadable objects and promote to a bigger index type when we find them.
ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
return;
}
if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
}
RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
Var subItem;
uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
{
if (JavascriptOperators::HasItem(itemObject, idxSubItem))
{
subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext);
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, subItem);
}
else
{
ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest);
}
}
++idxDest;
}
for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
{
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
if (JavascriptOperators::HasProperty(itemObject,propertyRecord->GetPropertyId()))
{
subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext);
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, subItem);
}
else
{
ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem);
}
}
++idxDest;
}
}
else // concat 1 item
{
JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
++idxDest;
}
}
}
if (!pDestArray)
{
pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr);
}
else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
{
pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
}
}
bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
{
return false; // already a big index
}
bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
{
::Math::RecordOverflowPolicy destLengthOverflow;
if (lhs.IsSmallIndex())
{
UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
return destLengthOverflow.HasOverflowed();
}
return true;
}
JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
{
uint idxDest = 0u;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
bool concatSpreadable = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem);
if (!JavascriptNativeIntArray::Is(pDestArray))
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pDestArray;
}
if(!concatSpreadable)
{
pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
idxDest = idxDest + 1;
if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
continue;
}
if (JavascriptNativeIntArray::Is(aItem)) // Fast path
{
JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
if (converted)
{
// Copying the last array forced a conversion, so switch over to the var version
// to finish.
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
}
else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
{
if (TaggedInt::Is(aItem))
{
pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
}
else
{
#if DBG
int32 int32Value;
Assert(
JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
!SparseArraySegment<int32>::IsMissingItem(&int32Value));
#endif
pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
}
++idxDest;
}
else
{
JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pVarDestArray;
}
}
if (pDestArray->GetLength() != idxDest)
{
pDestArray->SetLength(idxDest);
}
return pDestArray;
}
JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
{
uint idxDest = 0u;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
bool concatSpreadable = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem);
if (!JavascriptNativeFloatArray::Is(pDestArray))
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pDestArray;
}
if (!concatSpreadable)
{
pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
idxDest = idxDest + 1;
if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
continue;
}
bool converted;
if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
{
if (JavascriptNativeIntArray::Is(aItem)) // Fast path
{
JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray);
idxDest = idxDest + pIntArray->length;
}
else if (JavascriptNativeFloatArray::Is(aItem))
{
JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else
{
JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pVarDestArray;
}
if (converted)
{
// Copying the last array forced a conversion, so switch over to the var version
// to finish.
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
}
else
{
if (TaggedInt::Is(aItem))
{
pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
}
else
{
Assert(JavascriptNumber::Is(aItem));
pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
}
++idxDest;
}
}
if (pDestArray->GetLength() != idxDest)
{
pDestArray->SetLength(idxDest);
}
return pDestArray;
}
bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
{
return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
}
Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
}
//
// Compute the destination ScriptArray size:
// - Each item, flattening only one level if a ScriptArray.
//
uint32 cDestLength = 0;
JavascriptArray * pDestArray = NULL;
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
bool isInt = true;
bool isFloat = true;
::Math::RecordOverflowPolicy destLengthOverflow;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
#endif
if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
{
JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
if (isFloat)
{
if (!JavascriptNativeIntArray::Is(pItemArray))
{
isInt = false;
if (!JavascriptNativeFloatArray::Is(pItemArray))
{
isFloat = false;
}
}
}
cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
}
else // Get remote array or object length
{
// We already checked for types derived from JavascriptArray. These are types that should behave like array
// i.e. proxy to array and remote array.
if (JavascriptOperators::IsArray(aItem))
{
// Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
// worth it.
isInt = false;
isFloat = false;
if (!JavascriptProxy::Is(aItem))
{
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
// clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
}
else
{
uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
}
}
remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
}
else
{
if (isFloat)
{
if (BoxConcatItem(aItem, idxArg, scriptContext))
{
// A primitive will be boxed, so we have to create a var array for the result.
isInt = false;
isFloat = false;
}
else if (!TaggedInt::Is(aItem))
{
if (!JavascriptNumber::Is(aItem))
{
isInt = false;
isFloat = false;
}
else if (isInt)
{
int32 int32Value;
if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
SparseArraySegment<int32>::IsMissingItem(&int32Value))
{
isInt = false;
}
}
}
else if(isInt)
{
int32 int32Value = TaggedInt::ToInt32(aItem);
if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
{
isInt = false;
}
}
}
remoteTypeIds[idxArg] = TypeIds_Limit;
cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
}
}
}
if (destLengthOverflow.HasOverflowed())
{
cDestLength = MaxArrayLength;
isInt = false;
isFloat = false;
}
//
// Create the destination array
//
RecyclableObject* pDestObj = nullptr;
bool isArray = false;
pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext);
if (pDestObj)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
#endif
// Check the thing that species create made. If it's a native array that can't handle the source
// data, convert it. If it's a more conservative kind of array than the source data, indicate that
// so that the data will be converted on copy.
if (isInt)
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
isArray = true;
}
else
{
isInt = false;
isFloat = JavascriptNativeFloatArray::Is(pDestObj);
isArray = JavascriptArray::Is(pDestObj);
}
}
else if (isFloat)
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
isArray = true;
}
else
{
isFloat = JavascriptNativeFloatArray::Is(pDestObj);
isArray = JavascriptArray::Is(pDestObj);
}
}
else
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
isArray = true;
}
else if (JavascriptNativeFloatArray::Is(pDestObj))
{
JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
isArray = true;
}
else
{
isArray = JavascriptArray::Is(pDestObj);
}
}
}
if (pDestObj == nullptr || isArray)
{
if (isInt)
{
JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
pIntArray->EnsureHead<int32>();
pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext);
}
else if (isFloat)
{
JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
pFArray->EnsureHead<double>();
pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext);
}
else
{
pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
// if the constructor has changed then we no longer specialize for ints and floats
pDestArray->EnsureHead<Var>();
ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow);
}
//
// Return the new array instance.
//
#ifdef VALIDATE_ARRAY
pDestArray->ValidateArray();
#endif
return pDestArray;
}
Assert(pDestObj);
ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow);
return pDestObj;
}
void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
{
if (destLengthOverflow.HasOverflowed())
{
ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
}
else
{
// Use faster uint32 version if no overflow
ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
}
}
template<typename T>
/* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
{
if (BoxConcatItem(aItem, idxArg, scriptContext))
{
// bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
RecyclableObject* pObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
}
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, pObj);
}
else
{
SetArrayLikeObjects(pDestObj, idxDest, pObj);
}
}
else
{
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, aItem);
}
else
{
SetArrayLikeObjects(pDestObj, idxDest, aItem);
}
}
}
uint32 JavascriptArray::GetFromIndex(Var arg, uint32 length, ScriptContext *scriptContext)
{
uint32 fromIndex;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue >= 0)
{
fromIndex = intValue;
}
else
{
// (intValue + length) may exceed 2^31 or may be < 0, so promote to int64
fromIndex = (uint32)max(0i64, (int64)(length) + intValue);
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value > length)
{
return (uint32)-1;
}
else if (value >= 0)
{
fromIndex = (uint32)value;
}
else
{
fromIndex = (uint32)max((double)0, value + length);
}
}
return fromIndex;
}
uint64 JavascriptArray::GetFromIndex(Var arg, uint64 length, ScriptContext *scriptContext)
{
uint64 fromIndex;
if (TaggedInt::Is(arg))
{
int64 intValue = TaggedInt::ToInt64(arg);
if (intValue >= 0)
{
fromIndex = intValue;
}
else
{
fromIndex = max((int64)0, (int64)(intValue + length));
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value > length)
{
return (uint64)-1;
}
else if (value >= 0)
{
fromIndex = (uint64)value;
}
else
{
fromIndex = (uint64)max((double)0, value + length);
}
}
return fromIndex;
}
int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
{
int64 fromIndex;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue >= 0)
{
fromIndex = min<int64>(intValue, length - 1);
}
else if ((uint32)-intValue > length)
{
return length;
}
else
{
fromIndex = intValue + length;
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value >= 0)
{
fromIndex = (int64)min(value, (double)(length - 1));
}
else if (value + length < 0)
{
return length;
}
else
{
fromIndex = (int64)(value + length);
}
}
return fromIndex;
}
// includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
// Differences
// 1. Returns boolean true or false value instead of the search hit index
// 2. Follows SameValueZero algorithm instead of StrictEquals
// 3. Missing values are scanned if the search value is undefined
template <bool includesAlgorithm>
Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
{
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
BigIndex length;
Var trueValue = scriptContext->GetLibrary()->GetTrue();
Var falseValue = scriptContext->GetLibrary()->GetFalse();
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.indexOf"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (pArr)
{
Var search;
uint32 fromIndex;
uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext);
// If we found the search value in the head segment, or if we determined there is no need to search other segments,
// we stop right here.
if (index != -1 || fromIndex == -1)
{
if (includesAlgorithm)
{
//Array.prototype.includes
return (index == -1)? falseValue : trueValue;
}
else
{
//Array.prototype.indexOf
return JavascriptNumber::ToVar(index, scriptContext);
}
}
// If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
switch (pArr->GetTypeId())
{
case Js::TypeIds_Array:
return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
case Js::TypeIds_NativeIntArray:
return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext);
case Js::TypeIds_NativeFloatArray:
return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext);
default:
AssertMsg(FALSE, "invalid array typeid");
return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
}
}
// source object is not a JavascriptArray but source could be a TypedArray
if (TypedArrayBase::Is(obj))
{
if (length.IsSmallIndex() || length.IsUint32Max())
{
Var search;
uint32 fromIndex;
uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext);
}
}
if (length.IsSmallIndex())
{
Var search;
uint32 fromIndex;
if (!GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext);
}
else
{
Var search;
uint64 fromIndex;
if (!GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetBigIndex(), scriptContext);
}
}
// Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
Var returnValue = IndexOfHelper<false>(args, scriptContext);
//IndexOfHelper code is reused for array.prototype.includes as well. Let us assert here we didn't get a true or false instead of index
Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
return returnValue;
}
Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
Var returnValue = IndexOfHelper<true>(args, scriptContext);
Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
return returnValue;
}
template<typename T>
BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
{
if (length == 0)
{
return false;
}
if (args.Info.Count > 2)
{
fromIndex = GetFromIndex(args[2], length, scriptContext);
if (fromIndex >= length)
{
return false;
}
search = args[1];
}
else
{
fromIndex = 0;
search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
}
return true;
}
template <>
BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// Note: Sometime cross site array go down this path to get the marshalling
Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
{
return FALSE;
}
return JavascriptOperators::GetItem(obj, index, element, scriptContext);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// Note: Sometime cross site array go down this path to get the marshalling
Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
{
return FALSE;
}
*element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
return *element != scriptContext->GetLibrary()->GetUndefined();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// We need to do explicit check for items since length value may not actually match the actual TypedArray length.
// User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
// Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
// we don't know whether or not length == typedArrayBase->GetLength().
if (checkHasItem && !typedArrayBase->HasItem(index))
{
return false;
}
*element = typedArrayBase->DirectGetItem(index);
return true;
}
template <>
BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <bool includesAlgorithm, typename T, typename P>
Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
{
Var element = nullptr;
bool isSearchTaggedInt = TaggedInt::Is(search);
bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
Var trueValue = scriptContext->GetLibrary()->GetTrue();
Var falseValue = scriptContext->GetLibrary()->GetFalse();
//Consider: enumerating instead of walking all indices
for (P i = fromIndex; i < toIndex; i++)
{
if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
{
if (doUndefinedSearch)
{
return trueValue;
}
continue;
}
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
}
continue;
}
if (includesAlgorithm)
{
//Array.prototype.includes
if (JavascriptConversion::SameValueZero(element, search))
{
return trueValue;
}
}
else
{
//Array.prototype.indexOf
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return JavascriptNumber::ToVar(i, scriptContext);
}
}
}
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
// We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
// virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
// either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
Var element = head->GetElement(i);
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (search == element)
{
return i;
}
}
else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
{
//Array.prototype.includes
return i;
}
else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
//Array.prototype.indexOf
return i;
}
}
// Element not found in the head segment. Keep looking only if the range of indices extends past
// the head segment.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
template<typename T>
bool AreAllBytesEqual(T value)
{
byte* bValue = (byte*)&value;
byte firstByte = *bValue++;
for (int i = 1; i < sizeof(T); ++i)
{
if (*bValue++ != firstByte)
{
return false;
}
}
return true;
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(double* buffer, uint32 length, double value)
{
if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
{
memset(buffer, 0, sizeof(double) * length);
}
else
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(int32* buffer, uint32 length, int32 value)
{
if (value == 0 || AreAllBytesEqual(value))
{
memset(buffer, *(byte*)&value, sizeof(int32)* length);
}
else
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(Js::Var* buffer, uint32 length, Js::Var value)
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
// We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
// except when we can further optimize thanks to the knowledge that all elements in the array are int32's. This allows for two additional optimizations:
// 1. Only tagged ints or JavascriptNumbers that can be represented as int32 can be strict equal to some element in the array (all int32). Thus, if
// the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
// 2. If the search value is a number that can be represented as int32, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
// Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
int32 searchAsInt32;
if (isSearchTaggedInt)
{
searchAsInt32 = TaggedInt::ToInt32(search);
}
else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
// We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
// virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
// the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
int32 element = head->GetElement(i);
if (searchAsInt32 == element)
{
return i;
}
}
// Element not found in the head segment. Keep looking only if the range of indices extends past
// the head segment.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
// We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
// except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
// 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
// the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
// 2. If the search value is a number, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
// Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
// We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
// segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
// used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
double element = head->GetElement(i);
if (element == searchAsDouble)
{
return i;
}
//NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
if (matchNaN && JavascriptNumber::IsNan(element))
{
return i;
}
}
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
}
JavascriptString* separator;
if (args.Info.Count >= 2)
{
TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
//ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
if (TypeIds_Undefined != typeId)
{
separator = JavascriptConversion::ToString(args[1], scriptContext);
}
else
{
separator = scriptContext->GetLibrary()->GetCommaDisplayString();
}
}
else
{
separator = scriptContext->GetLibrary()->GetCommaDisplayString();
}
return JoinHelper(args[0], separator, scriptContext);
}
JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
{
TypeId typeId = JavascriptOperators::GetTypeId(value);
if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
return JavascriptConversion::ToString(value, scriptContext);
}
}
JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
{
bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
Var target = NULL;
bool isTargetObjectPushed = false;
// if we are visiting a proxy object, track that we have visited the target object as well so the next time w
// call the join helper for the target of this proxy, we will return above.
if (isProxy)
{
JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
Assert(proxy);
target = proxy->GetTarget();
if (target != nullptr)
{
// If we end up joining same array, instead of going in infinite loop, return the empty string
if (scriptContext->CheckObject(target))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
scriptContext->PushObject(target);
isTargetObjectPushed = true;
}
}
}
// If we end up joining same array, instead of going in infinite loop, return the empty string
else if (scriptContext->CheckObject(thisArg))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
if (!isTargetObjectPushed)
{
scriptContext->PushObject(thisArg);
}
JavascriptString* res = nullptr;
TryFinally([&]()
{
if (isArray)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
#endif
JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
switch (arr->GetTypeId())
{
case Js::TypeIds_Array:
res = JoinArrayHelper(arr, separator, scriptContext);
break;
case Js::TypeIds_NativeIntArray:
res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext);
break;
case Js::TypeIds_NativeFloatArray:
res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext);
break;
}
}
else if (RecyclableObject::Is(thisArg))
{
res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext);
}
else
{
res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext);
}
},
[&](bool/*hasException*/)
{
Var top = scriptContext->PopObject();
if (isProxy)
{
AssertMsg(top == target, "Unmatched operation stack");
}
else
{
AssertMsg(top == thisArg, "Unmatched operation stack");
}
});
if (res == nullptr)
{
res = scriptContext->GetLibrary()->GetEmptyString();
}
return res;
}
static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
template <typename T>
JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
{
Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
const uint32 arrLength = arr->length;
switch(arrLength)
{
default:
{
CaseDefault:
bool hasSeparator = (separator->GetLength() != 0);
const charcount_t estimatedAppendCount =
min(
Join_MaxEstimatedAppendCount,
static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
CompoundString *const cs =
CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(item, scriptContext));
}
for (uint32 i = 1; i < arrLength; i++)
{
if (hasSeparator)
{
cs->Append(separator);
}
if (TryTemplatedGetItem(arr, i, &item, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(item, scriptContext));
}
}
return cs;
}
case 2:
{
bool hasSeparator = (separator->GetLength() != 0);
if(hasSeparator)
{
goto CaseDefault;
}
JavascriptString *res = nullptr;
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
res = JavascriptArray::JoinToString(item, scriptContext);
}
if (TryTemplatedGetItem(arr, 1u, &item, scriptContext))
{
JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext);
return res ? ConcatString::New(res, itemString) : itemString;
}
if(res)
{
return res;
}
goto Case0;
}
case 1:
{
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
return JavascriptArray::JoinToString(item, scriptContext);
}
// fall through
}
case 0:
Case0:
return scriptContext->GetLibrary()->GetEmptyString();
}
}
JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
{
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(object, scriptContext);
int64 cSrcLength = JavascriptConversion::ToLength(lenValue, scriptContext);
switch (cSrcLength)
{
default:
{
CaseDefault:
bool hasSeparator = (separator->GetLength() != 0);
const charcount_t estimatedAppendCount =
min(
Join_MaxEstimatedAppendCount,
static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
CompoundString *const cs =
CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(value, scriptContext));
}
for (uint32 i = 1; i < cSrcLength; i++)
{
if (hasSeparator)
{
cs->Append(separator);
}
if (JavascriptOperators::GetItem(object, i, &value, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(value, scriptContext));
}
}
return cs;
}
case 2:
{
bool hasSeparator = (separator->GetLength() != 0);
if(hasSeparator)
{
goto CaseDefault;
}
JavascriptString *res = nullptr;
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
res = JavascriptArray::JoinToString(value, scriptContext);
}
if (JavascriptOperators::GetItem(object, 1u, &value, scriptContext))
{
JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext);
return res ? ConcatString::New(res, valueString) : valueString;
}
if(res)
{
return res;
}
goto Case0;
}
case 1:
{
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
return JavascriptArray::JoinToString(value, scriptContext);
}
// fall through
}
case 0:
Case0:
return scriptContext->GetLibrary()->GetEmptyString();
}
}
Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
Assert(!(callInfo.Flags & CallFlags_New));
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.lastIndexOf"));
}
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
Var search;
int64 fromIndex;
if (!GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext))
{
return TaggedInt::ToVarUnchecked(-1);
}
if (pArr)
{
switch (pArr->GetTypeId())
{
case Js::TypeIds_Array:
return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
case Js::TypeIds_NativeIntArray:
return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext);
case Js::TypeIds_NativeFloatArray:
return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext);
default:
AssertMsg(FALSE, "invalid array typeid");
return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
}
}
// source object is not a JavascriptArray but source could be a TypedArray
if (TypedArrayBase::Is(obj))
{
return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext);
}
return LastIndexOfHelper(obj, search, fromIndex, scriptContext);
}
// Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
{
if (length == 0)
{
return false;
}
if (args.Info.Count > 2)
{
fromIndex = GetFromLastIndex(args[2], length, scriptContext);
if (fromIndex >= length)
{
return false;
}
search = args[1];
}
else
{
search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
fromIndex = length - 1;
}
return true;
}
template <typename T>
Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
{
Var element = nullptr;
bool isSearchTaggedInt = TaggedInt::Is(search);
// First handle the indices > 2^32
while (fromIndex >= MaxArrayLength)
{
Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
{
element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return index;
}
fromIndex--;
continue;
}
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return index;
}
}
fromIndex--;
}
Assert(fromIndex < MaxArrayLength);
// fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
uint32 end = static_cast<uint32>(fromIndex);
for (uint32 i = 0; i <= end; i++)
{
uint32 index = end - i;
if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
{
continue;
}
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return JavascriptNumber::ToVar(index, scriptContext);
}
continue;
}
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return JavascriptNumber::ToVar(index, scriptContext);
}
}
return TaggedInt::ToVarUnchecked(-1);
}
/*
* PopWithNoDst
* - For pop calls that do not return a value, we only need to decrement the length of the array.
*/
void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
{
Assert(JavascriptNativeArray::Is(nativeArray));
JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
// we will bailout on length 0
Assert(arr->GetLength() != 0);
uint32 index = arr->GetLength() - 1;
arr->SetLength(index);
}
/*
* JavascriptNativeIntArray::Pop
* - Returns int32 value from the array.
* - Returns missing item when the element is not available in the array object.
* - It doesn't walk up the prototype chain.
* - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
* - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
*/
int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
{
Assert(JavascriptNativeIntArray::Is(object));
JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
Assert(arr->GetLength() != 0);
uint32 index = arr->length - 1;
int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
//If it is a missing item, then don't update the length - Pre-op Bail out will happen.
if(!SparseArraySegment<int32>::IsMissingItem(&element))
{
arr->SetLength(index);
}
return element;
}
/*
* JavascriptNativeFloatArray::Pop
* - Returns double value from the array.
* - Returns missing item when the element is not available in the array object.
* - It doesn't walk up the prototype chain.
* - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
* - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
*/
double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
{
Assert(JavascriptNativeFloatArray::Is(object));
JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
Assert(arr->GetLength() != 0);
uint32 index = arr->length - 1;
double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
// If it is a missing item then don't update the length - Pre-op Bail out will happen.
if(!SparseArraySegment<double>::IsMissingItem(&element))
{
arr->SetLength(index);
}
return element;
}
/*
* JavascriptArray::Pop
* - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
* - This API may cause implicit calls. Handles Array and non-array objects
*/
Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
{
if (JavascriptArray::Is(object))
{
return EntryPopJavascriptArray(scriptContext, object);
}
else
{
return EntryPopNonJavascriptArray(scriptContext, object);
}
}
Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, Var object)
{
JavascriptArray * arr = JavascriptArray::FromVar(object);
uint32 length = arr->length;
if (length == 0)
{
// If length is 0, return 'undefined'
return scriptContext->GetLibrary()->GetUndefined();
}
uint32 index = length - 1;
Var element;
if (!arr->DirectGetItemAtFull(index, &element))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
else
{
element = CrossSite::MarshalVar(scriptContext, element);
}
arr->SetLength(index); // SetLength will clear element at index
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return element;
}
Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
}
BigIndex length;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
if (length == 0u)
{
// Set length = 0
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
return scriptContext->GetLibrary()->GetUndefined();
}
BigIndex index = length;
--index;
Var element;
if (index.IsSmallIndex())
{
if (!JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
// Set the new length
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
if (!JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
// Set the new length
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
return element;
}
Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
}
if (JavascriptArray::Is(args[0]))
{
return EntryPopJavascriptArray(scriptContext, args.Values[0]);
}
else
{
return EntryPopNonJavascriptArray(scriptContext, args.Values[0]);
}
}
/*
* JavascriptNativeIntArray::Push
* Pushes Int element in a native Int Array.
* We call the generic Push, if the array is not native Int or we have a really big array.
*/
Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
{
// Handle non crossSite native int arrays here length within MaxArrayLength.
// JavascriptArray::Push will handle other cases.
if (JavascriptNativeIntArray::IsNonCrossSite(array))
{
JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
Assert(!nativeIntArray->IsCrossSiteObject());
uint32 n = nativeIntArray->length;
if(n < JavascriptArray::MaxArrayLength)
{
nativeIntArray->SetItem(n, value);
n++;
AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
return JavascriptNumber::ToVar(n, scriptContext);
}
}
return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
}
/*
* JavascriptNativeFloatArray::Push
* Pushes Float element in a native Int Array.
* We call the generic Push, if the array is not native Float or we have a really big array.
*/
Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
{
// Handle non crossSite native int arrays here length within MaxArrayLength.
// JavascriptArray::Push will handle other cases.
if(JavascriptNativeFloatArray::IsNonCrossSite(array))
{
JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
Assert(!nativeFloatArray->IsCrossSiteObject());
uint32 n = nativeFloatArray->length;
if(n < JavascriptArray::MaxArrayLength)
{
nativeFloatArray->SetItem(n, value);
n++;
AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
return JavascriptNumber::ToVar(n, scriptContext);
}
}
return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
}
/*
* JavascriptArray::Push
* Pushes Var element in a Var Array.
*/
Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
{
Var args[2];
args[0] = object;
args[1] = value;
if (JavascriptArray::Is(object))
{
return EntryPushJavascriptArray(scriptContext, args, 2);
}
else
{
return EntryPushNonJavascriptArray(scriptContext, args, 2);
}
}
/*
* EntryPushNonJavascriptArray
* - Handles Entry push calls, when Objects are not javascript arrays
*/
Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
{
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
}
Var length = JavascriptOperators::OP_GetLength(obj, scriptContext);
if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
{
return length;
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
BigIndex n;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
}
else
{
n = JavascriptConversion::ToUInt32(length, scriptContext);
}
// First handle "small" indices.
uint index;
for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
{
if (h.IsThrowTypeError(JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if (scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
}
// Use BigIndex if we need to push indices >= MaxArrayLength
if (index < argCount)
{
BigIndex big = n;
for (; index < argCount; ++index, ++big)
{
if (h.IsThrowTypeError(big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
}
// Set the new length; for objects it is all right for this to be >= MaxArrayLength
if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
return big.ToNumber(scriptContext);
}
else
{
// Set the new length
Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
return lengthAsNUmberVar;
}
}
/*
* JavascriptArray::EntryPushJavascriptArray
* Pushes Var element in a Var Array.
* Returns the length of the array.
*/
Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
{
JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
uint n = arr->length;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
// Fast Path for one push for small indexes
if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
{
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
return JavascriptNumber::ToVar(n + 1, scriptContext);
}
// Fast Path for multiple push for small indexes
if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
{
uint index;
for (index = 1; index < argCount; ++index, ++n)
{
Assert(n != JavascriptArray::MaxArrayLength);
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
arr->JavascriptArray::DirectSetItemAt(n, args[index]);
}
return JavascriptNumber::ToVar(n, scriptContext);
}
return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
}
Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
{
JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
uint n = arr->length;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
// First handle "small" indices.
uint index;
for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
{
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
}
// Use BigIndex if we need to push indices >= MaxArrayLength
if (index < argCount)
{
// Not supporting native array with BigIndex.
arr = EnsureNonNativeArray(arr);
Assert(n == JavascriptArray::MaxArrayLength);
for (BigIndex big = n; index < argCount; ++index, ++big)
{
h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index]));
}
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
// This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return JavascriptNumber::ToVar(n, scriptContext);
}
/*
* JavascriptArray::EntryPush
* Handles Push calls(Script Function)
*/
Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
}
if (JavascriptArray::Is(args[0]))
{
return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
}
else
{
return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
}
}
Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
}
BigIndex length = 0u;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]))
{
pArr = JavascriptArray::FromVar(args[0]);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext);
}
// Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
template <typename T>
Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
{
T middle = length / 2;
Var lowerValue = nullptr, upperValue = nullptr;
T lowerExists, upperExists;
const char16* methodName;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
if (isTypedArrayEntryPoint)
{
methodName = _u("[TypedArray].prototype.reverse");
}
else
{
methodName = _u("Array.prototype.reverse");
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
if (pArr)
{
Recycler * recycler = scriptContext->GetRecycler();
if (length <= 1)
{
return pArr;
}
if (pArr->IsFillFromPrototypes())
{
// For odd-length arrays, the middle element is unchanged,
// so we cannot fill it from the prototypes.
if (length % 2 == 0)
{
pArr->FillFromPrototypes(0, (uint32)length);
}
else
{
middle = length / 2;
pArr->FillFromPrototypes(0, (uint32)middle);
pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
}
}
if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
{
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
}
// Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
// not work with the stale length. Update the length.
// Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
length = pArr->length;
SparseArraySegmentBase* seg = pArr->head;
SparseArraySegmentBase *prevSeg = nullptr;
SparseArraySegmentBase *nextSeg = nullptr;
SparseArraySegmentBase *pinPrevSeg = nullptr;
bool isIntArray = false;
bool isFloatArray = false;
if (JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if (JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
while (seg)
{
nextSeg = seg->next;
// If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
// resulting in 2 segments sharing the same "left".
if (seg->length > 0)
{
if (isIntArray)
{
((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
}
else if (isFloatArray)
{
((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
}
else
{
((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
}
seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
seg->next = prevSeg;
// Make sure size doesn't overlap with next segment.
// An easy fix is to just truncate the size...
seg->EnsureSizeInBound();
// If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
// segment. Hold onto it with pinPrevSeg until we reallocate below.
pinPrevSeg = prevSeg;
prevSeg = seg;
}
seg = nextSeg;
}
pArr->head = prevSeg;
// Just dump the segment map on reverse
pArr->ClearSegmentMap();
if (isIntArray)
{
if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
{
pArr->ReallocNonLeafSegment((SparseArraySegment<int32>*)pArr->head, pArr->head->next);
}
pArr->EnsureHeadStartsFromZero<int32>(recycler);
}
else if (isFloatArray)
{
if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
{
pArr->ReallocNonLeafSegment((SparseArraySegment<double>*)pArr->head, pArr->head->next);
}
pArr->EnsureHeadStartsFromZero<double>(recycler);
}
else
{
pArr->EnsureHeadStartsFromZero<Var>(recycler);
}
pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
}
else if (typedArrayBase)
{
Assert(length <= JavascriptArray::MaxArrayLength);
if (typedArrayBase->GetLength() == length)
{
// If typedArrayBase->length == length then we know that the TypedArray will have all items < length
// and we won't have to check that the elements exist or not.
for (uint32 lower = 0; lower < (uint32)middle; lower++)
{
uint32 upper = (uint32)length - lower - 1;
lowerValue = typedArrayBase->DirectGetItem(lower);
upperValue = typedArrayBase->DirectGetItem(upper);
// We still have to call HasItem even though we know the TypedArray has both lower and upper because
// there may be a proxy handler trapping HasProperty.
lowerExists = typedArrayBase->HasItem(lower);
upperExists = typedArrayBase->HasItem(upper);
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
}
else
{
for (uint32 lower = 0; lower < middle; lower++)
{
uint32 upper = (uint32)length - lower - 1;
lowerValue = typedArrayBase->DirectGetItem(lower);
upperValue = typedArrayBase->DirectGetItem(upper);
lowerExists = typedArrayBase->HasItem(lower);
upperExists = typedArrayBase->HasItem(upper);
if (lowerExists)
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
else
{
// This will always fail for a TypedArray if lower < length
h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
}
else
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
// This will always fail for a TypedArray if upper < length
h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
}
}
}
else
{
for (T lower = 0; lower < middle; lower++)
{
T upper = length - lower - 1;
lowerExists = JavascriptOperators::HasItem(obj, lower) &&
JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext);
upperExists = JavascriptOperators::HasItem(obj, upper) &&
JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext);
if (lowerExists)
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
}
else
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
}
}
return obj;
}
template<typename T>
void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
{
Recycler * recycler = scriptContext->GetRecycler();
SparseArraySegment<T>* next = (SparseArraySegment<T>*)pArr->head->next;
while (next)
{
next->left--;
next = (SparseArraySegment<T>*)next->next;
}
// head and next might overlap as the next segment left is decremented
next = (SparseArraySegment<T>*)pArr->head->next;
if (next && (pArr->head->size > next->left))
{
AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
SparseArraySegment<T> *head = (SparseArraySegment<T>*)pArr->head;
// Merge the two adjacent segments
if (next->length != 0)
{
uint32 offset = head->size - 1;
// There is room for one unshifted element in head segment.
// Hence it's enough if we grow the head segment by next->length - 1
if (next->next)
{
// If we have a next->next, we can't grow pass the left of that
// If the array had a segment map before, the next->next might just be right after next as well.
// So we just need to grow to the end of the next segment
// TODO: merge that segment too?
Assert(next->next->left >= head->size);
uint32 maxGrowSize = next->next->left - head->size;
if (maxGrowSize != 0)
{
head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
}
else
{
// The next segment is only of length one, so we already have space in the header to copy that
Assert(next->length == 1);
}
}
else
{
head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
}
memmove(head->elements + offset, next->elements, next->length * sizeof(T));
head->length = offset + next->length;
pArr->head = head;
}
head->next = next->next;
pArr->InvalidateLastUsedSegment();
}
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
}
Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
if (JavascriptArray::Is(args[0]))
{
JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
if (pArr->length == 0)
{
return res;
}
if(pArr->IsFillFromPrototypes())
{
pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
}
if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
{
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
}
pArr->length--;
pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
Recycler * recycler = scriptContext->GetRecycler();
bool isIntArray = false;
bool isFloatArray = false;
if(JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if(JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
if (pArr->head->length != 0)
{
if(isIntArray)
{
int32 nativeResult = ((SparseArraySegment<int32>*)pArr->head)->GetElement(0);
if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
}
((SparseArraySegment<int32>*)pArr->head)->RemoveElement(recycler, 0);
}
else if (isFloatArray)
{
double nativeResult = ((SparseArraySegment<double>*)pArr->head)->GetElement(0);
if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
}
((SparseArraySegment<double>*)pArr->head)->RemoveElement(recycler, 0);
}
else
{
res = ((SparseArraySegment<Var>*)pArr->head)->GetElement(0);
if(SparseArraySegment<Var>::IsMissingItem(&res))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = CrossSite::MarshalVar(scriptContext, res);
}
((SparseArraySegment<Var>*)pArr->head)->RemoveElement(recycler, 0);
}
}
if(isIntArray)
{
ShiftHelper<int32>(pArr, scriptContext);
}
else if (isFloatArray)
{
ShiftHelper<double>(pArr, scriptContext);
}
else
{
ShiftHelper<Var>(pArr, scriptContext);
}
}
else
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
BigIndex length = 0u;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (length == 0u)
{
// If length is 0, return 'undefined'
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
return scriptContext->GetLibrary()->GetUndefined();
}
if (!JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
--length;
uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
for (uint32 i = 0u; i < lengthToUin32Max; i++)
{
if (JavascriptOperators::HasItem(dynamicObject, i + 1))
{
Var element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
for (uint64 i = MaxArrayLength; length > i; i++)
{
if (JavascriptOperators::HasItem(dynamicObject, i + 1))
{
Var element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
if (length.IsSmallIndex())
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
}
return res;
}
Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
{
if (isIntArray)
{
Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
pnewArr->EnsureHead<int32>();
#if ENABLE_PROFILE_INFO
pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
#endif
return pnewArr;
}
else if (isFloatArray)
{
Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
pnewArr->EnsureHead<double>();
#if ENABLE_PROFILE_INFO
pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
#endif
return pnewArr;
}
else
{
JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
pnewArr->EnsureHead<Var>();
return pnewArr;
}
}
template<typename T>
void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
{
SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)pArr->head;
SparseArraySegment<T>* pnewHeadSeg = (SparseArraySegment<T>*)pnewArr->head;
// Fill the newly created sliced array
js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);
pnewHeadSeg->length = newLen;
Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
// Prototype lookup for missing elements
if (!pArr->HasNoMissingValues())
{
for (uint32 i = 0; i < newLen && (i + start) < pArr->length; i++)
{
// array type might be changed in the below call to DirectGetItemAtFull
// need recheck array type before checking array item [i + start]
if (pArr->IsMissingItem(i + start))
{
Var element;
pnewArr->SetHasNoMissingValues(false);
if (pArr->DirectGetItemAtFull(i + start, &element))
{
pnewArr->SetItem(i, element, PropertyOperation_None);
}
}
}
}
#ifdef DBG
else
{
for (uint32 i = 0; i < newLen; i++)
{
AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
}
}
#endif
}
// If the creating profile data has changed, convert it to the type of array indicated
// in the profile
void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
{
if (JavascriptNativeIntArray::Is(this))
{
#if ENABLE_PROFILE_INFO
JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
if(!info || info->IsNativeIntArray())
{
*isIntArray = true;
}
else if(info->IsNativeFloatArray())
{
JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
*isFloatArray = true;
}
else
{
JavascriptNativeIntArray::ToVarArray(nativeIntArray);
}
#else
*isIntArray = true;
#endif
}
else if (JavascriptNativeFloatArray::Is(this))
{
#if ENABLE_PROFILE_INFO
JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
if(info && !info->IsNativeArray())
{
JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
}
else
{
*isFloatArray = true;
}
#else
*isFloatArray = true;
#endif
}
}
Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.slice"));
}
}
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(lenValue, scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(lenValue, scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max());
return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
template <typename T>
Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
JavascriptLibrary* library = scriptContext->GetLibrary();
JavascriptArray* newArr = nullptr;
RecyclableObject* newObj = nullptr;
bool isIntArray = false;
bool isFloatArray = false;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
bool isBuiltinArrayCtor = true;
T startT = 0;
T newLenT = length;
T endT = length;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
if (args.Info.Count > 1)
{
startT = GetFromIndex(args[1], length, scriptContext);
if (startT > length)
{
startT = length;
}
if (args.Info.Count > 2)
{
if (JavascriptOperators::GetTypeId(args[2]) == TypeIds_Undefined)
{
endT = length;
}
else
{
endT = GetFromIndex(args[2], length, scriptContext);
if (endT > length)
{
endT = length;
}
}
}
newLenT = endT > startT ? endT - startT : 0;
}
if (TypedArrayBase::IsDetachedTypedArray(obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
}
// If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// If the entry point is %TypedArray%.prototype.slice or the source object is an Array exotic object we should try to load the constructor property
// and use it to construct the return object.
if (isTypedArrayEntryPoint)
{
Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
isBuiltinArrayCtor = (constructor == library->GetArrayConstructor());
// If we have an array source object, we need to make sure to do the right thing if it's a native array.
// The helpers below which do the element copying require the source and destination arrays to have the same native type.
if (pArr && isBuiltinArrayCtor)
{
if (newLenT > JavascriptArray::MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
// If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
newObj = newArr;
}
else if (JavascriptOperators::IsConstructor(constructor))
{
if (pArr)
{
// If the constructor function is any other function, it can return anything so we have to call it.
// Roll the source array into a non-native array if it was one.
pArr = EnsureNonNativeArray(pArr);
}
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext));
}
else
{
// We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.slice was called
JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArray_Constructor, _u("[TypedArray].prototype.slice"));
}
}
else if (pArr != nullptr)
{
newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor);
}
// skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
else
{
newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
}
// If we didn't create a new object above we will create a new array here.
// This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
if (newObj == nullptr)
{
if (pArr)
{
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
}
if (newLenT > JavascriptArray::MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
#endif
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
uint32 start = (uint32) startT;
uint32 newLen = (uint32) newLenT;
// We at least have to have newObj as a valid object
Assert(newObj);
// Bail out early if the new object will have zero length.
if (newLen == 0)
{
return newObj;
}
if (pArr)
{
// If we constructed a new Array object, we have some nice helpers here
if (newArr && isBuiltinArrayCtor)
{
if (JavascriptArray::IsDirectAccessArray(newArr))
{
if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
{
if (isIntArray)
{
SliceHelper<int32>(pArr, newArr, start, newLen);
}
else if (isFloatArray)
{
SliceHelper<double>(pArr, newArr, start, newLen);
}
else
{
SliceHelper<Var>(pArr, newArr, start, newLen);
}
}
else
{
if (isIntArray)
{
CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen);
}
else if (isFloatArray)
{
CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen);
}
else
{
CopyArrayElements(newArr, 0u, pArr, start, start + newLen);
}
}
}
else
{
AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
Var element;
for (uint32 i = 0; i < newLen; i++)
{
if (!pArr->DirectGetItemAtFull(i + start, &element))
{
continue;
}
newArr->SetItem(i, element, PropertyOperation_None);
}
}
}
else
{
// The constructed object isn't an array, we'll need to use normal object manipulation
Var element;
for (uint32 i = 0; i < newLen; i++)
{
if (!pArr->DirectGetItemAtFull(i + start, &element))
{
continue;
}
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
}
}
else if (typedArrayBase)
{
// Source is a TypedArray, we must have created the return object via a call to constructor, but newObj may not be a TypedArray (or an array either)
TypedArrayBase* newTypedArray = nullptr;
if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
Var element;
for (uint32 i = 0; i < newLen; i++)
{
// We only need to call HasItem in the case that we are called from Array.prototype.slice
if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
{
continue;
}
element = typedArrayBase->DirectGetItem(i + start);
// The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
if (newTypedArray)
{
newTypedArray->DirectSetItem(i, element);
}
else if (newArr)
{
newArr->DirectSetItemAt(i, element);
}
else
{
JavascriptOperators::OP_SetElementI_UInt32(newObj, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
}
}
else
{
for (uint32 i = 0; i < newLen; i++)
{
if (JavascriptOperators::HasItem(obj, i + start))
{
Var element = JavascriptOperators::GetItem(obj, i + start, scriptContext);
if (newArr != nullptr)
{
newArr->SetItem(i, element, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
}
}
}
if (!isTypedArrayEntryPoint)
{
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
#ifdef VALIDATE_ARRAY
if (JavascriptArray::Is(newObj))
{
JavascriptArray::FromVar(newObj)->ValidateArray();
}
#endif
return newObj;
}
struct CompareVarsInfo
{
ScriptContext* scriptContext;
RecyclableObject* compFn;
};
int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
{
CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
ScriptContext* requestContext=cvInfo->scriptContext;
RecyclableObject* compFn=cvInfo->compFn;
AssertMsg(*(Var*)aRef, "No null expected in sort");
AssertMsg(*(Var*)bRef, "No null expected in sort");
if (compFn != nullptr)
{
ScriptContext* scriptContext = compFn->GetScriptContext();
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var undefined = scriptContext->GetLibrary()->GetUndefined();
Var retVal;
if (requestContext != scriptContext)
{
Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
retVal = CALL_FUNCTION(compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
}
else
{
retVal = CALL_FUNCTION(compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
}
if (TaggedInt::Is(retVal))
{
return TaggedInt::ToInt32(retVal);
}
double dblResult;
if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
{
dblResult = JavascriptNumber::GetValue(retVal);
}
else
{
dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
}
if (dblResult < 0)
{
return -1;
}
return (dblResult > 0) ? 1 : 0;
}
else
{
JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
return JavascriptString::strcmp(pStr1, pStr2);
}
}
static void hybridSort(__inout_ecount(length) Var *elements, uint32 length, CompareVarsInfo* compareInfo)
{
// The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
// for arrays of more than 512 elements.
if (length > 512)
{
qsort_s(elements, length, sizeof(Var), compareVars, compareInfo);
return;
}
for (int i = 1; i < (int)length; i++)
{
if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
// binary search for the left-most element greater than value:
int first = 0;
int last = i - 1;
while (first <= last)
{
int middle = (first + last) / 2;
if (compareVars(compareInfo, elements + i, elements + middle) < 0)
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
// insert value right before first:
Var value = elements[i];
memmove(elements + first + 1, elements + first, (i - first) * sizeof(Var));
elements[first] = value;
}
}
}
void JavascriptArray::Sort(RecyclableObject* compFn)
{
if (length <= 1)
{
return;
}
this->EnsureHead<Var>();
ScriptContext* scriptContext = this->GetScriptContext();
Recycler* recycler = scriptContext->GetRecycler();
CompareVarsInfo cvInfo;
cvInfo.scriptContext = scriptContext;
cvInfo.compFn = compFn;
Assert(head != nullptr);
// Just dump the segment map on sort
ClearSegmentMap();
uint32 countUndefined = 0;
SparseArraySegment<Var>* startSeg = (SparseArraySegment<Var>*)head;
// Sort may have side effects on the array. Setting a dummy head so that original array is not affected
uint32 saveLength = length;
// that if compare function tries to modify the array it won't AV.
head = const_cast<SparseArraySegmentBase*>(EmptySegment);
SetFlags(DynamicObjectFlags::None);
this->InvalidateLastUsedSegment();
length = 0;
TryFinally([&]()
{
//The array is a continuous array if there is only one segment
if (startSeg->next == nullptr) // Single segment fast path
{
if (compFn != nullptr)
{
countUndefined = startSeg->RemoveUndefined(scriptContext);
#ifdef VALIDATE_ARRAY
ValidateSegment(startSeg);
#endif
hybridSort(startSeg->elements, startSeg->length, &cvInfo);
}
else
{
countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext);
}
head = startSeg;
}
else
{
SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
SparseArraySegment<Var>* next = startSeg;
uint32 nextIndex = 0;
// copy all the elements to single segment
while (next)
{
countUndefined += next->RemoveUndefined(scriptContext);
if (next->length != 0)
{
allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
}
next = (SparseArraySegment<Var>*)next->next;
nextIndex = allElements->length;
#ifdef VALIDATE_ARRAY
ValidateSegment(allElements);
#endif
}
if (compFn != nullptr)
{
hybridSort(allElements->elements, allElements->length, &cvInfo);
}
else
{
sort(allElements->elements, &allElements->length, scriptContext);
}
head = allElements;
head->next = nullptr;
}
},
[&](bool hasException)
{
length = saveLength;
ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
if (hasException)
{
head = startSeg;
this->InvalidateLastUsedSegment();
}
});
#if DEBUG
{
uint32 countNull = 0;
uint32 index = head->length - 1;
while (countNull < head->length)
{
if (((SparseArraySegment<Var>*)head)->elements[index] != NULL)
{
break;
}
index--;
countNull++;
}
AssertMsg(countNull == 0, "No null expected at the end");
}
#endif
if (countUndefined != 0)
{
// fill undefined at the end
uint32 newLength = head->length + countUndefined;
if (newLength > head->size)
{
head = ((SparseArraySegment<Var>*)head)->GrowByMin(recycler, newLength - head->size);
}
Var undefined = scriptContext->GetLibrary()->GetUndefined();
for (uint32 i = head->length; i < newLength; i++)
{
((SparseArraySegment<Var>*)head)->elements[i] = undefined;
}
head->length = newLength;
}
SetHasNoMissingValues();
this->InvalidateLastUsedSegment();
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
return;
}
uint32 JavascriptArray::sort(__inout_ecount(*len) Var *orig, uint32 *len, ScriptContext *scriptContext)
{
uint32 count = 0, countUndefined = 0;
Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
//
// Create the Elements array
//
for (uint32 i = 0; i < *len; ++i)
{
if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
{
if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
{
elements[count].Value = orig[i];
elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
count++;
}
else
{
countUndefined++;
}
}
}
if (count > 0)
{
SortElements(elements, 0, count - 1);
for (uint32 i = 0; i < count; ++i)
{
orig[i] = elements[i].Value;
}
}
for (uint32 i = count + countUndefined; i < *len; ++i)
{
orig[i] = SparseArraySegment<Var>::GetMissingItem();
}
*len = count; // set the correct length
return countUndefined;
}
int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
{
const Element* element1 = static_cast<const Element*>(elem1);
const Element* element2 = static_cast<const Element*>(elem2);
Assert(element1 != NULL);
Assert(element2 != NULL);
return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
}
void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
{
qsort_s(elements, right - left + 1, sizeof(Element), CompareElements, this);
}
Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
Assert(!(callInfo.Flags & CallFlags_New));
AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
RecyclableObject* compFn = NULL;
if (args.Info.Count > 1)
{
if (JavascriptConversion::IsCallable(args[1]))
{
compFn = RecyclableObject::FromVar(args[1]);
}
else
{
TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
// Use default comparer:
// - In ES5 mode if the argument is undefined.
bool useDefaultComparer = typeId == TypeIds_Undefined;
if (!useDefaultComparer)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedInternalObject, _u("Array.prototype.sort"));
}
}
}
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
if (arr->length <= 1)
{
return args[0];
}
if(arr->IsFillFromPrototypes())
{
arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
}
// Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
// - int cases for X86 and
// - FloatArray for AMD64
// We convert the entire array back and forth once here O(n), rather than doing the costly conversion down the call stack which is O(nlogn)
#if defined(_M_X64_OR_ARM64)
if(compFn && JavascriptNativeFloatArray::Is(arr))
{
arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
arr->Sort(compFn);
arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
}
else
{
EnsureNonNativeArray(arr);
arr->Sort(compFn);
}
#else
if(compFn && JavascriptNativeIntArray::Is(arr))
{
//EnsureNonNativeArray(arr);
arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
arr->Sort(compFn);
arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
}
else
{
EnsureNonNativeArray(arr);
arr->Sort(compFn);
}
#endif
}
else
{
RecyclableObject* pObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
}
uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
sortArray->EnsureHead<Var>();
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
{
JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
for (uint32 i = 0; i < len; i++)
{
Var item;
if (JavascriptOperators::GetItem(pObj, i, &item, scriptContext))
{
indexList->Add(i);
sortArray->DirectSetItemAt(i, item);
}
}
if (indexList->Count() > 0)
{
if (sortArray->length > 1)
{
sortArray->FillFromPrototypes(0, sortArray->length); // We need find all missing value from [[proto]] object
}
sortArray->Sort(compFn);
uint32 removeIndex = sortArray->head->length;
for (uint32 i = 0; i < removeIndex; i++)
{
AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&((SparseArraySegment<Var>*)sortArray->head)->elements[i]), "No gaps expected in sorted array");
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, ((SparseArraySegment<Var>*)sortArray->head)->elements[i], scriptContext));
}
for (int i = 0; i < indexList->Count(); i++)
{
uint32 value = indexList->Item(i);
if (value >= removeIndex)
{
h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value)));
}
}
}
}
END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
}
return args[0];
}
Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
Assert(!(callInfo.Flags & CallFlags_New));
AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
bool isArr = false;
JavascriptArray* pArr = 0;
RecyclableObject* pObj = 0;
RecyclableObject* newObj = nullptr;
uint32 start = 0;
uint32 deleteLen = 0;
uint32 len = 0;
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
isArr = true;
pArr = JavascriptArray::FromVar(args[0]);
pObj = pArr;
len = pArr->length;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.splice"));
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
int64 len64 = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
len = len64 > UINT_MAX ? UINT_MAX : (uint)len64;
}
else
{
len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
}
}
switch (args.Info.Count)
{
case 1:
start = len;
deleteLen = 0;
break;
case 2:
start = min(GetFromIndex(args[1], len, scriptContext), len);
deleteLen = len - start;
break;
default:
start = GetFromIndex(args[1], len, scriptContext);
if (start > len)
{
start = len;
}
// When start >= len, we know we won't be deleting any items and don't really need to evaluate the second argument.
// However, ECMA 262 15.4.4.12 requires that it be evaluated, anyway. If the argument is an object with a valueOf
// with a side effect, this evaluation is observable. Hence, we must evaluate.
if (TaggedInt::Is(args[2]))
{
int intDeleteLen = TaggedInt::ToInt32(args[2]);
if (intDeleteLen < 0)
{
deleteLen = 0;
}
else
{
deleteLen = intDeleteLen;
}
}
else
{
double dblDeleteLen = JavascriptConversion::ToInteger(args[2], scriptContext);
if (dblDeleteLen > len)
{
deleteLen = (uint32)-1;
}
else if (dblDeleteLen <= 0)
{
deleteLen = 0;
}
else
{
deleteLen = (uint32)dblDeleteLen;
}
}
deleteLen = min(len - start, deleteLen);
break;
}
Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
::Math::RecordOverflowPolicy newLenOverflow;
uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
if (isArr)
{
// If we have missing values then convert to not native array for now
// In future, we could support this scenario.
if (deleteLen == insertLen)
{
pArr->FillFromPrototypes(start, start + deleteLen);
}
else if (len)
{
pArr->FillFromPrototypes(start, len);
}
//
// If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
// max array length, which would result in tons of index overflow and difficult to fix.
//
if (newLenOverflow.HasOverflowed())
{
pArr = EnsureNonNativeArray(pArr);
BigIndex dstIndex = MaxArrayLength;
uint32 maxInsertLen = MaxArrayLength - start;
if (insertLen > maxInsertLen)
{
// Copy overflowing insertArgs to properties
for (uint32 i = maxInsertLen; i < insertLen; i++)
{
pArr->DirectSetItemAt(dstIndex, insertArgs[i]);
++dstIndex;
}
insertLen = maxInsertLen; // update
// Truncate elements on the right to properties
if (start + deleteLen < len)
{
pArr->TruncateToProperties(dstIndex, start + deleteLen);
}
}
else
{
// Truncate would-overflow elements to properties
pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
}
len = pArr->length; // update
newLen = len - deleteLen + insertLen;
Assert(newLen == MaxArrayLength);
}
if (insertArgs)
{
pArr = EnsureNonNativeArray(pArr);
}
bool isIntArray = false;
bool isFloatArray = false;
bool isBuiltinArrayCtor = true;
JavascriptArray *newArr = nullptr;
// Just dump the segment map on splice (before any possible allocation and throw)
pArr->ClearSegmentMap();
// If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
// and use it to construct the return object.
newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
if (newObj != nullptr)
{
pArr = EnsureNonNativeArray(pArr);
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
// This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
{
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
#endif
}
// If return object is a JavascriptArray, we can use all the array splice helpers
if (newArr && isBuiltinArrayCtor && len == pArr->length)
{
// Array has a single segment (need not start at 0) and splice start lies in the range
// of that segment we optimize splice - Fast path.
if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
{
if (isIntArray)
{
ArraySegmentSpliceHelper<int32>(newArr, (SparseArraySegment<int32>*)pArr->head, (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
else if (isFloatArray)
{
ArraySegmentSpliceHelper<double>(newArr, (SparseArraySegment<double>*)pArr->head, (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
else
{
ArraySegmentSpliceHelper<Var>(newArr, (SparseArraySegment<Var>*)pArr->head, (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
// Since the start index is within the bounds of the original array's head segment, it will not acquire any new
// missing values. If the original array had missing values in the head segment, some of them may have been
// copied into the array that will be returned; otherwise, the array that is returned will also not have any
// missing values.
newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
}
else
{
if (isIntArray)
{
ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
else if (isFloatArray)
{
ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
else
{
ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
newArr->SetHasNoMissingValues(false);
}
if (isIntArray)
{
pArr->EnsureHeadStartsFromZero<int32>(recycler);
newArr->EnsureHeadStartsFromZero<int32>(recycler);
}
else if (isFloatArray)
{
pArr->EnsureHeadStartsFromZero<double>(recycler);
newArr->EnsureHeadStartsFromZero<double>(recycler);
}
else
{
pArr->EnsureHeadStartsFromZero<Var>(recycler);
newArr->EnsureHeadStartsFromZero<Var>(recycler);
}
pArr->InvalidateLastUsedSegment();
// it is possible for valueOf accessors for the start or deleteLen
// arguments to modify the size of the array. Since the resulting size of the array
// is based on the cached value of length, this might lead to us having to trim
// excess array segments at the end of the splice operation, which SetLength() will do.
// However, this is also slower than performing the simple length assignment, so we only
// do it if we can detect the array length changing.
if(pArr->length != len)
{
pArr->SetLength(newLen);
}
else
{
pArr->length = newLen;
}
if (newArr->length != deleteLen)
{
newArr->SetLength(deleteLen);
}
else
{
newArr->length = deleteLen;
}
newArr->InvalidateLastUsedSegment();
#ifdef VALIDATE_ARRAY
newArr->ValidateArray();
pArr->ValidateArray();
#endif
if (newLenOverflow.HasOverflowed())
{
// ES5 15.4.4.12 16: If new len overflowed, SetLength throws
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
return newArr;
}
}
if (newLenOverflow.HasOverflowed())
{
return ObjectSpliceHelper<BigIndex>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
}
else // Use uint32 version if no overflow
{
return ObjectSpliceHelper<uint32>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
}
}
inline BOOL JavascriptArray::IsSingleSegmentArray() const
{
return nullptr == head->next;
}
template<typename T>
void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
{
// book keeping variables
uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
//(Missing elements at the beginning)
uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
// head if deleteLen overflows the length of head
uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
// Save the deleted elements
if (headDeleteLen != 0)
{
pnewArr->InvalidateLastUsedSegment();
pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, (SparseArraySegment<T>*)pnewArr->head, 0, seg, start, headDeleteLen);
}
if (newHeadLen != 0)
{
if (seg->size < newHeadLen)
{
if (seg->next)
{
// If we have "next", require that we haven't adjusted next segments left yet.
seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
}
else
{
seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
}
#ifdef VALIDATE_ARRAY
ValidateSegment(seg);
#endif
}
// Move the elements if necessary
if (headDeleteLen != insertLen)
{
uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
memmove(seg->elements + relativeStart + insertLen,
seg->elements + relativeStart + headDeleteLen,
sizeof(T) * noElementsToMove);
if (newHeadLen < seg->length) // truncate if necessary
{
seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
}
seg->length = newHeadLen;
}
// Copy the new elements
if (insertLen > 0)
{
Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
!VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
// inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
js_memcpy_s(seg->elements + relativeStart, sizeof(Var) * insertLen, insertArgs, sizeof(Var) * insertLen);
}
*prev = seg;
}
else
{
*prev = (SparseArraySegment<T>*)seg->next;
}
}
template<typename T>
void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
{
// Skip pnewArr->EnsureHead(): we don't use existing segment at all.
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase** prevSeg = &pArr->head; // holds the next pointer of previous
SparseArraySegmentBase** prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
SparseArraySegmentBase* savePrev = nullptr;
Assert(pArr->head); // We should never have a null head.
pArr->EnsureHead<T>();
SparseArraySegment<T>* startSeg = (SparseArraySegment<T>*)pArr->head;
const uint32 limit = start + deleteLen;
uint32 rightLimit;
if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
{
rightLimit = JavascriptArray::MaxArrayLength;
}
// Find out the segment to start delete
while (startSeg && (rightLimit <= start))
{
savePrev = startSeg;
prevPrevSeg = prevSeg;
prevSeg = &startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
if (startSeg)
{
if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
{
rightLimit = JavascriptArray::MaxArrayLength;
}
}
}
// handle inlined segment
SparseArraySegmentBase* inlineHeadSegment = nullptr;
bool hasInlineSegment = false;
// The following if else set is used to determine whether a shallow or hard copy is needed
if (JavascriptNativeArray::Is(pArr))
{
if (JavascriptNativeFloatArray::Is(pArr))
{
inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
}
else if (JavascriptNativeIntArray::Is(pArr))
{
inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
}
Assert(inlineHeadSegment);
hasInlineSegment = (startSeg == (SparseArraySegment<T>*)inlineHeadSegment);
}
else
{
// This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
// does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
// This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
// so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
// false positives. It is better than always doing a hard copy.
hasInlineSegment = HasInlineHeadSegment(pArr->head->length);
}
if (startSeg)
{
// Delete Phase
if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
{
// All splice happens in one segment.
SparseArraySegmentBase *nextSeg = startSeg->next;
// Splice the segment first, which might OOM throw but the array would be intact.
JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
while (nextSeg)
{
// adjust next segments left
nextSeg->left = nextSeg->left - deleteLen + insertLen;
if (nextSeg->next == nullptr)
{
nextSeg->EnsureSizeInBound();
}
nextSeg = nextSeg->next;
}
if (*prevSeg)
{
(*prevSeg)->EnsureSizeInBound();
}
return;
}
else
{
SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
SparseArraySegmentBase** prevNewHeadSeg = &(pnewArr->head);
// delete till deleteLen and reuse segments for new array if it is possible.
// 3 steps -
//1. delete 1st segment (which may be partial delete)
// 2. delete next n complete segments
// 3. delete last segment (which again may be partial delete)
// Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
if (startSeg->left < start)
{
if (start < startSeg->left + startSeg->length)
{
uint32 headDeleteLen = startSeg->left + startSeg->length - start;
if (startSeg->next)
{
// We know the new segment will have a next segment, so allocate it as non-leaf.
newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
else
{
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
newHeadSeg->next = nullptr;
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
startSeg->Truncate(start);
}
savePrev = startSeg;
prevPrevSeg = prevSeg;
prevSeg = &startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
// Step (2) first we should do a hard copy if we have an inline head Segment
else if (hasInlineSegment && nullptr != startSeg)
{
// start should be in between left and left + length
if (startSeg->left <= start && start < startSeg->left + startSeg->length)
{
uint32 headDeleteLen = startSeg->left + startSeg->length - start;
if (startSeg->next)
{
// We know the new segment will have a next segment, so allocate it as non-leaf.
newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
else
{
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
// Remove the entire segment from the original array
*prevSeg = startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
// if we have an inline head segment with 0 elements, remove it
else if (startSeg->left == 0 && startSeg->length == 0)
{
Assert(startSeg->size != 0);
*prevSeg = startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
}
// Step (2) proper
SparseArraySegmentBase *temp = nullptr;
while (startSeg && (startSeg->left + startSeg->length) <= limit)
{
temp = startSeg->next;
// move that entire segment to new array
startSeg->left = startSeg->left - start;
startSeg->next = nullptr;
*prevNewHeadSeg = startSeg;
prevNewHeadSeg = &startSeg->next;
// Remove the entire segment from the original array
*prevSeg = temp;
startSeg = (SparseArraySegment<T>*)temp;
}
// Step(2) above could delete the original head segment entirely, causing current head not
// starting from 0. Then if any of the following throw, we have a corrupted array. Need
// protection here.
bool dummyHeadNodeInserted = false;
if (!savePrev && (!startSeg || startSeg->left != 0))
{
Assert(pArr->head == startSeg);
pArr->EnsureHeadStartsFromZero<T>(recycler);
Assert(pArr->head && pArr->head->next == startSeg);
savePrev = pArr->head;
prevPrevSeg = prevSeg;
prevSeg = &pArr->head->next;
dummyHeadNodeInserted = true;
}
// Step (3)
if (startSeg && (startSeg->left < limit))
{
// copy the first part of the last segment to be deleted to new array
uint32 headDeleteLen = start + deleteLen - startSeg->left ;
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
newHeadSeg->next = nullptr;
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
// move the last segment
memmove(startSeg->elements, startSeg->elements + headDeleteLen, sizeof(T) * (startSeg->length - headDeleteLen));
startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
startSeg->length = startSeg->length - headDeleteLen;
startSeg->Truncate(startSeg->left + startSeg->length);
startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
}
if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
{
Assert(start + insertLen == 0);
// Remove the dummy head node to preserve array consistency.
pArr->head = startSeg;
savePrev = nullptr;
prevSeg = &pArr->head;
}
while (startSeg)
{
startSeg->left = startSeg->left - deleteLen + insertLen ;
if (startSeg->next == nullptr)
{
startSeg->EnsureSizeInBound();
}
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
}
}
// The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
pnewArr->head->EnsureSizeInBound();
if (savePrev)
{
savePrev->EnsureSizeInBound();
}
// insert elements
if (insertLen > 0)
{
Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
// InsertPhase
SparseArraySegment<T> *segInsert = nullptr;
// see if we are just about the right of the previous segment
Assert(!savePrev || savePrev->left <= start);
if (savePrev && (start - savePrev->left < savePrev->size))
{
segInsert = (SparseArraySegment<T>*)savePrev;
uint32 spaceLeft = segInsert->size - (start - segInsert->left);
if(spaceLeft < insertLen)
{
if (!segInsert->next)
{
segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
}
else
{
segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
}
}
*prevPrevSeg = segInsert;
segInsert->length = start + insertLen - segInsert->left;
}
else
{
segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
segInsert->next = *prevSeg;
*prevSeg = segInsert;
savePrev = segInsert;
}
uint32 relativeStart = start - segInsert->left;
// inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
js_memcpy_s(segInsert->elements + relativeStart, sizeof(T) * insertLen, insertArgs, sizeof(T) * insertLen);
}
}
template<typename indexT>
RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, uint32 len, uint32 start,
uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
{
JavascriptArray *pnewArr = nullptr;
if (pNewObj == nullptr)
{
pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext);
if (pNewObj == nullptr || !JavascriptArray::Is(pNewObj))
{
pnewArr = scriptContext->GetLibrary()->CreateArray(deleteLen);
pnewArr->EnsureHead<Var>();
pNewObj = pnewArr;
}
}
if (JavascriptArray::Is(pNewObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
#endif
pnewArr = JavascriptArray::FromVar(pNewObj);
}
// copy elements to delete to new array
if (deleteLen > 0)
{
for (uint32 i = 0; i < deleteLen; i++)
{
if (JavascriptOperators::HasItem(pObj, start+i))
{
Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext);
if (pnewArr)
{
pnewArr->SetItem(i, element, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, i, element), scriptContext, i);
}
}
}
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
// If the return object is not an array, we'll need to set the 'length' property
if (pnewArr == nullptr)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, JavascriptNumber::ToVar(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
// Now we need reserve room if it is necessary
if (insertLen > deleteLen) // Might overflow max array length
{
// Unshift [start + deleteLen, len) to start + insertLen
Unshift<indexT>(pObj, start + insertLen, start + deleteLen, len, scriptContext);
}
else if (insertLen < deleteLen) // Won't overflow max array length
{
uint32 j = 0;
for (uint32 i = start + deleteLen; i < len; i++)
{
if (JavascriptOperators::HasItem(pObj, i))
{
Var element = JavascriptOperators::GetItem(pObj, i, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
j++;
}
// Clean up the rest
for (uint32 i = len; i > len - deleteLen + insertLen; i--)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
if (insertLen > 0)
{
indexT dstIndex = start; // insert index might overflow max array length
for (uint i = 0; i < insertLen; i++)
{
h.ThrowTypeErrorOnFailure(IndexTrace<indexT>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible));
++dstIndex;
}
}
// Set up new length
indexT newLen = indexT(len - deleteLen) + insertLen;
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<indexT>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<indexT>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
#ifdef VALIDATE_ARRAY
if (pnewArr)
{
pnewArr->ValidateArray();
}
#endif
return pNewObj;
}
Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
}
if (JavascriptArray::IsDirectAccessArray(args[0]))
{
JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
return ToLocaleString(arr, scriptContext);
}
else
{
if (TypedArrayBase::IsDetachedTypedArray(args[0]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
}
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
}
return ToLocaleString(obj, scriptContext);
}
}
//
// Unshift object elements [start, end) to toIndex, asserting toIndex > start.
//
template<typename T, typename P>
void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, uint32 start, P end, ScriptContext* scriptContext)
{
typedef IndexTrace<T> index_trace;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
if (start < end)
{
T newEnd = (end - start - 1);// newEnd - 1
T dst = toIndex + newEnd;
uint32 i = 0;
if (end > UINT32_MAX)
{
uint64 i64 = end;
for (; i64 > UINT32_MAX; i64--)
{
if (JavascriptOperators::HasItem(obj, i64 - 1))
{
Var element = JavascriptOperators::GetItem(obj, i64 - 1, scriptContext);
h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
--dst;
}
i = UINT32_MAX;
}
else
{
i = (uint32) end;
}
for (; i > start; i--)
{
if (JavascriptOperators::HasItem(obj, i-1))
{
Var element = JavascriptOperators::GetItem(obj, i - 1, scriptContext);
h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
--dst;
}
}
}
template<typename T>
void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
{
SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
Recycler* recycler = scriptContext->GetRecycler();
if (nextToHeadSeg == nullptr)
{
pArr->EnsureHead<T>();
pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMin(recycler, unshiftElements);
}
else
{
pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
}
}
template<typename T>
void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
{
SparseArraySegment<T>* head = (SparseArraySegment<T>*)pArr->head;
// Make enough room in the head segment to insert new elements at the front
memmove(head->elements + unshiftElements, head->elements, sizeof(T) * pArr->head->length);
uint32 oldHeadLength = head->length;
head->length += unshiftElements;
/* Set head segment as the last used segment */
pArr->InvalidateLastUsedSegment();
bool hasNoMissingValues = pArr->HasNoMissingValues();
/* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
if(unshiftElements > oldHeadLength)
{
pArr->SetHasNoMissingValues(false);
}
#if ENABLE_PROFILE_INFO
pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
#else
pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
#endif
// Setting back to the old value
pArr->SetHasNoMissingValues(hasNoMissingValues);
}
Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
uint32 unshiftElements = args.Info.Count - 1;
if (unshiftElements > 0)
{
if (pArr->IsFillFromPrototypes())
{
pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
}
// Pre-process: truncate overflowing elements to properties
bool newLenOverflowed = false;
uint32 maxLen = MaxArrayLength - unshiftElements;
if (pArr->length > maxLen)
{
newLenOverflowed = true;
// Ensure the array is non-native when overflow happens
EnsureNonNativeArray(pArr);
pArr->TruncateToProperties(MaxArrayLength, maxLen);
Assert(pArr->length + unshiftElements == MaxArrayLength);
}
pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
Assert(pArr->length <= MaxArrayLength - unshiftElements);
SparseArraySegmentBase* renumberSeg = pArr->head->next;
bool isIntArray = false;
bool isFloatArray = false;
if (JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if (JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
// If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
// If there is OOM in array allocation, then array consistency is maintained.
if (pArr->head->size < pArr->head->length + unshiftElements)
{
if (isIntArray)
{
GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
}
else if (isFloatArray)
{
GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
}
else
{
GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
}
}
while (renumberSeg)
{
renumberSeg->left += unshiftElements;
if (renumberSeg->next == nullptr)
{
// last segment can shift its left + size beyond MaxArrayLength, so truncate if so
renumberSeg->EnsureSizeInBound();
}
renumberSeg = renumberSeg->next;
}
if (isIntArray)
{
UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
}
else if (isFloatArray)
{
UnshiftHelper<double>(pArr, unshiftElements, args.Values);
}
else
{
UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
}
pArr->InvalidateLastUsedSegment();
pArr->length += unshiftElements;
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
res = JavascriptNumber::ToVar(pArr->length, scriptContext);
}
else
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
}
BigIndex length;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
uint32 unshiftElements = args.Info.Count - 1;
if (unshiftElements > 0)
{
uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
// Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
// or MaxSpaceUint32 is greater than length meaning length is a uint32 number
BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
if (end < length)
{
// Unshift [end, length) to MaxArrayLength
// MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
if (length.IsSmallIndex())
{
Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext);
}
else
{
Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetBigIndex(), scriptContext);
}
}
// Unshift [0, end) to unshiftElements
// unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
Unshift<uint32>(dynamicObject, unshiftElements, 0, end.GetSmallIndex(), scriptContext);
for (uint32 i = 0; i < unshiftElements; i++)
{
JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true);
}
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
//ES6 - update 'length' even if unshiftElements == 0;
BigIndex newLen = length + unshiftElements;
res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
return res;
}
Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
}
// ES5 15.4.4.2: call join, or built-in Object.prototype.toString
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
}
// In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext);
if (JavascriptConversion::IsCallable(join))
{
RecyclableObject* func = RecyclableObject::FromVar(join);
// We need to record implicit call here, because marked the Array.toString as no side effect,
// but if we call user code here which may have side effect
ThreadContext * threadContext = scriptContext->GetThreadContext();
Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
{
// Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
Assert(!ThreadContext::IsOnStack(obj));
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
return CALL_FUNCTION(func, CallInfo(flags, 1), obj);
});
if(!result)
{
// There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
Assert(threadContext->IsDisableImplicitCall());
result = scriptContext->GetLibrary()->GetNull();
}
return result;
}
else
{
// call built-in Object.prototype.toString
return CALL_ENTRYPOINT(JavascriptObject::EntryToString, function, CallInfo(1), obj);
}
}
#if DEBUG
BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
{
uint32 lu, luDig;
int32 cch = (int32)wcslen(propName);
char16* pch = const_cast<char16 *>(propName);
lu = *pch - '0';
if (lu > 9)
return FALSE;
if (0 == lu)
{
*pIndex = 0;
return 1 == cch;
}
while ((luDig = *++pch - '0') < 10)
{
// If we overflow 32 bits, ignore the item
if (lu > 0x19999999)
return FALSE;
lu *= 10;
if(lu > (ULONG_MAX - luDig))
return FALSE;
lu += luDig;
}
if (pch - propName != cch)
return FALSE;
if (lu == JavascriptArray::InvalidIndex)
{
// 0xFFFFFFFF is not treated as an array index so that the length can be
// capped at 32 bits.
return FALSE;
}
*pIndex = lu;
return TRUE;
}
#endif
JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
{
#ifdef ENABLE_GLOBALIZATION
LCID lcid = GetUserDefaultLCID();
int count = 0;
char16 szSeparator[6];
// According to the document for GetLocaleInfo this is a sufficient buffer size.
count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
if( !count)
{
AssertMsg(FALSE, "GetLocaleInfo failed");
return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
}
else
{
// Append ' ' if necessary
if( count < 2 || szSeparator[count-2] != ' ')
{
szSeparator[count-1] = ' ';
szSeparator[count] = '\0';
}
return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
}
#else
// xplat-todo: Support locale-specific seperator
return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
#endif
}
template <typename T>
JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
{
uint32 length = 0;
if (TypedArrayBase::Is(arr))
{
// For a TypedArray use the actual length of the array.
length = TypedArrayBase::FromVar(arr)->GetLength();
}
else
{
//For anything else, use the "length" property if present.
length = ItemTrace<T>::GetLength(arr, scriptContext);
}
if (length == 0 || scriptContext->CheckObject(arr))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
bool pushedObject = false;
TryFinally([&]()
{
scriptContext->PushObject(arr);
pushedObject = true;
Var element;
if (ItemTrace<T>::GetItem(arr, 0, &element, scriptContext))
{
res = JavascriptArray::ToLocaleStringHelper(element, scriptContext);
}
if (length > 1)
{
JavascriptString* separator = GetLocaleSeparator(scriptContext);
for (uint32 i = 1; i < length; i++)
{
res = JavascriptString::Concat(res, separator);
if (ItemTrace<T>::GetItem(arr, i, &element, scriptContext))
{
res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext));
}
}
}
},
[&](bool/*hasException*/)
{
if (pushedObject)
{
Var top = scriptContext->PopObject();
AssertMsg(top == arr, "Unmatched operation stack");
}
});
if (res == nullptr)
{
res = scriptContext->GetLibrary()->GetEmptyString();
}
return res;
}
Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
if (args.Info.Count < 2)
{
return scriptContext->GetLibrary()->GetFalse();
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
#endif
if (JavascriptOperators::IsArray(args[1]))
{
return scriptContext->GetLibrary()->GetTrue();
}
return scriptContext->GetLibrary()->GetFalse();
}
///----------------------------------------------------------------------------
/// Find() calls the given predicate callback on each element of the array, in
/// order, and returns the first element that makes the predicate return true,
/// as described in (ES6.0: S22.1.3.8).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
}
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
}
template <bool findIndex>
Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var element = nullptr;
Var testResult = nullptr;
if (pArr)
{
Var undefined = scriptContext->GetLibrary()->GetUndefined();
for (uint32 k = 0; k < length; k++)
{
element = undefined;
pArr->DirectGetItemAtFull(k, &element);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
pArr);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
else if (typedArrayBase)
{
for (uint32 k = 0; k < length; k++)
{
element = typedArrayBase->DirectGetItem(k);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
typedArrayBase);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
else
{
for (uint32 k = 0; k < length; k++)
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
obj);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
}
///----------------------------------------------------------------------------
/// FindIndex() calls the given predicate callback on each element of the
/// array, in order, and returns the index of the first element that makes the
/// predicate return true, as described in (ES6.0: S22.1.3.9).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
}
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
}
///----------------------------------------------------------------------------
/// Entries() returns a new ArrayIterator object configured to return key-
/// value pairs matching the elements of the this array/array-like object,
/// as described in (ES6.0: S22.1.3.4).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue);
}
///----------------------------------------------------------------------------
/// Keys() returns a new ArrayIterator object configured to return the keys
/// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key);
}
///----------------------------------------------------------------------------
/// Values() returns a new ArrayIterator object configured to return the values
/// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value);
}
Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
template <typename T>
Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
Var element = nullptr;
Var testResult = nullptr;
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
if (pArr)
{
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (uint32 k = 0; k < length; k++)
{
if (!typedArrayBase->HasItem(k))
{
continue;
}
element = typedArrayBase->DirectGetItem(k);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
else
{
for (T k = 0; k < length; k++)
{
// According to es6 spec, we need to call Has first before calling Get
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
}
return scriptContext->GetLibrary()->GetTrue();
}
Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
template <typename T>
Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var element = nullptr;
Var testResult = nullptr;
if (pArr)
{
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (uint32 k = 0; k < length; k++)
{
// If k < typedArrayBase->length, we know that HasItem will return true.
// But we still have to call it in case there's a proxy trap or in the case that we are calling
// Array.prototype.some with a TypedArray that has a different length instance property.
if (!typedArrayBase->HasItem(k))
{
continue;
}
element = typedArrayBase->DirectGetItem(k);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
else
{
for (T k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
}
return scriptContext->GetLibrary()->GetFalse();
}
Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* dynamicObject = nullptr;
RecyclableObject* callBackFn = nullptr;
Var thisArg = nullptr;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
pArr = JavascriptArray::FromVar(args[0]);
dynamicObject = pArr;
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
}
if (JavascriptArray::Is(dynamicObject) && scriptContext == JavascriptArray::FromVar(dynamicObject)->GetScriptContext())
{
pArr = JavascriptArray::FromVar(dynamicObject);
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
}
callBackFn = RecyclableObject::FromVar(args[1]);
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
auto fn32 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint32 k, Var element)
{
CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
dynamicObject);
};
auto fn64 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint64 k, Var element)
{
CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
dynamicObject);
};
if (pArr)
{
Assert(pArr == dynamicObject);
pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32);
}
else
{
if (length.IsSmallIndex())
{
TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32);
}
else
{
TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64);
}
}
return scriptContext->GetLibrary()->GetUndefined();
}
Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
int64 length;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.copyWithin"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
}
// Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
JavascriptLibrary* library = scriptContext->GetLibrary();
int64 fromVal = 0;
int64 toVal = 0;
int64 finalVal = length;
// If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
if (args.Info.Count > 1)
{
toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext);
if (args.Info.Count > 2)
{
fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
if (args.Info.Count > 3 && args[3] != library->GetUndefined())
{
finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
}
}
}
// If count would be negative or zero, we won't do anything so go ahead and return early.
if (finalVal <= fromVal || length <= toVal)
{
return obj;
}
// Make sure we won't underflow during the count calculation
Assert(finalVal > fromVal && length > toVal);
int64 count = min(finalVal - fromVal, length - toVal);
// We shouldn't have made it here if the count was going to be zero
Assert(count > 0);
int direction;
if (fromVal < toVal && toVal < (fromVal + count))
{
direction = -1;
fromVal += count - 1;
toVal += count - 1;
}
else
{
direction = 1;
}
// If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
// It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
|| (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
{
while (count > 0)
{
Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
if (JavascriptOperators::OP_HasItem(obj, index, scriptContext))
{
Var val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext);
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
else
{
JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
}
fromVal += direction;
toVal += direction;
count--;
}
}
else
{
Assert(fromVal < MaxArrayLength);
Assert(toVal < MaxArrayLength);
Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
uint32 fromIndex = static_cast<uint32>(fromVal);
uint32 toIndex = static_cast<uint32>(toVal);
while (count > 0)
{
if (obj->HasItem(fromIndex))
{
if (typedArrayBase)
{
Var val = typedArrayBase->DirectGetItem(fromIndex);
typedArrayBase->DirectSetItem(toIndex, val);
}
else if (pArr)
{
Var val = pArr->DirectGetItem(fromIndex);
pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
}
else
{
Var val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext);
JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
}
else
{
obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
}
fromIndex += direction;
toIndex += direction;
count--;
}
}
return obj;
}
Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
int64 length;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.fill"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
}
// Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
JavascriptLibrary* library = scriptContext->GetLibrary();
// If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
Var fillValue;
if (args.Info.Count > 1)
{
fillValue = args[1];
}
else
{
fillValue = library->GetUndefined();
}
int64 k = 0;
int64 finalVal = length;
if (args.Info.Count > 2)
{
k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
{
finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
}
}
if (k < MaxArrayLength)
{
int64 end = min<int64>(finalVal, MaxArrayLength);
uint32 u32k = static_cast<uint32>(k);
while (u32k < end)
{
if (typedArrayBase)
{
typedArrayBase->DirectSetItem(u32k, fillValue);
}
else if (pArr)
{
pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
}
else
{
JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
u32k++;
}
BigIndex dstIndex = MaxArrayLength;
for (int64 i = end; i < finalVal; ++i)
{
if (pArr)
{
pArr->DirectSetItemAt(dstIndex, fillValue);
++dstIndex;
}
else
{
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
}
}
else
{
BigIndex dstIndex = static_cast<uint64>(k);
for (int64 i = k; i < finalVal; i++)
{
if (pArr)
{
pArr->DirectSetItemAt(dstIndex, fillValue);
++dstIndex;
}
else
{
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
}
}
return obj;
}
// Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
}
}
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
if (length.IsSmallIndex())
{
return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
template<typename T>
Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
RecyclableObject* newObj = nullptr;
JavascriptArray* newArr = nullptr;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
bool isBuiltinArrayCtor = true;
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (isTypedArrayEntryPoint)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// If the entry point is %TypedArray%.prototype.map or the source object is an Array exotic object we should try to load the constructor property
// and use it to construct the return object.
if (isTypedArrayEntryPoint)
{
Var constructor = JavascriptOperators::SpeciesConstructor(
typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
if (JavascriptOperators::IsConstructor(constructor))
{
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext));
}
else if (isTypedArrayEntryPoint)
{
// We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.map was called
JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("[TypedArray].prototype.map"));
}
}
// skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
{
newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
}
if (newObj == nullptr)
{
if (length > UINT_MAX)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
newArr->EnsureHead<Var>();
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
Var element = nullptr;
Var mappedValue = nullptr;
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags callBackFnflags = CallFlags_Value;
CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
// We at least have to have newObj as a valid object
Assert(newObj);
if (pArr != nullptr)
{
// If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
// If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
if (newArr && isBuiltinArrayCtor)
{
newArr->DirectSetItemAt(k, mappedValue);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue), scriptContext, k);
}
}
}
else if (typedArrayBase != nullptr)
{
// Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
TypedArrayBase* newTypedArray = nullptr;
if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
for (uint32 k = 0; k < length; k++)
{
// We can't rely on the length value being equal to typedArrayBase->GetLength() because user code may lie and
// attach any length property to a TypedArray instance and pass it as this parameter when .calling
// Array.prototype.map.
if (!typedArrayBase->HasItem(k))
{
// We know that if HasItem returns false, all the future calls to HasItem will return false as well since
// we visit the items in order. We could return early here except that we have to continue calling HasItem
// on all the subsequent items according to the spec.
continue;
}
element = typedArrayBase->DirectGetItem(k);
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
// If newObj is a TypedArray, set the mappedValue directly, otherwise see if it's an array and finally fall back to
// the normal Set path.
if (newTypedArray)
{
newTypedArray->DirectSetItem(k, mappedValue);
}
else if (newArr)
{
newArr->DirectSetItemAt(k, mappedValue);
}
else
{
JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue);
}
}
}
else
{
for (uint32 k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (newArr && isBuiltinArrayCtor)
{
newArr->SetItem(k, mappedValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue), scriptContext, k);
}
}
}
}
#ifdef VALIDATE_ARRAY
if (JavascriptArray::Is(newObj))
{
newArr->ValidateArray();
}
#endif
return newObj;
}
Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* dynamicObject = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
dynamicObject = pArr;
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::FilterHelper(pArr, dynamicObject, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::FilterHelper(pArr, dynamicObject, length.GetBigIndex(), args, scriptContext);
}
template <typename T>
Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If the source object is an Array exotic object we should try to load the constructor property and use it to construct the return object.
bool isBuiltinArrayCtor = true;
RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
JavascriptArray* newArr = nullptr;
if (newObj == nullptr)
{
newArr = scriptContext->GetLibrary()->CreateArray(0);
newArr->EnsureHead<Var>();
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
Var element = nullptr;
Var selected = nullptr;
if (pArr)
{
Assert(length <= MaxArrayLength);
uint32 i = 0;
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
selected = CALL_ENTRYPOINT(callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (JavascriptConversion::ToBoolean(selected, scriptContext))
{
// Try to fast path if the return object is an array
if (newArr && isBuiltinArrayCtor)
{
newArr->DirectSetItemAt(i, element);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
++i;
}
}
}
else
{
BigIndex i = 0u;
for (T k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
selected = CALL_ENTRYPOINT(callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (JavascriptConversion::ToBoolean(selected, scriptContext))
{
if (newArr)
{
newArr->DirectSetItemAt(i, element);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
++i;
}
}
}
}
#ifdef VALIDATE_ARRAY
if (newArr)
{
newArr->ValidateArray();
}
#endif
return newObj;
}
Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
}
BigIndex length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
template <typename T>
Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
}
}
// If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
T k = 0;
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var accumulator = nullptr;
Var element = nullptr;
if (args.Info.Count > 2)
{
accumulator = args[2];
}
else
{
if (length == 0)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
bool bPresent = false;
if (pArr)
{
for (; k < length && bPresent == false; k++)
{
if (!pArr->DirectGetItemAtFull((uint32)k, &element))
{
continue;
}
bPresent = true;
accumulator = element;
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length && bPresent == false; k++)
{
if (!typedArrayBase->HasItem((uint32)k))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)k);
bPresent = true;
accumulator = element;
}
}
else
{
for (; k < length && bPresent == false; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
accumulator = JavascriptOperators::GetItem(obj, k, scriptContext);
bPresent = true;
}
}
}
if (bPresent == false)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
}
Assert(accumulator);
Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
if (pArr)
{
for (; k < length; k++)
{
if (!pArr->DirectGetItemAtFull((uint32)k, &element))
{
continue;
}
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length; k++)
{
if (!typedArrayBase->HasItem((uint32)k))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)k);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
}
}
else
{
for (; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
}
}
}
return accumulator;
}
Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
}
BigIndex length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
template <typename T>
Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
}
}
// If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var accumulator = nullptr;
Var element = nullptr;
T k = 0;
T index = 0;
if (args.Info.Count > 2)
{
accumulator = args[2];
}
else
{
if (length == 0)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
bool bPresent = false;
if (pArr)
{
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (!pArr->DirectGetItemAtFull((uint32)index, &element))
{
continue;
}
bPresent = true;
accumulator = element;
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (!typedArrayBase->HasItem((uint32)index))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)index);
bPresent = true;
accumulator = element;
}
}
else
{
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (JavascriptOperators::HasItem(obj, index))
{
accumulator = JavascriptOperators::GetItem(obj, index, scriptContext);
bPresent = true;
}
}
}
if (bPresent == false)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
if (pArr)
{
for (; k < length; k++)
{
index = length - k - 1;
if (!pArr->DirectGetItemAtFull((uint32)index, &element))
{
continue;
}
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
pArr);
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length; k++)
{
index = length - k - 1;
if (!typedArrayBase->HasItem((uint32) index))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)index);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
typedArrayBase);
}
}
else
{
for (; k < length; k++)
{
index = length - k - 1;
if (JavascriptOperators::HasItem(obj, index))
{
element = JavascriptOperators::GetItem(obj, index, scriptContext);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
obj);
}
}
}
return accumulator;
}
Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
Assert(!(callInfo.Flags & CallFlags_New));
JavascriptLibrary* library = scriptContext->GetLibrary();
RecyclableObject* constructor = nullptr;
if (JavascriptOperators::IsConstructor(args[0]))
{
constructor = RecyclableObject::FromVar(args[0]);
}
RecyclableObject* items = nullptr;
if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
}
JavascriptArray* itemsArr = nullptr;
if (JavascriptArray::Is(items))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
#endif
itemsArr = JavascriptArray::FromVar(items);
}
bool mapping = false;
JavascriptFunction* mapFn = nullptr;
Var mapFnThisArg = nullptr;
if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
{
if (!JavascriptFunction::Is(args[2]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
}
mapFn = JavascriptFunction::FromVar(args[2]);
if (args.Info.Count >= 4)
{
mapFnThisArg = args[3];
}
else
{
mapFnThisArg = library->GetUndefined();
}
mapping = true;
}
RecyclableObject* newObj = nullptr;
JavascriptArray* newArr = nullptr;
RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */);
if (iterator != nullptr)
{
if (constructor)
{
Js::Var constructorArgs[] = { constructor };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
{
newArr = scriptContext->GetLibrary()->CreateArray(0);
newArr->EnsureHead<Var>();
newObj = newArr;
}
uint32 k = 0;
JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
if (mapping)
{
Assert(mapFn != nullptr);
Assert(mapFnThisArg != nullptr);
Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
}
if (newArr)
{
newArr->SetItem(k, nextValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, nextValue), scriptContext, k);
}
k++;
});
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
else
{
Var lenValue = JavascriptOperators::OP_GetLength(items, scriptContext);
int64 len = JavascriptConversion::ToLength(lenValue, scriptContext);
if (constructor)
{
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
{
// Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
if (len > MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
}
// Static cast len should be valid (len < 2^32) or we would throw above
newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
newArr->EnsureHead<Var>();
newObj = newArr;
}
uint32 k = 0;
for ( ; k < len; k++)
{
Var kValue;
if (itemsArr)
{
kValue = itemsArr->DirectGetItem(k);
}
else
{
kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext);
}
if (mapping)
{
Assert(mapFn != nullptr);
Assert(mapFnThisArg != nullptr);
Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
}
if (newArr)
{
newArr->SetItem(k, kValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k);
}
}
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
return newObj;
}
Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
}
return JavascriptArray::OfHelper(false, args, scriptContext);
}
Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
Assert(args.Info.Count > 0);
return args[0];
}
// Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
// args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
uint32 len = args.Info.Count - 1;
Var newObj = nullptr;
JavascriptArray* newArr = nullptr;
TypedArrayBase* newTypedArray = nullptr;
bool isBuiltinArrayCtor = true;
if (JavascriptOperators::IsConstructor(args[0]))
{
RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = isTypedArrayEntryPoint ?
TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext) :
JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
else if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
}
else
{
// We only throw when the constructor property is not a constructor function in the TypedArray version
if (isTypedArrayEntryPoint)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
}
newArr = scriptContext->GetLibrary()->CreateArray(len);
newArr->EnsureHead<Var>();
newObj = newArr;
}
// At least we have a new object of some kind
Assert(newObj);
if (isBuiltinArrayCtor)
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
newArr->DirectSetItemAt(k, kValue);
}
}
else if (newTypedArray)
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
newTypedArray->DirectSetItem(k, kValue);
}
}
else
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k);
}
}
if (!isTypedArrayEntryPoint)
{
// Set length if we are in the Array version of the function
JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible);
}
return newObj;
}
JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
{
TypeId typeId = JavascriptOperators::GetTypeId(value);
if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
return JavascriptConversion::ToLocaleString(value, scriptContext);
}
}
inline BOOL JavascriptArray::IsFullArray() const
{
if (head && head->length == length)
{
AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
return true;
}
return (0 == length);
}
/*
* IsFillFromPrototypes
* - Check the array has no missing values and only head segment.
* - Also ensure if the lengths match.
*/
bool JavascriptArray::IsFillFromPrototypes()
{
return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
}
// Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
// typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
{
if (startIndex >= limitIndex)
{
return;
}
RecyclableObject* prototype = this->GetPrototype();
// Fill all missing values by walking through prototype
while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
this->SetItem(index, value, PropertyOperation_None);
});
prototype = prototype->GetPrototype();
}
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
}
//
// JavascriptArray requires head->left == 0 for fast path Get.
//
template<typename T>
void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
{
if (head == nullptr || head->left != 0)
{
// This is used to fix up altered arrays.
// any SegmentMap would be invalid at this point.
ClearSegmentMap();
//
// We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
// some protection here. Save the head and switch this array to EmptySegment. Will be restored
// correctly if allocating new segment succeeds.
//
SparseArraySegment<T>* savedHead = (SparseArraySegment<T>*)this->head;
SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
newSeg->next = savedHead;
this->head = newSeg;
SetHasNoMissingValues();
this->SetLastUsedSegment(savedLastUsedSegment);
}
}
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
void JavascriptArray::CheckForceES5Array()
{
if (Configuration::Global.flags.ForceES5Array)
{
// There's a bad interaction with the jitted code for native array creation here.
// ForceES5Array doesn't interact well with native arrays
if (PHASE_OFF1(NativeArrayPhase))
{
GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
}
}
}
#endif
template <typename T, typename Fn>
void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, T destIndex, Fn fn)
{
Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
Var oldValue;
JavascriptArray* arr = nullptr;
if (DynamicObject::IsAnyArray(obj))
{
arr = JavascriptArray::FromAnyArray(obj);
}
else if (DynamicType::Is(obj->GetTypeId()))
{
DynamicObject* dynobj = DynamicObject::FromVar(obj);
ArrayObject* objectArray = dynobj->GetObjectArray();
arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
}
if (arr != nullptr)
{
if (JavascriptArray::Is(arr))
{
arr = EnsureNonNativeArray(arr);
ArrayElementEnumerator e(arr, startIndex, limitIndex);
while(e.MoveNext<Var>())
{
uint32 index = e.GetIndex();
if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
{
T n = destIndex + (index - startIndex);
if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
{
fn(index, e.GetItem<Var>());
}
}
}
}
else
{
ScriptContext* scriptContext = obj->GetScriptContext();
Assert(ES5Array::Is(arr));
ES5Array* es5Array = ES5Array::FromVar(arr);
ES5ArrayIndexStaticEnumerator<true> e(es5Array);
while (e.MoveNext())
{
uint32 index = e.GetIndex();
if (index < startIndex) continue;
else if (index >= limitIndex) break;
if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
{
T n = destIndex + (index - startIndex);
if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
{
Var value = nullptr;
if (JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext))
{
fn(index, value);
}
}
}
}
}
}
}
//
// ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
//
JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
: start(start), end(min(end, arr->length))
{
Init(arr);
}
//
// Initialize this enumerator and prepare for the first MoveNext.
//
void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
{
// Find start segment
seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
while (seg && (seg->left + seg->length <= start))
{
seg = seg->next;
}
// Set start index and endIndex
if (seg)
{
if (seg->left >= end)
{
seg = nullptr;
}
else
{
// set index to be at target index - 1, so MoveNext will move to target
index = max(seg->left, start) - seg->left - 1;
endIndex = min(end - seg->left, seg->length);
}
}
}
//
// Move to the next element if available.
//
template<typename T>
inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
{
while (seg)
{
// Look for next non-null item in current segment
while (++index < endIndex)
{
if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
{
return true;
}
}
// Move to next segment
seg = seg->next;
if (seg)
{
if (seg->left >= end)
{
seg = nullptr;
break;
}
else
{
index = static_cast<uint32>(-1);
endIndex = min(end - seg->left, seg->length);
}
}
}
return false;
}
//
// Get current array element index.
//
uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
{
Assert(seg && index < seg->length && index < endIndex);
return seg->left + index;
}
//
// Get current array element value.
//
template<typename T>
T JavascriptArray::ArrayElementEnumerator::GetItem() const
{
Assert(seg && index < seg->length && index < endIndex &&
!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
return ((SparseArraySegment<T>*)seg)->elements[index];
}
//
// Construct a BigIndex initialized to a given uint32 (small index).
//
JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
: index(initIndex), bigIndex(InvalidIndex)
{
//ok if initIndex == InvalidIndex
}
//
// Construct a BigIndex initialized to a given uint64 (large or small index).
//
JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
: index(InvalidIndex), bigIndex(initIndex)
{
if (bigIndex < InvalidIndex) // if it's actually small index
{
index = static_cast<uint32>(bigIndex);
bigIndex = InvalidIndex;
}
}
bool JavascriptArray::BigIndex::IsUint32Max() const
{
return index == InvalidIndex && bigIndex == InvalidIndex;
}
bool JavascriptArray::BigIndex::IsSmallIndex() const
{
return index < InvalidIndex;
}
uint32 JavascriptArray::BigIndex::GetSmallIndex() const
{
Assert(IsSmallIndex());
return index;
}
uint64 JavascriptArray::BigIndex::GetBigIndex() const
{
Assert(!IsSmallIndex());
return bigIndex;
}
//
// Convert this index value to a JS number
//
Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
{
if (IsSmallIndex())
{
return small_index::ToNumber(index, scriptContext);
}
else
{
return JavascriptNumber::ToVar(bigIndex, scriptContext);
}
}
//
// Increment this index by 1.
//
const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
{
if (IsSmallIndex())
{
++index;
// If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
}
else
{
bigIndex = bigIndex + 1;
}
return *this;
}
//
// Decrement this index by 1.
//
const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
{
if (IsSmallIndex())
{
--index;
}
else
{
Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
--bigIndex;
if (bigIndex < InvalidIndex)
{
index = InvalidIndex - 1;
bigIndex = InvalidIndex;
}
}
return *this;
}
JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
{
if (delta.IsSmallIndex())
{
return operator+(delta.GetSmallIndex());
}
if (IsSmallIndex())
{
return index + delta.GetBigIndex();
}
return bigIndex + delta.GetBigIndex();
}
//
// Get a new BigIndex representing this + delta.
//
JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
{
if (IsSmallIndex())
{
uint32 newIndex;
if (UInt32Math::Add(index, delta, &newIndex))
{
return static_cast<uint64>(index) + static_cast<uint64>(delta);
}
else
{
return newIndex; // ok if newIndex == InvalidIndex
}
}
else
{
return bigIndex + static_cast<uint64>(delta);
}
}
bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() == rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
}
return this->GetBigIndex() == rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() > rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
}
return this->GetBigIndex() > rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() < rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
}
return this->GetBigIndex() < rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() <= rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
}
return this->GetBigIndex() <= rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() >= rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
}
return this->GetBigIndex() >= rhs.GetBigIndex();
}
BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
{
if (IsSmallIndex())
{
return small_index::GetItem(arr, index, outVal);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
}
}
BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
{
if (IsSmallIndex())
{
return small_index::SetItem(arr, index, newValue);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
}
}
void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
{
if (IsSmallIndex())
{
small_index::SetItemIfNotExist(arr, index, newValue);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
Var oldValue;
PropertyId propertyId = propertyRecord->GetPropertyId();
if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
{
arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
}
}
}
BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
{
if (IsSmallIndex())
{
return small_index::DeleteItem(arr, index);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
}
}
BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
{
if (IsSmallIndex())
{
return small_index::SetItem(obj, index, newValue, flags);
}
else
{
ScriptContext* scriptContext = obj->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
}
}
BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
{
if (IsSmallIndex())
{
return small_index::DeleteItem(obj, index, flags);
}
else
{
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
}
}
//
// Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
//
void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
{
Assert(!dstIndex.IsSmallIndex());
typedef IndexTrace<BigIndex> index_trace;
BigIndex dst = dstIndex;
uint32 i = start;
ArrayElementEnumerator e(this, start);
while(e.MoveNext<Var>())
{
// delete all items not enumerated
while (i < e.GetIndex())
{
index_trace::DeleteItem(this, dst);
++i;
++dst;
}
// Copy over the item
index_trace::SetItem(this, dst, e.GetItem<Var>());
++i;
++dst;
}
// Delete the rest till length
while (i < this->length)
{
index_trace::DeleteItem(this, dst);
++i;
++dst;
}
// Elements moved, truncate the array at start
SetLength(start);
}
//
// Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
//
template<typename T>
void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<Var>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<Var>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
//
// Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index. If the index grows larger than
// "array index", it will automatically turn to SetProperty using the index as property name.
//
void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
template <typename T>
void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
#endif
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
#endif
if (JavascriptNativeIntArray::Is(srcArray))
{
CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
}
else if (JavascriptNativeFloatArray::Is(srcArray))
{
CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
}
else
{
CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyNativeIntArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<int32>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyNativeFloatArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<double>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<double>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
#endif
if (JavascriptNativeIntArray::Is(arr))
{
arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
}
else if (JavascriptNativeFloatArray::Is(arr))
{
arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
}
return arr;
}
BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
ScriptContext* requestContext = type->GetScriptContext();
if (JavascriptNativeIntArray::GetItem(this, index, outVal, requestContext))
{
return TRUE;
}
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
ScriptContext* requestContext = type->GetScriptContext();
if (JavascriptNativeFloatArray::GetItem(this, index, outVal, requestContext))
{
return TRUE;
}
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
template<typename T>
void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ScriptContext *scriptContext = dstArray->GetScriptContext();
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
template<typename T>
void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ScriptContext *scriptContext = dstArray->GetScriptContext();
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<double>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
{
// At this stage we have an array literal with some arguments to be spread.
// First we need to calculate the real size of the final literal.
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
#endif
JavascriptArray *array = FromVar(arrayToSpread);
uint32 actualLength = array->GetLength();
for (unsigned i = 0; i < spreadIndices->count; ++i)
{
actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext));
}
JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
// Now we copy each element and expand the spread parameters inline.
for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < array->GetLength() && resultIndex < actualLength; ++i)
{
uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
// An array needs a slow copy if it is a cross-site object or we have missing values that need to be set to undefined.
auto needArraySlowCopy = [&](Var instance) {
if (JavascriptArray::Is(instance))
{
JavascriptArray *arr = JavascriptArray::FromVar(instance);
return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes();
}
return false;
};
// Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
auto slowCopy = [&scriptContext, &needArraySlowCopy](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
RecyclableObject *propertyObject;
if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
}
for (uint32 j = start; j < end; j++)
{
Var element;
if (!JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext))
{
// Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
element = scriptContext->GetLibrary()->GetUndefined();
}
dstArray->DirectSetItemAt(dstIndex++, element);
}
};
if (i < spreadIndex)
{
// Any non-spread elements can be copied in bulk.
if (needArraySlowCopy(array))
{
slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex);
}
resultIndex += spreadIndex - i;
i = spreadIndex - 1;
continue;
}
else if (i > spreadIndex)
{
// Any non-spread elements terminating the array can also be copied in bulk.
Assert(spreadArrIndex == spreadIndices->count - 1);
if (needArraySlowCopy(array))
{
slowCopy(result, resultIndex, array, i, array->GetLength());
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, array, i, array->GetLength());
}
break;
}
else
{
Var instance = array->DirectGetItem(i);
if (SpreadArgument::Is(instance))
{
SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
uint32 len = spreadArgument->GetArgumentSpreadCount();
const Var* spreadItems = spreadArgument->GetArgumentSpread();
for (uint32 j = 0; j < len; j++)
{
result->DirectSetItemAt(resultIndex++, spreadItems[j]);
}
}
else
{
AssertMsg(JavascriptArray::Is(instance) || TypedArrayBase::Is(instance), "Only SpreadArgument, TypedArray, and JavascriptArray should be listed as spread arguments");
// We first try to interpret the spread parameter as a JavascriptArray.
JavascriptArray *arr = nullptr;
if (JavascriptArray::Is(instance))
{
arr = JavascriptArray::FromVar(instance);
}
if (arr != nullptr)
{
if (arr->GetLength() > 0)
{
if (needArraySlowCopy(arr))
{
slowCopy(result, resultIndex, arr, 0, arr->GetLength());
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, arr, 0, arr->GetLength());
}
resultIndex += arr->GetLength();
}
}
else
{
uint32 len = GetSpreadArgLen(instance, scriptContext);
slowCopy(result, resultIndex, instance, 0, len);
resultIndex += len;
}
}
if (spreadArrIndex < spreadIndices->count - 1)
{
spreadArrIndex++;
}
}
}
return result;
}
uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
{
// A spread argument can be anything that returns a 'length' property, even if that
// property is null or undefined.
spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
if (JavascriptArray::Is(spreadArg))
{
JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
return arr->GetLength();
}
if (TypedArrayBase::Is(spreadArg))
{
TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
return tarr->GetLength();
}
if (SpreadArgument::Is(spreadArg))
{
SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
return spreadFunctionArgs->GetArgumentSpreadCount();
}
AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
Throw::FatalInternalError();
}
#ifdef VALIDATE_ARRAY
class ArraySegmentsVisitor
{
private:
SparseArraySegmentBase* seg;
public:
ArraySegmentsVisitor(SparseArraySegmentBase* head)
: seg(head)
{
}
void operator()(SparseArraySegmentBase* s)
{
Assert(seg == s);
if (seg)
{
seg = seg->next;
}
}
};
void JavascriptArray::ValidateArrayCommon()
{
SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
// Simple segments validation
bool foundLastUsedSegment = false;
SparseArraySegmentBase *seg = head;
while(seg != nullptr)
{
if (seg == lastUsedSegment)
{
foundLastUsedSegment = true;
}
AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
SparseArraySegmentBase* next = seg->next;
if (next != nullptr)
{
AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
else
{
AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
}
seg = next;
}
AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
// Validate segmentMap if present
if (HasSegmentMap())
{
ArraySegmentsVisitor visitor(head);
GetSegmentMap()->Walk(visitor);
}
}
void JavascriptArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateVarSegment((SparseArraySegment<Var>*)head);
}
void JavascriptNativeIntArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
#if DBG
SparseArraySegmentBase *seg = head;
while (seg)
{
if (seg->next != nullptr)
{
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
seg = seg->next;
}
#endif
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateSegment<int32>((SparseArraySegment<int32>*)head);
}
void JavascriptNativeFloatArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
#if DBG
SparseArraySegmentBase *seg = head;
while (seg)
{
if (seg->next != nullptr)
{
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
seg = seg->next;
}
#endif
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateSegment<double>((SparseArraySegment<double>*)head);
}
void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
int32 inspect;
double inspectDouble;
while (seg)
{
uint32 i = 0;
for (i = 0; i < seg->length; i++)
{
if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
{
continue;
}
if (TaggedInt::Is(seg->elements[i]))
{
inspect = TaggedInt::ToInt32(seg->elements[i]);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
{
inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
}
else
{
AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
}
}
ValidateSegment(seg);
seg = (SparseArraySegment<Var>*)seg->next;
}
}
template<typename T>
void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
while (seg)
{
uint32 i = seg->length;
while (i < seg->size)
{
AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
i++;
}
seg = (SparseArraySegment<T>*)seg->next;
}
}
#endif
template <typename T>
void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
{
// Don't copy the segment map, we will build it again
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
SetHeadAndLastUsedSegment(dst);
dst->left = src->left;
dst->length = src->length;
dst->size = src->size;
dst->next = src->next;
js_memcpy_s(dst->elements, sizeof(T) * dst->size, src->elements, sizeof(T) * src->size);
}
JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
: ArrayObject(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), (SparseArraySegment<Var>*)instance->head);
}
else
{
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
head = instance->head;
SetLastUsedSegment(instance->GetLastUsedSegment());
}
}
template <typename T>
T * JavascriptArray::BoxStackInstance(T * instance)
{
Assert(ThreadContext::IsOnStack(instance));
// On the stack, the we reserved a pointer before the object as to store the boxed value
T ** boxedInstanceRef = ((T **)instance) - 1;
T * boxedInstance = *boxedInstanceRef;
if (boxedInstance)
{
return boxedInstance;
}
const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
if (ThreadContext::IsOnStack(instance->head))
{
boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
T, instance, true);
}
else if(inlineSlotsSize)
{
boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
}
else
{
boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
}
*boxedInstanceRef = boxedInstance;
return boxedInstance;
}
JavascriptArray *
JavascriptArray::BoxStackInstance(JavascriptArray * instance)
{
return BoxStackInstance<JavascriptArray>(instance);
}
#if ENABLE_TTD
void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
ScriptContext* ctx = this->GetScriptContext();
uint32 index = Js::JavascriptArray::InvalidIndex;
while(true)
{
index = this->GetNextIndex(index);
if(index == Js::JavascriptArray::InvalidIndex) // End of array
{
break;
}
Js::Var aval = nullptr;
if(this->DirectGetVarItemAt(index, &aval, ctx))
{
extractor->MarkVisitVar(aval);
}
}
}
void JavascriptArray::ProcessCorePaths()
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
ScriptContext* ctx = this->GetScriptContext();
uint32 index = Js::JavascriptArray::InvalidIndex;
while(true)
{
index = this->GetNextIndex(index);
if(index == Js::JavascriptArray::InvalidIndex) // End of array
{
break;
}
Js::Var aval = nullptr;
if(this->DirectGetVarItemAt(index, &aval, ctx))
{
TTD::UtilSupport::TTAutoString pathExt;
ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
}
}
}
TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
}
void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
}
#endif
JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
JavascriptArray(instance, false),
weakRefToFuncBody(instance->weakRefToFuncBody)
{
}
JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
JavascriptNativeArray(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), (SparseArraySegment<int>*)instance->head);
}
else
{
// Base class ctor should have copied these
Assert(head == instance->head);
Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
}
}
JavascriptNativeIntArray *
JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
{
return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
}
#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
}
void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
}
#if ENABLE_COPYONACCESS_ARRAY
TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::Invalid;
}
void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(false, "Not implemented yet!!!");
}
#endif
#endif
JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
JavascriptNativeArray(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), (SparseArraySegment<double>*)instance->head);
}
else
{
// Base class ctor should have copied these
Assert(head == instance->head);
Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
}
}
JavascriptNativeFloatArray *
JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
{
return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
}
#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
}
void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
}
#endif
template<typename T>
RecyclableObject*
JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
{
if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
{
return nullptr;
}
if (JavascriptArray::Is(originalArray)
&& !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
&& DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
&& !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
{
return nullptr;
}
Var constructor = scriptContext->GetLibrary()->GetUndefined();
if (JavascriptOperators::IsArray(originalArray))
{
if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
{
return nullptr;
}
if (JavascriptOperators::IsConstructor(constructor))
{
ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
if (constructorScriptContext != scriptContext)
{
if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
{
constructor = scriptContext->GetLibrary()->GetUndefined();
}
}
}
if (JavascriptOperators::IsObject(constructor))
{
if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
{
if (pIsBuiltinArrayCtor != nullptr)
{
*pIsBuiltinArrayCtor = false;
}
return nullptr;
}
if (constructor == scriptContext->GetLibrary()->GetNull())
{
constructor = scriptContext->GetLibrary()->GetUndefined();
}
}
}
if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
{
if (length > UINT_MAX)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
if (nullptr == pIsIntArray)
{
return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
}
else
{
// If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
}
}
if (!JavascriptOperators::IsConstructor(constructor))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
}
if (pIsBuiltinArrayCtor != nullptr)
{
*pIsBuiltinArrayCtor = false;
}
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
}
/*static*/
PropertyId const JavascriptArray::specialPropertyIds[] =
{
PropertyIds::length
};
BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::DeleteProperty(propertyId, flags);
}
BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
{
JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
if (BuiltInPropertyRecords::length.Equals(propertyName))
{
return false;
}
return DynamicObject::DeleteProperty(propertyNameString, flags);
}
BOOL JavascriptArray::HasProperty(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return true;
}
ScriptContext* scriptContext = GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return this->HasItem(index);
}
return DynamicObject::HasProperty(propertyId);
}
BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::IsEnumerable(propertyId);
}
BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::IsConfigurable(propertyId);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
{
if (propertyId == PropertyIds::length)
{
Assert(!value); // Can't change array length enumerable
return true;
}
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetEnumerable(this, propertyId, value);
}
return __super::SetEnumerable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
{
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetWritable(this, propertyId, value);
}
return __super::SetWritable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
{
if (propertyId == PropertyIds::length)
{
Assert(!value); // Can't change array length configurable
return true;
}
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetConfigurable(this, propertyId, value);
}
return __super::SetConfigurable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
{
ScriptContext* scriptContext = this->GetScriptContext();
// SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
// changed, we need to handle it here.
Assert(propertyId != PropertyIds::length);
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAttributes(this, index, attributes);
}
return __super::SetAttributes(propertyId, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
{
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAccessors(this, index, getter, setter);
}
return __super::SetAccessors(propertyId, getter, setter, flags);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemWithAttributes(this, index, value, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAttributes(this, index, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAccessors(this, index, getter, setter);
}
// Check if this objectArray isFrozen.
BOOL JavascriptArray::IsObjectArrayFrozen()
{
// If this is still a JavascriptArray, it's not frozen.
return false;
}
JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
{
if (!!(flags & EnumeratorFlags::SnapShotSemantics))
{
return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
}
return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
}
BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
{
return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
}
BOOL JavascriptArray::IsItemEnumerable(uint32 index)
{
return true;
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::PreventExtensions()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::Seal()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::Freeze()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
}
BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext)
{
if (index == 0)
{
*propertyName = requestContext->GetPropertyString(PropertyIds::length);
return true;
}
return false;
}
// Returns the number of special non-enumerable properties this type has.
uint JavascriptArray::GetSpecialPropertyCount() const
{
return _countof(specialPropertyIds);
}
// Returns the list of special non-enumerable properties for the type.
PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
{
return specialPropertyIds;
}
BOOL JavascriptArray::GetPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
return JavascriptArray::GetProperty(originalInstance, propertyId, value, info, requestContext);
}
BOOL JavascriptArray::GetProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
if (GetPropertyBuiltIns(propertyId, value))
{
return true;
}
ScriptContext* scriptContext = GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return this->GetItem(this, index, value, scriptContext);
}
return DynamicObject::GetProperty(originalInstance, propertyId, value, info, requestContext);
}
BOOL JavascriptArray::GetProperty(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
"Numeric property names should have been converted to uint or PropertyRecord*");
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
{
return true;
}
return DynamicObject::GetProperty(originalInstance, propertyNameString, value, info, requestContext);
}
BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
{
//
// length being accessed. Return array length
//
if (propertyId == PropertyIds::length)
{
*value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
return true;
}
return false;
}
BOOL JavascriptArray::HasItem(uint32 index)
{
Var value;
return this->DirectGetItemAt<Var>(index, &value);
}
BOOL JavascriptArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptNativeIntArray::HasItem(uint32 index)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
int32 value;
return this->DirectGetItemAt<int32>(index, &value);
}
BOOL JavascriptNativeFloatArray::HasItem(uint32 index)
{
double dvalue;
return this->DirectGetItemAt<double>(index, &dvalue);
}
BOOL JavascriptNativeIntArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
return JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext);
}
BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
int32 intvalue;
if (!this->DirectGetItemAt<int32>(index, &intvalue))
{
return FALSE;
}
*value = JavascriptNumber::ToVar(intvalue, requestContext);
return TRUE;
}
BOOL JavascriptNativeIntArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeIntArray::GetItem(originalInstance, index, value, requestContext);
}
BOOL JavascriptNativeFloatArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext);
}
BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
double dvalue;
int32 ivalue;
if (!this->DirectGetItemAt<double>(index, &dvalue))
{
return FALSE;
}
if (*(uint64*)&dvalue == 0ull)
{
*value = TaggedInt::ToVarUnchecked(0);
}
else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
{
*value = TaggedInt::ToVarUnchecked(ivalue);
}
else
{
*value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
}
return TRUE;
}
BOOL JavascriptNativeFloatArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeFloatArray::GetItem(originalInstance, index, value, requestContext);
}
BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
uint32 indexValue;
if (propertyId == PropertyIds::length)
{
return this->SetLength(value);
}
else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
{
// Call this or subclass method
return SetItem(indexValue, value, flags);
}
else
{
return DynamicObject::SetProperty(propertyId, value, flags, info);
}
}
BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
{
AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
"Numeric property names should have been converted to uint or PropertyRecord*");
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
{
return this->SetLength(value);
}
return DynamicObject::SetProperty(propertyNameString, value, flags, info);
}
BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
ScriptContext* scriptContext = GetScriptContext();
if (propertyId == PropertyIds::length)
{
Assert(attributes == PropertyWritable);
Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
return this->SetLength(value);
}
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
// Call this or subclass method
return SetItemWithAttributes(index, value, attributes);
}
return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
}
BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
this->DirectSetItemAt(index, value);
return true;
}
BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
int32 iValue;
double dValue;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
if (typeId == TypeIds_NativeIntArray)
{
this->SetItem(index, iValue);
}
else if (typeId == TypeIds_NativeFloatArray)
{
reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
}
else
{
this->DirectSetItemAt<Var>(index, value);
}
return TRUE;
}
TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
{
if (TaggedInt::Is(value))
{
int32 i = TaggedInt::ToInt32(value);
if (i != JavascriptNativeIntArray::MissingItem)
{
*iValue = i;
return TypeIds_NativeIntArray;
}
}
if (JavascriptNumber::Is_NoTaggedIntCheck(value))
{
bool isInt32;
int32 i;
double d = JavascriptNumber::GetValue(value);
if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
{
if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
{
*iValue = i;
return TypeIds_NativeIntArray;
}
}
else
{
*dValue = d;
JavascriptNativeIntArray::ToNativeFloatArray(this);
return TypeIds_NativeFloatArray;
}
}
JavascriptNativeIntArray::ToVarArray(this);
return TypeIds_Array;
}
BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
{
if (iValue == JavascriptNativeIntArray::MissingItem)
{
JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
return TRUE;
}
this->DirectSetItemAt(index, iValue);
return TRUE;
}
BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
double dValue;
TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
if (typeId == TypeIds_NativeFloatArray)
{
this->SetItem(index, dValue);
}
else
{
this->DirectSetItemAt(index, value);
}
return TRUE;
}
TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
{
if (TaggedInt::Is(value))
{
*dValue = (double)TaggedInt::ToInt32(value);
return TypeIds_NativeFloatArray;
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
{
*dValue = JavascriptNumber::GetValue(value);
return TypeIds_NativeFloatArray;
}
JavascriptNativeFloatArray::ToVarArray(this);
return TypeIds_Array;
}
BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
{
if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
{
JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
return TRUE;
}
this->DirectSetItemAt<double>(index, dValue);
return TRUE;
}
BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<Var>(index);
}
BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<int32>(index);
}
BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<double>(index);
}
BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
{
return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
}
BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
{
stringBuilder->Append(_u('['));
if (this->length < 10)
{
auto funcPtr = [&]()
{
ENTER_PINNED_SCOPE(JavascriptString, valueStr);
valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
LEAVE_PINNED_SCOPE();
};
if (!requestContext->GetThreadContext()->IsScriptActive())
{
BEGIN_JS_RUNTIME_CALL(requestContext);
{
funcPtr();
}
END_JS_RUNTIME_CALL(requestContext);
}
else
{
funcPtr();
}
}
else
{
stringBuilder->AppendCppLiteral(_u("..."));
}
stringBuilder->Append(_u(']'));
return TRUE;
}
BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
{
stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
return TRUE;
}
bool JavascriptNativeArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeArray::Is(typeId);
}
bool JavascriptNativeArray::Is(TypeId typeId)
{
return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
}
JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
}
bool JavascriptNativeIntArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeIntArray::Is(typeId);
}
#if ENABLE_COPYONACCESS_ARRAY
bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
}
#endif
bool JavascriptNativeIntArray::Is(TypeId typeId)
{
return typeId == TypeIds_NativeIntArray;
}
#if ENABLE_COPYONACCESS_ARRAY
bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
{
return typeId == TypeIds_CopyOnAccessNativeIntArray;
}
#endif
bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
{
bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
return ret;
}
JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
}
#endif
bool JavascriptNativeFloatArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeFloatArray::Is(typeId);
}
bool JavascriptNativeFloatArray::Is(TypeId typeId)
{
return typeId == TypeIds_NativeFloatArray;
}
bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
{
bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
return ret;
}
JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
}
template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
} //namespace Js
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_2487_0 |
crossvul-cpp_data_bad_1387_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/fastcgi/fastcgi-server.h"
#include "hphp/runtime/server/http-server.h"
namespace HPHP {
////////////////////////////////////////////////////////////////////////////////
bool FastCGIAcceptor::canAccept(const folly::SocketAddress& /*address*/) {
// TODO: Support server IP whitelist.
auto const cons = m_server->getLibEventConnectionCount();
return (RuntimeOption::ServerConnectionLimit == 0 ||
cons < RuntimeOption::ServerConnectionLimit);
}
void FastCGIAcceptor::onNewConnection(
folly::AsyncTransportWrapper::UniquePtr sock,
const folly::SocketAddress* peerAddress,
const std::string& /*nextProtocolName*/,
SecureTransportType /*secureProtocolType*/,
const ::wangle::TransportInfo& /*tinfo*/) {
folly::SocketAddress localAddress;
try {
sock->getLocalAddress(&localAddress);
} catch (std::system_error& e) {
// If getSockName fails it's bad news; abort the connection
return;
}
// Will delete itself when it gets a closing callback
auto session = new FastCGISession(
m_server->getEventBaseManager()->getExistingEventBase(),
m_server->getDispatcher(),
std::move(sock),
localAddress,
*peerAddress
);
// NB: ~ManagedConnection will call removeConnection() before the session
// destroys itself.
Acceptor::addConnection(session);
};
void FastCGIAcceptor::onConnectionsDrained() {
m_server->onConnectionsDrained();
}
////////////////////////////////////////////////////////////////////////////////
FastCGIServer::FastCGIServer(const std::string &address,
int port,
int workers,
bool useFileSocket)
: Server(address, port),
m_worker(&m_eventBaseManager),
m_dispatcher(workers, workers,
RuntimeOption::ServerThreadDropCacheTimeoutSeconds,
RuntimeOption::ServerThreadDropStack,
this,
RuntimeOption::ServerThreadJobLIFOSwitchThreshold,
RuntimeOption::ServerThreadJobMaxQueuingMilliSeconds,
RequestPriority::k_numPriorities) {
folly::SocketAddress sock_addr;
if (useFileSocket) {
sock_addr.setFromPath(address);
} else if (address.empty()) {
sock_addr.setFromLocalPort(port);
} else {
sock_addr.setFromHostPort(address, port);
}
m_socketConfig.bindAddress = sock_addr;
m_socketConfig.acceptBacklog = RuntimeOption::ServerBacklog;
std::chrono::seconds timeout;
if (RuntimeOption::ConnectionTimeoutSeconds >= 0) {
timeout = std::chrono::seconds(RuntimeOption::ConnectionTimeoutSeconds);
} else {
// default to 2 minutes
timeout = std::chrono::seconds(120);
}
m_socketConfig.connectionIdleTimeout = timeout;
}
void FastCGIServer::start() {
// It's not safe to call this function more than once
m_socket.reset(new folly::AsyncServerSocket(m_worker.getEventBase()));
try {
m_socket->bind(m_socketConfig.bindAddress);
} catch (const std::system_error& ex) {
Logger::Error(std::string(ex.what()));
if (m_socketConfig.bindAddress.getFamily() == AF_UNIX) {
throw FailedToListenException(m_socketConfig.bindAddress.getPath());
}
throw FailedToListenException(m_socketConfig.bindAddress.getAddressStr(),
m_socketConfig.bindAddress.getPort());
}
if (m_socketConfig.bindAddress.getFamily() == AF_UNIX) {
auto path = m_socketConfig.bindAddress.getPath();
chmod(path.c_str(), 0760);
}
m_acceptor.reset(new FastCGIAcceptor(m_socketConfig, this));
m_acceptor->init(m_socket.get(), m_worker.getEventBase());
m_worker.getEventBase()->runInEventBaseThread([&] {
if (!m_socket) {
// Someone called stop before we got here. With the exception of a
// second call to start being made this should be safe as any place
// we mutate m_socket is done within the event base.
return;
}
m_socket->listen(m_socketConfig.acceptBacklog);
m_socket->startAccepting();
});
setStatus(RunStatus::RUNNING);
folly::AsyncTimeout::attachEventBase(m_worker.getEventBase());
m_worker.start();
m_dispatcher.start();
}
void FastCGIServer::waitForEnd() {
// When m_worker stops the server has stopped accepting new requests, there
// may be pedning vm jobs. wait() is always safe to call regardless of thread
m_worker.wait();
}
void FastCGIServer::stop() {
if (getStatus() != RunStatus::RUNNING) return; // nothing to do
setStatus(RunStatus::STOPPING);
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DRAIN_READS);
m_worker.getEventBase()->runInEventBaseThread([&] {
// Shutdown the server socket. Unfortunately, we will drop all unaccepted
// connections; there is no way to do a partial shutdown of a server socket
m_socket->stopAccepting();
if (RuntimeOption::ServerGracefulShutdownWait > 0) {
// Gracefully drain any incomplete requests. We cannot go offline until
// they are finished as we own their dispatcher and event base.
if (m_acceptor) {
m_acceptor->drainAllConnections();
}
std::chrono::seconds s(RuntimeOption::ServerGracefulShutdownWait);
std::chrono::milliseconds m(s);
scheduleTimeout(m);
} else {
// Drop all connections. We cannot shutdown until they stop because we
// own their dispatcher and event base.
if (m_acceptor) {
m_acceptor->forceStop();
}
terminateServer();
}
});
}
void FastCGIServer::onConnectionsDrained() {
// NOTE: called from FastCGIAcceptor::onConnectionsDrained()
cancelTimeout();
terminateServer();
}
void FastCGIServer::timeoutExpired() noexcept {
// Acceptor failed to drain connections on time; drop them so that we can
// shutdown.
if (m_acceptor) {
m_acceptor->forceStop();
}
terminateServer();
}
void FastCGIServer::terminateServer() {
if (getStatus() != RunStatus::STOPPING) {
setStatus(RunStatus::STOPPING);
}
// Wait for the server socket thread to stop running
m_worker.stopWhenIdle();
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DRAIN_DISPATCHER);
// Wait for VMs to shutdown
m_dispatcher.stop();
setStatus(RunStatus::STOPPED);
HttpServer::MarkShutdownStat(ShutdownEvent::SHUTDOWN_DONE);
// Notify HttpServer that we've shutdown
for (auto listener: m_listeners) {
listener->serverStopped(this);
}
}
////////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1387_0 |
crossvul-cpp_data_bad_1512_0 | // rw.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "rw.h"
#include "nbtheory.h"
#include "asn.h"
#ifndef CRYPTOPP_IMPORTS
NAMESPACE_BEGIN(CryptoPP)
void RWFunction::BERDecode(BufferedTransformation &bt)
{
BERSequenceDecoder seq(bt);
m_n.BERDecode(seq);
seq.MessageEnd();
}
void RWFunction::DEREncode(BufferedTransformation &bt) const
{
DERSequenceEncoder seq(bt);
m_n.DEREncode(seq);
seq.MessageEnd();
}
Integer RWFunction::ApplyFunction(const Integer &in) const
{
DoQuickSanityCheck();
Integer out = in.Squared()%m_n;
const word r = 12;
// this code was written to handle both r = 6 and r = 12,
// but now only r = 12 is used in P1363
const word r2 = r/2;
const word r3a = (16 + 5 - r) % 16; // n%16 could be 5 or 13
const word r3b = (16 + 13 - r) % 16;
const word r4 = (8 + 5 - r/2) % 8; // n%8 == 5
switch (out % 16)
{
case r:
break;
case r2:
case r2+8:
out <<= 1;
break;
case r3a:
case r3b:
out.Negate();
out += m_n;
break;
case r4:
case r4+8:
out.Negate();
out += m_n;
out <<= 1;
break;
default:
out = Integer::Zero();
}
return out;
}
bool RWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
bool pass = true;
pass = pass && m_n > Integer::One() && m_n%8 == 5;
return pass;
}
bool RWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
return GetValueHelper(this, name, valueType, pValue).Assignable()
CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
;
}
void RWFunction::AssignFrom(const NameValuePairs &source)
{
AssignFromHelper(this, source)
CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
;
}
// *****************************************************************************
// private key operations:
// generate a random private key
void InvertibleRWFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
{
int modulusSize = 2048;
alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize);
if (modulusSize < 16)
throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small");
AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize);
m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8)));
m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8)));
m_n = m_p * m_q;
m_u = m_q.InverseMod(m_p);
}
void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
{
BERSequenceDecoder seq(bt);
m_n.BERDecode(seq);
m_p.BERDecode(seq);
m_q.BERDecode(seq);
m_u.BERDecode(seq);
seq.MessageEnd();
}
void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
{
DERSequenceEncoder seq(bt);
m_n.DEREncode(seq);
m_p.DEREncode(seq);
m_q.DEREncode(seq);
m_u.DEREncode(seq);
seq.MessageEnd();
}
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
{
DoQuickSanityCheck();
ModularArithmetic modn(m_n);
Integer r, rInv;
do { // do this in a loop for people using small numbers for testing
r.Randomize(rng, Integer::One(), m_n - Integer::One());
rInv = modn.MultiplicativeInverse(r);
} while (rInv.IsZero());
Integer re = modn.Square(r);
re = modn.Multiply(re, x); // blind
Integer cp=re%m_p, cq=re%m_q;
if (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)
{
cp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;
cq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;
}
#pragma omp parallel
#pragma omp sections
{
#pragma omp section
cp = ModularSquareRoot(cp, m_p);
#pragma omp section
cq = ModularSquareRoot(cq, m_q);
}
Integer y = CRT(cq, m_q, cp, m_p, m_u);
y = modn.Multiply(y, rInv); // unblind
y = STDMIN(y, m_n-y);
if (ApplyFunction(y) != x) // check
throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");
return y;
}
bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
bool pass = RWFunction::Validate(rng, level);
pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
pass = pass && m_u.IsPositive() && m_u < m_p;
if (level >= 1)
{
pass = pass && m_p * m_q == m_n;
pass = pass && m_u * m_q % m_p == 1;
}
if (level >= 2)
pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
return pass;
}
bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
;
}
void InvertibleRWFunction::AssignFrom(const NameValuePairs &source)
{
AssignFromHelper<RWFunction>(this, source)
CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
;
}
NAMESPACE_END
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1512_0 |
crossvul-cpp_data_bad_5212_1 | /* linenoise.c -- guerrilla line editing library against the idea that a
*
* Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* line editing lib needs to be 20,000 lines of C code.
*
* You can find the latest source code at:
*
* http://github.com/antirez/linenoise
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* References:
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
*
* Todo list:
* - Switch to gets() if $TERM is something we can't support.
* - Filter bogus Ctrl+<char> combinations.
* - Win32 support
*
* Bloat:
* - Completion?
* - History search like Ctrl+r in readline?
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* CHA (Cursor Horizontal Absolute)
* Sequence: ESC [ n G
* Effect: moves cursor to column n (1 based)
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (Cursor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward of n chars
*
* The following are used to clear the screen: ESC [ H ESC [ 2 J
* This is actually composed of two sequences:
*
* cursorhome
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED2 (Clear entire screen)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
*/
#ifdef _WIN32
#include <conio.h>
#include <io.h>
#include <windows.h>
#define strcasecmp _stricmp
#define strdup _strdup
#define isatty _isatty
#define write _write
#define STDIN_FILENO 0
#else /* _WIN32 */
#include <cctype>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <wctype.h>
#endif /* _WIN32 */
#include "linenoise.h"
#include "linenoise_utf8.h"
#include "mk_wcwidth.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::unique_ptr;
using linenoise_utf8::UChar8;
using linenoise_utf8::UChar32;
using linenoise_utf8::copyString8to32;
using linenoise_utf8::copyString32;
using linenoise_utf8::copyString32to8;
using linenoise_utf8::strlen32;
using linenoise_utf8::strncmp32;
using linenoise_utf8::write32;
using linenoise_utf8::Utf8String;
using linenoise_utf8::Utf32String;
struct linenoiseCompletions {
vector<Utf32String> completionStrings;
};
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE 4096
// make control-characters more readable
#define ctrlChar(upperCaseASCII) (upperCaseASCII - 0x40)
/**
* Recompute widths of all characters in a UChar32 buffer
* @param text input buffer of Unicode characters
* @param widths output buffer of character widths
* @param charCount number of characters in buffer
*/
static void recomputeCharacterWidths(const UChar32* text, char* widths, int charCount) {
for (int i = 0; i < charCount; ++i) {
widths[i] = mk_wcwidth(text[i]);
}
}
/**
* Calculate a new screen position given a starting position, screen width and character count
* @param x initial x position (zero-based)
* @param y initial y position (zero-based)
* @param screenColumns screen column count
* @param charCount character positions to advance
* @param xOut returned x position (zero-based)
* @param yOut returned y position (zero-based)
*/
static void calculateScreenPosition(
int x, int y, int screenColumns, int charCount, int& xOut, int& yOut) {
xOut = x;
yOut = y;
int charsRemaining = charCount;
while (charsRemaining > 0) {
int charsThisRow =
(x + charsRemaining < screenColumns) ? charsRemaining : screenColumns - x;
xOut = x + charsThisRow;
yOut = y;
charsRemaining -= charsThisRow;
x = 0;
++y;
}
if (xOut == screenColumns) { // we have to special-case line wrap
xOut = 0;
++yOut;
}
}
/**
* Calculate a column width using mk_wcswidth()
* @param buf32 text to calculate
* @param len length of text to calculate
*/
static int calculateColumnPosition(UChar32* buf32, int len) {
int width = mk_wcswidth(reinterpret_cast<const int*>(buf32), len);
if (width == -1)
return len;
else
return width;
}
static bool isControlChar(UChar32 testChar) {
return (testChar < ' ') || // C0 controls
(testChar >= 0x7F && testChar <= 0x9F); // DEL and C1 controls
}
struct PromptBase { // a convenience struct for grouping prompt info
Utf32String promptText; // our copy of the prompt text, edited
char* promptCharWidths; // character widths from mk_wcwidth()
int promptChars; // chars in promptText
int promptExtraLines; // extra lines (beyond 1) occupied by prompt
int promptIndentation; // column offset to end of prompt
int promptLastLinePosition; // index into promptText where last line begins
int promptPreviousInputLen; // promptChars of previous input line, for clearing
int promptCursorRowOffset; // where the cursor is relative to the start of the prompt
int promptScreenColumns; // width of screen in columns
int promptPreviousLen; // help erasing
int promptErrorCode; // error code (invalid UTF-8) or zero
PromptBase() : promptPreviousInputLen(0) {}
};
struct PromptInfo : public PromptBase {
PromptInfo(const UChar8* textPtr, int columns) {
promptExtraLines = 0;
promptLastLinePosition = 0;
promptPreviousLen = 0;
promptScreenColumns = columns;
Utf32String tempUnicode(textPtr);
// strip control characters from the prompt -- we do allow newline
UChar32* pIn = tempUnicode.get();
UChar32* pOut = pIn;
while (*pIn) {
UChar32 c = *pIn;
if ('\n' == c || !isControlChar(c)) {
*pOut = c;
++pOut;
}
++pIn;
}
*pOut = 0;
promptChars = pOut - tempUnicode.get();
promptText = tempUnicode;
int x = 0;
for (int i = 0; i < promptChars; ++i) {
UChar32 c = promptText[i];
if ('\n' == c) {
x = 0;
++promptExtraLines;
promptLastLinePosition = i + 1;
} else {
++x;
if (x >= promptScreenColumns) {
x = 0;
++promptExtraLines;
promptLastLinePosition = i + 1;
}
}
}
promptIndentation = promptChars - promptLastLinePosition;
promptCursorRowOffset = promptExtraLines;
}
};
// Used with DynamicPrompt (history search)
//
static const Utf32String forwardSearchBasePrompt(reinterpret_cast<const UChar8*>("(i-search)`"));
static const Utf32String reverseSearchBasePrompt(
reinterpret_cast<const UChar8*>("(reverse-i-search)`"));
static const Utf32String endSearchBasePrompt(reinterpret_cast<const UChar8*>("': "));
static Utf32String previousSearchText; // remembered across invocations of linenoise()
// changing prompt for "(reverse-i-search)`text':" etc.
//
struct DynamicPrompt : public PromptBase {
Utf32String searchText; // text we are searching for
char* searchCharWidths; // character widths from mk_wcwidth()
int searchTextLen; // chars in searchText
int direction; // current search direction, 1=forward, -1=reverse
DynamicPrompt(PromptBase& pi, int initialDirection)
: searchTextLen(0), direction(initialDirection) {
promptScreenColumns = pi.promptScreenColumns;
promptCursorRowOffset = 0;
Utf32String emptyString(1);
searchText = emptyString;
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars = promptStartLength + endSearchBasePrompt.length();
promptLastLinePosition =
promptChars; // TODO fix this, we are asssuming that the history prompt won't wrap (!)
promptPreviousLen = promptChars;
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(), sizeof(UChar32) * promptStartLength);
memcpy(&tempUnicode[promptStartLength],
endSearchBasePrompt.get(),
sizeof(UChar32) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
calculateScreenPosition(
0, 0, pi.promptScreenColumns, promptChars, promptIndentation, promptExtraLines);
}
void updateSearchPrompt(void) {
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars = promptStartLength + searchTextLen + endSearchBasePrompt.length();
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(), sizeof(UChar32) * promptStartLength);
memcpy(&tempUnicode[promptStartLength], searchText.get(), sizeof(UChar32) * searchTextLen);
size_t endIndex = promptStartLength + searchTextLen;
memcpy(&tempUnicode[endIndex],
endSearchBasePrompt.get(),
sizeof(UChar32) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
}
void updateSearchText(const UChar32* textPtr) {
Utf32String tempUnicode(textPtr);
searchTextLen = tempUnicode.chars();
searchText = tempUnicode;
updateSearchPrompt();
}
};
class KillRing {
static const int capacity = 10;
int size;
int index;
char indexToSlot[10];
vector<Utf32String> theRing;
public:
enum action { actionOther, actionKill, actionYank };
action lastAction;
size_t lastYankSize;
KillRing() : size(0), index(0), lastAction(actionOther) {
theRing.reserve(capacity);
}
void kill(const UChar32* text, int textLen, bool forward) {
if (textLen == 0) {
return;
}
Utf32String killedText(text, textLen);
if (lastAction == actionKill && size > 0) {
int slot = indexToSlot[0];
int currentLen = theRing[slot].length();
int resultLen = currentLen + textLen;
Utf32String temp(resultLen + 1);
if (forward) {
memcpy(temp.get(), theRing[slot].get(), currentLen * sizeof(UChar32));
memcpy(&temp[currentLen], killedText.get(), textLen * sizeof(UChar32));
} else {
memcpy(temp.get(), killedText.get(), textLen * sizeof(UChar32));
memcpy(&temp[textLen], theRing[slot].get(), currentLen * sizeof(UChar32));
}
temp[resultLen] = 0;
temp.initFromBuffer();
theRing[slot] = temp;
} else {
if (size < capacity) {
if (size > 0) {
memmove(&indexToSlot[1], &indexToSlot[0], size);
}
indexToSlot[0] = size;
size++;
theRing.push_back(killedText);
} else {
int slot = indexToSlot[capacity - 1];
theRing[slot] = killedText;
memmove(&indexToSlot[1], &indexToSlot[0], capacity - 1);
indexToSlot[0] = slot;
}
index = 0;
}
}
Utf32String* yank() {
return (size > 0) ? &theRing[indexToSlot[index]] : 0;
}
Utf32String* yankPop() {
if (size == 0) {
return 0;
}
++index;
if (index == size) {
index = 0;
}
return &theRing[indexToSlot[index]];
}
};
class InputBuffer {
UChar32* buf32; // input buffer
char* charWidths; // character widths from mk_wcwidth()
int buflen; // buffer size in characters
int len; // length of text in input buffer
int pos; // character position in buffer ( 0 <= pos <= len )
void clearScreen(PromptBase& pi);
int incrementalHistorySearch(PromptBase& pi, int startChar);
int completeLine(PromptBase& pi);
void refreshLine(PromptBase& pi);
public:
InputBuffer(UChar32* buffer, char* widthArray, int bufferLen)
: buf32(buffer), charWidths(widthArray), buflen(bufferLen - 1), len(0), pos(0) {
buf32[0] = 0;
}
void preloadBuffer(const UChar8* preloadText) {
size_t ucharCount;
int errorCode;
copyString8to32(buf32, preloadText, buflen + 1, ucharCount, errorCode);
recomputeCharacterWidths(buf32, charWidths, ucharCount);
len = ucharCount;
pos = ucharCount;
}
int getInputLine(PromptBase& pi);
int length(void) const {
return len;
}
};
// Special codes for keyboard input:
//
// Between Windows and the various Linux "terminal" programs, there is some
// pretty diverse behavior in the "scan codes" and escape sequences we are
// presented with. So ... we'll translate them all into our own pidgin
// pseudocode, trying to stay out of the way of UTF-8 and international
// characters. Here's the general plan.
//
// "User input keystrokes" (key chords, whatever) will be encoded as a single value.
// The low 21 bits are reserved for Unicode characters. Popular function-type keys
// get their own codes in the range 0x10200000 to (if needed) 0x1FE00000, currently
// just arrow keys, Home, End and Delete. Keypresses with Ctrl get ORed with
// 0x20000000, with Alt get ORed with 0x40000000. So, Ctrl+Alt+Home is encoded
// as 0x20000000 + 0x40000000 + 0x10A00000 == 0x70A00000. To keep things complicated,
// the Alt key is equivalent to prefixing the keystroke with ESC, so ESC followed by
// D is treated the same as Alt + D ... we'll just use Emacs terminology and call
// this "Meta". So, we will encode both ESC followed by D and Alt held down while D
// is pressed the same, as Meta-D, encoded as 0x40000064.
//
// Here are the definitions of our component constants:
//
// Maximum unsigned 32-bit value = 0xFFFFFFFF; // For reference, max 32-bit value
// Highest allocated Unicode char = 0x001FFFFF; // For reference, max Unicode value
static const int META = 0x40000000; // Meta key combination
static const int CTRL = 0x20000000; // Ctrl key combination
static const int SPECIAL_KEY = 0x10000000; // Common bit for all special keys
static const int UP_ARROW_KEY = 0x10200000; // Special keys
static const int DOWN_ARROW_KEY = 0x10400000;
static const int RIGHT_ARROW_KEY = 0x10600000;
static const int LEFT_ARROW_KEY = 0x10800000;
static const int HOME_KEY = 0x10A00000;
static const int END_KEY = 0x10C00000;
static const int DELETE_KEY = 0x10E00000;
static const int PAGE_UP_KEY = 0x11000000;
static const int PAGE_DOWN_KEY = 0x11200000;
static const char* unsupported_term[] = {"dumb", "cons25", "emacs", NULL};
static linenoiseCompletionCallback* completionCallback = NULL;
#ifdef _WIN32
static HANDLE console_in, console_out;
static DWORD oldMode;
static WORD oldDisplayAttribute;
#else
static struct termios orig_termios; /* in order to restore at exit */
#endif
static KillRing killRing;
static int rawmode = 0; /* for atexit() function to check if restore is needed*/
static int atexit_registered = 0; /* register atexit just 1 time */
static int historyMaxLen = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int historyLen = 0;
static int historyIndex = 0;
static UChar8** history = NULL;
// used to emulate Windows command prompt on down-arrow after a recall
// we use -2 as our "not set" value because we add 1 to the previous index on down-arrow,
// and zero is a valid index (so -1 is a valid "previous index")
static int historyPreviousIndex = -2;
static bool historyRecallMostRecent = false;
static void linenoiseAtExit(void);
static bool isUnsupportedTerm(void) {
char* term = getenv("TERM");
if (term == NULL)
return false;
for (int j = 0; unsupported_term[j]; ++j)
if (!strcasecmp(term, unsupported_term[j])) {
return true;
}
return false;
}
static void beep() {
fprintf(stderr, "\x7"); // ctrl-G == bell/beep
fflush(stderr);
}
void linenoiseHistoryFree(void) {
if (history) {
for (int j = 0; j < historyLen; ++j)
free(history[j]);
historyLen = 0;
free(history);
history = 0;
}
}
static int enableRawMode(void) {
#ifdef _WIN32
if (!console_in) {
console_in = GetStdHandle(STD_INPUT_HANDLE);
console_out = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(console_in, &oldMode);
SetConsoleMode(console_in,
oldMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT));
}
return 0;
#else
struct termios raw;
if (!isatty(0))
goto fatal;
if (!atexit_registered) {
atexit(linenoiseAtExit);
atexit_registered = 1;
}
if (tcgetattr(0, &orig_termios) == -1)
goto fatal;
raw = orig_termios; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
// this is wrong, we don't want raw output, it turns newlines into straight linefeeds
// raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - echoing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
if (tcsetattr(0, TCSADRAIN, &raw) < 0)
goto fatal;
rawmode = 1;
return 0;
fatal:
errno = ENOTTY;
return -1;
#endif
}
static void disableRawMode(void) {
#ifdef _WIN32
SetConsoleMode(console_in, oldMode);
console_in = 0;
console_out = 0;
#else
if (rawmode && tcsetattr(0, TCSADRAIN, &orig_termios) != -1)
rawmode = 0;
#endif
}
// At exit we'll try to fix the terminal to the initial conditions
static void linenoiseAtExit(void) {
disableRawMode();
}
static int getScreenColumns(void) {
int cols;
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &inf);
cols = inf.dwSize.X;
#else
struct winsize ws;
cols = (ioctl(1, TIOCGWINSZ, &ws) == -1) ? 80 : ws.ws_col;
#endif
// cols is 0 in certain circumstances like inside debugger, which creates further issues
return (cols > 0) ? cols : 80;
}
static int getScreenRows(void) {
int rows;
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &inf);
rows = 1 + inf.srWindow.Bottom - inf.srWindow.Top;
#else
struct winsize ws;
rows = (ioctl(1, TIOCGWINSZ, &ws) == -1) ? 24 : ws.ws_row;
#endif
return (rows > 0) ? rows : 24;
}
static void setDisplayAttribute(bool enhancedDisplay) {
#ifdef _WIN32
if (enhancedDisplay) {
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
oldDisplayAttribute = inf.wAttributes;
BYTE oldLowByte = oldDisplayAttribute & 0xFF;
BYTE newLowByte;
switch (oldLowByte) {
case 0x07:
// newLowByte = FOREGROUND_BLUE | FOREGROUND_INTENSITY; // too dim
// newLowByte = FOREGROUND_BLUE; // even dimmer
newLowByte =
FOREGROUND_BLUE | FOREGROUND_GREEN; // most similar to xterm appearance
break;
case 0x70:
newLowByte = BACKGROUND_BLUE | BACKGROUND_INTENSITY;
break;
default:
newLowByte = oldLowByte ^ 0xFF; // default to inverse video
break;
}
inf.wAttributes = (inf.wAttributes & 0xFF00) | newLowByte;
SetConsoleTextAttribute(console_out, inf.wAttributes);
} else {
SetConsoleTextAttribute(console_out, oldDisplayAttribute);
}
#else
if (enhancedDisplay) {
if (write(1, "\x1b[1;34m", 7) == -1)
return; /* bright blue (visible with both B&W bg) */
} else {
if (write(1, "\x1b[0m", 4) == -1)
return; /* reset */
}
#endif
}
/**
* Display the dynamic incremental search prompt and the current user input line.
* @param pi PromptBase struct holding information about the prompt and our screen position
* @param buf32 input buffer to be displayed
* @param len count of characters in the buffer
* @param pos current cursor position within the buffer (0 <= pos <= len)
*/
static void dynamicRefresh(PromptBase& pi, UChar32* buf32, int len, int pos) {
// calculate the position of the end of the prompt
int xEndOfPrompt, yEndOfPrompt;
calculateScreenPosition(
0, 0, pi.promptScreenColumns, pi.promptChars, xEndOfPrompt, yEndOfPrompt);
pi.promptIndentation = xEndOfPrompt;
// calculate the position of the end of the input line
int xEndOfInput, yEndOfInput;
calculateScreenPosition(xEndOfPrompt,
yEndOfPrompt,
pi.promptScreenColumns,
calculateColumnPosition(buf32, len),
xEndOfInput,
yEndOfInput);
// calculate the desired position of the cursor
int xCursorPos, yCursorPos;
calculateScreenPosition(xEndOfPrompt,
yEndOfPrompt,
pi.promptScreenColumns,
calculateColumnPosition(buf32, pos),
xCursorPos,
yCursorPos);
#ifdef _WIN32
// position at the start of the prompt, clear to end of previous input
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = 0;
inf.dwCursorPosition.Y -= pi.promptCursorRowOffset /*- pi.promptExtraLines*/;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
DWORD count;
FillConsoleOutputCharacterA(console_out,
' ',
pi.promptPreviousLen + pi.promptPreviousInputLen,
inf.dwCursorPosition,
&count);
pi.promptPreviousLen = pi.promptIndentation;
pi.promptPreviousInputLen = len;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
// display the input line
if (write32(1, buf32, len) == -1)
return;
// position the cursor
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = xCursorPos; // 0-based on Win32
inf.dwCursorPosition.Y -= yEndOfInput - yCursorPos;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
#else // _WIN32
char seq[64];
int cursorRowMovement = pi.promptCursorRowOffset - pi.promptExtraLines;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position at the start of the prompt, clear to end of screen
snprintf(seq, sizeof seq, "\x1b[1G\x1b[J"); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
// display the input line
if (write32(1, buf32, len) == -1)
return;
// we have to generate our own newline on line wrap
if (xEndOfInput == 0 && yEndOfInput > 0)
if (write(1, "\n", 1) == -1)
return;
// position the cursor
cursorRowMovement = yEndOfInput - yCursorPos;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position the cursor within the line
snprintf(seq, sizeof seq, "\x1b[%dG", xCursorPos + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines + yCursorPos; // remember row for next pass
}
/**
* Refresh the user's input line: the prompt is already onscreen and is not redrawn here
* @param pi PromptBase struct holding information about the prompt and our screen position
*/
void InputBuffer::refreshLine(PromptBase& pi) {
// check for a matching brace/bracket/paren, remember its position if found
int highlight = -1;
if (pos < len) {
/* this scans for a brace matching buf32[pos] to highlight */
int scanDirection = 0;
if (strchr("}])", buf32[pos]))
scanDirection = -1; /* backwards */
else if (strchr("{[(", buf32[pos]))
scanDirection = 1; /* forwards */
if (scanDirection) {
int unmatched = scanDirection;
for (int i = pos + scanDirection; i >= 0 && i < len; i += scanDirection) {
/* TODO: the right thing when inside a string */
if (strchr("}])", buf32[i]))
--unmatched;
else if (strchr("{[(", buf32[i]))
++unmatched;
if (unmatched == 0) {
highlight = i;
break;
}
}
}
}
// calculate the position of the end of the input line
int xEndOfInput, yEndOfInput;
calculateScreenPosition(pi.promptIndentation,
0,
pi.promptScreenColumns,
calculateColumnPosition(buf32, len),
xEndOfInput,
yEndOfInput);
// calculate the desired position of the cursor
int xCursorPos, yCursorPos;
calculateScreenPosition(pi.promptIndentation,
0,
pi.promptScreenColumns,
calculateColumnPosition(buf32, pos),
xCursorPos,
yCursorPos);
#ifdef _WIN32
// position at the end of the prompt, clear to end of previous input
CONSOLE_SCREEN_BUFFER_INFO inf;
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = pi.promptIndentation; // 0-based on Win32
inf.dwCursorPosition.Y -= pi.promptCursorRowOffset - pi.promptExtraLines;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
DWORD count;
if (len < pi.promptPreviousInputLen)
FillConsoleOutputCharacterA(
console_out, ' ', pi.promptPreviousInputLen, inf.dwCursorPosition, &count);
pi.promptPreviousInputLen = len;
// display the input line
if (highlight == -1) {
if (write32(1, buf32, len) == -1)
return;
} else {
if (write32(1, buf32, highlight) == -1)
return;
setDisplayAttribute(true); /* bright blue (visible with both B&W bg) */
if (write32(1, &buf32[highlight], 1) == -1)
return;
setDisplayAttribute(false);
if (write32(1, buf32 + highlight + 1, len - highlight - 1) == -1)
return;
}
// position the cursor
GetConsoleScreenBufferInfo(console_out, &inf);
inf.dwCursorPosition.X = xCursorPos; // 0-based on Win32
inf.dwCursorPosition.Y -= yEndOfInput - yCursorPos;
SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
#else // _WIN32
char seq[64];
int cursorRowMovement = pi.promptCursorRowOffset - pi.promptExtraLines;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position at the end of the prompt, clear to end of screen
snprintf(seq, sizeof seq, "\x1b[%dG\x1b[J", pi.promptIndentation + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
if (highlight == -1) { // write unhighlighted text
if (write32(1, buf32, len) == -1)
return;
} else { // highlight the matching brace/bracket/parenthesis
if (write32(1, buf32, highlight) == -1)
return;
setDisplayAttribute(true);
if (write32(1, &buf32[highlight], 1) == -1)
return;
setDisplayAttribute(false);
if (write32(1, buf32 + highlight + 1, len - highlight - 1) == -1)
return;
}
// we have to generate our own newline on line wrap
if (xEndOfInput == 0 && yEndOfInput > 0)
if (write(1, "\n", 1) == -1)
return;
// position the cursor
cursorRowMovement = yEndOfInput - yCursorPos;
if (cursorRowMovement > 0) { // move the cursor up as required
snprintf(seq, sizeof seq, "\x1b[%dA", cursorRowMovement);
if (write(1, seq, strlen(seq)) == -1)
return;
}
// position the cursor within the line
snprintf(seq, sizeof seq, "\x1b[%dG", xCursorPos + 1); // 1-based on VT100
if (write(1, seq, strlen(seq)) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines + yCursorPos; // remember row for next pass
}
#ifndef _WIN32
/**
* Read a UTF-8 sequence from the non-Windows keyboard and return the Unicode (UChar32) character it
* encodes
*
* @return UChar32 Unicode character
*/
static UChar32 readUnicodeCharacter(void) {
static UChar8 utf8String[5];
static size_t utf8Count = 0;
while (true) {
UChar8 c;
if (read(0, &c, 1) <= 0)
return 0;
if (c <= 0x7F) { // short circuit ASCII
utf8Count = 0;
return c;
} else if (utf8Count < sizeof(utf8String) - 1) {
utf8String[utf8Count++] = c;
utf8String[utf8Count] = 0;
UChar32 unicodeChar[2];
size_t ucharCount;
int errorCode;
copyString8to32(unicodeChar, utf8String, 2, ucharCount, errorCode);
if (ucharCount && errorCode == 0) {
utf8Count = 0;
return unicodeChar[0];
}
} else {
utf8Count = 0; // this shouldn't happen: got four bytes but no UTF-8 character
}
}
}
namespace EscapeSequenceProcessing { // move these out of global namespace
// This chunk of code does parsing of the escape sequences sent by various Linux terminals.
//
// It handles arrow keys, Home, End and Delete keys by interpreting the sequences sent by
// gnome terminal, xterm, rxvt, konsole, aterm and yakuake including the Alt and Ctrl key
// combinations that are understood by linenoise.
//
// The parsing uses tables, a bunch of intermediate dispatch routines and a doDispatch
// loop that reads the tables and sends control to "deeper" routines to continue the
// parsing. The starting call to doDispatch( c, initialDispatch ) will eventually return
// either a character (with optional CTRL and META bits set), or -1 if parsing fails, or
// zero if an attempt to read from the keyboard fails.
//
// This is rather sloppy escape sequence processing, since we're not paying attention to what the
// actual TERM is set to and are processing all key sequences for all terminals, but it works with
// the most common keystrokes on the most common terminals. It's intricate, but the nested 'if'
// statements required to do it directly would be worse. This way has the advantage of allowing
// changes and extensions without having to touch a lot of code.
// This is a typedef for the routine called by doDispatch(). It takes the current character
// as input, does any required processing including reading more characters and calling other
// dispatch routines, then eventually returns the final (possibly extended or special) character.
//
typedef UChar32 (*CharacterDispatchRoutine)(UChar32);
// This structure is used by doDispatch() to hold a list of characters to test for and
// a list of routines to call if the character matches. The dispatch routine list is one
// longer than the character list; the final entry is used if no character matches.
//
struct CharacterDispatch {
unsigned int len; // length of the chars list
const char* chars; // chars to test
CharacterDispatchRoutine* dispatch; // array of routines to call
};
// This dispatch routine is given a dispatch table and then farms work out to routines
// listed in the table based on the character it is called with. The dispatch routines can
// read more input characters to decide what should eventually be returned. Eventually,
// a called routine returns either a character or -1 to indicate parsing failure.
//
static UChar32 doDispatch(UChar32 c, CharacterDispatch& dispatchTable) {
for (unsigned int i = 0; i < dispatchTable.len; ++i) {
if (static_cast<unsigned char>(dispatchTable.chars[i]) == c) {
return dispatchTable.dispatch[i](c);
}
}
return dispatchTable.dispatch[dispatchTable.len](c);
}
static UChar32 thisKeyMetaCtrl = 0; // holds pre-set Meta and/or Ctrl modifiers
// Final dispatch routines -- return something
//
static UChar32 normalKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | c;
}
static UChar32 upArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | UP_ARROW_KEY;
}
static UChar32 downArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | DOWN_ARROW_KEY;
}
static UChar32 rightArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | RIGHT_ARROW_KEY;
}
static UChar32 leftArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | LEFT_ARROW_KEY;
}
static UChar32 homeKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | HOME_KEY;
}
static UChar32 endKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | END_KEY;
}
static UChar32 pageUpKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | PAGE_UP_KEY;
}
static UChar32 pageDownKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | PAGE_DOWN_KEY;
}
static UChar32 deleteCharRoutine(UChar32 c) {
return thisKeyMetaCtrl | ctrlChar('H');
} // key labeled Backspace
static UChar32 deleteKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | DELETE_KEY;
} // key labeled Delete
static UChar32 ctrlUpArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | UP_ARROW_KEY;
}
static UChar32 ctrlDownArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | DOWN_ARROW_KEY;
}
static UChar32 ctrlRightArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | RIGHT_ARROW_KEY;
}
static UChar32 ctrlLeftArrowKeyRoutine(UChar32 c) {
return thisKeyMetaCtrl | CTRL | LEFT_ARROW_KEY;
}
static UChar32 escFailureRoutine(UChar32 c) {
beep();
return -1;
}
// Handle ESC [ 1 ; 3 (or 5) <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket1Semicolon3or5Routines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket1Semicolon3or5Dispatch = {
4, "ABCD", escLeftBracket1Semicolon3or5Routines};
// Handle ESC [ 1 ; <more stuff> escape sequences
//
static UChar32 escLeftBracket1Semicolon3Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
thisKeyMetaCtrl |= META;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static UChar32 escLeftBracket1Semicolon5Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
thisKeyMetaCtrl |= CTRL;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static CharacterDispatchRoutine escLeftBracket1SemicolonRoutines[] = {
escLeftBracket1Semicolon3Routine, escLeftBracket1Semicolon5Routine, escFailureRoutine};
static CharacterDispatch escLeftBracket1SemicolonDispatch = {
2, "35", escLeftBracket1SemicolonRoutines};
// Handle ESC [ 1 <more stuff> escape sequences
//
static UChar32 escLeftBracket1SemicolonRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket1SemicolonDispatch);
}
static CharacterDispatchRoutine escLeftBracket1Routines[] = {
homeKeyRoutine, escLeftBracket1SemicolonRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Dispatch = {2, "~;", escLeftBracket1Routines};
// Handle ESC [ 3 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket3Routines[] = {deleteKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket3Dispatch = {1, "~", escLeftBracket3Routines};
// Handle ESC [ 4 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket4Routines[] = {endKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket4Dispatch = {1, "~", escLeftBracket4Routines};
// Handle ESC [ 5 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket5Routines[] = {pageUpKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket5Dispatch = {1, "~", escLeftBracket5Routines};
// Handle ESC [ 6 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket6Routines[] = {pageDownKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket6Dispatch = {1, "~", escLeftBracket6Routines};
// Handle ESC [ 7 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket7Routines[] = {homeKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket7Dispatch = {1, "~", escLeftBracket7Routines};
// Handle ESC [ 8 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket8Routines[] = {endKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket8Dispatch = {1, "~", escLeftBracket8Routines};
// Handle ESC [ <digit> escape sequences
//
static UChar32 escLeftBracket0Routine(UChar32 c) {
return escFailureRoutine(c);
}
static UChar32 escLeftBracket1Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket1Dispatch);
}
static UChar32 escLeftBracket2Routine(UChar32 c) {
return escFailureRoutine(c); // Insert key, unused
}
static UChar32 escLeftBracket3Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket3Dispatch);
}
static UChar32 escLeftBracket4Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket4Dispatch);
}
static UChar32 escLeftBracket5Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket5Dispatch);
}
static UChar32 escLeftBracket6Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket6Dispatch);
}
static UChar32 escLeftBracket7Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket7Dispatch);
}
static UChar32 escLeftBracket8Routine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracket8Dispatch);
}
static UChar32 escLeftBracket9Routine(UChar32 c) {
return escFailureRoutine(c);
}
// Handle ESC [ <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracketRoutines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
homeKeyRoutine,
endKeyRoutine,
escLeftBracket0Routine,
escLeftBracket1Routine,
escLeftBracket2Routine,
escLeftBracket3Routine,
escLeftBracket4Routine,
escLeftBracket5Routine,
escLeftBracket6Routine,
escLeftBracket7Routine,
escLeftBracket8Routine,
escLeftBracket9Routine,
escFailureRoutine};
static CharacterDispatch escLeftBracketDispatch = {16, "ABCDHF0123456789", escLeftBracketRoutines};
// Handle ESC O <char> escape sequences
//
static CharacterDispatchRoutine escORoutines[] = {upArrowKeyRoutine,
downArrowKeyRoutine,
rightArrowKeyRoutine,
leftArrowKeyRoutine,
homeKeyRoutine,
endKeyRoutine,
ctrlUpArrowKeyRoutine,
ctrlDownArrowKeyRoutine,
ctrlRightArrowKeyRoutine,
ctrlLeftArrowKeyRoutine,
escFailureRoutine};
static CharacterDispatch escODispatch = {10, "ABCDHFabcd", escORoutines};
// Initial ESC dispatch -- could be a Meta prefix or the start of an escape sequence
//
static UChar32 escLeftBracketRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escLeftBracketDispatch);
}
static UChar32 escORoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escODispatch);
}
static UChar32 setMetaRoutine(UChar32 c); // need forward reference
static CharacterDispatchRoutine escRoutines[] = {
escLeftBracketRoutine, escORoutine, setMetaRoutine};
static CharacterDispatch escDispatch = {2, "[O", escRoutines};
// Initial dispatch -- we are not in the middle of anything yet
//
static UChar32 escRoutine(UChar32 c) {
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escDispatch);
}
static CharacterDispatchRoutine initialRoutines[] = {
escRoutine, deleteCharRoutine, normalKeyRoutine};
static CharacterDispatch initialDispatch = {2, "\x1B\x7F", initialRoutines};
// Special handling for the ESC key because it does double duty
//
static UChar32 setMetaRoutine(UChar32 c) {
thisKeyMetaCtrl = META;
if (c == 0x1B) { // another ESC, stay in ESC processing mode
c = readUnicodeCharacter();
if (c == 0)
return 0;
return doDispatch(c, escDispatch);
}
return doDispatch(c, initialDispatch);
}
} // namespace EscapeSequenceProcessing // move these out of global namespace
#endif // #ifndef _WIN32
// linenoiseReadChar -- read a keystroke or keychord from the keyboard, and translate it
// into an encoded "keystroke". When convenient, extended keys are translated into their
// simpler Emacs keystrokes, so an unmodified "left arrow" becomes Ctrl-B.
//
// A return value of zero means "no input available", and a return value of -1 means "invalid key".
//
static UChar32 linenoiseReadChar(void) {
#ifdef _WIN32
INPUT_RECORD rec;
DWORD count;
int modifierKeys = 0;
bool escSeen = false;
while (true) {
ReadConsoleInputW(console_in, &rec, 1, &count);
#if 0 // helper for debugging keystrokes, display info in the debug "Output" window in the debugger
{
if ( rec.EventType == KEY_EVENT ) {
//if ( rec.Event.KeyEvent.uChar.UnicodeChar ) {
char buf[1024];
sprintf(
buf,
"Unicode character 0x%04X, repeat count %d, virtual keycode 0x%04X, "
"virtual scancode 0x%04X, key %s%s%s%s%s\n",
rec.Event.KeyEvent.uChar.UnicodeChar,
rec.Event.KeyEvent.wRepeatCount,
rec.Event.KeyEvent.wVirtualKeyCode,
rec.Event.KeyEvent.wVirtualScanCode,
rec.Event.KeyEvent.bKeyDown ? "down" : "up",
(rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) ?
" L-Ctrl" : "",
(rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED) ?
" R-Ctrl" : "",
(rec.Event.KeyEvent.dwControlKeyState & LEFT_ALT_PRESSED) ?
" L-Alt" : "",
(rec.Event.KeyEvent.dwControlKeyState & RIGHT_ALT_PRESSED) ?
" R-Alt" : ""
);
OutputDebugStringA( buf );
//}
}
}
#endif
if (rec.EventType != KEY_EVENT) {
continue;
}
// Windows provides for entry of characters that are not on your keyboard by sending the
// Unicode characters as a "key up" with virtual keycode 0x12 (VK_MENU == Alt key) ...
// accept these characters, otherwise only process characters on "key down"
if (!rec.Event.KeyEvent.bKeyDown && rec.Event.KeyEvent.wVirtualKeyCode != VK_MENU) {
continue;
}
modifierKeys = 0;
// AltGr is encoded as ( LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED ), so don't treat this
// combination as either CTRL or META we just turn off those two bits, so it is still
// possible to combine CTRL and/or META with an AltGr key by using right-Ctrl and/or
// left-Alt
if ((rec.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED)) ==
(LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED)) {
rec.Event.KeyEvent.dwControlKeyState &= ~(LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED);
}
if (rec.Event.KeyEvent.dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) {
modifierKeys |= CTRL;
}
if (rec.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) {
modifierKeys |= META;
}
if (escSeen) {
modifierKeys |= META;
}
if (rec.Event.KeyEvent.uChar.UnicodeChar == 0) {
switch (rec.Event.KeyEvent.wVirtualKeyCode) {
case VK_LEFT:
return modifierKeys | LEFT_ARROW_KEY;
case VK_RIGHT:
return modifierKeys | RIGHT_ARROW_KEY;
case VK_UP:
return modifierKeys | UP_ARROW_KEY;
case VK_DOWN:
return modifierKeys | DOWN_ARROW_KEY;
case VK_DELETE:
return modifierKeys | DELETE_KEY;
case VK_HOME:
return modifierKeys | HOME_KEY;
case VK_END:
return modifierKeys | END_KEY;
case VK_PRIOR:
return modifierKeys | PAGE_UP_KEY;
case VK_NEXT:
return modifierKeys | PAGE_DOWN_KEY;
default:
continue; // in raw mode, ReadConsoleInput shows shift, ctrl ...
} // ... ignore them
} else if (rec.Event.KeyEvent.uChar.UnicodeChar ==
ctrlChar('[')) { // ESC, set flag for later
escSeen = true;
continue;
} else {
// we got a real character, return it
return modifierKeys | rec.Event.KeyEvent.uChar.UnicodeChar;
}
}
#else
UChar32 c;
c = readUnicodeCharacter();
if (c == 0)
return 0;
// If _DEBUG_LINUX_KEYBOARD is set, then ctrl-^ puts us into a keyboard debugging mode
// where we print out decimal and decoded values for whatever the "terminal" program
// gives us on different keystrokes. Hit ctrl-C to exit this mode.
//
#define _DEBUG_LINUX_KEYBOARD
#if defined(_DEBUG_LINUX_KEYBOARD)
if (c == ctrlChar('^')) { // ctrl-^, special debug mode, prints all keys hit, ctrl-C to get out
printf("\nEntering keyboard debugging mode (on ctrl-^), press ctrl-C to exit this mode\n");
while (true) {
unsigned char keys[10];
int ret = read(0, keys, 10);
if (ret <= 0) {
printf("\nret: %d\n", ret);
}
for (int i = 0; i < ret; ++i) {
UChar32 key = static_cast<UChar32>(keys[i]);
char* friendlyTextPtr;
char friendlyTextBuf[10];
const char* prefixText = (key < 0x80) ? "" : "0x80+";
UChar32 keyCopy = (key < 0x80) ? key : key - 0x80;
if (keyCopy >= '!' && keyCopy <= '~') { // printable
friendlyTextBuf[0] = '\'';
friendlyTextBuf[1] = keyCopy;
friendlyTextBuf[2] = '\'';
friendlyTextBuf[3] = 0;
friendlyTextPtr = friendlyTextBuf;
} else if (keyCopy == ' ') {
friendlyTextPtr = const_cast<char*>("space");
} else if (keyCopy == 27) {
friendlyTextPtr = const_cast<char*>("ESC");
} else if (keyCopy == 0) {
friendlyTextPtr = const_cast<char*>("NUL");
} else if (keyCopy == 127) {
friendlyTextPtr = const_cast<char*>("DEL");
} else {
friendlyTextBuf[0] = '^';
friendlyTextBuf[1] = keyCopy + 0x40;
friendlyTextBuf[2] = 0;
friendlyTextPtr = friendlyTextBuf;
}
printf("%d x%02X (%s%s) ", key, key, prefixText, friendlyTextPtr);
}
printf("\x1b[1G\n"); // go to first column of new line
// drop out of this loop on ctrl-C
if (keys[0] == ctrlChar('C')) {
printf("Leaving keyboard debugging mode (on ctrl-C)\n");
fflush(stdout);
return -2;
}
}
}
#endif // _DEBUG_LINUX_KEYBOARD
EscapeSequenceProcessing::thisKeyMetaCtrl = 0; // no modifiers yet at initialDispatch
return EscapeSequenceProcessing::doDispatch(c, EscapeSequenceProcessing::initialDispatch);
#endif // #_WIN32
}
/**
* Free memory used in a recent command completion session
*
* @param lc pointer to a linenoiseCompletions struct
*/
static void freeCompletions(linenoiseCompletions* lc) {
lc->completionStrings.clear();
}
/**
* convert {CTRL + 'A'}, {CTRL + 'a'} and {CTRL + ctrlChar( 'A' )} into ctrlChar( 'A' )
* leave META alone
*
* @param c character to clean up
* @return cleaned-up character
*/
static int cleanupCtrl(int c) {
if (c & CTRL) {
int d = c & 0x1FF;
if (d >= 'a' && d <= 'z') {
c = (c + ('a' - ctrlChar('A'))) & ~CTRL;
}
if (d >= 'A' && d <= 'Z') {
c = (c + ('A' - ctrlChar('A'))) & ~CTRL;
}
if (d >= ctrlChar('A') && d <= ctrlChar('Z')) {
c = c & ~CTRL;
}
}
return c;
}
// break characters that may precede items to be completed
static const char breakChars[] = " =+-/\\*?\"'`&<>;|@{([])}";
// maximum number of completions to display without asking
static const size_t completionCountCutoff = 100;
/**
* Handle command completion, using a completionCallback() routine to provide possible substitutions
* This routine handles the mechanics of updating the user's input buffer with possible replacement
* of text as the user selects a proposed completion string, or cancels the completion attempt.
* @param pi PromptBase struct holding information about the prompt and our screen position
*/
int InputBuffer::completeLine(PromptBase& pi) {
linenoiseCompletions lc;
char c = 0;
// completionCallback() expects a parsable entity, so find the previous break character and
// extract a copy to parse. we also handle the case where tab is hit while not at end-of-line.
int startIndex = pos;
while (--startIndex >= 0) {
if (strchr(breakChars, buf32[startIndex])) {
break;
}
}
++startIndex;
int itemLength = pos - startIndex;
Utf32String unicodeCopy(&buf32[startIndex], itemLength);
Utf8String parseItem(unicodeCopy);
// get a list of completions
completionCallback(reinterpret_cast<char*>(parseItem.get()), &lc);
// if no completions, we are done
if (lc.completionStrings.size() == 0) {
beep();
freeCompletions(&lc);
return 0;
}
// at least one completion
int longestCommonPrefix = 0;
int displayLength = 0;
if (lc.completionStrings.size() == 1) {
longestCommonPrefix = lc.completionStrings[0].length();
} else {
bool keepGoing = true;
while (keepGoing) {
for (size_t j = 0; j < lc.completionStrings.size() - 1; ++j) {
char c1 = lc.completionStrings[j][longestCommonPrefix];
char c2 = lc.completionStrings[j + 1][longestCommonPrefix];
if ((0 == c1) || (0 == c2) || (c1 != c2)) {
keepGoing = false;
break;
}
}
if (keepGoing) {
++longestCommonPrefix;
}
}
}
if (lc.completionStrings.size() != 1) { // beep if ambiguous
beep();
}
// if we can extend the item, extend it and return to main loop
if (longestCommonPrefix > itemLength) {
displayLength = len + longestCommonPrefix - itemLength;
if (displayLength > buflen) {
longestCommonPrefix -= displayLength - buflen; // don't overflow buffer
displayLength = buflen; // truncate the insertion
beep(); // and make a noise
}
Utf32String displayText(displayLength + 1);
memcpy(displayText.get(), buf32, sizeof(UChar32) * startIndex);
memcpy(&displayText[startIndex],
&lc.completionStrings[0][0],
sizeof(UChar32) * longestCommonPrefix);
int tailIndex = startIndex + longestCommonPrefix;
memcpy(&displayText[tailIndex],
&buf32[pos],
sizeof(UChar32) * (displayLength - tailIndex + 1));
copyString32(buf32, displayText.get(), buflen + 1);
pos = startIndex + longestCommonPrefix;
len = displayLength;
refreshLine(pi);
return 0;
}
// we can't complete any further, wait for second tab
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
// if any character other than tab, pass it to the main loop
if (c != ctrlChar('I')) {
freeCompletions(&lc);
return c;
}
// we got a second tab, maybe show list of possible completions
bool showCompletions = true;
bool onNewLine = false;
if (lc.completionStrings.size() > completionCountCutoff) {
int savePos = pos; // move cursor to EOL to avoid overwriting the command line
pos = len;
refreshLine(pi);
pos = savePos;
printf("\nDisplay all %u possibilities? (y or n)",
static_cast<unsigned int>(lc.completionStrings.size()));
fflush(stdout);
onNewLine = true;
while (c != 'y' && c != 'Y' && c != 'n' && c != 'N' && c != ctrlChar('C')) {
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
}
switch (c) {
case 'n':
case 'N':
showCompletions = false;
freeCompletions(&lc);
break;
case ctrlChar('C'):
showCompletions = false;
freeCompletions(&lc);
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
c = 0;
break;
}
}
// if showing the list, do it the way readline does it
bool stopList = false;
if (showCompletions) {
int longestCompletion = 0;
for (size_t j = 0; j < lc.completionStrings.size(); ++j) {
itemLength = lc.completionStrings[j].length();
if (itemLength > longestCompletion) {
longestCompletion = itemLength;
}
}
longestCompletion += 2;
int columnCount = pi.promptScreenColumns / longestCompletion;
if (columnCount < 1) {
columnCount = 1;
}
if (!onNewLine) { // skip this if we showed "Display all %d possibilities?"
int savePos = pos; // move cursor to EOL to avoid overwriting the command line
pos = len;
refreshLine(pi);
pos = savePos;
}
size_t pauseRow = getScreenRows() - 1;
size_t rowCount = (lc.completionStrings.size() + columnCount - 1) / columnCount;
for (size_t row = 0; row < rowCount; ++row) {
if (row == pauseRow) {
printf("\n--More--");
fflush(stdout);
c = 0;
bool doBeep = false;
while (c != ' ' && c != '\r' && c != '\n' && c != 'y' && c != 'Y' && c != 'n' &&
c != 'N' && c != 'q' && c != 'Q' && c != ctrlChar('C')) {
if (doBeep) {
beep();
}
doBeep = true;
do {
c = linenoiseReadChar();
c = cleanupCtrl(c);
} while (c == static_cast<char>(-1));
}
switch (c) {
case ' ':
case 'y':
case 'Y':
printf("\r \r");
pauseRow += getScreenRows() - 1;
break;
case '\r':
case '\n':
printf("\r \r");
++pauseRow;
break;
case 'n':
case 'N':
case 'q':
case 'Q':
printf("\r \r");
stopList = true;
break;
case ctrlChar('C'):
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
stopList = true;
break;
}
} else {
printf("\n");
}
if (stopList) {
break;
}
for (int column = 0; column < columnCount; ++column) {
size_t index = (column * rowCount) + row;
if (index < lc.completionStrings.size()) {
itemLength = lc.completionStrings[index].length();
fflush(stdout);
if (write32(1, lc.completionStrings[index].get(), itemLength) == -1)
return -1;
if (((column + 1) * rowCount) + row < lc.completionStrings.size()) {
for (int k = itemLength; k < longestCompletion; ++k) {
printf(" ");
}
}
}
}
}
fflush(stdout);
freeCompletions(&lc);
}
// display the prompt on a new line, then redisplay the input buffer
if (!stopList || c == ctrlChar('C')) {
if (write(1, "\n", 1) == -1)
return 0;
}
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return 0;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return 0;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines;
refreshLine(pi);
return 0;
}
/**
* Clear the screen ONLY (no redisplay of anything)
*/
void linenoiseClearScreen(void) {
#ifdef _WIN32
COORD coord = {0, 0};
CONSOLE_SCREEN_BUFFER_INFO inf;
HANDLE screenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(screenHandle, &inf);
SetConsoleCursorPosition(screenHandle, coord);
DWORD count;
FillConsoleOutputCharacterA(screenHandle, ' ', inf.dwSize.X * inf.dwSize.Y, coord, &count);
#else
if (write(1, "\x1b[H\x1b[2J", 7) <= 0)
return;
#endif
}
void InputBuffer::clearScreen(PromptBase& pi) {
linenoiseClearScreen();
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return;
#endif
pi.promptCursorRowOffset = pi.promptExtraLines;
refreshLine(pi);
}
/**
* Incremental history search -- take over the prompt and keyboard as the user types a search
* string, deletes characters from it, changes direction, and either accepts the found line (for
* execution orediting) or cancels.
* @param pi PromptBase struct holding information about the (old, static) prompt and our
* screen position
* @param startChar the character that began the search, used to set the initial direction
*/
int InputBuffer::incrementalHistorySearch(PromptBase& pi, int startChar) {
size_t bufferSize;
size_t ucharCount;
int errorCode;
// if not already recalling, add the current line to the history list so we don't have to
// special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
bufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[bufferSize]);
copyString32to8(tempBuffer.get(), buf32, bufferSize);
history[historyLen - 1] =
reinterpret_cast<UChar8*>(strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
int historyLineLength = len;
int historyLinePosition = pos;
UChar32 emptyBuffer[1];
char emptyWidths[1];
InputBuffer empty(emptyBuffer, emptyWidths, 1);
empty.refreshLine(pi); // erase the old input first
DynamicPrompt dp(pi, (startChar == ctrlChar('R')) ? -1 : 1);
dp.promptPreviousLen = pi.promptPreviousLen;
dp.promptPreviousInputLen = pi.promptPreviousInputLen;
dynamicRefresh(
dp, buf32, historyLineLength, historyLinePosition); // draw user's text with our prompt
// loop until we get an exit character
int c;
bool keepLooping = true;
bool useSearchedLine = true;
bool searchAgain = false;
UChar32* activeHistoryLine = 0;
while (keepLooping) {
c = linenoiseReadChar();
c = cleanupCtrl(c); // convert CTRL + <char> into normal ctrl
switch (c) {
// these characters keep the selected text but do not execute it
case ctrlChar('A'): // ctrl-A, move cursor to start of line
case HOME_KEY:
case ctrlChar('B'): // ctrl-B, move cursor left by one character
case LEFT_ARROW_KEY:
case META + 'b': // meta-B, move cursor left by one word
case META + 'B':
case CTRL + LEFT_ARROW_KEY:
case META + LEFT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
case ctrlChar('D'):
case META + 'd': // meta-D, kill word to right of cursor
case META + 'D':
case ctrlChar('E'): // ctrl-E, move cursor to end of line
case END_KEY:
case ctrlChar('F'): // ctrl-F, move cursor right by one character
case RIGHT_ARROW_KEY:
case META + 'f': // meta-F, move cursor right by one word
case META + 'F':
case CTRL + RIGHT_ARROW_KEY:
case META + RIGHT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
case META + ctrlChar('H'):
case ctrlChar('J'):
case ctrlChar('K'): // ctrl-K, kill from cursor to end of line
case ctrlChar('M'):
case ctrlChar('N'): // ctrl-N, recall next line in history
case ctrlChar('P'): // ctrl-P, recall previous line in history
case DOWN_ARROW_KEY:
case UP_ARROW_KEY:
case ctrlChar('T'): // ctrl-T, transpose characters
case ctrlChar('U'): // ctrl-U, kill all characters to the left of the cursor
case ctrlChar('W'):
case META + 'y': // meta-Y, "yank-pop", rotate popped text
case META + 'Y':
case 127:
case DELETE_KEY:
case META + '<': // start of history
case PAGE_UP_KEY:
case META + '>': // end of history
case PAGE_DOWN_KEY:
keepLooping = false;
break;
// these characters revert the input line to its previous state
case ctrlChar('C'): // ctrl-C, abort this line
case ctrlChar('G'):
case ctrlChar('L'): // ctrl-L, clear screen and redisplay line
keepLooping = false;
useSearchedLine = false;
if (c != ctrlChar('L')) {
c = -1; // ctrl-C and ctrl-G just abort the search and do nothing else
}
break;
// these characters stay in search mode and update the display
case ctrlChar('S'):
case ctrlChar('R'):
if (dp.searchTextLen == 0) { // if no current search text, recall previous text
if (previousSearchText.length()) {
dp.updateSearchText(previousSearchText.get());
}
}
if ((dp.direction == 1 && c == ctrlChar('R')) ||
(dp.direction == -1 && c == ctrlChar('S'))) {
dp.direction = 0 - dp.direction; // reverse direction
dp.updateSearchPrompt(); // change the prompt
} else {
searchAgain = true; // same direction, search again
}
break;
// job control is its own thing
#ifndef _WIN32
case ctrlChar('Z'): // ctrl-Z, job control
disableRawMode(); // Returning to Linux (whatever) shell, leave raw mode
raise(SIGSTOP); // Break out in mid-line
enableRawMode(); // Back from Linux shell, re-enter raw mode
{
bufferSize = historyLineLength + 1;
unique_ptr<UChar32[]> tempUnicode(new UChar32[bufferSize]);
copyString8to32(tempUnicode.get(),
history[historyIndex],
bufferSize,
ucharCount,
errorCode);
dynamicRefresh(dp, tempUnicode.get(), historyLineLength, historyLinePosition);
}
continue;
break;
#endif
// these characters update the search string, and hence the selected input line
case ctrlChar('H'): // backspace/ctrl-H, delete char to left of cursor
if (dp.searchTextLen > 0) {
unique_ptr<UChar32[]> tempUnicode(new UChar32[dp.searchTextLen]);
--dp.searchTextLen;
dp.searchText[dp.searchTextLen] = 0;
copyString32(tempUnicode.get(), dp.searchText.get(), dp.searchTextLen + 1);
dp.updateSearchText(tempUnicode.get());
} else {
beep();
}
break;
case ctrlChar('Y'): // ctrl-Y, yank killed text
break;
default:
if (!isControlChar(c) && c <= 0x0010FFFF) { // not an action character
unique_ptr<UChar32[]> tempUnicode(new UChar32[dp.searchTextLen + 2]);
copyString32(tempUnicode.get(), dp.searchText.get(), dp.searchTextLen + 2);
tempUnicode[dp.searchTextLen] = c;
tempUnicode[dp.searchTextLen + 1] = 0;
dp.updateSearchText(tempUnicode.get());
} else {
beep();
}
} // switch
// if we are staying in search mode, search now
if (keepLooping) {
bufferSize = historyLineLength + 1;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(
activeHistoryLine, history[historyIndex], bufferSize, ucharCount, errorCode);
if (dp.searchTextLen > 0) {
bool found = false;
int historySearchIndex = historyIndex;
int lineLength = ucharCount;
int lineSearchPos = historyLinePosition;
if (searchAgain) {
lineSearchPos += dp.direction;
}
searchAgain = false;
while (true) {
while ((dp.direction > 0) ? (lineSearchPos < lineLength)
: (lineSearchPos >= 0)) {
if (strncmp32(dp.searchText.get(),
&activeHistoryLine[lineSearchPos],
dp.searchTextLen) == 0) {
found = true;
break;
}
lineSearchPos += dp.direction;
}
if (found) {
historyIndex = historySearchIndex;
historyLineLength = lineLength;
historyLinePosition = lineSearchPos;
break;
} else if ((dp.direction > 0) ? (historySearchIndex < historyLen - 1)
: (historySearchIndex > 0)) {
historySearchIndex += dp.direction;
bufferSize =
strlen(reinterpret_cast<char*>(history[historySearchIndex])) + 1;
delete[] activeHistoryLine;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(activeHistoryLine,
history[historySearchIndex],
bufferSize,
ucharCount,
errorCode);
lineLength = ucharCount;
lineSearchPos = (dp.direction > 0) ? 0 : (lineLength - dp.searchTextLen);
} else {
beep();
break;
}
}; // while
}
if (activeHistoryLine) {
delete[] activeHistoryLine;
}
bufferSize = historyLineLength + 1;
activeHistoryLine = new UChar32[bufferSize];
copyString8to32(
activeHistoryLine, history[historyIndex], bufferSize, ucharCount, errorCode);
dynamicRefresh(dp,
activeHistoryLine,
historyLineLength,
historyLinePosition); // draw user's text with our prompt
}
} // while
// leaving history search, restore previous prompt, maybe make searched line current
PromptBase pb;
pb.promptChars = pi.promptIndentation;
Utf32String tempUnicode(pb.promptChars + 1);
copyString32(tempUnicode.get(), &pi.promptText[pi.promptLastLinePosition], pb.promptChars + 1);
tempUnicode.initFromBuffer();
pb.promptText = tempUnicode;
pb.promptExtraLines = 0;
pb.promptIndentation = pi.promptIndentation;
pb.promptLastLinePosition = 0;
pb.promptPreviousInputLen = historyLineLength;
pb.promptCursorRowOffset = dp.promptCursorRowOffset;
pb.promptScreenColumns = pi.promptScreenColumns;
pb.promptPreviousLen = dp.promptChars;
if (useSearchedLine && activeHistoryLine) {
historyRecallMostRecent = true;
copyString32(buf32, activeHistoryLine, buflen + 1);
len = historyLineLength;
pos = historyLinePosition;
}
if (activeHistoryLine) {
delete[] activeHistoryLine;
}
dynamicRefresh(pb, buf32, len, pos); // redraw the original prompt with current input
pi.promptPreviousInputLen = len;
pi.promptCursorRowOffset = pi.promptExtraLines + pb.promptCursorRowOffset;
previousSearchText = dp.searchText; // save search text for possible reuse on ctrl-R ctrl-R
return c; // pass a character or -1 back to main loop
}
static bool isCharacterAlphanumeric(UChar32 testChar) {
return iswalnum(testChar);
}
int InputBuffer::getInputLine(PromptBase& pi) {
// The latest history entry is always our current buffer
if (len > 0) {
size_t bufferSize = sizeof(UChar32) * len + 1;
unique_ptr<char[]> tempBuffer(new char[bufferSize]);
copyString32to8(reinterpret_cast<UChar8*>(tempBuffer.get()), buf32, bufferSize);
linenoiseHistoryAdd(tempBuffer.get());
} else {
linenoiseHistoryAdd("");
}
historyIndex = historyLen - 1;
historyRecallMostRecent = false;
// display the prompt
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return -1;
#ifndef _WIN32
// we have to generate our own newline on line wrap on Linux
if (pi.promptIndentation == 0 && pi.promptExtraLines > 0)
if (write(1, "\n", 1) == -1)
return -1;
#endif
// the cursor starts out at the end of the prompt
pi.promptCursorRowOffset = pi.promptExtraLines;
// kill and yank start in "other" mode
killRing.lastAction = KillRing::actionOther;
// when history search returns control to us, we execute its terminating keystroke
int terminatingKeystroke = -1;
// if there is already text in the buffer, display it first
if (len > 0) {
refreshLine(pi);
}
// loop collecting characters, respond to line editing characters
while (true) {
int c;
if (terminatingKeystroke == -1) {
c = linenoiseReadChar(); // get a new keystroke
} else {
c = terminatingKeystroke; // use the terminating keystroke from search
terminatingKeystroke = -1; // clear it once we've used it
}
c = cleanupCtrl(c); // convert CTRL + <char> into normal ctrl
if (c == 0) {
return len;
}
if (c == -1) {
refreshLine(pi);
continue;
}
if (c == -2) {
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return -1;
refreshLine(pi);
continue;
}
// ctrl-I/tab, command completion, needs to be before switch statement
if (c == ctrlChar('I') && completionCallback) {
if (pos == 0) // SERVER-4967 -- in earlier versions, you could paste previous output
continue; // back into the shell ... this output may have leading tabs.
// This hack (i.e. what the old code did) prevents command completion
// on an empty line but lets users paste text with leading tabs.
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
// completeLine does the actual completion and replacement
c = completeLine(pi);
if (c < 0) // return on error
return len;
if (c == 0) // read next character when 0
continue;
// deliberate fall-through here, so we use the terminating character
}
switch (c) {
case ctrlChar('A'): // ctrl-A, move cursor to start of line
case HOME_KEY:
killRing.lastAction = KillRing::actionOther;
pos = 0;
refreshLine(pi);
break;
case ctrlChar('B'): // ctrl-B, move cursor left by one character
case LEFT_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
--pos;
refreshLine(pi);
}
break;
case META + 'b': // meta-B, move cursor left by one word
case META + 'B':
case CTRL + LEFT_ARROW_KEY:
case META + LEFT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
while (pos > 0 && !isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
while (pos > 0 && isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
refreshLine(pi);
}
break;
case ctrlChar('C'): // ctrl-C, abort this line
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
errno = EAGAIN;
--historyLen;
free(history[historyLen]);
// we need one last refresh with the cursor at the end of the line
// so we don't display the next prompt over the previous input line
pos = len; // pass len as pos for EOL
refreshLine(pi);
if (write(1, "^C", 2) == -1)
return -1; // Display the ^C we got
return -1;
case META + 'c': // meta-C, give word initial Cap
case META + 'C':
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
if (pos < len) {
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
if (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'a' && buf32[pos] <= 'z') {
buf32[pos] += 'A' - 'a';
}
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'A' && buf32[pos] <= 'Z') {
buf32[pos] += 'a' - 'A';
}
++pos;
}
refreshLine(pi);
}
break;
// ctrl-D, delete the character under the cursor
// on an empty line, exit the shell
case ctrlChar('D'):
killRing.lastAction = KillRing::actionOther;
if (len > 0 && pos < len) {
historyRecallMostRecent = false;
memmove(buf32 + pos, buf32 + pos + 1, sizeof(UChar32) * (len - pos));
--len;
refreshLine(pi);
} else if (len == 0) {
--historyLen;
free(history[historyLen]);
return -1;
}
break;
case META + 'd': // meta-D, kill word to right of cursor
case META + 'D':
if (pos < len) {
historyRecallMostRecent = false;
int endingPos = pos;
while (endingPos < len && !isCharacterAlphanumeric(buf32[endingPos])) {
++endingPos;
}
while (endingPos < len && isCharacterAlphanumeric(buf32[endingPos])) {
++endingPos;
}
killRing.kill(&buf32[pos], endingPos - pos, true);
memmove(
buf32 + pos, buf32 + endingPos, sizeof(UChar32) * (len - endingPos + 1));
len -= endingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('E'): // ctrl-E, move cursor to end of line
case END_KEY:
killRing.lastAction = KillRing::actionOther;
pos = len;
refreshLine(pi);
break;
case ctrlChar('F'): // ctrl-F, move cursor right by one character
case RIGHT_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
++pos;
refreshLine(pi);
}
break;
case META + 'f': // meta-F, move cursor right by one word
case META + 'F':
case CTRL + RIGHT_ARROW_KEY:
case META + RIGHT_ARROW_KEY: // Emacs allows Meta, bash & readline don't
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
refreshLine(pi);
}
break;
case ctrlChar('H'): // backspace/ctrl-H, delete char to left of cursor
killRing.lastAction = KillRing::actionOther;
if (pos > 0) {
historyRecallMostRecent = false;
memmove(buf32 + pos - 1, buf32 + pos, sizeof(UChar32) * (1 + len - pos));
--pos;
--len;
refreshLine(pi);
}
break;
// meta-Backspace, kill word to left of cursor
case META + ctrlChar('H'):
if (pos > 0) {
historyRecallMostRecent = false;
int startingPos = pos;
while (pos > 0 && !isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
while (pos > 0 && isCharacterAlphanumeric(buf32[pos - 1])) {
--pos;
}
killRing.kill(&buf32[pos], startingPos - pos, false);
memmove(buf32 + pos,
buf32 + startingPos,
sizeof(UChar32) * (len - startingPos + 1));
len -= startingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('J'): // ctrl-J/linefeed/newline, accept line
case ctrlChar('M'): // ctrl-M/return/enter
killRing.lastAction = KillRing::actionOther;
// we need one last refresh with the cursor at the end of the line
// so we don't display the next prompt over the previous input line
pos = len; // pass len as pos for EOL
refreshLine(pi);
historyPreviousIndex = historyRecallMostRecent ? historyIndex : -2;
--historyLen;
free(history[historyLen]);
return len;
case ctrlChar('K'): // ctrl-K, kill from cursor to end of line
killRing.kill(&buf32[pos], len - pos, true);
buf32[pos] = '\0';
len = pos;
refreshLine(pi);
killRing.lastAction = KillRing::actionKill;
historyRecallMostRecent = false;
break;
case ctrlChar('L'): // ctrl-L, clear screen and redisplay line
clearScreen(pi);
break;
case META + 'l': // meta-L, lowercase word
case META + 'L':
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
historyRecallMostRecent = false;
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'A' && buf32[pos] <= 'Z') {
buf32[pos] += 'a' - 'A';
}
++pos;
}
refreshLine(pi);
}
break;
case ctrlChar('N'): // ctrl-N, recall next line in history
case ctrlChar('P'): // ctrl-P, recall previous line in history
case DOWN_ARROW_KEY:
case UP_ARROW_KEY:
killRing.lastAction = KillRing::actionOther;
// if not already recalling, add the current line to the history list so we don't
// have to special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
size_t tempBufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[tempBufferSize]);
copyString32to8(tempBuffer.get(), buf32, tempBufferSize);
history[historyLen - 1] = reinterpret_cast<UChar8*>(
strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
if (historyLen > 1) {
if (c == UP_ARROW_KEY) {
c = ctrlChar('P');
}
if (historyPreviousIndex != -2 && c != ctrlChar('P')) {
historyIndex = 1 + historyPreviousIndex; // emulate Windows down-arrow
} else {
historyIndex += (c == ctrlChar('P')) ? -1 : 1;
}
historyPreviousIndex = -2;
if (historyIndex < 0) {
historyIndex = 0;
break;
} else if (historyIndex >= historyLen) {
historyIndex = historyLen - 1;
break;
}
historyRecallMostRecent = true;
size_t ucharCount;
int errorCode;
copyString8to32(buf32, history[historyIndex], buflen, ucharCount, errorCode);
len = pos = ucharCount;
refreshLine(pi);
}
break;
case ctrlChar('R'): // ctrl-R, reverse history search
case ctrlChar('S'): // ctrl-S, forward history search
terminatingKeystroke = incrementalHistorySearch(pi, c);
break;
case ctrlChar('T'): // ctrl-T, transpose characters
killRing.lastAction = KillRing::actionOther;
if (pos > 0 && len > 1) {
historyRecallMostRecent = false;
size_t leftCharPos = (pos == len) ? pos - 2 : pos - 1;
char aux = buf32[leftCharPos];
buf32[leftCharPos] = buf32[leftCharPos + 1];
buf32[leftCharPos + 1] = aux;
if (pos != len)
++pos;
refreshLine(pi);
}
break;
case ctrlChar('U'): // ctrl-U, kill all characters to the left of the cursor
if (pos > 0) {
historyRecallMostRecent = false;
killRing.kill(&buf32[0], pos, false);
len -= pos;
memmove(buf32, buf32 + pos, sizeof(UChar32) * (len + 1));
pos = 0;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case META + 'u': // meta-U, uppercase word
case META + 'U':
killRing.lastAction = KillRing::actionOther;
if (pos < len) {
historyRecallMostRecent = false;
while (pos < len && !isCharacterAlphanumeric(buf32[pos])) {
++pos;
}
while (pos < len && isCharacterAlphanumeric(buf32[pos])) {
if (buf32[pos] >= 'a' && buf32[pos] <= 'z') {
buf32[pos] += 'A' - 'a';
}
++pos;
}
refreshLine(pi);
}
break;
// ctrl-W, kill to whitespace (not word) to left of cursor
case ctrlChar('W'):
if (pos > 0) {
historyRecallMostRecent = false;
int startingPos = pos;
while (pos > 0 && buf32[pos - 1] == ' ') {
--pos;
}
while (pos > 0 && buf32[pos - 1] != ' ') {
--pos;
}
killRing.kill(&buf32[pos], startingPos - pos, false);
memmove(buf32 + pos,
buf32 + startingPos,
sizeof(UChar32) * (len - startingPos + 1));
len -= startingPos - pos;
refreshLine(pi);
}
killRing.lastAction = KillRing::actionKill;
break;
case ctrlChar('Y'): // ctrl-Y, yank killed text
historyRecallMostRecent = false;
{
Utf32String* restoredText = killRing.yank();
if (restoredText) {
bool truncated = false;
size_t ucharCount = restoredText->length();
if (ucharCount > static_cast<size_t>(buflen - len)) {
ucharCount = buflen - len;
truncated = true;
}
memmove(buf32 + pos + ucharCount,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
memmove(buf32 + pos, restoredText->get(), sizeof(UChar32) * ucharCount);
pos += ucharCount;
len += ucharCount;
refreshLine(pi);
killRing.lastAction = KillRing::actionYank;
killRing.lastYankSize = ucharCount;
if (truncated) {
beep();
}
} else {
beep();
}
}
break;
case META + 'y': // meta-Y, "yank-pop", rotate popped text
case META + 'Y':
if (killRing.lastAction == KillRing::actionYank) {
historyRecallMostRecent = false;
Utf32String* restoredText = killRing.yankPop();
if (restoredText) {
bool truncated = false;
size_t ucharCount = restoredText->length();
if (ucharCount >
static_cast<size_t>(killRing.lastYankSize + buflen - len)) {
ucharCount = killRing.lastYankSize + buflen - len;
truncated = true;
}
if (ucharCount > killRing.lastYankSize) {
memmove(buf32 + pos + ucharCount - killRing.lastYankSize,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
memmove(buf32 + pos - killRing.lastYankSize,
restoredText->get(),
sizeof(UChar32) * ucharCount);
} else {
memmove(buf32 + pos - killRing.lastYankSize,
restoredText->get(),
sizeof(UChar32) * ucharCount);
memmove(buf32 + pos + ucharCount - killRing.lastYankSize,
buf32 + pos,
sizeof(UChar32) * (len - pos + 1));
}
pos += ucharCount - killRing.lastYankSize;
len += ucharCount - killRing.lastYankSize;
killRing.lastYankSize = ucharCount;
refreshLine(pi);
if (truncated) {
beep();
}
break;
}
}
beep();
break;
#ifndef _WIN32
case ctrlChar('Z'): // ctrl-Z, job control
disableRawMode(); // Returning to Linux (whatever) shell, leave raw mode
raise(SIGSTOP); // Break out in mid-line
enableRawMode(); // Back from Linux shell, re-enter raw mode
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
break; // Redraw prompt
refreshLine(pi); // Refresh the line
break;
#endif
// DEL, delete the character under the cursor
case 127:
case DELETE_KEY:
killRing.lastAction = KillRing::actionOther;
if (len > 0 && pos < len) {
historyRecallMostRecent = false;
memmove(buf32 + pos, buf32 + pos + 1, sizeof(UChar32) * (len - pos));
--len;
refreshLine(pi);
}
break;
case META + '<': // meta-<, beginning of history
case PAGE_UP_KEY: // Page Up, beginning of history
case META + '>': // meta->, end of history
case PAGE_DOWN_KEY: // Page Down, end of history
killRing.lastAction = KillRing::actionOther;
// if not already recalling, add the current line to the history list so we don't
// have to special case it
if (historyIndex == historyLen - 1) {
free(history[historyLen - 1]);
size_t tempBufferSize = sizeof(UChar32) * len + 1;
unique_ptr<UChar8[]> tempBuffer(new UChar8[tempBufferSize]);
copyString32to8(tempBuffer.get(), buf32, tempBufferSize);
history[historyLen - 1] = reinterpret_cast<UChar8*>(
strdup(reinterpret_cast<const char*>(tempBuffer.get())));
}
if (historyLen > 1) {
historyIndex = (c == META + '<' || c == PAGE_UP_KEY) ? 0 : historyLen - 1;
historyPreviousIndex = -2;
historyRecallMostRecent = true;
size_t ucharCount;
int errorCode;
copyString8to32(buf32, history[historyIndex], buflen, ucharCount, errorCode);
len = pos = ucharCount;
refreshLine(pi);
}
break;
// not one of our special characters, maybe insert it in the buffer
default:
killRing.lastAction = KillRing::actionOther;
historyRecallMostRecent = false;
if (c & (META | CTRL)) { // beep on unknown Ctrl and/or Meta keys
beep();
break;
}
if (len < buflen) {
if (isControlChar(c)) { // don't insert control characters
beep();
break;
}
if (len == pos) { // at end of buffer
buf32[pos] = c;
++pos;
++len;
buf32[len] = '\0';
int inputLen = calculateColumnPosition(buf32, len);
if (pi.promptIndentation + inputLen < pi.promptScreenColumns) {
if (inputLen > pi.promptPreviousInputLen)
pi.promptPreviousInputLen = inputLen;
/* Avoid a full update of the line in the
* trivial case. */
if (write32(1, reinterpret_cast<UChar32*>(&c), 1) == -1)
return -1;
} else {
refreshLine(pi);
}
} else { // not at end of buffer, have to move characters to our right
memmove(buf32 + pos + 1, buf32 + pos, sizeof(UChar32) * (len - pos));
buf32[pos] = c;
++len;
++pos;
buf32[len] = '\0';
refreshLine(pi);
}
} else {
beep(); // buffer is full, beep on new characters
}
break;
}
}
return len;
}
string preloadedBufferContents; // used with linenoisePreloadBuffer
string preloadErrorMessage;
/**
* linenoisePreloadBuffer provides text to be inserted into the command buffer
*
* the provided text will be processed to be usable and will be used to preload
* the input buffer on the next call to linenoise()
*
* @param preloadText text to begin with on the next call to linenoise()
*/
void linenoisePreloadBuffer(const char* preloadText) {
if (!preloadText) {
return;
}
int bufferSize = strlen(preloadText) + 1;
unique_ptr<char[]> tempBuffer(new char[bufferSize]);
strncpy(&tempBuffer[0], preloadText, bufferSize);
// remove characters that won't display correctly
char* pIn = &tempBuffer[0];
char* pOut = pIn;
bool controlsStripped = false;
bool whitespaceSeen = false;
while (*pIn) {
unsigned char c = *pIn++; // we need unsigned so chars 0x80 and above are allowed
if ('\r' == c) { // silently skip CR
continue;
}
if ('\n' == c || '\t' == c) { // note newline or tab
whitespaceSeen = true;
continue;
}
if (isControlChar(c)) { // remove other control characters, flag for message
controlsStripped = true;
*pOut++ = ' ';
continue;
}
if (whitespaceSeen) { // convert whitespace to a single space
*pOut++ = ' ';
whitespaceSeen = false;
}
*pOut++ = c;
}
*pOut = 0;
int processedLength = pOut - tempBuffer.get();
bool lineTruncated = false;
if (processedLength > (LINENOISE_MAX_LINE - 1)) {
lineTruncated = true;
tempBuffer[LINENOISE_MAX_LINE - 1] = 0;
}
preloadedBufferContents = tempBuffer.get();
if (controlsStripped) {
preloadErrorMessage += " [Edited line: control characters were converted to spaces]\n";
}
if (lineTruncated) {
preloadErrorMessage += " [Edited line: the line length was reduced from ";
char buf[128];
snprintf(buf, sizeof(buf), "%d to %d]\n", processedLength, (LINENOISE_MAX_LINE - 1));
preloadErrorMessage += buf;
}
}
/**
* linenoise is a readline replacement.
*
* call it with a prompt to display and it will return a line of input from the user
*
* @param prompt text of prompt to display to the user
* @return the returned string belongs to the caller on return and must be freed to prevent
* memory leaks
*/
char* linenoise(const char* prompt) {
if (isatty(STDIN_FILENO)) { // input is from a terminal
UChar32 buf32[LINENOISE_MAX_LINE];
char charWidths[LINENOISE_MAX_LINE];
if (!preloadErrorMessage.empty()) {
printf("%s", preloadErrorMessage.c_str());
fflush(stdout);
preloadErrorMessage.clear();
}
PromptInfo pi(reinterpret_cast<const UChar8*>(prompt), getScreenColumns());
if (isUnsupportedTerm()) {
if (write32(1, pi.promptText.get(), pi.promptChars) == -1)
return 0;
fflush(stdout);
if (preloadedBufferContents.empty()) {
unique_ptr<char[]> buf8(new char[LINENOISE_MAX_LINE]);
if (fgets(buf8.get(), LINENOISE_MAX_LINE, stdin) == NULL) {
return NULL;
}
size_t len = strlen(buf8.get());
while (len && (buf8[len - 1] == '\n' || buf8[len - 1] == '\r')) {
--len;
buf8[len] = '\0';
}
return strdup(buf8.get()); // caller must free buffer
} else {
char* buf8 = strdup(preloadedBufferContents.c_str());
preloadedBufferContents.clear();
return buf8; // caller must free buffer
}
} else {
if (enableRawMode() == -1) {
return NULL;
}
InputBuffer ib(buf32, charWidths, LINENOISE_MAX_LINE);
if (!preloadedBufferContents.empty()) {
ib.preloadBuffer(reinterpret_cast<const UChar8*>(preloadedBufferContents.c_str()));
preloadedBufferContents.clear();
}
int count = ib.getInputLine(pi);
disableRawMode();
printf("\n");
if (count == -1) {
return NULL;
}
size_t bufferSize = sizeof(UChar32) * ib.length() + 1;
unique_ptr<UChar8[]> buf8(new UChar8[bufferSize]);
copyString32to8(buf8.get(), buf32, bufferSize);
return strdup(reinterpret_cast<char*>(buf8.get())); // caller must free buffer
}
} else { // input not from a terminal, we should work with piped input, i.e. redirected stdin
unique_ptr<char[]> buf8(new char[LINENOISE_MAX_LINE]);
if (fgets(buf8.get(), LINENOISE_MAX_LINE, stdin) == NULL) {
return NULL;
}
// if fgets() gave us the newline, remove it
int count = strlen(buf8.get());
if (count > 0 && buf8[count - 1] == '\n') {
--count;
buf8[count] = '\0';
}
return strdup(buf8.get()); // caller must free buffer
}
}
/* Register a callback function to be called for tab-completion. */
void linenoiseSetCompletionCallback(linenoiseCompletionCallback* fn) {
completionCallback = fn;
}
void linenoiseAddCompletion(linenoiseCompletions* lc, const char* str) {
lc->completionStrings.push_back(Utf32String(reinterpret_cast<const UChar8*>(str)));
}
int linenoiseHistoryAdd(const char* line) {
if (historyMaxLen == 0) {
return 0;
}
if (history == NULL) {
history = reinterpret_cast<UChar8**>(malloc(sizeof(UChar8*) * historyMaxLen));
if (history == NULL) {
return 0;
}
memset(history, 0, (sizeof(char*) * historyMaxLen));
}
UChar8* linecopy = reinterpret_cast<UChar8*>(strdup(line));
if (!linecopy) {
return 0;
}
if (historyLen == historyMaxLen) {
free(history[0]);
memmove(history, history + 1, sizeof(char*) * (historyMaxLen - 1));
--historyLen;
if (--historyPreviousIndex < -1) {
historyPreviousIndex = -2;
}
}
// convert newlines in multi-line code to spaces before storing
UChar8* p = linecopy;
while (*p) {
if (*p == '\n') {
*p = ' ';
}
++p;
}
history[historyLen] = linecopy;
++historyLen;
return 1;
}
int linenoiseHistorySetMaxLen(int len) {
if (len < 1) {
return 0;
}
if (history) {
int tocopy = historyLen;
UChar8** newHistory = reinterpret_cast<UChar8**>(malloc(sizeof(UChar8*) * len));
if (newHistory == NULL) {
return 0;
}
if (len < tocopy) {
tocopy = len;
}
memcpy(newHistory, history + historyMaxLen - tocopy, sizeof(UChar8*) * tocopy);
free(history);
history = newHistory;
}
historyMaxLen = len;
if (historyLen > historyMaxLen) {
historyLen = historyMaxLen;
}
return 1;
}
/* Save the history in the specified file. On success 0 is returned
* otherwise -1 is returned. */
int linenoiseHistorySave(const char* filename) {
FILE* fp = fopen(filename, "wt");
if (fp == NULL) {
return -1;
}
for (int j = 0; j < historyLen; ++j) {
if (history[j][0] != '\0') {
fprintf(fp, "%s\n", history[j]);
}
}
fclose(fp);
return 0;
}
/* Load the history from the specified file. If the file does not exist
* zero is returned and no operation is performed.
*
* If the file exists and the operation succeeded 0 is returned, otherwise
* on error -1 is returned. */
int linenoiseHistoryLoad(const char* filename) {
FILE* fp = fopen(filename, "rt");
if (fp == NULL) {
return -1;
}
char buf[LINENOISE_MAX_LINE];
while (fgets(buf, LINENOISE_MAX_LINE, fp) != NULL) {
char* p = strchr(buf, '\r');
if (!p) {
p = strchr(buf, '\n');
}
if (p) {
*p = '\0';
}
if (p != buf) {
linenoiseHistoryAdd(buf);
}
}
fclose(fp);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_5212_1 |
crossvul-cpp_data_bad_1650_2 | /*
Copyright (C) 2003 - 2015 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
// Include files for opendir(3), readdir(3), etc.
// These files may vary from platform to platform,
// since these functions are NOT ANSI-conforming functions.
// They may have to be altered to port to new platforms
//for mkdir
#include <sys/stat.h>
#ifdef _WIN32
#include "filesystem_win32.ii"
#include <cctype>
#else /* !_WIN32 */
#include <unistd.h>
#include <dirent.h>
#include <libgen.h>
#endif /* !_WIN32 */
// for getenv
#include <cerrno>
#include <fstream>
#include <iomanip>
#include <set>
#include <boost/algorithm/string.hpp>
// for strerror
#include <cstring>
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "scoped_resource.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "version.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace {
const mode_t AccessMode = 00770;
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFBase.h>
#endif
namespace filesystem {
void get_files_in_dir(const std::string &directory,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum)
{
// If we have a path to find directories in,
// then convert relative pathnames to be rooted
// on the wesnoth path
if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
std::string dir = game_config::path + "/" + directory;
if(is_directory(dir)) {
get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
return;
}
}
struct stat st;
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
std::string maincfg;
if (directory.empty() || directory[directory.size()-1] == '/')
maincfg = directory + maincfg_filename;
else
maincfg = (directory + "/") + maincfg_filename;
if (::stat(maincfg.c_str(), &st) != -1) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(maincfg);
else
files->push_back(maincfg_filename);
}
return;
}
}
DIR* dir = opendir(directory.c_str());
if(dir == NULL) {
// Probably not a directory, let the caller deal with it.
return;
}
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] == '.')
continue;
#ifdef __APPLE__
// HFS Mac OS X decomposes filenames using combining unicode characters.
// Try to get the precomposed form.
char macname[MAXNAMLEN+1];
CFStringRef cstr = CFStringCreateWithCString(NULL,
entry->d_name,
kCFStringEncodingUTF8);
CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
0, cstr);
CFStringNormalize(mut_str, kCFStringNormalizationFormC);
CFStringGetCString(mut_str,
macname,sizeof(macname)-1,
kCFStringEncodingUTF8);
CFRelease(cstr);
CFRelease(mut_str);
const std::string basename = macname;
#else
// generic Unix
const std::string basename = entry->d_name;
#endif /* !APPLE */
std::string fullname;
if (directory.empty() || directory[directory.size()-1] == '/')
fullname = directory + basename;
else
fullname = directory + "/" + basename;
if (::stat(fullname.c_str(), &st) != -1) {
if (S_ISREG(st.st_mode)) {
if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
continue;
}
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(fullname);
else
files->push_back(basename);
}
if (checksum != NULL) {
if(st.st_mtime > checksum->modified) {
checksum->modified = st.st_mtime;
}
checksum->sum_size += st.st_size;
checksum->nfiles++;
}
} else if (S_ISDIR(st.st_mode)) {
if (filter == SKIP_MEDIA_DIR
&& (basename == "images"|| basename == "sounds"))
continue;
if (reorder == DO_REORDER &&
::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
S_ISREG(st.st_mode)) {
LOG_FS << "_main.cfg found : ";
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH) {
files->push_back(fullname + "/" + maincfg_filename);
LOG_FS << fullname << "/" << maincfg_filename << '\n';
} else {
files->push_back(basename + "/" + maincfg_filename);
LOG_FS << basename << "/" << maincfg_filename << '\n';
}
} else {
// Show what I consider strange
LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory " << std::endl;
}
} else if (dirs != NULL) {
if (mode == ENTIRE_FILE_PATH)
dirs->push_back(fullname);
else
dirs->push_back(basename);
}
}
}
}
closedir(dir);
if(files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
unsigned int foundit = 0;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
// If _initial.cfg needs to be moved (it was found, but not at index 0).
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; --i)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
std::string get_dir(const std::string& dir_path)
{
DIR* dir = opendir(dir_path.c_str());
if(dir == NULL) {
const int res = mkdir(dir_path.c_str(),AccessMode);
if(res == 0) {
dir = opendir(dir_path.c_str());
} else {
ERR_FS << "could not open or create directory: " << dir_path << std::endl;
}
}
if(dir == NULL)
return "";
closedir(dir);
return dir_path;
}
bool make_directory(const std::string& path)
{
return (mkdir(path.c_str(),AccessMode) == 0);
}
// This deletes a directory with no hidden files and subdirectories.
// Also deletes a single file.
bool delete_directory(const std::string& path, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
errno = 0;
if(remove((*i).c_str()) != 0) {
LOG_FS << "remove(" << (*i) << "): " << strerror(errno) << std::endl;
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
if(!delete_directory(*j))
ret = false;
}
}
errno = 0;
#ifdef _WIN32
// remove() doesn't delete directories on windows.
int (*remove)(const char*);
if(is_directory(path))
remove = rmdir;
else
remove = ::remove;
#endif
if(remove(path.c_str()) != 0) {
LOG_FS << "remove(" << path << "): " << strerror(errno) << std::endl;
ret = false;
}
return ret;
}
bool delete_file(const std::string& path)
{
bool ret = true;
if(remove(path.c_str()) != 0 && errno != ENOENT) {
ERR_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
std::string get_cwd()
{
char buf[1024];
const char* const res = getcwd(buf,sizeof(buf));
if(res != NULL) {
std::string str(res);
#ifdef _WIN32
std::replace(str.begin(),str.end(),'\\','/');
#endif
return str;
} else {
return "";
}
}
std::string get_exe_dir()
{
#ifndef _WIN32
char buf[1024];
size_t path_size = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if(path_size == static_cast<size_t>(-1))
return std::string();
buf[path_size] = 0;
return std::string(dirname(buf));
#else
return get_cwd();
#endif
}
bool create_directory_if_missing(const std::string& dirname)
{
if(is_directory(dirname)) {
DBG_FS << "directory " << dirname << " exists, not creating" << std::endl;
return true;
} else if(file_exists(dirname)) {
ERR_FS << "cannot create directory " << dirname << "; file exists" << std::endl;
return false;
}
DBG_FS << "creating missing directory " << dirname << '\n';
return make_directory(dirname);
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
DBG_FS<<"creating recursive directory: "<<dirname<<'\n';
if (is_directory(dirname) == false && dirname.empty() == false)
{
std::string tmp_dirname = dirname;
// remove trailing slashes or backslashes
while ((tmp_dirname[tmp_dirname.size()-1] == '/' ||
tmp_dirname[tmp_dirname.size()-1] == '\\') &&
!tmp_dirname.empty())
{
tmp_dirname.erase(tmp_dirname.size()-1);
}
// create the first non-existing directory
size_t pos = tmp_dirname.rfind("/");
// we get the most right directory and *skip* it
// we are creating it when we get back here
if (tmp_dirname.rfind('\\') != std::string::npos &&
tmp_dirname.rfind('\\') > pos )
pos = tmp_dirname.rfind('\\');
if (pos != std::string::npos)
create_directory_if_missing_recursive(tmp_dirname.substr(0,pos));
return create_directory_if_missing(tmp_dirname);
}
return create_directory_if_missing(dirname);
}
static std::string user_data_dir, user_config_dir, cache_dir;
static void setup_user_data_dir();
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
void set_user_data_dir(std::string path)
{
#ifdef _WIN32
if(path.empty()) {
user_data_dir = get_cwd() + "/userdata";
} else if (path.size() > 2 && path[1] == ':') {
//allow absolute path override
user_data_dir = path;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathA;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathA = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathA"));
if(SHGetSpecialFolderPathA) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents" << std::endl;
char my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathA(NULL, my_documents_path, 5, 1)) {
std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path + "/" + path;
} else {
WRN_FS << "SHGetSpecialFolderPath failed" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function" << std::endl;
user_data_dir = get_cwd() + "/" + path;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (path.empty()) path = PREFERENCES_DIR;
#endif
std::string path2 = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (path.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
path = path2;
goto other;
}
user_data_dir = home_str;
user_data_dir += "/.local/share";
} else user_data_dir = xdg_data;
user_data_dir += "/wesnoth/";
user_data_dir += get_version_path_suffix();
create_directory_if_missing_recursive(user_data_dir);
} else {
other:
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + "/" + path;
}
#else
if (path.empty()) path = path2;
const char* home_str = getenv("HOME");
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + std::string("/") + path;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
void set_user_config_dir(std::string path)
{
user_config_dir = path;
create_directory_if_missing(user_config_dir);
}
static void setup_user_data_dir()
{
#ifdef _WIN32
_mkdir(user_data_dir.c_str());
_mkdir((user_data_dir + "/editor").c_str());
_mkdir((user_data_dir + "/editor/maps").c_str());
_mkdir((user_data_dir + "/editor/scenarios").c_str());
_mkdir((user_data_dir + "/data").c_str());
_mkdir((user_data_dir + "/data/add-ons").c_str());
_mkdir((user_data_dir + "/saves").c_str());
_mkdir((user_data_dir + "/persist").c_str());
#else
const std::string& dir_path = user_data_dir;
const bool res = create_directory_if_missing(dir_path);
// probe read permissions (if we could make the directory)
DIR* const dir = res ? opendir(dir_path.c_str()) : NULL;
if(dir == NULL) {
ERR_FS << "could not open or create preferences directory at " << dir_path << std::endl;
return;
}
closedir(dir);
// Create user data and add-on directories
create_directory_if_missing(dir_path + "/editor");
create_directory_if_missing(dir_path + "/editor/maps");
create_directory_if_missing(dir_path + "/editor/scenarios");
create_directory_if_missing(dir_path + "/data");
create_directory_if_missing(dir_path + "/data/add-ons");
create_directory_if_missing(dir_path + "/saves");
create_directory_if_missing(dir_path + "/persist");
#endif
}
std::string get_user_data_dir()
{
// ensure setup gets called only once per session
// FIXME: this is okay and optimized, but how should we react
// if the user deletes a dir while we are running?
if (user_data_dir.empty())
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
std::string path;
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_dir();
return user_config_dir;
}
path = xdg_config;
path += "/.config";
} else path = xdg_config;
path += "/wesnoth";
set_user_config_dir(path);
#else
user_config_dir = get_user_data_dir();
#endif
}
return user_config_dir;
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_dir() + "/cache");
return cache_dir;
}
cache_dir = xdg_cache;
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
return cache_dir;
}
static std::string read_stream(std::istream& s)
{
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading." << std::endl;
if (fname.empty())
{
ERR_FS << "Trying to open file with empty name." << std::endl;
std::ifstream *s = new std::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
std::ifstream *s = new std::ifstream(fname.c_str(),std::ios_base::binary);
if (s->is_open()) {
return s;
}
if (treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading." << std::endl;
} else {
LOG_FS << "Could not open '" << fname << "' for reading." << std::endl;
}
return s;
}
std::string read_file(const std::string &fname)
{
scoped_istream s = istream_file(fname);
return read_stream(*s);
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing." << std::endl;
return new std::ofstream(fname.c_str(), std::ios_base::binary);
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
//const util::scoped_resource<FILE*,close_FILE> file(fopen(fname.c_str(),"wb"));
const util::scoped_FILE file(fopen(fname.c_str(),"wb"));
if(file.get() == NULL) {
throw io_exception("Could not open file for writing: '" + fname + "'");
}
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
const size_t res = fwrite(buf,1,bytes,file.get());
if(res != bytes) {
throw io_exception("Error writing to file: '" + fname + "'");
}
}
}
static bool is_directory_internal(const std::string& fname)
{
#ifdef _WIN32
_finddata_t info;
const long handle = _findfirst((fname + "/*").c_str(),&info);
if(handle >= 0) {
_findclose(handle);
return true;
} else {
return false;
}
#else
struct stat dir_stat;
if(::stat(fname.c_str(), &dir_stat) == -1) {
return false;
}
return S_ISDIR(dir_stat.st_mode);
#endif
}
bool is_directory(const std::string& fname)
{
if(fname.empty()) {
return false;
}
if(fname[0] != '/' && !game_config::path.empty()) {
if(is_directory_internal(game_config::path + "/" + fname))
return true;
}
return is_directory_internal(fname);
}
bool file_exists(const std::string& name)
{
#ifdef _WIN32
struct stat st;
return (::stat(name.c_str(), &st) == 0);
#else
struct stat st;
return (::stat(name.c_str(), &st) != -1);
#endif
}
time_t file_modified_time(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return 0;
return buf.st_mtime;
}
/**
* Returns true if the file ends with '.gz'.
*
* @param filename The name to test.
*/
bool is_gzip_file(const std::string& filename)
{
return (filename.length() > 3
&& filename.substr(filename.length() - 3) == ".gz");
}
/**
* Returns true if the file ends with '.bz2'.
*
* @param filename The name to test.
*/
bool is_bzip2_file(const std::string& filename)
{
return (filename.length() > 4
&& filename.substr(filename.length() - 4) == ".bz2");
}
int file_size(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return -1;
return buf.st_size;
}
int dir_size(const std::string& path)
{
std::vector<std::string> files, dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH);
int res = 0;
BOOST_FOREACH(const std::string& file_path, files)
{
res += file_size(file_path);
}
BOOST_FOREACH(const std::string& dir_path, dirs)
{
// FIXME: this could result in infinite recursion with symlinks!!
res += dir_size(dir_path);
}
return res;
}
std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return file;
if(pos >= file.size()-1)
return "";
return file.substr(pos+1);
}
std::string directory_name(const std::string& file)
// Analogous to POSIX dirname(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return "";
return file.substr(0,pos+1);
}
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'" << std::endl;
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths" << std::endl;
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
// Some parts of Wesnoth enjoy putting ".." inside filenames. This is
// bad and should be fixed. But in the meantime, deal with them in a dumb way.
std::string::size_type pos = filename.rfind("../");
if (pos != std::string::npos) {
std::string nf = filename.substr(pos + 3);
LOG_FS << "Illegal path '" << filename << "' replaced by '" << nf << "'" << std::endl;
return get_binary_file_location(type, nf);
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if(file_exists(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")" << std::endl;
return std::string();
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'" << std::endl;
if (is_directory(file)) {
DBG_FS << " found at '" << file << "'" << std::endl;
return file;
}
}
DBG_FS << " not found" << std::endl;
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
if (ends_with(filename, ".pbl")) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
}
std::string get_short_wml_path(const std::string &filename)
{
std::string match = get_user_data_dir() + "/data/";
if (filename.find(match) == 0) {
return "~" + filename.substr(match.size());
}
match = game_config::path + "/data/";
if (filename.find(match) == 0) {
return filename.substr(match.size());
}
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
std::string full_path = get_binary_file_location("images", filename);
if(!full_path.empty()) {
std::string match = get_user_data_dir() + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
match = game_config::path + "/";
if(full_path.find(match) == 0) {
return full_path.substr(match.size());
}
}
return full_path;
}
std::string get_program_invocation(const std::string& program_name) {
#ifdef DEBUG
#ifdef _WIN32
const char *program_suffix = "-debug.exe";
#else
const char *program_suffix = "-debug";
#endif
#else
#ifdef _WIN32
const char *program_suffix = ".exe";
#else
const char *program_suffix = "";
#endif
#endif
const std::string real_program_name(program_name + program_suffix);
if(game_config::wesnoth_program_dir.empty()) return real_program_name;
#ifdef _WIN32
return game_config::wesnoth_program_dir + "\\" + real_program_name;
#else
return game_config::wesnoth_program_dir + "/" + real_program_name;
#endif
}
bool is_path_sep(char c)
{
#ifdef _WIN32
if (c == '/' || c == '\\') return true;
#else
if (c == '/') return true;
#endif
return false;
}
std::string normalize_path(const std::string &p1)
{
if (p1.empty()) return p1;
std::string p2;
#ifdef _WIN32
if (p1.size() >= 2 && p1[1] == ':')
// Windows relative paths with explicit drive name are not handled.
p2 = p1;
else
#endif
if (!is_path_sep(p1[0]))
p2 = get_cwd() + "/" + p1;
else
p2 = p1;
#ifdef _WIN32
std::string drive;
if (p2.size() >= 2 && p2[1] == ':') {
drive = p2.substr(0, 2);
p2.erase(0, 2);
}
#endif
std::vector<std::string> components(1);
for (int i = 0, i_end = p2.size(); i <= i_end; ++i)
{
std::string &last = components[components.size() - 1];
char c = p2.c_str()[i];
if (is_path_sep(c) || c == 0)
{
if (last == ".")
last.clear();
else if (last == "..")
{
if (components.size() >= 2) {
components.pop_back();
components[components.size() - 1].clear();
} else
last.clear();
}
else if (!last.empty())
components.push_back(std::string());
}
else
last += c;
}
std::ostringstream p4;
components.pop_back();
#ifdef _WIN32
p4 << drive;
#endif
BOOST_FOREACH(const std::string &s, components)
{
p4 << '/' << s;
}
DBG_FS << "Normalizing '" << p2 << "' to '" << p4.str() << "'" << std::endl;
return p4.str();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1650_2 |
crossvul-cpp_data_bad_1811_1 | /****************************************************************************
** libmatroska : parse Matroska files, see http://www.matroska.org/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id: KaxBlock.cpp 1265 2007-01-14 17:20:35Z mosu $
\author Steve Lhomme <robux4 @ users.sf.net>
\author Julien Coloos <suiryc @ users.sf.net>
\author Moritz Bunkus <moritz@bunkus.org>
*/
#include <cassert>
//#include <streams.h>
#include "ebml/MemReadIOCallback.h"
#include "ebml/SafeReadIOCallback.h"
#include "matroska/KaxBlock.h"
#include "matroska/KaxContexts.h"
#include "matroska/KaxBlockData.h"
#include "matroska/KaxCluster.h"
#include "matroska/KaxDefines.h"
START_LIBMATROSKA_NAMESPACE
DataBuffer * DataBuffer::Clone()
{
binary *ClonedData = (binary *)malloc(mySize * sizeof(binary));
assert(ClonedData != NULL);
memcpy(ClonedData, myBuffer ,mySize );
SimpleDataBuffer * result = new SimpleDataBuffer(ClonedData, mySize, 0);
result->bValidValue = bValidValue;
return result;
}
SimpleDataBuffer::SimpleDataBuffer(const SimpleDataBuffer & ToClone)
:DataBuffer((binary *)malloc(ToClone.mySize * sizeof(binary)), ToClone.mySize, myFreeBuffer)
{
assert(myBuffer != NULL);
memcpy(myBuffer, ToClone.myBuffer ,mySize );
bValidValue = ToClone.bValidValue;
}
bool KaxInternalBlock::ValidateSize() const
{
return (GetSize() >= 4); /// for the moment
}
KaxInternalBlock::~KaxInternalBlock()
{
ReleaseFrames();
}
KaxInternalBlock::KaxInternalBlock(const KaxInternalBlock & ElementToClone)
:EbmlBinary(ElementToClone)
,myBuffers(ElementToClone.myBuffers.size())
,Timecode(ElementToClone.Timecode)
,LocalTimecode(ElementToClone.LocalTimecode)
,bLocalTimecodeUsed(ElementToClone.bLocalTimecodeUsed)
,TrackNumber(ElementToClone.TrackNumber)
,ParentCluster(ElementToClone.ParentCluster) ///< \todo not exactly
{
// add a clone of the list
std::vector<DataBuffer *>::const_iterator Itr = ElementToClone.myBuffers.begin();
std::vector<DataBuffer *>::iterator myItr = myBuffers.begin();
while (Itr != ElementToClone.myBuffers.end()) {
*myItr = (*Itr)->Clone();
++Itr; ++myItr;
}
}
KaxBlockGroup::~KaxBlockGroup()
{
//NOTE("KaxBlockGroup::~KaxBlockGroup");
}
KaxBlockGroup::KaxBlockGroup(EBML_EXTRA_DEF)
:EbmlMaster(EBML_CLASS_SEMCONTEXT(KaxBlockGroup) EBML_DEF_SEP EBML_EXTRA_CALL)
,ParentCluster(NULL)
,ParentTrack(NULL)
{}
/*!
\todo handle flags
\todo hardcoded limit of the number of frames in a lace should be a parameter
\return true if more frames can be added to this Block
*/
bool KaxInternalBlock::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing, bool invisible)
{
SetValueIsSet();
if (myBuffers.size() == 0) {
// first frame
Timecode = timecode;
TrackNumber = track.TrackNumber();
mInvisible = invisible;
mLacing = lacing;
}
myBuffers.push_back(&buffer);
// we don't allow more than 8 frames in a Block because the overhead improvement is minimal
if (myBuffers.size() >= 8 || lacing == LACING_NONE)
return false;
if (lacing == LACING_XIPH)
// decide wether a new frame can be added or not
// a frame in a lace is not efficient when the place necessary to code it in a lace is bigger
// than the size of a simple Block. That means more than 6 bytes (4 in struct + 2 for EBML) to code the size
return (buffer.Size() < 6*0xFF);
else
return true;
}
/*!
\return Returns the lacing type that produces the smallest footprint.
*/
LacingType KaxInternalBlock::GetBestLacingType() const {
int XiphLacingSize, EbmlLacingSize, i;
bool SameSize = true;
if (myBuffers.size() <= 1)
return LACING_NONE;
XiphLacingSize = 1; // Number of laces is stored in 1 byte.
EbmlLacingSize = 1;
for (i = 0; i < (int)myBuffers.size() - 1; i++) {
if (myBuffers[i]->Size() != myBuffers[i + 1]->Size())
SameSize = false;
XiphLacingSize += myBuffers[i]->Size() / 255 + 1;
}
EbmlLacingSize += CodedSizeLength(myBuffers[0]->Size(), 0, IsFiniteSize());
for (i = 1; i < (int)myBuffers.size() - 1; i++)
EbmlLacingSize += CodedSizeLengthSigned(int64(myBuffers[i]->Size()) - int64(myBuffers[i - 1]->Size()), 0);
if (SameSize)
return LACING_FIXED;
else if (XiphLacingSize < EbmlLacingSize)
return LACING_XIPH;
else
return LACING_EBML;
}
filepos_t KaxInternalBlock::UpdateSize(bool /* bSaveDefault */, bool /* bForceRender */)
{
LacingType LacingHere;
assert(EbmlBinary::GetBuffer() == NULL); // Data is not used for KaxInternalBlock
assert(TrackNumber < 0x4000); // no more allowed for the moment
unsigned int i;
// compute the final size of the data
switch (myBuffers.size()) {
case 0:
SetSize_(0);
break;
case 1:
SetSize_(4 + myBuffers[0]->Size());
break;
default:
SetSize_(4 + 1); // 1 for the lacing head
if (mLacing == LACING_AUTO)
LacingHere = GetBestLacingType();
else
LacingHere = mLacing;
switch (LacingHere) {
case LACING_XIPH:
for (i=0; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size() + (myBuffers[i]->Size() / 0xFF + 1));
}
break;
case LACING_EBML:
SetSize_(GetSize() + myBuffers[0]->Size() + CodedSizeLength(myBuffers[0]->Size(), 0, IsFiniteSize()));
for (i=1; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size() + CodedSizeLengthSigned(int64(myBuffers[i]->Size()) - int64(myBuffers[i-1]->Size()), 0));
}
break;
case LACING_FIXED:
for (i=0; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size());
}
break;
default:
i = 0;
assert(0);
}
// Size of the last frame (not in lace)
SetSize_(GetSize() + myBuffers[i]->Size());
break;
}
if (TrackNumber >= 0x80)
SetSize_(GetSize() + 1); // the size will be coded with one more octet
return GetSize();
}
#if MATROSKA_VERSION >= 2
KaxBlockVirtual::KaxBlockVirtual(const KaxBlockVirtual & ElementToClone)
:EbmlBinary(ElementToClone)
,Timecode(ElementToClone.Timecode)
,TrackNumber(ElementToClone.TrackNumber)
,ParentCluster(ElementToClone.ParentCluster) ///< \todo not exactly
{
SetBuffer(DataBlock,sizeof(DataBlock));
SetValueIsSet(false);
}
KaxBlockVirtual::KaxBlockVirtual(EBML_EXTRA_DEF)
:EBML_DEF_BINARY(KaxBlockVirtual)EBML_DEF_SEP ParentCluster(NULL)
{
SetBuffer(DataBlock,sizeof(DataBlock));
SetValueIsSet(false);
}
KaxBlockVirtual::~KaxBlockVirtual()
{
if(GetBuffer() == DataBlock)
SetBuffer( NULL, 0 );
}
filepos_t KaxBlockVirtual::UpdateSize(bool /* bSaveDefault */, bool /* bForceRender */)
{
assert(TrackNumber < 0x4000);
binary *cursor = EbmlBinary::GetBuffer();
// fill data
if (TrackNumber < 0x80) {
assert(GetSize() >= 4);
*cursor++ = TrackNumber | 0x80; // set the first bit to 1
} else {
assert(GetSize() >= 5);
*cursor++ = (TrackNumber >> 8) | 0x40; // set the second bit to 1
*cursor++ = TrackNumber & 0xFF;
}
assert(ParentCluster != NULL);
int16 ActualTimecode = ParentCluster->GetBlockLocalTimecode(Timecode);
big_int16 b16(ActualTimecode);
b16.Fill(cursor);
cursor += 2;
*cursor++ = 0; // flags
return GetSize();
}
#endif // MATROSKA_VERSION
/*!
\todo more optimisation is possible (render the Block head and don't copy the buffer in memory, care should be taken with the allocation of Data)
\todo the actual timecode to write should be retrieved from the Cluster from here
*/
filepos_t KaxInternalBlock::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bSaveDefault */)
{
if (myBuffers.size() == 0) {
return 0;
} else {
assert(TrackNumber < 0x4000);
binary BlockHead[5], *cursor = BlockHead;
unsigned int i;
if (myBuffers.size() == 1) {
SetSize_(4);
mLacing = LACING_NONE;
} else {
if (mLacing == LACING_NONE)
mLacing = LACING_EBML; // supposedly the best of all
SetSize_(4 + 1); // 1 for the lacing head (number of laced elements)
}
if (TrackNumber > 0x80)
SetSize_(GetSize() + 1);
// write Block Head
if (TrackNumber < 0x80) {
*cursor++ = TrackNumber | 0x80; // set the first bit to 1
} else {
*cursor++ = (TrackNumber >> 8) | 0x40; // set the second bit to 1
*cursor++ = TrackNumber & 0xFF;
}
assert(ParentCluster != NULL);
int16 ActualTimecode = ParentCluster->GetBlockLocalTimecode(Timecode);
big_int16 b16(ActualTimecode);
b16.Fill(cursor);
cursor += 2;
*cursor = 0; // flags
if (mLacing == LACING_AUTO) {
mLacing = GetBestLacingType();
}
// invisible flag
if (mInvisible)
*cursor = 0x08;
if (bIsSimple) {
if (bIsKeyframe)
*cursor |= 0x80;
if (bIsDiscardable)
*cursor |= 0x01;
}
// lacing flag
switch (mLacing) {
case LACING_XIPH:
*cursor++ |= 0x02;
break;
case LACING_EBML:
*cursor++ |= 0x06;
break;
case LACING_FIXED:
*cursor++ |= 0x04;
break;
case LACING_NONE:
break;
default:
assert(0);
}
output.writeFully(BlockHead, 4 + ((TrackNumber > 0x80) ? 1 : 0));
binary tmpValue;
switch (mLacing) {
case LACING_XIPH:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
// set the size of each member in the lace
for (i=0; i<myBuffers.size()-1; i++) {
tmpValue = 0xFF;
uint16 tmpSize = myBuffers[i]->Size();
while (tmpSize >= 0xFF) {
output.writeFully(&tmpValue, 1);
SetSize_(GetSize() + 1);
tmpSize -= 0xFF;
}
tmpValue = binary(tmpSize);
output.writeFully(&tmpValue, 1);
SetSize_(GetSize() + 1);
}
break;
case LACING_EBML:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
{
int64 _Size;
int _CodedSize;
binary _FinalHead[8]; // 64 bits max coded size
_Size = myBuffers[0]->Size();
_CodedSize = CodedSizeLength(_Size, 0, IsFiniteSize());
// first size in the lace is not a signed
CodedValueLength(_Size, _CodedSize, _FinalHead);
output.writeFully(_FinalHead, _CodedSize);
SetSize_(GetSize() + _CodedSize);
// set the size of each member in the lace
for (i=1; i<myBuffers.size()-1; i++) {
_Size = int64(myBuffers[i]->Size()) - int64(myBuffers[i-1]->Size());
_CodedSize = CodedSizeLengthSigned(_Size, 0);
CodedValueLengthSigned(_Size, _CodedSize, _FinalHead);
output.writeFully(_FinalHead, _CodedSize);
SetSize_(GetSize() + _CodedSize);
}
}
break;
case LACING_FIXED:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
break;
case LACING_NONE:
break;
default:
assert(0);
}
// put the data of each frame
for (i=0; i<myBuffers.size(); i++) {
output.writeFully(myBuffers[i]->Buffer(), myBuffers[i]->Size());
SetSize_(GetSize() + myBuffers[i]->Size());
}
}
return GetSize();
}
uint64 KaxInternalBlock::ReadInternalHead(IOCallback & input)
{
binary Buffer[5], *cursor = Buffer;
uint64 Result = input.read(cursor, 4);
if (Result != 4)
return Result;
// update internal values
TrackNumber = *cursor++;
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
return Result;
}
Result += input.read(&Buffer[4], 1);
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += *cursor++;
} else {
TrackNumber &= 0x7F;
}
big_int16 b16;
b16.Eval(cursor);
assert(ParentCluster != NULL);
Timecode = ParentCluster->GetBlockGlobalTimecode(int16(b16));
bLocalTimecodeUsed = false;
cursor += 2;
return Result;
}
/*!
\todo better zero copy handling
*/
filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)
{
filepos_t Result;
FirstFrameLocation = input.getFilePointer(); // will be updated accordingly below
SetValueIsSet(false);
try {
if (ReadFully == SCOPE_ALL_DATA) {
Result = EbmlBinary::ReadData(input, ReadFully);
if (Result != GetSize())
throw SafeReadIOCallback::EndOfStreamX(GetSize() - Result);
binary *BufferStart = EbmlBinary::GetBuffer();
SafeReadIOCallback Mem(*this);
uint8 BlockHeadSize = 4;
// update internal values
TrackNumber = Mem.GetUInt8();
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
throw SafeReadIOCallback::EndOfStreamX(0);
}
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += Mem.GetUInt8();
BlockHeadSize++;
} else {
TrackNumber &= 0x7F;
}
LocalTimecode = int16(Mem.GetUInt16BE());
bLocalTimecodeUsed = true;
uint8 Flags = Mem.GetUInt8();
if (EbmlId(*this) == EBML_ID(KaxSimpleBlock)) {
bIsKeyframe = (Flags & 0x80) != 0;
bIsDiscardable = (Flags & 0x01) != 0;
}
mInvisible = (Flags & 0x08) >> 3;
mLacing = LacingType((Flags & 0x06) >> 1);
// put all Frames in the list
if (mLacing == LACING_NONE) {
FirstFrameLocation += Mem.GetPosition();
DataBuffer * soloFrame = new DataBuffer(BufferStart + Mem.GetPosition(), GetSize() - BlockHeadSize);
myBuffers.push_back(soloFrame);
SizeList.resize(1);
SizeList[0] = GetSize() - BlockHeadSize;
} else {
// read the number of frames in the lace
uint32 LastBufferSize = GetSize() - BlockHeadSize - 1; // 1 for number of frame
uint8 FrameNum = Mem.GetUInt8(); // number of frames in the lace - 1
// read the list of frame sizes
uint8 Index;
int32 FrameSize;
uint32 SizeRead;
uint64 SizeUnknown;
SizeList.resize(FrameNum + 1);
switch (mLacing) {
case LACING_XIPH:
for (Index=0; Index<FrameNum; Index++) {
// get the size of the frame
FrameSize = 0;
uint8 Value;
do {
Value = Mem.GetUInt8();
FrameSize += Value;
LastBufferSize--;
} while (Value == 0xFF);
SizeList[Index] = FrameSize;
LastBufferSize -= FrameSize;
}
SizeList[Index] = LastBufferSize;
break;
case LACING_EBML:
SizeRead = LastBufferSize;
FrameSize = ReadCodedSizeValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);
SizeList[0] = FrameSize;
Mem.Skip(SizeRead);
LastBufferSize -= FrameSize + SizeRead;
for (Index=1; Index<FrameNum; Index++) {
// get the size of the frame
SizeRead = LastBufferSize;
FrameSize += ReadCodedSizeSignedValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);
SizeList[Index] = FrameSize;
Mem.Skip(SizeRead);
LastBufferSize -= FrameSize + SizeRead;
}
if (Index <= FrameNum) // Safety check if FrameNum == 0
SizeList[Index] = LastBufferSize;
break;
case LACING_FIXED:
for (Index=0; Index<=FrameNum; Index++) {
// get the size of the frame
SizeList[Index] = LastBufferSize / (FrameNum + 1);
}
break;
default: // other lacing not supported
assert(0);
}
FirstFrameLocation += Mem.GetPosition();
for (Index=0; Index<=FrameNum; Index++) {
DataBuffer * lacedFrame = new DataBuffer(BufferStart + Mem.GetPosition(), SizeList[Index]);
myBuffers.push_back(lacedFrame);
Mem.Skip(SizeList[Index]);
}
}
binary *BufferEnd = BufferStart + GetSize();
size_t NumFrames = myBuffers.size();
// Sanity checks for frame pointers and boundaries.
for (size_t Index = 0; Index < NumFrames; ++Index) {
binary *FrameStart = myBuffers[Index]->Buffer();
binary *FrameEnd = FrameStart + myBuffers[Index]->Size();
binary *ExpectedEnd = (Index + 1) < NumFrames ? myBuffers[Index + 1]->Buffer() : BufferEnd;
if ((FrameStart < BufferStart) || (FrameEnd > BufferEnd) || (FrameEnd != ExpectedEnd))
throw SafeReadIOCallback::EndOfStreamX(0);
}
SetValueIsSet();
} else if (ReadFully == SCOPE_PARTIAL_DATA) {
binary _TempHead[5];
Result = input.read(_TempHead, 5);
if (Result != 5)
throw SafeReadIOCallback::EndOfStreamX(0);
binary *cursor = _TempHead;
binary *_tmpBuf;
uint8 BlockHeadSize = 4;
// update internal values
TrackNumber = *cursor++;
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
return Result;
}
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += *cursor++;
BlockHeadSize++;
} else {
TrackNumber &= 0x7F;
}
big_int16 b16;
b16.Eval(cursor);
LocalTimecode = int16(b16);
bLocalTimecodeUsed = true;
cursor += 2;
if (EbmlId(*this) == EBML_ID(KaxSimpleBlock)) {
bIsKeyframe = (*cursor & 0x80) != 0;
bIsDiscardable = (*cursor & 0x01) != 0;
}
mInvisible = (*cursor & 0x08) >> 3;
mLacing = LacingType((*cursor++ & 0x06) >> 1);
if (cursor == &_TempHead[4]) {
_TempHead[0] = _TempHead[4];
} else {
Result += input.read(_TempHead, 1);
}
FirstFrameLocation += cursor - _TempHead;
// put all Frames in the list
if (mLacing != LACING_NONE) {
// read the number of frames in the lace
uint32 LastBufferSize = GetSize() - BlockHeadSize - 1; // 1 for number of frame
uint8 FrameNum = _TempHead[0]; // number of frames in the lace - 1
// read the list of frame sizes
uint8 Index;
int32 FrameSize;
uint32 SizeRead;
uint64 SizeUnknown;
SizeList.resize(FrameNum + 1);
switch (mLacing) {
case LACING_XIPH:
for (Index=0; Index<FrameNum; Index++) {
// get the size of the frame
FrameSize = 0;
do {
Result += input.read(_TempHead, 1);
FrameSize += uint8(_TempHead[0]);
LastBufferSize--;
FirstFrameLocation++;
} while (_TempHead[0] == 0xFF);
FirstFrameLocation++;
SizeList[Index] = FrameSize;
LastBufferSize -= FrameSize;
}
SizeList[Index] = LastBufferSize;
break;
case LACING_EBML:
SizeRead = LastBufferSize;
cursor = _tmpBuf = new binary[FrameNum*4]; /// \warning assume the mean size will be coded in less than 4 bytes
Result += input.read(cursor, FrameNum*4);
FrameSize = ReadCodedSizeValue(cursor, SizeRead, SizeUnknown);
SizeList[0] = FrameSize;
cursor += SizeRead;
LastBufferSize -= FrameSize + SizeRead;
for (Index=1; Index<FrameNum; Index++) {
// get the size of the frame
SizeRead = LastBufferSize;
FrameSize += ReadCodedSizeSignedValue(cursor, SizeRead, SizeUnknown);
SizeList[Index] = FrameSize;
cursor += SizeRead;
LastBufferSize -= FrameSize + SizeRead;
}
FirstFrameLocation += cursor - _tmpBuf;
SizeList[Index] = LastBufferSize;
delete [] _tmpBuf;
break;
case LACING_FIXED:
for (Index=0; Index<=FrameNum; Index++) {
// get the size of the frame
SizeList[Index] = LastBufferSize / (FrameNum + 1);
}
break;
default: // other lacing not supported
assert(0);
}
} else {
SizeList.resize(1);
SizeList[0] = GetSize() - BlockHeadSize;
}
SetValueIsSet(false);
Result = GetSize();
} else {
SetValueIsSet(false);
Result = GetSize();
}
} catch (SafeReadIOCallback::EndOfStreamX &) {
SetValueIsSet(false);
std::memset(EbmlBinary::GetBuffer(), 0, GetSize());
myBuffers.clear();
SizeList.clear();
Timecode = 0;
LocalTimecode = 0;
TrackNumber = 0;
bLocalTimecodeUsed = false;
FirstFrameLocation = 0;
return 0;
}
return Result;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing)
{
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
return theBlock.AddFrame(track, timecode, buffer, lacing);
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockGroup & PastBlock, LacingType lacing)
{
// assert(past_timecode < 0);
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
return bRes;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockGroup & PastBlock, const KaxBlockGroup & ForwBlock, LacingType lacing)
{
// assert(past_timecode < 0);
// assert(forw_timecode > 0);
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
KaxReferenceBlock & theFutureRef = AddNewChild<KaxReferenceBlock>(*this);
theFutureRef.SetReferencedBlock(ForwBlock);
theFutureRef.SetParentBlock(*this);
return bRes;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockBlob * PastBlock, const KaxBlockBlob * ForwBlock, LacingType lacing)
{
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
if (PastBlock != NULL) {
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
}
if (ForwBlock != NULL) {
KaxReferenceBlock & theFutureRef = AddNewChild<KaxReferenceBlock>(*this);
theFutureRef.SetReferencedBlock(ForwBlock);
theFutureRef.SetParentBlock(*this);
}
return bRes;
}
/*!
\todo we may cache the reference to the timecode block
*/
uint64 KaxBlockGroup::GlobalTimecode() const
{
assert(ParentCluster != NULL); // impossible otherwise
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
return MyBlock.GlobalTimecode();
}
uint16 KaxBlockGroup::TrackNumber() const
{
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
return MyBlock.TrackNum();
}
uint64 KaxBlockGroup::ClusterPosition() const
{
assert(ParentCluster != NULL); // impossible otherwise
return ParentCluster->GetPosition();
}
uint64 KaxInternalBlock::ClusterPosition() const
{
assert(ParentCluster != NULL); // impossible otherwise
return ParentCluster->GetPosition();
}
unsigned int KaxBlockGroup::ReferenceCount() const
{
unsigned int Result = 0;
KaxReferenceBlock * MyBlockAdds = static_cast<KaxReferenceBlock *>(FindFirstElt(EBML_INFO(KaxReferenceBlock)));
if (MyBlockAdds != NULL) {
Result++;
while ((MyBlockAdds = static_cast<KaxReferenceBlock *>(FindNextElt(*MyBlockAdds))) != NULL) {
Result++;
}
}
return Result;
}
const KaxReferenceBlock & KaxBlockGroup::Reference(unsigned int Index) const
{
KaxReferenceBlock * MyBlockAdds = static_cast<KaxReferenceBlock *>(FindFirstElt(EBML_INFO(KaxReferenceBlock)));
assert(MyBlockAdds != NULL); // call of a non existing reference
while (Index != 0) {
MyBlockAdds = static_cast<KaxReferenceBlock *>(FindNextElt(*MyBlockAdds));
assert(MyBlockAdds != NULL);
Index--;
}
return *MyBlockAdds;
}
void KaxBlockGroup::ReleaseFrames()
{
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
MyBlock.ReleaseFrames();
}
void KaxInternalBlock::ReleaseFrames()
{
// free the allocated Frames
int i;
for (i=myBuffers.size()-1; i>=0; i--) {
if (myBuffers[i] != NULL) {
myBuffers[i]->FreeBuffer(*myBuffers[i]);
delete myBuffers[i];
myBuffers[i] = NULL;
}
}
}
void KaxBlockGroup::SetBlockDuration(uint64 TimeLength)
{
assert(ParentTrack != NULL);
int64 scale = ParentTrack->GlobalTimecodeScale();
KaxBlockDuration & myDuration = *static_cast<KaxBlockDuration *>(FindFirstElt(EBML_INFO(KaxBlockDuration), true));
*(static_cast<EbmlUInteger *>(&myDuration)) = TimeLength / uint64(scale);
}
bool KaxBlockGroup::GetBlockDuration(uint64 &TheTimecode) const
{
KaxBlockDuration * myDuration = static_cast<KaxBlockDuration *>(FindElt(EBML_INFO(KaxBlockDuration)));
if (myDuration == NULL) {
return false;
}
assert(ParentTrack != NULL);
TheTimecode = uint64(*myDuration) * ParentTrack->GlobalTimecodeScale();
return true;
}
KaxBlockGroup::operator KaxInternalBlock &() {
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
return theBlock;
}
void KaxBlockGroup::SetParent(KaxCluster & aParentCluster) {
ParentCluster = &aParentCluster;
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
theBlock.SetParent( aParentCluster );
}
void KaxSimpleBlock::SetParent(KaxCluster & aParentCluster) {
KaxInternalBlock::SetParent( aParentCluster );
}
void KaxInternalBlock::SetParent(KaxCluster & aParentCluster)
{
ParentCluster = &aParentCluster;
if (bLocalTimecodeUsed) {
Timecode = aParentCluster.GetBlockGlobalTimecode(LocalTimecode);
bLocalTimecodeUsed = false;
}
}
int64 KaxInternalBlock::GetDataPosition(size_t FrameNumber)
{
int64 _Result = -1;
if (ValueIsSet() && FrameNumber < SizeList.size()) {
_Result = FirstFrameLocation;
size_t _Idx = 0;
while(FrameNumber--) {
_Result += SizeList[_Idx++];
}
}
return _Result;
}
int64 KaxInternalBlock::GetFrameSize(size_t FrameNumber)
{
int64 _Result = -1;
if (/*bValueIsSet &&*/ FrameNumber < SizeList.size()) {
_Result = SizeList[FrameNumber];
}
return _Result;
}
KaxBlockBlob::operator KaxBlockGroup &()
{
assert(!bUseSimpleBlock);
assert(Block.group);
return *Block.group;
}
KaxBlockBlob::operator const KaxBlockGroup &() const
{
assert(!bUseSimpleBlock);
assert(Block.group);
return *Block.group;
}
KaxBlockBlob::operator KaxInternalBlock &()
{
assert(Block.group);
#if MATROSKA_VERSION >= 2
if (bUseSimpleBlock)
return *Block.simpleblock;
else
#endif
return *Block.group;
}
KaxBlockBlob::operator const KaxInternalBlock &() const
{
assert(Block.group);
#if MATROSKA_VERSION >= 2
if (bUseSimpleBlock)
return *Block.simpleblock;
else
#endif
return *Block.group;
}
#if MATROSKA_VERSION >= 2
KaxBlockBlob::operator KaxSimpleBlock &()
{
assert(bUseSimpleBlock);
assert(Block.simpleblock);
return *Block.simpleblock;
}
#endif
bool KaxBlockBlob::AddFrameAuto(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing, const KaxBlockBlob * PastBlock, const KaxBlockBlob * ForwBlock)
{
bool bResult = false;
#if MATROSKA_VERSION >= 2
if ((SimpleBlockMode == BLOCK_BLOB_ALWAYS_SIMPLE) || (SimpleBlockMode == BLOCK_BLOB_SIMPLE_AUTO && PastBlock == NULL && ForwBlock == NULL)) {
assert(bUseSimpleBlock == true);
if (Block.simpleblock == NULL) {
Block.simpleblock = new KaxSimpleBlock();
Block.simpleblock->SetParent(*ParentCluster);
}
bResult = Block.simpleblock->AddFrame(track, timecode, buffer, lacing);
if (PastBlock == NULL && ForwBlock == NULL) {
Block.simpleblock->SetKeyframe(true);
Block.simpleblock->SetDiscardable(false);
} else {
Block.simpleblock->SetKeyframe(false);
if ((ForwBlock == NULL || ((const KaxInternalBlock &)*ForwBlock).GlobalTimecode() <= timecode) &&
(PastBlock == NULL || ((const KaxInternalBlock &)*PastBlock).GlobalTimecode() <= timecode))
Block.simpleblock->SetDiscardable(false);
else
Block.simpleblock->SetDiscardable(true);
}
}
else
#endif
if (ReplaceSimpleByGroup())
bResult = Block.group->AddFrame(track, timecode, buffer, PastBlock, ForwBlock, lacing);
return bResult;
}
void KaxBlockBlob::SetParent(KaxCluster & parent_clust)
{
ParentCluster = &parent_clust;
}
void KaxBlockBlob::SetBlockDuration(uint64 TimeLength)
{
if (ReplaceSimpleByGroup())
Block.group->SetBlockDuration(TimeLength);
}
bool KaxBlockBlob::ReplaceSimpleByGroup()
{
if (SimpleBlockMode== BLOCK_BLOB_ALWAYS_SIMPLE)
return false;
if (!bUseSimpleBlock) {
if (Block.group == NULL) {
Block.group = new KaxBlockGroup();
}
}
#if MATROSKA_VERSION >= 2
else {
if (Block.simpleblock != NULL) {
KaxSimpleBlock *old_simpleblock = Block.simpleblock;
Block.group = new KaxBlockGroup();
// _TODO_ : move all the data to the blockgroup
assert(false);
// -> while(frame) AddFrame(myBuffer)
delete old_simpleblock;
} else {
Block.group = new KaxBlockGroup();
}
}
#endif
if (ParentCluster != NULL)
Block.group->SetParent(*ParentCluster);
bUseSimpleBlock = false;
return true;
}
void KaxBlockBlob::SetBlockGroup( KaxBlockGroup &BlockRef )
{
assert(!bUseSimpleBlock);
Block.group = &BlockRef;
}
filepos_t KaxBlockVirtual::ReadData(IOCallback & input, ScopeMode /* ReadFully */)
{
input.setFilePointer(SizePosition + CodedSizeLength(Size, SizeLength, bSizeIsFinite) + Size, seek_beginning);
return GetSize();
}
END_LIBMATROSKA_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1811_1 |
crossvul-cpp_data_bad_1649_2 | /* $Id$ */
/*
Copyright (C) 2003 - 2012 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
#include "filesystem.hpp"
#include "serialization/unicode.hpp"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/system/windows_error.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <set>
using boost::uintmax_t;
#ifdef _WIN32
#include <boost/locale.hpp>
#include <windows.h>
#endif /* !_WIN32 */
#include "config.hpp"
#include "game_config.hpp"
#include "log.hpp"
#include "util.hpp"
#include "version.hpp"
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace bfs = boost::filesystem;
using boost::filesystem::path;
using boost::system::error_code;
namespace {
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
namespace {
//only used by windows but put outside the ifdef to let it check by ci build.
class customcodecvt : public std::codecvt<wchar_t /*intern*/, char /*extern*/, std::mbstate_t>
{
private:
//private static helper things
template<typename char_t_to>
struct customcodecvt_do_conversion_writer
{
customcodecvt_do_conversion_writer(char_t_to*& _to_next, char_t_to* _to_end) :
to_next(_to_next),
to_end(_to_end)
{}
char_t_to*& to_next;
char_t_to* to_end;
bool can_push(size_t count)
{
return static_cast<size_t>(to_end - to_next) > count;
}
void push(char_t_to val)
{
assert(to_next != to_end);
*to_next++ = val;
}
};
template<typename char_t_from , typename char_t_to>
static void customcodecvt_do_conversion( std::mbstate_t& /*state*/,
const char_t_from* from,
const char_t_from* from_end,
const char_t_from*& from_next,
char_t_to* to,
char_t_to* to_end,
char_t_to*& to_next )
{
typedef typename ucs4_convert_impl::convert_impl<char_t_from>::type impl_type_from;
typedef typename ucs4_convert_impl::convert_impl<char_t_to>::type impl_type_to;
from_next = from;
to_next = to;
customcodecvt_do_conversion_writer<char_t_to> writer(to_next, to_end);
while(from_next != from_end)
{
impl_type_to::write(writer, impl_type_from::read(from_next, from_end));
}
}
public:
//Not used by boost filesystem
int do_encoding() const throw() { return 0; }
//Not used by boost filesystem
bool do_always_noconv() const throw() { return false; }
int do_length( std::mbstate_t& /*state*/,
const char* /*from*/,
const char* /*from_end*/,
std::size_t /*max*/ ) const
{
//Not used by boost filesystem
throw "Not supported";
}
std::codecvt_base::result unshift( std::mbstate_t& /*state*/,
char* /*to*/,
char* /*to_end*/,
char*& /*to_next*/) const
{
//Not used by boost filesystem
throw "Not supported";
}
//there are still some methods which could be implemented but arent because boost filesystem won't use them.
std::codecvt_base::result do_in( std::mbstate_t& state,
const char* from,
const char* from_end,
const char*& from_next,
wchar_t* to,
wchar_t* to_end,
wchar_t*& to_next ) const
{
try
{
customcodecvt_do_conversion<char, wchar_t>(state, from, from_end, from_next, to, to_end, to_next);
}
catch(...)
{
ERR_FS << "Invalid UTF-8 string'" << std::string(from, from_end) << "' " << std::endl;
return std::codecvt_base::error;
}
return std::codecvt_base::ok;
}
std::codecvt_base::result do_out( std::mbstate_t& state,
const wchar_t* from,
const wchar_t* from_end,
const wchar_t*& from_next,
char* to,
char* to_end,
char*& to_next ) const
{
try
{
customcodecvt_do_conversion<wchar_t, char>(state, from, from_end, from_next, to, to_end, to_next);
}
catch(...)
{
ERR_FS << "Invalid UTF-16 string" << std::endl;
return std::codecvt_base::error;
}
return std::codecvt_base::ok;
}
};
#ifdef _WIN32
class static_runner {
public:
static_runner() {
// Boost uses the current locale to generate a UTF-8 one
std::locale utf8_loc = boost::locale::generator().generate("");
// use a custom locale becasue we want to use out log.hpp functions in case of an invalid string.
utf8_loc = std::locale(utf8_loc, new customcodecvt());
boost::filesystem::path::imbue(utf8_loc);
}
};
static static_runner static_bfs_path_imbuer;
#endif
}
namespace filesystem {
static void push_if_exists(std::vector<std::string> *vec, const path &file, bool full) {
if (vec != NULL) {
if (full)
vec->push_back(file.generic_string());
else
vec->push_back(file.filename().generic_string());
}
}
static inline bool error_except_not_found(const error_code &ec)
{
return (ec
&& ec.value() != boost::system::errc::no_such_file_or_directory
#ifdef _WIN32
&& ec.value() != boost::system::windows_error::path_not_found
#endif /*_WIN32*/
);
}
static bool is_directory_internal(const path &fpath)
{
error_code ec;
bool is_dir = bfs::is_directory(fpath, ec);
if (error_except_not_found(ec)) {
LOG_FS << "Failed to check if " << fpath.string() << " is a directory: " << ec.message() << '\n';
}
return is_dir;
}
static bool file_exists(const path &fpath)
{
error_code ec;
bool exists = bfs::exists(fpath, ec);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to check existence of file " << fpath.string() << ": " << ec.message() << '\n';
}
return exists;
}
static path get_dir(const path &dirpath)
{
bool is_dir = is_directory_internal(dirpath);
if (!is_dir) {
error_code ec;
bfs::create_directory(dirpath, ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
}
// This is probably redundant
is_dir = is_directory_internal(dirpath);
}
if (!is_dir) {
ERR_FS << "Could not open or create directory " << dirpath.string() << '\n';
return std::string();
}
return dirpath;
}
static bool create_directory_if_missing(const path &dirpath)
{
error_code ec;
bfs::file_status fs = bfs::status(dirpath, ec);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
return false;
} else if (bfs::is_directory(fs)) {
DBG_FS << "directory " << dirpath.string() << " exists, not creating\n";
return true;
} else if (bfs::exists(fs)) {
ERR_FS << "cannot create directory " << dirpath.string() << "; file exists\n";
return false;
}
bool created = bfs::create_directory(dirpath, ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
}
return created;
}
static bool create_directory_if_missing_recursive(const path& dirpath)
{
DBG_FS << "creating recursive directory: " << dirpath.string() << '\n';
if (dirpath.empty())
return false;
error_code ec;
bfs::file_status fs = bfs::status(dirpath);
if (error_except_not_found(ec)) {
ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
return false;
} else if (bfs::is_directory(fs)) {
return true;
} else if (bfs::exists(fs)) {
return false;
}
if (!dirpath.has_parent_path() || create_directory_if_missing_recursive(dirpath.parent_path())) {
return create_directory_if_missing(dirpath);
} else {
ERR_FS << "Could not create parents to " << dirpath.string() << '\n';
return false;
}
}
void get_files_in_dir(const std::string &dir,
std::vector<std::string>* files,
std::vector<std::string>* dirs,
file_name_option mode,
file_filter_option filter,
file_reorder_option reorder,
file_tree_checksum* checksum) {
if(path(dir).is_relative() && !game_config::path.empty()) {
path absolute_dir(game_config::path);
absolute_dir /= dir;
if(is_directory_internal(absolute_dir)) {
get_files_in_dir(absolute_dir.string(), files, dirs, mode, filter, reorder, checksum);
return;
}
}
const path dirpath(dir);
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << dir << '\n';
const path maincfg = dirpath / maincfg_filename;
if (file_exists(maincfg)) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
push_if_exists(files, maincfg, mode == ENTIRE_FILE_PATH);
return;
}
}
error_code ec;
bfs::directory_iterator di(dirpath, ec);
bfs::directory_iterator end;
if (ec) {
// Probably not a directory, let the caller deal with it.
return;
}
for(; di != end; ++di) {
bfs::file_status st = di->status(ec);
if (ec) {
LOG_FS << "Failed to get file status of " << di->path().string() << ": " << ec.message() << '\n';
continue;
}
if (st.type() == bfs::regular_file) {
{
std::string basename = di->path().filename().string();
if (filter == SKIP_PBL_FILES && looks_like_pbl(basename))
continue;
if(!basename.empty() && basename[0] == '.' )
continue;
}
push_if_exists(files, di->path(), mode == ENTIRE_FILE_PATH);
if (checksum != NULL) {
std::time_t mtime = bfs::last_write_time(di->path(), ec);
if (ec) {
LOG_FS << "Failed to read modification time of " << di->path().string() << ": " << ec.message() << '\n';
} else if (mtime > checksum->modified) {
checksum->modified = mtime;
}
uintmax_t size = bfs::file_size(di->path(), ec);
if (ec) {
LOG_FS << "Failed to read filesize of " << di->path().string() << ": " << ec.message() << '\n';
} else {
checksum->sum_size += size;
}
checksum->nfiles++;
}
} else if (st.type() == bfs::directory_file) {
std::string basename = di->path().filename().string();
if(!basename.empty() && basename[0] == '.' )
continue;
if (filter == SKIP_MEDIA_DIR
&& (basename == "images" || basename == "sounds"))
continue;
const path inner_main(di->path() / maincfg_filename);
bfs::file_status main_st = bfs::status(inner_main, ec);
if (error_except_not_found(ec)) {
LOG_FS << "Failed to get file status of " << inner_main.string() << ": " << ec.message() << '\n';
} else if (reorder == DO_REORDER && main_st.type() == bfs::regular_file) {
LOG_FS << "_main.cfg found : " << (mode == ENTIRE_FILE_PATH ? inner_main.string() : inner_main.filename().string()) << '\n';
push_if_exists(files, inner_main, mode == ENTIRE_FILE_PATH);
} else {
push_if_exists(dirs, di->path(), mode == ENTIRE_FILE_PATH);
}
}
}
if (files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
int foundit = -1;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; i--)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_dir(const std::string &dir)
{
return get_dir(path(dir)).string();
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
static path user_data_dir, user_config_dir, cache_dir;
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
static void setup_user_data_dir()
{
if (!create_directory_if_missing_recursive(user_data_dir)) {
ERR_FS << "could not open or create user data directory at " << user_data_dir.string() << '\n';
return;
}
// TODO: this may not print the error message if the directory exists but we don't have the proper permissions
// Create user data and add-on directories
create_directory_if_missing(user_data_dir / "editor");
create_directory_if_missing(user_data_dir / "editor" / "maps");
create_directory_if_missing(user_data_dir / "editor" / "scenarios");
create_directory_if_missing(user_data_dir / "data");
create_directory_if_missing(user_data_dir / "data" / "add-ons");
create_directory_if_missing(user_data_dir / "saves");
create_directory_if_missing(user_data_dir / "persist");
}
void set_user_data_dir(std::string newprefdir)
{
#ifdef _WIN32
if(newprefdir.empty()) {
user_data_dir = path(get_cwd()) / "userdata";
} else if (newprefdir.size() > 2 && newprefdir[1] == ':') {
//allow absolute path override
user_data_dir = newprefdir;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPWSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPathW;
HMODULE module = LoadLibraryA("shell32");
SHGetSpecialFolderPathW = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathW"));
if(SHGetSpecialFolderPathW) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents\n";
wchar_t my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPathW(NULL, my_documents_path, 5, 1)) {
path mygames_path = path(my_documents_path) / "My Games";
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path / newprefdir;
} else {
WRN_FS << "SHGetSpecialFolderPath failed\n";
user_data_dir = path(get_cwd()) / newprefdir;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function\n";
user_data_dir = path(get_cwd()) / newprefdir;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (newprefdir.empty()) newprefdir = PREFERENCES_DIR;
#endif
std::string backupprefdir = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (newprefdir.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
newprefdir = backupprefdir;
goto other;
}
user_data_dir = home_str;
user_data_dir /= ".local/share";
} else user_data_dir = xdg_data;
user_data_dir /= "wesnoth";
user_data_dir /= get_version_path_suffix();
} else {
other:
path home = home_str ? home_str : ".";
if (newprefdir[0] == '/')
user_data_dir = newprefdir;
else
user_data_dir = home / newprefdir;
}
#else
if (newprefdir.empty()) newprefdir = backupprefdir;
const char* home_str = getenv("HOME");
path home = home_str ? home_str : ".";
if (newprefdir[0] == '/')
user_data_dir = newprefdir;
else
user_data_dir = home / newprefdir;
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
static void set_user_config_path(path newconfig)
{
user_config_dir = newconfig;
if (!create_directory_if_missing_recursive(user_config_dir)) {
ERR_FS << "could not open or create user config directory at " << user_config_dir.string() << '\n';
}
}
void set_user_config_dir(std::string newconfigdir)
{
set_user_config_path(newconfigdir);
}
static const path &get_user_data_path()
{
// TODO:
// This function is called frequently. The file_exists call may slow things down a lot.
if (user_data_dir.empty() || !file_exists(user_data_dir))
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_path();
return user_config_dir.string();
}
user_config_dir = xdg_config;
user_config_dir /= ".config";
} else user_config_dir = xdg_config;
user_config_dir /= "wesnoth";
set_user_config_path(user_config_dir);
#else
user_config_dir = get_user_data_path();
#endif
}
return user_config_dir.string();
}
std::string get_user_data_dir()
{
return get_user_data_path().string();
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_path() / "cache");
return cache_dir.string();
}
cache_dir = xdg_cache;
cache_dir /= ".cache";
} else cache_dir = xdg_cache;
cache_dir /= "wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_path() / "cache");
#endif
}
return cache_dir.string();
}
std::string get_cwd()
{
error_code ec;
path cwd = bfs::current_path(ec);
if (ec) {
ERR_FS << "Failed to get current directory: " << ec.message() << '\n';
return "";
}
return cwd.generic_string();
}
std::string get_exe_dir()
{
#ifndef _WIN32
path self_exe("/proc/self/exe");
error_code ec;
path exe = bfs::read_symlink(self_exe, ec);
if (ec) {
return std::string();
}
return exe.parent_path().string();
#else
return get_cwd();
#endif
}
bool make_directory(const std::string& dirname)
{
error_code ec;
bool created = bfs::create_directory(path(dirname), ec);
if (ec) {
ERR_FS << "Failed to create directory " << dirname << ": " << ec.message() << '\n';
}
return created;
}
bool delete_directory(const std::string& dirname, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
error_code ec;
get_files_in_dir(dirname, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
bfs::remove(path(*i), ec);
if (ec) {
LOG_FS << "remove(" << (*i) << "): " << ec.message() << '\n';
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
//TODO: this does not preserve any other PBL files
// filesystem.cpp does this too, so this might be intentional
if(!delete_directory(*j))
ret = false;
}
}
if (ret) {
bfs::remove(path(dirname), ec);
if (ec) {
LOG_FS << "remove(" << dirname << "): " << ec.message() << '\n';
ret = false;
}
}
return ret;
}
bool delete_file(const std::string &filename)
{
error_code ec;
bool ret = bfs::remove(path(filename), ec);
if (ec) {
ERR_FS << "Could not delete file " << filename << ": " << ec.message() << '\n';
}
return ret;
}
std::string read_file(const std::string &fname)
{
scoped_istream is = istream_file(fname);
std::stringstream ss;
ss << is->rdbuf();
return ss.str();
}
#if BOOST_VERSION < 1048000
//boost iostream < 1.48 expects boost filesystem v2 paths. This is an adapter
struct iostream_path
{
template<typename stringtype>
iostream_path(const stringtype& s)
: path_(s)
{
}
typedef bfs::path::string_type external_string_type;
external_string_type external_file_string() const
{
return path_.native();
}
bfs::path path_;
};
#else
typedef bfs::path iostream_path;
#endif
std::istream *istream_file(const std::string &fname, bool treat_failure_as_error)
{
LOG_FS << "Streaming " << fname << " for reading.\n";
if (fname.empty()) {
ERR_FS << "Trying to open file with empty name.\n";
bfs::ifstream *s = new bfs::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
//mingw doesn't support std::basic_ifstream::basic_ifstream(const wchar_t* fname)
//that why boost::filesystem::fstream.hpp doesnt work with mingw.
try
{
boost::iostreams::file_descriptor_source fd(iostream_path(fname), std::ios_base::binary);
//TODO: has this still use ?
if (!fd.is_open() && treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading.\n";
}
return new boost::iostreams::stream<boost::iostreams::file_descriptor_source>(fd, 4096, 0);
}
catch(const std::exception ex)
{
if(treat_failure_as_error)
{
ERR_FS << "Could not open '" << fname << "' for reading.\n";
}
bfs::ifstream *s = new bfs::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing.\n";
#if 1
try
{
boost::iostreams::file_descriptor_sink fd(iostream_path(fname), std::ios_base::binary);
return new boost::iostreams::stream<boost::iostreams::file_descriptor_sink>(fd, 4096, 0);
}
catch(BOOST_IOSTREAMS_FAILURE& e)
{
throw filesystem::io_exception(e.what());
}
#else
return new bfs::ofstream(path(fname), std::ios_base::binary);
#endif
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
scoped_ostream os = ostream_file(fname);
os->exceptions(std::ios_base::goodbit);
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
os->write(buf, bytes);
if (os->bad())
throw io_exception("Error writing to file: '" + fname + "'");
}
}
bool create_directory_if_missing(const std::string& dirname)
{
return create_directory_if_missing(path(dirname));
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
return create_directory_if_missing_recursive(path(dirname));
}
bool is_directory(const std::string& fname)
{
return is_directory_internal(path(fname));
}
bool file_exists(const std::string& name)
{
return file_exists(path(name));
}
time_t file_modified_time(const std::string& fname)
{
error_code ec;
std::time_t mtime = bfs::last_write_time(path(fname), ec);
if (ec) {
LOG_FS << "Failed to read modification time of " << fname << ": " << ec.message() << '\n';
}
return mtime;
}
bool is_gzip_file(const std::string& filename)
{
return path(filename).extension() == ".gz";
}
bool is_bzip2_file(const std::string& filename)
{
return path(filename).extension() == ".bz2";
}
int file_size(const std::string& fname)
{
error_code ec;
uintmax_t size = bfs::file_size(path(fname), ec);
if (ec) {
LOG_FS << "Failed to read filesize of " << fname << ": " << ec.message() << '\n';
return -1;
} else if (size > INT_MAX)
return INT_MAX;
else
return size;
}
int dir_size(const std::string& pname)
{
bfs::path p(pname);
uintmax_t size_sum = 0;
error_code ec;
for ( bfs::recursive_directory_iterator i(p), end; i != end && !ec; ++i ) {
if(bfs::is_regular_file(i->path())) {
size_sum += bfs::file_size(i->path(), ec);
}
}
if (ec) {
LOG_FS << "Failed to read directorysize of " << pname << ": " << ec.message() << '\n';
return -1;
}
else if (size_sum > INT_MAX)
return INT_MAX;
else
return size_sum;
}
std::string base_name(const std::string& file)
{
return path(file).filename().string();
}
std::string directory_name(const std::string& file)
{
return path(file).parent_path().string();
}
bool is_path_sep(char c)
{
static const path sep = path("/").make_preferred();
const std::string s = std::string(1, c);
return sep == path(s).make_preferred();
}
std::string normalize_path(const std::string &fpath)
{
if (fpath.empty()) {
return fpath;
}
return bfs::absolute(fpath).string();
}
/**
* The paths manager is responsible for recording the various paths
* that binary files may be located at.
* It should be passed a config object which holds binary path information.
* This is in the format
*@verbatim
* [binary_path]
* path=<path>
* [/binary_path]
* Binaries will be searched for in [wesnoth-path]/data/<path>/images/
*@endverbatim
*/
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'\n";
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
static bool is_legal_file(const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'.\n";
if (filename.empty()) {
LOG_FS << " invalid filename\n";
return false;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n";
return false;
}
return true;
}
/**
* Returns a vector with all possible paths to a given type of binary,
* e.g. 'images', 'sounds', etc,
*/
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths\n";
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
// We define ".." as "remove everything before" this is needed becasue
// on the one hand allowing ".." would be a security risk but
// especialy for terrains the c++ engine puts a hardcoded "terrain/" before filename
// and there would be no way to "escape" from "terrain/" otherwise. This is not the
// best solution but we cannot remove it without another solution (subtypes maybe?).
// using 'for' instead 'if' to allow putting delcaration and check into the brackets
for(std::string::size_type pos = filename.rfind("../"); pos != std::string::npos;)
return get_binary_file_location(type, filename.substr(pos + 3));
if (!is_legal_file(filename))
return std::string();
BOOST_FOREACH(const std::string &bp, get_binary_paths(type))
{
path bpath(bp);
bpath /= filename;
DBG_FS << " checking '" << bp << "'\n";
if (file_exists(bpath)) {
DBG_FS << " found at '" << bpath.string() << "'\n";
return bpath.string();
}
}
DBG_FS << " not found\n";
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
if (!is_legal_file(filename))
return std::string();
BOOST_FOREACH(const std::string &bp, get_binary_paths(type))
{
path bpath(bp);
bpath /= filename;
DBG_FS << " checking '" << bp << "'\n";
if (is_directory_internal(bpath)) {
DBG_FS << " found at '" << bpath.string() << "'\n";
return bpath.string();
}
}
DBG_FS << " not found\n";
return std::string();
}
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
if (!is_legal_file(filename))
return std::string();
assert(game_config::path.empty() == false);
path fpath(filename);
path result;
if (filename[0] == '~')
{
result /= get_user_data_path() / "data" / filename.substr(1);
DBG_FS << " trying '" << result.string() << "'\n";
} else if (*fpath.begin() == ".") {
if (!current_dir.empty()) {
result /= path(current_dir);
} else {
result /= path(game_config::path) / "data";
}
result /= filename;
} else if (!game_config::path.empty()) {
result /= path(game_config::path) / "data" / filename;
}
if (result.empty() || !file_exists(result)) {
DBG_FS << " not found\n";
result.clear();
} else
DBG_FS << " found: '" << result.string() << "'\n";
return result.string();
}
static path subtract_path(const path &full, const path &prefix)
{
path::iterator fi = full.begin()
, fe = full.end()
, pi = prefix.begin()
, pe = prefix.end();
while (fi != fe && pi != pe && *fi == *pi) {
++fi;
++pi;
}
path rest;
if (pi == pe)
while (fi != fe) {
rest /= *fi;
++fi;
}
return rest;
}
std::string get_short_wml_path(const std::string &filename)
{
path full_path(filename);
path partial = subtract_path(full_path, get_user_data_path() / "data");
if (!partial.empty())
return "~" + partial.string();
partial = subtract_path(full_path, path(game_config::path) / "data");
if (!partial.empty())
return partial.string();
return filename;
}
std::string get_independent_image_path(const std::string &filename)
{
path full_path(get_binary_file_location("images", filename));
if (full_path.empty())
return full_path.string();
path partial = subtract_path(full_path, get_user_data_path());
if (!partial.empty())
return partial.string();
partial = subtract_path(full_path, game_config::path);
if (!partial.empty())
return partial.string();
return full_path.string();
}
std::string get_program_invocation(const std::string &program_name)
{
const std::string real_program_name(program_name
#ifdef DEBUG
+ "-debug"
#endif
#ifdef _WIN32
+ ".exe"
#endif
);
return (path(game_config::wesnoth_program_dir) / real_program_name).string();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_1649_2 |
crossvul-cpp_data_good_2264_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/ext_hash.h"
#include <algorithm>
#include <memory>
#include "hphp/runtime/ext/ext_file.h"
#include "hphp/runtime/ext/ext_string.h"
#include "hphp/runtime/ext/hash/hash_md.h"
#include "hphp/runtime/ext/hash/hash_sha.h"
#include "hphp/runtime/ext/hash/hash_ripemd.h"
#include "hphp/runtime/ext/hash/hash_whirlpool.h"
#include "hphp/runtime/ext/hash/hash_tiger.h"
#include "hphp/runtime/ext/hash/hash_snefru.h"
#include "hphp/runtime/ext/hash/hash_gost.h"
#include "hphp/runtime/ext/hash/hash_adler32.h"
#include "hphp/runtime/ext/hash/hash_crc32.h"
#include "hphp/runtime/ext/hash/hash_haval.h"
#include "hphp/runtime/ext/hash/hash_fnv1.h"
#include "hphp/runtime/ext/hash/hash_furc.h"
#include "hphp/runtime/ext/hash/hash_murmur.h"
#include "hphp/system/constants.h"
#if defined(HPHP_OSS)
#define furc_hash furc_hash_internal
#else
#include "mcrouter/lib/fbi/hash.h" // @nolint
#endif
namespace HPHP {
static class HashExtension : public Extension {
public:
HashExtension() : Extension("hash", "1.0") { }
virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) {
HHVM_FE(hash);
HHVM_FE(hash_algos);
HHVM_FE(hash_file);
HHVM_FE(hash_final);
HHVM_FE(hash_init);
HHVM_FE(hash_update);
HHVM_FE(hash_copy);
HHVM_FE(hash_equals);
HHVM_FE(furchash_hphp_ext);
HHVM_FE(hphp_murmurhash);
}
} s_hash_extension;
///////////////////////////////////////////////////////////////////////////////
// hash engines
static HashEngineMap HashEngines;
using HashEnginePtr = std::shared_ptr<HashEngine>;
class HashEngineMapInitializer {
public:
HashEngineMapInitializer() {
HashEngines["md2"] = HashEnginePtr(new hash_md2());
HashEngines["md4"] = HashEnginePtr(new hash_md4());
HashEngines["md5"] = HashEnginePtr(new hash_md5());
HashEngines["sha1"] = HashEnginePtr(new hash_sha1());
HashEngines["sha224"] = HashEnginePtr(new hash_sha224());
HashEngines["sha256"] = HashEnginePtr(new hash_sha256());
HashEngines["sha384"] = HashEnginePtr(new hash_sha384());
HashEngines["sha512"] = HashEnginePtr(new hash_sha512());
HashEngines["ripemd128"] = HashEnginePtr(new hash_ripemd128());
HashEngines["ripemd160"] = HashEnginePtr(new hash_ripemd160());
HashEngines["ripemd256"] = HashEnginePtr(new hash_ripemd256());
HashEngines["ripemd320"] = HashEnginePtr(new hash_ripemd320());
HashEngines["whirlpool"] = HashEnginePtr(new hash_whirlpool());
#ifdef FACEBOOK
// The original version of tiger got the endianness backwards
// This fb-specific version remains for backward compatibility
HashEngines["tiger128,3-fb"]
= HashEnginePtr(new hash_tiger(true, 128, true));
#endif
HashEngines["tiger128,3"] = HashEnginePtr(new hash_tiger(true, 128));
HashEngines["tiger160,3"] = HashEnginePtr(new hash_tiger(true, 160));
HashEngines["tiger192,3"] = HashEnginePtr(new hash_tiger(true, 192));
HashEngines["tiger128,4"] = HashEnginePtr(new hash_tiger(false, 128));
HashEngines["tiger160,4"] = HashEnginePtr(new hash_tiger(false, 160));
HashEngines["tiger192,4"] = HashEnginePtr(new hash_tiger(false, 192));
HashEngines["snefru"] = HashEnginePtr(new hash_snefru());
HashEngines["gost"] = HashEnginePtr(new hash_gost());
#ifdef FACEBOOK
// Temporarily leave adler32 algo inverting its hash output
// to retain BC pending conversion of user code to correct endianness
// sgolemon(2014-01-30)
HashEngines["adler32-fb"] = HashEnginePtr(new hash_adler32(true));
HashEngines["adler32"] = HashEnginePtr(new hash_adler32(true));
#else
HashEngines["adler32"] = HashEnginePtr(new hash_adler32());
#endif
HashEngines["crc32"] = HashEnginePtr(new hash_crc32(false));
HashEngines["crc32b"] = HashEnginePtr(new hash_crc32(true));
HashEngines["haval128,3"] = HashEnginePtr(new hash_haval(3,128));
HashEngines["haval160,3"] = HashEnginePtr(new hash_haval(3,160));
HashEngines["haval192,3"] = HashEnginePtr(new hash_haval(3,192));
HashEngines["haval224,3"] = HashEnginePtr(new hash_haval(3,224));
HashEngines["haval256,3"] = HashEnginePtr(new hash_haval(3,256));
HashEngines["haval128,4"] = HashEnginePtr(new hash_haval(4,128));
HashEngines["haval160,4"] = HashEnginePtr(new hash_haval(4,160));
HashEngines["haval192,4"] = HashEnginePtr(new hash_haval(4,192));
HashEngines["haval224,4"] = HashEnginePtr(new hash_haval(4,224));
HashEngines["haval256,4"] = HashEnginePtr(new hash_haval(4,256));
HashEngines["haval128,5"] = HashEnginePtr(new hash_haval(5,128));
HashEngines["haval160,5"] = HashEnginePtr(new hash_haval(5,160));
HashEngines["haval192,5"] = HashEnginePtr(new hash_haval(5,192));
HashEngines["haval224,5"] = HashEnginePtr(new hash_haval(5,224));
HashEngines["haval256,5"] = HashEnginePtr(new hash_haval(5,256));
HashEngines["fnv132"] = HashEnginePtr(new hash_fnv132(false));
HashEngines["fnv1a32"] = HashEnginePtr(new hash_fnv132(true));
HashEngines["fnv164"] = HashEnginePtr(new hash_fnv164(false));
HashEngines["fnv1a64"] = HashEnginePtr(new hash_fnv164(true));
}
};
static HashEngineMapInitializer s_engine_initializer;
///////////////////////////////////////////////////////////////////////////////
// hash context
class HashContext : public SweepableResourceData {
public:
CLASSNAME_IS("Hash Context")
// overriding ResourceData
virtual const String& o_getClassNameHook() const { return classnameof(); }
HashContext(HashEnginePtr ops_, void *context_, int options_)
: ops(ops_), context(context_), options(options_), key(nullptr) {
}
explicit HashContext(const HashContext* ctx) {
assert(ctx->ops);
assert(ctx->ops->context_size >= 0);
ops = ctx->ops;
context = malloc(ops->context_size);
ops->hash_copy(context, ctx->context);
options = ctx->options;
if (ctx->key) {
key = static_cast<char*>(malloc(ops->block_size));
memcpy(key, ctx->key, ops->block_size);
} else {
key = nullptr;
}
}
~HashContext() {
HashContext::sweep();
}
void sweep() FOLLY_OVERRIDE {
/* Just in case the algo has internally allocated resources */
if (context) {
assert(ops->digest_size >= 0);
unsigned char dummy[ops->digest_size];
ops->hash_final(dummy, context);
free(context);
}
free(key);
}
HashEnginePtr ops;
void *context;
int options;
char *key;
};
///////////////////////////////////////////////////////////////////////////////
// hash functions
Array HHVM_FUNCTION(hash_algos) {
Array ret;
for (HashEngineMap::const_iterator iter = HashEngines.begin();
iter != HashEngines.end(); ++iter) {
ret.append(String(iter->first));
}
return ret;
}
static HashEnginePtr php_hash_fetch_ops(const String& algo) {
HashEngineMap::const_iterator iter =
HashEngines.find(f_strtolower(algo).data());
if (iter == HashEngines.end()) {
return HashEnginePtr();
}
return iter->second;
}
static Variant php_hash_do_hash(const String& algo, const String& data,
bool isfilename,
bool raw_output) {
HashEnginePtr ops = php_hash_fetch_ops(algo);
if (!ops) {
raise_warning("Unknown hashing algorithm: %s", algo.data());
return false;
}
Variant f;
if (isfilename) {
f = f_fopen(data, "rb");
if (same(f, false)) {
return false;
}
}
void *context = malloc(ops->context_size);
ops->hash_init(context);
if (isfilename) {
for (Variant chunk = f_fread(f.toResource(), 1024);
!is_empty_string(chunk);
chunk = f_fread(f.toResource(), 1024)) {
String schunk = chunk.toString();
ops->hash_update(context, (unsigned char *)schunk.data(), schunk.size());
}
} else {
ops->hash_update(context, (unsigned char *)data.data(), data.size());
}
String raw = String(ops->digest_size, ReserveString);
char *digest = raw.bufferSlice().ptr;
ops->hash_final((unsigned char *)digest, context);
free(context);
raw.setSize(ops->digest_size);
if (raw_output) {
return raw;
}
return f_bin2hex(raw);
}
Variant HHVM_FUNCTION(hash, const String& algo, const String& data,
bool raw_output /* = false */) {
return php_hash_do_hash(algo, data, false, raw_output);
}
Variant HHVM_FUNCTION(hash_file, const String& algo, const String& filename,
bool raw_output /* = false */) {
if (filename.size() != strlen(filename.data())) {
raise_warning(
"hash_file() expects parameter 2 to be a valid path, string given"
);
return null_variant;
}
return php_hash_do_hash(algo, filename, true, raw_output);
}
static char *prepare_hmac_key(HashEnginePtr ops, void *context,
const String& key) {
char *K = (char*)malloc(ops->block_size);
memset(K, 0, ops->block_size);
if (key.size() > ops->block_size) {
/* Reduce the key first */
ops->hash_update(context, (unsigned char *)key.data(), key.size());
ops->hash_final((unsigned char *)K, context);
/* Make the context ready to start over */
ops->hash_init(context);
} else {
memcpy(K, key.data(), key.size());
}
/* XOR ipad */
for (int i = 0; i < ops->block_size; i++) {
K[i] ^= 0x36;
}
ops->hash_update(context, (unsigned char *)K, ops->block_size);
return K;
}
static void finalize_hmac_key(char *K, HashEnginePtr ops, void *context,
char *digest) {
/* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
for (int i = 0; i < ops->block_size; i++) {
K[i] ^= 0x6A;
}
/* Feed this result into the outter hash */
ops->hash_init(context);
ops->hash_update(context, (unsigned char *)K, ops->block_size);
ops->hash_update(context, (unsigned char *)digest, ops->digest_size);
ops->hash_final((unsigned char *)digest, context);
/* Zero the key */
memset(K, 0, ops->block_size);
free(K);
}
Variant HHVM_FUNCTION(hash_init, const String& algo,
int64_t options /* = 0 */,
const String& key /* = null_string */) {
HashEnginePtr ops = php_hash_fetch_ops(algo);
if (!ops) {
raise_warning("Unknown hashing algorithm: %s", algo.data());
return false;
}
if ((options & k_HASH_HMAC) && key.empty()) {
raise_warning("HMAC requested without a key");
return false;
}
void *context = malloc(ops->context_size);
ops->hash_init(context);
const auto hash = new HashContext(ops, context, options);
if (options & k_HASH_HMAC) {
hash->key = prepare_hmac_key(ops, context, key);
}
return Resource(hash);
}
bool HHVM_FUNCTION(hash_update, const Resource& context, const String& data) {
HashContext *hash = context.getTyped<HashContext>();
hash->ops->hash_update(hash->context, (unsigned char *)data.data(),
data.size());
return true;
}
Variant HHVM_FUNCTION(hash_final, const Resource& context,
bool raw_output /* = false */) {
HashContext *hash = context.getTyped<HashContext>();
if (hash->context == nullptr) {
raise_warning(
"hash_final(): supplied resource is not a valid Hash Context resource"
);
return false;
}
String raw = String(hash->ops->digest_size, ReserveString);
char *digest = raw.bufferSlice().ptr;
hash->ops->hash_final((unsigned char *)digest, hash->context);
if (hash->options & k_HASH_HMAC) {
finalize_hmac_key(hash->key, hash->ops, hash->context, digest);
hash->key = NULL;
}
free(hash->context);
hash->context = NULL;
raw.setSize(hash->ops->digest_size);
if (raw_output) {
return raw;
}
return f_bin2hex(raw);
}
Resource HHVM_FUNCTION(hash_copy, const Resource& context) {
HashContext *oldhash = context.getTyped<HashContext>();
auto const hash = new HashContext(oldhash);
return Resource(hash);
}
/**
* It is important that the run time of this function is dependent
* only on the length of the user-supplied string.
*
* The only branch in the code below *should* result in non-branching
* machine code.
*
* Do not try to optimize this function.
*/
bool HHVM_FUNCTION(hash_equals, const Variant& known, const Variant& user) {
if (!known.isString()) {
raise_warning(
"hash_equals(): Expected known_string to be a string, %s given",
getDataTypeString(known.getType()).c_str()
);
return false;
}
if (!user.isString()) {
raise_warning(
"hash_equals(): Expected user_string to be a string, %s given",
getDataTypeString(user.getType()).c_str()
);
return false;
}
String known_str = known.toString();
String user_str = user.toString();
const auto known_len = known_str.size();
const auto known_limit = known_len - 1;
const auto user_len = user_str.size();
int64_t result = known_len ^ user_len;
int64_t ki = 0;
for (int64_t ui = 0; ui < user_len; ++ui) {
result |= user_str[ui] ^ known_str[ki];
if (ki < known_limit) {
++ki;
}
}
return (result == 0);
}
int64_t HHVM_FUNCTION(furchash_hphp_ext, const String& key,
int64_t len, int64_t nPart) {
len = std::max<int64_t>(std::min<int64_t>(len, key.size()), 0);
return furc_hash(key.data(), len, nPart);
}
int64_t HHVM_FUNCTION(hphp_murmurhash, const String& key,
int64_t len, int64_t seed) {
len = std::max<int64_t>(std::min<int64_t>(len, key.size()), 0);
return murmur_hash_64A(key.data(), len, seed);
}
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_2264_0 |
crossvul-cpp_data_good_1811_1 | /****************************************************************************
** libmatroska : parse Matroska files, see http://www.matroska.org/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id: KaxBlock.cpp 1265 2007-01-14 17:20:35Z mosu $
\author Steve Lhomme <robux4 @ users.sf.net>
\author Julien Coloos <suiryc @ users.sf.net>
\author Moritz Bunkus <moritz@bunkus.org>
*/
#include <cassert>
//#include <streams.h>
#include "ebml/MemReadIOCallback.h"
#include "ebml/SafeReadIOCallback.h"
#include "matroska/KaxBlock.h"
#include "matroska/KaxContexts.h"
#include "matroska/KaxBlockData.h"
#include "matroska/KaxCluster.h"
#include "matroska/KaxDefines.h"
START_LIBMATROSKA_NAMESPACE
DataBuffer * DataBuffer::Clone()
{
binary *ClonedData = (binary *)malloc(mySize * sizeof(binary));
assert(ClonedData != NULL);
memcpy(ClonedData, myBuffer ,mySize );
SimpleDataBuffer * result = new SimpleDataBuffer(ClonedData, mySize, 0);
result->bValidValue = bValidValue;
return result;
}
SimpleDataBuffer::SimpleDataBuffer(const SimpleDataBuffer & ToClone)
:DataBuffer((binary *)malloc(ToClone.mySize * sizeof(binary)), ToClone.mySize, myFreeBuffer)
{
assert(myBuffer != NULL);
memcpy(myBuffer, ToClone.myBuffer ,mySize );
bValidValue = ToClone.bValidValue;
}
bool KaxInternalBlock::ValidateSize() const
{
return (GetSize() >= 4); /// for the moment
}
KaxInternalBlock::~KaxInternalBlock()
{
ReleaseFrames();
}
KaxInternalBlock::KaxInternalBlock(const KaxInternalBlock & ElementToClone)
:EbmlBinary(ElementToClone)
,myBuffers(ElementToClone.myBuffers.size())
,Timecode(ElementToClone.Timecode)
,LocalTimecode(ElementToClone.LocalTimecode)
,bLocalTimecodeUsed(ElementToClone.bLocalTimecodeUsed)
,TrackNumber(ElementToClone.TrackNumber)
,ParentCluster(ElementToClone.ParentCluster) ///< \todo not exactly
{
// add a clone of the list
std::vector<DataBuffer *>::const_iterator Itr = ElementToClone.myBuffers.begin();
std::vector<DataBuffer *>::iterator myItr = myBuffers.begin();
while (Itr != ElementToClone.myBuffers.end()) {
*myItr = (*Itr)->Clone();
++Itr; ++myItr;
}
}
KaxBlockGroup::~KaxBlockGroup()
{
//NOTE("KaxBlockGroup::~KaxBlockGroup");
}
KaxBlockGroup::KaxBlockGroup(EBML_EXTRA_DEF)
:EbmlMaster(EBML_CLASS_SEMCONTEXT(KaxBlockGroup) EBML_DEF_SEP EBML_EXTRA_CALL)
,ParentCluster(NULL)
,ParentTrack(NULL)
{}
/*!
\todo handle flags
\todo hardcoded limit of the number of frames in a lace should be a parameter
\return true if more frames can be added to this Block
*/
bool KaxInternalBlock::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing, bool invisible)
{
SetValueIsSet();
if (myBuffers.size() == 0) {
// first frame
Timecode = timecode;
TrackNumber = track.TrackNumber();
mInvisible = invisible;
mLacing = lacing;
}
myBuffers.push_back(&buffer);
// we don't allow more than 8 frames in a Block because the overhead improvement is minimal
if (myBuffers.size() >= 8 || lacing == LACING_NONE)
return false;
if (lacing == LACING_XIPH)
// decide wether a new frame can be added or not
// a frame in a lace is not efficient when the place necessary to code it in a lace is bigger
// than the size of a simple Block. That means more than 6 bytes (4 in struct + 2 for EBML) to code the size
return (buffer.Size() < 6*0xFF);
else
return true;
}
/*!
\return Returns the lacing type that produces the smallest footprint.
*/
LacingType KaxInternalBlock::GetBestLacingType() const {
int XiphLacingSize, EbmlLacingSize, i;
bool SameSize = true;
if (myBuffers.size() <= 1)
return LACING_NONE;
XiphLacingSize = 1; // Number of laces is stored in 1 byte.
EbmlLacingSize = 1;
for (i = 0; i < (int)myBuffers.size() - 1; i++) {
if (myBuffers[i]->Size() != myBuffers[i + 1]->Size())
SameSize = false;
XiphLacingSize += myBuffers[i]->Size() / 255 + 1;
}
EbmlLacingSize += CodedSizeLength(myBuffers[0]->Size(), 0, IsFiniteSize());
for (i = 1; i < (int)myBuffers.size() - 1; i++)
EbmlLacingSize += CodedSizeLengthSigned(int64(myBuffers[i]->Size()) - int64(myBuffers[i - 1]->Size()), 0);
if (SameSize)
return LACING_FIXED;
else if (XiphLacingSize < EbmlLacingSize)
return LACING_XIPH;
else
return LACING_EBML;
}
filepos_t KaxInternalBlock::UpdateSize(bool /* bSaveDefault */, bool /* bForceRender */)
{
LacingType LacingHere;
assert(EbmlBinary::GetBuffer() == NULL); // Data is not used for KaxInternalBlock
assert(TrackNumber < 0x4000); // no more allowed for the moment
unsigned int i;
// compute the final size of the data
switch (myBuffers.size()) {
case 0:
SetSize_(0);
break;
case 1:
SetSize_(4 + myBuffers[0]->Size());
break;
default:
SetSize_(4 + 1); // 1 for the lacing head
if (mLacing == LACING_AUTO)
LacingHere = GetBestLacingType();
else
LacingHere = mLacing;
switch (LacingHere) {
case LACING_XIPH:
for (i=0; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size() + (myBuffers[i]->Size() / 0xFF + 1));
}
break;
case LACING_EBML:
SetSize_(GetSize() + myBuffers[0]->Size() + CodedSizeLength(myBuffers[0]->Size(), 0, IsFiniteSize()));
for (i=1; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size() + CodedSizeLengthSigned(int64(myBuffers[i]->Size()) - int64(myBuffers[i-1]->Size()), 0));
}
break;
case LACING_FIXED:
for (i=0; i<myBuffers.size()-1; i++) {
SetSize_(GetSize() + myBuffers[i]->Size());
}
break;
default:
i = 0;
assert(0);
}
// Size of the last frame (not in lace)
SetSize_(GetSize() + myBuffers[i]->Size());
break;
}
if (TrackNumber >= 0x80)
SetSize_(GetSize() + 1); // the size will be coded with one more octet
return GetSize();
}
#if MATROSKA_VERSION >= 2
KaxBlockVirtual::KaxBlockVirtual(const KaxBlockVirtual & ElementToClone)
:EbmlBinary(ElementToClone)
,Timecode(ElementToClone.Timecode)
,TrackNumber(ElementToClone.TrackNumber)
,ParentCluster(ElementToClone.ParentCluster) ///< \todo not exactly
{
SetBuffer(DataBlock,sizeof(DataBlock));
SetValueIsSet(false);
}
KaxBlockVirtual::KaxBlockVirtual(EBML_EXTRA_DEF)
:EBML_DEF_BINARY(KaxBlockVirtual)EBML_DEF_SEP ParentCluster(NULL)
{
SetBuffer(DataBlock,sizeof(DataBlock));
SetValueIsSet(false);
}
KaxBlockVirtual::~KaxBlockVirtual()
{
if(GetBuffer() == DataBlock)
SetBuffer( NULL, 0 );
}
filepos_t KaxBlockVirtual::UpdateSize(bool /* bSaveDefault */, bool /* bForceRender */)
{
assert(TrackNumber < 0x4000);
binary *cursor = EbmlBinary::GetBuffer();
// fill data
if (TrackNumber < 0x80) {
assert(GetSize() >= 4);
*cursor++ = TrackNumber | 0x80; // set the first bit to 1
} else {
assert(GetSize() >= 5);
*cursor++ = (TrackNumber >> 8) | 0x40; // set the second bit to 1
*cursor++ = TrackNumber & 0xFF;
}
assert(ParentCluster != NULL);
int16 ActualTimecode = ParentCluster->GetBlockLocalTimecode(Timecode);
big_int16 b16(ActualTimecode);
b16.Fill(cursor);
cursor += 2;
*cursor++ = 0; // flags
return GetSize();
}
#endif // MATROSKA_VERSION
/*!
\todo more optimisation is possible (render the Block head and don't copy the buffer in memory, care should be taken with the allocation of Data)
\todo the actual timecode to write should be retrieved from the Cluster from here
*/
filepos_t KaxInternalBlock::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bSaveDefault */)
{
if (myBuffers.size() == 0) {
return 0;
} else {
assert(TrackNumber < 0x4000);
binary BlockHead[5], *cursor = BlockHead;
unsigned int i;
if (myBuffers.size() == 1) {
SetSize_(4);
mLacing = LACING_NONE;
} else {
if (mLacing == LACING_NONE)
mLacing = LACING_EBML; // supposedly the best of all
SetSize_(4 + 1); // 1 for the lacing head (number of laced elements)
}
if (TrackNumber > 0x80)
SetSize_(GetSize() + 1);
// write Block Head
if (TrackNumber < 0x80) {
*cursor++ = TrackNumber | 0x80; // set the first bit to 1
} else {
*cursor++ = (TrackNumber >> 8) | 0x40; // set the second bit to 1
*cursor++ = TrackNumber & 0xFF;
}
assert(ParentCluster != NULL);
int16 ActualTimecode = ParentCluster->GetBlockLocalTimecode(Timecode);
big_int16 b16(ActualTimecode);
b16.Fill(cursor);
cursor += 2;
*cursor = 0; // flags
if (mLacing == LACING_AUTO) {
mLacing = GetBestLacingType();
}
// invisible flag
if (mInvisible)
*cursor = 0x08;
if (bIsSimple) {
if (bIsKeyframe)
*cursor |= 0x80;
if (bIsDiscardable)
*cursor |= 0x01;
}
// lacing flag
switch (mLacing) {
case LACING_XIPH:
*cursor++ |= 0x02;
break;
case LACING_EBML:
*cursor++ |= 0x06;
break;
case LACING_FIXED:
*cursor++ |= 0x04;
break;
case LACING_NONE:
break;
default:
assert(0);
}
output.writeFully(BlockHead, 4 + ((TrackNumber > 0x80) ? 1 : 0));
binary tmpValue;
switch (mLacing) {
case LACING_XIPH:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
// set the size of each member in the lace
for (i=0; i<myBuffers.size()-1; i++) {
tmpValue = 0xFF;
uint16 tmpSize = myBuffers[i]->Size();
while (tmpSize >= 0xFF) {
output.writeFully(&tmpValue, 1);
SetSize_(GetSize() + 1);
tmpSize -= 0xFF;
}
tmpValue = binary(tmpSize);
output.writeFully(&tmpValue, 1);
SetSize_(GetSize() + 1);
}
break;
case LACING_EBML:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
{
int64 _Size;
int _CodedSize;
binary _FinalHead[8]; // 64 bits max coded size
_Size = myBuffers[0]->Size();
_CodedSize = CodedSizeLength(_Size, 0, IsFiniteSize());
// first size in the lace is not a signed
CodedValueLength(_Size, _CodedSize, _FinalHead);
output.writeFully(_FinalHead, _CodedSize);
SetSize_(GetSize() + _CodedSize);
// set the size of each member in the lace
for (i=1; i<myBuffers.size()-1; i++) {
_Size = int64(myBuffers[i]->Size()) - int64(myBuffers[i-1]->Size());
_CodedSize = CodedSizeLengthSigned(_Size, 0);
CodedValueLengthSigned(_Size, _CodedSize, _FinalHead);
output.writeFully(_FinalHead, _CodedSize);
SetSize_(GetSize() + _CodedSize);
}
}
break;
case LACING_FIXED:
// number of laces
tmpValue = myBuffers.size()-1;
output.writeFully(&tmpValue, 1);
break;
case LACING_NONE:
break;
default:
assert(0);
}
// put the data of each frame
for (i=0; i<myBuffers.size(); i++) {
output.writeFully(myBuffers[i]->Buffer(), myBuffers[i]->Size());
SetSize_(GetSize() + myBuffers[i]->Size());
}
}
return GetSize();
}
uint64 KaxInternalBlock::ReadInternalHead(IOCallback & input)
{
binary Buffer[5], *cursor = Buffer;
uint64 Result = input.read(cursor, 4);
if (Result != 4)
return Result;
// update internal values
TrackNumber = *cursor++;
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
return Result;
}
Result += input.read(&Buffer[4], 1);
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += *cursor++;
} else {
TrackNumber &= 0x7F;
}
big_int16 b16;
b16.Eval(cursor);
assert(ParentCluster != NULL);
Timecode = ParentCluster->GetBlockGlobalTimecode(int16(b16));
bLocalTimecodeUsed = false;
cursor += 2;
return Result;
}
/*!
\todo better zero copy handling
*/
filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)
{
filepos_t Result;
FirstFrameLocation = input.getFilePointer(); // will be updated accordingly below
SetValueIsSet(false);
try {
if (ReadFully == SCOPE_ALL_DATA) {
Result = EbmlBinary::ReadData(input, ReadFully);
if (Result != GetSize())
throw SafeReadIOCallback::EndOfStreamX(GetSize() - Result);
binary *BufferStart = EbmlBinary::GetBuffer();
SafeReadIOCallback Mem(*this);
uint8 BlockHeadSize = 4;
// update internal values
TrackNumber = Mem.GetUInt8();
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
throw SafeReadIOCallback::EndOfStreamX(0);
}
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += Mem.GetUInt8();
BlockHeadSize++;
} else {
TrackNumber &= 0x7F;
}
LocalTimecode = int16(Mem.GetUInt16BE());
bLocalTimecodeUsed = true;
uint8 Flags = Mem.GetUInt8();
if (EbmlId(*this) == EBML_ID(KaxSimpleBlock)) {
bIsKeyframe = (Flags & 0x80) != 0;
bIsDiscardable = (Flags & 0x01) != 0;
}
mInvisible = (Flags & 0x08) >> 3;
mLacing = LacingType((Flags & 0x06) >> 1);
// put all Frames in the list
if (mLacing == LACING_NONE) {
FirstFrameLocation += Mem.GetPosition();
DataBuffer * soloFrame = new DataBuffer(BufferStart + Mem.GetPosition(), GetSize() - BlockHeadSize);
myBuffers.push_back(soloFrame);
SizeList.resize(1);
SizeList[0] = GetSize() - BlockHeadSize;
} else {
// read the number of frames in the lace
uint32 LastBufferSize = GetSize() - BlockHeadSize - 1; // 1 for number of frame
uint8 FrameNum = Mem.GetUInt8(); // number of frames in the lace - 1
// read the list of frame sizes
uint8 Index;
int32 FrameSize;
uint32 SizeRead;
uint64 SizeUnknown;
SizeList.resize(FrameNum + 1);
switch (mLacing) {
case LACING_XIPH:
for (Index=0; Index<FrameNum; Index++) {
// get the size of the frame
FrameSize = 0;
uint8 Value;
do {
Value = Mem.GetUInt8();
FrameSize += Value;
LastBufferSize--;
} while (Value == 0xFF);
SizeList[Index] = FrameSize;
LastBufferSize -= FrameSize;
}
SizeList[Index] = LastBufferSize;
break;
case LACING_EBML:
SizeRead = LastBufferSize;
FrameSize = ReadCodedSizeValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);
if (!FrameSize || (static_cast<uint32>(FrameSize + SizeRead) > LastBufferSize))
throw SafeReadIOCallback::EndOfStreamX(SizeRead);
SizeList[0] = FrameSize;
Mem.Skip(SizeRead);
LastBufferSize -= FrameSize + SizeRead;
for (Index=1; Index<FrameNum; Index++) {
// get the size of the frame
SizeRead = LastBufferSize;
FrameSize += ReadCodedSizeSignedValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);
if (!FrameSize || (static_cast<uint32>(FrameSize + SizeRead) > LastBufferSize))
throw SafeReadIOCallback::EndOfStreamX(SizeRead);
SizeList[Index] = FrameSize;
Mem.Skip(SizeRead);
LastBufferSize -= FrameSize + SizeRead;
}
if (Index <= FrameNum) // Safety check if FrameNum == 0
SizeList[Index] = LastBufferSize;
break;
case LACING_FIXED:
for (Index=0; Index<=FrameNum; Index++) {
// get the size of the frame
SizeList[Index] = LastBufferSize / (FrameNum + 1);
}
break;
default: // other lacing not supported
assert(0);
}
FirstFrameLocation += Mem.GetPosition();
for (Index=0; Index<=FrameNum; Index++) {
DataBuffer * lacedFrame = new DataBuffer(BufferStart + Mem.GetPosition(), SizeList[Index]);
myBuffers.push_back(lacedFrame);
Mem.Skip(SizeList[Index]);
}
}
binary *BufferEnd = BufferStart + GetSize();
size_t NumFrames = myBuffers.size();
// Sanity checks for frame pointers and boundaries.
for (size_t Index = 0; Index < NumFrames; ++Index) {
binary *FrameStart = myBuffers[Index]->Buffer();
binary *FrameEnd = FrameStart + myBuffers[Index]->Size();
binary *ExpectedEnd = (Index + 1) < NumFrames ? myBuffers[Index + 1]->Buffer() : BufferEnd;
if ((FrameStart < BufferStart) || (FrameEnd > BufferEnd) || (FrameEnd != ExpectedEnd))
throw SafeReadIOCallback::EndOfStreamX(0);
}
SetValueIsSet();
} else if (ReadFully == SCOPE_PARTIAL_DATA) {
binary _TempHead[5];
Result = input.read(_TempHead, 5);
if (Result != 5)
throw SafeReadIOCallback::EndOfStreamX(0);
binary *cursor = _TempHead;
binary *_tmpBuf;
uint8 BlockHeadSize = 4;
// update internal values
TrackNumber = *cursor++;
if ((TrackNumber & 0x80) == 0) {
// there is extra data
if ((TrackNumber & 0x40) == 0) {
// We don't support track numbers that large !
return Result;
}
TrackNumber = (TrackNumber & 0x3F) << 8;
TrackNumber += *cursor++;
BlockHeadSize++;
} else {
TrackNumber &= 0x7F;
}
big_int16 b16;
b16.Eval(cursor);
LocalTimecode = int16(b16);
bLocalTimecodeUsed = true;
cursor += 2;
if (EbmlId(*this) == EBML_ID(KaxSimpleBlock)) {
bIsKeyframe = (*cursor & 0x80) != 0;
bIsDiscardable = (*cursor & 0x01) != 0;
}
mInvisible = (*cursor & 0x08) >> 3;
mLacing = LacingType((*cursor++ & 0x06) >> 1);
if (cursor == &_TempHead[4]) {
_TempHead[0] = _TempHead[4];
} else {
Result += input.read(_TempHead, 1);
}
FirstFrameLocation += cursor - _TempHead;
// put all Frames in the list
if (mLacing != LACING_NONE) {
// read the number of frames in the lace
uint32 LastBufferSize = GetSize() - BlockHeadSize - 1; // 1 for number of frame
uint8 FrameNum = _TempHead[0]; // number of frames in the lace - 1
// read the list of frame sizes
uint8 Index;
int32 FrameSize;
uint32 SizeRead;
uint64 SizeUnknown;
SizeList.resize(FrameNum + 1);
switch (mLacing) {
case LACING_XIPH:
for (Index=0; Index<FrameNum; Index++) {
// get the size of the frame
FrameSize = 0;
do {
Result += input.read(_TempHead, 1);
FrameSize += uint8(_TempHead[0]);
LastBufferSize--;
FirstFrameLocation++;
} while (_TempHead[0] == 0xFF);
FirstFrameLocation++;
SizeList[Index] = FrameSize;
LastBufferSize -= FrameSize;
}
SizeList[Index] = LastBufferSize;
break;
case LACING_EBML:
SizeRead = LastBufferSize;
cursor = _tmpBuf = new binary[FrameNum*4]; /// \warning assume the mean size will be coded in less than 4 bytes
Result += input.read(cursor, FrameNum*4);
FrameSize = ReadCodedSizeValue(cursor, SizeRead, SizeUnknown);
SizeList[0] = FrameSize;
cursor += SizeRead;
LastBufferSize -= FrameSize + SizeRead;
for (Index=1; Index<FrameNum; Index++) {
// get the size of the frame
SizeRead = LastBufferSize;
FrameSize += ReadCodedSizeSignedValue(cursor, SizeRead, SizeUnknown);
SizeList[Index] = FrameSize;
cursor += SizeRead;
LastBufferSize -= FrameSize + SizeRead;
}
FirstFrameLocation += cursor - _tmpBuf;
SizeList[Index] = LastBufferSize;
delete [] _tmpBuf;
break;
case LACING_FIXED:
for (Index=0; Index<=FrameNum; Index++) {
// get the size of the frame
SizeList[Index] = LastBufferSize / (FrameNum + 1);
}
break;
default: // other lacing not supported
assert(0);
}
} else {
SizeList.resize(1);
SizeList[0] = GetSize() - BlockHeadSize;
}
SetValueIsSet(false);
Result = GetSize();
} else {
SetValueIsSet(false);
Result = GetSize();
}
} catch (SafeReadIOCallback::EndOfStreamX &) {
SetValueIsSet(false);
std::memset(EbmlBinary::GetBuffer(), 0, GetSize());
myBuffers.clear();
SizeList.clear();
Timecode = 0;
LocalTimecode = 0;
TrackNumber = 0;
bLocalTimecodeUsed = false;
FirstFrameLocation = 0;
return 0;
}
return Result;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing)
{
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
return theBlock.AddFrame(track, timecode, buffer, lacing);
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockGroup & PastBlock, LacingType lacing)
{
// assert(past_timecode < 0);
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
return bRes;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockGroup & PastBlock, const KaxBlockGroup & ForwBlock, LacingType lacing)
{
// assert(past_timecode < 0);
// assert(forw_timecode > 0);
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
KaxReferenceBlock & theFutureRef = AddNewChild<KaxReferenceBlock>(*this);
theFutureRef.SetReferencedBlock(ForwBlock);
theFutureRef.SetParentBlock(*this);
return bRes;
}
bool KaxBlockGroup::AddFrame(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, const KaxBlockBlob * PastBlock, const KaxBlockBlob * ForwBlock, LacingType lacing)
{
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
assert(ParentCluster != NULL);
theBlock.SetParent(*ParentCluster);
ParentTrack = &track;
bool bRes = theBlock.AddFrame(track, timecode, buffer, lacing);
if (PastBlock != NULL) {
KaxReferenceBlock & thePastRef = GetChild<KaxReferenceBlock>(*this);
thePastRef.SetReferencedBlock(PastBlock);
thePastRef.SetParentBlock(*this);
}
if (ForwBlock != NULL) {
KaxReferenceBlock & theFutureRef = AddNewChild<KaxReferenceBlock>(*this);
theFutureRef.SetReferencedBlock(ForwBlock);
theFutureRef.SetParentBlock(*this);
}
return bRes;
}
/*!
\todo we may cache the reference to the timecode block
*/
uint64 KaxBlockGroup::GlobalTimecode() const
{
assert(ParentCluster != NULL); // impossible otherwise
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
return MyBlock.GlobalTimecode();
}
uint16 KaxBlockGroup::TrackNumber() const
{
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
return MyBlock.TrackNum();
}
uint64 KaxBlockGroup::ClusterPosition() const
{
assert(ParentCluster != NULL); // impossible otherwise
return ParentCluster->GetPosition();
}
uint64 KaxInternalBlock::ClusterPosition() const
{
assert(ParentCluster != NULL); // impossible otherwise
return ParentCluster->GetPosition();
}
unsigned int KaxBlockGroup::ReferenceCount() const
{
unsigned int Result = 0;
KaxReferenceBlock * MyBlockAdds = static_cast<KaxReferenceBlock *>(FindFirstElt(EBML_INFO(KaxReferenceBlock)));
if (MyBlockAdds != NULL) {
Result++;
while ((MyBlockAdds = static_cast<KaxReferenceBlock *>(FindNextElt(*MyBlockAdds))) != NULL) {
Result++;
}
}
return Result;
}
const KaxReferenceBlock & KaxBlockGroup::Reference(unsigned int Index) const
{
KaxReferenceBlock * MyBlockAdds = static_cast<KaxReferenceBlock *>(FindFirstElt(EBML_INFO(KaxReferenceBlock)));
assert(MyBlockAdds != NULL); // call of a non existing reference
while (Index != 0) {
MyBlockAdds = static_cast<KaxReferenceBlock *>(FindNextElt(*MyBlockAdds));
assert(MyBlockAdds != NULL);
Index--;
}
return *MyBlockAdds;
}
void KaxBlockGroup::ReleaseFrames()
{
KaxInternalBlock & MyBlock = *static_cast<KaxBlock *>(this->FindElt(EBML_INFO(KaxBlock)));
MyBlock.ReleaseFrames();
}
void KaxInternalBlock::ReleaseFrames()
{
// free the allocated Frames
int i;
for (i=myBuffers.size()-1; i>=0; i--) {
if (myBuffers[i] != NULL) {
myBuffers[i]->FreeBuffer(*myBuffers[i]);
delete myBuffers[i];
myBuffers[i] = NULL;
}
}
}
void KaxBlockGroup::SetBlockDuration(uint64 TimeLength)
{
assert(ParentTrack != NULL);
int64 scale = ParentTrack->GlobalTimecodeScale();
KaxBlockDuration & myDuration = *static_cast<KaxBlockDuration *>(FindFirstElt(EBML_INFO(KaxBlockDuration), true));
*(static_cast<EbmlUInteger *>(&myDuration)) = TimeLength / uint64(scale);
}
bool KaxBlockGroup::GetBlockDuration(uint64 &TheTimecode) const
{
KaxBlockDuration * myDuration = static_cast<KaxBlockDuration *>(FindElt(EBML_INFO(KaxBlockDuration)));
if (myDuration == NULL) {
return false;
}
assert(ParentTrack != NULL);
TheTimecode = uint64(*myDuration) * ParentTrack->GlobalTimecodeScale();
return true;
}
KaxBlockGroup::operator KaxInternalBlock &() {
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
return theBlock;
}
void KaxBlockGroup::SetParent(KaxCluster & aParentCluster) {
ParentCluster = &aParentCluster;
KaxBlock & theBlock = GetChild<KaxBlock>(*this);
theBlock.SetParent( aParentCluster );
}
void KaxSimpleBlock::SetParent(KaxCluster & aParentCluster) {
KaxInternalBlock::SetParent( aParentCluster );
}
void KaxInternalBlock::SetParent(KaxCluster & aParentCluster)
{
ParentCluster = &aParentCluster;
if (bLocalTimecodeUsed) {
Timecode = aParentCluster.GetBlockGlobalTimecode(LocalTimecode);
bLocalTimecodeUsed = false;
}
}
int64 KaxInternalBlock::GetDataPosition(size_t FrameNumber)
{
int64 _Result = -1;
if (ValueIsSet() && FrameNumber < SizeList.size()) {
_Result = FirstFrameLocation;
size_t _Idx = 0;
while(FrameNumber--) {
_Result += SizeList[_Idx++];
}
}
return _Result;
}
int64 KaxInternalBlock::GetFrameSize(size_t FrameNumber)
{
int64 _Result = -1;
if (/*bValueIsSet &&*/ FrameNumber < SizeList.size()) {
_Result = SizeList[FrameNumber];
}
return _Result;
}
KaxBlockBlob::operator KaxBlockGroup &()
{
assert(!bUseSimpleBlock);
assert(Block.group);
return *Block.group;
}
KaxBlockBlob::operator const KaxBlockGroup &() const
{
assert(!bUseSimpleBlock);
assert(Block.group);
return *Block.group;
}
KaxBlockBlob::operator KaxInternalBlock &()
{
assert(Block.group);
#if MATROSKA_VERSION >= 2
if (bUseSimpleBlock)
return *Block.simpleblock;
else
#endif
return *Block.group;
}
KaxBlockBlob::operator const KaxInternalBlock &() const
{
assert(Block.group);
#if MATROSKA_VERSION >= 2
if (bUseSimpleBlock)
return *Block.simpleblock;
else
#endif
return *Block.group;
}
#if MATROSKA_VERSION >= 2
KaxBlockBlob::operator KaxSimpleBlock &()
{
assert(bUseSimpleBlock);
assert(Block.simpleblock);
return *Block.simpleblock;
}
#endif
bool KaxBlockBlob::AddFrameAuto(const KaxTrackEntry & track, uint64 timecode, DataBuffer & buffer, LacingType lacing, const KaxBlockBlob * PastBlock, const KaxBlockBlob * ForwBlock)
{
bool bResult = false;
#if MATROSKA_VERSION >= 2
if ((SimpleBlockMode == BLOCK_BLOB_ALWAYS_SIMPLE) || (SimpleBlockMode == BLOCK_BLOB_SIMPLE_AUTO && PastBlock == NULL && ForwBlock == NULL)) {
assert(bUseSimpleBlock == true);
if (Block.simpleblock == NULL) {
Block.simpleblock = new KaxSimpleBlock();
Block.simpleblock->SetParent(*ParentCluster);
}
bResult = Block.simpleblock->AddFrame(track, timecode, buffer, lacing);
if (PastBlock == NULL && ForwBlock == NULL) {
Block.simpleblock->SetKeyframe(true);
Block.simpleblock->SetDiscardable(false);
} else {
Block.simpleblock->SetKeyframe(false);
if ((ForwBlock == NULL || ((const KaxInternalBlock &)*ForwBlock).GlobalTimecode() <= timecode) &&
(PastBlock == NULL || ((const KaxInternalBlock &)*PastBlock).GlobalTimecode() <= timecode))
Block.simpleblock->SetDiscardable(false);
else
Block.simpleblock->SetDiscardable(true);
}
}
else
#endif
if (ReplaceSimpleByGroup())
bResult = Block.group->AddFrame(track, timecode, buffer, PastBlock, ForwBlock, lacing);
return bResult;
}
void KaxBlockBlob::SetParent(KaxCluster & parent_clust)
{
ParentCluster = &parent_clust;
}
void KaxBlockBlob::SetBlockDuration(uint64 TimeLength)
{
if (ReplaceSimpleByGroup())
Block.group->SetBlockDuration(TimeLength);
}
bool KaxBlockBlob::ReplaceSimpleByGroup()
{
if (SimpleBlockMode== BLOCK_BLOB_ALWAYS_SIMPLE)
return false;
if (!bUseSimpleBlock) {
if (Block.group == NULL) {
Block.group = new KaxBlockGroup();
}
}
#if MATROSKA_VERSION >= 2
else {
if (Block.simpleblock != NULL) {
KaxSimpleBlock *old_simpleblock = Block.simpleblock;
Block.group = new KaxBlockGroup();
// _TODO_ : move all the data to the blockgroup
assert(false);
// -> while(frame) AddFrame(myBuffer)
delete old_simpleblock;
} else {
Block.group = new KaxBlockGroup();
}
}
#endif
if (ParentCluster != NULL)
Block.group->SetParent(*ParentCluster);
bUseSimpleBlock = false;
return true;
}
void KaxBlockBlob::SetBlockGroup( KaxBlockGroup &BlockRef )
{
assert(!bUseSimpleBlock);
Block.group = &BlockRef;
}
filepos_t KaxBlockVirtual::ReadData(IOCallback & input, ScopeMode /* ReadFully */)
{
input.setFilePointer(SizePosition + CodedSizeLength(Size, SizeLength, bSizeIsFinite) + Size, seek_beginning);
return GetSize();
}
END_LIBMATROSKA_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1811_1 |
crossvul-cpp_data_bad_2487_0 | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeLibraryPch.h"
#include "Types/PathTypeHandler.h"
#include "Types/SpreadArgument.h"
namespace Js
{
// Make sure EmptySegment points to read-only memory.
// Can't do this the easy way because SparseArraySegment has a constructor...
static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
// col0 : allocation bucket
// col1 : No. of missing items to set during initialization depending on bucket.
// col2 : allocation size for elements in given bucket.
// col1 and col2 is calculated at runtime
uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
{ 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
{ 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
{ 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
};
#if defined(_M_X64_OR_ARM64)
const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{2, 0, 0},
{6, 0, 0},
{8, 0, 0},
};
uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{4, 0, 0},
{6, 0, 0},
{8, 0, 0},
};
#else
const Var JavascriptArray::MissingItem = (Var)0x80000002;
uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{ 3, 0, 0 },
{ 7, 0, 0 },
{ 8, 0, 0 },
};
uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
{
// See comments above on how to read this
{ 4, 0, 0 },
{ 8, 0, 0 },
};
#endif
const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
// Allocate enough space for 4 inline property slots and 16 inline element slots
const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
SegmentBTree::SegmentBTree()
: segmentCount(0),
segments(NULL),
keys(NULL),
children(NULL)
{
}
uint32 SegmentBTree::GetLazyCrossOverLimit()
{
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.DisableArrayBTree)
{
return Js::JavascriptArray::InvalidIndex;
}
else if (Js::Configuration::Global.flags.ForceArrayBTree)
{
return ARRAY_CROSSOVER_FOR_VALIDATE;
}
#endif
#ifdef VALIDATE_ARRAY
if (Js::Configuration::Global.flags.ArrayValidate)
{
return ARRAY_CROSSOVER_FOR_VALIDATE;
}
#endif
return SegmentBTree::MinDegree * 3;
}
BOOL SegmentBTree::IsLeaf() const
{
return children == NULL;
}
BOOL SegmentBTree::IsFullNode() const
{
return segmentCount == MaxKeys;
}
void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
{
uint32 i = 0;
for(; i < node->segmentCount; i++)
{
Assert(node->keys[i] == node->segments[i]->left);
if (itemIndex < node->keys[i])
{
break;
}
}
// i indicates the 1st segment in the node past any matching segment.
// the i'th child is the children to the 'left' of the i'th segment.
// If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
if (matches)
{
// Find prev segment
if (node->IsLeaf())
{
if (i > 1)
{
// Previous is either sibling or set in a parent
prev = node->segments[i-2];
}
}
else
{
// prev is the right most leaf in children[i-1] tree
SegmentBTree* child = &node->children[i - 1];
while (!child->IsLeaf())
{
child = &child->children[child->segmentCount];
}
prev = child->segments[child->segmentCount - 1];
}
// Return the matching segment
matchOrNext = node->segments[i-1];
}
else // itemIndex in between segment i-1 and i
{
if (i > 0)
{
// Store in previous in case a match or next is the first segment in a child.
prev = node->segments[i-1];
}
if (node->IsLeaf())
{
matchOrNext = (i == 0 ? node->segments[0] : prev->next);
}
else
{
InternalFind(node->children + i, itemIndex, prev, matchOrNext);
}
}
}
void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
{
prev = matchOrNext = NULL;
InternalFind(this, itemIndex, prev, matchOrNext);
Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
}
void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
{
if (IsFullNode())
{
SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
children[0] = *this;
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
this->segmentCount = 0;
this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
this->children = children;
// This split is the only way the tree gets deeper
SplitChild(recycler, this, 0, &children[0]);
}
InsertNonFullNode(recycler, this, newSeg);
}
void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
{
// Find old segment
uint32 itemIndex = originalKey;
uint32 i = 0;
for(; i < segmentCount; i++)
{
Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
if (itemIndex < keys[i])
{
break;
}
}
// i is 1 past any match
if (i > 0)
{
if (oldSeg == segments[i-1])
{
segments[i-1] = newSeg;
keys[i-1] = newSeg->left;
return;
}
}
Assert(!IsLeaf());
children[i].SwapSegment(originalKey, oldSeg, newSeg);
}
void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
{
// Split child in two, move it's median key up to parent, and put the result of the split
// on either side of the key moved up into parent
Assert(child != NULL);
Assert(parent != NULL);
Assert(!parent->IsFullNode());
Assert(child->IsFullNode());
SegmentBTree newNode;
newNode.segmentCount = MinKeys;
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
// Move the keys above the median into the new node
for(uint32 i = 0; i < MinKeys; i++)
{
newNode.segments[i] = child->segments[i+MinDegree];
newNode.keys[i] = child->keys[i+MinDegree];
// Do not leave false positive references around in the b-tree
child->segments[i+MinDegree] = NULL;
}
// If children exist move those as well.
if (!child->IsLeaf())
{
newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
for(uint32 j = 0; j < MinDegree; j++)
{
newNode.children[j] = child->children[j+MinDegree];
// Do not leave false positive references around in the b-tree
child->children[j+MinDegree].segments = NULL;
child->children[j+MinDegree].children = NULL;
}
}
child->segmentCount = MinKeys;
// Make room for the new child in parent
for(uint32 j = parent->segmentCount; j > iChild; j--)
{
parent->children[j+1] = parent->children[j];
}
// Copy the contents of the new node into the correct place in the parent's child array
parent->children[iChild+1] = newNode;
// Move the keys to make room for the median key
for(uint32 k = parent->segmentCount; k > iChild; k--)
{
parent->segments[k] = parent->segments[k-1];
parent->keys[k] = parent->keys[k-1];
}
// Move the median key into the proper place in the parent node
parent->segments[iChild] = child->segments[MinKeys];
parent->keys[iChild] = child->keys[MinKeys];
// Do not leave false positive references around in the b-tree
child->segments[MinKeys] = NULL;
parent->segmentCount++;
}
void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
{
Assert(!node->IsFullNode());
AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
Assert(newSeg != NULL);
if (node->IsLeaf())
{
// Move the keys
uint32 i = node->segmentCount - 1;
while( (i != -1) && (newSeg->left < node->keys[i]))
{
node->segments[i+1] = node->segments[i];
node->keys[i+1] = node->keys[i];
i--;
}
if (!node->segments)
{
// Even though the segments point to a GC pointer, the main array should keep a references
// as well. So just make it a leaf allocation
node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
}
node->segments[i + 1] = newSeg;
node->keys[i + 1] = newSeg->left;
node->segmentCount++;
}
else
{
// find the correct child node
uint32 i = node->segmentCount-1;
while((i != -1) && (newSeg->left < node->keys[i]))
{
i--;
}
i++;
// Make room if full
if(node->children[i].IsFullNode())
{
// This split doesn't make the tree any deeper as node already has children.
SplitChild(recycler, node, i, node->children+i);
Assert(node->keys[i] == node->segments[i]->left);
if (newSeg->left > node->keys[i])
{
i++;
}
}
InsertNonFullNode(recycler, node->children+i, newSeg);
}
}
inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
{
if (IsThrowTypeError(operationSucceeded))
{
ThrowTypeErrorOnFailure();
}
}
inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
{
JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
}
inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
{
return !operationSucceeded;
}
// Make sure EmptySegment points to read-only memory.
// Can't do this the easy way because SparseArraySegment has a constructor...
JavascriptArray::JavascriptArray(DynamicType * type)
: ArrayObject(type, false, 0)
{
Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
}
JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
: ArrayObject(type, false, length)
{
Assert(JavascriptArray::Is(type->GetTypeId()));
Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
}
JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
: ArrayObject(type, false, length)
{
Assert(type->GetTypeId() == TypeIds_Array);
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
: ArrayObject(type, false)
{
InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
head->size = size;
Var fill = Js::JavascriptArray::MissingItem;
for (uint i = 0; i < size; i++)
{
((SparseArraySegment<Var>*)head)->elements[i] = fill;
}
}
JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
: JavascriptNativeArray(type)
{
Assert(type->GetTypeId() == TypeIds_NativeIntArray);
this->length = length;
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
: JavascriptNativeArray(type)
{
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
head->size = size;
((SparseArraySegment<int32>*)head)->FillSegmentBuffer(0, size);
}
JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
: JavascriptNativeArray(type)
{
Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
this->length = length;
Recycler* recycler = GetRecycler();
SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
}
JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
: JavascriptNativeArray(type)
{
SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
head->size = size;
((SparseArraySegment<double>*)head)->FillSegmentBuffer(0, size);
}
bool JavascriptArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptArray::Is(typeId);
}
bool JavascriptArray::Is(TypeId typeId)
{
return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
}
bool JavascriptArray::IsVarArray(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptArray::IsVarArray(typeId);
}
bool JavascriptArray::IsVarArray(TypeId typeId)
{
return typeId == TypeIds_Array;
}
template<typename T>
bool JavascriptArray::IsMissingItemAt(uint32 index) const
{
SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)this->head;
return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
}
bool JavascriptArray::IsMissingItem(uint32 index)
{
bool isIntArray = false, isFloatArray = false;
this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
if (isIntArray)
{
return IsMissingItemAt<int32>(index);
}
else if (isFloatArray)
{
return IsMissingItemAt<double>(index);
}
else
{
return IsMissingItemAt<Var>(index);
}
}
JavascriptArray* JavascriptArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
}
// Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
{
AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
}
// Check if a Var is a direct-accessible (fast path) JavascriptArray.
bool JavascriptArray::IsDirectAccessArray(Var aValue)
{
return RecyclableObject::Is(aValue) &&
(VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
}
DynamicObjectFlags JavascriptArray::GetFlags() const
{
return GetArrayFlags();
}
DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
{
return GetArrayFlags_Unchecked();
}
void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
{
SetArrayFlags(flags);
}
DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetArrayType();
}
JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
{
bool isObjectWithArray;
TypeId arrayTypeId;
return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
}
JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
const Var var,
bool *const isObjectWithArrayRef,
TypeId *const arrayTypeIdRef)
{
// This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
// (see Lowerer::GenerateArrayTest) to minimize bailouts.
Assert(var);
Assert(isObjectWithArrayRef);
Assert(arrayTypeIdRef);
*isObjectWithArrayRef = false;
*arrayTypeIdRef = TypeIds_Undefined;
if(!RecyclableObject::Is(var))
{
return nullptr;
}
JavascriptArray *array = nullptr;
INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
if(vtable == VirtualTableInfo<DynamicObject>::Address)
{
ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
if(!array)
{
return nullptr;
}
*isObjectWithArrayRef = true;
vtable = VirtualTableInfoBase::GetVirtualTable(array);
}
if(vtable == VirtualTableInfo<JavascriptArray>::Address)
{
*arrayTypeIdRef = TypeIds_Array;
}
else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
{
*arrayTypeIdRef = TypeIds_NativeIntArray;
}
else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
{
*arrayTypeIdRef = TypeIds_NativeFloatArray;
}
else
{
return nullptr;
}
if(!array)
{
array = FromVar(var);
}
return array;
}
const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
{
// This is a helper function used by jitted code
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
return array ? array->head : nullptr;
}
uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
{
// This is a helper function used by jitted code
return headSegment ? headSegment->length : 0;
}
bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
const SparseArraySegmentBase *const headSegmentBeforeOperation,
const uint32 headSegmentLengthBeforeOperation,
const Var varAfterOperation)
{
// This is a helper function used by jitted code
Assert(varAfterOperation);
if(!headSegmentBeforeOperation)
{
return false;
}
const SparseArraySegmentBase *const headSegmentAfterOperation =
Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
return
headSegmentAfterOperation != headSegmentBeforeOperation ||
headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
}
uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
{
// This is a helper function used by jitted code
bool isObjectWithArray;
TypeId arrayTypeId;
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
return array && !isObjectWithArray ? array->GetLength() : 0;
}
bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
{
// This is a helper function used by jitted code
return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
}
DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
{
// This is a helper function used by jitted code
JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
}
bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
const DynamicObjectFlags flagsBeforeOperation,
const Var varAfterOperation)
{
// This is a helper function used by jitted code
Assert(varAfterOperation);
return
!!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
!(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
}
bool JavascriptArray::HasNoMissingValues() const
{
return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
}
bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
{
return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
}
void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
{
SetFlags(
hasNoMissingValues
? GetFlags() | DynamicObjectFlags::HasNoMissingValues
: GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
}
template<class T>
bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
{
Assert(index < head->length);
return SparseArraySegment<T>::IsMissingItem(&static_cast<SparseArraySegment<T> *>(head)->elements[index]);
}
bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<Var>(index);
}
#if ENABLE_COPYONACCESS_ARRAY
void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
{
Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
#if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
{
Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
Output::Flush();
}
#endif
newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
this->SetHeadAndLastUsedSegment(newSeg);
VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
{
arrayInfo->isNotCopyOnAccessArray = 1;
}
}
uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
{
if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
{
return Js::JavascriptArray::InvalidIndex;
}
else if (index == Js::JavascriptArray::InvalidIndex)
{
return 0;
}
else
{
return index + 1;
}
}
BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
{
Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
{
return FALSE;
}
else
{
*outVal = seg->elements[index];
return TRUE;
}
}
#endif
bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<int32>(index);
}
bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
{
return IsMissingHeadSegmentItemImpl<double>(index);
}
template<typename T>
void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const T& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
{
RecyclableObject* prototype = srcArray->GetPrototype();
while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
T n = dstIndex + (index - start);
dstArray->DirectSetItemAt(n, value);
count++;
});
prototype = prototype->GetPrototype();
}
}
template<>
void JavascriptArray::InternalFillFromPrototype<uint32>(JavascriptArray *dstArray, const uint32& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
{
RecyclableObject* prototype = srcArray->GetPrototype();
while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
uint32 n = dstIndex + (index - start);
dstArray->SetItem(n, value, PropertyOperation_None);
count++;
});
prototype = prototype->GetPrototype();
}
}
/* static */
bool JavascriptArray::HasInlineHeadSegment(uint32 length)
{
return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
}
Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
}
Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(elementCount <= head->length);
js_memcpy_s(head->elements, sizeof(Var) * head->length, elements, sizeof(Var) * elementCount);
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return arr;
}
Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
{
// Called only to create array literals: size is known.
JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
array->SetHasNoMissingValues(false);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)array->head;
head->FillSegmentBuffer(0, elementCount);
return array;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
return arr;
}
#endif
Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
{
uint32 count = ints->count;
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
}
return arr;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
// Called only to create array literals: size is known.
uint32 count = ints->count;
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary *lib = scriptContext->GetLibrary();
FunctionBody *functionBody = weakFuncRef->Get();
if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
{
Assert(lib->cacheForCopyOnAccessArraySegments);
arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
}
else
#endif
{
arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
SparseArraySegment<int32> *head = static_cast<SparseArraySegment<int32>*>(arr->head);
Assert(count > 0 && count == head->length);
js_memcpy_s(head->elements, sizeof(int32)* head->length, ints->elements, sizeof(int32)* count);
}
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
head->elements[i] = (double)ints->elements[i];
}
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return OP_NewScIntArray(ints, scriptContext);
}
#endif
Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
{
uint32 count = doubles->count;
JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
Assert(count > 0 && count == head->length);
for (uint i = 0; i < count; i++)
{
double dval = doubles->elements[i];
int32 ival;
if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
{
head->elements[i] = TaggedInt::ToVarUnchecked(ival);
}
else
{
head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
}
}
return arr;
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
// Called only to create array literals: size is known.
if (arrayInfo->IsNativeFloatArray())
{
arrayInfo->SetIsNotNativeIntArray();
uint32 count = doubles->count;
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
Assert(count > 0 && count == head->length);
js_memcpy_s(head->elements, sizeof(double) * head->length, doubles->elements, sizeof(double) * count);
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return OP_NewScFltArray(doubles, scriptContext);
}
Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
Assert(JavascriptFunction::Is(function) &&
JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
Assert(callInfo.Count >= 2);
ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(elementCount);
}
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(uvalue);
}
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
if (arrayInfo && arrayInfo->IsNativeArray())
{
if (arrayInfo->IsNativeIntArray())
{
pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
}
else
{
pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
}
}
else
{
pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
}
pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
#endif
Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
{
// Call to new Array(), possibly under another name.
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
// SkipDefaultNewObject function flag should have prevented the default object
// being created, except when call true a host dispatch.
const CallInfo &callInfo = args.Info;
Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
|| JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
ScriptContext* scriptContext = function->GetScriptContext();
JavascriptArray* pNew = nullptr;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
return isCtorSuperCall ?
JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
pNew;
}
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = CreateArrayFromConstructor(function, 1, scriptContext);
JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
// If we were passed an uninitialized JavascriptArray as the this argument,
// we need to set the length. We must do this _after_ setting the first
// element as the array may have side effects such as a setter for property
// named '0' which would make the previous length of the array observable.
// If we weren't passed a JavascriptArray as the this argument, this is no-op.
pNew->SetLength(1);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return isCtorSuperCall ?
JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
pNew;
}
JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
{
JavascriptLibrary* library = constructor->GetLibrary();
// Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
// Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
// This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
// constructor.
return library->CreateArray(length);
}
JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
{
JavascriptLibrary* library = constructor->GetLibrary();
return library->CreateArray();
}
#if ENABLE_PROFILE_INFO
Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
{
Assert(JavascriptFunction::Is(function) &&
JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
if (arrayInfo->IsNativeIntArray())
{
JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
if (arrayInfo->IsNativeFloatArray())
{
JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
return arr;
}
return scriptContext->GetLibrary()->CreateArray();
}
#endif
Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
{
Assert(!PHASE_OFF1(NativeArrayPhase));
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
const CallInfo &callInfo = args.Info;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
return function->GetLibrary()->CreateNativeIntArray();
}
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
return NewInstance(function, args);
}
Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
{
Assert(!PHASE_OFF1(NativeArrayPhase));
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
const CallInfo &callInfo = args.Info;
if (callInfo.Count < 2)
{
// No arguments passed to Array(), so create with the default size (0).
return function->GetLibrary()->CreateNativeFloatArray();
}
JavascriptArray* pNew = nullptr;
if (callInfo.Count == 2)
{
// Exactly one argument, which is the array length if it's a uint32.
Var firstArgument = args[1];
int elementCount;
if (TaggedInt::Is(firstArgument))
{
elementCount = TaggedInt::ToInt32(firstArgument);
if (elementCount < 0)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
{
// Non-tagged-int number: make sure the double value is really a uint32.
double value = JavascriptNumber::GetValue(firstArgument);
uint32 uvalue = JavascriptConversion::ToUInt32(value);
if (value != uvalue)
{
JavascriptError::ThrowRangeError(
function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
}
pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
}
else
{
//
// First element is not int/double
// create an array of length 1.
// Set first element as the passed Var
//
pNew = function->GetLibrary()->CreateArray(1);
pNew->DirectSetItemAt<Var>(0, firstArgument);
}
}
else
{
// Called with a list of initial element values.
// Create an array of the appropriate length and walk the list.
JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
}
#ifdef VALIDATE_ARRAY
pNew->ValidateArray();
#endif
return pNew;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
bool isTaggedInt = TaggedInt::Is(item);
bool isTaggedIntMissingValue = false;
#ifdef _M_AMD64
if (isTaggedInt)
{
int32 iValue = TaggedInt::ToInt32(item);
isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
}
#endif
if (isTaggedInt && !isTaggedIntMissingValue)
{
// This is taggedInt case and we verified that item is not missing value in AMD64.
this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
}
else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
{
double dvalue = JavascriptNumber::GetValue(item);
int32 ivalue;
if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
{
this->DirectSetItemAt(i, ivalue);
}
else
{
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeIntArray();
}
#endif
if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
{
// Avoid shrinking the number of elements in the head segment. We can still create a new
// array here, so go ahead.
JavascriptNativeFloatArray *fArr =
this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
}
JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
fArr->DirectSetItemAt(i, dvalue);
#if ENABLE_PROFILE_INFO
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
#else
return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
#endif
}
}
else
{
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeArray();
}
#endif
#pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
{
// Avoid shrinking the number of elements in the head segment. We can still create a new
// array here, so go ahead.
JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
return arr->JavascriptArray::FillFromArgs(length, 0, args);
}
JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
#if ENABLE_PROFILE_INFO
return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
#else
return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
#endif
}
}
return this;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
if (TaggedInt::Is(item))
{
this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
{
this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
}
else
{
JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
#if ENABLE_PROFILE_INFO
if (arrayInfo)
{
arrayInfo->SetIsNotNativeArray();
}
return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
#else
return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
#endif
}
}
return this;
}
#if ENABLE_PROFILE_INFO
JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
#else
JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
#endif
{
uint32 i;
for (i = start; i < length; i++)
{
Var item = args[i + 1];
this->DirectSetItemAt(i, item);
}
return this;
}
DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetNativeIntArrayType();
}
#if ENABLE_COPYONACCESS_ARRAY
DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
}
#endif
JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(intArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Float array"));
Output::Flush();
}
#endif
arrayInfo->SetIsNotNativeIntArray();
}
#endif
// Grow the segments
ScriptContext *scriptContext = intArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = intArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
int i;
int32 ival;
// The old segment will have size/2 and length capped by the new size.
seg->size >>= 1;
if (seg == intArray->head || seg->length > (seg->size >>= 1))
{
// Some live elements are being pushed out of this segment, so allocate a new one.
SparseArraySegment<double> *newSeg =
SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
Assert(newSeg != nullptr);
Assert((prevSeg == nullptr) == (seg == intArray->head));
newSeg->next = nextSeg;
intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
if (intArray->GetLastUsedSegment() == seg)
{
intArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = intArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
// Fill the new segment with the overflow.
for (i = 0; (uint)i < newSeg->length; i++)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
if (ival == JavascriptNativeIntArray::MissingItem)
{
continue;
}
newSeg->elements[i] = (double)ival;
}
}
else
{
// Now convert the contents that will remain in the old segment.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
}
else
{
((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
}
}
prevSeg = seg;
}
}
if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
{
intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
else
{
if (intArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
}
else
{
intArray->ChangeType();
}
}
intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
}
if (CrossSite::IsCrossSiteObjectTyped(intArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
}
return (JavascriptNativeFloatArray*)intArray;
}
/*
* JavascriptArray::ChangeArrayTypeToNativeArray<double>
* - Converts the Var Array's type to NativeFloat.
* - Sets the VirtualTable to "JavascriptNativeFloatArray"
*/
template<>
void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
{
varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
else
{
if (varArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
}
else
{
varArray->ChangeType();
}
}
varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
}
if (CrossSite::IsCrossSiteObjectTyped(varArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
}
else
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
}
}
/*
* JavascriptArray::ChangeArrayTypeToNativeArray<int32>
* - Converts the Var Array's type to NativeInt.
* - Sets the VirtualTable to "JavascriptNativeIntArray"
*/
template<>
void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
{
varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
}
else
{
if (varArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
}
else
{
varArray->ChangeType();
}
}
varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
}
if (CrossSite::IsCrossSiteObjectTyped(varArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
}
else
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
}
}
template<>
int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
{
return JavascriptConversion::ToInt32(ival, scriptContext);
}
template <>
double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
{
return JavascriptConversion::ToNumber(ival, scriptContext);
}
/*
* JavascriptArray::ConvertToNativeArrayInPlace
* In place conversion of all Var elements to Native Int/Double elements in an array.
* We do not update the DynamicProfileInfo of the array here.
*/
template<typename NativeArrayType, typename T>
NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
{
AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
ScriptContext *scriptContext = varArray->GetScriptContext();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = varArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
int i;
Var ival;
uint32 growFactor = sizeof(Var) / sizeof(T);
AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
// Now convert the contents that will remain in the old segment.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<Var>*)seg)->elements[i];
if (ival == JavascriptArray::MissingItem)
{
((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
}
else
{
((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
}
}
prevSeg = seg;
}
// Update the type of the Array
ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
return (NativeArrayType*)varArray;
}
JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
#endif
ScriptContext *scriptContext = intArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = intArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
uint32 size = seg->size;
if (size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
int i;
int32 ival;
// Shrink?
uint32 growFactor = sizeof(Var) / sizeof(int32);
if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size /= growFactor))) ||
(seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
{
// Some live elements are being pushed out of this segment, so allocate a new one.
// And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
SparseArraySegment<Var> *newSeg =
SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
AnalysisAssert(newSeg);
Assert((prevSeg == nullptr) == (seg == intArray->head));
newSeg->next = nextSeg;
intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
if (intArray->GetLastUsedSegment() == seg)
{
intArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = intArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
// Fill the new segment with the overflow.
for (i = 0; (uint)i < newSeg->length; i++)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
continue;
}
newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
}
}
else
{
// Now convert the contents that will remain in the old segment.
// Walk backward in case we're growing the element size.
for (i = seg->length - 1; i >= 0; i--)
{
ival = ((SparseArraySegment<int32>*)seg)->elements[i];
if (ival == JavascriptNativeIntArray::MissingItem)
{
((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
}
else
{
((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
}
}
prevSeg = seg;
}
}
if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
{
intArray->type = scriptContext->GetLibrary()->GetArrayType();
}
else
{
if (intArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
}
else
{
intArray->ChangeType();
}
}
intArray->GetType()->SetTypeId(TypeIds_Array);
}
if (CrossSite::IsCrossSiteObjectTyped(intArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
}
return intArray;
}
JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(intArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Int array to Var array"));
Output::Flush();
}
#endif
arrayInfo->SetIsNotNativeArray();
}
#endif
intArray->ClearArrayCallSiteIndex();
return ConvertToVarArray(intArray);
}
DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
{
return scriptContext->GetLibrary()->GetNativeFloatArrayType();
}
/*
* JavascriptNativeFloatArray::ConvertToVarArray
* This function only converts all Float elements to Var elements in an array.
* DynamicProfileInfo of the array is not updated in this function.
*/
JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
{
// We can't be growing the size of the element.
Assert(sizeof(double) >= sizeof(Var));
uint32 shrinkFactor = sizeof(double) / sizeof(Var);
ScriptContext *scriptContext = fArray->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
for (seg = fArray->head; seg; seg = nextSeg)
{
nextSeg = seg->next;
if (seg->size == 0)
{
continue;
}
uint32 left = seg->left;
uint32 length = seg->length;
SparseArraySegment<Var> *newSeg;
if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
{
// The old segment is not scanned by the recycler, so we need a new one to hold vars.
newSeg =
SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
Assert((prevSeg == nullptr) == (seg == fArray->head));
newSeg->next = nextSeg;
fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
if (fArray->GetLastUsedSegment() == seg)
{
fArray->SetLastUsedSegment(newSeg);
}
prevSeg = newSeg;
SegmentBTree * segmentMap = fArray->GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(left, seg, newSeg);
}
}
else
{
newSeg = (SparseArraySegment<Var>*)seg;
prevSeg = seg;
if (shrinkFactor != 1)
{
uint32 newSize = seg->size * shrinkFactor;
uint32 limit;
if (seg->next)
{
limit = seg->next->left;
}
else
{
limit = JavascriptArray::MaxArrayLength;
}
seg->size = min(newSize, limit - seg->left);
}
}
uint32 i;
for (i = 0; i < seg->length; i++)
{
if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
{
if (seg == newSeg)
{
newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
}
Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
}
else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
{
newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
}
else
{
int32 ival;
double dval = ((SparseArraySegment<double>*)seg)->elements[i];
if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
{
newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
}
else
{
newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
}
}
}
if (seg == newSeg && shrinkFactor != 1)
{
// Fill the remaining slots.
newSeg->FillSegmentBuffer(i, seg->size);
}
}
if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
{
fArray->type = scriptContext->GetLibrary()->GetArrayType();
}
else
{
if (fArray->GetDynamicType()->GetIsLocked())
{
DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
if (typeHandler->IsPathTypeHandler())
{
// We can't allow a type with the new type ID to be promoted to the old type.
// So go to a dictionary type handler, which will orphan the new type.
// This should be a corner case, so the inability to share the new type is unlikely to matter.
// If it does matter, try building a path from the new type's built-in root.
static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
}
else
{
fArray->ChangeType();
}
}
fArray->GetType()->SetTypeId(TypeIds_Array);
}
if (CrossSite::IsCrossSiteObjectTyped(fArray))
{
Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
}
else
{
Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
}
return fArray;
}
JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
{
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
if (arrayInfo)
{
#if DBG
Js::JavascriptStackWalker walker(fArray->GetScriptContext());
Js::JavascriptFunction* caller = NULL;
bool foundScriptCaller = false;
while(walker.GetCaller(&caller))
{
if(caller != NULL && Js::ScriptFunction::Is(caller))
{
foundScriptCaller = true;
break;
}
}
if(foundScriptCaller)
{
Assert(caller);
Assert(caller->GetFunctionBody());
if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
{
Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
Output::Flush();
}
}
else
{
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
Output::Flush();
}
}
#else
if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
{
Output::Print(_u("Conversion: Float array to Var array"));
Output::Flush();
}
#endif
if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
{
Assert(!arrayInfo->IsNativeIntArray());
}
arrayInfo->SetIsNotNativeArray();
}
#endif
fArray->ClearArrayCallSiteIndex();
return ConvertToVarArray(fArray);
}
// Convert Var to index in the Array.
// Note: Spec calls out a few rules for these parameters:
// 1. if (arg > length) { return length; }
// clamp to length, not length-1
// 2. if (arg < 0) { return max(0, length + arg); }
// treat negative arg as index from the end of the array (with -1 mapping to length-1)
// Effectively, this function will return a value between 0 and length, inclusive.
int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
{
int64 index;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue < 0)
{
index = max<int64>(0, length + intValue);
}
else
{
index = intValue;
}
if (index > length)
{
index = length;
}
}
else
{
double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
// Handle the Number.POSITIVE_INFINITY case
if (doubleValue > length)
{
return length;
}
index = NumberUtilities::TryToInt64(doubleValue);
if (index < 0)
{
index = max<int64>(0, index + length);
}
}
return index;
}
TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
{
int32 iValue;
double dValue;
TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
if (typeId == TypeIds_NativeIntArray)
{
arr->SetArrayLiteralItem(index, iValue);
}
else if (typeId == TypeIds_NativeFloatArray)
{
arr->SetArrayLiteralItem(index, dValue);
}
else
{
arr->SetArrayLiteralItem(index, value);
}
return typeId;
}
TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
{
double dValue;
TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
if (typeId == TypeIds_NativeFloatArray)
{
arr->SetArrayLiteralItem(index, dValue);
}
else
{
arr->SetArrayLiteralItem(index, value);
}
return typeId;
}
template<typename T>
void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
{
SparseArraySegment<T> * segment = (SparseArraySegment<T>*)this->head;
Assert(segment->left == 0);
Assert(index < segment->length);
segment->elements[index] = value;
}
void JavascriptNativeIntArray::SetIsPrototype()
{
// Force the array to be non-native to simplify inspection, filling from proto, etc.
ToVarArray(this);
__super::SetIsPrototype();
}
void JavascriptNativeFloatArray::SetIsPrototype()
{
// Force the array to be non-native to simplify inspection, filling from proto, etc.
ToVarArray(this);
__super::SetIsPrototype();
}
#if ENABLE_PROFILE_INFO
ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
{
RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
if (weakRef)
{
FunctionBody *functionBody = weakRef->Get();
if (functionBody)
{
if (functionBody->HasDynamicProfileInfo())
{
Js::ProfileId profileId = this->GetArrayCallSiteIndex();
if (profileId < functionBody->GetProfiledArrayCallSiteCount())
{
return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
}
}
}
else
{
this->ClearArrayCallSiteIndex();
}
}
return nullptr;
}
void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
{
Assert(weakRef);
FunctionBody *functionBody = weakRef->Get();
if (functionBody && functionBody->HasDynamicProfileInfo())
{
ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
Assert(index < functionBody->GetProfiledArrayCallSiteCount());
SetArrayCallSite(index, weakRef);
}
}
void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
{
if (baseArray->weakRefToFuncBody)
{
if (baseArray->weakRefToFuncBody->Get())
{
SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
}
else
{
baseArray->ClearArrayCallSiteIndex();
}
}
}
#endif
Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
{
if (JavascriptNativeIntArray::Is(this))
{
return this->FindMinOrMax<int32, false>(scriptContext, findMax);
}
else
{
return this->FindMinOrMax<double, true>(scriptContext, findMax);
}
}
template <typename T, bool checkNaNAndNegZero>
Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
{
AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
uint len = this->GetLength();
Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
uint headSegLen = headSegment->length;
Assert(headSegLen == len);
if (headSegment->next == nullptr)
{
T currentRes = headSegment->elements[0];
for (uint i = 0; i < headSegLen; i++)
{
T compare = headSegment->elements[i];
if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
{
return scriptContext->GetLibrary()->GetNaN();
}
if (findMax ? currentRes < compare : currentRes > compare ||
(checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
{
currentRes = compare;
}
}
return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
}
else
{
AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
Throw::FatalInternalError();
}
}
SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
{
return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot->lastUsedSegment : segmentUnion.lastUsedSegment);
}
void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
{
Assert(!HasSegmentMap());
this->head = this->segmentUnion.lastUsedSegment = segment;
}
void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
{
if (HasSegmentMap())
{
this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
}
else
{
this->segmentUnion.lastUsedSegment = segment;
}
}
bool JavascriptArray::HasSegmentMap() const
{
return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
}
SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
{
return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
}
void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
{
Assert(!HasSegmentMap());
SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
segmentUnion.segmentBTreeRoot = segmentMap;
segmentMap->lastUsedSegment = lastUsedSeg;
}
void JavascriptArray::ClearSegmentMap()
{
if (HasSegmentMap())
{
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
segmentUnion.segmentBTreeRoot = nullptr;
segmentUnion.lastUsedSegment = lastUsedSeg;
}
}
SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
{
Recycler* recycler = GetRecycler();
SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
{
tmpSegmentMap->Add(recycler, current);
return false;
});
// There could be OOM during building segment map. Save to array only after its successful completion.
SetSegmentMap(tmpSegmentMap);
return tmpSegmentMap;
}
void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
{
SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
if (savedSegmentMap)
{
//
// We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
// array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
// if adding segment succeeds.
//
ClearSegmentMap();
savedSegmentMap->Add(recycler, seg);
SetSegmentMap(savedSegmentMap);
}
}
void JavascriptArray::InvalidateLastUsedSegment()
{
this->SetLastUsedSegment(this->head);
}
DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
{
DescriptorFlags flags;
if (GetSetterBuiltIns(propertyId, info, &flags))
{
return flags;
}
return __super::GetSetter(propertyId, setterValue, info, requestContext);
}
DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
{
DescriptorFlags flags;
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
{
return flags;
}
return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
}
bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
{
if (propertyId == PropertyIds::length)
{
PropertyValueInfo::SetNoCache(info, this);
*descriptorFlags = WritableData;
return true;
}
return false;
}
SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
{
SparseArraySegmentBase *seg = nullptr;
SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
{
seg = lastUsedSeg;
if(index - lastUsedSeg->left < lastUsedSeg->size)
{
return seg;
}
}
SegmentBTreeRoot * segmentMap = GetSegmentMap();
if(!useSegmentMap || !segmentMap)
{
return seg ? seg : this->head;
}
if(seg)
{
// If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
// segment map, as it is likely to hit
SparseArraySegmentBase *const nextSeg = seg->next;
if(nextSeg)
{
if(index < nextSeg->left)
{
return seg;
}
else if(index - nextSeg->left < nextSeg->size)
{
return nextSeg;
}
}
}
SparseArraySegmentBase *matchOrNextSeg;
segmentMap->Find(index, seg, matchOrNextSeg);
return seg ? seg : matchOrNextSeg;
}
uint32 JavascriptArray::GetNextIndex(uint32 index) const
{
if (JavascriptNativeIntArray::Is((Var)this))
{
return this->GetNextIndexHelper<int32>(index);
}
else if (JavascriptNativeFloatArray::Is((Var)this))
{
return this->GetNextIndexHelper<double>(index);
}
return this->GetNextIndexHelper<Var>(index);
}
template<typename T>
uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
{
AssertMsg(this->head, "array head should never be null");
uint candidateIndex;
if (index == JavascriptArray::InvalidIndex)
{
candidateIndex = head->left;
}
else
{
candidateIndex = index + 1;
}
SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
while (current != nullptr)
{
if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
{
for (uint i = candidateIndex - current->left; i < current->length; i++)
{
if (!SparseArraySegment<T>::IsMissingItem(¤t->elements[i]))
{
return i + current->left;
}
}
}
current = (SparseArraySegment<T>*)current->next;
if (current != NULL)
{
if (candidateIndex < current->left)
{
candidateIndex = current->left;
}
}
}
return JavascriptArray::InvalidIndex;
}
// If new length > length, we just reset the length
// If new length < length, we need to remove the rest of the elements and segment
void JavascriptArray::SetLength(uint32 newLength)
{
if (newLength == length)
return;
if (head == EmptySegment)
{
// Do nothing to the segment.
}
else if (newLength == 0)
{
this->ClearElements(head, 0);
head->length = 0;
head->next = nullptr;
SetHasNoMissingValues();
ClearSegmentMap();
this->InvalidateLastUsedSegment();
}
else if (newLength < length)
{
// _ _ 2 3 _ _ 6 7 _ _
// SetLength(0)
// 0 <= left -> set *prev = null
// SetLength(2)
// 2 <= left -> set *prev = null
// SetLength(3)
// 3 !<= left; 3 <= right -> truncate to length - 1
// SetLength(5)
// 5 <=
SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
SparseArraySegmentBase** prev = &head;
while(next != nullptr)
{
if (newLength <= next->left)
{
ClearSegmentMap(); // truncate segments, null out segmentMap
*prev = nullptr;
break;
}
else if (newLength <= (next->left + next->length))
{
if (next->next)
{
ClearSegmentMap(); // Will truncate segments, null out segmentMap
}
uint32 newSegmentLength = newLength - next->left;
this->ClearElements(next, newSegmentLength);
next->next = nullptr;
next->length = newSegmentLength;
break;
}
else
{
prev = &next->next;
next = next->next;
}
}
this->InvalidateLastUsedSegment();
}
this->length = newLength;
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
}
BOOL JavascriptArray::SetLength(Var newLength)
{
ScriptContext *scriptContext;
if(TaggedInt::Is(newLength))
{
int32 lenValue = TaggedInt::ToInt32(newLength);
if (lenValue < 0)
{
scriptContext = GetScriptContext();
if (scriptContext->GetThreadContext()->RecordImplicitException())
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
else
{
this->SetLength(lenValue);
}
return TRUE;
}
scriptContext = GetScriptContext();
uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
if (dblValue == uintValue)
{
this->SetLength(uintValue);
}
else
{
ThreadContext* threadContext = scriptContext->GetThreadContext();
ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
{
// We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
// Do nothing and let the jitted code bail out.
return TRUE;
}
if (threadContext->RecordImplicitException())
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
return TRUE;
}
void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
{
SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
}
Var JavascriptArray::DirectGetItem(uint32 index)
{
SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
{
return seg->elements[offset];
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
{
return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
int32 value = 0;
return this->DirectGetItemAt(index, &value) ? WritableData : None;
}
Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
{
SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
uint32 offset = index - seg->left;
if (index >= seg->left && offset < seg->length)
{
if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
{
return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
}
}
Var element;
if (DirectGetItemAtFull(index, &element))
{
return element;
}
return GetType()->GetLibrary()->GetUndefined();
}
Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
{
PropertyRecord const * propertyRecord;
scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
}
BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
if (this->DirectGetItemAt(index, outVal))
{
return TRUE;
}
ScriptContext* requestContext = type->GetScriptContext();
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
//
// Link prev and current. If prev is NULL, make current the head segment.
//
void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
{
if (prev)
{
prev->next = current;
}
else
{
Assert(current);
head = current;
}
}
template<typename T>
BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
{
if (itemIndex >= length)
{
return true;
}
SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
while(next != nullptr && next->left <= itemIndex)
{
uint32 limit = next->left + next->length;
if (itemIndex < limit)
{
next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
if(itemIndex - next->left == next->length - 1)
{
--next->length;
}
else if(next == head)
{
SetHasNoMissingValues(false);
}
break;
}
next = (SparseArraySegment<T>*)next->next;
}
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
return true;
}
template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
{
return idxDest.ToNumber(scriptContext);
}
template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
{
// Note this is only for setting Array length which is a uint32
return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
}
template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
{
return JavascriptNumber::ToVar(idxDest, scriptContext);
}
void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
{
if (!succeeded)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
}
}
void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
{
if (!succeeded)
{
uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
}
}
BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
{
return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
}
BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
{
ScriptContext* scriptContext = pDestObj->GetScriptContext();
if (idxDest.IsSmallIndex())
{
return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
}
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
}
template<typename T>
void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest, BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength)
{
// This never gets called.
Throw::InternalError();
}
//
// Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
//
template<typename T>
void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest, BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength)
{
JavascriptArray* pDestArray = nullptr;
if (JavascriptArray::Is(pDestObj))
{
pDestArray = JavascriptArray::FromVar(pDestObj);
}
T idxDest = startIdxDest;
for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
BOOL spreadable = false;
if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
{
// firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
// we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
// want to do the work a second time as soon as we record the length we clear the flag.
spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem);
if (!spreadable)
{
JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
++idxDest;
continue;
}
}
if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
&& BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex()) // Fast path
{
if (JavascriptNativeIntArray::Is(aItem))
{
JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
CopyNativeIntArrayElementsToVar(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else if (JavascriptNativeFloatArray::Is(aItem))
{
JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
CopyNativeFloatArrayElementsToVar(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else
{
JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
CopyArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
}
else
{
// Flatten if other array or remote array (marked with TypeIds_Array)
if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
{
//CONSIDER: enumerating remote array instead of walking all indices
BigIndex length;
if (firstPromotedItemIsSpreadable)
{
firstPromotedItemIsSpreadable = false;
length = firstPromotedItemLength;
}
else if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
// we can cast to uin64 without fear of converting negative numbers to large positive ones
// from int64 because ToLength makes negative lengths 0
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
}
if (PromoteToBigIndex(length,idxDest))
{
// This is a special case for spreadable objects. We do not pre-calculate the length
// in EntryConcat like we do with Arrays because a getProperty on an object Length
// is observable. The result is we have to check for overflows separately for
// spreadable objects and promote to a bigger index type when we find them.
ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
return;
}
if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
}
RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
Var subItem;
uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
{
if (JavascriptOperators::HasItem(itemObject, idxSubItem))
{
subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext);
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, subItem);
}
else
{
ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest);
}
}
++idxDest;
}
for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
{
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
if (JavascriptOperators::HasProperty(itemObject,propertyRecord->GetPropertyId()))
{
subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext);
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, subItem);
}
else
{
ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem);
}
}
++idxDest;
}
}
else // concat 1 item
{
JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
++idxDest;
}
}
}
if (!pDestArray)
{
pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr);
}
else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
{
pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
}
}
bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
{
return false; // already a big index
}
bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
{
::Math::RecordOverflowPolicy destLengthOverflow;
if (lhs.IsSmallIndex())
{
UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
return destLengthOverflow.HasOverflowed();
}
return true;
}
JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
{
uint idxDest = 0u;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
bool concatSpreadable = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem);
if (!JavascriptNativeIntArray::Is(pDestArray))
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pDestArray;
}
if(!concatSpreadable)
{
pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
idxDest = idxDest + 1;
if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
continue;
}
if (JavascriptNativeIntArray::Is(aItem)) // Fast path
{
JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
if (converted)
{
// Copying the last array forced a conversion, so switch over to the var version
// to finish.
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
}
else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
{
if (TaggedInt::Is(aItem))
{
pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
}
else
{
#if DBG
int32 int32Value;
Assert(
JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
!SparseArraySegment<int32>::IsMissingItem(&int32Value));
#endif
pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
}
++idxDest;
}
else
{
JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pVarDestArray;
}
}
if (pDestArray->GetLength() != idxDest)
{
pDestArray->SetLength(idxDest);
}
return pDestArray;
}
JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
{
uint idxDest = 0u;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
bool concatSpreadable = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem);
if (!JavascriptNativeFloatArray::Is(pDestArray))
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pDestArray;
}
if (!concatSpreadable)
{
pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
idxDest = idxDest + 1;
if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
{
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
continue;
}
bool converted;
if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
{
if (JavascriptNativeIntArray::Is(aItem)) // Fast path
{
JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray);
idxDest = idxDest + pIntArray->length;
}
else if (JavascriptNativeFloatArray::Is(aItem))
{
JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray);
idxDest = idxDest + pItemArray->length;
}
else
{
JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest);
return pVarDestArray;
}
if (converted)
{
// Copying the last array forced a conversion, so switch over to the var version
// to finish.
ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
return pDestArray;
}
}
else
{
if (TaggedInt::Is(aItem))
{
pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
}
else
{
Assert(JavascriptNumber::Is(aItem));
pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
}
++idxDest;
}
}
if (pDestArray->GetLength() != idxDest)
{
pDestArray->SetLength(idxDest);
}
return pDestArray;
}
bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
{
return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
}
Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
}
//
// Compute the destination ScriptArray size:
// - Each item, flattening only one level if a ScriptArray.
//
uint32 cDestLength = 0;
JavascriptArray * pDestArray = NULL;
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
bool isInt = true;
bool isFloat = true;
::Math::RecordOverflowPolicy destLengthOverflow;
for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
{
Var aItem = args[idxArg];
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
#endif
if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
{
JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
if (isFloat)
{
if (!JavascriptNativeIntArray::Is(pItemArray))
{
isInt = false;
if (!JavascriptNativeFloatArray::Is(pItemArray))
{
isFloat = false;
}
}
}
cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
}
else // Get remote array or object length
{
// We already checked for types derived from JavascriptArray. These are types that should behave like array
// i.e. proxy to array and remote array.
if (JavascriptOperators::IsArray(aItem))
{
// Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
// worth it.
isInt = false;
isFloat = false;
if (!JavascriptProxy::Is(aItem))
{
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
// clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
}
else
{
uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
}
}
remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
}
else
{
if (isFloat)
{
if (BoxConcatItem(aItem, idxArg, scriptContext))
{
// A primitive will be boxed, so we have to create a var array for the result.
isInt = false;
isFloat = false;
}
else if (!TaggedInt::Is(aItem))
{
if (!JavascriptNumber::Is(aItem))
{
isInt = false;
isFloat = false;
}
else if (isInt)
{
int32 int32Value;
if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
SparseArraySegment<int32>::IsMissingItem(&int32Value))
{
isInt = false;
}
}
}
else if(isInt)
{
int32 int32Value = TaggedInt::ToInt32(aItem);
if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
{
isInt = false;
}
}
}
remoteTypeIds[idxArg] = TypeIds_Limit;
cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
}
}
}
if (destLengthOverflow.HasOverflowed())
{
cDestLength = MaxArrayLength;
isInt = false;
isFloat = false;
}
//
// Create the destination array
//
RecyclableObject* pDestObj = nullptr;
bool isArray = false;
pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext);
if (pDestObj)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
#endif
// Check the thing that species create made. If it's a native array that can't handle the source
// data, convert it. If it's a more conservative kind of array than the source data, indicate that
// so that the data will be converted on copy.
if (isInt)
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
isArray = true;
}
else
{
isInt = false;
isFloat = JavascriptNativeFloatArray::Is(pDestObj);
isArray = JavascriptArray::Is(pDestObj);
}
}
else if (isFloat)
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
isArray = true;
}
else
{
isFloat = JavascriptNativeFloatArray::Is(pDestObj);
isArray = JavascriptArray::Is(pDestObj);
}
}
else
{
if (JavascriptNativeIntArray::Is(pDestObj))
{
JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
isArray = true;
}
else if (JavascriptNativeFloatArray::Is(pDestObj))
{
JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
isArray = true;
}
else
{
isArray = JavascriptArray::Is(pDestObj);
}
}
}
if (pDestObj == nullptr || isArray)
{
if (isInt)
{
JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
pIntArray->EnsureHead<int32>();
pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext);
}
else if (isFloat)
{
JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
pFArray->EnsureHead<double>();
pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext);
}
else
{
pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
// if the constructor has changed then we no longer specialize for ints and floats
pDestArray->EnsureHead<Var>();
ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow);
}
//
// Return the new array instance.
//
#ifdef VALIDATE_ARRAY
pDestArray->ValidateArray();
#endif
return pDestArray;
}
Assert(pDestObj);
ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow);
return pDestObj;
}
void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
{
if (destLengthOverflow.HasOverflowed())
{
ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
}
else
{
// Use faster uint32 version if no overflow
ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
}
}
template<typename T>
/* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
{
if (BoxConcatItem(aItem, idxArg, scriptContext))
{
// bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
RecyclableObject* pObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
}
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, pObj);
}
else
{
SetArrayLikeObjects(pDestObj, idxDest, pObj);
}
}
else
{
if (pDestArray)
{
pDestArray->DirectSetItemAt(idxDest, aItem);
}
else
{
SetArrayLikeObjects(pDestObj, idxDest, aItem);
}
}
}
uint32 JavascriptArray::GetFromIndex(Var arg, uint32 length, ScriptContext *scriptContext)
{
uint32 fromIndex;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue >= 0)
{
fromIndex = intValue;
}
else
{
// (intValue + length) may exceed 2^31 or may be < 0, so promote to int64
fromIndex = (uint32)max(0i64, (int64)(length) + intValue);
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value > length)
{
return (uint32)-1;
}
else if (value >= 0)
{
fromIndex = (uint32)value;
}
else
{
fromIndex = (uint32)max((double)0, value + length);
}
}
return fromIndex;
}
uint64 JavascriptArray::GetFromIndex(Var arg, uint64 length, ScriptContext *scriptContext)
{
uint64 fromIndex;
if (TaggedInt::Is(arg))
{
int64 intValue = TaggedInt::ToInt64(arg);
if (intValue >= 0)
{
fromIndex = intValue;
}
else
{
fromIndex = max((int64)0, (int64)(intValue + length));
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value > length)
{
return (uint64)-1;
}
else if (value >= 0)
{
fromIndex = (uint64)value;
}
else
{
fromIndex = (uint64)max((double)0, value + length);
}
}
return fromIndex;
}
int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
{
int64 fromIndex;
if (TaggedInt::Is(arg))
{
int intValue = TaggedInt::ToInt32(arg);
if (intValue >= 0)
{
fromIndex = min<int64>(intValue, length - 1);
}
else if ((uint32)-intValue > length)
{
return length;
}
else
{
fromIndex = intValue + length;
}
}
else
{
double value = JavascriptConversion::ToInteger(arg, scriptContext);
if (value >= 0)
{
fromIndex = (int64)min(value, (double)(length - 1));
}
else if (value + length < 0)
{
return length;
}
else
{
fromIndex = (int64)(value + length);
}
}
return fromIndex;
}
// includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
// Differences
// 1. Returns boolean true or false value instead of the search hit index
// 2. Follows SameValueZero algorithm instead of StrictEquals
// 3. Missing values are scanned if the search value is undefined
template <bool includesAlgorithm>
Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
{
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
BigIndex length;
Var trueValue = scriptContext->GetLibrary()->GetTrue();
Var falseValue = scriptContext->GetLibrary()->GetFalse();
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.indexOf"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (pArr)
{
Var search;
uint32 fromIndex;
uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext);
// If we found the search value in the head segment, or if we determined there is no need to search other segments,
// we stop right here.
if (index != -1 || fromIndex == -1)
{
if (includesAlgorithm)
{
//Array.prototype.includes
return (index == -1)? falseValue : trueValue;
}
else
{
//Array.prototype.indexOf
return JavascriptNumber::ToVar(index, scriptContext);
}
}
// If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
switch (pArr->GetTypeId())
{
case Js::TypeIds_Array:
return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
case Js::TypeIds_NativeIntArray:
return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext);
case Js::TypeIds_NativeFloatArray:
return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext);
default:
AssertMsg(FALSE, "invalid array typeid");
return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
}
}
// source object is not a JavascriptArray but source could be a TypedArray
if (TypedArrayBase::Is(obj))
{
if (length.IsSmallIndex() || length.IsUint32Max())
{
Var search;
uint32 fromIndex;
uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext);
}
}
if (length.IsSmallIndex())
{
Var search;
uint32 fromIndex;
if (!GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext);
}
else
{
Var search;
uint64 fromIndex;
if (!GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex, scriptContext))
{
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetBigIndex(), scriptContext);
}
}
// Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
Var returnValue = IndexOfHelper<false>(args, scriptContext);
//IndexOfHelper code is reused for array.prototype.includes as well. Let us assert here we didn't get a true or false instead of index
Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
return returnValue;
}
Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
Var returnValue = IndexOfHelper<true>(args, scriptContext);
Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
return returnValue;
}
template<typename T>
BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
{
if (length == 0)
{
return false;
}
if (args.Info.Count > 2)
{
fromIndex = GetFromIndex(args[2], length, scriptContext);
if (fromIndex >= length)
{
return false;
}
search = args[1];
}
else
{
fromIndex = 0;
search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
}
return true;
}
template <>
BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// Note: Sometime cross site array go down this path to get the marshalling
Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
{
return FALSE;
}
return JavascriptOperators::GetItem(obj, index, element, scriptContext);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// Note: Sometime cross site array go down this path to get the marshalling
Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
&& !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
{
return FALSE;
}
*element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
return *element != scriptContext->GetLibrary()->GetUndefined();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
|| VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
}
template <>
BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <>
BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// We need to do explicit check for items since length value may not actually match the actual TypedArray length.
// User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
// Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
// we don't know whether or not length == typedArrayBase->GetLength().
if (checkHasItem && !typedArrayBase->HasItem(index))
{
return false;
}
*element = typedArrayBase->DirectGetItem(index);
return true;
}
template <>
BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
{
// This should never get called.
Assert(false);
Throw::InternalError();
}
template <bool includesAlgorithm, typename T, typename P>
Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
{
Var element = nullptr;
bool isSearchTaggedInt = TaggedInt::Is(search);
bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
Var trueValue = scriptContext->GetLibrary()->GetTrue();
Var falseValue = scriptContext->GetLibrary()->GetFalse();
//Consider: enumerating instead of walking all indices
for (P i = fromIndex; i < toIndex; i++)
{
if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
{
if (doUndefinedSearch)
{
return trueValue;
}
continue;
}
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
}
continue;
}
if (includesAlgorithm)
{
//Array.prototype.includes
if (JavascriptConversion::SameValueZero(element, search))
{
return trueValue;
}
}
else
{
//Array.prototype.indexOf
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return JavascriptNumber::ToVar(i, scriptContext);
}
}
}
return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
}
int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
// We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
// virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
// either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
Var element = head->GetElement(i);
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (search == element)
{
return i;
}
}
else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
{
//Array.prototype.includes
return i;
}
else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
//Array.prototype.indexOf
return i;
}
}
// Element not found in the head segment. Keep looking only if the range of indices extends past
// the head segment.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
template<typename T>
bool AreAllBytesEqual(T value)
{
byte* bValue = (byte*)&value;
byte firstByte = *bValue++;
for (int i = 1; i < sizeof(T); ++i)
{
if (*bValue++ != firstByte)
{
return false;
}
}
return true;
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(double* buffer, uint32 length, double value)
{
if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
{
memset(buffer, 0, sizeof(double) * length);
}
else
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(int32* buffer, uint32 length, int32 value)
{
if (value == 0 || AreAllBytesEqual(value))
{
memset(buffer, *(byte*)&value, sizeof(int32)* length);
}
else
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
}
template<>
void JavascriptArray::CopyValueToSegmentBuferNoCheck(Js::Var* buffer, uint32 length, Js::Var value)
{
for (uint32 i = 0; i < length; i++)
{
buffer[i] = value;
}
}
int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
// We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
// except when we can further optimize thanks to the knowledge that all elements in the array are int32's. This allows for two additional optimizations:
// 1. Only tagged ints or JavascriptNumbers that can be represented as int32 can be strict equal to some element in the array (all int32). Thus, if
// the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
// 2. If the search value is a number that can be represented as int32, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
// Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
int32 searchAsInt32;
if (isSearchTaggedInt)
{
searchAsInt32 = TaggedInt::ToInt32(search);
}
else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
// We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
// virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
// the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
int32 element = head->GetElement(i);
if (searchAsInt32 == element)
{
return i;
}
}
// Element not found in the head segment. Keep looking only if the range of indices extends past
// the head segment.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
{
// We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
// except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
// 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
// the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
// 2. If the search value is a number, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
// Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
{
return -1;
}
bool isSearchTaggedInt = TaggedInt::Is(search);
if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
{
// The value can't be in the array, but it could be in a prototype, and we can only guarantee that
// the head segment has no gaps.
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
// We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
// segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
// used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
{
double element = head->GetElement(i);
if (element == searchAsDouble)
{
return i;
}
//NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
if (matchNaN && JavascriptNumber::IsNan(element))
{
return i;
}
}
fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
return -1;
}
Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
}
JavascriptString* separator;
if (args.Info.Count >= 2)
{
TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
//ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
if (TypeIds_Undefined != typeId)
{
separator = JavascriptConversion::ToString(args[1], scriptContext);
}
else
{
separator = scriptContext->GetLibrary()->GetCommaDisplayString();
}
}
else
{
separator = scriptContext->GetLibrary()->GetCommaDisplayString();
}
return JoinHelper(args[0], separator, scriptContext);
}
JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
{
TypeId typeId = JavascriptOperators::GetTypeId(value);
if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
return JavascriptConversion::ToString(value, scriptContext);
}
}
JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
{
bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
Var target = NULL;
bool isTargetObjectPushed = false;
// if we are visiting a proxy object, track that we have visited the target object as well so the next time w
// call the join helper for the target of this proxy, we will return above.
if (isProxy)
{
JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
Assert(proxy);
target = proxy->GetTarget();
if (target != nullptr)
{
// If we end up joining same array, instead of going in infinite loop, return the empty string
if (scriptContext->CheckObject(target))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
scriptContext->PushObject(target);
isTargetObjectPushed = true;
}
}
}
// If we end up joining same array, instead of going in infinite loop, return the empty string
else if (scriptContext->CheckObject(thisArg))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
if (!isTargetObjectPushed)
{
scriptContext->PushObject(thisArg);
}
JavascriptString* res = nullptr;
TryFinally([&]()
{
if (isArray)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
#endif
JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
switch (arr->GetTypeId())
{
case Js::TypeIds_Array:
res = JoinArrayHelper(arr, separator, scriptContext);
break;
case Js::TypeIds_NativeIntArray:
res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext);
break;
case Js::TypeIds_NativeFloatArray:
res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext);
break;
}
}
else if (RecyclableObject::Is(thisArg))
{
res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext);
}
else
{
res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext);
}
},
[&](bool/*hasException*/)
{
Var top = scriptContext->PopObject();
if (isProxy)
{
AssertMsg(top == target, "Unmatched operation stack");
}
else
{
AssertMsg(top == thisArg, "Unmatched operation stack");
}
});
if (res == nullptr)
{
res = scriptContext->GetLibrary()->GetEmptyString();
}
return res;
}
static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
template <typename T>
JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
{
Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
const uint32 arrLength = arr->length;
switch(arrLength)
{
default:
{
CaseDefault:
bool hasSeparator = (separator->GetLength() != 0);
const charcount_t estimatedAppendCount =
min(
Join_MaxEstimatedAppendCount,
static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
CompoundString *const cs =
CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(item, scriptContext));
}
for (uint32 i = 1; i < arrLength; i++)
{
if (hasSeparator)
{
cs->Append(separator);
}
if (TryTemplatedGetItem(arr, i, &item, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(item, scriptContext));
}
}
return cs;
}
case 2:
{
bool hasSeparator = (separator->GetLength() != 0);
if(hasSeparator)
{
goto CaseDefault;
}
JavascriptString *res = nullptr;
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
res = JavascriptArray::JoinToString(item, scriptContext);
}
if (TryTemplatedGetItem(arr, 1u, &item, scriptContext))
{
JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext);
return res ? ConcatString::New(res, itemString) : itemString;
}
if(res)
{
return res;
}
goto Case0;
}
case 1:
{
Var item;
if (TemplatedGetItem(arr, 0u, &item, scriptContext))
{
return JavascriptArray::JoinToString(item, scriptContext);
}
// fall through
}
case 0:
Case0:
return scriptContext->GetLibrary()->GetEmptyString();
}
}
JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
{
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(object, scriptContext);
int64 cSrcLength = JavascriptConversion::ToLength(lenValue, scriptContext);
switch (cSrcLength)
{
default:
{
CaseDefault:
bool hasSeparator = (separator->GetLength() != 0);
const charcount_t estimatedAppendCount =
min(
Join_MaxEstimatedAppendCount,
static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
CompoundString *const cs =
CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(value, scriptContext));
}
for (uint32 i = 1; i < cSrcLength; i++)
{
if (hasSeparator)
{
cs->Append(separator);
}
if (JavascriptOperators::GetItem(object, i, &value, scriptContext))
{
cs->Append(JavascriptArray::JoinToString(value, scriptContext));
}
}
return cs;
}
case 2:
{
bool hasSeparator = (separator->GetLength() != 0);
if(hasSeparator)
{
goto CaseDefault;
}
JavascriptString *res = nullptr;
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
res = JavascriptArray::JoinToString(value, scriptContext);
}
if (JavascriptOperators::GetItem(object, 1u, &value, scriptContext))
{
JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext);
return res ? ConcatString::New(res, valueString) : valueString;
}
if(res)
{
return res;
}
goto Case0;
}
case 1:
{
Var value;
if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
{
return JavascriptArray::JoinToString(value, scriptContext);
}
// fall through
}
case 0:
Case0:
return scriptContext->GetLibrary()->GetEmptyString();
}
}
Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
Assert(!(callInfo.Flags & CallFlags_New));
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.lastIndexOf"));
}
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
Var search;
int64 fromIndex;
if (!GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext))
{
return TaggedInt::ToVarUnchecked(-1);
}
if (pArr)
{
switch (pArr->GetTypeId())
{
case Js::TypeIds_Array:
return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
case Js::TypeIds_NativeIntArray:
return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext);
case Js::TypeIds_NativeFloatArray:
return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext);
default:
AssertMsg(FALSE, "invalid array typeid");
return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
}
}
// source object is not a JavascriptArray but source could be a TypedArray
if (TypedArrayBase::Is(obj))
{
return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext);
}
return LastIndexOfHelper(obj, search, fromIndex, scriptContext);
}
// Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
{
if (length == 0)
{
return false;
}
if (args.Info.Count > 2)
{
fromIndex = GetFromLastIndex(args[2], length, scriptContext);
if (fromIndex >= length)
{
return false;
}
search = args[1];
}
else
{
search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
fromIndex = length - 1;
}
return true;
}
template <typename T>
Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
{
Var element = nullptr;
bool isSearchTaggedInt = TaggedInt::Is(search);
// First handle the indices > 2^32
while (fromIndex >= MaxArrayLength)
{
Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
{
element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return index;
}
fromIndex--;
continue;
}
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return index;
}
}
fromIndex--;
}
Assert(fromIndex < MaxArrayLength);
// fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
uint32 end = static_cast<uint32>(fromIndex);
for (uint32 i = 0; i <= end; i++)
{
uint32 index = end - i;
if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
{
continue;
}
if (isSearchTaggedInt && TaggedInt::Is(element))
{
if (element == search)
{
return JavascriptNumber::ToVar(index, scriptContext);
}
continue;
}
if (JavascriptOperators::StrictEqual(element, search, scriptContext))
{
return JavascriptNumber::ToVar(index, scriptContext);
}
}
return TaggedInt::ToVarUnchecked(-1);
}
/*
* PopWithNoDst
* - For pop calls that do not return a value, we only need to decrement the length of the array.
*/
void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
{
Assert(JavascriptNativeArray::Is(nativeArray));
JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
// we will bailout on length 0
Assert(arr->GetLength() != 0);
uint32 index = arr->GetLength() - 1;
arr->SetLength(index);
}
/*
* JavascriptNativeIntArray::Pop
* - Returns int32 value from the array.
* - Returns missing item when the element is not available in the array object.
* - It doesn't walk up the prototype chain.
* - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
* - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
*/
int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
{
Assert(JavascriptNativeIntArray::Is(object));
JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
Assert(arr->GetLength() != 0);
uint32 index = arr->length - 1;
int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
//If it is a missing item, then don't update the length - Pre-op Bail out will happen.
if(!SparseArraySegment<int32>::IsMissingItem(&element))
{
arr->SetLength(index);
}
return element;
}
/*
* JavascriptNativeFloatArray::Pop
* - Returns double value from the array.
* - Returns missing item when the element is not available in the array object.
* - It doesn't walk up the prototype chain.
* - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
* - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
*/
double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
{
Assert(JavascriptNativeFloatArray::Is(object));
JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
Assert(arr->GetLength() != 0);
uint32 index = arr->length - 1;
double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
// If it is a missing item then don't update the length - Pre-op Bail out will happen.
if(!SparseArraySegment<double>::IsMissingItem(&element))
{
arr->SetLength(index);
}
return element;
}
/*
* JavascriptArray::Pop
* - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
* - This API may cause implicit calls. Handles Array and non-array objects
*/
Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
{
if (JavascriptArray::Is(object))
{
return EntryPopJavascriptArray(scriptContext, object);
}
else
{
return EntryPopNonJavascriptArray(scriptContext, object);
}
}
Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, Var object)
{
JavascriptArray * arr = JavascriptArray::FromVar(object);
uint32 length = arr->length;
if (length == 0)
{
// If length is 0, return 'undefined'
return scriptContext->GetLibrary()->GetUndefined();
}
uint32 index = length - 1;
Var element;
if (!arr->DirectGetItemAtFull(index, &element))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
else
{
element = CrossSite::MarshalVar(scriptContext, element);
}
arr->SetLength(index); // SetLength will clear element at index
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return element;
}
Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
}
BigIndex length;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
if (length == 0u)
{
// Set length = 0
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
return scriptContext->GetLibrary()->GetUndefined();
}
BigIndex index = length;
--index;
Var element;
if (index.IsSmallIndex())
{
if (!JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
// Set the new length
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
if (!JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext))
{
element = scriptContext->GetLibrary()->GetUndefined();
}
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
// Set the new length
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
return element;
}
Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
}
if (JavascriptArray::Is(args[0]))
{
return EntryPopJavascriptArray(scriptContext, args.Values[0]);
}
else
{
return EntryPopNonJavascriptArray(scriptContext, args.Values[0]);
}
}
/*
* JavascriptNativeIntArray::Push
* Pushes Int element in a native Int Array.
* We call the generic Push, if the array is not native Int or we have a really big array.
*/
Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
{
// Handle non crossSite native int arrays here length within MaxArrayLength.
// JavascriptArray::Push will handle other cases.
if (JavascriptNativeIntArray::IsNonCrossSite(array))
{
JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
Assert(!nativeIntArray->IsCrossSiteObject());
uint32 n = nativeIntArray->length;
if(n < JavascriptArray::MaxArrayLength)
{
nativeIntArray->SetItem(n, value);
n++;
AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
return JavascriptNumber::ToVar(n, scriptContext);
}
}
return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
}
/*
* JavascriptNativeFloatArray::Push
* Pushes Float element in a native Int Array.
* We call the generic Push, if the array is not native Float or we have a really big array.
*/
Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
{
// Handle non crossSite native int arrays here length within MaxArrayLength.
// JavascriptArray::Push will handle other cases.
if(JavascriptNativeFloatArray::IsNonCrossSite(array))
{
JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
Assert(!nativeFloatArray->IsCrossSiteObject());
uint32 n = nativeFloatArray->length;
if(n < JavascriptArray::MaxArrayLength)
{
nativeFloatArray->SetItem(n, value);
n++;
AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
return JavascriptNumber::ToVar(n, scriptContext);
}
}
return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
}
/*
* JavascriptArray::Push
* Pushes Var element in a Var Array.
*/
Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
{
Var args[2];
args[0] = object;
args[1] = value;
if (JavascriptArray::Is(object))
{
return EntryPushJavascriptArray(scriptContext, args, 2);
}
else
{
return EntryPushNonJavascriptArray(scriptContext, args, 2);
}
}
/*
* EntryPushNonJavascriptArray
* - Handles Entry push calls, when Objects are not javascript arrays
*/
Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
{
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
}
Var length = JavascriptOperators::OP_GetLength(obj, scriptContext);
if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
{
return length;
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
BigIndex n;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
}
else
{
n = JavascriptConversion::ToUInt32(length, scriptContext);
}
// First handle "small" indices.
uint index;
for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
{
if (h.IsThrowTypeError(JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if (scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
}
// Use BigIndex if we need to push indices >= MaxArrayLength
if (index < argCount)
{
BigIndex big = n;
for (; index < argCount; ++index, ++big)
{
if (h.IsThrowTypeError(big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
}
// Set the new length; for objects it is all right for this to be >= MaxArrayLength
if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
return big.ToNumber(scriptContext);
}
else
{
// Set the new length
Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible)))
{
if(scriptContext->GetThreadContext()->RecordImplicitException())
{
h.ThrowTypeErrorOnFailure();
}
else
{
return nullptr;
}
}
return lengthAsNUmberVar;
}
}
/*
* JavascriptArray::EntryPushJavascriptArray
* Pushes Var element in a Var Array.
* Returns the length of the array.
*/
Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
{
JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
uint n = arr->length;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
// Fast Path for one push for small indexes
if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
{
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
return JavascriptNumber::ToVar(n + 1, scriptContext);
}
// Fast Path for multiple push for small indexes
if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
{
uint index;
for (index = 1; index < argCount; ++index, ++n)
{
Assert(n != JavascriptArray::MaxArrayLength);
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
arr->JavascriptArray::DirectSetItemAt(n, args[index]);
}
return JavascriptNumber::ToVar(n, scriptContext);
}
return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
}
Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
{
JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
uint n = arr->length;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
// First handle "small" indices.
uint index;
for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
{
// Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
}
// Use BigIndex if we need to push indices >= MaxArrayLength
if (index < argCount)
{
// Not supporting native array with BigIndex.
arr = EnsureNonNativeArray(arr);
Assert(n == JavascriptArray::MaxArrayLength);
for (BigIndex big = n; index < argCount; ++index, ++big)
{
h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index]));
}
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
// This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
#ifdef VALIDATE_ARRAY
arr->ValidateArray();
#endif
return JavascriptNumber::ToVar(n, scriptContext);
}
/*
* JavascriptArray::EntryPush
* Handles Push calls(Script Function)
*/
Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
}
if (JavascriptArray::Is(args[0]))
{
return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
}
else
{
return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
}
}
Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
}
BigIndex length = 0u;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]))
{
pArr = JavascriptArray::FromVar(args[0]);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext);
}
// Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
template <typename T>
Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
{
T middle = length / 2;
Var lowerValue = nullptr, upperValue = nullptr;
T lowerExists, upperExists;
const char16* methodName;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
if (isTypedArrayEntryPoint)
{
methodName = _u("[TypedArray].prototype.reverse");
}
else
{
methodName = _u("Array.prototype.reverse");
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
if (pArr)
{
Recycler * recycler = scriptContext->GetRecycler();
if (length <= 1)
{
return pArr;
}
if (pArr->IsFillFromPrototypes())
{
// For odd-length arrays, the middle element is unchanged,
// so we cannot fill it from the prototypes.
if (length % 2 == 0)
{
pArr->FillFromPrototypes(0, (uint32)length);
}
else
{
middle = length / 2;
pArr->FillFromPrototypes(0, (uint32)middle);
pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
}
}
if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
{
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
}
// Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
// not work with the stale length. Update the length.
// Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
length = pArr->length;
SparseArraySegmentBase* seg = pArr->head;
SparseArraySegmentBase *prevSeg = nullptr;
SparseArraySegmentBase *nextSeg = nullptr;
SparseArraySegmentBase *pinPrevSeg = nullptr;
bool isIntArray = false;
bool isFloatArray = false;
if (JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if (JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
while (seg)
{
nextSeg = seg->next;
// If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
// resulting in 2 segments sharing the same "left".
if (seg->length > 0)
{
if (isIntArray)
{
((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
}
else if (isFloatArray)
{
((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
}
else
{
((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
}
seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
seg->next = prevSeg;
// Make sure size doesn't overlap with next segment.
// An easy fix is to just truncate the size...
seg->EnsureSizeInBound();
// If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
// segment. Hold onto it with pinPrevSeg until we reallocate below.
pinPrevSeg = prevSeg;
prevSeg = seg;
}
seg = nextSeg;
}
pArr->head = prevSeg;
// Just dump the segment map on reverse
pArr->ClearSegmentMap();
if (isIntArray)
{
if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
{
pArr->ReallocNonLeafSegment((SparseArraySegment<int32>*)pArr->head, pArr->head->next);
}
pArr->EnsureHeadStartsFromZero<int32>(recycler);
}
else if (isFloatArray)
{
if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
{
pArr->ReallocNonLeafSegment((SparseArraySegment<double>*)pArr->head, pArr->head->next);
}
pArr->EnsureHeadStartsFromZero<double>(recycler);
}
else
{
pArr->EnsureHeadStartsFromZero<Var>(recycler);
}
pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
}
else if (typedArrayBase)
{
Assert(length <= JavascriptArray::MaxArrayLength);
if (typedArrayBase->GetLength() == length)
{
// If typedArrayBase->length == length then we know that the TypedArray will have all items < length
// and we won't have to check that the elements exist or not.
for (uint32 lower = 0; lower < (uint32)middle; lower++)
{
uint32 upper = (uint32)length - lower - 1;
lowerValue = typedArrayBase->DirectGetItem(lower);
upperValue = typedArrayBase->DirectGetItem(upper);
// We still have to call HasItem even though we know the TypedArray has both lower and upper because
// there may be a proxy handler trapping HasProperty.
lowerExists = typedArrayBase->HasItem(lower);
upperExists = typedArrayBase->HasItem(upper);
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
}
else
{
for (uint32 lower = 0; lower < middle; lower++)
{
uint32 upper = (uint32)length - lower - 1;
lowerValue = typedArrayBase->DirectGetItem(lower);
upperValue = typedArrayBase->DirectGetItem(upper);
lowerExists = typedArrayBase->HasItem(lower);
upperExists = typedArrayBase->HasItem(upper);
if (lowerExists)
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
else
{
// This will always fail for a TypedArray if lower < length
h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue));
}
}
else
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue));
// This will always fail for a TypedArray if upper < length
h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
}
}
}
else
{
for (T lower = 0; lower < middle; lower++)
{
T upper = length - lower - 1;
lowerExists = JavascriptOperators::HasItem(obj, lower) &&
JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext);
upperExists = JavascriptOperators::HasItem(obj, upper) &&
JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext);
if (lowerExists)
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
}
else
{
if (upperExists)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
}
}
return obj;
}
template<typename T>
void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
{
Recycler * recycler = scriptContext->GetRecycler();
SparseArraySegment<T>* next = (SparseArraySegment<T>*)pArr->head->next;
while (next)
{
next->left--;
next = (SparseArraySegment<T>*)next->next;
}
// head and next might overlap as the next segment left is decremented
next = (SparseArraySegment<T>*)pArr->head->next;
if (next && (pArr->head->size > next->left))
{
AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
SparseArraySegment<T> *head = (SparseArraySegment<T>*)pArr->head;
// Merge the two adjacent segments
if (next->length != 0)
{
uint32 offset = head->size - 1;
// There is room for one unshifted element in head segment.
// Hence it's enough if we grow the head segment by next->length - 1
if (next->next)
{
// If we have a next->next, we can't grow pass the left of that
// If the array had a segment map before, the next->next might just be right after next as well.
// So we just need to grow to the end of the next segment
// TODO: merge that segment too?
Assert(next->next->left >= head->size);
uint32 maxGrowSize = next->next->left - head->size;
if (maxGrowSize != 0)
{
head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
}
else
{
// The next segment is only of length one, so we already have space in the header to copy that
Assert(next->length == 1);
}
}
else
{
head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
}
memmove(head->elements + offset, next->elements, next->length * sizeof(T));
head->length = offset + next->length;
pArr->head = head;
}
head->next = next->next;
pArr->InvalidateLastUsedSegment();
}
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
}
Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
if (JavascriptArray::Is(args[0]))
{
JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
if (pArr->length == 0)
{
return res;
}
if(pArr->IsFillFromPrototypes())
{
pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
}
if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
{
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
}
pArr->length--;
pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
Recycler * recycler = scriptContext->GetRecycler();
bool isIntArray = false;
bool isFloatArray = false;
if(JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if(JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
if (pArr->head->length != 0)
{
if(isIntArray)
{
int32 nativeResult = ((SparseArraySegment<int32>*)pArr->head)->GetElement(0);
if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
}
((SparseArraySegment<int32>*)pArr->head)->RemoveElement(recycler, 0);
}
else if (isFloatArray)
{
double nativeResult = ((SparseArraySegment<double>*)pArr->head)->GetElement(0);
if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
}
((SparseArraySegment<double>*)pArr->head)->RemoveElement(recycler, 0);
}
else
{
res = ((SparseArraySegment<Var>*)pArr->head)->GetElement(0);
if(SparseArraySegment<Var>::IsMissingItem(&res))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
else
{
res = CrossSite::MarshalVar(scriptContext, res);
}
((SparseArraySegment<Var>*)pArr->head)->RemoveElement(recycler, 0);
}
}
if(isIntArray)
{
ShiftHelper<int32>(pArr, scriptContext);
}
else if (isFloatArray)
{
ShiftHelper<double>(pArr, scriptContext);
}
else
{
ShiftHelper<Var>(pArr, scriptContext);
}
}
else
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
BigIndex length = 0u;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (length == 0u)
{
// If length is 0, return 'undefined'
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
return scriptContext->GetLibrary()->GetUndefined();
}
if (!JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext))
{
res = scriptContext->GetLibrary()->GetUndefined();
}
--length;
uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
for (uint32 i = 0u; i < lengthToUin32Max; i++)
{
if (JavascriptOperators::HasItem(dynamicObject, i + 1))
{
Var element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
for (uint64 i = MaxArrayLength; length > i; i++)
{
if (JavascriptOperators::HasItem(dynamicObject, i + 1))
{
Var element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
if (length.IsSmallIndex())
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
}
return res;
}
Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
{
if (isIntArray)
{
Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
pnewArr->EnsureHead<int32>();
#if ENABLE_PROFILE_INFO
pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
#endif
return pnewArr;
}
else if (isFloatArray)
{
Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
pnewArr->EnsureHead<double>();
#if ENABLE_PROFILE_INFO
pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
#endif
return pnewArr;
}
else
{
JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
pnewArr->EnsureHead<Var>();
return pnewArr;
}
}
template<typename T>
void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
{
SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)pArr->head;
SparseArraySegment<T>* pnewHeadSeg = (SparseArraySegment<T>*)pnewArr->head;
// Fill the newly created sliced array
js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);
pnewHeadSeg->length = newLen;
Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
// Prototype lookup for missing elements
if (!pArr->HasNoMissingValues())
{
for (uint32 i = 0; i < newLen; i++)
{
// array type might be changed in the below call to DirectGetItemAtFull
// need recheck array type before checking array item [i + start]
if (pArr->IsMissingItem(i + start))
{
Var element;
pnewArr->SetHasNoMissingValues(false);
if (pArr->DirectGetItemAtFull(i + start, &element))
{
pnewArr->SetItem(i, element, PropertyOperation_None);
}
}
}
}
#ifdef DBG
else
{
for (uint32 i = 0; i < newLen; i++)
{
AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
}
}
#endif
}
// If the creating profile data has changed, convert it to the type of array indicated
// in the profile
void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
{
if (JavascriptNativeIntArray::Is(this))
{
#if ENABLE_PROFILE_INFO
JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
if(!info || info->IsNativeIntArray())
{
*isIntArray = true;
}
else if(info->IsNativeFloatArray())
{
JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
*isFloatArray = true;
}
else
{
JavascriptNativeIntArray::ToVarArray(nativeIntArray);
}
#else
*isIntArray = true;
#endif
}
else if (JavascriptNativeFloatArray::Is(this))
{
#if ENABLE_PROFILE_INFO
JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
if(info && !info->IsNativeArray())
{
JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
}
else
{
*isFloatArray = true;
}
#else
*isFloatArray = true;
#endif
}
}
Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.slice"));
}
}
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(lenValue, scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(lenValue, scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max());
return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
template <typename T>
Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
JavascriptLibrary* library = scriptContext->GetLibrary();
JavascriptArray* newArr = nullptr;
RecyclableObject* newObj = nullptr;
bool isIntArray = false;
bool isFloatArray = false;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
bool isBuiltinArrayCtor = true;
T startT = 0;
T newLenT = length;
T endT = length;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
#endif
if (args.Info.Count > 1)
{
startT = GetFromIndex(args[1], length, scriptContext);
if (startT > length)
{
startT = length;
}
if (args.Info.Count > 2)
{
if (JavascriptOperators::GetTypeId(args[2]) == TypeIds_Undefined)
{
endT = length;
}
else
{
endT = GetFromIndex(args[2], length, scriptContext);
if (endT > length)
{
endT = length;
}
}
}
newLenT = endT > startT ? endT - startT : 0;
}
if (TypedArrayBase::IsDetachedTypedArray(obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
}
// If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// If the entry point is %TypedArray%.prototype.slice or the source object is an Array exotic object we should try to load the constructor property
// and use it to construct the return object.
if (isTypedArrayEntryPoint)
{
Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
isBuiltinArrayCtor = (constructor == library->GetArrayConstructor());
// If we have an array source object, we need to make sure to do the right thing if it's a native array.
// The helpers below which do the element copying require the source and destination arrays to have the same native type.
if (pArr && isBuiltinArrayCtor)
{
if (newLenT > JavascriptArray::MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
// If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
newObj = newArr;
}
else if (JavascriptOperators::IsConstructor(constructor))
{
if (pArr)
{
// If the constructor function is any other function, it can return anything so we have to call it.
// Roll the source array into a non-native array if it was one.
pArr = EnsureNonNativeArray(pArr);
}
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext));
}
else
{
// We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.slice was called
JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArray_Constructor, _u("[TypedArray].prototype.slice"));
}
}
else if (pArr != nullptr)
{
newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor);
}
// skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
else
{
newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
}
// If we didn't create a new object above we will create a new array here.
// This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
if (newObj == nullptr)
{
if (pArr)
{
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
}
if (newLenT > JavascriptArray::MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
#endif
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
uint32 start = (uint32) startT;
uint32 newLen = (uint32) newLenT;
// We at least have to have newObj as a valid object
Assert(newObj);
// Bail out early if the new object will have zero length.
if (newLen == 0)
{
return newObj;
}
if (pArr)
{
// If we constructed a new Array object, we have some nice helpers here
if (newArr && isBuiltinArrayCtor)
{
if (JavascriptArray::IsDirectAccessArray(newArr))
{
if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
{
if (isIntArray)
{
SliceHelper<int32>(pArr, newArr, start, newLen);
}
else if (isFloatArray)
{
SliceHelper<double>(pArr, newArr, start, newLen);
}
else
{
SliceHelper<Var>(pArr, newArr, start, newLen);
}
}
else
{
if (isIntArray)
{
CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen);
}
else if (isFloatArray)
{
CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen);
}
else
{
CopyArrayElements(newArr, 0u, pArr, start, start + newLen);
}
}
}
else
{
AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
Var element;
for (uint32 i = 0; i < newLen; i++)
{
if (!pArr->DirectGetItemAtFull(i + start, &element))
{
continue;
}
newArr->SetItem(i, element, PropertyOperation_None);
}
}
}
else
{
// The constructed object isn't an array, we'll need to use normal object manipulation
Var element;
for (uint32 i = 0; i < newLen; i++)
{
if (!pArr->DirectGetItemAtFull(i + start, &element))
{
continue;
}
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
}
}
else if (typedArrayBase)
{
// Source is a TypedArray, we must have created the return object via a call to constructor, but newObj may not be a TypedArray (or an array either)
TypedArrayBase* newTypedArray = nullptr;
if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
Var element;
for (uint32 i = 0; i < newLen; i++)
{
// We only need to call HasItem in the case that we are called from Array.prototype.slice
if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
{
continue;
}
element = typedArrayBase->DirectGetItem(i + start);
// The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
if (newTypedArray)
{
newTypedArray->DirectSetItem(i, element);
}
else if (newArr)
{
newArr->DirectSetItemAt(i, element);
}
else
{
JavascriptOperators::OP_SetElementI_UInt32(newObj, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
}
}
else
{
for (uint32 i = 0; i < newLen; i++)
{
if (JavascriptOperators::HasItem(obj, i + start))
{
Var element = JavascriptOperators::GetItem(obj, i + start, scriptContext);
if (newArr != nullptr)
{
newArr->SetItem(i, element, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
}
}
}
if (!isTypedArrayEntryPoint)
{
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
#ifdef VALIDATE_ARRAY
if (JavascriptArray::Is(newObj))
{
JavascriptArray::FromVar(newObj)->ValidateArray();
}
#endif
return newObj;
}
struct CompareVarsInfo
{
ScriptContext* scriptContext;
RecyclableObject* compFn;
};
int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
{
CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
ScriptContext* requestContext=cvInfo->scriptContext;
RecyclableObject* compFn=cvInfo->compFn;
AssertMsg(*(Var*)aRef, "No null expected in sort");
AssertMsg(*(Var*)bRef, "No null expected in sort");
if (compFn != nullptr)
{
ScriptContext* scriptContext = compFn->GetScriptContext();
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var undefined = scriptContext->GetLibrary()->GetUndefined();
Var retVal;
if (requestContext != scriptContext)
{
Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
retVal = CALL_FUNCTION(compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
}
else
{
retVal = CALL_FUNCTION(compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
}
if (TaggedInt::Is(retVal))
{
return TaggedInt::ToInt32(retVal);
}
double dblResult;
if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
{
dblResult = JavascriptNumber::GetValue(retVal);
}
else
{
dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
}
if (dblResult < 0)
{
return -1;
}
return (dblResult > 0) ? 1 : 0;
}
else
{
JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
return JavascriptString::strcmp(pStr1, pStr2);
}
}
static void hybridSort(__inout_ecount(length) Var *elements, uint32 length, CompareVarsInfo* compareInfo)
{
// The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
// for arrays of more than 512 elements.
if (length > 512)
{
qsort_s(elements, length, sizeof(Var), compareVars, compareInfo);
return;
}
for (int i = 1; i < (int)length; i++)
{
if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
// binary search for the left-most element greater than value:
int first = 0;
int last = i - 1;
while (first <= last)
{
int middle = (first + last) / 2;
if (compareVars(compareInfo, elements + i, elements + middle) < 0)
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
// insert value right before first:
Var value = elements[i];
memmove(elements + first + 1, elements + first, (i - first) * sizeof(Var));
elements[first] = value;
}
}
}
void JavascriptArray::Sort(RecyclableObject* compFn)
{
if (length <= 1)
{
return;
}
this->EnsureHead<Var>();
ScriptContext* scriptContext = this->GetScriptContext();
Recycler* recycler = scriptContext->GetRecycler();
CompareVarsInfo cvInfo;
cvInfo.scriptContext = scriptContext;
cvInfo.compFn = compFn;
Assert(head != nullptr);
// Just dump the segment map on sort
ClearSegmentMap();
uint32 countUndefined = 0;
SparseArraySegment<Var>* startSeg = (SparseArraySegment<Var>*)head;
// Sort may have side effects on the array. Setting a dummy head so that original array is not affected
uint32 saveLength = length;
// that if compare function tries to modify the array it won't AV.
head = const_cast<SparseArraySegmentBase*>(EmptySegment);
SetFlags(DynamicObjectFlags::None);
this->InvalidateLastUsedSegment();
length = 0;
TryFinally([&]()
{
//The array is a continuous array if there is only one segment
if (startSeg->next == nullptr) // Single segment fast path
{
if (compFn != nullptr)
{
countUndefined = startSeg->RemoveUndefined(scriptContext);
#ifdef VALIDATE_ARRAY
ValidateSegment(startSeg);
#endif
hybridSort(startSeg->elements, startSeg->length, &cvInfo);
}
else
{
countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext);
}
head = startSeg;
}
else
{
SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
SparseArraySegment<Var>* next = startSeg;
uint32 nextIndex = 0;
// copy all the elements to single segment
while (next)
{
countUndefined += next->RemoveUndefined(scriptContext);
if (next->length != 0)
{
allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
}
next = (SparseArraySegment<Var>*)next->next;
nextIndex = allElements->length;
#ifdef VALIDATE_ARRAY
ValidateSegment(allElements);
#endif
}
if (compFn != nullptr)
{
hybridSort(allElements->elements, allElements->length, &cvInfo);
}
else
{
sort(allElements->elements, &allElements->length, scriptContext);
}
head = allElements;
head->next = nullptr;
}
},
[&](bool hasException)
{
length = saveLength;
ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
if (hasException)
{
head = startSeg;
this->InvalidateLastUsedSegment();
}
});
#if DEBUG
{
uint32 countNull = 0;
uint32 index = head->length - 1;
while (countNull < head->length)
{
if (((SparseArraySegment<Var>*)head)->elements[index] != NULL)
{
break;
}
index--;
countNull++;
}
AssertMsg(countNull == 0, "No null expected at the end");
}
#endif
if (countUndefined != 0)
{
// fill undefined at the end
uint32 newLength = head->length + countUndefined;
if (newLength > head->size)
{
head = ((SparseArraySegment<Var>*)head)->GrowByMin(recycler, newLength - head->size);
}
Var undefined = scriptContext->GetLibrary()->GetUndefined();
for (uint32 i = head->length; i < newLength; i++)
{
((SparseArraySegment<Var>*)head)->elements[i] = undefined;
}
head->length = newLength;
}
SetHasNoMissingValues();
this->InvalidateLastUsedSegment();
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
return;
}
uint32 JavascriptArray::sort(__inout_ecount(*len) Var *orig, uint32 *len, ScriptContext *scriptContext)
{
uint32 count = 0, countUndefined = 0;
Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
//
// Create the Elements array
//
for (uint32 i = 0; i < *len; ++i)
{
if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
{
if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
{
elements[count].Value = orig[i];
elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
count++;
}
else
{
countUndefined++;
}
}
}
if (count > 0)
{
SortElements(elements, 0, count - 1);
for (uint32 i = 0; i < count; ++i)
{
orig[i] = elements[i].Value;
}
}
for (uint32 i = count + countUndefined; i < *len; ++i)
{
orig[i] = SparseArraySegment<Var>::GetMissingItem();
}
*len = count; // set the correct length
return countUndefined;
}
int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
{
const Element* element1 = static_cast<const Element*>(elem1);
const Element* element2 = static_cast<const Element*>(elem2);
Assert(element1 != NULL);
Assert(element2 != NULL);
return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
}
void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
{
qsort_s(elements, right - left + 1, sizeof(Element), CompareElements, this);
}
Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
Assert(!(callInfo.Flags & CallFlags_New));
AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
RecyclableObject* compFn = NULL;
if (args.Info.Count > 1)
{
if (JavascriptConversion::IsCallable(args[1]))
{
compFn = RecyclableObject::FromVar(args[1]);
}
else
{
TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
// Use default comparer:
// - In ES5 mode if the argument is undefined.
bool useDefaultComparer = typeId == TypeIds_Undefined;
if (!useDefaultComparer)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedInternalObject, _u("Array.prototype.sort"));
}
}
}
if (JavascriptArray::Is(args[0]))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
if (arr->length <= 1)
{
return args[0];
}
if(arr->IsFillFromPrototypes())
{
arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
}
// Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
// - int cases for X86 and
// - FloatArray for AMD64
// We convert the entire array back and forth once here O(n), rather than doing the costly conversion down the call stack which is O(nlogn)
#if defined(_M_X64_OR_ARM64)
if(compFn && JavascriptNativeFloatArray::Is(arr))
{
arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
arr->Sort(compFn);
arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
}
else
{
EnsureNonNativeArray(arr);
arr->Sort(compFn);
}
#else
if(compFn && JavascriptNativeIntArray::Is(arr))
{
//EnsureNonNativeArray(arr);
arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
arr->Sort(compFn);
arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
}
else
{
EnsureNonNativeArray(arr);
arr->Sort(compFn);
}
#endif
}
else
{
RecyclableObject* pObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
}
uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
sortArray->EnsureHead<Var>();
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
{
JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
for (uint32 i = 0; i < len; i++)
{
Var item;
if (JavascriptOperators::GetItem(pObj, i, &item, scriptContext))
{
indexList->Add(i);
sortArray->DirectSetItemAt(i, item);
}
}
if (indexList->Count() > 0)
{
if (sortArray->length > 1)
{
sortArray->FillFromPrototypes(0, sortArray->length); // We need find all missing value from [[proto]] object
}
sortArray->Sort(compFn);
uint32 removeIndex = sortArray->head->length;
for (uint32 i = 0; i < removeIndex; i++)
{
AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&((SparseArraySegment<Var>*)sortArray->head)->elements[i]), "No gaps expected in sorted array");
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, ((SparseArraySegment<Var>*)sortArray->head)->elements[i], scriptContext));
}
for (int i = 0; i < indexList->Count(); i++)
{
uint32 value = indexList->Item(i);
if (value >= removeIndex)
{
h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value)));
}
}
}
}
END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
}
return args[0];
}
Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Recycler *recycler = scriptContext->GetRecycler();
Assert(!(callInfo.Flags & CallFlags_New));
AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
bool isArr = false;
JavascriptArray* pArr = 0;
RecyclableObject* pObj = 0;
RecyclableObject* newObj = nullptr;
uint32 start = 0;
uint32 deleteLen = 0;
uint32 len = 0;
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
isArr = true;
pArr = JavascriptArray::FromVar(args[0]);
pObj = pArr;
len = pArr->length;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.splice"));
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
int64 len64 = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
len = len64 > UINT_MAX ? UINT_MAX : (uint)len64;
}
else
{
len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
}
}
switch (args.Info.Count)
{
case 1:
start = len;
deleteLen = 0;
break;
case 2:
start = min(GetFromIndex(args[1], len, scriptContext), len);
deleteLen = len - start;
break;
default:
start = GetFromIndex(args[1], len, scriptContext);
if (start > len)
{
start = len;
}
// When start >= len, we know we won't be deleting any items and don't really need to evaluate the second argument.
// However, ECMA 262 15.4.4.12 requires that it be evaluated, anyway. If the argument is an object with a valueOf
// with a side effect, this evaluation is observable. Hence, we must evaluate.
if (TaggedInt::Is(args[2]))
{
int intDeleteLen = TaggedInt::ToInt32(args[2]);
if (intDeleteLen < 0)
{
deleteLen = 0;
}
else
{
deleteLen = intDeleteLen;
}
}
else
{
double dblDeleteLen = JavascriptConversion::ToInteger(args[2], scriptContext);
if (dblDeleteLen > len)
{
deleteLen = (uint32)-1;
}
else if (dblDeleteLen <= 0)
{
deleteLen = 0;
}
else
{
deleteLen = (uint32)dblDeleteLen;
}
}
deleteLen = min(len - start, deleteLen);
break;
}
Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
::Math::RecordOverflowPolicy newLenOverflow;
uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
if (isArr)
{
// If we have missing values then convert to not native array for now
// In future, we could support this scenario.
if (deleteLen == insertLen)
{
pArr->FillFromPrototypes(start, start + deleteLen);
}
else if (len)
{
pArr->FillFromPrototypes(start, len);
}
//
// If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
// max array length, which would result in tons of index overflow and difficult to fix.
//
if (newLenOverflow.HasOverflowed())
{
pArr = EnsureNonNativeArray(pArr);
BigIndex dstIndex = MaxArrayLength;
uint32 maxInsertLen = MaxArrayLength - start;
if (insertLen > maxInsertLen)
{
// Copy overflowing insertArgs to properties
for (uint32 i = maxInsertLen; i < insertLen; i++)
{
pArr->DirectSetItemAt(dstIndex, insertArgs[i]);
++dstIndex;
}
insertLen = maxInsertLen; // update
// Truncate elements on the right to properties
if (start + deleteLen < len)
{
pArr->TruncateToProperties(dstIndex, start + deleteLen);
}
}
else
{
// Truncate would-overflow elements to properties
pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
}
len = pArr->length; // update
newLen = len - deleteLen + insertLen;
Assert(newLen == MaxArrayLength);
}
if (insertArgs)
{
pArr = EnsureNonNativeArray(pArr);
}
bool isIntArray = false;
bool isFloatArray = false;
bool isBuiltinArrayCtor = true;
JavascriptArray *newArr = nullptr;
// Just dump the segment map on splice (before any possible allocation and throw)
pArr->ClearSegmentMap();
// If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
// and use it to construct the return object.
newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
if (newObj != nullptr)
{
pArr = EnsureNonNativeArray(pArr);
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
// This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
{
pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
#endif
}
// If return object is a JavascriptArray, we can use all the array splice helpers
if (newArr && isBuiltinArrayCtor && len == pArr->length)
{
// Array has a single segment (need not start at 0) and splice start lies in the range
// of that segment we optimize splice - Fast path.
if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
{
if (isIntArray)
{
ArraySegmentSpliceHelper<int32>(newArr, (SparseArraySegment<int32>*)pArr->head, (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
else if (isFloatArray)
{
ArraySegmentSpliceHelper<double>(newArr, (SparseArraySegment<double>*)pArr->head, (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
else
{
ArraySegmentSpliceHelper<Var>(newArr, (SparseArraySegment<Var>*)pArr->head, (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
}
// Since the start index is within the bounds of the original array's head segment, it will not acquire any new
// missing values. If the original array had missing values in the head segment, some of them may have been
// copied into the array that will be returned; otherwise, the array that is returned will also not have any
// missing values.
newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
}
else
{
if (isIntArray)
{
ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
else if (isFloatArray)
{
ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
else
{
ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
}
// This function currently does not track missing values in the head segment if there are multiple segments
pArr->SetHasNoMissingValues(false);
newArr->SetHasNoMissingValues(false);
}
if (isIntArray)
{
pArr->EnsureHeadStartsFromZero<int32>(recycler);
newArr->EnsureHeadStartsFromZero<int32>(recycler);
}
else if (isFloatArray)
{
pArr->EnsureHeadStartsFromZero<double>(recycler);
newArr->EnsureHeadStartsFromZero<double>(recycler);
}
else
{
pArr->EnsureHeadStartsFromZero<Var>(recycler);
newArr->EnsureHeadStartsFromZero<Var>(recycler);
}
pArr->InvalidateLastUsedSegment();
// it is possible for valueOf accessors for the start or deleteLen
// arguments to modify the size of the array. Since the resulting size of the array
// is based on the cached value of length, this might lead to us having to trim
// excess array segments at the end of the splice operation, which SetLength() will do.
// However, this is also slower than performing the simple length assignment, so we only
// do it if we can detect the array length changing.
if(pArr->length != len)
{
pArr->SetLength(newLen);
}
else
{
pArr->length = newLen;
}
if (newArr->length != deleteLen)
{
newArr->SetLength(deleteLen);
}
else
{
newArr->length = deleteLen;
}
newArr->InvalidateLastUsedSegment();
#ifdef VALIDATE_ARRAY
newArr->ValidateArray();
pArr->ValidateArray();
#endif
if (newLenOverflow.HasOverflowed())
{
// ES5 15.4.4.12 16: If new len overflowed, SetLength throws
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
return newArr;
}
}
if (newLenOverflow.HasOverflowed())
{
return ObjectSpliceHelper<BigIndex>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
}
else // Use uint32 version if no overflow
{
return ObjectSpliceHelper<uint32>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
}
}
inline BOOL JavascriptArray::IsSingleSegmentArray() const
{
return nullptr == head->next;
}
template<typename T>
void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
{
// book keeping variables
uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
//(Missing elements at the beginning)
uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
// head if deleteLen overflows the length of head
uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
// Save the deleted elements
if (headDeleteLen != 0)
{
pnewArr->InvalidateLastUsedSegment();
pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, (SparseArraySegment<T>*)pnewArr->head, 0, seg, start, headDeleteLen);
}
if (newHeadLen != 0)
{
if (seg->size < newHeadLen)
{
if (seg->next)
{
// If we have "next", require that we haven't adjusted next segments left yet.
seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
}
else
{
seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
}
#ifdef VALIDATE_ARRAY
ValidateSegment(seg);
#endif
}
// Move the elements if necessary
if (headDeleteLen != insertLen)
{
uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
memmove(seg->elements + relativeStart + insertLen,
seg->elements + relativeStart + headDeleteLen,
sizeof(T) * noElementsToMove);
if (newHeadLen < seg->length) // truncate if necessary
{
seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
}
seg->length = newHeadLen;
}
// Copy the new elements
if (insertLen > 0)
{
Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
!VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
// inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
js_memcpy_s(seg->elements + relativeStart, sizeof(Var) * insertLen, insertArgs, sizeof(Var) * insertLen);
}
*prev = seg;
}
else
{
*prev = (SparseArraySegment<T>*)seg->next;
}
}
template<typename T>
void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
{
// Skip pnewArr->EnsureHead(): we don't use existing segment at all.
Recycler *recycler = scriptContext->GetRecycler();
SparseArraySegmentBase** prevSeg = &pArr->head; // holds the next pointer of previous
SparseArraySegmentBase** prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
SparseArraySegmentBase* savePrev = nullptr;
Assert(pArr->head); // We should never have a null head.
pArr->EnsureHead<T>();
SparseArraySegment<T>* startSeg = (SparseArraySegment<T>*)pArr->head;
const uint32 limit = start + deleteLen;
uint32 rightLimit;
if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
{
rightLimit = JavascriptArray::MaxArrayLength;
}
// Find out the segment to start delete
while (startSeg && (rightLimit <= start))
{
savePrev = startSeg;
prevPrevSeg = prevSeg;
prevSeg = &startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
if (startSeg)
{
if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
{
rightLimit = JavascriptArray::MaxArrayLength;
}
}
}
// handle inlined segment
SparseArraySegmentBase* inlineHeadSegment = nullptr;
bool hasInlineSegment = false;
// The following if else set is used to determine whether a shallow or hard copy is needed
if (JavascriptNativeArray::Is(pArr))
{
if (JavascriptNativeFloatArray::Is(pArr))
{
inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
}
else if (JavascriptNativeIntArray::Is(pArr))
{
inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
}
Assert(inlineHeadSegment);
hasInlineSegment = (startSeg == (SparseArraySegment<T>*)inlineHeadSegment);
}
else
{
// This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
// does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
// This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
// so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
// false positives. It is better than always doing a hard copy.
hasInlineSegment = HasInlineHeadSegment(pArr->head->length);
}
if (startSeg)
{
// Delete Phase
if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
{
// All splice happens in one segment.
SparseArraySegmentBase *nextSeg = startSeg->next;
// Splice the segment first, which might OOM throw but the array would be intact.
JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
while (nextSeg)
{
// adjust next segments left
nextSeg->left = nextSeg->left - deleteLen + insertLen;
if (nextSeg->next == nullptr)
{
nextSeg->EnsureSizeInBound();
}
nextSeg = nextSeg->next;
}
if (*prevSeg)
{
(*prevSeg)->EnsureSizeInBound();
}
return;
}
else
{
SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
SparseArraySegmentBase** prevNewHeadSeg = &(pnewArr->head);
// delete till deleteLen and reuse segments for new array if it is possible.
// 3 steps -
//1. delete 1st segment (which may be partial delete)
// 2. delete next n complete segments
// 3. delete last segment (which again may be partial delete)
// Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
if (startSeg->left < start)
{
if (start < startSeg->left + startSeg->length)
{
uint32 headDeleteLen = startSeg->left + startSeg->length - start;
if (startSeg->next)
{
// We know the new segment will have a next segment, so allocate it as non-leaf.
newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
else
{
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
newHeadSeg->next = nullptr;
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
startSeg->Truncate(start);
}
savePrev = startSeg;
prevPrevSeg = prevSeg;
prevSeg = &startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
// Step (2) first we should do a hard copy if we have an inline head Segment
else if (hasInlineSegment && nullptr != startSeg)
{
// start should be in between left and left + length
if (startSeg->left <= start && start < startSeg->left + startSeg->length)
{
uint32 headDeleteLen = startSeg->left + startSeg->length - start;
if (startSeg->next)
{
// We know the new segment will have a next segment, so allocate it as non-leaf.
newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
else
{
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
}
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
// Remove the entire segment from the original array
*prevSeg = startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
// if we have an inline head segment with 0 elements, remove it
else if (startSeg->left == 0 && startSeg->length == 0)
{
Assert(startSeg->size != 0);
*prevSeg = startSeg->next;
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
}
// Step (2) proper
SparseArraySegmentBase *temp = nullptr;
while (startSeg && (startSeg->left + startSeg->length) <= limit)
{
temp = startSeg->next;
// move that entire segment to new array
startSeg->left = startSeg->left - start;
startSeg->next = nullptr;
*prevNewHeadSeg = startSeg;
prevNewHeadSeg = &startSeg->next;
// Remove the entire segment from the original array
*prevSeg = temp;
startSeg = (SparseArraySegment<T>*)temp;
}
// Step(2) above could delete the original head segment entirely, causing current head not
// starting from 0. Then if any of the following throw, we have a corrupted array. Need
// protection here.
bool dummyHeadNodeInserted = false;
if (!savePrev && (!startSeg || startSeg->left != 0))
{
Assert(pArr->head == startSeg);
pArr->EnsureHeadStartsFromZero<T>(recycler);
Assert(pArr->head && pArr->head->next == startSeg);
savePrev = pArr->head;
prevPrevSeg = prevSeg;
prevSeg = &pArr->head->next;
dummyHeadNodeInserted = true;
}
// Step (3)
if (startSeg && (startSeg->left < limit))
{
// copy the first part of the last segment to be deleted to new array
uint32 headDeleteLen = start + deleteLen - startSeg->left ;
newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
newHeadSeg->next = nullptr;
*prevNewHeadSeg = newHeadSeg;
prevNewHeadSeg = &newHeadSeg->next;
// move the last segment
memmove(startSeg->elements, startSeg->elements + headDeleteLen, sizeof(T) * (startSeg->length - headDeleteLen));
startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
startSeg->length = startSeg->length - headDeleteLen;
startSeg->Truncate(startSeg->left + startSeg->length);
startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
}
if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
{
Assert(start + insertLen == 0);
// Remove the dummy head node to preserve array consistency.
pArr->head = startSeg;
savePrev = nullptr;
prevSeg = &pArr->head;
}
while (startSeg)
{
startSeg->left = startSeg->left - deleteLen + insertLen ;
if (startSeg->next == nullptr)
{
startSeg->EnsureSizeInBound();
}
startSeg = (SparseArraySegment<T>*)startSeg->next;
}
}
}
// The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
pnewArr->head->EnsureSizeInBound();
if (savePrev)
{
savePrev->EnsureSizeInBound();
}
// insert elements
if (insertLen > 0)
{
Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
// InsertPhase
SparseArraySegment<T> *segInsert = nullptr;
// see if we are just about the right of the previous segment
Assert(!savePrev || savePrev->left <= start);
if (savePrev && (start - savePrev->left < savePrev->size))
{
segInsert = (SparseArraySegment<T>*)savePrev;
uint32 spaceLeft = segInsert->size - (start - segInsert->left);
if(spaceLeft < insertLen)
{
if (!segInsert->next)
{
segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
}
else
{
segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
}
}
*prevPrevSeg = segInsert;
segInsert->length = start + insertLen - segInsert->left;
}
else
{
segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
segInsert->next = *prevSeg;
*prevSeg = segInsert;
savePrev = segInsert;
}
uint32 relativeStart = start - segInsert->left;
// inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
js_memcpy_s(segInsert->elements + relativeStart, sizeof(T) * insertLen, insertArgs, sizeof(T) * insertLen);
}
}
template<typename indexT>
RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, uint32 len, uint32 start,
uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
{
JavascriptArray *pnewArr = nullptr;
if (pNewObj == nullptr)
{
pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext);
if (pNewObj == nullptr || !JavascriptArray::Is(pNewObj))
{
pnewArr = scriptContext->GetLibrary()->CreateArray(deleteLen);
pnewArr->EnsureHead<Var>();
pNewObj = pnewArr;
}
}
if (JavascriptArray::Is(pNewObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
#endif
pnewArr = JavascriptArray::FromVar(pNewObj);
}
// copy elements to delete to new array
if (deleteLen > 0)
{
for (uint32 i = 0; i < deleteLen; i++)
{
if (JavascriptOperators::HasItem(pObj, start+i))
{
Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext);
if (pnewArr)
{
pnewArr->SetItem(i, element, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, i, element), scriptContext, i);
}
}
}
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
// If the return object is not an array, we'll need to set the 'length' property
if (pnewArr == nullptr)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, JavascriptNumber::ToVar(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
// Now we need reserve room if it is necessary
if (insertLen > deleteLen) // Might overflow max array length
{
// Unshift [start + deleteLen, len) to start + insertLen
Unshift<indexT>(pObj, start + insertLen, start + deleteLen, len, scriptContext);
}
else if (insertLen < deleteLen) // Won't overflow max array length
{
uint32 j = 0;
for (uint32 i = start + deleteLen; i < len; i++)
{
if (JavascriptOperators::HasItem(pObj, i))
{
Var element = JavascriptOperators::GetItem(pObj, i, scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
j++;
}
// Clean up the rest
for (uint32 i = len; i > len - deleteLen + insertLen; i--)
{
h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
}
if (insertLen > 0)
{
indexT dstIndex = start; // insert index might overflow max array length
for (uint i = 0; i < insertLen; i++)
{
h.ThrowTypeErrorOnFailure(IndexTrace<indexT>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible));
++dstIndex;
}
}
// Set up new length
indexT newLen = indexT(len - deleteLen) + insertLen;
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<indexT>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<indexT>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
#ifdef VALIDATE_ARRAY
if (pnewArr)
{
pnewArr->ValidateArray();
}
#endif
return pNewObj;
}
Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
}
if (JavascriptArray::IsDirectAccessArray(args[0]))
{
JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
return ToLocaleString(arr, scriptContext);
}
else
{
if (TypedArrayBase::IsDetachedTypedArray(args[0]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
}
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
}
return ToLocaleString(obj, scriptContext);
}
}
//
// Unshift object elements [start, end) to toIndex, asserting toIndex > start.
//
template<typename T, typename P>
void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, uint32 start, P end, ScriptContext* scriptContext)
{
typedef IndexTrace<T> index_trace;
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
if (start < end)
{
T newEnd = (end - start - 1);// newEnd - 1
T dst = toIndex + newEnd;
uint32 i = 0;
if (end > UINT32_MAX)
{
uint64 i64 = end;
for (; i64 > UINT32_MAX; i64--)
{
if (JavascriptOperators::HasItem(obj, i64 - 1))
{
Var element = JavascriptOperators::GetItem(obj, i64 - 1, scriptContext);
h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
--dst;
}
i = UINT32_MAX;
}
else
{
i = (uint32) end;
}
for (; i > start; i--)
{
if (JavascriptOperators::HasItem(obj, i-1))
{
Var element = JavascriptOperators::GetItem(obj, i - 1, scriptContext);
h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
}
else
{
h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig));
}
--dst;
}
}
}
template<typename T>
void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
{
SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
Recycler* recycler = scriptContext->GetRecycler();
if (nextToHeadSeg == nullptr)
{
pArr->EnsureHead<T>();
pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMin(recycler, unshiftElements);
}
else
{
pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
}
}
template<typename T>
void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
{
SparseArraySegment<T>* head = (SparseArraySegment<T>*)pArr->head;
// Make enough room in the head segment to insert new elements at the front
memmove(head->elements + unshiftElements, head->elements, sizeof(T) * pArr->head->length);
uint32 oldHeadLength = head->length;
head->length += unshiftElements;
/* Set head segment as the last used segment */
pArr->InvalidateLastUsedSegment();
bool hasNoMissingValues = pArr->HasNoMissingValues();
/* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
if(unshiftElements > oldHeadLength)
{
pArr->SetHasNoMissingValues(false);
}
#if ENABLE_PROFILE_INFO
pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
#else
pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
#endif
// Setting back to the old value
pArr->SetHasNoMissingValues(hasNoMissingValues);
}
Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
Var res = scriptContext->GetLibrary()->GetUndefined();
if (args.Info.Count == 0)
{
return res;
}
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
uint32 unshiftElements = args.Info.Count - 1;
if (unshiftElements > 0)
{
if (pArr->IsFillFromPrototypes())
{
pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
}
// Pre-process: truncate overflowing elements to properties
bool newLenOverflowed = false;
uint32 maxLen = MaxArrayLength - unshiftElements;
if (pArr->length > maxLen)
{
newLenOverflowed = true;
// Ensure the array is non-native when overflow happens
EnsureNonNativeArray(pArr);
pArr->TruncateToProperties(MaxArrayLength, maxLen);
Assert(pArr->length + unshiftElements == MaxArrayLength);
}
pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
Assert(pArr->length <= MaxArrayLength - unshiftElements);
SparseArraySegmentBase* renumberSeg = pArr->head->next;
bool isIntArray = false;
bool isFloatArray = false;
if (JavascriptNativeIntArray::Is(pArr))
{
isIntArray = true;
}
else if (JavascriptNativeFloatArray::Is(pArr))
{
isFloatArray = true;
}
// If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
// If there is OOM in array allocation, then array consistency is maintained.
if (pArr->head->size < pArr->head->length + unshiftElements)
{
if (isIntArray)
{
GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
}
else if (isFloatArray)
{
GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
}
else
{
GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
}
}
while (renumberSeg)
{
renumberSeg->left += unshiftElements;
if (renumberSeg->next == nullptr)
{
// last segment can shift its left + size beyond MaxArrayLength, so truncate if so
renumberSeg->EnsureSizeInBound();
}
renumberSeg = renumberSeg->next;
}
if (isIntArray)
{
UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
}
else if (isFloatArray)
{
UnshiftHelper<double>(pArr, unshiftElements, args.Values);
}
else
{
UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
}
pArr->InvalidateLastUsedSegment();
pArr->length += unshiftElements;
#ifdef VALIDATE_ARRAY
pArr->ValidateArray();
#endif
if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
}
}
res = JavascriptNumber::ToVar(pArr->length, scriptContext);
}
else
{
RecyclableObject* dynamicObject = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
}
BigIndex length;
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
uint32 unshiftElements = args.Info.Count - 1;
if (unshiftElements > 0)
{
uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
// Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
// or MaxSpaceUint32 is greater than length meaning length is a uint32 number
BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
if (end < length)
{
// Unshift [end, length) to MaxArrayLength
// MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
if (length.IsSmallIndex())
{
Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext);
}
else
{
Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetBigIndex(), scriptContext);
}
}
// Unshift [0, end) to unshiftElements
// unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
Unshift<uint32>(dynamicObject, unshiftElements, 0, end.GetSmallIndex(), scriptContext);
for (uint32 i = 0; i < unshiftElements; i++)
{
JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true);
}
}
ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
//ES6 - update 'length' even if unshiftElements == 0;
BigIndex newLen = length + unshiftElements;
res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
}
return res;
}
Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
}
// ES5 15.4.4.2: call join, or built-in Object.prototype.toString
RecyclableObject* obj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
}
// In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext);
if (JavascriptConversion::IsCallable(join))
{
RecyclableObject* func = RecyclableObject::FromVar(join);
// We need to record implicit call here, because marked the Array.toString as no side effect,
// but if we call user code here which may have side effect
ThreadContext * threadContext = scriptContext->GetThreadContext();
Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
{
// Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
Assert(!ThreadContext::IsOnStack(obj));
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
return CALL_FUNCTION(func, CallInfo(flags, 1), obj);
});
if(!result)
{
// There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
Assert(threadContext->IsDisableImplicitCall());
result = scriptContext->GetLibrary()->GetNull();
}
return result;
}
else
{
// call built-in Object.prototype.toString
return CALL_ENTRYPOINT(JavascriptObject::EntryToString, function, CallInfo(1), obj);
}
}
#if DEBUG
BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
{
uint32 lu, luDig;
int32 cch = (int32)wcslen(propName);
char16* pch = const_cast<char16 *>(propName);
lu = *pch - '0';
if (lu > 9)
return FALSE;
if (0 == lu)
{
*pIndex = 0;
return 1 == cch;
}
while ((luDig = *++pch - '0') < 10)
{
// If we overflow 32 bits, ignore the item
if (lu > 0x19999999)
return FALSE;
lu *= 10;
if(lu > (ULONG_MAX - luDig))
return FALSE;
lu += luDig;
}
if (pch - propName != cch)
return FALSE;
if (lu == JavascriptArray::InvalidIndex)
{
// 0xFFFFFFFF is not treated as an array index so that the length can be
// capped at 32 bits.
return FALSE;
}
*pIndex = lu;
return TRUE;
}
#endif
JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
{
#ifdef ENABLE_GLOBALIZATION
LCID lcid = GetUserDefaultLCID();
int count = 0;
char16 szSeparator[6];
// According to the document for GetLocaleInfo this is a sufficient buffer size.
count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
if( !count)
{
AssertMsg(FALSE, "GetLocaleInfo failed");
return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
}
else
{
// Append ' ' if necessary
if( count < 2 || szSeparator[count-2] != ' ')
{
szSeparator[count-1] = ' ';
szSeparator[count] = '\0';
}
return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
}
#else
// xplat-todo: Support locale-specific seperator
return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
#endif
}
template <typename T>
JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
{
uint32 length = 0;
if (TypedArrayBase::Is(arr))
{
// For a TypedArray use the actual length of the array.
length = TypedArrayBase::FromVar(arr)->GetLength();
}
else
{
//For anything else, use the "length" property if present.
length = ItemTrace<T>::GetLength(arr, scriptContext);
}
if (length == 0 || scriptContext->CheckObject(arr))
{
return scriptContext->GetLibrary()->GetEmptyString();
}
JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
bool pushedObject = false;
TryFinally([&]()
{
scriptContext->PushObject(arr);
pushedObject = true;
Var element;
if (ItemTrace<T>::GetItem(arr, 0, &element, scriptContext))
{
res = JavascriptArray::ToLocaleStringHelper(element, scriptContext);
}
if (length > 1)
{
JavascriptString* separator = GetLocaleSeparator(scriptContext);
for (uint32 i = 1; i < length; i++)
{
res = JavascriptString::Concat(res, separator);
if (ItemTrace<T>::GetItem(arr, i, &element, scriptContext))
{
res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext));
}
}
}
},
[&](bool/*hasException*/)
{
if (pushedObject)
{
Var top = scriptContext->PopObject();
AssertMsg(top == arr, "Unmatched operation stack");
}
});
if (res == nullptr)
{
res = scriptContext->GetLibrary()->GetEmptyString();
}
return res;
}
Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
if (args.Info.Count < 2)
{
return scriptContext->GetLibrary()->GetFalse();
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
#endif
if (JavascriptOperators::IsArray(args[1]))
{
return scriptContext->GetLibrary()->GetTrue();
}
return scriptContext->GetLibrary()->GetFalse();
}
///----------------------------------------------------------------------------
/// Find() calls the given predicate callback on each element of the array, in
/// order, and returns the first element that makes the predicate return true,
/// as described in (ES6.0: S22.1.3.8).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
}
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
}
template <bool findIndex>
Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var element = nullptr;
Var testResult = nullptr;
if (pArr)
{
Var undefined = scriptContext->GetLibrary()->GetUndefined();
for (uint32 k = 0; k < length; k++)
{
element = undefined;
pArr->DirectGetItemAtFull(k, &element);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
pArr);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
else if (typedArrayBase)
{
for (uint32 k = 0; k < length; k++)
{
element = typedArrayBase->DirectGetItem(k);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
typedArrayBase);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
else
{
for (uint32 k = 0; k < length; k++)
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
Var index = JavascriptNumber::ToVar(k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
index,
obj);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return findIndex ? index : element;
}
}
}
return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
}
///----------------------------------------------------------------------------
/// FindIndex() calls the given predicate callback on each element of the
/// array, in order, and returns the index of the first element that makes the
/// predicate return true, as described in (ES6.0: S22.1.3.9).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
}
int64 length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
}
///----------------------------------------------------------------------------
/// Entries() returns a new ArrayIterator object configured to return key-
/// value pairs matching the elements of the this array/array-like object,
/// as described in (ES6.0: S22.1.3.4).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue);
}
///----------------------------------------------------------------------------
/// Keys() returns a new ArrayIterator object configured to return the keys
/// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key);
}
///----------------------------------------------------------------------------
/// Values() returns a new ArrayIterator object configured to return the values
/// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
///----------------------------------------------------------------------------
Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
}
RecyclableObject* thisObj = nullptr;
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
#endif
return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value);
}
Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
Assert(!(callInfo.Flags & CallFlags_New));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
template <typename T>
Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
Var element = nullptr;
Var testResult = nullptr;
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
if (pArr)
{
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (uint32 k = 0; k < length; k++)
{
if (!typedArrayBase->HasItem(k))
{
continue;
}
element = typedArrayBase->DirectGetItem(k);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
else
{
for (T k = 0; k < length; k++)
{
// According to es6 spec, we need to call Has first before calling Get
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetFalse();
}
}
}
}
return scriptContext->GetLibrary()->GetTrue();
}
Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
template <typename T>
Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
// We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var element = nullptr;
Var testResult = nullptr;
if (pArr)
{
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (uint32 k = 0; k < length; k++)
{
// If k < typedArrayBase->length, we know that HasItem will return true.
// But we still have to call it in case there's a proxy trap or in the case that we are calling
// Array.prototype.some with a TypedArray that has a different length instance property.
if (!typedArrayBase->HasItem(k))
{
continue;
}
element = typedArrayBase->DirectGetItem(k);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
else
{
for (T k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
testResult = CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (JavascriptConversion::ToBoolean(testResult, scriptContext))
{
return scriptContext->GetLibrary()->GetTrue();
}
}
}
}
return scriptContext->GetLibrary()->GetFalse();
}
Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* dynamicObject = nullptr;
RecyclableObject* callBackFn = nullptr;
Var thisArg = nullptr;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
{
pArr = JavascriptArray::FromVar(args[0]);
dynamicObject = pArr;
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
}
if (JavascriptArray::Is(dynamicObject) && scriptContext == JavascriptArray::FromVar(dynamicObject)->GetScriptContext())
{
pArr = JavascriptArray::FromVar(dynamicObject);
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
}
callBackFn = RecyclableObject::FromVar(args[1]);
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
auto fn32 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint32 k, Var element)
{
CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
dynamicObject);
};
auto fn64 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint64 k, Var element)
{
CALL_FUNCTION(callBackFn, CallInfo(flags, 4), thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
dynamicObject);
};
if (pArr)
{
Assert(pArr == dynamicObject);
pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32);
}
else
{
if (length.IsSmallIndex())
{
TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32);
}
else
{
TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64);
}
}
return scriptContext->GetLibrary()->GetUndefined();
}
Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
int64 length;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
#endif
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.copyWithin"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
}
// Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
JavascriptLibrary* library = scriptContext->GetLibrary();
int64 fromVal = 0;
int64 toVal = 0;
int64 finalVal = length;
// If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
if (args.Info.Count > 1)
{
toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext);
if (args.Info.Count > 2)
{
fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
if (args.Info.Count > 3 && args[3] != library->GetUndefined())
{
finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
}
}
}
// If count would be negative or zero, we won't do anything so go ahead and return early.
if (finalVal <= fromVal || length <= toVal)
{
return obj;
}
// Make sure we won't underflow during the count calculation
Assert(finalVal > fromVal && length > toVal);
int64 count = min(finalVal - fromVal, length - toVal);
// We shouldn't have made it here if the count was going to be zero
Assert(count > 0);
int direction;
if (fromVal < toVal && toVal < (fromVal + count))
{
direction = -1;
fromVal += count - 1;
toVal += count - 1;
}
else
{
direction = 1;
}
// If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
// It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
|| (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
{
while (count > 0)
{
Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
if (JavascriptOperators::OP_HasItem(obj, index, scriptContext))
{
Var val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext);
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
else
{
JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
}
fromVal += direction;
toVal += direction;
count--;
}
}
else
{
Assert(fromVal < MaxArrayLength);
Assert(toVal < MaxArrayLength);
Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
uint32 fromIndex = static_cast<uint32>(fromVal);
uint32 toIndex = static_cast<uint32>(toVal);
while (count > 0)
{
if (obj->HasItem(fromIndex))
{
if (typedArrayBase)
{
Var val = typedArrayBase->DirectGetItem(fromIndex);
typedArrayBase->DirectSetItem(toIndex, val);
}
else if (pArr)
{
Var val = pArr->DirectGetItem(fromIndex);
pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
}
else
{
Var val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext);
JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
}
else
{
obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
}
fromIndex += direction;
toIndex += direction;
count--;
}
}
return obj;
}
Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
RecyclableObject* obj = nullptr;
JavascriptArray* pArr = nullptr;
int64 length;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.fill"));
}
// In ES6-mode, we always load the length property from the object instead of using the internal slot.
// Even for arrays, this is now observable via proxies.
// If source object is not an array, we fall back to this behavior anyway.
Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
length = JavascriptConversion::ToLength(lenValue, scriptContext);
}
return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
}
// Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
JavascriptLibrary* library = scriptContext->GetLibrary();
// If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
Var fillValue;
if (args.Info.Count > 1)
{
fillValue = args[1];
}
else
{
fillValue = library->GetUndefined();
}
int64 k = 0;
int64 finalVal = length;
if (args.Info.Count > 2)
{
k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
{
finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
}
}
if (k < MaxArrayLength)
{
int64 end = min<int64>(finalVal, MaxArrayLength);
uint32 u32k = static_cast<uint32>(k);
while (u32k < end)
{
if (typedArrayBase)
{
typedArrayBase->DirectSetItem(u32k, fillValue);
}
else if (pArr)
{
pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
}
else
{
JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
u32k++;
}
BigIndex dstIndex = MaxArrayLength;
for (int64 i = end; i < finalVal; ++i)
{
if (pArr)
{
pArr->DirectSetItemAt(dstIndex, fillValue);
++dstIndex;
}
else
{
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
}
}
else
{
BigIndex dstIndex = static_cast<uint64>(k);
for (int64 i = k; i < finalVal; i++)
{
if (pArr)
{
pArr->DirectSetItemAt(dstIndex, fillValue);
++dstIndex;
}
else
{
JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
}
}
}
return obj;
}
// Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
}
}
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
if (length.IsSmallIndex())
{
return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
template<typename T>
Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
RecyclableObject* newObj = nullptr;
JavascriptArray* newArr = nullptr;
bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
bool isBuiltinArrayCtor = true;
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (isTypedArrayEntryPoint)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
}
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
// If the entry point is %TypedArray%.prototype.map or the source object is an Array exotic object we should try to load the constructor property
// and use it to construct the return object.
if (isTypedArrayEntryPoint)
{
Var constructor = JavascriptOperators::SpeciesConstructor(
typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
if (JavascriptOperators::IsConstructor(constructor))
{
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext));
}
else if (isTypedArrayEntryPoint)
{
// We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.map was called
JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("[TypedArray].prototype.map"));
}
}
// skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
{
newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
}
if (newObj == nullptr)
{
if (length > UINT_MAX)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
newArr->EnsureHead<Var>();
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
Var element = nullptr;
Var mappedValue = nullptr;
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags callBackFnflags = CallFlags_Value;
CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
// We at least have to have newObj as a valid object
Assert(newObj);
if (pArr != nullptr)
{
// If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
// If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
if (newArr && isBuiltinArrayCtor)
{
newArr->DirectSetItemAt(k, mappedValue);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue), scriptContext, k);
}
}
}
else if (typedArrayBase != nullptr)
{
// Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
TypedArrayBase* newTypedArray = nullptr;
if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
for (uint32 k = 0; k < length; k++)
{
// We can't rely on the length value being equal to typedArrayBase->GetLength() because user code may lie and
// attach any length property to a TypedArray instance and pass it as this parameter when .calling
// Array.prototype.map.
if (!typedArrayBase->HasItem(k))
{
// We know that if HasItem returns false, all the future calls to HasItem will return false as well since
// we visit the items in order. We could return early here except that we have to continue calling HasItem
// on all the subsequent items according to the spec.
continue;
}
element = typedArrayBase->DirectGetItem(k);
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
// If newObj is a TypedArray, set the mappedValue directly, otherwise see if it's an array and finally fall back to
// the normal Set path.
if (newTypedArray)
{
newTypedArray->DirectSetItem(k, mappedValue);
}
else if (newArr)
{
newArr->DirectSetItemAt(k, mappedValue);
}
else
{
JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue);
}
}
}
else
{
for (uint32 k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
mappedValue = CALL_FUNCTION(callBackFn, callBackFnInfo, thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (newArr && isBuiltinArrayCtor)
{
newArr->SetItem(k, mappedValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue), scriptContext, k);
}
}
}
}
#ifdef VALIDATE_ARRAY
if (JavascriptArray::Is(newObj))
{
newArr->ValidateArray();
}
#endif
return newObj;
}
Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
}
BigIndex length;
JavascriptArray* pArr = nullptr;
RecyclableObject* dynamicObject = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
dynamicObject = pArr;
}
else
{
if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::FilterHelper(pArr, dynamicObject, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::FilterHelper(pArr, dynamicObject, length.GetBigIndex(), args, scriptContext);
}
template <typename T>
Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var thisArg = nullptr;
if (args.Info.Count > 2)
{
thisArg = args[2];
}
else
{
thisArg = scriptContext->GetLibrary()->GetUndefined();
}
// If the source object is an Array exotic object we should try to load the constructor property and use it to construct the return object.
bool isBuiltinArrayCtor = true;
RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor);
JavascriptArray* newArr = nullptr;
if (newObj == nullptr)
{
newArr = scriptContext->GetLibrary()->CreateArray(0);
newArr->EnsureHead<Var>();
newObj = newArr;
}
else
{
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
Var element = nullptr;
Var selected = nullptr;
if (pArr)
{
Assert(length <= MaxArrayLength);
uint32 i = 0;
for (uint32 k = 0; k < length; k++)
{
if (!pArr->DirectGetItemAtFull(k, &element))
{
continue;
}
selected = CALL_ENTRYPOINT(callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
if (JavascriptConversion::ToBoolean(selected, scriptContext))
{
// Try to fast path if the return object is an array
if (newArr && isBuiltinArrayCtor)
{
newArr->DirectSetItemAt(i, element);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
++i;
}
}
}
else
{
BigIndex i = 0u;
for (T k = 0; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
selected = CALL_ENTRYPOINT(callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
thisArg,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
if (JavascriptConversion::ToBoolean(selected, scriptContext))
{
if (newArr)
{
newArr->DirectSetItemAt(i, element);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i);
}
++i;
}
}
}
}
#ifdef VALIDATE_ARRAY
if (newArr)
{
newArr->ValidateArray();
}
#endif
return newObj;
}
Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
}
BigIndex length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
length = pArr->length;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
template <typename T>
Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
}
}
// If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
T k = 0;
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var accumulator = nullptr;
Var element = nullptr;
if (args.Info.Count > 2)
{
accumulator = args[2];
}
else
{
if (length == 0)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
bool bPresent = false;
if (pArr)
{
for (; k < length && bPresent == false; k++)
{
if (!pArr->DirectGetItemAtFull((uint32)k, &element))
{
continue;
}
bPresent = true;
accumulator = element;
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length && bPresent == false; k++)
{
if (!typedArrayBase->HasItem((uint32)k))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)k);
bPresent = true;
accumulator = element;
}
}
else
{
for (; k < length && bPresent == false; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
accumulator = JavascriptOperators::GetItem(obj, k, scriptContext);
bPresent = true;
}
}
}
if (bPresent == false)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
}
Assert(accumulator);
Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
if (pArr)
{
for (; k < length; k++)
{
if (!pArr->DirectGetItemAtFull((uint32)k, &element))
{
continue;
}
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
pArr);
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length; k++)
{
if (!typedArrayBase->HasItem((uint32)k))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)k);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
typedArrayBase);
}
}
else
{
for (; k < length; k++)
{
if (JavascriptOperators::HasItem(obj, k))
{
element = JavascriptOperators::GetItem(obj, k, scriptContext);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(k, scriptContext),
obj);
}
}
}
return accumulator;
}
Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
}
BigIndex length;
JavascriptArray * pArr = nullptr;
RecyclableObject* obj = nullptr;
if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
{
pArr = JavascriptArray::FromVar(args[0]);
obj = pArr;
}
else
{
if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
}
}
if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
{
length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
else
{
length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
}
if (length.IsSmallIndex())
{
return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
}
return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
}
// Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
template <typename T>
Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
{
if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
{
if (typedArrayBase != nullptr)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
}
else
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
}
}
// If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
{
typedArrayBase = TypedArrayBase::FromVar(obj);
}
RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
Var accumulator = nullptr;
Var element = nullptr;
T k = 0;
T index = 0;
if (args.Info.Count > 2)
{
accumulator = args[2];
}
else
{
if (length == 0)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
bool bPresent = false;
if (pArr)
{
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (!pArr->DirectGetItemAtFull((uint32)index, &element))
{
continue;
}
bPresent = true;
accumulator = element;
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (!typedArrayBase->HasItem((uint32)index))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)index);
bPresent = true;
accumulator = element;
}
}
else
{
for (; k < length && bPresent == false; k++)
{
index = length - k - 1;
if (JavascriptOperators::HasItem(obj, index))
{
accumulator = JavascriptOperators::GetItem(obj, index, scriptContext);
bPresent = true;
}
}
}
if (bPresent == false)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
}
// The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
CallFlags flags = CallFlags_Value;
Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
if (pArr)
{
for (; k < length; k++)
{
index = length - k - 1;
if (!pArr->DirectGetItemAtFull((uint32)index, &element))
{
continue;
}
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
pArr);
}
}
else if (typedArrayBase)
{
Assert(length <= UINT_MAX);
for (; k < length; k++)
{
index = length - k - 1;
if (!typedArrayBase->HasItem((uint32) index))
{
continue;
}
element = typedArrayBase->DirectGetItem((uint32)index);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
typedArrayBase);
}
}
else
{
for (; k < length; k++)
{
index = length - k - 1;
if (JavascriptOperators::HasItem(obj, index))
{
element = JavascriptOperators::GetItem(obj, index, scriptContext);
accumulator = CALL_FUNCTION(callBackFn, CallInfo(flags, 5), undefinedValue,
accumulator,
element,
JavascriptNumber::ToVar(index, scriptContext),
obj);
}
}
}
return accumulator;
}
Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
Assert(!(callInfo.Flags & CallFlags_New));
JavascriptLibrary* library = scriptContext->GetLibrary();
RecyclableObject* constructor = nullptr;
if (JavascriptOperators::IsConstructor(args[0]))
{
constructor = RecyclableObject::FromVar(args[0]);
}
RecyclableObject* items = nullptr;
if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
}
JavascriptArray* itemsArr = nullptr;
if (JavascriptArray::Is(items))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
#endif
itemsArr = JavascriptArray::FromVar(items);
}
bool mapping = false;
JavascriptFunction* mapFn = nullptr;
Var mapFnThisArg = nullptr;
if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
{
if (!JavascriptFunction::Is(args[2]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
}
mapFn = JavascriptFunction::FromVar(args[2]);
if (args.Info.Count >= 4)
{
mapFnThisArg = args[3];
}
else
{
mapFnThisArg = library->GetUndefined();
}
mapping = true;
}
RecyclableObject* newObj = nullptr;
JavascriptArray* newArr = nullptr;
RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */);
if (iterator != nullptr)
{
if (constructor)
{
Js::Var constructorArgs[] = { constructor };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
{
newArr = scriptContext->GetLibrary()->CreateArray(0);
newArr->EnsureHead<Var>();
newObj = newArr;
}
uint32 k = 0;
JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
if (mapping)
{
Assert(mapFn != nullptr);
Assert(mapFnThisArg != nullptr);
Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
}
if (newArr)
{
newArr->SetItem(k, nextValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, nextValue), scriptContext, k);
}
k++;
});
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
else
{
Var lenValue = JavascriptOperators::OP_GetLength(items, scriptContext);
int64 len = JavascriptConversion::ToLength(lenValue, scriptContext);
if (constructor)
{
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
}
else
{
// Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
if (len > MaxArrayLength)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
}
// Static cast len should be valid (len < 2^32) or we would throw above
newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
newArr->EnsureHead<Var>();
newObj = newArr;
}
uint32 k = 0;
for ( ; k < len; k++)
{
Var kValue;
if (itemsArr)
{
kValue = itemsArr->DirectGetItem(k);
}
else
{
kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext);
}
if (mapping)
{
Assert(mapFn != nullptr);
Assert(mapFnThisArg != nullptr);
Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
}
if (newArr)
{
newArr->SetItem(k, kValue, PropertyOperation_None);
}
else
{
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k);
}
}
JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
}
return newObj;
}
Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
if (args.Info.Count == 0)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
}
return JavascriptArray::OfHelper(false, args, scriptContext);
}
Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
Assert(args.Info.Count > 0);
return args[0];
}
// Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
{
Assert(args.Info.Count > 0);
// args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
uint32 len = args.Info.Count - 1;
Var newObj = nullptr;
JavascriptArray* newArr = nullptr;
TypedArrayBase* newTypedArray = nullptr;
bool isBuiltinArrayCtor = true;
if (JavascriptOperators::IsConstructor(args[0]))
{
RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
newObj = isTypedArrayEntryPoint ?
TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext) :
JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
// If the new object we created is an array, remember that as it will save us time setting properties in the object below
if (JavascriptArray::Is(newObj))
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
#endif
newArr = JavascriptArray::FromVar(newObj);
}
else if (TypedArrayBase::Is(newObj))
{
newTypedArray = TypedArrayBase::FromVar(newObj);
}
}
else
{
// We only throw when the constructor property is not a constructor function in the TypedArray version
if (isTypedArrayEntryPoint)
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
}
newArr = scriptContext->GetLibrary()->CreateArray(len);
newArr->EnsureHead<Var>();
newObj = newArr;
}
// At least we have a new object of some kind
Assert(newObj);
if (isBuiltinArrayCtor)
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
newArr->DirectSetItemAt(k, kValue);
}
}
else if (newTypedArray)
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
newTypedArray->DirectSetItem(k, kValue);
}
}
else
{
for (uint32 k = 0; k < len; k++)
{
Var kValue = args[k + 1];
ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k);
}
}
if (!isTypedArrayEntryPoint)
{
// Set length if we are in the Array version of the function
JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible);
}
return newObj;
}
JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
{
TypeId typeId = JavascriptOperators::GetTypeId(value);
if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
{
return scriptContext->GetLibrary()->GetEmptyString();
}
else
{
return JavascriptConversion::ToLocaleString(value, scriptContext);
}
}
inline BOOL JavascriptArray::IsFullArray() const
{
if (head && head->length == length)
{
AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
return true;
}
return (0 == length);
}
/*
* IsFillFromPrototypes
* - Check the array has no missing values and only head segment.
* - Also ensure if the lengths match.
*/
bool JavascriptArray::IsFillFromPrototypes()
{
return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
}
// Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
// typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
{
if (startIndex >= limitIndex)
{
return;
}
RecyclableObject* prototype = this->GetPrototype();
// Fill all missing values by walking through prototype
while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
{
ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
this->SetItem(index, value, PropertyOperation_None);
});
prototype = prototype->GetPrototype();
}
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
}
//
// JavascriptArray requires head->left == 0 for fast path Get.
//
template<typename T>
void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
{
if (head == nullptr || head->left != 0)
{
// This is used to fix up altered arrays.
// any SegmentMap would be invalid at this point.
ClearSegmentMap();
//
// We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
// some protection here. Save the head and switch this array to EmptySegment. Will be restored
// correctly if allocating new segment succeeds.
//
SparseArraySegment<T>* savedHead = (SparseArraySegment<T>*)this->head;
SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
newSeg->next = savedHead;
this->head = newSeg;
SetHasNoMissingValues();
this->SetLastUsedSegment(savedLastUsedSegment);
}
}
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
void JavascriptArray::CheckForceES5Array()
{
if (Configuration::Global.flags.ForceES5Array)
{
// There's a bad interaction with the jitted code for native array creation here.
// ForceES5Array doesn't interact well with native arrays
if (PHASE_OFF1(NativeArrayPhase))
{
GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
}
}
}
#endif
template <typename T, typename Fn>
void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, T destIndex, Fn fn)
{
Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
Var oldValue;
JavascriptArray* arr = nullptr;
if (DynamicObject::IsAnyArray(obj))
{
arr = JavascriptArray::FromAnyArray(obj);
}
else if (DynamicType::Is(obj->GetTypeId()))
{
DynamicObject* dynobj = DynamicObject::FromVar(obj);
ArrayObject* objectArray = dynobj->GetObjectArray();
arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
}
if (arr != nullptr)
{
if (JavascriptArray::Is(arr))
{
arr = EnsureNonNativeArray(arr);
ArrayElementEnumerator e(arr, startIndex, limitIndex);
while(e.MoveNext<Var>())
{
uint32 index = e.GetIndex();
if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
{
T n = destIndex + (index - startIndex);
if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
{
fn(index, e.GetItem<Var>());
}
}
}
}
else
{
ScriptContext* scriptContext = obj->GetScriptContext();
Assert(ES5Array::Is(arr));
ES5Array* es5Array = ES5Array::FromVar(arr);
ES5ArrayIndexStaticEnumerator<true> e(es5Array);
while (e.MoveNext())
{
uint32 index = e.GetIndex();
if (index < startIndex) continue;
else if (index >= limitIndex) break;
if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
{
T n = destIndex + (index - startIndex);
if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
{
Var value = nullptr;
if (JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext))
{
fn(index, value);
}
}
}
}
}
}
}
//
// ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
//
JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
: start(start), end(min(end, arr->length))
{
Init(arr);
}
//
// Initialize this enumerator and prepare for the first MoveNext.
//
void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
{
// Find start segment
seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
while (seg && (seg->left + seg->length <= start))
{
seg = seg->next;
}
// Set start index and endIndex
if (seg)
{
if (seg->left >= end)
{
seg = nullptr;
}
else
{
// set index to be at target index - 1, so MoveNext will move to target
index = max(seg->left, start) - seg->left - 1;
endIndex = min(end - seg->left, seg->length);
}
}
}
//
// Move to the next element if available.
//
template<typename T>
inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
{
while (seg)
{
// Look for next non-null item in current segment
while (++index < endIndex)
{
if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
{
return true;
}
}
// Move to next segment
seg = seg->next;
if (seg)
{
if (seg->left >= end)
{
seg = nullptr;
break;
}
else
{
index = static_cast<uint32>(-1);
endIndex = min(end - seg->left, seg->length);
}
}
}
return false;
}
//
// Get current array element index.
//
uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
{
Assert(seg && index < seg->length && index < endIndex);
return seg->left + index;
}
//
// Get current array element value.
//
template<typename T>
T JavascriptArray::ArrayElementEnumerator::GetItem() const
{
Assert(seg && index < seg->length && index < endIndex &&
!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
return ((SparseArraySegment<T>*)seg)->elements[index];
}
//
// Construct a BigIndex initialized to a given uint32 (small index).
//
JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
: index(initIndex), bigIndex(InvalidIndex)
{
//ok if initIndex == InvalidIndex
}
//
// Construct a BigIndex initialized to a given uint64 (large or small index).
//
JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
: index(InvalidIndex), bigIndex(initIndex)
{
if (bigIndex < InvalidIndex) // if it's actually small index
{
index = static_cast<uint32>(bigIndex);
bigIndex = InvalidIndex;
}
}
bool JavascriptArray::BigIndex::IsUint32Max() const
{
return index == InvalidIndex && bigIndex == InvalidIndex;
}
bool JavascriptArray::BigIndex::IsSmallIndex() const
{
return index < InvalidIndex;
}
uint32 JavascriptArray::BigIndex::GetSmallIndex() const
{
Assert(IsSmallIndex());
return index;
}
uint64 JavascriptArray::BigIndex::GetBigIndex() const
{
Assert(!IsSmallIndex());
return bigIndex;
}
//
// Convert this index value to a JS number
//
Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
{
if (IsSmallIndex())
{
return small_index::ToNumber(index, scriptContext);
}
else
{
return JavascriptNumber::ToVar(bigIndex, scriptContext);
}
}
//
// Increment this index by 1.
//
const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
{
if (IsSmallIndex())
{
++index;
// If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
}
else
{
bigIndex = bigIndex + 1;
}
return *this;
}
//
// Decrement this index by 1.
//
const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
{
if (IsSmallIndex())
{
--index;
}
else
{
Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
--bigIndex;
if (bigIndex < InvalidIndex)
{
index = InvalidIndex - 1;
bigIndex = InvalidIndex;
}
}
return *this;
}
JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
{
if (delta.IsSmallIndex())
{
return operator+(delta.GetSmallIndex());
}
if (IsSmallIndex())
{
return index + delta.GetBigIndex();
}
return bigIndex + delta.GetBigIndex();
}
//
// Get a new BigIndex representing this + delta.
//
JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
{
if (IsSmallIndex())
{
uint32 newIndex;
if (UInt32Math::Add(index, delta, &newIndex))
{
return static_cast<uint64>(index) + static_cast<uint64>(delta);
}
else
{
return newIndex; // ok if newIndex == InvalidIndex
}
}
else
{
return bigIndex + static_cast<uint64>(delta);
}
}
bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() == rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
}
return this->GetBigIndex() == rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() > rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
}
return this->GetBigIndex() > rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() < rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
}
return this->GetBigIndex() < rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() <= rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
}
return this->GetBigIndex() <= rhs.GetBigIndex();
}
bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
{
if (rhs.IsSmallIndex() && this->IsSmallIndex())
{
return this->GetSmallIndex() >= rhs.GetSmallIndex();
}
else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
{
// if lhs is big promote rhs
return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
}
else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
{
// if rhs is big promote lhs
return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
}
return this->GetBigIndex() >= rhs.GetBigIndex();
}
BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
{
if (IsSmallIndex())
{
return small_index::GetItem(arr, index, outVal);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
}
}
BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
{
if (IsSmallIndex())
{
return small_index::SetItem(arr, index, newValue);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
}
}
void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
{
if (IsSmallIndex())
{
small_index::SetItemIfNotExist(arr, index, newValue);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
Var oldValue;
PropertyId propertyId = propertyRecord->GetPropertyId();
if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
{
arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
}
}
}
BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
{
if (IsSmallIndex())
{
return small_index::DeleteItem(arr, index);
}
else
{
ScriptContext* scriptContext = arr->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
}
}
BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
{
if (IsSmallIndex())
{
return small_index::SetItem(obj, index, newValue, flags);
}
else
{
ScriptContext* scriptContext = obj->GetScriptContext();
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
}
}
BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
{
if (IsSmallIndex())
{
return small_index::DeleteItem(obj, index, flags);
}
else
{
PropertyRecord const * propertyRecord;
JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
}
}
//
// Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
//
void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
{
Assert(!dstIndex.IsSmallIndex());
typedef IndexTrace<BigIndex> index_trace;
BigIndex dst = dstIndex;
uint32 i = start;
ArrayElementEnumerator e(this, start);
while(e.MoveNext<Var>())
{
// delete all items not enumerated
while (i < e.GetIndex())
{
index_trace::DeleteItem(this, dst);
++i;
++dst;
}
// Copy over the item
index_trace::SetItem(this, dst, e.GetItem<Var>());
++i;
++dst;
}
// Delete the rest till length
while (i < this->length)
{
index_trace::DeleteItem(this, dst);
++i;
++dst;
}
// Elements moved, truncate the array at start
SetLength(start);
}
//
// Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
//
template<typename T>
void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<Var>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<Var>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
//
// Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index. If the index grows larger than
// "array index", it will automatically turn to SetProperty using the index as property name.
//
void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
template <typename T>
void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
#endif
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
#endif
if (JavascriptNativeIntArray::Is(srcArray))
{
CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
}
else if (JavascriptNativeFloatArray::Is(srcArray))
{
CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
}
else
{
CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyNativeIntArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<int32>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
uint32 len = end - start;
if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
{
// Won't overflow, use faster small_index version
InternalCopyNativeFloatArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
}
else
{
InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
}
//
// Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
//
void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start < end)
{
Assert(end - start <= MaxArrayLength - dstIndex);
InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
}
}
bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
end = min(end, srcArray->length);
if (start >= end)
{
return false;
}
Assert(end - start <= MaxArrayLength - dstIndex);
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<double>())
{
uint n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, e.GetItem<double>());
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
return true;
}
return false;
}
JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
#endif
if (JavascriptNativeIntArray::Is(arr))
{
arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
}
else if (JavascriptNativeFloatArray::Is(arr))
{
arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
}
return arr;
}
BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
ScriptContext* requestContext = type->GetScriptContext();
if (JavascriptNativeIntArray::GetItem(this, index, outVal, requestContext))
{
return TRUE;
}
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
{
ScriptContext* requestContext = type->GetScriptContext();
if (JavascriptNativeFloatArray::GetItem(this, index, outVal, requestContext))
{
return TRUE;
}
return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
}
template<typename T>
void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ScriptContext *scriptContext = dstArray->GetScriptContext();
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<int32>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
template<typename T>
void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
{
Assert(start < end && end <= srcArray->length);
uint32 count = 0;
// iterate on the array itself
ScriptContext *scriptContext = dstArray->GetScriptContext();
ArrayElementEnumerator e(srcArray, start, end);
while(e.MoveNext<double>())
{
T n = dstIndex + (e.GetIndex() - start);
dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
count++;
}
// iterate on the array's prototypes only if not all elements found
if (start + count != end)
{
InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
}
}
Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
{
// At this stage we have an array literal with some arguments to be spread.
// First we need to calculate the real size of the final literal.
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
#endif
JavascriptArray *array = FromVar(arrayToSpread);
uint32 actualLength = array->GetLength();
for (unsigned i = 0; i < spreadIndices->count; ++i)
{
actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext));
}
JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
// Now we copy each element and expand the spread parameters inline.
for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < array->GetLength() && resultIndex < actualLength; ++i)
{
uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
// An array needs a slow copy if it is a cross-site object or we have missing values that need to be set to undefined.
auto needArraySlowCopy = [&](Var instance) {
if (JavascriptArray::Is(instance))
{
JavascriptArray *arr = JavascriptArray::FromVar(instance);
return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes();
}
return false;
};
// Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
auto slowCopy = [&scriptContext, &needArraySlowCopy](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
RecyclableObject *propertyObject;
if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
}
for (uint32 j = start; j < end; j++)
{
Var element;
if (!JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext))
{
// Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
element = scriptContext->GetLibrary()->GetUndefined();
}
dstArray->DirectSetItemAt(dstIndex++, element);
}
};
if (i < spreadIndex)
{
// Any non-spread elements can be copied in bulk.
if (needArraySlowCopy(array))
{
slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex);
}
resultIndex += spreadIndex - i;
i = spreadIndex - 1;
continue;
}
else if (i > spreadIndex)
{
// Any non-spread elements terminating the array can also be copied in bulk.
Assert(spreadArrIndex == spreadIndices->count - 1);
if (needArraySlowCopy(array))
{
slowCopy(result, resultIndex, array, i, array->GetLength());
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, array, i, array->GetLength());
}
break;
}
else
{
Var instance = array->DirectGetItem(i);
if (SpreadArgument::Is(instance))
{
SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
uint32 len = spreadArgument->GetArgumentSpreadCount();
const Var* spreadItems = spreadArgument->GetArgumentSpread();
for (uint32 j = 0; j < len; j++)
{
result->DirectSetItemAt(resultIndex++, spreadItems[j]);
}
}
else
{
AssertMsg(JavascriptArray::Is(instance) || TypedArrayBase::Is(instance), "Only SpreadArgument, TypedArray, and JavascriptArray should be listed as spread arguments");
// We first try to interpret the spread parameter as a JavascriptArray.
JavascriptArray *arr = nullptr;
if (JavascriptArray::Is(instance))
{
arr = JavascriptArray::FromVar(instance);
}
if (arr != nullptr)
{
if (arr->GetLength() > 0)
{
if (needArraySlowCopy(arr))
{
slowCopy(result, resultIndex, arr, 0, arr->GetLength());
}
else
{
CopyAnyArrayElementsToVar(result, resultIndex, arr, 0, arr->GetLength());
}
resultIndex += arr->GetLength();
}
}
else
{
uint32 len = GetSpreadArgLen(instance, scriptContext);
slowCopy(result, resultIndex, instance, 0, len);
resultIndex += len;
}
}
if (spreadArrIndex < spreadIndices->count - 1)
{
spreadArrIndex++;
}
}
}
return result;
}
uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
{
// A spread argument can be anything that returns a 'length' property, even if that
// property is null or undefined.
spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
if (JavascriptArray::Is(spreadArg))
{
JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
return arr->GetLength();
}
if (TypedArrayBase::Is(spreadArg))
{
TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
return tarr->GetLength();
}
if (SpreadArgument::Is(spreadArg))
{
SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
return spreadFunctionArgs->GetArgumentSpreadCount();
}
AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
Throw::FatalInternalError();
}
#ifdef VALIDATE_ARRAY
class ArraySegmentsVisitor
{
private:
SparseArraySegmentBase* seg;
public:
ArraySegmentsVisitor(SparseArraySegmentBase* head)
: seg(head)
{
}
void operator()(SparseArraySegmentBase* s)
{
Assert(seg == s);
if (seg)
{
seg = seg->next;
}
}
};
void JavascriptArray::ValidateArrayCommon()
{
SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
// Simple segments validation
bool foundLastUsedSegment = false;
SparseArraySegmentBase *seg = head;
while(seg != nullptr)
{
if (seg == lastUsedSegment)
{
foundLastUsedSegment = true;
}
AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
SparseArraySegmentBase* next = seg->next;
if (next != nullptr)
{
AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
else
{
AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
}
seg = next;
}
AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
// Validate segmentMap if present
if (HasSegmentMap())
{
ArraySegmentsVisitor visitor(head);
GetSegmentMap()->Walk(visitor);
}
}
void JavascriptArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateVarSegment((SparseArraySegment<Var>*)head);
}
void JavascriptNativeIntArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
#if DBG
SparseArraySegmentBase *seg = head;
while (seg)
{
if (seg->next != nullptr)
{
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
seg = seg->next;
}
#endif
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateSegment<int32>((SparseArraySegment<int32>*)head);
}
void JavascriptNativeFloatArray::ValidateArray()
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
#if DBG
SparseArraySegmentBase *seg = head;
while (seg)
{
if (seg->next != nullptr)
{
AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
}
seg = seg->next;
}
#endif
return;
}
ValidateArrayCommon();
// Detailed segments validation
JavascriptArray::ValidateSegment<double>((SparseArraySegment<double>*)head);
}
void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
int32 inspect;
double inspectDouble;
while (seg)
{
uint32 i = 0;
for (i = 0; i < seg->length; i++)
{
if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
{
continue;
}
if (TaggedInt::Is(seg->elements[i]))
{
inspect = TaggedInt::ToInt32(seg->elements[i]);
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
{
inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
}
else
{
AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
}
}
ValidateSegment(seg);
seg = (SparseArraySegment<Var>*)seg->next;
}
}
template<typename T>
void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
{
if (!Js::Configuration::Global.flags.ArrayValidate)
{
return;
}
while (seg)
{
uint32 i = seg->length;
while (i < seg->size)
{
AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
i++;
}
seg = (SparseArraySegment<T>*)seg->next;
}
}
#endif
template <typename T>
void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
{
// Don't copy the segment map, we will build it again
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
SetHeadAndLastUsedSegment(dst);
dst->left = src->left;
dst->length = src->length;
dst->size = src->size;
dst->next = src->next;
js_memcpy_s(dst->elements, sizeof(T) * dst->size, src->elements, sizeof(T) * src->size);
}
JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
: ArrayObject(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), (SparseArraySegment<Var>*)instance->head);
}
else
{
SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
head = instance->head;
SetLastUsedSegment(instance->GetLastUsedSegment());
}
}
template <typename T>
T * JavascriptArray::BoxStackInstance(T * instance)
{
Assert(ThreadContext::IsOnStack(instance));
// On the stack, the we reserved a pointer before the object as to store the boxed value
T ** boxedInstanceRef = ((T **)instance) - 1;
T * boxedInstance = *boxedInstanceRef;
if (boxedInstance)
{
return boxedInstance;
}
const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
if (ThreadContext::IsOnStack(instance->head))
{
boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
T, instance, true);
}
else if(inlineSlotsSize)
{
boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
}
else
{
boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
}
*boxedInstanceRef = boxedInstance;
return boxedInstance;
}
JavascriptArray *
JavascriptArray::BoxStackInstance(JavascriptArray * instance)
{
return BoxStackInstance<JavascriptArray>(instance);
}
#if ENABLE_TTD
void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
ScriptContext* ctx = this->GetScriptContext();
uint32 index = Js::JavascriptArray::InvalidIndex;
while(true)
{
index = this->GetNextIndex(index);
if(index == Js::JavascriptArray::InvalidIndex) // End of array
{
break;
}
Js::Var aval = nullptr;
if(this->DirectGetVarItemAt(index, &aval, ctx))
{
extractor->MarkVisitVar(aval);
}
}
}
void JavascriptArray::ProcessCorePaths()
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
ScriptContext* ctx = this->GetScriptContext();
uint32 index = Js::JavascriptArray::InvalidIndex;
while(true)
{
index = this->GetNextIndex(index);
if(index == Js::JavascriptArray::InvalidIndex) // End of array
{
break;
}
Js::Var aval = nullptr;
if(this->DirectGetVarItemAt(index, &aval, ctx))
{
TTD::UtilSupport::TTAutoString pathExt;
ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
}
}
}
TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
}
void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
}
#endif
JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
JavascriptArray(instance, false),
weakRefToFuncBody(instance->weakRefToFuncBody)
{
}
JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
JavascriptNativeArray(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), (SparseArraySegment<int>*)instance->head);
}
else
{
// Base class ctor should have copied these
Assert(head == instance->head);
Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
}
}
JavascriptNativeIntArray *
JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
{
return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
}
#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
}
void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
}
#if ENABLE_COPYONACCESS_ARRAY
TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::Invalid;
}
void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(false, "Not implemented yet!!!");
}
#endif
#endif
JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
JavascriptNativeArray(instance)
{
if (boxHead)
{
InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), (SparseArraySegment<double>*)instance->head);
}
else
{
// Base class ctor should have copied these
Assert(head == instance->head);
Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
}
}
JavascriptNativeFloatArray *
JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
{
return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
}
#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
{
return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
}
void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
}
#endif
template<typename T>
RecyclableObject*
JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
{
if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
{
return nullptr;
}
if (JavascriptArray::Is(originalArray)
&& !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
&& DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
&& !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
{
return nullptr;
}
Var constructor = scriptContext->GetLibrary()->GetUndefined();
if (JavascriptOperators::IsArray(originalArray))
{
if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
{
return nullptr;
}
if (JavascriptOperators::IsConstructor(constructor))
{
ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
if (constructorScriptContext != scriptContext)
{
if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
{
constructor = scriptContext->GetLibrary()->GetUndefined();
}
}
}
if (JavascriptOperators::IsObject(constructor))
{
if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
{
if (pIsBuiltinArrayCtor != nullptr)
{
*pIsBuiltinArrayCtor = false;
}
return nullptr;
}
if (constructor == scriptContext->GetLibrary()->GetNull())
{
constructor = scriptContext->GetLibrary()->GetUndefined();
}
}
}
if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
{
if (length > UINT_MAX)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
}
if (nullptr == pIsIntArray)
{
return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
}
else
{
// If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
}
}
if (!JavascriptOperators::IsConstructor(constructor))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
}
if (pIsBuiltinArrayCtor != nullptr)
{
*pIsBuiltinArrayCtor = false;
}
Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
}
/*static*/
PropertyId const JavascriptArray::specialPropertyIds[] =
{
PropertyIds::length
};
BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::DeleteProperty(propertyId, flags);
}
BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
{
JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
if (BuiltInPropertyRecords::length.Equals(propertyName))
{
return false;
}
return DynamicObject::DeleteProperty(propertyNameString, flags);
}
BOOL JavascriptArray::HasProperty(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return true;
}
ScriptContext* scriptContext = GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return this->HasItem(index);
}
return DynamicObject::HasProperty(propertyId);
}
BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::IsEnumerable(propertyId);
}
BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
{
if (propertyId == PropertyIds::length)
{
return false;
}
return DynamicObject::IsConfigurable(propertyId);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
{
if (propertyId == PropertyIds::length)
{
Assert(!value); // Can't change array length enumerable
return true;
}
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetEnumerable(this, propertyId, value);
}
return __super::SetEnumerable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
{
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetWritable(this, propertyId, value);
}
return __super::SetWritable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
{
if (propertyId == PropertyIds::length)
{
Assert(!value); // Can't change array length configurable
return true;
}
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetConfigurable(this, propertyId, value);
}
return __super::SetConfigurable(propertyId, value);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
{
ScriptContext* scriptContext = this->GetScriptContext();
// SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
// changed, we need to handle it here.
Assert(propertyId != PropertyIds::length);
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAttributes(this, index, attributes);
}
return __super::SetAttributes(propertyId, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
{
ScriptContext* scriptContext = this->GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAccessors(this, index, getter, setter);
}
return __super::SetAccessors(propertyId, getter, setter, flags);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemWithAttributes(this, index, value, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAttributes(this, index, attributes);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
->SetItemAccessors(this, index, getter, setter);
}
// Check if this objectArray isFrozen.
BOOL JavascriptArray::IsObjectArrayFrozen()
{
// If this is still a JavascriptArray, it's not frozen.
return false;
}
JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
{
if (!!(flags & EnumeratorFlags::SnapShotSemantics))
{
return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
}
return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
}
BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
{
return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
}
BOOL JavascriptArray::IsItemEnumerable(uint32 index)
{
return true;
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::PreventExtensions()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::Seal()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
}
//
// Evolve typeHandlers explicitly so that simple typeHandlers can skip array
// handling and only check instance objectArray for numeric propertyIds.
//
BOOL JavascriptArray::Freeze()
{
return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
}
BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext)
{
if (index == 0)
{
*propertyName = requestContext->GetPropertyString(PropertyIds::length);
return true;
}
return false;
}
// Returns the number of special non-enumerable properties this type has.
uint JavascriptArray::GetSpecialPropertyCount() const
{
return _countof(specialPropertyIds);
}
// Returns the list of special non-enumerable properties for the type.
PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
{
return specialPropertyIds;
}
BOOL JavascriptArray::GetPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
return JavascriptArray::GetProperty(originalInstance, propertyId, value, info, requestContext);
}
BOOL JavascriptArray::GetProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
if (GetPropertyBuiltIns(propertyId, value))
{
return true;
}
ScriptContext* scriptContext = GetScriptContext();
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
return this->GetItem(this, index, value, scriptContext);
}
return DynamicObject::GetProperty(originalInstance, propertyId, value, info, requestContext);
}
BOOL JavascriptArray::GetProperty(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
{
AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
"Numeric property names should have been converted to uint or PropertyRecord*");
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
{
return true;
}
return DynamicObject::GetProperty(originalInstance, propertyNameString, value, info, requestContext);
}
BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
{
//
// length being accessed. Return array length
//
if (propertyId == PropertyIds::length)
{
*value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
return true;
}
return false;
}
BOOL JavascriptArray::HasItem(uint32 index)
{
Var value;
return this->DirectGetItemAt<Var>(index, &value);
}
BOOL JavascriptArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
return this->DirectGetItemAt<Var>(index, value);
}
BOOL JavascriptNativeIntArray::HasItem(uint32 index)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
int32 value;
return this->DirectGetItemAt<int32>(index, &value);
}
BOOL JavascriptNativeFloatArray::HasItem(uint32 index)
{
double dvalue;
return this->DirectGetItemAt<double>(index, &dvalue);
}
BOOL JavascriptNativeIntArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
return JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext);
}
BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
int32 intvalue;
if (!this->DirectGetItemAt<int32>(index, &intvalue))
{
return FALSE;
}
*value = JavascriptNumber::ToVar(intvalue, requestContext);
return TRUE;
}
BOOL JavascriptNativeIntArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeIntArray::GetItem(originalInstance, index, value, requestContext);
}
BOOL JavascriptNativeFloatArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext);
}
BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
{
double dvalue;
int32 ivalue;
if (!this->DirectGetItemAt<double>(index, &dvalue))
{
return FALSE;
}
if (*(uint64*)&dvalue == 0ull)
{
*value = TaggedInt::ToVarUnchecked(0);
}
else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
{
*value = TaggedInt::ToVarUnchecked(ivalue);
}
else
{
*value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
}
return TRUE;
}
BOOL JavascriptNativeFloatArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
{
return JavascriptNativeFloatArray::GetItem(originalInstance, index, value, requestContext);
}
BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
uint32 indexValue;
if (propertyId == PropertyIds::length)
{
return this->SetLength(value);
}
else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
{
// Call this or subclass method
return SetItem(indexValue, value, flags);
}
else
{
return DynamicObject::SetProperty(propertyId, value, flags, info);
}
}
BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
{
AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
"Numeric property names should have been converted to uint or PropertyRecord*");
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
PropertyRecord const* propertyRecord;
this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
{
return this->SetLength(value);
}
return DynamicObject::SetProperty(propertyNameString, value, flags, info);
}
BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
ScriptContext* scriptContext = GetScriptContext();
if (propertyId == PropertyIds::length)
{
Assert(attributes == PropertyWritable);
Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
return this->SetLength(value);
}
uint32 index;
if (scriptContext->IsNumericPropertyId(propertyId, &index))
{
// Call this or subclass method
return SetItemWithAttributes(index, value, attributes);
}
return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
}
BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
this->DirectSetItemAt(index, value);
return true;
}
BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
int32 iValue;
double dValue;
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
#endif
TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
if (typeId == TypeIds_NativeIntArray)
{
this->SetItem(index, iValue);
}
else if (typeId == TypeIds_NativeFloatArray)
{
reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
}
else
{
this->DirectSetItemAt<Var>(index, value);
}
return TRUE;
}
TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
{
if (TaggedInt::Is(value))
{
int32 i = TaggedInt::ToInt32(value);
if (i != JavascriptNativeIntArray::MissingItem)
{
*iValue = i;
return TypeIds_NativeIntArray;
}
}
if (JavascriptNumber::Is_NoTaggedIntCheck(value))
{
bool isInt32;
int32 i;
double d = JavascriptNumber::GetValue(value);
if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
{
if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
{
*iValue = i;
return TypeIds_NativeIntArray;
}
}
else
{
*dValue = d;
JavascriptNativeIntArray::ToNativeFloatArray(this);
return TypeIds_NativeFloatArray;
}
}
JavascriptNativeIntArray::ToVarArray(this);
return TypeIds_Array;
}
BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
{
if (iValue == JavascriptNativeIntArray::MissingItem)
{
JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
return TRUE;
}
this->DirectSetItemAt(index, iValue);
return TRUE;
}
BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
{
double dValue;
TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
if (typeId == TypeIds_NativeFloatArray)
{
this->SetItem(index, dValue);
}
else
{
this->DirectSetItemAt(index, value);
}
return TRUE;
}
TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
{
if (TaggedInt::Is(value))
{
*dValue = (double)TaggedInt::ToInt32(value);
return TypeIds_NativeFloatArray;
}
else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
{
*dValue = JavascriptNumber::GetValue(value);
return TypeIds_NativeFloatArray;
}
JavascriptNativeFloatArray::ToVarArray(this);
return TypeIds_Array;
}
BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
{
if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
{
JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
return TRUE;
}
this->DirectSetItemAt<double>(index, dValue);
return TRUE;
}
BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<Var>(index);
}
BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<int32>(index);
}
BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
{
return this->DirectDeleteItemAt<double>(index);
}
BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
{
return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
}
BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
{
stringBuilder->Append(_u('['));
if (this->length < 10)
{
auto funcPtr = [&]()
{
ENTER_PINNED_SCOPE(JavascriptString, valueStr);
valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
LEAVE_PINNED_SCOPE();
};
if (!requestContext->GetThreadContext()->IsScriptActive())
{
BEGIN_JS_RUNTIME_CALL(requestContext);
{
funcPtr();
}
END_JS_RUNTIME_CALL(requestContext);
}
else
{
funcPtr();
}
}
else
{
stringBuilder->AppendCppLiteral(_u("..."));
}
stringBuilder->Append(_u(']'));
return TRUE;
}
BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
{
stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
return TRUE;
}
bool JavascriptNativeArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeArray::Is(typeId);
}
bool JavascriptNativeArray::Is(TypeId typeId)
{
return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
}
JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
}
bool JavascriptNativeIntArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeIntArray::Is(typeId);
}
#if ENABLE_COPYONACCESS_ARRAY
bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
}
#endif
bool JavascriptNativeIntArray::Is(TypeId typeId)
{
return typeId == TypeIds_NativeIntArray;
}
#if ENABLE_COPYONACCESS_ARRAY
bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
{
return typeId == TypeIds_CopyOnAccessNativeIntArray;
}
#endif
bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
{
bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
return ret;
}
JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
}
#if ENABLE_COPYONACCESS_ARRAY
JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
}
#endif
bool JavascriptNativeFloatArray::Is(Var aValue)
{
TypeId typeId = JavascriptOperators::GetTypeId(aValue);
return JavascriptNativeFloatArray::Is(typeId);
}
bool JavascriptNativeFloatArray::Is(TypeId typeId)
{
return typeId == TypeIds_NativeFloatArray;
}
bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
{
bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
return ret;
}
JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
{
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
}
template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
} //namespace Js
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_2487_0 |
crossvul-cpp_data_good_1809_1 | /****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Jory Stone <jcsston @ toughguy.net>
*/
#include <cassert>
#if __GNUC__ == 2 && ! defined ( __OpenBSD__ )
#include <wchar.h>
#endif
#include "ebml/EbmlUnicodeString.h"
START_LIBEBML_NAMESPACE
// ===================== UTFstring class ===================
static unsigned int UTFCharLength(uint8 lead)
{
if (lead < 0x80)
return 1;
else if ((lead >> 5) == 0x6)
return 2;
else if ((lead >> 4) == 0xe)
return 3;
else if ((lead >> 3) == 0x1e)
return 4;
else
// Invalid size?
return 0;
}
UTFstring::UTFstring()
:_Length(0)
,_Data(NULL)
{}
UTFstring::UTFstring(const wchar_t * _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf;
}
UTFstring::UTFstring(std::wstring const &_aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring::~UTFstring()
{
delete [] _Data;
}
UTFstring::UTFstring(const UTFstring & _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring & UTFstring::operator=(const UTFstring & _aBuf)
{
*this = _aBuf.c_str();
return *this;
}
UTFstring::operator const wchar_t*() const {return _Data;}
UTFstring & UTFstring::operator=(const wchar_t * _aBuf)
{
delete [] _Data;
if (_aBuf == NULL) {
_Data = new wchar_t[1];
_Data[0] = 0;
UpdateFromUCS2();
return *this;
}
size_t aLen;
for (aLen=0; _aBuf[aLen] != 0; aLen++);
_Length = aLen;
_Data = new wchar_t[_Length+1];
for (aLen=0; _aBuf[aLen] != 0; aLen++) {
_Data[aLen] = _aBuf[aLen];
}
_Data[aLen] = 0;
UpdateFromUCS2();
return *this;
}
UTFstring & UTFstring::operator=(wchar_t _aChar)
{
delete [] _Data;
_Data = new wchar_t[2];
_Length = 1;
_Data[0] = _aChar;
_Data[1] = 0;
UpdateFromUCS2();
return *this;
}
bool UTFstring::operator==(const UTFstring& _aStr) const
{
if ((_Data == NULL) && (_aStr._Data == NULL))
return true;
if ((_Data == NULL) || (_aStr._Data == NULL))
return false;
return wcscmp_internal(_Data, _aStr._Data);
}
void UTFstring::SetUTF8(const std::string & _aStr)
{
UTF8string = _aStr;
UpdateFromUTF8();
}
/*!
\see RFC 2279
*/
void UTFstring::UpdateFromUTF8()
{
delete [] _Data;
// find the size of the final UCS-2 string
size_t i;
const size_t SrcLength = UTF8string.length();
for (_Length=0, i=0; i<SrcLength; _Length++) {
const unsigned int CharLength = UTFCharLength(static_cast<uint8>(UTF8string[i]));
if ((CharLength >= 1) && (CharLength <= 4))
i += CharLength;
else
// Invalid size?
break;
}
_Data = new wchar_t[_Length+1];
size_t j;
for (j=0, i=0; i<SrcLength; j++) {
const uint8 lead = static_cast<uint8>(UTF8string[i]);
const unsigned int CharLength = UTFCharLength(lead);
if ((CharLength < 1) || (CharLength > 4))
// Invalid char?
break;
if ((i + CharLength) > SrcLength)
// Guard against invalid memory access beyond the end of the
// source buffer.
break;
if (CharLength == 1)
_Data[j] = lead;
else if (CharLength == 2)
_Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);
else if (CharLength == 3)
_Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);
else if (CharLength == 4)
_Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);
i += CharLength;
}
_Data[j] = 0;
}
void UTFstring::UpdateFromUCS2()
{
// find the size of the final UTF-8 string
size_t i,Size=0;
for (i=0; i<_Length; i++) {
if (_Data[i] < 0x80) {
Size++;
} else if (_Data[i] < 0x800) {
Size += 2;
} else {
Size += 3;
}
}
std::string::value_type *tmpStr = new std::string::value_type[Size+1];
for (i=0, Size=0; i<_Length; i++) {
if (_Data[i] < 0x80) {
tmpStr[Size++] = _Data[i];
} else if (_Data[i] < 0x800) {
tmpStr[Size++] = 0xC0 | (_Data[i] >> 6);
tmpStr[Size++] = 0x80 | (_Data[i] & 0x3F);
} else {
tmpStr[Size++] = 0xE0 | (_Data[i] >> 12);
tmpStr[Size++] = 0x80 | ((_Data[i] >> 6) & 0x3F);
tmpStr[Size++] = 0x80 | (_Data[i] & 0x3F);
}
}
tmpStr[Size] = 0;
UTF8string = tmpStr; // implicit conversion
delete [] tmpStr;
}
bool UTFstring::wcscmp_internal(const wchar_t *str1, const wchar_t *str2)
{
size_t Index=0;
while (str1[Index] == str2[Index] && str1[Index] != 0) {
Index++;
}
return (str1[Index] == str2[Index]);
}
// ===================== EbmlUnicodeString class ===================
EbmlUnicodeString::EbmlUnicodeString()
:EbmlElement(0, false)
{
SetDefaultSize(0);
}
EbmlUnicodeString::EbmlUnicodeString(const UTFstring & aDefaultValue)
:EbmlElement(0, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultSize(0);
SetDefaultIsSet();
}
EbmlUnicodeString::EbmlUnicodeString(const EbmlUnicodeString & ElementToClone)
:EbmlElement(ElementToClone)
,Value(ElementToClone.Value)
,DefaultValue(ElementToClone.DefaultValue)
{
}
void EbmlUnicodeString::SetDefaultValue(UTFstring & aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
const UTFstring & EbmlUnicodeString::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
/*!
\note limited to UCS-2
\todo handle exception on errors
*/
filepos_t EbmlUnicodeString::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
uint32 Result = Value.GetUTF8().length();
if (Result != 0) {
output.writeFully(Value.GetUTF8().c_str(), Result);
}
if (Result < GetDefaultSize()) {
// pad the rest with 0
binary *Pad = new (std::nothrow) binary[GetDefaultSize() - Result];
if (Pad != NULL) {
memset(Pad, 0x00, GetDefaultSize() - Result);
output.writeFully(Pad, GetDefaultSize() - Result);
Result = GetDefaultSize();
delete [] Pad;
}
}
return Result;
}
EbmlUnicodeString::operator const UTFstring &() const {return Value;}
EbmlUnicodeString & EbmlUnicodeString::operator=(const UTFstring & NewString)
{
Value = NewString;
SetValueIsSet();
return *this;
}
EbmlUnicodeString &EbmlUnicodeString::SetValue(UTFstring const &NewValue) {
return *this = NewValue;
}
EbmlUnicodeString &EbmlUnicodeString::SetValueUTF8(std::string const &NewValue) {
UTFstring NewValueUTFstring;
NewValueUTFstring.SetUTF8(NewValue);
return *this = NewValueUTFstring;
}
UTFstring EbmlUnicodeString::GetValue() const {
return Value;
}
std::string EbmlUnicodeString::GetValueUTF8() const {
return Value.GetUTF8();
}
/*!
\note limited to UCS-2
*/
uint64 EbmlUnicodeString::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
SetSize_(Value.GetUTF8().length());
if (GetSize() < GetDefaultSize())
SetSize_(GetDefaultSize());
return GetSize();
}
/*!
\note limited to UCS-2
*/
filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully != SCOPE_NO_DATA) {
if (GetSize() == 0) {
Value = UTFstring::value_type(0);
SetValueIsSet();
} else {
char *Buffer = new (std::nothrow) char[GetSize()+1];
if (Buffer == NULL) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
} else {
input.readFully(Buffer, GetSize());
if (Buffer[GetSize()-1] != 0) {
Buffer[GetSize()] = 0;
}
Value.SetUTF8(Buffer); // implicit conversion to std::string
delete [] Buffer;
SetValueIsSet();
}
}
}
return GetSize();
}
END_LIBEBML_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1809_1 |
crossvul-cpp_data_good_186_2 | /*
* ECC Domain Parameters
*
* (C) 2007 Falko Strenzke, FlexSecure GmbH
* (C) 2008,2018 Jack Lloyd
* (C) 2018 Tobias Niemann
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/ec_group.h>
#include <botan/internal/point_mul.h>
#include <botan/ber_dec.h>
#include <botan/der_enc.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/reducer.h>
#include <botan/mutex.h>
#include <vector>
namespace Botan {
class EC_Group_Data final
{
public:
EC_Group_Data(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid) :
m_curve(p, a, b),
m_base_point(m_curve, g_x, g_y),
m_g_x(g_x),
m_g_y(g_y),
m_order(order),
m_cofactor(cofactor),
m_mod_order(order),
m_base_mult(m_base_point, m_mod_order),
m_oid(oid),
m_p_bits(p.bits()),
m_order_bits(order.bits()),
m_a_is_minus_3(a == p - 3),
m_a_is_zero(a.is_zero())
{
}
bool match(const BigInt& p, const BigInt& a, const BigInt& b,
const BigInt& g_x, const BigInt& g_y,
const BigInt& order, const BigInt& cofactor) const
{
return (this->p() == p &&
this->a() == a &&
this->b() == b &&
this->order() == order &&
this->cofactor() == cofactor &&
this->g_x() == g_x &&
this->g_y() == g_y);
}
const OID& oid() const { return m_oid; }
const BigInt& p() const { return m_curve.get_p(); }
const BigInt& a() const { return m_curve.get_a(); }
const BigInt& b() const { return m_curve.get_b(); }
const BigInt& order() const { return m_order; }
const BigInt& cofactor() const { return m_cofactor; }
const BigInt& g_x() const { return m_g_x; }
const BigInt& g_y() const { return m_g_y; }
size_t p_bits() const { return m_p_bits; }
size_t p_bytes() const { return (m_p_bits + 7) / 8; }
size_t order_bits() const { return m_order_bits; }
size_t order_bytes() const { return (m_order_bits + 7) / 8; }
const CurveGFp& curve() const { return m_curve; }
const PointGFp& base_point() const { return m_base_point; }
bool a_is_minus_3() const { return m_a_is_minus_3; }
bool a_is_zero() const { return m_a_is_zero; }
BigInt mod_order(const BigInt& x) const { return m_mod_order.reduce(x); }
BigInt square_mod_order(const BigInt& x) const
{
return m_mod_order.square(x);
}
BigInt multiply_mod_order(const BigInt& x, const BigInt& y) const
{
return m_mod_order.multiply(x, y);
}
BigInt multiply_mod_order(const BigInt& x, const BigInt& y, const BigInt& z) const
{
return m_mod_order.multiply(m_mod_order.multiply(x, y), z);
}
BigInt inverse_mod_order(const BigInt& x) const
{
return inverse_mod(x, m_order);
}
PointGFp blinded_base_point_multiply(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
return m_base_mult.mul(k, rng, m_order, ws);
}
private:
CurveGFp m_curve;
PointGFp m_base_point;
BigInt m_g_x;
BigInt m_g_y;
BigInt m_order;
BigInt m_cofactor;
Modular_Reducer m_mod_order;
PointGFp_Base_Point_Precompute m_base_mult;
OID m_oid;
size_t m_p_bits;
size_t m_order_bits;
bool m_a_is_minus_3;
bool m_a_is_zero;
};
class EC_Group_Data_Map final
{
public:
EC_Group_Data_Map() {}
size_t clear()
{
lock_guard_type<mutex_type> lock(m_mutex);
size_t count = m_registered_curves.size();
m_registered_curves.clear();
return count;
}
std::shared_ptr<EC_Group_Data> lookup(const OID& oid)
{
lock_guard_type<mutex_type> lock(m_mutex);
for(auto i : m_registered_curves)
{
if(i->oid() == oid)
return i;
}
// Not found, check hardcoded data
std::shared_ptr<EC_Group_Data> data = EC_Group::EC_group_info(oid);
if(data)
{
m_registered_curves.push_back(data);
return data;
}
// Nope, unknown curve
return std::shared_ptr<EC_Group_Data>();
}
std::shared_ptr<EC_Group_Data> lookup_or_create(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
lock_guard_type<mutex_type> lock(m_mutex);
for(auto i : m_registered_curves)
{
if(oid.has_value())
{
if(i->oid() == oid)
return i;
else if(i->oid().has_value())
continue;
}
if(i->match(p, a, b, g_x, g_y, order, cofactor))
return i;
}
// Not found - if OID is set try looking up that way
if(oid.has_value())
{
// Not located in existing store - try hardcoded data set
std::shared_ptr<EC_Group_Data> data = EC_Group::EC_group_info(oid);
if(data)
{
m_registered_curves.push_back(data);
return data;
}
}
// Not found or no OID, add data and return
return add_curve(p, a, b, g_x, g_y, order, cofactor, oid);
}
private:
std::shared_ptr<EC_Group_Data> add_curve(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
std::shared_ptr<EC_Group_Data> d =
std::make_shared<EC_Group_Data>(p, a, b, g_x, g_y, order, cofactor, oid);
// This function is always called with the lock held
m_registered_curves.push_back(d);
return d;
}
mutex_type m_mutex;
std::vector<std::shared_ptr<EC_Group_Data>> m_registered_curves;
};
//static
EC_Group_Data_Map& EC_Group::ec_group_data()
{
/*
* This exists purely to ensure the allocator is constructed before g_ec_data,
* which ensures that its destructor runs after ~g_ec_data is complete.
*/
static Allocator_Initializer g_init_allocator;
static EC_Group_Data_Map g_ec_data;
return g_ec_data;
}
//static
size_t EC_Group::clear_registered_curve_data()
{
return ec_group_data().clear();
}
//static
std::shared_ptr<EC_Group_Data>
EC_Group::load_EC_group_info(const char* p_str,
const char* a_str,
const char* b_str,
const char* g_x_str,
const char* g_y_str,
const char* order_str,
const OID& oid)
{
const BigInt p(p_str);
const BigInt a(a_str);
const BigInt b(b_str);
const BigInt g_x(g_x_str);
const BigInt g_y(g_y_str);
const BigInt order(order_str);
const BigInt cofactor(1); // implicit
return std::make_shared<EC_Group_Data>(p, a, b, g_x, g_y, order, cofactor, oid);
}
//static
std::shared_ptr<EC_Group_Data> EC_Group::BER_decode_EC_group(const uint8_t bits[], size_t len)
{
BER_Decoder ber(bits, len);
BER_Object obj = ber.get_next_object();
if(obj.type() == NULL_TAG)
{
throw Decoding_Error("Cannot handle ImplicitCA ECC parameters");
}
else if(obj.type() == OBJECT_ID)
{
OID dom_par_oid;
BER_Decoder(bits, len).decode(dom_par_oid);
return ec_group_data().lookup(dom_par_oid);
}
else if(obj.type() == SEQUENCE)
{
BigInt p, a, b, order, cofactor;
std::vector<uint8_t> base_pt;
std::vector<uint8_t> seed;
BER_Decoder(bits, len)
.start_cons(SEQUENCE)
.decode_and_check<size_t>(1, "Unknown ECC param version code")
.start_cons(SEQUENCE)
.decode_and_check(OID("1.2.840.10045.1.1"),
"Only prime ECC fields supported")
.decode(p)
.end_cons()
.start_cons(SEQUENCE)
.decode_octet_string_bigint(a)
.decode_octet_string_bigint(b)
.decode_optional_string(seed, BIT_STRING, BIT_STRING)
.end_cons()
.decode(base_pt, OCTET_STRING)
.decode(order)
.decode(cofactor)
.end_cons()
.verify_end();
if(p.bits() < 64 || p.is_negative() || a.is_negative() || b.is_negative() || order <= 0 || cofactor <= 0)
throw Decoding_Error("Invalid ECC parameters");
std::pair<BigInt, BigInt> base_xy = Botan::OS2ECP(base_pt.data(), base_pt.size(), p, a, b);
return ec_group_data().lookup_or_create(p, a, b, base_xy.first, base_xy.second, order, cofactor, OID());
}
else
{
throw Decoding_Error("Unexpected tag while decoding ECC domain params");
}
}
EC_Group::EC_Group()
{
}
EC_Group::~EC_Group()
{
// shared_ptr possibly freed here
}
EC_Group::EC_Group(const OID& domain_oid)
{
this->m_data = ec_group_data().lookup(domain_oid);
if(!this->m_data)
throw Invalid_Argument("Unknown EC_Group " + domain_oid.as_string());
}
EC_Group::EC_Group(const std::string& str)
{
if(str == "")
return; // no initialization / uninitialized
try
{
OID oid = OIDS::lookup(str);
if(oid.empty() == false)
m_data = ec_group_data().lookup(oid);
}
catch(Invalid_OID&)
{
}
if(m_data == nullptr)
{
if(str.size() > 30 && str.substr(0, 29) == "-----BEGIN EC PARAMETERS-----")
{
// OK try it as PEM ...
secure_vector<uint8_t> ber = PEM_Code::decode_check_label(str, "EC PARAMETERS");
this->m_data = BER_decode_EC_group(ber.data(), ber.size());
}
}
if(m_data == nullptr)
throw Invalid_Argument("Unknown ECC group '" + str + "'");
}
//static
std::string EC_Group::PEM_for_named_group(const std::string& name)
{
try
{
EC_Group group(name);
return group.PEM_encode();
}
catch(...)
{
return "";
}
}
EC_Group::EC_Group(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& base_x,
const BigInt& base_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
m_data = ec_group_data().lookup_or_create(p, a, b, base_x, base_y, order, cofactor, oid);
}
EC_Group::EC_Group(const std::vector<uint8_t>& ber)
{
m_data = BER_decode_EC_group(ber.data(), ber.size());
}
const EC_Group_Data& EC_Group::data() const
{
if(m_data == nullptr)
throw Invalid_State("EC_Group uninitialized");
return *m_data;
}
const CurveGFp& EC_Group::get_curve() const
{
return data().curve();
}
bool EC_Group::a_is_minus_3() const
{
return data().a_is_minus_3();
}
bool EC_Group::a_is_zero() const
{
return data().a_is_zero();
}
size_t EC_Group::get_p_bits() const
{
return data().p_bits();
}
size_t EC_Group::get_p_bytes() const
{
return data().p_bytes();
}
size_t EC_Group::get_order_bits() const
{
return data().order_bits();
}
size_t EC_Group::get_order_bytes() const
{
return data().order_bytes();
}
const BigInt& EC_Group::get_p() const
{
return data().p();
}
const BigInt& EC_Group::get_a() const
{
return data().a();
}
const BigInt& EC_Group::get_b() const
{
return data().b();
}
const PointGFp& EC_Group::get_base_point() const
{
return data().base_point();
}
const BigInt& EC_Group::get_order() const
{
return data().order();
}
const BigInt& EC_Group::get_g_x() const
{
return data().g_x();
}
const BigInt& EC_Group::get_g_y() const
{
return data().g_y();
}
const BigInt& EC_Group::get_cofactor() const
{
return data().cofactor();
}
BigInt EC_Group::mod_order(const BigInt& k) const
{
return data().mod_order(k);
}
BigInt EC_Group::square_mod_order(const BigInt& x) const
{
return data().square_mod_order(x);
}
BigInt EC_Group::multiply_mod_order(const BigInt& x, const BigInt& y) const
{
return data().multiply_mod_order(x, y);
}
BigInt EC_Group::multiply_mod_order(const BigInt& x, const BigInt& y, const BigInt& z) const
{
return data().multiply_mod_order(x, y, z);
}
BigInt EC_Group::inverse_mod_order(const BigInt& x) const
{
return data().inverse_mod_order(x);
}
const OID& EC_Group::get_curve_oid() const
{
return data().oid();
}
PointGFp EC_Group::OS2ECP(const uint8_t bits[], size_t len) const
{
return Botan::OS2ECP(bits, len, data().curve());
}
PointGFp EC_Group::point(const BigInt& x, const BigInt& y) const
{
// TODO: randomize the representation?
return PointGFp(data().curve(), x, y);
}
PointGFp EC_Group::point_multiply(const BigInt& x, const PointGFp& pt, const BigInt& y) const
{
PointGFp_Multi_Point_Precompute xy_mul(get_base_point(), pt);
return xy_mul.multi_exp(x, y);
}
PointGFp EC_Group::blinded_base_point_multiply(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
return data().blinded_base_point_multiply(k, rng, ws);
}
BigInt EC_Group::blinded_base_point_multiply_x(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
const PointGFp pt = data().blinded_base_point_multiply(k, rng, ws);
if(pt.is_zero())
return 0;
return pt.get_affine_x();
}
BigInt EC_Group::random_scalar(RandomNumberGenerator& rng) const
{
return BigInt::random_integer(rng, 1, get_order());
}
PointGFp EC_Group::blinded_var_point_multiply(const PointGFp& point,
const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
PointGFp_Var_Point_Precompute mul(point);
mul.randomize_repr(rng, ws);
return mul.mul(k, rng, get_order(), ws);
}
PointGFp EC_Group::zero_point() const
{
return PointGFp(data().curve());
}
std::vector<uint8_t>
EC_Group::DER_encode(EC_Group_Encoding form) const
{
std::vector<uint8_t> output;
DER_Encoder der(output);
if(form == EC_DOMPAR_ENC_EXPLICIT)
{
const size_t ecpVers1 = 1;
const OID curve_type("1.2.840.10045.1.1"); // prime field
const size_t p_bytes = get_p_bytes();
der.start_cons(SEQUENCE)
.encode(ecpVers1)
.start_cons(SEQUENCE)
.encode(curve_type)
.encode(get_p())
.end_cons()
.start_cons(SEQUENCE)
.encode(BigInt::encode_1363(get_a(), p_bytes),
OCTET_STRING)
.encode(BigInt::encode_1363(get_b(), p_bytes),
OCTET_STRING)
.end_cons()
.encode(get_base_point().encode(PointGFp::UNCOMPRESSED), OCTET_STRING)
.encode(get_order())
.encode(get_cofactor())
.end_cons();
}
else if(form == EC_DOMPAR_ENC_OID)
{
const OID oid = get_curve_oid();
if(oid.empty())
{
throw Encoding_Error("Cannot encode EC_Group as OID because OID not set");
}
der.encode(oid);
}
else if(form == EC_DOMPAR_ENC_IMPLICITCA)
{
der.encode_null();
}
else
{
throw Internal_Error("EC_Group::DER_encode: Unknown encoding");
}
return output;
}
std::string EC_Group::PEM_encode() const
{
const std::vector<uint8_t> der = DER_encode(EC_DOMPAR_ENC_EXPLICIT);
return PEM_Code::encode(der, "EC PARAMETERS");
}
bool EC_Group::operator==(const EC_Group& other) const
{
if(m_data == other.m_data)
return true; // same shared rep
/*
* No point comparing order/cofactor as they are uniquely determined
* by the curve equation (p,a,b) and the base point.
*/
return (get_p() == other.get_p() &&
get_a() == other.get_a() &&
get_b() == other.get_b() &&
get_g_x() == other.get_g_x() &&
get_g_y() == other.get_g_y());
}
bool EC_Group::verify_public_element(const PointGFp& point) const
{
//check that public point is not at infinity
if(point.is_zero())
return false;
//check that public point is on the curve
if(point.on_the_curve() == false)
return false;
//check that public point has order q
if((point * get_order()).is_zero() == false)
return false;
if(get_cofactor() > 1)
{
if((point * get_cofactor()).is_zero())
return false;
}
return true;
}
bool EC_Group::verify_group(RandomNumberGenerator& rng,
bool) const
{
//compute the discriminant
Modular_Reducer p(get_p());
BigInt discriminant = p.multiply(4, get_a());
discriminant += p.multiply(27, get_b());
discriminant = p.reduce(discriminant);
//check the discriminant
if(discriminant == 0)
{
return false;
}
//check for valid cofactor
if(get_cofactor() < 1)
{
return false;
}
const PointGFp base_point = get_base_point();
//check if the base point is on the curve
if(!base_point.on_the_curve())
{
return false;
}
if((base_point * get_cofactor()).is_zero())
{
return false;
}
const BigInt& order = get_order();
//check if order is prime
if(!is_prime(order, rng, 128))
{
return false;
}
//check if order of the base point is correct
if(!(base_point * order).is_zero())
{
return false;
}
return true;
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_186_2 |
crossvul-cpp_data_bad_186_2 | /*
* ECC Domain Parameters
*
* (C) 2007 Falko Strenzke, FlexSecure GmbH
* (C) 2008,2018 Jack Lloyd
* (C) 2018 Tobias Niemann
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/ec_group.h>
#include <botan/internal/point_mul.h>
#include <botan/ber_dec.h>
#include <botan/der_enc.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/reducer.h>
#include <botan/mutex.h>
#include <vector>
namespace Botan {
class EC_Group_Data final
{
public:
EC_Group_Data(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid) :
m_curve(p, a, b),
m_base_point(m_curve, g_x, g_y),
m_g_x(g_x),
m_g_y(g_y),
m_order(order),
m_cofactor(cofactor),
m_mod_order(order),
m_base_mult(m_base_point, m_mod_order),
m_oid(oid),
m_p_bits(p.bits()),
m_order_bits(order.bits()),
m_a_is_minus_3(a == p - 3),
m_a_is_zero(a.is_zero())
{
}
bool match(const BigInt& p, const BigInt& a, const BigInt& b,
const BigInt& g_x, const BigInt& g_y,
const BigInt& order, const BigInt& cofactor) const
{
return (this->p() == p &&
this->a() == a &&
this->b() == b &&
this->order() == order &&
this->cofactor() == cofactor &&
this->g_x() == g_x &&
this->g_y() == g_y);
}
const OID& oid() const { return m_oid; }
const BigInt& p() const { return m_curve.get_p(); }
const BigInt& a() const { return m_curve.get_a(); }
const BigInt& b() const { return m_curve.get_b(); }
const BigInt& order() const { return m_order; }
const BigInt& cofactor() const { return m_cofactor; }
const BigInt& g_x() const { return m_g_x; }
const BigInt& g_y() const { return m_g_y; }
size_t p_bits() const { return m_p_bits; }
size_t p_bytes() const { return (m_p_bits + 7) / 8; }
size_t order_bits() const { return m_order_bits; }
size_t order_bytes() const { return (m_order_bits + 7) / 8; }
const CurveGFp& curve() const { return m_curve; }
const PointGFp& base_point() const { return m_base_point; }
bool a_is_minus_3() const { return m_a_is_minus_3; }
bool a_is_zero() const { return m_a_is_zero; }
BigInt mod_order(const BigInt& x) const { return m_mod_order.reduce(x); }
BigInt multiply_mod_order(const BigInt& x, const BigInt& y) const
{
return m_mod_order.multiply(x, y);
}
BigInt inverse_mod_order(const BigInt& x) const
{
return inverse_mod(x, m_order);
}
PointGFp blinded_base_point_multiply(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
return m_base_mult.mul(k, rng, m_order, ws);
}
private:
CurveGFp m_curve;
PointGFp m_base_point;
BigInt m_g_x;
BigInt m_g_y;
BigInt m_order;
BigInt m_cofactor;
Modular_Reducer m_mod_order;
PointGFp_Base_Point_Precompute m_base_mult;
OID m_oid;
size_t m_p_bits;
size_t m_order_bits;
bool m_a_is_minus_3;
bool m_a_is_zero;
};
class EC_Group_Data_Map final
{
public:
EC_Group_Data_Map() {}
size_t clear()
{
lock_guard_type<mutex_type> lock(m_mutex);
size_t count = m_registered_curves.size();
m_registered_curves.clear();
return count;
}
std::shared_ptr<EC_Group_Data> lookup(const OID& oid)
{
lock_guard_type<mutex_type> lock(m_mutex);
for(auto i : m_registered_curves)
{
if(i->oid() == oid)
return i;
}
// Not found, check hardcoded data
std::shared_ptr<EC_Group_Data> data = EC_Group::EC_group_info(oid);
if(data)
{
m_registered_curves.push_back(data);
return data;
}
// Nope, unknown curve
return std::shared_ptr<EC_Group_Data>();
}
std::shared_ptr<EC_Group_Data> lookup_or_create(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
lock_guard_type<mutex_type> lock(m_mutex);
for(auto i : m_registered_curves)
{
if(oid.has_value())
{
if(i->oid() == oid)
return i;
else if(i->oid().has_value())
continue;
}
if(i->match(p, a, b, g_x, g_y, order, cofactor))
return i;
}
// Not found - if OID is set try looking up that way
if(oid.has_value())
{
// Not located in existing store - try hardcoded data set
std::shared_ptr<EC_Group_Data> data = EC_Group::EC_group_info(oid);
if(data)
{
m_registered_curves.push_back(data);
return data;
}
}
// Not found or no OID, add data and return
return add_curve(p, a, b, g_x, g_y, order, cofactor, oid);
}
private:
std::shared_ptr<EC_Group_Data> add_curve(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& g_x,
const BigInt& g_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
std::shared_ptr<EC_Group_Data> d =
std::make_shared<EC_Group_Data>(p, a, b, g_x, g_y, order, cofactor, oid);
// This function is always called with the lock held
m_registered_curves.push_back(d);
return d;
}
mutex_type m_mutex;
std::vector<std::shared_ptr<EC_Group_Data>> m_registered_curves;
};
//static
EC_Group_Data_Map& EC_Group::ec_group_data()
{
/*
* This exists purely to ensure the allocator is constructed before g_ec_data,
* which ensures that its destructor runs after ~g_ec_data is complete.
*/
static Allocator_Initializer g_init_allocator;
static EC_Group_Data_Map g_ec_data;
return g_ec_data;
}
//static
size_t EC_Group::clear_registered_curve_data()
{
return ec_group_data().clear();
}
//static
std::shared_ptr<EC_Group_Data>
EC_Group::load_EC_group_info(const char* p_str,
const char* a_str,
const char* b_str,
const char* g_x_str,
const char* g_y_str,
const char* order_str,
const OID& oid)
{
const BigInt p(p_str);
const BigInt a(a_str);
const BigInt b(b_str);
const BigInt g_x(g_x_str);
const BigInt g_y(g_y_str);
const BigInt order(order_str);
const BigInt cofactor(1); // implicit
return std::make_shared<EC_Group_Data>(p, a, b, g_x, g_y, order, cofactor, oid);
}
//static
std::shared_ptr<EC_Group_Data> EC_Group::BER_decode_EC_group(const uint8_t bits[], size_t len)
{
BER_Decoder ber(bits, len);
BER_Object obj = ber.get_next_object();
if(obj.type() == NULL_TAG)
{
throw Decoding_Error("Cannot handle ImplicitCA ECC parameters");
}
else if(obj.type() == OBJECT_ID)
{
OID dom_par_oid;
BER_Decoder(bits, len).decode(dom_par_oid);
return ec_group_data().lookup(dom_par_oid);
}
else if(obj.type() == SEQUENCE)
{
BigInt p, a, b, order, cofactor;
std::vector<uint8_t> base_pt;
std::vector<uint8_t> seed;
BER_Decoder(bits, len)
.start_cons(SEQUENCE)
.decode_and_check<size_t>(1, "Unknown ECC param version code")
.start_cons(SEQUENCE)
.decode_and_check(OID("1.2.840.10045.1.1"),
"Only prime ECC fields supported")
.decode(p)
.end_cons()
.start_cons(SEQUENCE)
.decode_octet_string_bigint(a)
.decode_octet_string_bigint(b)
.decode_optional_string(seed, BIT_STRING, BIT_STRING)
.end_cons()
.decode(base_pt, OCTET_STRING)
.decode(order)
.decode(cofactor)
.end_cons()
.verify_end();
if(p.bits() < 64 || p.is_negative() || a.is_negative() || b.is_negative() || order <= 0 || cofactor <= 0)
throw Decoding_Error("Invalid ECC parameters");
std::pair<BigInt, BigInt> base_xy = Botan::OS2ECP(base_pt.data(), base_pt.size(), p, a, b);
return ec_group_data().lookup_or_create(p, a, b, base_xy.first, base_xy.second, order, cofactor, OID());
}
else
{
throw Decoding_Error("Unexpected tag while decoding ECC domain params");
}
}
EC_Group::EC_Group()
{
}
EC_Group::~EC_Group()
{
// shared_ptr possibly freed here
}
EC_Group::EC_Group(const OID& domain_oid)
{
this->m_data = ec_group_data().lookup(domain_oid);
if(!this->m_data)
throw Invalid_Argument("Unknown EC_Group " + domain_oid.as_string());
}
EC_Group::EC_Group(const std::string& str)
{
if(str == "")
return; // no initialization / uninitialized
try
{
OID oid = OIDS::lookup(str);
if(oid.empty() == false)
m_data = ec_group_data().lookup(oid);
}
catch(Invalid_OID&)
{
}
if(m_data == nullptr)
{
if(str.size() > 30 && str.substr(0, 29) == "-----BEGIN EC PARAMETERS-----")
{
// OK try it as PEM ...
secure_vector<uint8_t> ber = PEM_Code::decode_check_label(str, "EC PARAMETERS");
this->m_data = BER_decode_EC_group(ber.data(), ber.size());
}
}
if(m_data == nullptr)
throw Invalid_Argument("Unknown ECC group '" + str + "'");
}
//static
std::string EC_Group::PEM_for_named_group(const std::string& name)
{
try
{
EC_Group group(name);
return group.PEM_encode();
}
catch(...)
{
return "";
}
}
EC_Group::EC_Group(const BigInt& p,
const BigInt& a,
const BigInt& b,
const BigInt& base_x,
const BigInt& base_y,
const BigInt& order,
const BigInt& cofactor,
const OID& oid)
{
m_data = ec_group_data().lookup_or_create(p, a, b, base_x, base_y, order, cofactor, oid);
}
EC_Group::EC_Group(const std::vector<uint8_t>& ber)
{
m_data = BER_decode_EC_group(ber.data(), ber.size());
}
const EC_Group_Data& EC_Group::data() const
{
if(m_data == nullptr)
throw Invalid_State("EC_Group uninitialized");
return *m_data;
}
const CurveGFp& EC_Group::get_curve() const
{
return data().curve();
}
bool EC_Group::a_is_minus_3() const
{
return data().a_is_minus_3();
}
bool EC_Group::a_is_zero() const
{
return data().a_is_zero();
}
size_t EC_Group::get_p_bits() const
{
return data().p_bits();
}
size_t EC_Group::get_p_bytes() const
{
return data().p_bytes();
}
size_t EC_Group::get_order_bits() const
{
return data().order_bits();
}
size_t EC_Group::get_order_bytes() const
{
return data().order_bytes();
}
const BigInt& EC_Group::get_p() const
{
return data().p();
}
const BigInt& EC_Group::get_a() const
{
return data().a();
}
const BigInt& EC_Group::get_b() const
{
return data().b();
}
const PointGFp& EC_Group::get_base_point() const
{
return data().base_point();
}
const BigInt& EC_Group::get_order() const
{
return data().order();
}
const BigInt& EC_Group::get_g_x() const
{
return data().g_x();
}
const BigInt& EC_Group::get_g_y() const
{
return data().g_y();
}
const BigInt& EC_Group::get_cofactor() const
{
return data().cofactor();
}
BigInt EC_Group::mod_order(const BigInt& k) const
{
return data().mod_order(k);
}
BigInt EC_Group::multiply_mod_order(const BigInt& x, const BigInt& y) const
{
return data().multiply_mod_order(x, y);
}
BigInt EC_Group::inverse_mod_order(const BigInt& x) const
{
return data().inverse_mod_order(x);
}
const OID& EC_Group::get_curve_oid() const
{
return data().oid();
}
PointGFp EC_Group::OS2ECP(const uint8_t bits[], size_t len) const
{
return Botan::OS2ECP(bits, len, data().curve());
}
PointGFp EC_Group::point(const BigInt& x, const BigInt& y) const
{
// TODO: randomize the representation?
return PointGFp(data().curve(), x, y);
}
PointGFp EC_Group::point_multiply(const BigInt& x, const PointGFp& pt, const BigInt& y) const
{
PointGFp_Multi_Point_Precompute xy_mul(get_base_point(), pt);
return xy_mul.multi_exp(x, y);
}
PointGFp EC_Group::blinded_base_point_multiply(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
return data().blinded_base_point_multiply(k, rng, ws);
}
BigInt EC_Group::blinded_base_point_multiply_x(const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
const PointGFp pt = data().blinded_base_point_multiply(k, rng, ws);
if(pt.is_zero())
return 0;
return pt.get_affine_x();
}
BigInt EC_Group::random_scalar(RandomNumberGenerator& rng) const
{
return BigInt::random_integer(rng, 1, get_order());
}
PointGFp EC_Group::blinded_var_point_multiply(const PointGFp& point,
const BigInt& k,
RandomNumberGenerator& rng,
std::vector<BigInt>& ws) const
{
PointGFp_Var_Point_Precompute mul(point);
mul.randomize_repr(rng, ws);
return mul.mul(k, rng, get_order(), ws);
}
PointGFp EC_Group::zero_point() const
{
return PointGFp(data().curve());
}
std::vector<uint8_t>
EC_Group::DER_encode(EC_Group_Encoding form) const
{
std::vector<uint8_t> output;
DER_Encoder der(output);
if(form == EC_DOMPAR_ENC_EXPLICIT)
{
const size_t ecpVers1 = 1;
const OID curve_type("1.2.840.10045.1.1"); // prime field
const size_t p_bytes = get_p_bytes();
der.start_cons(SEQUENCE)
.encode(ecpVers1)
.start_cons(SEQUENCE)
.encode(curve_type)
.encode(get_p())
.end_cons()
.start_cons(SEQUENCE)
.encode(BigInt::encode_1363(get_a(), p_bytes),
OCTET_STRING)
.encode(BigInt::encode_1363(get_b(), p_bytes),
OCTET_STRING)
.end_cons()
.encode(get_base_point().encode(PointGFp::UNCOMPRESSED), OCTET_STRING)
.encode(get_order())
.encode(get_cofactor())
.end_cons();
}
else if(form == EC_DOMPAR_ENC_OID)
{
const OID oid = get_curve_oid();
if(oid.empty())
{
throw Encoding_Error("Cannot encode EC_Group as OID because OID not set");
}
der.encode(oid);
}
else if(form == EC_DOMPAR_ENC_IMPLICITCA)
{
der.encode_null();
}
else
{
throw Internal_Error("EC_Group::DER_encode: Unknown encoding");
}
return output;
}
std::string EC_Group::PEM_encode() const
{
const std::vector<uint8_t> der = DER_encode(EC_DOMPAR_ENC_EXPLICIT);
return PEM_Code::encode(der, "EC PARAMETERS");
}
bool EC_Group::operator==(const EC_Group& other) const
{
if(m_data == other.m_data)
return true; // same shared rep
/*
* No point comparing order/cofactor as they are uniquely determined
* by the curve equation (p,a,b) and the base point.
*/
return (get_p() == other.get_p() &&
get_a() == other.get_a() &&
get_b() == other.get_b() &&
get_g_x() == other.get_g_x() &&
get_g_y() == other.get_g_y());
}
bool EC_Group::verify_public_element(const PointGFp& point) const
{
//check that public point is not at infinity
if(point.is_zero())
return false;
//check that public point is on the curve
if(point.on_the_curve() == false)
return false;
//check that public point has order q
if((point * get_order()).is_zero() == false)
return false;
if(get_cofactor() > 1)
{
if((point * get_cofactor()).is_zero())
return false;
}
return true;
}
bool EC_Group::verify_group(RandomNumberGenerator& rng,
bool) const
{
//compute the discriminant
Modular_Reducer p(get_p());
BigInt discriminant = p.multiply(4, get_a());
discriminant += p.multiply(27, get_b());
discriminant = p.reduce(discriminant);
//check the discriminant
if(discriminant == 0)
{
return false;
}
//check for valid cofactor
if(get_cofactor() < 1)
{
return false;
}
const PointGFp base_point = get_base_point();
//check if the base point is on the curve
if(!base_point.on_the_curve())
{
return false;
}
if((base_point * get_cofactor()).is_zero())
{
return false;
}
const BigInt& order = get_order();
//check if order is prime
if(!is_prime(order, rng, 128))
{
return false;
}
//check if order of the base point is correct
if(!(base_point * order).is_zero())
{
return false;
}
return true;
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_186_2 |
crossvul-cpp_data_good_1810_1 | /****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
*/
#include <cassert>
#include <cstring>
#include "ebml/EbmlElement.h"
#include "ebml/EbmlMaster.h"
#include "ebml/EbmlStream.h"
#include "ebml/EbmlVoid.h"
#include "ebml/EbmlDummy.h"
#include "ebml/EbmlContexts.h"
START_LIBEBML_NAMESPACE
/*!
\todo handle more than CodedSize of 5
*/
int CodedSizeLength(uint64 Length, unsigned int SizeLength, bool bSizeFinite)
{
unsigned int CodedSize;
if (bSizeFinite) {
// prepare the head of the size (000...01xxxxxx)
// optimal size
if (Length < 127) // 2^7 - 1
CodedSize = 1;
else if (Length < 16383) // 2^14 - 1
CodedSize = 2;
else if (Length < 2097151L) // 2^21 - 1
CodedSize = 3;
else if (Length < 268435455L) // 2^28 - 1
CodedSize = 4;
else CodedSize = 5;
} else {
if (Length <= 127) // 2^7 - 1
CodedSize = 1;
else if (Length <= 16383) // 2^14 - 1
CodedSize = 2;
else if (Length <= 2097151L) // 2^21 - 1
CodedSize = 3;
else if (Length <= 268435455L) // 2^28 - 1
CodedSize = 4;
else CodedSize = 5;
}
if (SizeLength > 0 && CodedSize < SizeLength) {
// defined size
CodedSize = SizeLength;
}
return CodedSize;
}
/*!
\todo handle more than CodedSize of 5
*/
int CodedSizeLengthSigned(int64 Length, unsigned int SizeLength)
{
unsigned int CodedSize;
// prepare the head of the size (000...01xxxxxx)
// optimal size
if (Length > -64 && Length < 64) // 2^6
CodedSize = 1;
else if (Length > -8192 && Length < 8192) // 2^13
CodedSize = 2;
else if (Length > -1048576L && Length < 1048576L) // 2^20
CodedSize = 3;
else if (Length > -134217728L && Length < 134217728L) // 2^27
CodedSize = 4;
else CodedSize = 5;
if (SizeLength > 0 && CodedSize < SizeLength) {
// defined size
CodedSize = SizeLength;
}
return CodedSize;
}
int CodedValueLength(uint64 Length, int CodedSize, binary * OutBuffer)
{
int _SizeMask = 0xFF;
OutBuffer[0] = 1 << (8 - CodedSize);
for (int i=1; i<CodedSize; i++) {
OutBuffer[CodedSize-i] = Length & 0xFF;
Length >>= 8;
_SizeMask >>= 1;
}
// first one use a OR with the "EBML size head"
OutBuffer[0] |= Length & 0xFF & _SizeMask;
return CodedSize;
}
int CodedValueLengthSigned(int64 Length, int CodedSize, binary * OutBuffer)
{
if (Length > -64 && Length < 64) // 2^6
Length += 63;
else if (Length > -8192 && Length < 8192) // 2^13
Length += 8191;
else if (Length > -1048576L && Length < 1048576L) // 2^20
Length += 1048575L;
else if (Length > -134217728L && Length < 134217728L) // 2^27
Length += 134217727L;
return CodedValueLength(Length, CodedSize, OutBuffer);
}
uint64 ReadCodedSizeValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)
{
binary SizeBitMask = 1 << 7;
uint64 Result = 0x7F;
unsigned int SizeIdx, PossibleSizeLength = 0;
binary PossibleSize[8];
memset(PossibleSize, 0, 8);
SizeUnknown = 0x7F; // the last bit is discarded when computing the size
for (SizeIdx = 0; SizeIdx < BufferSize && SizeIdx < 8; SizeIdx++) {
if (InBuffer[0] & (SizeBitMask >> SizeIdx)) {
// ID found
PossibleSizeLength = SizeIdx + 1;
SizeBitMask >>= SizeIdx;
// Guard against invalid memory accesses with incomplete IDs.
if (PossibleSizeLength > BufferSize)
break;
for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) {
PossibleSize[SizeIdx] = InBuffer[SizeIdx];
}
for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) {
Result <<= 7;
Result |= 0xFF;
}
Result = 0;
Result |= PossibleSize[0] & ~SizeBitMask;
for (unsigned int i = 1; i<PossibleSizeLength; i++) {
Result <<= 8;
Result |= PossibleSize[i];
}
BufferSize = PossibleSizeLength;
return Result;
}
SizeUnknown <<= 7;
SizeUnknown |= 0xFF;
}
BufferSize = 0;
return 0;
}
int64 ReadCodedSizeSignedValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)
{
int64 Result = ReadCodedSizeValue(InBuffer, BufferSize, SizeUnknown);
if (BufferSize != 0) {
switch (BufferSize) {
case 1:
Result -= 63;
break;
case 2:
Result -= 8191;
break;
case 3:
Result -= 1048575L;
break;
case 4:
Result -= 134217727L;
break;
}
}
return Result;
}
EbmlCallbacks::EbmlCallbacks(EbmlElement & (*Creator)(), const EbmlId & aGlobalId, const char * aDebugName, const EbmlSemanticContext & aContext)
:Create(Creator)
,GlobalId(aGlobalId)
,DebugName(aDebugName)
,Context(aContext)
{
assert((Create!=NULL) || !strcmp(aDebugName, "DummyElement"));
}
const EbmlSemantic & EbmlSemanticContext::GetSemantic(size_t i) const
{
assert(i<Size);
if (i<Size)
return MyTable[i];
else
return *(EbmlSemantic*)NULL;
}
EbmlElement::EbmlElement(uint64 aDefaultSize, bool bValueSet)
:DefaultSize(aDefaultSize)
,SizeLength(0) ///< write optimal size by default
,bSizeIsFinite(true)
,ElementPosition(0)
,SizePosition(0)
,bValueIsSet(bValueSet)
,DefaultIsSet(false)
,bLocked(false)
{
Size = DefaultSize;
}
EbmlElement::EbmlElement(const EbmlElement & ElementToClone)
:Size(ElementToClone.Size)
,DefaultSize(ElementToClone.DefaultSize)
,SizeLength(ElementToClone.SizeLength)
,bSizeIsFinite(ElementToClone.bSizeIsFinite)
,ElementPosition(ElementToClone.ElementPosition)
,SizePosition(ElementToClone.SizePosition)
,bValueIsSet(ElementToClone.bValueIsSet)
,DefaultIsSet(ElementToClone.DefaultIsSet)
,bLocked(ElementToClone.bLocked)
{
}
EbmlElement::~EbmlElement()
{
assert(!bLocked);
}
/*!
\todo this method is deprecated and should be called FindThisID
\todo replace the new RawElement with the appropriate class (when known)
*/
EbmlElement * EbmlElement::FindNextID(IOCallback & DataStream, const EbmlCallbacks & ClassInfos, uint64 MaxDataSize)
{
binary PossibleId[4];
int PossibleID_Length = 0;
binary PossibleSize[8]; // we don't support size stored in more than 64 bits
uint32 PossibleSizeLength = 0;
uint64 SizeUnknown;
uint64 SizeFound;
bool bElementFound = false;
binary BitMask;
uint64 aElementPosition, aSizePosition;
while (!bElementFound) {
// read ID
aElementPosition = DataStream.getFilePointer();
uint32 ReadSize = 0;
BitMask = 1 << 7;
while (1) {
ReadSize += DataStream.read(&PossibleId[PossibleID_Length], 1);
if (ReadSize == uint32(PossibleID_Length)) {
return NULL; // no more data ?
}
if (++PossibleID_Length > 4) {
return NULL; // we don't support element IDs over class D
}
if (PossibleId[0] & BitMask) {
// this is the last octet of the ID
// check wether that's the one we're looking for
/* if (PossibleID == EBML_INFO_ID(ClassInfos)) {
break;
} else {
/// \todo This element should be skipped (use a context ?)
}*/
bElementFound = true; /// \todo not exactly the one we're looking for
break;
}
BitMask >>= 1;
}
// read the data size
aSizePosition = DataStream.getFilePointer();
uint32 _SizeLength;
do {
if (PossibleSizeLength >= 8)
// Size is larger than 8 bytes
return NULL;
ReadSize += DataStream.read(&PossibleSize[PossibleSizeLength++], 1);
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleSize[0], _SizeLength, SizeUnknown);
} while (_SizeLength == 0);
}
EbmlElement *Result = NULL;
EbmlId PossibleID(PossibleId, PossibleID_Length);
if (PossibleID == EBML_INFO_ID(ClassInfos)) {
// the element is the one expected
Result = &EBML_INFO_CREATE(ClassInfos);
} else {
/// \todo find the element in the context
Result = new (std::nothrow) EbmlDummy(PossibleID);
if(Result == NULL)
return NULL;
}
Result->SetSizeLength(PossibleSizeLength);
Result->Size = SizeFound;
if (!Result->ValidateSize() || (SizeFound != SizeUnknown && MaxDataSize < Result->Size)) {
delete Result;
return NULL;
}
// check if the size is not all 1s
if (SizeFound == SizeUnknown) {
// Size of this element is unknown
// only possible for Master elements
if (!Result->SetSizeInfinite()) {
/// \todo the element is not allowed to be infinite
delete Result;
return NULL;
}
} else Result->SetSizeInfinite(false);
Result->ElementPosition = aElementPosition;
Result->SizePosition = aSizePosition;
return Result;
}
/*!
\todo replace the new RawElement with the appropriate class (when known)
\todo skip data for Dummy elements when they are not allowed
\todo better check of the size checking for upper elements (using a list of size for each level)
\param LowLevel Will be returned with the level of the element found compared to the context given
*/
EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel,
uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel)
{
int PossibleID_Length = 0;
binary PossibleIdNSize[16];
int PossibleSizeLength;
uint64 SizeUnknown;
int ReadIndex = 0; // trick for the algo, start index at 0
uint32 ReadSize = 0;
uint64 SizeFound;
int SizeIdx;
bool bFound;
int UpperLevel_original = UpperLevel;
do {
// read a potential ID
do {
assert(ReadIndex < 16);
// build the ID with the current Read Buffer
bFound = false;
binary IdBitMask = 1 << 7;
for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) {
if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) {
// ID found
PossibleID_Length = SizeIdx + 1;
IdBitMask >>= SizeIdx;
bFound = true;
break;
}
}
if (bFound) {
break;
}
if (ReadIndex >= 4) {
// ID not found
// shift left the read octets
memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex);
}
if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {
return NULL; // no more data ?
}
ReadSize++;
} while (!bFound && MaxDataSize > ReadSize);
SizeIdx = ReadIndex;
ReadIndex -= PossibleID_Length;
// read the data size
uint32 _SizeLength;
PossibleSizeLength = ReadIndex;
while (1) {
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown);
if (_SizeLength != 0) {
bFound = true;
break;
}
if (PossibleSizeLength >= 8) {
bFound = false;
break;
}
if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) {
return NULL; // no more data ?
}
ReadSize++;
PossibleSizeLength++;
}
if (bFound) {
// find the element in the context and use the correct creator
EbmlId PossibleID(PossibleIdNSize, PossibleID_Length);
EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel);
///< \todo continue is misplaced
if (Result != NULL) {
if (AllowDummyElt || !Result->IsDummy()) {
Result->SetSizeLength(_SizeLength);
Result->Size = SizeFound;
// UpperLevel values
// -1 : global element
// 0 : child
// 1 : same level
// + : further parent
if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) {
if (SizeFound == SizeUnknown) {
Result->SetSizeInfinite();
}
Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID);
Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID);
// place the file at the beggining of the data
DataStream.setFilePointer(Result->SizePosition + _SizeLength);
return Result;
}
}
delete Result;
}
}
// recover all the data in the buffer minus one byte
ReadIndex = SizeIdx - 1;
memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex);
UpperLevel = UpperLevel_original;
} while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length );
return NULL;
}
/*!
\todo what happens if we are in a upper element with a known size ?
*/
EbmlElement * EbmlElement::SkipData(EbmlStream & DataStream, const EbmlSemanticContext & Context, EbmlElement * TestReadElt, bool AllowDummyElt)
{
EbmlElement * Result = NULL;
if (bSizeIsFinite) {
assert(TestReadElt == NULL);
assert(ElementPosition < SizePosition);
DataStream.I_O().setFilePointer(SizePosition + CodedSizeLength(Size, SizeLength, bSizeIsFinite) + Size, seek_beginning);
// DataStream.I_O().setFilePointer(Size, seek_current);
} else {
/////////////////////////////////////////////////
// read elements until an upper element is found
/////////////////////////////////////////////////
bool bEndFound = false;
while (!bEndFound && Result == NULL) {
// read an element
/// \todo 0xFF... and true should be configurable
// EbmlElement * NewElt;
if (TestReadElt == NULL) {
int bUpperElement = 0; // trick to call FindNextID correctly
Result = DataStream.FindNextElement(Context, bUpperElement, 0xFFFFFFFFL, AllowDummyElt);
} else {
Result = TestReadElt;
TestReadElt = NULL;
}
if (Result != NULL) {
unsigned int EltIndex;
// data known in this Master's context
for (EltIndex = 0; EltIndex < EBML_CTX_SIZE(Context); EltIndex++) {
if (EbmlId(*Result) == EBML_CTX_IDX_ID(Context,EltIndex)) {
// skip the data with its own context
Result = Result->SkipData(DataStream, EBML_SEM_CONTEXT(EBML_CTX_IDX(Context,EltIndex)), NULL);
break; // let's go to the next ID
}
}
if (EltIndex >= EBML_CTX_SIZE(Context)) {
if (EBML_CTX_PARENT(Context) != NULL) {
Result = SkipData(DataStream, *EBML_CTX_PARENT(Context), Result);
} else {
assert(Context.GetGlobalContext != NULL);
if (Context != Context.GetGlobalContext()) {
Result = SkipData(DataStream, Context.GetGlobalContext(), Result);
} else {
bEndFound = true;
}
}
}
} else {
bEndFound = true;
}
}
}
return Result;
}
EbmlElement *EbmlElement::CreateElementUsingContext(const EbmlId & aID, const EbmlSemanticContext & Context,
int & LowLevel, bool IsGlobalContext, bool bAllowDummy, unsigned int MaxLowerLevel)
{
unsigned int ContextIndex;
EbmlElement *Result = NULL;
// elements at the current level
for (ContextIndex = 0; ContextIndex < EBML_CTX_SIZE(Context); ContextIndex++) {
if (aID == EBML_CTX_IDX_ID(Context,ContextIndex)) {
return &EBML_SEM_CREATE(EBML_CTX_IDX(Context,ContextIndex));
}
}
// global elements
assert(Context.GetGlobalContext != NULL); // global should always exist, at least the EBML ones
const EbmlSemanticContext & tstContext = Context.GetGlobalContext();
if (tstContext != Context) {
LowLevel--;
MaxLowerLevel--;
// recursive is good, but be carefull...
Result = CreateElementUsingContext(aID, tstContext, LowLevel, true, bAllowDummy, MaxLowerLevel);
if (Result != NULL) {
return Result;
}
LowLevel++;
MaxLowerLevel++;
} else {
return NULL;
}
// parent elements
if (EBML_CTX_MASTER(Context) != NULL && aID == EBML_INFO_ID(*EBML_CTX_MASTER(Context))) {
LowLevel++; // already one level up (same as context)
return &EBML_INFO_CREATE(*EBML_CTX_MASTER(Context));
}
// check wether it's not part of an upper context
if (EBML_CTX_PARENT(Context) != NULL) {
LowLevel++;
MaxLowerLevel++;
return CreateElementUsingContext(aID, *EBML_CTX_PARENT(Context), LowLevel, IsGlobalContext, bAllowDummy, MaxLowerLevel);
}
if (!IsGlobalContext && bAllowDummy) {
LowLevel = 0;
Result = new (std::nothrow) EbmlDummy(aID);
}
return Result;
}
/*!
\todo verify that the size written is the same as the data written
*/
filepos_t EbmlElement::Render(IOCallback & output, bool bWithDefault, bool bKeepPosition, bool bForceRender)
{
assert(bValueIsSet || (bWithDefault && DefaultISset())); // an element is been rendered without a value set !!!
// it may be a mandatory element without a default value
if (!bWithDefault && IsDefaultValue()) {
return 0;
}
#if defined(LIBEBML_DEBUG)
uint64 SupposedSize = UpdateSize(bWithDefault, bForceRender);
#endif // LIBEBML_DEBUG
filepos_t result = RenderHead(output, bForceRender, bWithDefault, bKeepPosition);
uint64 WrittenSize = RenderData(output, bForceRender, bWithDefault);
#if defined(LIBEBML_DEBUG)
if (static_cast<int64>(SupposedSize) != (0-1))
assert(WrittenSize == SupposedSize);
#endif // LIBEBML_DEBUG
result += WrittenSize;
return result;
}
/*!
\todo store the position of the Size writing for elements with unknown size
\todo handle exceptions on errors
\todo handle CodeSize bigger than 5 bytes
*/
filepos_t EbmlElement::RenderHead(IOCallback & output, bool bForceRender, bool bWithDefault, bool bKeepPosition)
{
if (EBML_ID_LENGTH((const EbmlId&)*this) <= 0 || EBML_ID_LENGTH((const EbmlId&)*this) > 4)
return 0;
UpdateSize(bWithDefault, bForceRender);
return MakeRenderHead(output, bKeepPosition);
}
filepos_t EbmlElement::MakeRenderHead(IOCallback & output, bool bKeepPosition)
{
binary FinalHead[4+8]; // Class D + 64 bits coded size
unsigned int FinalHeadSize;
FinalHeadSize = EBML_ID_LENGTH((const EbmlId&)*this);
EbmlId(*this).Fill(FinalHead);
int CodedSize = CodedSizeLength(Size, SizeLength, bSizeIsFinite);
CodedValueLength(Size, CodedSize, &FinalHead[FinalHeadSize]);
FinalHeadSize += CodedSize;
output.writeFully(FinalHead, FinalHeadSize);
if (!bKeepPosition) {
ElementPosition = output.getFilePointer() - FinalHeadSize;
SizePosition = ElementPosition + EBML_ID_LENGTH((const EbmlId&)*this);
}
return FinalHeadSize;
}
uint64 EbmlElement::ElementSize(bool bWithDefault) const
{
if (!bWithDefault && IsDefaultValue())
return 0; // won't be saved
return Size + EBML_ID_LENGTH((const EbmlId&)*this) + CodedSizeLength(Size, SizeLength, bSizeIsFinite);
}
bool EbmlElement::IsSmallerThan(const EbmlElement *Cmp) const
{
return EbmlId(*this) == EbmlId(*Cmp);
}
bool EbmlElement::CompareElements(const EbmlElement *A, const EbmlElement *B)
{
if (EbmlId(*A) == EbmlId(*B))
return A->IsSmallerThan(B);
else
return false;
}
void EbmlElement::Read(EbmlStream & inDataStream, const EbmlSemanticContext & /* Context */, int & /* UpperEltFound */, EbmlElement * & /* FoundElt */, bool /* AllowDummyElt */, ScopeMode ReadFully)
{
ReadData(inDataStream.I_O(), ReadFully);
}
bool EbmlElement::ForceSize(uint64 NewSize)
{
if (bSizeIsFinite) {
return false;
}
int OldSizeLen = CodedSizeLength(Size, SizeLength, bSizeIsFinite);
uint64 OldSize = Size;
Size = NewSize;
if (CodedSizeLength(Size, SizeLength, bSizeIsFinite) == OldSizeLen) {
bSizeIsFinite = true;
return true;
}
Size = OldSize;
return false;
}
filepos_t EbmlElement::OverwriteHead(IOCallback & output, bool bKeepPosition)
{
if (ElementPosition == 0) {
return 0; // the element has not been written
}
uint64 CurrentPosition = output.getFilePointer();
output.setFilePointer(GetElementPosition());
filepos_t Result = MakeRenderHead(output, bKeepPosition);
output.setFilePointer(CurrentPosition);
return Result;
}
uint64 EbmlElement::VoidMe(IOCallback & output, bool bWithDefault)
{
if (ElementPosition == 0) {
return 0; // the element has not been written
}
EbmlVoid Dummy;
return Dummy.Overwrite(*this, output, bWithDefault);
}
END_LIBEBML_NAMESPACE
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/good_1810_1 |
crossvul-cpp_data_bad_186_1 | /*
* DSA
* (C) 1999-2010,2014,2016 Jack Lloyd
* (C) 2016 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/dsa.h>
#include <botan/keypair.h>
#include <botan/reducer.h>
#include <botan/rng.h>
#include <botan/internal/pk_ops_impl.h>
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
#include <botan/emsa.h>
#include <botan/rfc6979.h>
#endif
namespace Botan {
/*
* DSA_PublicKey Constructor
*/
DSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1)
{
m_group = grp;
m_y = y1;
}
/*
* Create a DSA private key
*/
DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng,
const DL_Group& grp,
const BigInt& x_arg)
{
m_group = grp;
if(x_arg == 0)
m_x = BigInt::random_integer(rng, 2, group_q());
else
m_x = x_arg;
m_y = m_group.power_g_p(m_x);
}
DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id,
const secure_vector<uint8_t>& key_bits) :
DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_57)
{
m_y = m_group.power_g_p(m_x);
}
/*
* Check Private DSA Parameters
*/
bool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const
{
if(!DL_Scheme_PrivateKey::check_key(rng, strong) || m_x >= group_q())
return false;
if(!strong)
return true;
return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-256)");
}
namespace {
/**
* Object that can create a DSA signature
*/
class DSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA
{
public:
DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa) :
PK_Ops::Signature_with_EMSA(emsa),
m_group(dsa.get_group()),
m_x(dsa.get_x()),
m_mod_q(dsa.group_q())
{
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
m_rfc6979_hash = hash_for_emsa(emsa);
#endif
}
size_t max_input_bits() const override { return m_group.get_q().bits(); }
secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng) override;
private:
const DL_Group m_group;
const BigInt& m_x;
Modular_Reducer m_mod_q;
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
std::string m_rfc6979_hash;
#endif
};
secure_vector<uint8_t>
DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
const BigInt& q = m_group.get_q();
BigInt i(msg, msg_len, q.bits());
while(i >= q)
i -= q;
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
BOTAN_UNUSED(rng);
const BigInt k = generate_rfc6979_nonce(m_x, q, i, m_rfc6979_hash);
#else
const BigInt k = BigInt::random_integer(rng, 1, q);
#endif
BigInt s = inverse_mod(k, q);
const BigInt r = m_mod_q.reduce(m_group.power_g_p(k));
s = m_mod_q.multiply(s, mul_add(m_x, r, i));
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("Computed zero r/s during DSA signature");
return BigInt::encode_fixed_length_int_pair(r, s, q.bytes());
}
/**
* Object that can verify a DSA signature
*/
class DSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA
{
public:
DSA_Verification_Operation(const DSA_PublicKey& dsa,
const std::string& emsa) :
PK_Ops::Verification_with_EMSA(emsa),
m_group(dsa.get_group()),
m_y(dsa.get_y()),
m_mod_q(dsa.group_q())
{}
size_t max_input_bits() const override { return m_group.get_q().bits(); }
bool with_recovery() const override { return false; }
bool verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len) override;
private:
const DL_Group m_group;
const BigInt& m_y;
Modular_Reducer m_mod_q;
};
bool DSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len)
{
const BigInt& q = m_group.get_q();
const size_t q_bytes = q.bytes();
if(sig_len != 2*q_bytes || msg_len > q_bytes)
return false;
BigInt r(sig, q_bytes);
BigInt s(sig + q_bytes, q_bytes);
BigInt i(msg, msg_len, q.bits());
if(r <= 0 || r >= q || s <= 0 || s >= q)
return false;
s = inverse_mod(s, q);
const BigInt sr = m_mod_q.multiply(s, r);
const BigInt si = m_mod_q.multiply(s, i);
s = m_group.multi_exponentiate(si, m_y, sr);
return (m_mod_q.reduce(s) == r);
}
}
std::unique_ptr<PK_Ops::Verification>
DSA_PublicKey::create_verification_op(const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Verification>(new DSA_Verification_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
}
std::unique_ptr<PK_Ops::Signature>
DSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Signature>(new DSA_Signature_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/cpp/bad_186_1 |
crossvul-cpp_data_bad_3401_0 | /**************************************************************************
*
* Copyright © 2009-2015 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#include "vmwgfx_drv.h"
#include "vmwgfx_resource_priv.h"
#include "vmwgfx_so.h"
#include "vmwgfx_binding.h"
#include <ttm/ttm_placement.h>
#include "device_include/svga3d_surfacedefs.h"
/**
* struct vmw_user_surface - User-space visible surface resource
*
* @base: The TTM base object handling user-space visibility.
* @srf: The surface metadata.
* @size: TTM accounting size for the surface.
* @master: master of the creating client. Used for security check.
*/
struct vmw_user_surface {
struct ttm_prime_object prime;
struct vmw_surface srf;
uint32_t size;
struct drm_master *master;
struct ttm_base_object *backup_base;
};
/**
* struct vmw_surface_offset - Backing store mip level offset info
*
* @face: Surface face.
* @mip: Mip level.
* @bo_offset: Offset into backing store of this mip level.
*
*/
struct vmw_surface_offset {
uint32_t face;
uint32_t mip;
uint32_t bo_offset;
};
static void vmw_user_surface_free(struct vmw_resource *res);
static struct vmw_resource *
vmw_user_surface_base_to_res(struct ttm_base_object *base);
static int vmw_legacy_srf_bind(struct vmw_resource *res,
struct ttm_validate_buffer *val_buf);
static int vmw_legacy_srf_unbind(struct vmw_resource *res,
bool readback,
struct ttm_validate_buffer *val_buf);
static int vmw_legacy_srf_create(struct vmw_resource *res);
static int vmw_legacy_srf_destroy(struct vmw_resource *res);
static int vmw_gb_surface_create(struct vmw_resource *res);
static int vmw_gb_surface_bind(struct vmw_resource *res,
struct ttm_validate_buffer *val_buf);
static int vmw_gb_surface_unbind(struct vmw_resource *res,
bool readback,
struct ttm_validate_buffer *val_buf);
static int vmw_gb_surface_destroy(struct vmw_resource *res);
static const struct vmw_user_resource_conv user_surface_conv = {
.object_type = VMW_RES_SURFACE,
.base_obj_to_res = vmw_user_surface_base_to_res,
.res_free = vmw_user_surface_free
};
const struct vmw_user_resource_conv *user_surface_converter =
&user_surface_conv;
static uint64_t vmw_user_surface_size;
static const struct vmw_res_func vmw_legacy_surface_func = {
.res_type = vmw_res_surface,
.needs_backup = false,
.may_evict = true,
.type_name = "legacy surfaces",
.backup_placement = &vmw_srf_placement,
.create = &vmw_legacy_srf_create,
.destroy = &vmw_legacy_srf_destroy,
.bind = &vmw_legacy_srf_bind,
.unbind = &vmw_legacy_srf_unbind
};
static const struct vmw_res_func vmw_gb_surface_func = {
.res_type = vmw_res_surface,
.needs_backup = true,
.may_evict = true,
.type_name = "guest backed surfaces",
.backup_placement = &vmw_mob_placement,
.create = vmw_gb_surface_create,
.destroy = vmw_gb_surface_destroy,
.bind = vmw_gb_surface_bind,
.unbind = vmw_gb_surface_unbind
};
/**
* struct vmw_surface_dma - SVGA3D DMA command
*/
struct vmw_surface_dma {
SVGA3dCmdHeader header;
SVGA3dCmdSurfaceDMA body;
SVGA3dCopyBox cb;
SVGA3dCmdSurfaceDMASuffix suffix;
};
/**
* struct vmw_surface_define - SVGA3D Surface Define command
*/
struct vmw_surface_define {
SVGA3dCmdHeader header;
SVGA3dCmdDefineSurface body;
};
/**
* struct vmw_surface_destroy - SVGA3D Surface Destroy command
*/
struct vmw_surface_destroy {
SVGA3dCmdHeader header;
SVGA3dCmdDestroySurface body;
};
/**
* vmw_surface_dma_size - Compute fifo size for a dma command.
*
* @srf: Pointer to a struct vmw_surface
*
* Computes the required size for a surface dma command for backup or
* restoration of the surface represented by @srf.
*/
static inline uint32_t vmw_surface_dma_size(const struct vmw_surface *srf)
{
return srf->num_sizes * sizeof(struct vmw_surface_dma);
}
/**
* vmw_surface_define_size - Compute fifo size for a surface define command.
*
* @srf: Pointer to a struct vmw_surface
*
* Computes the required size for a surface define command for the definition
* of the surface represented by @srf.
*/
static inline uint32_t vmw_surface_define_size(const struct vmw_surface *srf)
{
return sizeof(struct vmw_surface_define) + srf->num_sizes *
sizeof(SVGA3dSize);
}
/**
* vmw_surface_destroy_size - Compute fifo size for a surface destroy command.
*
* Computes the required size for a surface destroy command for the destruction
* of a hw surface.
*/
static inline uint32_t vmw_surface_destroy_size(void)
{
return sizeof(struct vmw_surface_destroy);
}
/**
* vmw_surface_destroy_encode - Encode a surface_destroy command.
*
* @id: The surface id
* @cmd_space: Pointer to memory area in which the commands should be encoded.
*/
static void vmw_surface_destroy_encode(uint32_t id,
void *cmd_space)
{
struct vmw_surface_destroy *cmd = (struct vmw_surface_destroy *)
cmd_space;
cmd->header.id = SVGA_3D_CMD_SURFACE_DESTROY;
cmd->header.size = sizeof(cmd->body);
cmd->body.sid = id;
}
/**
* vmw_surface_define_encode - Encode a surface_define command.
*
* @srf: Pointer to a struct vmw_surface object.
* @cmd_space: Pointer to memory area in which the commands should be encoded.
*/
static void vmw_surface_define_encode(const struct vmw_surface *srf,
void *cmd_space)
{
struct vmw_surface_define *cmd = (struct vmw_surface_define *)
cmd_space;
struct drm_vmw_size *src_size;
SVGA3dSize *cmd_size;
uint32_t cmd_len;
int i;
cmd_len = sizeof(cmd->body) + srf->num_sizes * sizeof(SVGA3dSize);
cmd->header.id = SVGA_3D_CMD_SURFACE_DEFINE;
cmd->header.size = cmd_len;
cmd->body.sid = srf->res.id;
cmd->body.surfaceFlags = srf->flags;
cmd->body.format = srf->format;
for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i)
cmd->body.face[i].numMipLevels = srf->mip_levels[i];
cmd += 1;
cmd_size = (SVGA3dSize *) cmd;
src_size = srf->sizes;
for (i = 0; i < srf->num_sizes; ++i, cmd_size++, src_size++) {
cmd_size->width = src_size->width;
cmd_size->height = src_size->height;
cmd_size->depth = src_size->depth;
}
}
/**
* vmw_surface_dma_encode - Encode a surface_dma command.
*
* @srf: Pointer to a struct vmw_surface object.
* @cmd_space: Pointer to memory area in which the commands should be encoded.
* @ptr: Pointer to an SVGAGuestPtr indicating where the surface contents
* should be placed or read from.
* @to_surface: Boolean whether to DMA to the surface or from the surface.
*/
static void vmw_surface_dma_encode(struct vmw_surface *srf,
void *cmd_space,
const SVGAGuestPtr *ptr,
bool to_surface)
{
uint32_t i;
struct vmw_surface_dma *cmd = (struct vmw_surface_dma *)cmd_space;
const struct svga3d_surface_desc *desc =
svga3dsurface_get_desc(srf->format);
for (i = 0; i < srf->num_sizes; ++i) {
SVGA3dCmdHeader *header = &cmd->header;
SVGA3dCmdSurfaceDMA *body = &cmd->body;
SVGA3dCopyBox *cb = &cmd->cb;
SVGA3dCmdSurfaceDMASuffix *suffix = &cmd->suffix;
const struct vmw_surface_offset *cur_offset = &srf->offsets[i];
const struct drm_vmw_size *cur_size = &srf->sizes[i];
header->id = SVGA_3D_CMD_SURFACE_DMA;
header->size = sizeof(*body) + sizeof(*cb) + sizeof(*suffix);
body->guest.ptr = *ptr;
body->guest.ptr.offset += cur_offset->bo_offset;
body->guest.pitch = svga3dsurface_calculate_pitch(desc,
cur_size);
body->host.sid = srf->res.id;
body->host.face = cur_offset->face;
body->host.mipmap = cur_offset->mip;
body->transfer = ((to_surface) ? SVGA3D_WRITE_HOST_VRAM :
SVGA3D_READ_HOST_VRAM);
cb->x = 0;
cb->y = 0;
cb->z = 0;
cb->srcx = 0;
cb->srcy = 0;
cb->srcz = 0;
cb->w = cur_size->width;
cb->h = cur_size->height;
cb->d = cur_size->depth;
suffix->suffixSize = sizeof(*suffix);
suffix->maximumOffset =
svga3dsurface_get_image_buffer_size(desc, cur_size,
body->guest.pitch);
suffix->flags.discard = 0;
suffix->flags.unsynchronized = 0;
suffix->flags.reserved = 0;
++cmd;
}
};
/**
* vmw_hw_surface_destroy - destroy a Device surface
*
* @res: Pointer to a struct vmw_resource embedded in a struct
* vmw_surface.
*
* Destroys a the device surface associated with a struct vmw_surface if
* any, and adjusts accounting and resource count accordingly.
*/
static void vmw_hw_surface_destroy(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
struct vmw_surface *srf;
void *cmd;
if (res->func->destroy == vmw_gb_surface_destroy) {
(void) vmw_gb_surface_destroy(res);
return;
}
if (res->id != -1) {
cmd = vmw_fifo_reserve(dev_priv, vmw_surface_destroy_size());
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"destruction.\n");
return;
}
vmw_surface_destroy_encode(res->id, cmd);
vmw_fifo_commit(dev_priv, vmw_surface_destroy_size());
/*
* used_memory_size_atomic, or separate lock
* to avoid taking dev_priv::cmdbuf_mutex in
* the destroy path.
*/
mutex_lock(&dev_priv->cmdbuf_mutex);
srf = vmw_res_to_srf(res);
dev_priv->used_memory_size -= res->backup_size;
mutex_unlock(&dev_priv->cmdbuf_mutex);
}
vmw_fifo_resource_dec(dev_priv);
}
/**
* vmw_legacy_srf_create - Create a device surface as part of the
* resource validation process.
*
* @res: Pointer to a struct vmw_surface.
*
* If the surface doesn't have a hw id.
*
* Returns -EBUSY if there wasn't sufficient device resources to
* complete the validation. Retry after freeing up resources.
*
* May return other errors if the kernel is out of guest resources.
*/
static int vmw_legacy_srf_create(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
struct vmw_surface *srf;
uint32_t submit_size;
uint8_t *cmd;
int ret;
if (likely(res->id != -1))
return 0;
srf = vmw_res_to_srf(res);
if (unlikely(dev_priv->used_memory_size + res->backup_size >=
dev_priv->memory_size))
return -EBUSY;
/*
* Alloc id for the resource.
*/
ret = vmw_resource_alloc_id(res);
if (unlikely(ret != 0)) {
DRM_ERROR("Failed to allocate a surface id.\n");
goto out_no_id;
}
if (unlikely(res->id >= SVGA3D_MAX_SURFACE_IDS)) {
ret = -EBUSY;
goto out_no_fifo;
}
/*
* Encode surface define- commands.
*/
submit_size = vmw_surface_define_size(srf);
cmd = vmw_fifo_reserve(dev_priv, submit_size);
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"creation.\n");
ret = -ENOMEM;
goto out_no_fifo;
}
vmw_surface_define_encode(srf, cmd);
vmw_fifo_commit(dev_priv, submit_size);
/*
* Surface memory usage accounting.
*/
dev_priv->used_memory_size += res->backup_size;
return 0;
out_no_fifo:
vmw_resource_release_id(res);
out_no_id:
return ret;
}
/**
* vmw_legacy_srf_dma - Copy backup data to or from a legacy surface.
*
* @res: Pointer to a struct vmw_res embedded in a struct
* vmw_surface.
* @val_buf: Pointer to a struct ttm_validate_buffer containing
* information about the backup buffer.
* @bind: Boolean wether to DMA to the surface.
*
* Transfer backup data to or from a legacy surface as part of the
* validation process.
* May return other errors if the kernel is out of guest resources.
* The backup buffer will be fenced or idle upon successful completion,
* and if the surface needs persistent backup storage, the backup buffer
* will also be returned reserved iff @bind is true.
*/
static int vmw_legacy_srf_dma(struct vmw_resource *res,
struct ttm_validate_buffer *val_buf,
bool bind)
{
SVGAGuestPtr ptr;
struct vmw_fence_obj *fence;
uint32_t submit_size;
struct vmw_surface *srf = vmw_res_to_srf(res);
uint8_t *cmd;
struct vmw_private *dev_priv = res->dev_priv;
BUG_ON(!val_buf->bo);
submit_size = vmw_surface_dma_size(srf);
cmd = vmw_fifo_reserve(dev_priv, submit_size);
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"DMA.\n");
return -ENOMEM;
}
vmw_bo_get_guest_ptr(val_buf->bo, &ptr);
vmw_surface_dma_encode(srf, cmd, &ptr, bind);
vmw_fifo_commit(dev_priv, submit_size);
/*
* Create a fence object and fence the backup buffer.
*/
(void) vmw_execbuf_fence_commands(NULL, dev_priv,
&fence, NULL);
vmw_fence_single_bo(val_buf->bo, fence);
if (likely(fence != NULL))
vmw_fence_obj_unreference(&fence);
return 0;
}
/**
* vmw_legacy_srf_bind - Perform a legacy surface bind as part of the
* surface validation process.
*
* @res: Pointer to a struct vmw_res embedded in a struct
* vmw_surface.
* @val_buf: Pointer to a struct ttm_validate_buffer containing
* information about the backup buffer.
*
* This function will copy backup data to the surface if the
* backup buffer is dirty.
*/
static int vmw_legacy_srf_bind(struct vmw_resource *res,
struct ttm_validate_buffer *val_buf)
{
if (!res->backup_dirty)
return 0;
return vmw_legacy_srf_dma(res, val_buf, true);
}
/**
* vmw_legacy_srf_unbind - Perform a legacy surface unbind as part of the
* surface eviction process.
*
* @res: Pointer to a struct vmw_res embedded in a struct
* vmw_surface.
* @val_buf: Pointer to a struct ttm_validate_buffer containing
* information about the backup buffer.
*
* This function will copy backup data from the surface.
*/
static int vmw_legacy_srf_unbind(struct vmw_resource *res,
bool readback,
struct ttm_validate_buffer *val_buf)
{
if (unlikely(readback))
return vmw_legacy_srf_dma(res, val_buf, false);
return 0;
}
/**
* vmw_legacy_srf_destroy - Destroy a device surface as part of a
* resource eviction process.
*
* @res: Pointer to a struct vmw_res embedded in a struct
* vmw_surface.
*/
static int vmw_legacy_srf_destroy(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
uint32_t submit_size;
uint8_t *cmd;
BUG_ON(res->id == -1);
/*
* Encode the dma- and surface destroy commands.
*/
submit_size = vmw_surface_destroy_size();
cmd = vmw_fifo_reserve(dev_priv, submit_size);
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"eviction.\n");
return -ENOMEM;
}
vmw_surface_destroy_encode(res->id, cmd);
vmw_fifo_commit(dev_priv, submit_size);
/*
* Surface memory usage accounting.
*/
dev_priv->used_memory_size -= res->backup_size;
/*
* Release the surface ID.
*/
vmw_resource_release_id(res);
return 0;
}
/**
* vmw_surface_init - initialize a struct vmw_surface
*
* @dev_priv: Pointer to a device private struct.
* @srf: Pointer to the struct vmw_surface to initialize.
* @res_free: Pointer to a resource destructor used to free
* the object.
*/
static int vmw_surface_init(struct vmw_private *dev_priv,
struct vmw_surface *srf,
void (*res_free) (struct vmw_resource *res))
{
int ret;
struct vmw_resource *res = &srf->res;
BUG_ON(!res_free);
if (!dev_priv->has_mob)
vmw_fifo_resource_inc(dev_priv);
ret = vmw_resource_init(dev_priv, res, true, res_free,
(dev_priv->has_mob) ? &vmw_gb_surface_func :
&vmw_legacy_surface_func);
if (unlikely(ret != 0)) {
if (!dev_priv->has_mob)
vmw_fifo_resource_dec(dev_priv);
res_free(res);
return ret;
}
/*
* The surface won't be visible to hardware until a
* surface validate.
*/
INIT_LIST_HEAD(&srf->view_list);
vmw_resource_activate(res, vmw_hw_surface_destroy);
return ret;
}
/**
* vmw_user_surface_base_to_res - TTM base object to resource converter for
* user visible surfaces
*
* @base: Pointer to a TTM base object
*
* Returns the struct vmw_resource embedded in a struct vmw_surface
* for the user-visible object identified by the TTM base object @base.
*/
static struct vmw_resource *
vmw_user_surface_base_to_res(struct ttm_base_object *base)
{
return &(container_of(base, struct vmw_user_surface,
prime.base)->srf.res);
}
/**
* vmw_user_surface_free - User visible surface resource destructor
*
* @res: A struct vmw_resource embedded in a struct vmw_surface.
*/
static void vmw_user_surface_free(struct vmw_resource *res)
{
struct vmw_surface *srf = vmw_res_to_srf(res);
struct vmw_user_surface *user_srf =
container_of(srf, struct vmw_user_surface, srf);
struct vmw_private *dev_priv = srf->res.dev_priv;
uint32_t size = user_srf->size;
if (user_srf->master)
drm_master_put(&user_srf->master);
kfree(srf->offsets);
kfree(srf->sizes);
kfree(srf->snooper.image);
ttm_prime_object_kfree(user_srf, prime);
ttm_mem_global_free(vmw_mem_glob(dev_priv), size);
}
/**
* vmw_user_surface_free - User visible surface TTM base object destructor
*
* @p_base: Pointer to a pointer to a TTM base object
* embedded in a struct vmw_user_surface.
*
* Drops the base object's reference on its resource, and the
* pointer pointed to by *p_base is set to NULL.
*/
static void vmw_user_surface_base_release(struct ttm_base_object **p_base)
{
struct ttm_base_object *base = *p_base;
struct vmw_user_surface *user_srf =
container_of(base, struct vmw_user_surface, prime.base);
struct vmw_resource *res = &user_srf->srf.res;
*p_base = NULL;
if (user_srf->backup_base)
ttm_base_object_unref(&user_srf->backup_base);
vmw_resource_unreference(&res);
}
/**
* vmw_user_surface_destroy_ioctl - Ioctl function implementing
* the user surface destroy functionality.
*
* @dev: Pointer to a struct drm_device.
* @data: Pointer to data copied from / to user-space.
* @file_priv: Pointer to a drm file private structure.
*/
int vmw_surface_destroy_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vmw_surface_arg *arg = (struct drm_vmw_surface_arg *)data;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
return ttm_ref_object_base_unref(tfile, arg->sid, TTM_REF_USAGE);
}
/**
* vmw_user_surface_define_ioctl - Ioctl function implementing
* the user surface define functionality.
*
* @dev: Pointer to a struct drm_device.
* @data: Pointer to data copied from / to user-space.
* @file_priv: Pointer to a drm file private structure.
*/
int vmw_surface_define_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
struct vmw_resource *res;
struct vmw_resource *tmp;
union drm_vmw_surface_create_arg *arg =
(union drm_vmw_surface_create_arg *)data;
struct drm_vmw_surface_create_req *req = &arg->req;
struct drm_vmw_surface_arg *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
int i, j;
uint32_t cur_bo_offset;
struct drm_vmw_size *cur_size;
struct vmw_surface_offset *cur_offset;
uint32_t num_sizes;
uint32_t size;
const struct svga3d_surface_desc *desc;
if (unlikely(vmw_user_surface_size == 0))
vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) +
128;
num_sizes = 0;
for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) {
if (req->mip_levels[i] > DRM_VMW_MAX_MIP_LEVELS)
return -EINVAL;
num_sizes += req->mip_levels[i];
}
if (num_sizes > DRM_VMW_MAX_SURFACE_FACES * DRM_VMW_MAX_MIP_LEVELS ||
num_sizes == 0)
return -EINVAL;
size = vmw_user_surface_size + 128 +
ttm_round_pot(num_sizes * sizeof(struct drm_vmw_size)) +
ttm_round_pot(num_sizes * sizeof(struct vmw_surface_offset));
desc = svga3dsurface_get_desc(req->format);
if (unlikely(desc->block_desc == SVGA3DBLOCKDESC_NONE)) {
DRM_ERROR("Invalid surface format for surface creation.\n");
DRM_ERROR("Format requested is: %d\n", req->format);
return -EINVAL;
}
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
ret = ttm_mem_global_alloc(vmw_mem_glob(dev_priv),
size, false, true);
if (unlikely(ret != 0)) {
if (ret != -ERESTARTSYS)
DRM_ERROR("Out of graphics memory for surface"
" creation.\n");
goto out_unlock;
}
user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL);
if (unlikely(!user_srf)) {
ret = -ENOMEM;
goto out_no_user_srf;
}
srf = &user_srf->srf;
res = &srf->res;
srf->flags = req->flags;
srf->format = req->format;
srf->scanout = req->scanout;
memcpy(srf->mip_levels, req->mip_levels, sizeof(srf->mip_levels));
srf->num_sizes = num_sizes;
user_srf->size = size;
srf->sizes = memdup_user((struct drm_vmw_size __user *)(unsigned long)
req->size_addr,
sizeof(*srf->sizes) * srf->num_sizes);
if (IS_ERR(srf->sizes)) {
ret = PTR_ERR(srf->sizes);
goto out_no_sizes;
}
srf->offsets = kmalloc_array(srf->num_sizes,
sizeof(*srf->offsets),
GFP_KERNEL);
if (unlikely(!srf->offsets)) {
ret = -ENOMEM;
goto out_no_offsets;
}
srf->base_size = *srf->sizes;
srf->autogen_filter = SVGA3D_TEX_FILTER_NONE;
srf->multisample_count = 0;
cur_bo_offset = 0;
cur_offset = srf->offsets;
cur_size = srf->sizes;
for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) {
for (j = 0; j < srf->mip_levels[i]; ++j) {
uint32_t stride = svga3dsurface_calculate_pitch
(desc, cur_size);
cur_offset->face = i;
cur_offset->mip = j;
cur_offset->bo_offset = cur_bo_offset;
cur_bo_offset += svga3dsurface_get_image_buffer_size
(desc, cur_size, stride);
++cur_offset;
++cur_size;
}
}
res->backup_size = cur_bo_offset;
if (srf->scanout &&
srf->num_sizes == 1 &&
srf->sizes[0].width == 64 &&
srf->sizes[0].height == 64 &&
srf->format == SVGA3D_A8R8G8B8) {
srf->snooper.image = kzalloc(64 * 64 * 4, GFP_KERNEL);
if (!srf->snooper.image) {
DRM_ERROR("Failed to allocate cursor_image\n");
ret = -ENOMEM;
goto out_no_copy;
}
} else {
srf->snooper.image = NULL;
}
user_srf->prime.base.shareable = false;
user_srf->prime.base.tfile = NULL;
if (drm_is_primary_client(file_priv))
user_srf->master = drm_master_get(file_priv->master);
/**
* From this point, the generic resource management functions
* destroy the object on failure.
*/
ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free);
if (unlikely(ret != 0))
goto out_unlock;
/*
* A gb-aware client referencing a shared surface will
* expect a backup buffer to be present.
*/
if (dev_priv->has_mob && req->shareable) {
uint32_t backup_handle;
ret = vmw_user_dmabuf_alloc(dev_priv, tfile,
res->backup_size,
true,
&backup_handle,
&res->backup,
&user_srf->backup_base);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&res);
goto out_unlock;
}
}
tmp = vmw_resource_reference(&srf->res);
ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
req->shareable, VMW_RES_SURFACE,
&vmw_user_surface_base_release, NULL);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&tmp);
vmw_resource_unreference(&res);
goto out_unlock;
}
rep->sid = user_srf->prime.base.hash.key;
vmw_resource_unreference(&res);
ttm_read_unlock(&dev_priv->reservation_sem);
return 0;
out_no_copy:
kfree(srf->offsets);
out_no_offsets:
kfree(srf->sizes);
out_no_sizes:
ttm_prime_object_kfree(user_srf, prime);
out_no_user_srf:
ttm_mem_global_free(vmw_mem_glob(dev_priv), size);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
static int
vmw_surface_handle_reference(struct vmw_private *dev_priv,
struct drm_file *file_priv,
uint32_t u_handle,
enum drm_vmw_handle_type handle_type,
struct ttm_base_object **base_p)
{
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_user_surface *user_srf;
uint32_t handle;
struct ttm_base_object *base;
int ret;
bool require_exist = false;
if (handle_type == DRM_VMW_HANDLE_PRIME) {
ret = ttm_prime_fd_to_handle(tfile, u_handle, &handle);
if (unlikely(ret != 0))
return ret;
} else {
if (unlikely(drm_is_render_client(file_priv)))
require_exist = true;
if (ACCESS_ONCE(vmw_fpriv(file_priv)->locked_master)) {
DRM_ERROR("Locked master refused legacy "
"surface reference.\n");
return -EACCES;
}
handle = u_handle;
}
ret = -EINVAL;
base = ttm_base_object_lookup_for_ref(dev_priv->tdev, handle);
if (unlikely(!base)) {
DRM_ERROR("Could not find surface to reference.\n");
goto out_no_lookup;
}
if (unlikely(ttm_base_object_type(base) != VMW_RES_SURFACE)) {
DRM_ERROR("Referenced object is not a surface.\n");
goto out_bad_resource;
}
if (handle_type != DRM_VMW_HANDLE_PRIME) {
user_srf = container_of(base, struct vmw_user_surface,
prime.base);
/*
* Make sure the surface creator has the same
* authenticating master, or is already registered with us.
*/
if (drm_is_primary_client(file_priv) &&
user_srf->master != file_priv->master)
require_exist = true;
ret = ttm_ref_object_add(tfile, base, TTM_REF_USAGE, NULL,
require_exist);
if (unlikely(ret != 0)) {
DRM_ERROR("Could not add a reference to a surface.\n");
goto out_bad_resource;
}
}
*base_p = base;
return 0;
out_bad_resource:
ttm_base_object_unref(&base);
out_no_lookup:
if (handle_type == DRM_VMW_HANDLE_PRIME)
(void) ttm_ref_object_base_unref(tfile, handle, TTM_REF_USAGE);
return ret;
}
/**
* vmw_user_surface_define_ioctl - Ioctl function implementing
* the user surface reference functionality.
*
* @dev: Pointer to a struct drm_device.
* @data: Pointer to data copied from / to user-space.
* @file_priv: Pointer to a drm file private structure.
*/
int vmw_surface_reference_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
union drm_vmw_surface_reference_arg *arg =
(union drm_vmw_surface_reference_arg *)data;
struct drm_vmw_surface_arg *req = &arg->req;
struct drm_vmw_surface_create_req *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_surface *srf;
struct vmw_user_surface *user_srf;
struct drm_vmw_size __user *user_sizes;
struct ttm_base_object *base;
int ret;
ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid,
req->handle_type, &base);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(base, struct vmw_user_surface, prime.base);
srf = &user_srf->srf;
rep->flags = srf->flags;
rep->format = srf->format;
memcpy(rep->mip_levels, srf->mip_levels, sizeof(srf->mip_levels));
user_sizes = (struct drm_vmw_size __user *)(unsigned long)
rep->size_addr;
if (user_sizes)
ret = copy_to_user(user_sizes, &srf->base_size,
sizeof(srf->base_size));
if (unlikely(ret != 0)) {
DRM_ERROR("copy_to_user failed %p %u\n",
user_sizes, srf->num_sizes);
ttm_ref_object_base_unref(tfile, base->hash.key, TTM_REF_USAGE);
ret = -EFAULT;
}
ttm_base_object_unref(&base);
return ret;
}
/**
* vmw_surface_define_encode - Encode a surface_define command.
*
* @srf: Pointer to a struct vmw_surface object.
* @cmd_space: Pointer to memory area in which the commands should be encoded.
*/
static int vmw_gb_surface_create(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
struct vmw_surface *srf = vmw_res_to_srf(res);
uint32_t cmd_len, cmd_id, submit_len;
int ret;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdDefineGBSurface body;
} *cmd;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdDefineGBSurface_v2 body;
} *cmd2;
if (likely(res->id != -1))
return 0;
vmw_fifo_resource_inc(dev_priv);
ret = vmw_resource_alloc_id(res);
if (unlikely(ret != 0)) {
DRM_ERROR("Failed to allocate a surface id.\n");
goto out_no_id;
}
if (unlikely(res->id >= VMWGFX_NUM_GB_SURFACE)) {
ret = -EBUSY;
goto out_no_fifo;
}
if (srf->array_size > 0) {
/* has_dx checked on creation time. */
cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE_V2;
cmd_len = sizeof(cmd2->body);
submit_len = sizeof(*cmd2);
} else {
cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE;
cmd_len = sizeof(cmd->body);
submit_len = sizeof(*cmd);
}
cmd = vmw_fifo_reserve(dev_priv, submit_len);
cmd2 = (typeof(cmd2))cmd;
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"creation.\n");
ret = -ENOMEM;
goto out_no_fifo;
}
if (srf->array_size > 0) {
cmd2->header.id = cmd_id;
cmd2->header.size = cmd_len;
cmd2->body.sid = srf->res.id;
cmd2->body.surfaceFlags = srf->flags;
cmd2->body.format = cpu_to_le32(srf->format);
cmd2->body.numMipLevels = srf->mip_levels[0];
cmd2->body.multisampleCount = srf->multisample_count;
cmd2->body.autogenFilter = srf->autogen_filter;
cmd2->body.size.width = srf->base_size.width;
cmd2->body.size.height = srf->base_size.height;
cmd2->body.size.depth = srf->base_size.depth;
cmd2->body.arraySize = srf->array_size;
} else {
cmd->header.id = cmd_id;
cmd->header.size = cmd_len;
cmd->body.sid = srf->res.id;
cmd->body.surfaceFlags = srf->flags;
cmd->body.format = cpu_to_le32(srf->format);
cmd->body.numMipLevels = srf->mip_levels[0];
cmd->body.multisampleCount = srf->multisample_count;
cmd->body.autogenFilter = srf->autogen_filter;
cmd->body.size.width = srf->base_size.width;
cmd->body.size.height = srf->base_size.height;
cmd->body.size.depth = srf->base_size.depth;
}
vmw_fifo_commit(dev_priv, submit_len);
return 0;
out_no_fifo:
vmw_resource_release_id(res);
out_no_id:
vmw_fifo_resource_dec(dev_priv);
return ret;
}
static int vmw_gb_surface_bind(struct vmw_resource *res,
struct ttm_validate_buffer *val_buf)
{
struct vmw_private *dev_priv = res->dev_priv;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdBindGBSurface body;
} *cmd1;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdUpdateGBSurface body;
} *cmd2;
uint32_t submit_size;
struct ttm_buffer_object *bo = val_buf->bo;
BUG_ON(bo->mem.mem_type != VMW_PL_MOB);
submit_size = sizeof(*cmd1) + (res->backup_dirty ? sizeof(*cmd2) : 0);
cmd1 = vmw_fifo_reserve(dev_priv, submit_size);
if (unlikely(!cmd1)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"binding.\n");
return -ENOMEM;
}
cmd1->header.id = SVGA_3D_CMD_BIND_GB_SURFACE;
cmd1->header.size = sizeof(cmd1->body);
cmd1->body.sid = res->id;
cmd1->body.mobid = bo->mem.start;
if (res->backup_dirty) {
cmd2 = (void *) &cmd1[1];
cmd2->header.id = SVGA_3D_CMD_UPDATE_GB_SURFACE;
cmd2->header.size = sizeof(cmd2->body);
cmd2->body.sid = res->id;
res->backup_dirty = false;
}
vmw_fifo_commit(dev_priv, submit_size);
return 0;
}
static int vmw_gb_surface_unbind(struct vmw_resource *res,
bool readback,
struct ttm_validate_buffer *val_buf)
{
struct vmw_private *dev_priv = res->dev_priv;
struct ttm_buffer_object *bo = val_buf->bo;
struct vmw_fence_obj *fence;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdReadbackGBSurface body;
} *cmd1;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdInvalidateGBSurface body;
} *cmd2;
struct {
SVGA3dCmdHeader header;
SVGA3dCmdBindGBSurface body;
} *cmd3;
uint32_t submit_size;
uint8_t *cmd;
BUG_ON(bo->mem.mem_type != VMW_PL_MOB);
submit_size = sizeof(*cmd3) + (readback ? sizeof(*cmd1) : sizeof(*cmd2));
cmd = vmw_fifo_reserve(dev_priv, submit_size);
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"unbinding.\n");
return -ENOMEM;
}
if (readback) {
cmd1 = (void *) cmd;
cmd1->header.id = SVGA_3D_CMD_READBACK_GB_SURFACE;
cmd1->header.size = sizeof(cmd1->body);
cmd1->body.sid = res->id;
cmd3 = (void *) &cmd1[1];
} else {
cmd2 = (void *) cmd;
cmd2->header.id = SVGA_3D_CMD_INVALIDATE_GB_SURFACE;
cmd2->header.size = sizeof(cmd2->body);
cmd2->body.sid = res->id;
cmd3 = (void *) &cmd2[1];
}
cmd3->header.id = SVGA_3D_CMD_BIND_GB_SURFACE;
cmd3->header.size = sizeof(cmd3->body);
cmd3->body.sid = res->id;
cmd3->body.mobid = SVGA3D_INVALID_ID;
vmw_fifo_commit(dev_priv, submit_size);
/*
* Create a fence object and fence the backup buffer.
*/
(void) vmw_execbuf_fence_commands(NULL, dev_priv,
&fence, NULL);
vmw_fence_single_bo(val_buf->bo, fence);
if (likely(fence != NULL))
vmw_fence_obj_unreference(&fence);
return 0;
}
static int vmw_gb_surface_destroy(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
struct vmw_surface *srf = vmw_res_to_srf(res);
struct {
SVGA3dCmdHeader header;
SVGA3dCmdDestroyGBSurface body;
} *cmd;
if (likely(res->id == -1))
return 0;
mutex_lock(&dev_priv->binding_mutex);
vmw_view_surface_list_destroy(dev_priv, &srf->view_list);
vmw_binding_res_list_scrub(&res->binding_head);
cmd = vmw_fifo_reserve(dev_priv, sizeof(*cmd));
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"destruction.\n");
mutex_unlock(&dev_priv->binding_mutex);
return -ENOMEM;
}
cmd->header.id = SVGA_3D_CMD_DESTROY_GB_SURFACE;
cmd->header.size = sizeof(cmd->body);
cmd->body.sid = res->id;
vmw_fifo_commit(dev_priv, sizeof(*cmd));
mutex_unlock(&dev_priv->binding_mutex);
vmw_resource_release_id(res);
vmw_fifo_resource_dec(dev_priv);
return 0;
}
/**
* vmw_gb_surface_define_ioctl - Ioctl function implementing
* the user surface define functionality.
*
* @dev: Pointer to a struct drm_device.
* @data: Pointer to data copied from / to user-space.
* @file_priv: Pointer to a drm file private structure.
*/
int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
struct vmw_resource *res;
struct vmw_resource *tmp;
union drm_vmw_gb_surface_create_arg *arg =
(union drm_vmw_gb_surface_create_arg *)data;
struct drm_vmw_gb_surface_create_req *req = &arg->req;
struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
uint32_t size;
uint32_t backup_handle;
if (req->multisample_count != 0)
return -EINVAL;
if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS)
return -EINVAL;
if (unlikely(vmw_user_surface_size == 0))
vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) +
128;
size = vmw_user_surface_size + 128;
/* Define a surface based on the parameters. */
ret = vmw_surface_gb_priv_define(dev,
size,
req->svga3d_flags,
req->format,
req->drm_surface_flags & drm_vmw_surface_flag_scanout,
req->mip_levels,
req->multisample_count,
req->array_size,
req->base_size,
&srf);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(srf, struct vmw_user_surface, srf);
if (drm_is_primary_client(file_priv))
user_srf->master = drm_master_get(file_priv->master);
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
res = &user_srf->srf.res;
if (req->buffer_handle != SVGA3D_INVALID_ID) {
ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle,
&res->backup,
&user_srf->backup_base);
if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE <
res->backup_size) {
DRM_ERROR("Surface backup buffer is too small.\n");
vmw_dmabuf_unreference(&res->backup);
ret = -EINVAL;
goto out_unlock;
}
} else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer)
ret = vmw_user_dmabuf_alloc(dev_priv, tfile,
res->backup_size,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
&backup_handle,
&res->backup,
&user_srf->backup_base);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&res);
goto out_unlock;
}
tmp = vmw_resource_reference(res);
ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
VMW_RES_SURFACE,
&vmw_user_surface_base_release, NULL);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&tmp);
vmw_resource_unreference(&res);
goto out_unlock;
}
rep->handle = user_srf->prime.base.hash.key;
rep->backup_size = res->backup_size;
if (res->backup) {
rep->buffer_map_handle =
drm_vma_node_offset_addr(&res->backup->base.vma_node);
rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE;
rep->buffer_handle = backup_handle;
} else {
rep->buffer_map_handle = 0;
rep->buffer_size = 0;
rep->buffer_handle = SVGA3D_INVALID_ID;
}
vmw_resource_unreference(&res);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
/**
* vmw_gb_surface_reference_ioctl - Ioctl function implementing
* the user surface reference functionality.
*
* @dev: Pointer to a struct drm_device.
* @data: Pointer to data copied from / to user-space.
* @file_priv: Pointer to a drm file private structure.
*/
int vmw_gb_surface_reference_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
union drm_vmw_gb_surface_reference_arg *arg =
(union drm_vmw_gb_surface_reference_arg *)data;
struct drm_vmw_surface_arg *req = &arg->req;
struct drm_vmw_gb_surface_ref_rep *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_surface *srf;
struct vmw_user_surface *user_srf;
struct ttm_base_object *base;
uint32_t backup_handle;
int ret = -EINVAL;
ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid,
req->handle_type, &base);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(base, struct vmw_user_surface, prime.base);
srf = &user_srf->srf;
if (!srf->res.backup) {
DRM_ERROR("Shared GB surface is missing a backup buffer.\n");
goto out_bad_resource;
}
mutex_lock(&dev_priv->cmdbuf_mutex); /* Protect res->backup */
ret = vmw_user_dmabuf_reference(tfile, srf->res.backup,
&backup_handle);
mutex_unlock(&dev_priv->cmdbuf_mutex);
if (unlikely(ret != 0)) {
DRM_ERROR("Could not add a reference to a GB surface "
"backup buffer.\n");
(void) ttm_ref_object_base_unref(tfile, base->hash.key,
TTM_REF_USAGE);
goto out_bad_resource;
}
rep->creq.svga3d_flags = srf->flags;
rep->creq.format = srf->format;
rep->creq.mip_levels = srf->mip_levels[0];
rep->creq.drm_surface_flags = 0;
rep->creq.multisample_count = srf->multisample_count;
rep->creq.autogen_filter = srf->autogen_filter;
rep->creq.array_size = srf->array_size;
rep->creq.buffer_handle = backup_handle;
rep->creq.base_size = srf->base_size;
rep->crep.handle = user_srf->prime.base.hash.key;
rep->crep.backup_size = srf->res.backup_size;
rep->crep.buffer_handle = backup_handle;
rep->crep.buffer_map_handle =
drm_vma_node_offset_addr(&srf->res.backup->base.vma_node);
rep->crep.buffer_size = srf->res.backup->base.num_pages * PAGE_SIZE;
out_bad_resource:
ttm_base_object_unref(&base);
return ret;
}
/**
* vmw_surface_gb_priv_define - Define a private GB surface
*
* @dev: Pointer to a struct drm_device
* @user_accounting_size: Used to track user-space memory usage, set
* to 0 for kernel mode only memory
* @svga3d_flags: SVGA3d surface flags for the device
* @format: requested surface format
* @for_scanout: true if inteded to be used for scanout buffer
* @num_mip_levels: number of MIP levels
* @multisample_count:
* @array_size: Surface array size.
* @size: width, heigh, depth of the surface requested
* @user_srf_out: allocated user_srf. Set to NULL on failure.
*
* GB surfaces allocated by this function will not have a user mode handle, and
* thus will only be visible to vmwgfx. For optimization reasons the
* surface may later be given a user mode handle by another function to make
* it available to user mode drivers.
*/
int vmw_surface_gb_priv_define(struct drm_device *dev,
uint32_t user_accounting_size,
uint32_t svga3d_flags,
SVGA3dSurfaceFormat format,
bool for_scanout,
uint32_t num_mip_levels,
uint32_t multisample_count,
uint32_t array_size,
struct drm_vmw_size size,
struct vmw_surface **srf_out)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
int ret;
u32 num_layers;
*srf_out = NULL;
if (for_scanout) {
uint32_t max_width, max_height;
if (!svga3dsurface_is_screen_target_format(format)) {
DRM_ERROR("Invalid Screen Target surface format.");
return -EINVAL;
}
max_width = min(dev_priv->texture_max_width,
dev_priv->stdu_max_width);
max_height = min(dev_priv->texture_max_height,
dev_priv->stdu_max_height);
if (size.width > max_width || size.height > max_height) {
DRM_ERROR("%ux%u\n, exeeds max surface size %ux%u",
size.width, size.height,
max_width, max_height);
return -EINVAL;
}
} else {
const struct svga3d_surface_desc *desc;
desc = svga3dsurface_get_desc(format);
if (unlikely(desc->block_desc == SVGA3DBLOCKDESC_NONE)) {
DRM_ERROR("Invalid surface format.\n");
return -EINVAL;
}
}
/* array_size must be null for non-GL3 host. */
if (array_size > 0 && !dev_priv->has_dx) {
DRM_ERROR("Tried to create DX surface on non-DX host.\n");
return -EINVAL;
}
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
ret = ttm_mem_global_alloc(vmw_mem_glob(dev_priv),
user_accounting_size, false, true);
if (unlikely(ret != 0)) {
if (ret != -ERESTARTSYS)
DRM_ERROR("Out of graphics memory for surface"
" creation.\n");
goto out_unlock;
}
user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL);
if (unlikely(!user_srf)) {
ret = -ENOMEM;
goto out_no_user_srf;
}
*srf_out = &user_srf->srf;
user_srf->size = user_accounting_size;
user_srf->prime.base.shareable = false;
user_srf->prime.base.tfile = NULL;
srf = &user_srf->srf;
srf->flags = svga3d_flags;
srf->format = format;
srf->scanout = for_scanout;
srf->mip_levels[0] = num_mip_levels;
srf->num_sizes = 1;
srf->sizes = NULL;
srf->offsets = NULL;
srf->base_size = size;
srf->autogen_filter = SVGA3D_TEX_FILTER_NONE;
srf->array_size = array_size;
srf->multisample_count = multisample_count;
if (array_size)
num_layers = array_size;
else if (svga3d_flags & SVGA3D_SURFACE_CUBEMAP)
num_layers = SVGA3D_MAX_SURFACE_FACES;
else
num_layers = 1;
srf->res.backup_size =
svga3dsurface_get_serialized_size(srf->format,
srf->base_size,
srf->mip_levels[0],
num_layers);
if (srf->flags & SVGA3D_SURFACE_BIND_STREAM_OUTPUT)
srf->res.backup_size += sizeof(SVGA3dDXSOState);
if (dev_priv->active_display_unit == vmw_du_screen_target &&
for_scanout)
srf->flags |= SVGA3D_SURFACE_SCREENTARGET;
/*
* From this point, the generic resource management functions
* destroy the object on failure.
*/
ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free);
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
out_no_user_srf:
ttm_mem_global_free(vmw_mem_glob(dev_priv), user_accounting_size);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3401_0 |
crossvul-cpp_data_bad_2958_1 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* fileio.c: read from and write to a file
*/
#include "vim.h"
#if defined(__TANDEM) || defined(__MINT__)
# include <limits.h> /* for SSIZE_MAX */
#endif
#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
# include <utime.h> /* for struct utimbuf */
#endif
#define BUFSIZE 8192 /* size of normal write buffer */
#define SMBUFSIZE 256 /* size of emergency write buffer */
/* Is there any system that doesn't have access()? */
#define USE_MCH_ACCESS
#ifdef FEAT_MBYTE
static char_u *next_fenc(char_u **pp);
# ifdef FEAT_EVAL
static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
# endif
#endif
#ifdef FEAT_VIMINFO
static void check_marks_read(void);
#endif
#ifdef FEAT_CRYPT
static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
#endif
#ifdef UNIX
static void set_file_time(char_u *fname, time_t atime, time_t mtime);
#endif
static int set_rw_fname(char_u *fname, char_u *sfname);
static int msg_add_fileformat(int eol_type);
static void msg_add_eol(void);
static int check_mtime(buf_T *buf, stat_T *s);
static int time_differs(long t1, long t2);
#ifdef FEAT_AUTOCMD
static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
static int au_find_group(char_u *name);
# define AUGROUP_DEFAULT -1 /* default autocmd group */
# define AUGROUP_ERROR -2 /* erroneous autocmd group */
# define AUGROUP_ALL -3 /* all autocmd groups */
#endif
#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
# define HAS_BW_FLAGS
# define FIO_LATIN1 0x01 /* convert Latin1 */
# define FIO_UTF8 0x02 /* convert UTF-8 */
# define FIO_UCS2 0x04 /* convert UCS-2 */
# define FIO_UCS4 0x08 /* convert UCS-4 */
# define FIO_UTF16 0x10 /* convert UTF-16 */
# ifdef WIN3264
# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
# endif
# ifdef MACOS_CONVERT
# define FIO_MACROMAN 0x20 /* convert MacRoman */
# endif
# define FIO_ENDIAN_L 0x80 /* little endian */
# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
# define FIO_ALL -1 /* allow all formats */
#endif
/* When converting, a read() or write() may leave some bytes to be converted
* for the next call. The value is guessed... */
#define CONV_RESTLEN 30
/* We have to guess how much a sequence of bytes may expand when converting
* with iconv() to be able to allocate a buffer. */
#define ICONV_MULT 8
/*
* Structure to pass arguments from buf_write() to buf_write_bytes().
*/
struct bw_info
{
int bw_fd; /* file descriptor */
char_u *bw_buf; /* buffer with data to be written */
int bw_len; /* length of data */
#ifdef HAS_BW_FLAGS
int bw_flags; /* FIO_ flags */
#endif
#ifdef FEAT_CRYPT
buf_T *bw_buffer; /* buffer being written */
#endif
#ifdef FEAT_MBYTE
char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
int bw_restlen; /* nr of bytes in bw_rest[] */
int bw_first; /* first write call */
char_u *bw_conv_buf; /* buffer for writing converted chars */
int bw_conv_buflen; /* size of bw_conv_buf */
int bw_conv_error; /* set for conversion error */
linenr_T bw_conv_error_lnum; /* first line with error or zero */
linenr_T bw_start_lnum; /* line number at start of buffer */
# ifdef USE_ICONV
iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
# endif
#endif
};
static int buf_write_bytes(struct bw_info *ip);
#ifdef FEAT_MBYTE
static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
static int ucs2bytes(unsigned c, char_u **pp, int flags);
static int need_conversion(char_u *fenc);
static int get_fio_flags(char_u *ptr);
static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
static int make_bom(char_u *buf, char_u *name);
# ifdef WIN3264
static int get_win_fio_flags(char_u *ptr);
# endif
# ifdef MACOS_CONVERT
static int get_mac_fio_flags(char_u *ptr);
# endif
#endif
static int move_lines(buf_T *frombuf, buf_T *tobuf);
#ifdef TEMPDIRNAMES
static void vim_settempdir(char_u *tempdir);
#endif
#ifdef FEAT_AUTOCMD
static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
#endif
#ifdef FEAT_AUTOCMD
/*
* Set by the apply_autocmds_group function if the given event is equal to
* EVENT_FILETYPE. Used by the readfile function in order to determine if
* EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
*
* Relying on this value requires one to reset it prior calling
* apply_autocmds_group.
*/
static int au_did_filetype INIT(= FALSE);
#endif
void
filemess(
buf_T *buf,
char_u *name,
char_u *s,
int attr)
{
int msg_scroll_save;
if (msg_silent != 0)
return;
msg_add_fname(buf, name); /* put file name in IObuff with quotes */
/* If it's extremely long, truncate it. */
if (STRLEN(IObuff) > IOSIZE - 80)
IObuff[IOSIZE - 80] = NUL;
STRCAT(IObuff, s);
/*
* For the first message may have to start a new line.
* For further ones overwrite the previous one, reset msg_scroll before
* calling filemess().
*/
msg_scroll_save = msg_scroll;
if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
msg_scroll = FALSE;
if (!msg_scroll) /* wait a bit when overwriting an error msg */
check_for_delay(FALSE);
msg_start();
msg_scroll = msg_scroll_save;
msg_scrolled_ign = TRUE;
/* may truncate the message to avoid a hit-return prompt */
msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
msg_clr_eos();
out_flush();
msg_scrolled_ign = FALSE;
}
/*
* Read lines from file "fname" into the buffer after line "from".
*
* 1. We allocate blocks with lalloc, as big as possible.
* 2. Each block is filled with characters from the file with a single read().
* 3. The lines are inserted in the buffer with ml_append().
*
* (caller must check that fname != NULL, unless READ_STDIN is used)
*
* "lines_to_skip" is the number of lines that must be skipped
* "lines_to_read" is the number of lines that are appended
* When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
*
* flags:
* READ_NEW starting to edit a new buffer
* READ_FILTER reading filter output
* READ_STDIN read from stdin instead of a file
* READ_BUFFER read from curbuf instead of a file (converting after reading
* stdin)
* READ_DUMMY read into a dummy buffer (to check if file contents changed)
* READ_KEEP_UNDO don't clear undo info or read it from a file
* READ_FIFO read from fifo/socket instead of a file
*
* return FAIL for failure, NOTDONE for directory (failure), or OK
*/
int
readfile(
char_u *fname,
char_u *sfname,
linenr_T from,
linenr_T lines_to_skip,
linenr_T lines_to_read,
exarg_T *eap, /* can be NULL! */
int flags)
{
int fd = 0;
int newfile = (flags & READ_NEW);
int check_readonly;
int filtering = (flags & READ_FILTER);
int read_stdin = (flags & READ_STDIN);
int read_buffer = (flags & READ_BUFFER);
int read_fifo = (flags & READ_FIFO);
int set_options = newfile || read_buffer
|| (eap != NULL && eap->read_edit);
linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
colnr_T read_buf_col = 0; /* next char to read from this line */
char_u c;
linenr_T lnum = from;
char_u *ptr = NULL; /* pointer into read buffer */
char_u *buffer = NULL; /* read buffer */
char_u *new_buffer = NULL; /* init to shut up gcc */
char_u *line_start = NULL; /* init to shut up gcc */
int wasempty; /* buffer was empty before reading */
colnr_T len;
long size = 0;
char_u *p;
off_T filesize = 0;
int skip_read = FALSE;
#ifdef FEAT_CRYPT
char_u *cryptkey = NULL;
int did_ask_for_key = FALSE;
#endif
#ifdef FEAT_PERSISTENT_UNDO
context_sha256_T sha_ctx;
int read_undo_file = FALSE;
#endif
int split = 0; /* number of split lines */
#define UNKNOWN 0x0fffffff /* file size is unknown */
linenr_T linecnt;
int error = FALSE; /* errors encountered */
int ff_error = EOL_UNKNOWN; /* file format with errors */
long linerest = 0; /* remaining chars in line */
#ifdef UNIX
int perm = 0;
int swap_mode = -1; /* protection bits for swap file */
#else
int perm;
#endif
int fileformat = 0; /* end-of-line format */
int keep_fileformat = FALSE;
stat_T st;
int file_readonly;
linenr_T skip_count = 0;
linenr_T read_count = 0;
int msg_save = msg_scroll;
linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
* last read was missing the eol */
int try_mac;
int try_dos;
int try_unix;
int file_rewind = FALSE;
#ifdef FEAT_MBYTE
int can_retry;
linenr_T conv_error = 0; /* line nr with conversion error */
linenr_T illegal_byte = 0; /* line nr with illegal byte */
int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
in destination encoding */
int bad_char_behavior = BAD_REPLACE;
/* BAD_KEEP, BAD_DROP or character to
* replace with */
char_u *tmpname = NULL; /* name of 'charconvert' output file */
int fio_flags = 0;
char_u *fenc; /* fileencoding to use */
int fenc_alloced; /* fenc_next is in allocated memory */
char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
int advance_fenc = FALSE;
long real_size = 0;
# ifdef USE_ICONV
iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
# ifdef FEAT_EVAL
int did_iconv = FALSE; /* TRUE when iconv() failed and trying
'charconvert' next */
# endif
# endif
int converted = FALSE; /* TRUE if conversion done */
int notconverted = FALSE; /* TRUE if conversion wanted but it
wasn't possible */
char_u conv_rest[CONV_RESTLEN];
int conv_restlen = 0; /* nr of bytes in conv_rest[] */
#endif
#ifdef FEAT_AUTOCMD
buf_T *old_curbuf;
char_u *old_b_ffname;
char_u *old_b_fname;
int using_b_ffname;
int using_b_fname;
#endif
#ifdef FEAT_AUTOCMD
au_did_filetype = FALSE; /* reset before triggering any autocommands */
#endif
curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
/*
* If there is no file name yet, use the one for the read file.
* BF_NOTEDITED is set to reflect this.
* Don't do this for a read from a filter.
* Only do this when 'cpoptions' contains the 'f' flag.
*/
if (curbuf->b_ffname == NULL
&& !filtering
&& fname != NULL
&& vim_strchr(p_cpo, CPO_FNAMER) != NULL
&& !(flags & READ_DUMMY))
{
if (set_rw_fname(fname, sfname) == FAIL)
return FAIL;
}
#ifdef FEAT_AUTOCMD
/* Remember the initial values of curbuf, curbuf->b_ffname and
* curbuf->b_fname to detect whether they are altered as a result of
* executing nasty autocommands. Also check if "fname" and "sfname"
* point to one of these values. */
old_curbuf = curbuf;
old_b_ffname = curbuf->b_ffname;
old_b_fname = curbuf->b_fname;
using_b_ffname = (fname == curbuf->b_ffname)
|| (sfname == curbuf->b_ffname);
using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
#endif
/* After reading a file the cursor line changes but we don't want to
* display the line. */
ex_no_reprint = TRUE;
/* don't display the file info for another buffer now */
need_fileinfo = FALSE;
/*
* For Unix: Use the short file name whenever possible.
* Avoids problems with networks and when directory names are changed.
* Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
* another directory, which we don't detect.
*/
if (sfname == NULL)
sfname = fname;
#if defined(UNIX)
fname = sfname;
#endif
#ifdef FEAT_AUTOCMD
/*
* The BufReadCmd and FileReadCmd events intercept the reading process by
* executing the associated commands instead.
*/
if (!filtering && !read_stdin && !read_buffer)
{
pos_T pos;
pos = curbuf->b_op_start;
/* Set '[ mark to the line above where the lines go (line 1 if zero). */
curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
curbuf->b_op_start.col = 0;
if (newfile)
{
if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
FALSE, curbuf, eap))
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
}
else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
FALSE, NULL, eap))
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
curbuf->b_op_start = pos;
}
#endif
if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
msg_scroll = FALSE; /* overwrite previous file message */
else
msg_scroll = TRUE; /* don't overwrite previous file message */
/*
* If the name ends in a path separator, we can't open it. Check here,
* because reading the file may actually work, but then creating the swap
* file may destroy it! Reported on MS-DOS and Win 95.
* If the name is too long we might crash further on, quit here.
*/
if (fname != NULL && *fname != NUL)
{
p = fname + STRLEN(fname);
if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
{
filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
msg_end();
msg_scroll = msg_save;
return FAIL;
}
}
if (!read_stdin && !read_buffer && !read_fifo)
{
#ifdef UNIX
/*
* On Unix it is possible to read a directory, so we have to
* check for it before the mch_open().
*/
perm = mch_getperm(fname);
if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
# ifdef S_ISFIFO
&& !S_ISFIFO(perm) /* ... or fifo */
# endif
# ifdef S_ISSOCK
&& !S_ISSOCK(perm) /* ... or socket */
# endif
# ifdef OPEN_CHR_FILES
&& !(S_ISCHR(perm) && is_dev_fd_file(fname))
/* ... or a character special file named /dev/fd/<n> */
# endif
)
{
int retval = FAIL;
if (S_ISDIR(perm))
{
filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
retval = NOTDONE;
}
else
filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
msg_end();
msg_scroll = msg_save;
return retval;
}
#endif
#if defined(MSWIN)
/*
* MS-Windows allows opening a device, but we will probably get stuck
* trying to read it.
*/
if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
{
filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
msg_end();
msg_scroll = msg_save;
return FAIL;
}
#endif
}
/* Set default or forced 'fileformat' and 'binary'. */
set_file_options(set_options, eap);
/*
* When opening a new file we take the readonly flag from the file.
* Default is r/w, can be set to r/o below.
* Don't reset it when in readonly mode
* Only set/reset b_p_ro when BF_CHECK_RO is set.
*/
check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
if (check_readonly && !readonlymode)
curbuf->b_p_ro = FALSE;
if (newfile && !read_stdin && !read_buffer && !read_fifo)
{
/* Remember time of file. */
if (mch_stat((char *)fname, &st) >= 0)
{
buf_store_time(curbuf, &st, fname);
curbuf->b_mtime_read = curbuf->b_mtime;
#ifdef UNIX
/*
* Use the protection bits of the original file for the swap file.
* This makes it possible for others to read the name of the
* edited file from the swapfile, but only if they can read the
* edited file.
* Remove the "write" and "execute" bits for group and others
* (they must not write the swapfile).
* Add the "read" and "write" bits for the user, otherwise we may
* not be able to write to the file ourselves.
* Setting the bits is done below, after creating the swap file.
*/
swap_mode = (st.st_mode & 0644) | 0600;
#endif
#ifdef FEAT_CW_EDITOR
/* Get the FSSpec on MacOS
* TODO: Update it properly when the buffer name changes
*/
(void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
#endif
#ifdef VMS
curbuf->b_fab_rfm = st.st_fab_rfm;
curbuf->b_fab_rat = st.st_fab_rat;
curbuf->b_fab_mrs = st.st_fab_mrs;
#endif
}
else
{
curbuf->b_mtime = 0;
curbuf->b_mtime_read = 0;
curbuf->b_orig_size = 0;
curbuf->b_orig_mode = 0;
}
/* Reset the "new file" flag. It will be set again below when the
* file doesn't exist. */
curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
}
/*
* for UNIX: check readonly with perm and mch_access()
* for Amiga: check readonly by trying to open the file for writing
*/
file_readonly = FALSE;
if (read_stdin)
{
#if defined(MSWIN)
/* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
setmode(0, O_BINARY);
#endif
}
else if (!read_buffer)
{
#ifdef USE_MCH_ACCESS
if (
# ifdef UNIX
!(perm & 0222) ||
# endif
mch_access((char *)fname, W_OK))
file_readonly = TRUE;
fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
#else
if (!newfile
|| readonlymode
|| (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
{
file_readonly = TRUE;
/* try to open ro */
fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
}
#endif
}
if (fd < 0) /* cannot open at all */
{
#ifndef UNIX
int isdir_f;
#endif
msg_scroll = msg_save;
#ifndef UNIX
/*
* On Amiga we can't open a directory, check here.
*/
isdir_f = (mch_isdir(fname));
perm = mch_getperm(fname); /* check if the file exists */
if (isdir_f)
{
filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
else
#endif
if (newfile)
{
if (perm < 0
#ifdef ENOENT
&& errno == ENOENT
#endif
)
{
/*
* Set the 'new-file' flag, so that when the file has
* been created by someone else, a ":w" will complain.
*/
curbuf->b_flags |= BF_NEW;
/* Create a swap file now, so that other Vims are warned
* that we are editing this file. Don't do this for a
* "nofile" or "nowrite" buffer type. */
#ifdef FEAT_QUICKFIX
if (!bt_dontwrite(curbuf))
#endif
{
check_need_swap(newfile);
#ifdef FEAT_AUTOCMD
/* SwapExists autocommand may mess things up */
if (curbuf != old_curbuf
|| (using_b_ffname
&& (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname
&& (old_b_fname != curbuf->b_fname)))
{
EMSG(_(e_auchangedbuf));
return FAIL;
}
#endif
}
if (dir_of_file_exists(fname))
filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
else
filemess(curbuf, sfname,
(char_u *)_("[New DIRECTORY]"), 0);
#ifdef FEAT_VIMINFO
/* Even though this is a new file, it might have been
* edited before and deleted. Get the old marks. */
check_marks_read();
#endif
#ifdef FEAT_MBYTE
/* Set forced 'fileencoding'. */
if (eap != NULL)
set_forced_fenc(eap);
#endif
#ifdef FEAT_AUTOCMD
apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
FALSE, curbuf, eap);
#endif
/* remember the current fileformat */
save_file_ff(curbuf);
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (aborting()) /* autocmds may abort script processing */
return FAIL;
#endif
return OK; /* a new file is not an error */
}
else
{
filemess(curbuf, sfname, (char_u *)(
# ifdef EFBIG
(errno == EFBIG) ? _("[File too big]") :
# endif
# ifdef EOVERFLOW
(errno == EOVERFLOW) ? _("[File too big]") :
# endif
_("[Permission Denied]")), 0);
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
}
return FAIL;
}
/*
* Only set the 'ro' flag for readonly files the first time they are
* loaded. Help files always get readonly mode
*/
if ((check_readonly && file_readonly) || curbuf->b_help)
curbuf->b_p_ro = TRUE;
if (set_options)
{
/* Don't change 'eol' if reading from buffer as it will already be
* correctly set when reading stdin. */
if (!read_buffer)
{
curbuf->b_p_eol = TRUE;
curbuf->b_start_eol = TRUE;
}
#ifdef FEAT_MBYTE
curbuf->b_p_bomb = FALSE;
curbuf->b_start_bomb = FALSE;
#endif
}
/* Create a swap file now, so that other Vims are warned that we are
* editing this file.
* Don't do this for a "nofile" or "nowrite" buffer type. */
#ifdef FEAT_QUICKFIX
if (!bt_dontwrite(curbuf))
#endif
{
check_need_swap(newfile);
#ifdef FEAT_AUTOCMD
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))))
{
EMSG(_(e_auchangedbuf));
if (!read_buffer)
close(fd);
return FAIL;
}
#endif
#ifdef UNIX
/* Set swap file protection bits after creating it. */
if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
&& curbuf->b_ml.ml_mfp->mf_fname != NULL)
(void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
#endif
}
#if defined(HAS_SWAP_EXISTS_ACTION)
/* If "Quit" selected at ATTENTION dialog, don't load the file */
if (swap_exists_action == SEA_QUIT)
{
if (!read_buffer && !read_stdin)
close(fd);
return FAIL;
}
#endif
++no_wait_return; /* don't wait for return yet */
/*
* Set '[ mark to the line above where the lines go (line 1 if zero).
*/
curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
curbuf->b_op_start.col = 0;
try_mac = (vim_strchr(p_ffs, 'm') != NULL);
try_dos = (vim_strchr(p_ffs, 'd') != NULL);
try_unix = (vim_strchr(p_ffs, 'x') != NULL);
#ifdef FEAT_AUTOCMD
if (!read_buffer)
{
int m = msg_scroll;
int n = msg_scrolled;
/*
* The file must be closed again, the autocommands may want to change
* the file before reading it.
*/
if (!read_stdin)
close(fd); /* ignore errors */
/*
* The output from the autocommands should not overwrite anything and
* should not be overwritten: Set msg_scroll, restore its value if no
* output was done.
*/
msg_scroll = TRUE;
if (filtering)
apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else if (read_stdin)
apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else if (newfile)
apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else
apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
FALSE, NULL, eap);
/* autocommands may have changed it */
try_mac = (vim_strchr(p_ffs, 'm') != NULL);
try_dos = (vim_strchr(p_ffs, 'd') != NULL);
try_unix = (vim_strchr(p_ffs, 'x') != NULL);
if (msg_scrolled == n)
msg_scroll = m;
#ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
{
--no_wait_return;
msg_scroll = msg_save;
curbuf->b_p_ro = TRUE; /* must use "w!" now */
return FAIL;
}
#endif
/*
* Don't allow the autocommands to change the current buffer.
* Try to re-open the file.
*
* Don't allow the autocommands to change the buffer name either
* (cd for example) if it invalidates fname or sfname.
*/
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))
|| (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
{
--no_wait_return;
msg_scroll = msg_save;
if (fd < 0)
EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
else
EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
curbuf->b_p_ro = TRUE; /* must use "w!" now */
return FAIL;
}
}
#endif /* FEAT_AUTOCMD */
/* Autocommands may add lines to the file, need to check if it is empty */
wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
if (!recoverymode && !filtering && !(flags & READ_DUMMY))
{
/*
* Show the user that we are busy reading the input. Sometimes this
* may take a while. When reading from stdin another program may
* still be running, don't move the cursor to the last line, unless
* always using the GUI.
*/
if (read_stdin)
{
#ifndef ALWAYS_USE_GUI
mch_msg(_("Vim: Reading from stdin...\n"));
#endif
#ifdef FEAT_GUI
/* Also write a message in the GUI window, if there is one. */
if (gui.in_use && !gui.dying && !gui.starting)
{
p = (char_u *)_("Reading from stdin...");
gui_write(p, (int)STRLEN(p));
}
#endif
}
else if (!read_buffer)
filemess(curbuf, sfname, (char_u *)"", 0);
}
msg_scroll = FALSE; /* overwrite the file message */
/*
* Set linecnt now, before the "retry" caused by a wrong guess for
* fileformat, and after the autocommands, which may change them.
*/
linecnt = curbuf->b_ml.ml_line_count;
#ifdef FEAT_MBYTE
/* "++bad=" argument. */
if (eap != NULL && eap->bad_char != 0)
{
bad_char_behavior = eap->bad_char;
if (set_options)
curbuf->b_bad_char = eap->bad_char;
}
else
curbuf->b_bad_char = 0;
/*
* Decide which 'encoding' to use or use first.
*/
if (eap != NULL && eap->force_enc != 0)
{
fenc = enc_canonize(eap->cmd + eap->force_enc);
fenc_alloced = TRUE;
keep_dest_enc = TRUE;
}
else if (curbuf->b_p_bin)
{
fenc = (char_u *)""; /* binary: don't convert */
fenc_alloced = FALSE;
}
else if (curbuf->b_help)
{
char_u firstline[80];
int fc;
/* Help files are either utf-8 or latin1. Try utf-8 first, if this
* fails it must be latin1.
* Always do this when 'encoding' is "utf-8". Otherwise only do
* this when needed to avoid [converted] remarks all the time.
* It is needed when the first line contains non-ASCII characters.
* That is only in *.??x files. */
fenc = (char_u *)"latin1";
c = enc_utf8;
if (!c && !read_stdin)
{
fc = fname[STRLEN(fname) - 1];
if (TOLOWER_ASC(fc) == 'x')
{
/* Read the first line (and a bit more). Immediately rewind to
* the start of the file. If the read() fails "len" is -1. */
len = read_eintr(fd, firstline, 80);
vim_lseek(fd, (off_T)0L, SEEK_SET);
for (p = firstline; p < firstline + len; ++p)
if (*p >= 0x80)
{
c = TRUE;
break;
}
}
}
if (c)
{
fenc_next = fenc;
fenc = (char_u *)"utf-8";
/* When the file is utf-8 but a character doesn't fit in
* 'encoding' don't retry. In help text editing utf-8 bytes
* doesn't make sense. */
if (!enc_utf8)
keep_dest_enc = TRUE;
}
fenc_alloced = FALSE;
}
else if (*p_fencs == NUL)
{
fenc = curbuf->b_p_fenc; /* use format from buffer */
fenc_alloced = FALSE;
}
else
{
fenc_next = p_fencs; /* try items in 'fileencodings' */
fenc = next_fenc(&fenc_next);
fenc_alloced = TRUE;
}
#endif
/*
* Jump back here to retry reading the file in different ways.
* Reasons to retry:
* - encoding conversion failed: try another one from "fenc_next"
* - BOM detected and fenc was set, need to setup conversion
* - "fileformat" check failed: try another
*
* Variables set for special retry actions:
* "file_rewind" Rewind the file to start reading it again.
* "advance_fenc" Advance "fenc" using "fenc_next".
* "skip_read" Re-use already read bytes (BOM detected).
* "did_iconv" iconv() conversion failed, try 'charconvert'.
* "keep_fileformat" Don't reset "fileformat".
*
* Other status indicators:
* "tmpname" When != NULL did conversion with 'charconvert'.
* Output file has to be deleted afterwards.
* "iconv_fd" When != -1 did conversion with iconv().
*/
retry:
if (file_rewind)
{
if (read_buffer)
{
read_buf_lnum = 1;
read_buf_col = 0;
}
else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
{
/* Can't rewind the file, give up. */
error = TRUE;
goto failed;
}
/* Delete the previously read lines. */
while (lnum > from)
ml_delete(lnum--, FALSE);
file_rewind = FALSE;
#ifdef FEAT_MBYTE
if (set_options)
{
curbuf->b_p_bomb = FALSE;
curbuf->b_start_bomb = FALSE;
}
conv_error = 0;
#endif
}
/*
* When retrying with another "fenc" and the first time "fileformat"
* will be reset.
*/
if (keep_fileformat)
keep_fileformat = FALSE;
else
{
if (eap != NULL && eap->force_ff != 0)
{
fileformat = get_fileformat_force(curbuf, eap);
try_unix = try_dos = try_mac = FALSE;
}
else if (curbuf->b_p_bin)
fileformat = EOL_UNIX; /* binary: use Unix format */
else if (*p_ffs == NUL)
fileformat = get_fileformat(curbuf);/* use format from buffer */
else
fileformat = EOL_UNKNOWN; /* detect from file */
}
#ifdef FEAT_MBYTE
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
/* aborted conversion with iconv(), close the descriptor */
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
if (advance_fenc)
{
/*
* Try the next entry in 'fileencodings'.
*/
advance_fenc = FALSE;
if (eap != NULL && eap->force_enc != 0)
{
/* Conversion given with "++cc=" wasn't possible, read
* without conversion. */
notconverted = TRUE;
conv_error = 0;
if (fenc_alloced)
vim_free(fenc);
fenc = (char_u *)"";
fenc_alloced = FALSE;
}
else
{
if (fenc_alloced)
vim_free(fenc);
if (fenc_next != NULL)
{
fenc = next_fenc(&fenc_next);
fenc_alloced = (fenc_next != NULL);
}
else
{
fenc = (char_u *)"";
fenc_alloced = FALSE;
}
}
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
tmpname = NULL;
}
}
/*
* Conversion may be required when the encoding of the file is different
* from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
*/
fio_flags = 0;
converted = need_conversion(fenc);
if (converted)
{
/* "ucs-bom" means we need to check the first bytes of the file
* for a BOM. */
if (STRCMP(fenc, ENC_UCSBOM) == 0)
fio_flags = FIO_UCSBOM;
/*
* Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
* done. This is handled below after read(). Prepare the
* fio_flags to avoid having to parse the string each time.
* Also check for Unicode to Latin1 conversion, because iconv()
* appears not to handle this correctly. This works just like
* conversion to UTF-8 except how the resulting character is put in
* the buffer.
*/
else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
fio_flags = get_fio_flags(fenc);
# ifdef WIN3264
/*
* Conversion from an MS-Windows codepage to UTF-8 or another codepage
* is handled with MultiByteToWideChar().
*/
if (fio_flags == 0)
fio_flags = get_win_fio_flags(fenc);
# endif
# ifdef MACOS_CONVERT
/* Conversion from Apple MacRoman to latin1 or UTF-8 */
if (fio_flags == 0)
fio_flags = get_mac_fio_flags(fenc);
# endif
# ifdef USE_ICONV
/*
* Try using iconv() if we can't convert internally.
*/
if (fio_flags == 0
# ifdef FEAT_EVAL
&& !did_iconv
# endif
)
iconv_fd = (iconv_t)my_iconv_open(
enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
# endif
# ifdef FEAT_EVAL
/*
* Use the 'charconvert' expression when conversion is required
* and we can't do it internally or with iconv().
*/
if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
&& !read_fifo
# ifdef USE_ICONV
&& iconv_fd == (iconv_t)-1
# endif
)
{
# ifdef USE_ICONV
did_iconv = FALSE;
# endif
/* Skip conversion when it's already done (retry for wrong
* "fileformat"). */
if (tmpname == NULL)
{
tmpname = readfile_charconvert(fname, fenc, &fd);
if (tmpname == NULL)
{
/* Conversion failed. Try another one. */
advance_fenc = TRUE;
if (fd < 0)
{
/* Re-opening the original file failed! */
EMSG(_("E202: Conversion made file unreadable!"));
error = TRUE;
goto failed;
}
goto retry;
}
}
}
else
# endif
{
if (fio_flags == 0
# ifdef USE_ICONV
&& iconv_fd == (iconv_t)-1
# endif
)
{
/* Conversion wanted but we can't.
* Try the next conversion in 'fileencodings' */
advance_fenc = TRUE;
goto retry;
}
}
}
/* Set "can_retry" when it's possible to rewind the file and try with
* another "fenc" value. It's FALSE when no other "fenc" to try, reading
* stdin or fixed at a specific encoding. */
can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
#endif
if (!skip_read)
{
linerest = 0;
filesize = 0;
skip_count = lines_to_skip;
read_count = lines_to_read;
#ifdef FEAT_MBYTE
conv_restlen = 0;
#endif
#ifdef FEAT_PERSISTENT_UNDO
read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
&& curbuf->b_ffname != NULL
&& curbuf->b_p_udf
&& !filtering
&& !read_fifo
&& !read_stdin
&& !read_buffer);
if (read_undo_file)
sha256_start(&sha_ctx);
#endif
#ifdef FEAT_CRYPT
if (curbuf->b_cryptstate != NULL)
{
/* Need to free the state, but keep the key, don't want to ask for
* it again. */
crypt_free_state(curbuf->b_cryptstate);
curbuf->b_cryptstate = NULL;
}
#endif
}
while (!error && !got_int)
{
/*
* We allocate as much space for the file as we can get, plus
* space for the old line plus room for one terminating NUL.
* The amount is limited by the fact that read() only can read
* upto max_unsigned characters (and other things).
*/
#if VIM_SIZEOF_INT <= 2
if (linerest >= 0x7ff0)
{
++split;
*ptr = NL; /* split line by inserting a NL */
size = 1;
}
else
#endif
{
if (!skip_read)
{
#if VIM_SIZEOF_INT > 2
# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
size = SSIZE_MAX; /* use max I/O size, 52K */
# else
size = 0x10000L; /* use buffer >= 64K */
# endif
#else
size = 0x7ff0L - linerest; /* limit buffer to 32K */
#endif
for ( ; size >= 10; size = (long)((long_u)size >> 1))
{
if ((new_buffer = lalloc((long_u)(size + linerest + 1),
FALSE)) != NULL)
break;
}
if (new_buffer == NULL)
{
do_outofmem_msg((long_u)(size * 2 + linerest + 1));
error = TRUE;
break;
}
if (linerest) /* copy characters from the previous buffer */
mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
vim_free(buffer);
buffer = new_buffer;
ptr = buffer + linerest;
line_start = buffer;
#ifdef FEAT_MBYTE
/* May need room to translate into.
* For iconv() we don't really know the required space, use a
* factor ICONV_MULT.
* latin1 to utf-8: 1 byte becomes up to 2 bytes
* utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
* become up to 4 bytes, size must be multiple of 2
* ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
* multiple of 2
* ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
* multiple of 4 */
real_size = (int)size;
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
size = size / ICONV_MULT;
else
# endif
if (fio_flags & FIO_LATIN1)
size = size / 2;
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
size = (size * 2 / 3) & ~1;
else if (fio_flags & FIO_UCS4)
size = (size * 2 / 3) & ~3;
else if (fio_flags == FIO_UCSBOM)
size = size / ICONV_MULT; /* worst case */
# ifdef WIN3264
else if (fio_flags & FIO_CODEPAGE)
size = size / ICONV_MULT; /* also worst case */
# endif
# ifdef MACOS_CONVERT
else if (fio_flags & FIO_MACROMAN)
size = size / ICONV_MULT; /* also worst case */
# endif
#endif
#ifdef FEAT_MBYTE
if (conv_restlen > 0)
{
/* Insert unconverted bytes from previous line. */
mch_memmove(ptr, conv_rest, conv_restlen);
ptr += conv_restlen;
size -= conv_restlen;
}
#endif
if (read_buffer)
{
/*
* Read bytes from curbuf. Used for converting text read
* from stdin.
*/
if (read_buf_lnum > from)
size = 0;
else
{
int n, ni;
long tlen;
tlen = 0;
for (;;)
{
p = ml_get(read_buf_lnum) + read_buf_col;
n = (int)STRLEN(p);
if ((int)tlen + n + 1 > size)
{
/* Filled up to "size", append partial line.
* Change NL to NUL to reverse the effect done
* below. */
n = (int)(size - tlen);
for (ni = 0; ni < n; ++ni)
{
if (p[ni] == NL)
ptr[tlen++] = NUL;
else
ptr[tlen++] = p[ni];
}
read_buf_col += n;
break;
}
else
{
/* Append whole line and new-line. Change NL
* to NUL to reverse the effect done below. */
for (ni = 0; ni < n; ++ni)
{
if (p[ni] == NL)
ptr[tlen++] = NUL;
else
ptr[tlen++] = p[ni];
}
ptr[tlen++] = NL;
read_buf_col = 0;
if (++read_buf_lnum > from)
{
/* When the last line didn't have an
* end-of-line don't add it now either. */
if (!curbuf->b_p_eol)
--tlen;
size = tlen;
break;
}
}
}
}
}
else
{
/*
* Read bytes from the file.
*/
size = read_eintr(fd, ptr, size);
}
#ifdef FEAT_CRYPT
/*
* At start of file: Check for magic number of encryption.
*/
if (filesize == 0 && size > 0)
cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
&filesize, newfile, sfname,
&did_ask_for_key);
/*
* Decrypt the read bytes. This is done before checking for
* EOF because the crypt layer may be buffering.
*/
if (cryptkey != NULL && curbuf->b_cryptstate != NULL
&& size > 0)
{
if (crypt_works_inplace(curbuf->b_cryptstate))
{
crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
}
else
{
char_u *newptr = NULL;
int decrypted_size;
decrypted_size = crypt_decode_alloc(
curbuf->b_cryptstate, ptr, size, &newptr);
/* If the crypt layer is buffering, not producing
* anything yet, need to read more. */
if (size > 0 && decrypted_size == 0)
continue;
if (linerest == 0)
{
/* Simple case: reuse returned buffer (may be
* NULL, checked later). */
new_buffer = newptr;
}
else
{
long_u new_size;
/* Need new buffer to add bytes carried over. */
new_size = (long_u)(decrypted_size + linerest + 1);
new_buffer = lalloc(new_size, FALSE);
if (new_buffer == NULL)
{
do_outofmem_msg(new_size);
error = TRUE;
break;
}
mch_memmove(new_buffer, buffer, linerest);
if (newptr != NULL)
mch_memmove(new_buffer + linerest, newptr,
decrypted_size);
}
if (new_buffer != NULL)
{
vim_free(buffer);
buffer = new_buffer;
new_buffer = NULL;
line_start = buffer;
ptr = buffer + linerest;
}
size = decrypted_size;
}
}
#endif
if (size <= 0)
{
if (size < 0) /* read error */
error = TRUE;
#ifdef FEAT_MBYTE
else if (conv_restlen > 0)
{
/*
* Reached end-of-file but some trailing bytes could
* not be converted. Truncated file?
*/
/* When we did a conversion report an error. */
if (fio_flags != 0
# ifdef USE_ICONV
|| iconv_fd != (iconv_t)-1
# endif
)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = curbuf->b_ml.ml_line_count
- linecnt + 1;
}
/* Remember the first linenr with an illegal byte */
else if (illegal_byte == 0)
illegal_byte = curbuf->b_ml.ml_line_count
- linecnt + 1;
if (bad_char_behavior == BAD_DROP)
{
*(ptr - conv_restlen) = NUL;
conv_restlen = 0;
}
else
{
/* Replace the trailing bytes with the replacement
* character if we were converting; if we weren't,
* leave the UTF8 checking code to do it, as it
* works slightly differently. */
if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
# ifdef USE_ICONV
|| iconv_fd != (iconv_t)-1
# endif
))
{
while (conv_restlen > 0)
{
*(--ptr) = bad_char_behavior;
--conv_restlen;
}
}
fio_flags = 0; /* don't convert this */
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
}
}
#endif
}
}
skip_read = FALSE;
#ifdef FEAT_MBYTE
/*
* At start of file (or after crypt magic number): Check for BOM.
* Also check for a BOM for other Unicode encodings, but not after
* converting with 'charconvert' or when a BOM has already been
* found.
*/
if ((filesize == 0
# ifdef FEAT_CRYPT
|| (cryptkey != NULL
&& filesize == crypt_get_header_len(
crypt_get_method_nr(curbuf)))
# endif
)
&& (fio_flags == FIO_UCSBOM
|| (!curbuf->b_p_bomb
&& tmpname == NULL
&& (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
{
char_u *ccname;
int blen;
/* no BOM detection in a short file or in binary mode */
if (size < 2 || curbuf->b_p_bin)
ccname = NULL;
else
ccname = check_for_bom(ptr, size, &blen,
fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
if (ccname != NULL)
{
/* Remove BOM from the text */
filesize += blen;
size -= blen;
mch_memmove(ptr, ptr + blen, (size_t)size);
if (set_options)
{
curbuf->b_p_bomb = TRUE;
curbuf->b_start_bomb = TRUE;
}
}
if (fio_flags == FIO_UCSBOM)
{
if (ccname == NULL)
{
/* No BOM detected: retry with next encoding. */
advance_fenc = TRUE;
}
else
{
/* BOM detected: set "fenc" and jump back */
if (fenc_alloced)
vim_free(fenc);
fenc = ccname;
fenc_alloced = FALSE;
}
/* retry reading without getting new bytes or rewinding */
skip_read = TRUE;
goto retry;
}
}
/* Include not converted bytes. */
ptr -= conv_restlen;
size += conv_restlen;
conv_restlen = 0;
#endif
/*
* Break here for a read error or end-of-file.
*/
if (size <= 0)
break;
#ifdef FEAT_MBYTE
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
/*
* Attempt conversion of the read bytes to 'encoding' using
* iconv().
*/
const char *fromp;
char *top;
size_t from_size;
size_t to_size;
fromp = (char *)ptr;
from_size = size;
ptr += size;
top = (char *)ptr;
to_size = real_size - size;
/*
* If there is conversion error or not enough room try using
* another conversion. Except for when there is no
* alternative (help files).
*/
while ((iconv(iconv_fd, (void *)&fromp, &from_size,
&top, &to_size)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
|| from_size > CONV_RESTLEN)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, (char_u *)top);
/* Deal with a bad byte and continue with the next. */
++fromp;
--from_size;
if (bad_char_behavior == BAD_KEEP)
{
*top++ = *(fromp - 1);
--to_size;
}
else if (bad_char_behavior != BAD_DROP)
{
*top++ = bad_char_behavior;
--to_size;
}
}
if (from_size > 0)
{
/* Some remaining characters, keep them for the next
* round. */
mch_memmove(conv_rest, (char_u *)fromp, from_size);
conv_restlen = (int)from_size;
}
/* move the linerest to before the converted characters */
line_start = ptr - linerest;
mch_memmove(line_start, buffer, (size_t)linerest);
size = (long)((char_u *)top - ptr);
}
# endif
# ifdef WIN3264
if (fio_flags & FIO_CODEPAGE)
{
char_u *src, *dst;
WCHAR ucs2buf[3];
int ucs2len;
int codepage = FIO_GET_CP(fio_flags);
int bytelen;
int found_bad;
char replstr[2];
/*
* Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
* a codepage, using standard MS-Windows functions. This
* requires two steps:
* 1. convert from 'fileencoding' to ucs-2
* 2. convert from ucs-2 to 'encoding'
*
* Because there may be illegal bytes AND an incomplete byte
* sequence at the end, we may have to do the conversion one
* character at a time to get it right.
*/
/* Replacement string for WideCharToMultiByte(). */
if (bad_char_behavior > 0)
replstr[0] = bad_char_behavior;
else
replstr[0] = '?';
replstr[1] = NUL;
/*
* Move the bytes to the end of the buffer, so that we have
* room to put the result at the start.
*/
src = ptr + real_size - size;
mch_memmove(src, ptr, size);
/*
* Do the conversion.
*/
dst = ptr;
size = size;
while (size > 0)
{
found_bad = FALSE;
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (codepage == CP_UTF8)
{
/* Handle CP_UTF8 input ourselves to be able to handle
* trailing bytes properly.
* Get one UTF-8 character from src. */
bytelen = (int)utf_ptr2len_len(src, size);
if (bytelen > size)
{
/* Only got some bytes of a character. Normally
* it's put in "conv_rest", but if it's too long
* deal with it as if they were illegal bytes. */
if (bytelen <= CONV_RESTLEN)
break;
/* weird overlong byte sequence */
bytelen = size;
found_bad = TRUE;
}
else
{
int u8c = utf_ptr2char(src);
if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
found_bad = TRUE;
ucs2buf[0] = u8c;
ucs2len = 1;
}
}
else
# endif
{
/* We don't know how long the byte sequence is, try
* from one to three bytes. */
for (bytelen = 1; bytelen <= size && bytelen <= 3;
++bytelen)
{
ucs2len = MultiByteToWideChar(codepage,
MB_ERR_INVALID_CHARS,
(LPCSTR)src, bytelen,
ucs2buf, 3);
if (ucs2len > 0)
break;
}
if (ucs2len == 0)
{
/* If we have only one byte then it's probably an
* incomplete byte sequence. Otherwise discard
* one byte as a bad character. */
if (size == 1)
break;
found_bad = TRUE;
bytelen = 1;
}
}
if (!found_bad)
{
int i;
/* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
if (enc_utf8)
{
/* From UCS-2 to UTF-8. Cannot fail. */
for (i = 0; i < ucs2len; ++i)
dst += utf_char2bytes(ucs2buf[i], dst);
}
else
{
BOOL bad = FALSE;
int dstlen;
/* From UCS-2 to "enc_codepage". If the
* conversion uses the default character "?",
* the data doesn't fit in this encoding. */
dstlen = WideCharToMultiByte(enc_codepage, 0,
(LPCWSTR)ucs2buf, ucs2len,
(LPSTR)dst, (int)(src - dst),
replstr, &bad);
if (bad)
found_bad = TRUE;
else
dst += dstlen;
}
}
if (found_bad)
{
/* Deal with bytes we can't convert. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, dst);
if (bad_char_behavior != BAD_DROP)
{
if (bad_char_behavior == BAD_KEEP)
{
mch_memmove(dst, src, bytelen);
dst += bytelen;
}
else
*dst++ = bad_char_behavior;
}
}
src += bytelen;
size -= bytelen;
}
if (size > 0)
{
/* An incomplete byte sequence remaining. */
mch_memmove(conv_rest, src, size);
conv_restlen = size;
}
/* The new size is equal to how much "dst" was advanced. */
size = (long)(dst - ptr);
}
else
# endif
# ifdef MACOS_CONVERT
if (fio_flags & FIO_MACROMAN)
{
/*
* Conversion from Apple MacRoman char encoding to UTF-8 or
* latin1. This is in os_mac_conv.c.
*/
if (macroman2enc(ptr, &size, real_size) == FAIL)
goto rewind_retry;
}
else
# endif
if (fio_flags != 0)
{
int u8c;
char_u *dest;
char_u *tail = NULL;
/*
* "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
* "enc_utf8" not set: Convert Unicode to Latin1.
* Go from end to start through the buffer, because the number
* of bytes may increase.
* "dest" points to after where the UTF-8 bytes go, "p" points
* to after the next character to convert.
*/
dest = ptr + real_size;
if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
{
p = ptr + size;
if (fio_flags == FIO_UTF8)
{
/* Check for a trailing incomplete UTF-8 sequence */
tail = ptr + size - 1;
while (tail > ptr && (*tail & 0xc0) == 0x80)
--tail;
if (tail + utf_byte2len(*tail) <= ptr + size)
tail = NULL;
else
p = tail;
}
}
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
{
/* Check for a trailing byte */
p = ptr + (size & ~1);
if (size & 1)
tail = p;
if ((fio_flags & FIO_UTF16) && p > ptr)
{
/* Check for a trailing leading word */
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (*--p << 8);
u8c += *--p;
}
else
{
u8c = *--p;
u8c += (*--p << 8);
}
if (u8c >= 0xd800 && u8c <= 0xdbff)
tail = p;
else
p += 2;
}
}
else /* FIO_UCS4 */
{
/* Check for trailing 1, 2 or 3 bytes */
p = ptr + (size & ~3);
if (size & 3)
tail = p;
}
/* If there is a trailing incomplete sequence move it to
* conv_rest[]. */
if (tail != NULL)
{
conv_restlen = (int)((ptr + size) - tail);
mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
size -= conv_restlen;
}
while (p > ptr)
{
if (fio_flags & FIO_LATIN1)
u8c = *--p;
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
{
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (*--p << 8);
u8c += *--p;
}
else
{
u8c = *--p;
u8c += (*--p << 8);
}
if ((fio_flags & FIO_UTF16)
&& u8c >= 0xdc00 && u8c <= 0xdfff)
{
int u16c;
if (p == ptr)
{
/* Missing leading word. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
/* found second word of double-word, get the first
* word and compute the resulting character */
if (fio_flags & FIO_ENDIAN_L)
{
u16c = (*--p << 8);
u16c += *--p;
}
else
{
u16c = *--p;
u16c += (*--p << 8);
}
u8c = 0x10000 + ((u16c & 0x3ff) << 10)
+ (u8c & 0x3ff);
/* Check if the word is indeed a leading word. */
if (u16c < 0xd800 || u16c > 0xdbff)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
}
}
else if (fio_flags & FIO_UCS4)
{
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (unsigned)*--p << 24;
u8c += (unsigned)*--p << 16;
u8c += (unsigned)*--p << 8;
u8c += *--p;
}
else /* big endian */
{
u8c = *--p;
u8c += (unsigned)*--p << 8;
u8c += (unsigned)*--p << 16;
u8c += (unsigned)*--p << 24;
}
}
else /* UTF-8 */
{
if (*--p < 0x80)
u8c = *p;
else
{
len = utf_head_off(ptr, p);
p -= len;
u8c = utf_ptr2char(p);
if (len == 0)
{
/* Not a valid UTF-8 character, retry with
* another fenc when possible, otherwise just
* report the error. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
}
}
if (enc_utf8) /* produce UTF-8 */
{
dest -= utf_char2len(u8c);
(void)utf_char2bytes(u8c, dest);
}
else /* produce Latin1 */
{
--dest;
if (u8c >= 0x100)
{
/* character doesn't fit in latin1, retry with
* another fenc when possible, otherwise just
* report the error. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, p);
if (bad_char_behavior == BAD_DROP)
++dest;
else if (bad_char_behavior == BAD_KEEP)
*dest = u8c;
else if (eap != NULL && eap->bad_char != 0)
*dest = bad_char_behavior;
else
*dest = 0xBF;
}
else
*dest = u8c;
}
}
/* move the linerest to before the converted characters */
line_start = dest - linerest;
mch_memmove(line_start, buffer, (size_t)linerest);
size = (long)((ptr + real_size) - dest);
ptr = dest;
}
else if (enc_utf8 && !curbuf->b_p_bin)
{
int incomplete_tail = FALSE;
/* Reading UTF-8: Check if the bytes are valid UTF-8. */
for (p = ptr; ; ++p)
{
int todo = (int)((ptr + size) - p);
int l;
if (todo <= 0)
break;
if (*p >= 0x80)
{
/* A length of 1 means it's an illegal byte. Accept
* an incomplete character at the end though, the next
* read() will get the next bytes, we'll check it
* then. */
l = utf_ptr2len_len(p, todo);
if (l > todo && !incomplete_tail)
{
/* Avoid retrying with a different encoding when
* a truncated file is more likely, or attempting
* to read the rest of an incomplete sequence when
* we have already done so. */
if (p > ptr || filesize > 0)
incomplete_tail = TRUE;
/* Incomplete byte sequence, move it to conv_rest[]
* and try to read the rest of it, unless we've
* already done so. */
if (p > ptr)
{
conv_restlen = todo;
mch_memmove(conv_rest, p, conv_restlen);
size -= conv_restlen;
break;
}
}
if (l == 1 || l > todo)
{
/* Illegal byte. If we can try another encoding
* do that, unless at EOF where a truncated
* file is more likely than a conversion error. */
if (can_retry && !incomplete_tail)
break;
# ifdef USE_ICONV
/* When we did a conversion report an error. */
if (iconv_fd != (iconv_t)-1 && conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, p);
# endif
/* Remember the first linenr with an illegal byte */
if (conv_error == 0 && illegal_byte == 0)
illegal_byte = readfile_linenr(linecnt, ptr, p);
/* Drop, keep or replace the bad byte. */
if (bad_char_behavior == BAD_DROP)
{
mch_memmove(p, p + 1, todo - 1);
--p;
--size;
}
else if (bad_char_behavior != BAD_KEEP)
*p = bad_char_behavior;
}
else
p += l - 1;
}
}
if (p < ptr + size && !incomplete_tail)
{
/* Detected a UTF-8 error. */
rewind_retry:
/* Retry reading with another conversion. */
# if defined(FEAT_EVAL) && defined(USE_ICONV)
if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
/* iconv() failed, try 'charconvert' */
did_iconv = TRUE;
else
# endif
/* use next item from 'fileencodings' */
advance_fenc = TRUE;
file_rewind = TRUE;
goto retry;
}
}
#endif
/* count the number of characters (after conversion!) */
filesize += size;
/*
* when reading the first part of a file: guess EOL type
*/
if (fileformat == EOL_UNKNOWN)
{
/* First try finding a NL, for Dos and Unix */
if (try_dos || try_unix)
{
/* Reset the carriage return counter. */
if (try_mac)
try_mac = 1;
for (p = ptr; p < ptr + size; ++p)
{
if (*p == NL)
{
if (!try_unix
|| (try_dos && p > ptr && p[-1] == CAR))
fileformat = EOL_DOS;
else
fileformat = EOL_UNIX;
break;
}
else if (*p == CAR && try_mac)
try_mac++;
}
/* Don't give in to EOL_UNIX if EOL_MAC is more likely */
if (fileformat == EOL_UNIX && try_mac)
{
/* Need to reset the counters when retrying fenc. */
try_mac = 1;
try_unix = 1;
for (; p >= ptr && *p != CAR; p--)
;
if (p >= ptr)
{
for (p = ptr; p < ptr + size; ++p)
{
if (*p == NL)
try_unix++;
else if (*p == CAR)
try_mac++;
}
if (try_mac > try_unix)
fileformat = EOL_MAC;
}
}
else if (fileformat == EOL_UNKNOWN && try_mac == 1)
/* Looking for CR but found no end-of-line markers at
* all: use the default format. */
fileformat = default_fileformat();
}
/* No NL found: may use Mac format */
if (fileformat == EOL_UNKNOWN && try_mac)
fileformat = EOL_MAC;
/* Still nothing found? Use first format in 'ffs' */
if (fileformat == EOL_UNKNOWN)
fileformat = default_fileformat();
/* if editing a new file: may set p_tx and p_ff */
if (set_options)
set_fileformat(fileformat, OPT_LOCAL);
}
}
/*
* This loop is executed once for every character read.
* Keep it fast!
*/
if (fileformat == EOL_MAC)
{
--ptr;
while (++ptr, --size >= 0)
{
/* catch most common case first */
if ((c = *ptr) != NUL && c != CAR && c != NL)
continue;
if (c == NUL)
*ptr = NL; /* NULs are replaced by newlines! */
else if (c == NL)
*ptr = CAR; /* NLs are replaced by CRs! */
else
{
if (skip_count == 0)
{
*ptr = NUL; /* end of line */
len = (colnr_T) (ptr - line_start + 1);
if (ml_append(lnum, line_start, len, newfile) == FAIL)
{
error = TRUE;
break;
}
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
++lnum;
if (--read_count == 0)
{
error = TRUE; /* break loop */
line_start = ptr; /* nothing left to write */
break;
}
}
else
--skip_count;
line_start = ptr + 1;
}
}
}
else
{
--ptr;
while (++ptr, --size >= 0)
{
if ((c = *ptr) != NUL && c != NL) /* catch most common case */
continue;
if (c == NUL)
*ptr = NL; /* NULs are replaced by newlines! */
else
{
if (skip_count == 0)
{
*ptr = NUL; /* end of line */
len = (colnr_T)(ptr - line_start + 1);
if (fileformat == EOL_DOS)
{
if (ptr > line_start && ptr[-1] == CAR)
{
/* remove CR before NL */
ptr[-1] = NUL;
--len;
}
/*
* Reading in Dos format, but no CR-LF found!
* When 'fileformats' includes "unix", delete all
* the lines read so far and start all over again.
* Otherwise give an error message later.
*/
else if (ff_error != EOL_DOS)
{
if ( try_unix
&& !read_stdin
&& (read_buffer
|| vim_lseek(fd, (off_T)0L, SEEK_SET)
== 0))
{
fileformat = EOL_UNIX;
if (set_options)
set_fileformat(EOL_UNIX, OPT_LOCAL);
file_rewind = TRUE;
keep_fileformat = TRUE;
goto retry;
}
ff_error = EOL_DOS;
}
}
if (ml_append(lnum, line_start, len, newfile) == FAIL)
{
error = TRUE;
break;
}
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
++lnum;
if (--read_count == 0)
{
error = TRUE; /* break loop */
line_start = ptr; /* nothing left to write */
break;
}
}
else
--skip_count;
line_start = ptr + 1;
}
}
}
linerest = (long)(ptr - line_start);
ui_breakcheck();
}
failed:
/* not an error, max. number of lines reached */
if (error && read_count == 0)
error = FALSE;
/*
* If we get EOF in the middle of a line, note the fact and
* complete the line ourselves.
* In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
*/
if (!error
&& !got_int
&& linerest != 0
&& !(!curbuf->b_p_bin
&& fileformat == EOL_DOS
&& *line_start == Ctrl_Z
&& ptr == line_start + 1))
{
/* remember for when writing */
if (set_options)
curbuf->b_p_eol = FALSE;
*ptr = NUL;
len = (colnr_T)(ptr - line_start + 1);
if (ml_append(lnum, line_start, len, newfile) == FAIL)
error = TRUE;
else
{
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
read_no_eol_lnum = ++lnum;
}
}
if (set_options)
save_file_ff(curbuf); /* remember the current file format */
#ifdef FEAT_CRYPT
if (curbuf->b_cryptstate != NULL)
{
crypt_free_state(curbuf->b_cryptstate);
curbuf->b_cryptstate = NULL;
}
if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
crypt_free_key(cryptkey);
/* Don't set cryptkey to NULL, it's used below as a flag that
* encryption was used. */
#endif
#ifdef FEAT_MBYTE
/* If editing a new file: set 'fenc' for the current buffer.
* Also for ":read ++edit file". */
if (set_options)
set_string_option_direct((char_u *)"fenc", -1, fenc,
OPT_FREE|OPT_LOCAL, 0);
if (fenc_alloced)
vim_free(fenc);
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
#endif
if (!read_buffer && !read_stdin)
close(fd); /* errors are ignored */
#ifdef HAVE_FD_CLOEXEC
else
{
int fdflags = fcntl(fd, F_GETFD);
if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
(void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
}
#endif
vim_free(buffer);
#ifdef HAVE_DUP
if (read_stdin)
{
/* Use stderr for stdin, makes shell commands work. */
close(0);
ignored = dup(2);
}
#endif
#ifdef FEAT_MBYTE
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
}
#endif
--no_wait_return; /* may wait for return now */
/*
* In recovery mode everything but autocommands is skipped.
*/
if (!recoverymode)
{
/* need to delete the last line, which comes from the empty buffer */
if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
{
#ifdef FEAT_NETBEANS_INTG
netbeansFireChanges = 0;
#endif
ml_delete(curbuf->b_ml.ml_line_count, FALSE);
#ifdef FEAT_NETBEANS_INTG
netbeansFireChanges = 1;
#endif
--linecnt;
}
linecnt = curbuf->b_ml.ml_line_count - linecnt;
if (filesize == 0)
linecnt = 0;
if (newfile || read_buffer)
{
redraw_curbuf_later(NOT_VALID);
#ifdef FEAT_DIFF
/* After reading the text into the buffer the diff info needs to
* be updated. */
diff_invalidate(curbuf);
#endif
#ifdef FEAT_FOLDING
/* All folds in the window are invalid now. Mark them for update
* before triggering autocommands. */
foldUpdateAll(curwin);
#endif
}
else if (linecnt) /* appended at least one line */
appended_lines_mark(from, linecnt);
#ifndef ALWAYS_USE_GUI
/*
* If we were reading from the same terminal as where messages go,
* the screen will have been messed up.
* Switch on raw mode now and clear the screen.
*/
if (read_stdin)
{
settmode(TMODE_RAW); /* set to raw mode */
starttermcap();
screenclear();
}
#endif
if (got_int)
{
if (!(flags & READ_DUMMY))
{
filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
if (newfile)
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
msg_scroll = msg_save;
#ifdef FEAT_VIMINFO
check_marks_read();
#endif
return OK; /* an interrupt isn't really an error */
}
if (!filtering && !(flags & READ_DUMMY))
{
msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
c = FALSE;
#ifdef UNIX
# ifdef S_ISFIFO
if (S_ISFIFO(perm)) /* fifo or socket */
{
STRCAT(IObuff, _("[fifo/socket]"));
c = TRUE;
}
# else
# ifdef S_IFIFO
if ((perm & S_IFMT) == S_IFIFO) /* fifo */
{
STRCAT(IObuff, _("[fifo]"));
c = TRUE;
}
# endif
# ifdef S_IFSOCK
if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
{
STRCAT(IObuff, _("[socket]"));
c = TRUE;
}
# endif
# endif
# ifdef OPEN_CHR_FILES
if (S_ISCHR(perm)) /* or character special */
{
STRCAT(IObuff, _("[character special]"));
c = TRUE;
}
# endif
#endif
if (curbuf->b_p_ro)
{
STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
c = TRUE;
}
if (read_no_eol_lnum)
{
msg_add_eol();
c = TRUE;
}
if (ff_error == EOL_DOS)
{
STRCAT(IObuff, _("[CR missing]"));
c = TRUE;
}
if (split)
{
STRCAT(IObuff, _("[long lines split]"));
c = TRUE;
}
#ifdef FEAT_MBYTE
if (notconverted)
{
STRCAT(IObuff, _("[NOT converted]"));
c = TRUE;
}
else if (converted)
{
STRCAT(IObuff, _("[converted]"));
c = TRUE;
}
#endif
#ifdef FEAT_CRYPT
if (cryptkey != NULL)
{
crypt_append_msg(curbuf);
c = TRUE;
}
#endif
#ifdef FEAT_MBYTE
if (conv_error != 0)
{
sprintf((char *)IObuff + STRLEN(IObuff),
_("[CONVERSION ERROR in line %ld]"), (long)conv_error);
c = TRUE;
}
else if (illegal_byte > 0)
{
sprintf((char *)IObuff + STRLEN(IObuff),
_("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
c = TRUE;
}
else
#endif
if (error)
{
STRCAT(IObuff, _("[READ ERRORS]"));
c = TRUE;
}
if (msg_add_fileformat(fileformat))
c = TRUE;
#ifdef FEAT_CRYPT
if (cryptkey != NULL)
msg_add_lines(c, (long)linecnt, filesize
- crypt_get_header_len(crypt_get_method_nr(curbuf)));
else
#endif
msg_add_lines(c, (long)linecnt, filesize);
vim_free(keep_msg);
keep_msg = NULL;
msg_scrolled_ign = TRUE;
#ifdef ALWAYS_USE_GUI
/* Don't show the message when reading stdin, it would end up in a
* message box (which might be shown when exiting!) */
if (read_stdin || read_buffer)
p = msg_may_trunc(FALSE, IObuff);
else
#endif
p = msg_trunc_attr(IObuff, FALSE, 0);
if (read_stdin || read_buffer || restart_edit != 0
|| (msg_scrolled != 0 && !need_wait_return))
/* Need to repeat the message after redrawing when:
* - When reading from stdin (the screen will be cleared next).
* - When restart_edit is set (otherwise there will be a delay
* before redrawing).
* - When the screen was scrolled but there is no wait-return
* prompt. */
set_keep_msg(p, 0);
msg_scrolled_ign = FALSE;
}
/* with errors writing the file requires ":w!" */
if (newfile && (error
#ifdef FEAT_MBYTE
|| conv_error != 0
|| (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
#endif
))
curbuf->b_p_ro = TRUE;
u_clearline(); /* cannot use "U" command after adding lines */
/*
* In Ex mode: cursor at last new line.
* Otherwise: cursor at first new line.
*/
if (exmode_active)
curwin->w_cursor.lnum = from + linecnt;
else
curwin->w_cursor.lnum = from + 1;
check_cursor_lnum();
beginline(BL_WHITE | BL_FIX); /* on first non-blank */
/*
* Set '[ and '] marks to the newly read lines.
*/
curbuf->b_op_start.lnum = from + 1;
curbuf->b_op_start.col = 0;
curbuf->b_op_end.lnum = from + linecnt;
curbuf->b_op_end.col = 0;
#ifdef WIN32
/*
* Work around a weird problem: When a file has two links (only
* possible on NTFS) and we write through one link, then stat() it
* through the other link, the timestamp information may be wrong.
* It's correct again after reading the file, thus reset the timestamp
* here.
*/
if (newfile && !read_stdin && !read_buffer
&& mch_stat((char *)fname, &st) >= 0)
{
buf_store_time(curbuf, &st, fname);
curbuf->b_mtime_read = curbuf->b_mtime;
}
#endif
}
msg_scroll = msg_save;
#ifdef FEAT_VIMINFO
/*
* Get the marks before executing autocommands, so they can be used there.
*/
check_marks_read();
#endif
/*
* We remember if the last line of the read didn't have
* an eol even when 'binary' is off, to support turning 'fixeol' off,
* or writing the read again with 'binary' on. The latter is required
* for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
*/
curbuf->b_no_eol_lnum = read_no_eol_lnum;
/* When reloading a buffer put the cursor at the first line that is
* different. */
if (flags & READ_KEEP_UNDO)
u_find_first_changed();
#ifdef FEAT_PERSISTENT_UNDO
/*
* When opening a new file locate undo info and read it.
*/
if (read_undo_file)
{
char_u hash[UNDO_HASH_SIZE];
sha256_finish(&sha_ctx, hash);
u_read_undo(NULL, hash, fname);
}
#endif
#ifdef FEAT_AUTOCMD
if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
{
int m = msg_scroll;
int n = msg_scrolled;
/* Save the fileformat now, otherwise the buffer will be considered
* modified if the format/encoding was automatically detected. */
if (set_options)
save_file_ff(curbuf);
/*
* The output from the autocommands should not overwrite anything and
* should not be overwritten: Set msg_scroll, restore its value if no
* output was done.
*/
msg_scroll = TRUE;
if (filtering)
apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
FALSE, curbuf, eap);
else if (newfile || (read_buffer && sfname != NULL))
{
apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
FALSE, curbuf, eap);
if (!au_did_filetype && *curbuf->b_p_ft != NUL)
/*
* EVENT_FILETYPE was not triggered but the buffer already has a
* filetype. Trigger EVENT_FILETYPE using the existing filetype.
*/
apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
TRUE, curbuf);
}
else
apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
FALSE, NULL, eap);
if (msg_scrolled == n)
msg_scroll = m;
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
}
#endif
if (recoverymode && error)
return FAIL;
return OK;
}
#if defined(OPEN_CHR_FILES) || defined(PROTO)
/*
* Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
* which is the name of files used for process substitution output by
* some shells on some operating systems, e.g., bash on SunOS.
* Do not accept "/dev/fd/[012]", opening these may hang Vim.
*/
int
is_dev_fd_file(char_u *fname)
{
return (STRNCMP(fname, "/dev/fd/", 8) == 0
&& VIM_ISDIGIT(fname[8])
&& *skipdigits(fname + 9) == NUL
&& (fname[9] != NUL
|| (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
}
#endif
#ifdef FEAT_MBYTE
/*
* From the current line count and characters read after that, estimate the
* line number where we are now.
* Used for error messages that include a line number.
*/
static linenr_T
readfile_linenr(
linenr_T linecnt, /* line count before reading more bytes */
char_u *p, /* start of more bytes read */
char_u *endp) /* end of more bytes read */
{
char_u *s;
linenr_T lnum;
lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
for (s = p; s < endp; ++s)
if (*s == '\n')
++lnum;
return lnum;
}
#endif
/*
* Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
* equal to the buffer "buf". Used for calling readfile().
* Returns OK or FAIL.
*/
int
prep_exarg(exarg_T *eap, buf_T *buf)
{
eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
#ifdef FEAT_MBYTE
+ STRLEN(buf->b_p_fenc)
#endif
+ 15));
if (eap->cmd == NULL)
return FAIL;
#ifdef FEAT_MBYTE
sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
eap->bad_char = buf->b_bad_char;
#else
sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
#endif
eap->force_ff = 7;
eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
eap->read_edit = FALSE;
eap->forceit = FALSE;
return OK;
}
/*
* Set default or forced 'fileformat' and 'binary'.
*/
void
set_file_options(int set_options, exarg_T *eap)
{
/* set default 'fileformat' */
if (set_options)
{
if (eap != NULL && eap->force_ff != 0)
set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
else if (*p_ffs != NUL)
set_fileformat(default_fileformat(), OPT_LOCAL);
}
/* set or reset 'binary' */
if (eap != NULL && eap->force_bin != 0)
{
int oldval = curbuf->b_p_bin;
curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
}
}
#if defined(FEAT_MBYTE) || defined(PROTO)
/*
* Set forced 'fileencoding'.
*/
void
set_forced_fenc(exarg_T *eap)
{
if (eap->force_enc != 0)
{
char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
if (fenc != NULL)
set_string_option_direct((char_u *)"fenc", -1,
fenc, OPT_FREE|OPT_LOCAL, 0);
vim_free(fenc);
}
}
/*
* Find next fileencoding to use from 'fileencodings'.
* "pp" points to fenc_next. It's advanced to the next item.
* When there are no more items, an empty string is returned and *pp is set to
* NULL.
* When *pp is not set to NULL, the result is in allocated memory.
*/
static char_u *
next_fenc(char_u **pp)
{
char_u *p;
char_u *r;
if (**pp == NUL)
{
*pp = NULL;
return (char_u *)"";
}
p = vim_strchr(*pp, ',');
if (p == NULL)
{
r = enc_canonize(*pp);
*pp += STRLEN(*pp);
}
else
{
r = vim_strnsave(*pp, (int)(p - *pp));
*pp = p + 1;
if (r != NULL)
{
p = enc_canonize(r);
vim_free(r);
r = p;
}
}
if (r == NULL) /* out of memory */
{
r = (char_u *)"";
*pp = NULL;
}
return r;
}
# ifdef FEAT_EVAL
/*
* Convert a file with the 'charconvert' expression.
* This closes the file which is to be read, converts it and opens the
* resulting file for reading.
* Returns name of the resulting converted file (the caller should delete it
* after reading it).
* Returns NULL if the conversion failed ("*fdp" is not set) .
*/
static char_u *
readfile_charconvert(
char_u *fname, /* name of input file */
char_u *fenc, /* converted from */
int *fdp) /* in/out: file descriptor of file */
{
char_u *tmpname;
char_u *errmsg = NULL;
tmpname = vim_tempname('r', FALSE);
if (tmpname == NULL)
errmsg = (char_u *)_("Can't find temp file for conversion");
else
{
close(*fdp); /* close the input file, ignore errors */
*fdp = -1;
if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
fname, tmpname) == FAIL)
errmsg = (char_u *)_("Conversion with 'charconvert' failed");
if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
O_RDONLY | O_EXTRA, 0)) < 0)
errmsg = (char_u *)_("can't read output of 'charconvert'");
}
if (errmsg != NULL)
{
/* Don't use emsg(), it breaks mappings, the retry with
* another type of conversion might still work. */
MSG(errmsg);
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
tmpname = NULL;
}
}
/* If the input file is closed, open it (caller should check for error). */
if (*fdp < 0)
*fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
return tmpname;
}
# endif
#endif
#ifdef FEAT_VIMINFO
/*
* Read marks for the current buffer from the viminfo file, when we support
* buffer marks and the buffer has a name.
*/
static void
check_marks_read(void)
{
if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
&& curbuf->b_ffname != NULL)
read_viminfo(NULL, VIF_WANT_MARKS);
/* Always set b_marks_read; needed when 'viminfo' is changed to include
* the ' parameter after opening a buffer. */
curbuf->b_marks_read = TRUE;
}
#endif
#if defined(FEAT_CRYPT) || defined(PROTO)
/*
* Check for magic number used for encryption. Applies to the current buffer.
* If found, the magic number is removed from ptr[*sizep] and *sizep and
* *filesizep are updated.
* Return the (new) encryption key, NULL for no encryption.
*/
static char_u *
check_for_cryptkey(
char_u *cryptkey, /* previous encryption key or NULL */
char_u *ptr, /* pointer to read bytes */
long *sizep, /* length of read bytes */
off_T *filesizep, /* nr of bytes used from file */
int newfile, /* editing a new buffer */
char_u *fname, /* file name to display */
int *did_ask) /* flag: whether already asked for key */
{
int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
int b_p_ro = curbuf->b_p_ro;
if (method >= 0)
{
/* Mark the buffer as read-only until the decryption has taken place.
* Avoids accidentally overwriting the file with garbage. */
curbuf->b_p_ro = TRUE;
/* Set the cryptmethod local to the buffer. */
crypt_set_cm_option(curbuf, method);
if (cryptkey == NULL && !*did_ask)
{
if (*curbuf->b_p_key)
cryptkey = curbuf->b_p_key;
else
{
/* When newfile is TRUE, store the typed key in the 'key'
* option and don't free it. bf needs hash of the key saved.
* Don't ask for the key again when first time Enter was hit.
* Happens when retrying to detect encoding. */
smsg((char_u *)_(need_key_msg), fname);
msg_scroll = TRUE;
crypt_check_method(method);
cryptkey = crypt_get_key(newfile, FALSE);
*did_ask = TRUE;
/* check if empty key entered */
if (cryptkey != NULL && *cryptkey == NUL)
{
if (cryptkey != curbuf->b_p_key)
vim_free(cryptkey);
cryptkey = NULL;
}
}
}
if (cryptkey != NULL)
{
int header_len;
curbuf->b_cryptstate = crypt_create_from_header(
method, cryptkey, ptr);
crypt_set_cm_option(curbuf, method);
/* Remove cryptmethod specific header from the text. */
header_len = crypt_get_header_len(method);
if (*sizep <= header_len)
/* invalid header, buffer can't be encrypted */
return NULL;
*filesizep += header_len;
*sizep -= header_len;
mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
/* Restore the read-only flag. */
curbuf->b_p_ro = b_p_ro;
}
}
/* When starting to edit a new file which does not have encryption, clear
* the 'key' option, except when starting up (called with -x argument) */
else if (newfile && *curbuf->b_p_key != NUL && !starting)
set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
return cryptkey;
}
#endif /* FEAT_CRYPT */
#ifdef UNIX
static void
set_file_time(
char_u *fname,
time_t atime, /* access time */
time_t mtime) /* modification time */
{
# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
struct utimbuf buf;
buf.actime = atime;
buf.modtime = mtime;
(void)utime((char *)fname, &buf);
# else
# if defined(HAVE_UTIMES)
struct timeval tvp[2];
tvp[0].tv_sec = atime;
tvp[0].tv_usec = 0;
tvp[1].tv_sec = mtime;
tvp[1].tv_usec = 0;
# ifdef NeXT
(void)utimes((char *)fname, tvp);
# else
(void)utimes((char *)fname, (const struct timeval *)&tvp);
# endif
# endif
# endif
}
#endif /* UNIX */
#if defined(VMS) && !defined(MIN)
/* Older DECC compiler for VAX doesn't define MIN() */
# define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/*
* Return TRUE if a file appears to be read-only from the file permissions.
*/
int
check_file_readonly(
char_u *fname, /* full path to file */
int perm) /* known permissions on file */
{
#ifndef USE_MCH_ACCESS
int fd = 0;
#endif
return (
#ifdef USE_MCH_ACCESS
# ifdef UNIX
(perm & 0222) == 0 ||
# endif
mch_access((char *)fname, W_OK)
#else
(fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
? TRUE : (close(fd), FALSE)
#endif
);
}
/*
* buf_write() - write to file "fname" lines "start" through "end"
*
* We do our own buffering here because fwrite() is so slow.
*
* If "forceit" is true, we don't care for errors when attempting backups.
* In case of an error everything possible is done to restore the original
* file. But when "forceit" is TRUE, we risk losing it.
*
* When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
* "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
*
* This function must NOT use NameBuff (because it's called by autowrite()).
*
* return FAIL for failure, OK otherwise
*/
int
buf_write(
buf_T *buf,
char_u *fname,
char_u *sfname,
linenr_T start,
linenr_T end,
exarg_T *eap, /* for forced 'ff' and 'fenc', can be
NULL! */
int append, /* append to the file */
int forceit,
int reset_changed,
int filtering)
{
int fd;
char_u *backup = NULL;
int backup_copy = FALSE; /* copy the original file? */
int dobackup;
char_u *ffname;
char_u *wfname = NULL; /* name of file to write to */
char_u *s;
char_u *ptr;
char_u c;
int len;
linenr_T lnum;
long nchars;
char_u *errmsg = NULL;
int errmsg_allocated = FALSE;
char_u *errnum = NULL;
char_u *buffer;
char_u smallbuf[SMBUFSIZE];
char_u *backup_ext;
int bufsize;
long perm; /* file permissions */
int retval = OK;
int newfile = FALSE; /* TRUE if file doesn't exist yet */
int msg_save = msg_scroll;
int overwriting; /* TRUE if writing over original */
int no_eol = FALSE; /* no end-of-line written */
int device = FALSE; /* writing to a device */
stat_T st_old;
int prev_got_int = got_int;
int checking_conversion;
int file_readonly = FALSE; /* overwritten file is read-only */
static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
#if defined(UNIX) /*XXX fix me sometime? */
int made_writable = FALSE; /* 'w' bit has been set */
#endif
/* writing everything */
int whole = (start == 1 && end == buf->b_ml.ml_line_count);
#ifdef FEAT_AUTOCMD
linenr_T old_line_count = buf->b_ml.ml_line_count;
#endif
int attr;
int fileformat;
int write_bin;
struct bw_info write_info; /* info for buf_write_bytes() */
#ifdef FEAT_MBYTE
int converted = FALSE;
int notconverted = FALSE;
char_u *fenc; /* effective 'fileencoding' */
char_u *fenc_tofree = NULL; /* allocated "fenc" */
#endif
#ifdef HAS_BW_FLAGS
int wb_flags = 0;
#endif
#ifdef HAVE_ACL
vim_acl_T acl = NULL; /* ACL copied from original file to
backup or new file */
#endif
#ifdef FEAT_PERSISTENT_UNDO
int write_undo_file = FALSE;
context_sha256_T sha_ctx;
#endif
unsigned int bkc = get_bkc_value(buf);
if (fname == NULL || *fname == NUL) /* safety check */
return FAIL;
if (buf->b_ml.ml_mfp == NULL)
{
/* This can happen during startup when there is a stray "w" in the
* vimrc file. */
EMSG(_(e_emptybuf));
return FAIL;
}
/*
* Disallow writing from .exrc and .vimrc in current directory for
* security reasons.
*/
if (check_secure())
return FAIL;
/* Avoid a crash for a long name. */
if (STRLEN(fname) >= MAXPATHL)
{
EMSG(_(e_longname));
return FAIL;
}
#ifdef FEAT_MBYTE
/* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
write_info.bw_conv_buf = NULL;
write_info.bw_conv_error = FALSE;
write_info.bw_conv_error_lnum = 0;
write_info.bw_restlen = 0;
# ifdef USE_ICONV
write_info.bw_iconv_fd = (iconv_t)-1;
# endif
#endif
#ifdef FEAT_CRYPT
write_info.bw_buffer = buf;
#endif
/* After writing a file changedtick changes but we don't want to display
* the line. */
ex_no_reprint = TRUE;
/*
* If there is no file name yet, use the one for the written file.
* BF_NOTEDITED is set to reflect this (in case the write fails).
* Don't do this when the write is for a filter command.
* Don't do this when appending.
* Only do this when 'cpoptions' contains the 'F' flag.
*/
if (buf->b_ffname == NULL
&& reset_changed
&& whole
&& buf == curbuf
#ifdef FEAT_QUICKFIX
&& !bt_nofile(buf)
#endif
&& !filtering
&& (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
&& vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
{
if (set_rw_fname(fname, sfname) == FAIL)
return FAIL;
buf = curbuf; /* just in case autocmds made "buf" invalid */
}
if (sfname == NULL)
sfname = fname;
/*
* For Unix: Use the short file name whenever possible.
* Avoids problems with networks and when directory names are changed.
* Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
* another directory, which we don't detect
*/
ffname = fname; /* remember full fname */
#ifdef UNIX
fname = sfname;
#endif
if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
overwriting = TRUE;
else
overwriting = FALSE;
if (exiting)
settmode(TMODE_COOK); /* when exiting allow typeahead now */
++no_wait_return; /* don't wait for return yet */
/*
* Set '[ and '] marks to the lines to be written.
*/
buf->b_op_start.lnum = start;
buf->b_op_start.col = 0;
buf->b_op_end.lnum = end;
buf->b_op_end.col = 0;
#ifdef FEAT_AUTOCMD
{
aco_save_T aco;
int buf_ffname = FALSE;
int buf_sfname = FALSE;
int buf_fname_f = FALSE;
int buf_fname_s = FALSE;
int did_cmd = FALSE;
int nofile_err = FALSE;
int empty_memline = (buf->b_ml.ml_mfp == NULL);
bufref_T bufref;
/*
* Apply PRE autocommands.
* Set curbuf to the buffer to be written.
* Careful: The autocommands may call buf_write() recursively!
*/
if (ffname == buf->b_ffname)
buf_ffname = TRUE;
if (sfname == buf->b_sfname)
buf_sfname = TRUE;
if (fname == buf->b_ffname)
buf_fname_f = TRUE;
if (fname == buf->b_sfname)
buf_fname_s = TRUE;
/* set curwin/curbuf to buf and save a few things */
aucmd_prepbuf(&aco, buf);
set_bufref(&bufref, buf);
if (append)
{
if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
sfname, sfname, FALSE, curbuf, eap)))
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
else if (filtering)
{
apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
NULL, sfname, FALSE, curbuf, eap);
}
else if (reset_changed && whole)
{
int was_changed = curbufIsChanged();
did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
sfname, sfname, FALSE, curbuf, eap);
if (did_cmd)
{
if (was_changed && !curbufIsChanged())
{
/* Written everything correctly and BufWriteCmd has reset
* 'modified': Correct the undo information so that an
* undo now sets 'modified'. */
u_unchanged(curbuf);
u_update_save_nr(curbuf);
}
}
else
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_BUFWRITEPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
else
{
if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
sfname, sfname, FALSE, curbuf, eap)))
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_FILEWRITEPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
/*
* In three situations we return here and don't write the file:
* 1. the autocommands deleted or unloaded the buffer.
* 2. The autocommands abort script processing.
* 3. If one of the "Cmd" autocommands was executed.
*/
if (!bufref_valid(&bufref))
buf = NULL;
if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
|| did_cmd || nofile_err
#ifdef FEAT_EVAL
|| aborting()
#endif
)
{
--no_wait_return;
msg_scroll = msg_save;
if (nofile_err)
EMSG(_("E676: No matching autocommands for acwrite buffer"));
if (nofile_err
#ifdef FEAT_EVAL
|| aborting()
#endif
)
/* An aborting error, interrupt or exception in the
* autocommands. */
return FAIL;
if (did_cmd)
{
if (buf == NULL)
/* The buffer was deleted. We assume it was written
* (can't retry anyway). */
return OK;
if (overwriting)
{
/* Assume the buffer was written, update the timestamp. */
ml_timestamp(buf);
if (append)
buf->b_flags &= ~BF_NEW;
else
buf->b_flags &= ~BF_WRITE_MASK;
}
if (reset_changed && buf->b_changed && !append
&& (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
/* Buffer still changed, the autocommands didn't work
* properly. */
return FAIL;
return OK;
}
#ifdef FEAT_EVAL
if (!aborting())
#endif
EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
return FAIL;
}
/*
* The autocommands may have changed the number of lines in the file.
* When writing the whole file, adjust the end.
* When writing part of the file, assume that the autocommands only
* changed the number of lines that are to be written (tricky!).
*/
if (buf->b_ml.ml_line_count != old_line_count)
{
if (whole) /* write all */
end = buf->b_ml.ml_line_count;
else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
end += buf->b_ml.ml_line_count - old_line_count;
else /* less lines */
{
end -= old_line_count - buf->b_ml.ml_line_count;
if (end < start)
{
--no_wait_return;
msg_scroll = msg_save;
EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
return FAIL;
}
}
}
/*
* The autocommands may have changed the name of the buffer, which may
* be kept in fname, ffname and sfname.
*/
if (buf_ffname)
ffname = buf->b_ffname;
if (buf_sfname)
sfname = buf->b_sfname;
if (buf_fname_f)
fname = buf->b_ffname;
if (buf_fname_s)
fname = buf->b_sfname;
}
#endif
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active() && isNetbeansBuffer(buf))
{
if (whole)
{
/*
* b_changed can be 0 after an undo, but we still need to write
* the buffer to NetBeans.
*/
if (buf->b_changed || isNetbeansModified(buf))
{
--no_wait_return; /* may wait for return now */
msg_scroll = msg_save;
netbeans_save_buffer(buf); /* no error checking... */
return retval;
}
else
{
errnum = (char_u *)"E656: ";
errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
buffer = NULL;
goto fail;
}
}
else
{
errnum = (char_u *)"E657: ";
errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
buffer = NULL;
goto fail;
}
}
#endif
if (shortmess(SHM_OVER) && !exiting)
msg_scroll = FALSE; /* overwrite previous file message */
else
msg_scroll = TRUE; /* don't overwrite previous file message */
if (!filtering)
filemess(buf,
#ifndef UNIX
sfname,
#else
fname,
#endif
(char_u *)"", 0); /* show that we are busy */
msg_scroll = FALSE; /* always overwrite the file message now */
buffer = alloc(BUFSIZE);
if (buffer == NULL) /* can't allocate big buffer, use small
* one (to be able to write when out of
* memory) */
{
buffer = smallbuf;
bufsize = SMBUFSIZE;
}
else
bufsize = BUFSIZE;
/*
* Get information about original file (if there is one).
*/
#if defined(UNIX)
st_old.st_dev = 0;
st_old.st_ino = 0;
perm = -1;
if (mch_stat((char *)fname, &st_old) < 0)
newfile = TRUE;
else
{
perm = st_old.st_mode;
if (!S_ISREG(st_old.st_mode)) /* not a file */
{
if (S_ISDIR(st_old.st_mode))
{
errnum = (char_u *)"E502: ";
errmsg = (char_u *)_("is a directory");
goto fail;
}
if (mch_nodetype(fname) != NODE_WRITABLE)
{
errnum = (char_u *)"E503: ";
errmsg = (char_u *)_("is not a file or writable device");
goto fail;
}
/* It's a device of some kind (or a fifo) which we can write to
* but for which we can't make a backup. */
device = TRUE;
newfile = TRUE;
perm = -1;
}
}
#else /* !UNIX */
/*
* Check for a writable device name.
*/
c = mch_nodetype(fname);
if (c == NODE_OTHER)
{
errnum = (char_u *)"E503: ";
errmsg = (char_u *)_("is not a file or writable device");
goto fail;
}
if (c == NODE_WRITABLE)
{
# if defined(MSWIN)
/* MS-Windows allows opening a device, but we will probably get stuck
* trying to write to it. */
if (!p_odev)
{
errnum = (char_u *)"E796: ";
errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
goto fail;
}
# endif
device = TRUE;
newfile = TRUE;
perm = -1;
}
else
{
perm = mch_getperm(fname);
if (perm < 0)
newfile = TRUE;
else if (mch_isdir(fname))
{
errnum = (char_u *)"E502: ";
errmsg = (char_u *)_("is a directory");
goto fail;
}
if (overwriting)
(void)mch_stat((char *)fname, &st_old);
}
#endif /* !UNIX */
if (!device && !newfile)
{
/*
* Check if the file is really writable (when renaming the file to
* make a backup we won't discover it later).
*/
file_readonly = check_file_readonly(fname, (int)perm);
if (!forceit && file_readonly)
{
if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
{
errnum = (char_u *)"E504: ";
errmsg = (char_u *)_(err_readonly);
}
else
{
errnum = (char_u *)"E505: ";
errmsg = (char_u *)_("is read-only (add ! to override)");
}
goto fail;
}
/*
* Check if the timestamp hasn't changed since reading the file.
*/
if (overwriting)
{
retval = check_mtime(buf, &st_old);
if (retval == FAIL)
goto fail;
}
}
#ifdef HAVE_ACL
/*
* For systems that support ACL: get the ACL from the original file.
*/
if (!newfile)
acl = mch_get_acl(fname);
#endif
/*
* If 'backupskip' is not empty, don't make a backup for some files.
*/
dobackup = (p_wb || p_bk || *p_pm != NUL);
#ifdef FEAT_WILDIGN
if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
dobackup = FALSE;
#endif
/*
* Save the value of got_int and reset it. We don't want a previous
* interruption cancel writing, only hitting CTRL-C while writing should
* abort it.
*/
prev_got_int = got_int;
got_int = FALSE;
/* Mark the buffer as 'being saved' to prevent changed buffer warnings */
buf->b_saving = TRUE;
/*
* If we are not appending or filtering, the file exists, and the
* 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
* When 'patchmode' is set also make a backup when appending.
*
* Do not make any backup, if 'writebackup' and 'backup' are both switched
* off. This helps when editing large files on almost-full disks.
*/
if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
{
#if defined(UNIX) || defined(WIN32)
stat_T st;
#endif
if ((bkc & BKC_YES) || append) /* "yes" */
backup_copy = TRUE;
#if defined(UNIX) || defined(WIN32)
else if ((bkc & BKC_AUTO)) /* "auto" */
{
int i;
# ifdef UNIX
/*
* Don't rename the file when:
* - it's a hard link
* - it's a symbolic link
* - we don't have write permission in the directory
* - we can't set the owner/group of the new file
*/
if (st_old.st_nlink > 1
|| mch_lstat((char *)fname, &st) < 0
|| st.st_dev != st_old.st_dev
|| st.st_ino != st_old.st_ino
# ifndef HAVE_FCHOWN
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid
# endif
)
backup_copy = TRUE;
else
# else
# ifdef WIN32
/* On NTFS file systems hard links are possible. */
if (mch_is_linked(fname))
backup_copy = TRUE;
else
# endif
# endif
{
/*
* Check if we can create a file and set the owner/group to
* the ones from the original file.
* First find a file name that doesn't exist yet (use some
* arbitrary numbers).
*/
STRCPY(IObuff, fname);
for (i = 4913; ; i += 123)
{
sprintf((char *)gettail(IObuff), "%d", i);
if (mch_lstat((char *)IObuff, &st) < 0)
break;
}
fd = mch_open((char *)IObuff,
O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
if (fd < 0) /* can't write in directory */
backup_copy = TRUE;
else
{
# ifdef UNIX
# ifdef HAVE_FCHOWN
ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
# endif
if (mch_stat((char *)IObuff, &st) < 0
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid
|| (long)st.st_mode != perm)
backup_copy = TRUE;
# endif
/* Close the file before removing it, on MS-Windows we
* can't delete an open file. */
close(fd);
mch_remove(IObuff);
# ifdef MSWIN
/* MS-Windows may trigger a virus scanner to open the
* file, we can't delete it then. Keep trying for half a
* second. */
{
int try;
for (try = 0; try < 10; ++try)
{
if (mch_lstat((char *)IObuff, &st) < 0)
break;
ui_delay(50L, TRUE); /* wait 50 msec */
mch_remove(IObuff);
}
}
# endif
}
}
}
/*
* Break symlinks and/or hardlinks if we've been asked to.
*/
if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
{
# ifdef UNIX
int lstat_res;
lstat_res = mch_lstat((char *)fname, &st);
/* Symlinks. */
if ((bkc & BKC_BREAKSYMLINK)
&& lstat_res == 0
&& st.st_ino != st_old.st_ino)
backup_copy = FALSE;
/* Hardlinks. */
if ((bkc & BKC_BREAKHARDLINK)
&& st_old.st_nlink > 1
&& (lstat_res != 0 || st.st_ino == st_old.st_ino))
backup_copy = FALSE;
# else
# if defined(WIN32)
/* Symlinks. */
if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
backup_copy = FALSE;
/* Hardlinks. */
if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
backup_copy = FALSE;
# endif
# endif
}
#endif
/* make sure we have a valid backup extension to use */
if (*p_bex == NUL)
backup_ext = (char_u *)".bak";
else
backup_ext = p_bex;
if (backup_copy
&& (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
{
int bfd;
char_u *copybuf, *wp;
int some_error = FALSE;
stat_T st_new;
char_u *dirp;
char_u *rootname;
#if defined(UNIX)
int did_set_shortname;
#endif
copybuf = alloc(BUFSIZE + 1);
if (copybuf == NULL)
{
some_error = TRUE; /* out of memory */
goto nobackup;
}
/*
* Try to make the backup in each directory in the 'bdir' option.
*
* Unix semantics has it, that we may have a writable file,
* that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
* - the directory is not writable,
* - the file may be a symbolic link,
* - the file may belong to another user/group, etc.
*
* For these reasons, the existing writable file must be truncated
* and reused. Creation of a backup COPY will be attempted.
*/
dirp = p_bdir;
while (*dirp)
{
#ifdef UNIX
st_new.st_ino = 0;
st_new.st_dev = 0;
st_new.st_gid = 0;
#endif
/*
* Isolate one directory name, using an entry in 'bdir'.
*/
(void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
rootname = get_file_in_dir(fname, copybuf);
if (rootname == NULL)
{
some_error = TRUE; /* out of memory */
goto nobackup;
}
#if defined(UNIX)
did_set_shortname = FALSE;
#endif
/*
* May try twice if 'shortname' not set.
*/
for (;;)
{
/*
* Make backup file name.
*/
backup = buf_modname((buf->b_p_sn || buf->b_shortname),
rootname, backup_ext, FALSE);
if (backup == NULL)
{
vim_free(rootname);
some_error = TRUE; /* out of memory */
goto nobackup;
}
/*
* Check if backup file already exists.
*/
if (mch_stat((char *)backup, &st_new) >= 0)
{
#ifdef UNIX
/*
* Check if backup file is same as original file.
* May happen when modname() gave the same file back.
* E.g. silly link, or file name-length reached.
* If we don't check here, we either ruin the file
* when copying or erase it after writing. jw.
*/
if (st_new.st_dev == st_old.st_dev
&& st_new.st_ino == st_old.st_ino)
{
vim_free(backup);
backup = NULL; /* no backup file to delete */
/*
* may try again with 'shortname' set
*/
if (!(buf->b_shortname || buf->b_p_sn))
{
buf->b_shortname = TRUE;
did_set_shortname = TRUE;
continue;
}
/* setting shortname didn't help */
if (did_set_shortname)
buf->b_shortname = FALSE;
break;
}
#endif
/*
* If we are not going to keep the backup file, don't
* delete an existing one, try to use another name.
* Change one character, just before the extension.
*/
if (!p_bk)
{
wp = backup + STRLEN(backup) - 1
- STRLEN(backup_ext);
if (wp < backup) /* empty file name ??? */
wp = backup;
*wp = 'z';
while (*wp > 'a'
&& mch_stat((char *)backup, &st_new) >= 0)
--*wp;
/* They all exist??? Must be something wrong. */
if (*wp == 'a')
{
vim_free(backup);
backup = NULL;
}
}
}
break;
}
vim_free(rootname);
/*
* Try to create the backup file
*/
if (backup != NULL)
{
/* remove old backup, if present */
mch_remove(backup);
/* Open with O_EXCL to avoid the file being created while
* we were sleeping (symlink hacker attack?) */
bfd = mch_open((char *)backup,
O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
perm & 0777);
if (bfd < 0)
{
vim_free(backup);
backup = NULL;
}
else
{
/* set file protection same as original file, but
* strip s-bit */
(void)mch_setperm(backup, perm & 0777);
#ifdef UNIX
/*
* Try to set the group of the backup same as the
* original file. If this fails, set the protection
* bits for the group same as the protection bits for
* others.
*/
if (st_new.st_gid != st_old.st_gid
# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
&& fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
# endif
)
mch_setperm(backup,
(perm & 0707) | ((perm & 07) << 3));
# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(fname, backup);
# endif
#endif
/*
* copy the file.
*/
write_info.bw_fd = bfd;
write_info.bw_buf = copybuf;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = FIO_NOCONVERT;
#endif
while ((write_info.bw_len = read_eintr(fd, copybuf,
BUFSIZE)) > 0)
{
if (buf_write_bytes(&write_info) == FAIL)
{
errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
break;
}
ui_breakcheck();
if (got_int)
{
errmsg = (char_u *)_(e_interr);
break;
}
}
if (close(bfd) < 0 && errmsg == NULL)
errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
if (write_info.bw_len < 0)
errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
#ifdef UNIX
set_file_time(backup, st_old.st_atime, st_old.st_mtime);
#endif
#ifdef HAVE_ACL
mch_set_acl(backup, acl);
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(fname, backup);
#endif
break;
}
}
}
nobackup:
close(fd); /* ignore errors for closing read file */
vim_free(copybuf);
if (backup == NULL && errmsg == NULL)
errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
/* ignore errors when forceit is TRUE */
if ((some_error || errmsg != NULL) && !forceit)
{
retval = FAIL;
goto fail;
}
errmsg = NULL;
}
else
{
char_u *dirp;
char_u *p;
char_u *rootname;
/*
* Make a backup by renaming the original file.
*/
/*
* If 'cpoptions' includes the "W" flag, we don't want to
* overwrite a read-only file. But rename may be possible
* anyway, thus we need an extra check here.
*/
if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
{
errnum = (char_u *)"E504: ";
errmsg = (char_u *)_(err_readonly);
goto fail;
}
/*
*
* Form the backup file name - change path/fo.o.h to
* path/fo.o.h.bak Try all directories in 'backupdir', first one
* that works is used.
*/
dirp = p_bdir;
while (*dirp)
{
/*
* Isolate one directory name and make the backup file name.
*/
(void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
rootname = get_file_in_dir(fname, IObuff);
if (rootname == NULL)
backup = NULL;
else
{
backup = buf_modname((buf->b_p_sn || buf->b_shortname),
rootname, backup_ext, FALSE);
vim_free(rootname);
}
if (backup != NULL)
{
/*
* If we are not going to keep the backup file, don't
* delete an existing one, try to use another name.
* Change one character, just before the extension.
*/
if (!p_bk && mch_getperm(backup) >= 0)
{
p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
if (p < backup) /* empty file name ??? */
p = backup;
*p = 'z';
while (*p > 'a' && mch_getperm(backup) >= 0)
--*p;
/* They all exist??? Must be something wrong! */
if (*p == 'a')
{
vim_free(backup);
backup = NULL;
}
}
}
if (backup != NULL)
{
/*
* Delete any existing backup and move the current version
* to the backup. For safety, we don't remove the backup
* until the write has finished successfully. And if the
* 'backup' option is set, leave it around.
*/
/*
* If the renaming of the original file to the backup file
* works, quit here.
*/
if (vim_rename(fname, backup) == 0)
break;
vim_free(backup); /* don't do the rename below */
backup = NULL;
}
}
if (backup == NULL && !forceit)
{
errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
goto fail;
}
}
}
#if defined(UNIX)
/* When using ":w!" and the file was read-only: make it writable */
if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
&& vim_strchr(p_cpo, CPO_FWRITE) == NULL)
{
perm |= 0200;
(void)mch_setperm(fname, perm);
made_writable = TRUE;
}
#endif
/* When using ":w!" and writing to the current file, 'readonly' makes no
* sense, reset it, unless 'Z' appears in 'cpoptions'. */
if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
{
buf->b_p_ro = FALSE;
#ifdef FEAT_TITLE
need_maketitle = TRUE; /* set window title later */
#endif
status_redraw_all(); /* redraw status lines later */
}
if (end > buf->b_ml.ml_line_count)
end = buf->b_ml.ml_line_count;
if (buf->b_ml.ml_flags & ML_EMPTY)
start = end + 1;
/*
* If the original file is being overwritten, there is a small chance that
* we crash in the middle of writing. Therefore the file is preserved now.
* This makes all block numbers positive so that recovery does not need
* the original file.
* Don't do this if there is a backup file and we are exiting.
*/
if (reset_changed && !newfile && overwriting
&& !(exiting && backup != NULL))
{
ml_preserve(buf, FALSE);
if (got_int)
{
errmsg = (char_u *)_(e_interr);
goto restore_backup;
}
}
#ifdef VMS
vms_remove_version(fname); /* remove version */
#endif
/* Default: write the file directly. May write to a temp file for
* multi-byte conversion. */
wfname = fname;
#ifdef FEAT_MBYTE
/* Check for forced 'fileencoding' from "++opt=val" argument. */
if (eap != NULL && eap->force_enc != 0)
{
fenc = eap->cmd + eap->force_enc;
fenc = enc_canonize(fenc);
fenc_tofree = fenc;
}
else
fenc = buf->b_p_fenc;
/*
* Check if the file needs to be converted.
*/
converted = need_conversion(fenc);
/*
* Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
* Latin1 to Unicode conversion. This is handled in buf_write_bytes().
* Prepare the flags for it and allocate bw_conv_buf when needed.
*/
if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
{
wb_flags = get_fio_flags(fenc);
if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
{
/* Need to allocate a buffer to translate into. */
if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
write_info.bw_conv_buflen = bufsize * 2;
else /* FIO_UCS4 */
write_info.bw_conv_buflen = bufsize * 4;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
}
# ifdef WIN3264
if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
{
/* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
write_info.bw_conv_buflen = bufsize * 4;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
# endif
# ifdef MACOS_CONVERT
if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
{
write_info.bw_conv_buflen = bufsize * 3;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
# endif
# if defined(FEAT_EVAL) || defined(USE_ICONV)
if (converted && wb_flags == 0)
{
# ifdef USE_ICONV
/*
* Use iconv() conversion when conversion is needed and it's not done
* internally.
*/
write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
enc_utf8 ? (char_u *)"utf-8" : p_enc);
if (write_info.bw_iconv_fd != (iconv_t)-1)
{
/* We're going to use iconv(), allocate a buffer to convert in. */
write_info.bw_conv_buflen = bufsize * ICONV_MULT;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
write_info.bw_first = TRUE;
}
# ifdef FEAT_EVAL
else
# endif
# endif
# ifdef FEAT_EVAL
/*
* When the file needs to be converted with 'charconvert' after
* writing, write to a temp file instead and let the conversion
* overwrite the original file.
*/
if (*p_ccv != NUL)
{
wfname = vim_tempname('w', FALSE);
if (wfname == NULL) /* Can't write without a tempfile! */
{
errmsg = (char_u *)_("E214: Can't find temp file for writing");
goto restore_backup;
}
}
# endif
}
# endif
if (converted && wb_flags == 0
# ifdef USE_ICONV
&& write_info.bw_iconv_fd == (iconv_t)-1
# endif
# ifdef FEAT_EVAL
&& wfname == fname
# endif
)
{
if (!forceit)
{
errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
goto restore_backup;
}
notconverted = TRUE;
}
#endif
/*
* If conversion is taking place, we may first pretend to write and check
* for conversion errors. Then loop again to write for real.
* When not doing conversion this writes for real right away.
*/
for (checking_conversion = TRUE; ; checking_conversion = FALSE)
{
/*
* There is no need to check conversion when:
* - there is no conversion
* - we make a backup file, that can be restored in case of conversion
* failure.
*/
#ifdef FEAT_MBYTE
if (!converted || dobackup)
#endif
checking_conversion = FALSE;
if (checking_conversion)
{
/* Make sure we don't write anything. */
fd = -1;
write_info.bw_fd = fd;
}
else
{
/*
* Open the file "wfname" for writing.
* We may try to open the file twice: If we can't write to the file
* and forceit is TRUE we delete the existing file and try to
* create a new one. If this still fails we may have lost the
* original file! (this may happen when the user reached his
* quotum for number of files).
* Appending will fail if the file does not exist and forceit is
* FALSE.
*/
while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
: (O_CREAT | O_TRUNC))
, perm < 0 ? 0666 : (perm & 0777))) < 0)
{
/*
* A forced write will try to create a new file if the old one
* is still readonly. This may also happen when the directory
* is read-only. In that case the mch_remove() will fail.
*/
if (errmsg == NULL)
{
#ifdef UNIX
stat_T st;
/* Don't delete the file when it's a hard or symbolic link.
*/
if ((!newfile && st_old.st_nlink > 1)
|| (mch_lstat((char *)fname, &st) == 0
&& (st.st_dev != st_old.st_dev
|| st.st_ino != st_old.st_ino)))
errmsg = (char_u *)_("E166: Can't open linked file for writing");
else
#endif
{
errmsg = (char_u *)_("E212: Can't open file for writing");
if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
&& perm >= 0)
{
#ifdef UNIX
/* we write to the file, thus it should be marked
writable after all */
if (!(perm & 0200))
made_writable = TRUE;
perm |= 0200;
if (st_old.st_uid != getuid()
|| st_old.st_gid != getgid())
perm &= 0777;
#endif
if (!append) /* don't remove when appending */
mch_remove(wfname);
continue;
}
}
}
restore_backup:
{
stat_T st;
/*
* If we failed to open the file, we don't need a backup.
* Throw it away. If we moved or removed the original file
* try to put the backup in its place.
*/
if (backup != NULL && wfname == fname)
{
if (backup_copy)
{
/*
* There is a small chance that we removed the
* original, try to move the copy in its place.
* This may not work if the vim_rename() fails.
* In that case we leave the copy around.
*/
/* If file does not exist, put the copy in its
* place */
if (mch_stat((char *)fname, &st) < 0)
vim_rename(backup, fname);
/* if original file does exist throw away the copy
*/
if (mch_stat((char *)fname, &st) >= 0)
mch_remove(backup);
}
else
{
/* try to put the original file back */
vim_rename(backup, fname);
}
}
/* if original file no longer exists give an extra warning
*/
if (!newfile && mch_stat((char *)fname, &st) < 0)
end = 0;
}
#ifdef FEAT_MBYTE
if (wfname != fname)
vim_free(wfname);
#endif
goto fail;
}
write_info.bw_fd = fd;
#if defined(WIN3264)
if (backup != NULL && overwriting && !append)
{
if (backup_copy)
(void)mch_copy_file_attribute(wfname, backup);
else
(void)mch_copy_file_attribute(backup, wfname);
}
if (!overwriting && !append)
{
if (buf->b_ffname != NULL)
(void)mch_copy_file_attribute(buf->b_ffname, wfname);
/* Should copy resource fork */
}
#endif
#ifdef FEAT_CRYPT
if (*buf->b_p_key != NUL && !filtering)
{
char_u *header;
int header_len;
buf->b_cryptstate = crypt_create_for_writing(
crypt_get_method_nr(buf),
buf->b_p_key, &header, &header_len);
if (buf->b_cryptstate == NULL || header == NULL)
end = 0;
else
{
/* Write magic number, so that Vim knows how this file is
* encrypted when reading it back. */
write_info.bw_buf = header;
write_info.bw_len = header_len;
write_info.bw_flags = FIO_NOCONVERT;
if (buf_write_bytes(&write_info) == FAIL)
end = 0;
wb_flags |= FIO_ENCRYPTED;
vim_free(header);
}
}
#endif
}
errmsg = NULL;
write_info.bw_buf = buffer;
nchars = 0;
/* use "++bin", "++nobin" or 'binary' */
if (eap != NULL && eap->force_bin != 0)
write_bin = (eap->force_bin == FORCE_BIN);
else
write_bin = buf->b_p_bin;
#ifdef FEAT_MBYTE
/*
* The BOM is written just after the encryption magic number.
* Skip it when appending and the file already existed, the BOM only
* makes sense at the start of the file.
*/
if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
{
write_info.bw_len = make_bom(buffer, fenc);
if (write_info.bw_len > 0)
{
/* don't convert, do encryption */
write_info.bw_flags = FIO_NOCONVERT | wb_flags;
if (buf_write_bytes(&write_info) == FAIL)
end = 0;
else
nchars += write_info.bw_len;
}
}
write_info.bw_start_lnum = start;
#endif
#ifdef FEAT_PERSISTENT_UNDO
write_undo_file = (buf->b_p_udf
&& overwriting
&& !append
&& !filtering
&& reset_changed
&& !checking_conversion);
if (write_undo_file)
/* Prepare for computing the hash value of the text. */
sha256_start(&sha_ctx);
#endif
write_info.bw_len = bufsize;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = wb_flags;
#endif
fileformat = get_fileformat_force(buf, eap);
s = buffer;
len = 0;
for (lnum = start; lnum <= end; ++lnum)
{
/*
* The next while loop is done once for each character written.
* Keep it fast!
*/
ptr = ml_get_buf(buf, lnum, FALSE) - 1;
#ifdef FEAT_PERSISTENT_UNDO
if (write_undo_file)
sha256_update(&sha_ctx, ptr + 1,
(UINT32_T)(STRLEN(ptr + 1) + 1));
#endif
while ((c = *++ptr) != NUL)
{
if (c == NL)
*s = NUL; /* replace newlines with NULs */
else if (c == CAR && fileformat == EOL_MAC)
*s = NL; /* Mac: replace CRs with NLs */
else
*s = c;
++s;
if (++len != bufsize)
continue;
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
#ifdef FEAT_MBYTE
write_info.bw_start_lnum = lnum;
#endif
}
/* write failed or last line has no EOL: stop here */
if (end == 0
|| (lnum == end
&& (write_bin || !buf->b_p_fixeol)
&& (lnum == buf->b_no_eol_lnum
|| (lnum == buf->b_ml.ml_line_count
&& !buf->b_p_eol))))
{
++lnum; /* written the line, count it */
no_eol = TRUE;
break;
}
if (fileformat == EOL_UNIX)
*s++ = NL;
else
{
*s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
if (fileformat == EOL_DOS) /* write CR-NL */
{
if (++len == bufsize)
{
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
}
*s++ = NL;
}
}
if (++len == bufsize && end)
{
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
ui_breakcheck();
if (got_int)
{
end = 0; /* Interrupted, break loop */
break;
}
}
#ifdef VMS
/*
* On VMS there is a problem: newlines get added when writing
* blocks at a time. Fix it by writing a line at a time.
* This is much slower!
* Explanation: VAX/DECC RTL insists that records in some RMS
* structures end with a newline (carriage return) character, and
* if they don't it adds one.
* With other RMS structures it works perfect without this fix.
*/
if (buf->b_fab_rfm == FAB$C_VFC
|| ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
{
int b2write;
buf->b_fab_mrs = (buf->b_fab_mrs == 0
? MIN(4096, bufsize)
: MIN(buf->b_fab_mrs, bufsize));
b2write = len;
while (b2write > 0)
{
write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0;
break;
}
b2write -= MIN(b2write, buf->b_fab_mrs);
}
write_info.bw_len = bufsize;
nchars += len;
s = buffer;
len = 0;
}
#endif
}
if (len > 0 && end > 0)
{
write_info.bw_len = len;
if (buf_write_bytes(&write_info) == FAIL)
end = 0; /* write error */
nchars += len;
}
/* Stop when writing done or an error was encountered. */
if (!checking_conversion || end == 0)
break;
/* If no error happened until now, writing should be ok, so loop to
* really write the buffer. */
}
/* If we started writing, finish writing. Also when an error was
* encountered. */
if (!checking_conversion)
{
#if defined(UNIX) && defined(HAVE_FSYNC)
/*
* On many journalling file systems there is a bug that causes both the
* original and the backup file to be lost when halting the system
* right after writing the file. That's because only the meta-data is
* journalled. Syncing the file slows down the system, but assures it
* has been written to disk and we don't lose it.
* For a device do try the fsync() but don't complain if it does not
* work (could be a pipe).
* If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
*/
if (p_fs && fsync(fd) != 0 && !device)
{
errmsg = (char_u *)_("E667: Fsync failed");
end = 0;
}
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
/* Probably need to set the security context. */
if (!backup_copy)
mch_copy_sec(backup, wfname);
#endif
#ifdef UNIX
/* When creating a new file, set its owner/group to that of the
* original file. Get the new device and inode number. */
if (backup != NULL && !backup_copy)
{
# ifdef HAVE_FCHOWN
stat_T st;
/* don't change the owner when it's already OK, some systems remove
* permission or ACL stuff */
if (mch_stat((char *)wfname, &st) < 0
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid)
{
ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
if (perm >= 0) /* set permission again, may have changed */
(void)mch_setperm(wfname, perm);
}
# endif
buf_setino(buf);
}
else if (!buf->b_dev_valid)
/* Set the inode when creating a new file. */
buf_setino(buf);
#endif
if (close(fd) != 0)
{
errmsg = (char_u *)_("E512: Close failed");
end = 0;
}
#ifdef UNIX
if (made_writable)
perm &= ~0200; /* reset 'w' bit for security reasons */
#endif
if (perm >= 0) /* set perm. of new file same as old file */
(void)mch_setperm(wfname, perm);
#ifdef HAVE_ACL
/*
* Probably need to set the ACL before changing the user (can't set the
* ACL on a file the user doesn't own).
* On Solaris, with ZFS and the aclmode property set to "discard" (the
* default), chmod() discards all part of a file's ACL that don't
* represent the mode of the file. It's non-trivial for us to discover
* whether we're in that situation, so we simply always re-set the ACL.
*/
# ifndef HAVE_SOLARIS_ZFS_ACL
if (!backup_copy)
# endif
mch_set_acl(wfname, acl);
#endif
#ifdef FEAT_CRYPT
if (buf->b_cryptstate != NULL)
{
crypt_free_state(buf->b_cryptstate);
buf->b_cryptstate = NULL;
}
#endif
#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
if (wfname != fname)
{
/*
* The file was written to a temp file, now it needs to be
* converted with 'charconvert' to (overwrite) the output file.
*/
if (end != 0)
{
if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
fenc, wfname, fname) == FAIL)
{
write_info.bw_conv_error = TRUE;
end = 0;
}
}
mch_remove(wfname);
vim_free(wfname);
}
#endif
}
if (end == 0)
{
/*
* Error encountered.
*/
if (errmsg == NULL)
{
#ifdef FEAT_MBYTE
if (write_info.bw_conv_error)
{
if (write_info.bw_conv_error_lnum == 0)
errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
else
{
errmsg_allocated = TRUE;
errmsg = alloc(300);
vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
(long)write_info.bw_conv_error_lnum);
}
}
else
#endif
if (got_int)
errmsg = (char_u *)_(e_interr);
else
errmsg = (char_u *)_("E514: write error (file system full?)");
}
/*
* If we have a backup file, try to put it in place of the new file,
* because the new file is probably corrupt. This avoids losing the
* original file when trying to make a backup when writing the file a
* second time.
* When "backup_copy" is set we need to copy the backup over the new
* file. Otherwise rename the backup file.
* If this is OK, don't give the extra warning message.
*/
if (backup != NULL)
{
if (backup_copy)
{
/* This may take a while, if we were interrupted let the user
* know we got the message. */
if (got_int)
{
MSG(_(e_interr));
out_flush();
}
if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
{
if ((write_info.bw_fd = mch_open((char *)fname,
O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
perm & 0777)) >= 0)
{
/* copy the file. */
write_info.bw_buf = smallbuf;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = FIO_NOCONVERT;
#endif
while ((write_info.bw_len = read_eintr(fd, smallbuf,
SMBUFSIZE)) > 0)
if (buf_write_bytes(&write_info) == FAIL)
break;
if (close(write_info.bw_fd) >= 0
&& write_info.bw_len == 0)
end = 1; /* success */
}
close(fd); /* ignore errors for closing read file */
}
}
else
{
if (vim_rename(backup, fname) == 0)
end = 1;
}
}
goto fail;
}
lnum -= start; /* compute number of written lines */
--no_wait_return; /* may wait for return now */
#if !(defined(UNIX) || defined(VMS))
fname = sfname; /* use shortname now, for the messages */
#endif
if (!filtering)
{
msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
c = FALSE;
#ifdef FEAT_MBYTE
if (write_info.bw_conv_error)
{
STRCAT(IObuff, _(" CONVERSION ERROR"));
c = TRUE;
if (write_info.bw_conv_error_lnum != 0)
vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
(long)write_info.bw_conv_error_lnum);
}
else if (notconverted)
{
STRCAT(IObuff, _("[NOT converted]"));
c = TRUE;
}
else if (converted)
{
STRCAT(IObuff, _("[converted]"));
c = TRUE;
}
#endif
if (device)
{
STRCAT(IObuff, _("[Device]"));
c = TRUE;
}
else if (newfile)
{
STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
c = TRUE;
}
if (no_eol)
{
msg_add_eol();
c = TRUE;
}
/* may add [unix/dos/mac] */
if (msg_add_fileformat(fileformat))
c = TRUE;
#ifdef FEAT_CRYPT
if (wb_flags & FIO_ENCRYPTED)
{
crypt_append_msg(buf);
c = TRUE;
}
#endif
msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
if (!shortmess(SHM_WRITE))
{
if (append)
STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
else
STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
}
set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
}
/* When written everything correctly: reset 'modified'. Unless not
* writing to the original file and '+' is not in 'cpoptions'. */
if (reset_changed && whole && !append
#ifdef FEAT_MBYTE
&& !write_info.bw_conv_error
#endif
&& (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
)
{
unchanged(buf, TRUE);
#ifdef FEAT_AUTOCMD
/* b:changedtick is always incremented in unchanged() but that
* should not trigger a TextChanged event. */
if (last_changedtick + 1 == CHANGEDTICK(buf)
&& last_changedtick_buf == buf)
last_changedtick = CHANGEDTICK(buf);
#endif
u_unchanged(buf);
u_update_save_nr(buf);
}
/*
* If written to the current file, update the timestamp of the swap file
* and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
*/
if (overwriting)
{
ml_timestamp(buf);
if (append)
buf->b_flags &= ~BF_NEW;
else
buf->b_flags &= ~BF_WRITE_MASK;
}
/*
* If we kept a backup until now, and we are in patch mode, then we make
* the backup file our 'original' file.
*/
if (*p_pm && dobackup)
{
char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
fname, p_pm, FALSE);
if (backup != NULL)
{
stat_T st;
/*
* If the original file does not exist yet
* the current backup file becomes the original file
*/
if (org == NULL)
EMSG(_("E205: Patchmode: can't save original file"));
else if (mch_stat(org, &st) < 0)
{
vim_rename(backup, (char_u *)org);
vim_free(backup); /* don't delete the file */
backup = NULL;
#ifdef UNIX
set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
#endif
}
}
/*
* If there is no backup file, remember that a (new) file was
* created.
*/
else
{
int empty_fd;
if (org == NULL
|| (empty_fd = mch_open(org,
O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
perm < 0 ? 0666 : (perm & 0777))) < 0)
EMSG(_("E206: patchmode: can't touch empty original file"));
else
close(empty_fd);
}
if (org != NULL)
{
mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
vim_free(org);
}
}
/*
* Remove the backup unless 'backup' option is set
*/
if (!p_bk && backup != NULL && mch_remove(backup) != 0)
EMSG(_("E207: Can't delete backup file"));
#ifdef FEAT_SUN_WORKSHOP
if (usingSunWorkShop)
workshop_file_saved((char *) ffname);
#endif
goto nofail;
/*
* Finish up. We get here either after failure or success.
*/
fail:
--no_wait_return; /* may wait for return now */
nofail:
/* Done saving, we accept changed buffer warnings again */
buf->b_saving = FALSE;
vim_free(backup);
if (buffer != smallbuf)
vim_free(buffer);
#ifdef FEAT_MBYTE
vim_free(fenc_tofree);
vim_free(write_info.bw_conv_buf);
# ifdef USE_ICONV
if (write_info.bw_iconv_fd != (iconv_t)-1)
{
iconv_close(write_info.bw_iconv_fd);
write_info.bw_iconv_fd = (iconv_t)-1;
}
# endif
#endif
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
if (errmsg != NULL)
{
int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
attr = HL_ATTR(HLF_E); /* set highlight for error messages */
msg_add_fname(buf,
#ifndef UNIX
sfname
#else
fname
#endif
); /* put file name in IObuff with quotes */
if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
/* If the error message has the form "is ...", put the error number in
* front of the file name. */
if (errnum != NULL)
{
STRMOVE(IObuff + numlen, IObuff);
mch_memmove(IObuff, errnum, (size_t)numlen);
}
STRCAT(IObuff, errmsg);
emsg(IObuff);
if (errmsg_allocated)
vim_free(errmsg);
retval = FAIL;
if (end == 0)
{
MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
attr | MSG_HIST);
MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
attr | MSG_HIST);
/* Update the timestamp to avoid an "overwrite changed file"
* prompt when writing again. */
if (mch_stat((char *)fname, &st_old) >= 0)
{
buf_store_time(buf, &st_old, fname);
buf->b_mtime_read = buf->b_mtime;
}
}
}
msg_scroll = msg_save;
#ifdef FEAT_PERSISTENT_UNDO
/*
* When writing the whole file and 'undofile' is set, also write the undo
* file.
*/
if (retval == OK && write_undo_file)
{
char_u hash[UNDO_HASH_SIZE];
sha256_finish(&sha_ctx, hash);
u_write_undo(NULL, FALSE, buf, hash);
}
#endif
#ifdef FEAT_AUTOCMD
#ifdef FEAT_EVAL
if (!should_abort(retval))
#else
if (!got_int)
#endif
{
aco_save_T aco;
curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
/*
* Apply POST autocommands.
* Careful: The autocommands may call buf_write() recursively!
*/
aucmd_prepbuf(&aco, buf);
if (append)
apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
FALSE, curbuf, eap);
else if (filtering)
apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
FALSE, curbuf, eap);
else if (reset_changed && whole)
apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
FALSE, curbuf, eap);
else
apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
FALSE, curbuf, eap);
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
#ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
retval = FALSE;
#endif
}
#endif
got_int |= prev_got_int;
return retval;
}
/*
* Set the name of the current buffer. Use when the buffer doesn't have a
* name and a ":r" or ":w" command with a file name is used.
*/
static int
set_rw_fname(char_u *fname, char_u *sfname)
{
#ifdef FEAT_AUTOCMD
buf_T *buf = curbuf;
/* It's like the unnamed buffer is deleted.... */
if (curbuf->b_p_bl)
apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
if (curbuf != buf)
{
/* We are in another buffer now, don't do the renaming. */
EMSG(_(e_auchangedbuf));
return FAIL;
}
#endif
if (setfname(curbuf, fname, sfname, FALSE) == OK)
curbuf->b_flags |= BF_NOTEDITED;
#ifdef FEAT_AUTOCMD
/* ....and a new named one is created */
apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
if (curbuf->b_p_bl)
apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
/* Do filetype detection now if 'filetype' is empty. */
if (*curbuf->b_p_ft == NUL)
{
if (au_has_group((char_u *)"filetypedetect"))
(void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
do_modelines(0);
}
#endif
return OK;
}
/*
* Put file name into IObuff with quotes.
*/
void
msg_add_fname(buf_T *buf, char_u *fname)
{
if (fname == NULL)
fname = (char_u *)"-stdin-";
home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
IObuff[0] = '"';
STRCAT(IObuff, "\" ");
}
/*
* Append message for text mode to IObuff.
* Return TRUE if something appended.
*/
static int
msg_add_fileformat(int eol_type)
{
#ifndef USE_CRNL
if (eol_type == EOL_DOS)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
return TRUE;
}
#endif
#ifndef USE_CR
if (eol_type == EOL_MAC)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
return TRUE;
}
#endif
#if defined(USE_CRNL) || defined(USE_CR)
if (eol_type == EOL_UNIX)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
return TRUE;
}
#endif
return FALSE;
}
/*
* Append line and character count to IObuff.
*/
void
msg_add_lines(
int insert_space,
long lnum,
off_T nchars)
{
char_u *p;
p = IObuff + STRLEN(IObuff);
if (insert_space)
*p++ = ' ';
if (shortmess(SHM_LINES))
vim_snprintf((char *)p, IOSIZE - (p - IObuff),
"%ldL, %lldC", lnum, (varnumber_T)nchars);
else
{
if (lnum == 1)
STRCPY(p, _("1 line, "));
else
sprintf((char *)p, _("%ld lines, "), lnum);
p += STRLEN(p);
if (nchars == 1)
STRCPY(p, _("1 character"));
else
vim_snprintf((char *)p, IOSIZE - (p - IObuff),
_("%lld characters"), (varnumber_T)nchars);
}
}
/*
* Append message for missing line separator to IObuff.
*/
static void
msg_add_eol(void)
{
STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
}
/*
* Check modification time of file, before writing to it.
* The size isn't checked, because using a tool like "gzip" takes care of
* using the same timestamp but can't set the size.
*/
static int
check_mtime(buf_T *buf, stat_T *st)
{
if (buf->b_mtime_read != 0
&& time_differs((long)st->st_mtime, buf->b_mtime_read))
{
msg_scroll = TRUE; /* don't overwrite messages here */
msg_silent = 0; /* must give this prompt */
/* don't use emsg() here, don't want to flush the buffers */
MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
HL_ATTR(HLF_E));
if (ask_yesno((char_u *)_("Do you really want to write to it"),
TRUE) == 'n')
return FAIL;
msg_scroll = FALSE; /* always overwrite the file message now */
}
return OK;
}
static int
time_differs(long t1, long t2)
{
#if defined(__linux__) || defined(MSWIN)
/* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
* the seconds. Since the roundoff is done when flushing the inode, the
* time may change unexpectedly by one second!!! */
return (t1 - t2 > 1 || t2 - t1 > 1);
#else
return (t1 != t2);
#endif
}
/*
* Call write() to write a number of bytes to the file.
* Handles encryption and 'encoding' conversion.
*
* Return FAIL for failure, OK otherwise.
*/
static int
buf_write_bytes(struct bw_info *ip)
{
int wlen;
char_u *buf = ip->bw_buf; /* data to write */
int len = ip->bw_len; /* length of data */
#ifdef HAS_BW_FLAGS
int flags = ip->bw_flags; /* extra flags */
#endif
#ifdef FEAT_MBYTE
/*
* Skip conversion when writing the crypt magic number or the BOM.
*/
if (!(flags & FIO_NOCONVERT))
{
char_u *p;
unsigned c;
int n;
if (flags & FIO_UTF8)
{
/*
* Convert latin1 in the buffer to UTF-8 in the file.
*/
p = ip->bw_conv_buf; /* translate to buffer */
for (wlen = 0; wlen < len; ++wlen)
p += utf_char2bytes(buf[wlen], p);
buf = ip->bw_conv_buf;
len = (int)(p - ip->bw_conv_buf);
}
else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
{
/*
* Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
* Latin1 chars in the file.
*/
if (flags & FIO_LATIN1)
p = buf; /* translate in-place (can only get shorter) */
else
p = ip->bw_conv_buf; /* translate to buffer */
for (wlen = 0; wlen < len; wlen += n)
{
if (wlen == 0 && ip->bw_restlen != 0)
{
int l;
/* Use remainder of previous call. Append the start of
* buf[] to get a full sequence. Might still be too
* short! */
l = CONV_RESTLEN - ip->bw_restlen;
if (l > len)
l = len;
mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
if (n > ip->bw_restlen + len)
{
/* We have an incomplete byte sequence at the end to
* be written. We can't convert it without the
* remaining bytes. Keep them for the next call. */
if (ip->bw_restlen + len > CONV_RESTLEN)
return FAIL;
ip->bw_restlen += len;
break;
}
if (n > 1)
c = utf_ptr2char(ip->bw_rest);
else
c = ip->bw_rest[0];
if (n >= ip->bw_restlen)
{
n -= ip->bw_restlen;
ip->bw_restlen = 0;
}
else
{
ip->bw_restlen -= n;
mch_memmove(ip->bw_rest, ip->bw_rest + n,
(size_t)ip->bw_restlen);
n = 0;
}
}
else
{
n = utf_ptr2len_len(buf + wlen, len - wlen);
if (n > len - wlen)
{
/* We have an incomplete byte sequence at the end to
* be written. We can't convert it without the
* remaining bytes. Keep them for the next call. */
if (len - wlen > CONV_RESTLEN)
return FAIL;
ip->bw_restlen = len - wlen;
mch_memmove(ip->bw_rest, buf + wlen,
(size_t)ip->bw_restlen);
break;
}
if (n > 1)
c = utf_ptr2char(buf + wlen);
else
c = buf[wlen];
}
if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
{
ip->bw_conv_error = TRUE;
ip->bw_conv_error_lnum = ip->bw_start_lnum;
}
if (c == NL)
++ip->bw_start_lnum;
}
if (flags & FIO_LATIN1)
len = (int)(p - buf);
else
{
buf = ip->bw_conv_buf;
len = (int)(p - ip->bw_conv_buf);
}
}
# ifdef WIN3264
else if (flags & FIO_CODEPAGE)
{
/*
* Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
* codepage.
*/
char_u *from;
size_t fromlen;
char_u *to;
int u8c;
BOOL bad = FALSE;
int needed;
if (ip->bw_restlen > 0)
{
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
}
else
{
from = buf;
fromlen = len;
}
to = ip->bw_conv_buf;
if (enc_utf8)
{
/* Convert from UTF-8 to UCS-2, to the start of the buffer.
* The buffer has been allocated to be big enough. */
while (fromlen > 0)
{
n = (int)utf_ptr2len_len(from, (int)fromlen);
if (n > (int)fromlen) /* incomplete byte sequence */
break;
u8c = utf_ptr2char(from);
*to++ = (u8c & 0xff);
*to++ = (u8c >> 8);
fromlen -= n;
from += n;
}
/* Copy remainder to ip->bw_rest[] to be used for the next
* call. */
if (fromlen > CONV_RESTLEN)
{
/* weird overlong sequence */
ip->bw_conv_error = TRUE;
return FAIL;
}
mch_memmove(ip->bw_rest, from, fromlen);
ip->bw_restlen = (int)fromlen;
}
else
{
/* Convert from enc_codepage to UCS-2, to the start of the
* buffer. The buffer has been allocated to be big enough. */
ip->bw_restlen = 0;
needed = MultiByteToWideChar(enc_codepage,
MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
NULL, 0);
if (needed == 0)
{
/* When conversion fails there may be a trailing byte. */
needed = MultiByteToWideChar(enc_codepage,
MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
NULL, 0);
if (needed == 0)
{
/* Conversion doesn't work. */
ip->bw_conv_error = TRUE;
return FAIL;
}
/* Save the trailing byte for the next call. */
ip->bw_rest[0] = from[fromlen - 1];
ip->bw_restlen = 1;
}
needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
(LPCSTR)from, (int)(fromlen - ip->bw_restlen),
(LPWSTR)to, needed);
if (needed == 0)
{
/* Safety check: Conversion doesn't work. */
ip->bw_conv_error = TRUE;
return FAIL;
}
to += needed * 2;
}
fromlen = to - ip->bw_conv_buf;
buf = to;
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (FIO_GET_CP(flags) == CP_UTF8)
{
/* Convert from UCS-2 to UTF-8, using the remainder of the
* conversion buffer. Fails when out of space. */
for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
{
u8c = *from++;
u8c += (*from++ << 8);
to += utf_char2bytes(u8c, to);
if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
}
len = (int)(to - buf);
}
else
#endif
{
/* Convert from UCS-2 to the codepage, using the remainder of
* the conversion buffer. If the conversion uses the default
* character "0", the data doesn't fit in this encoding, so
* fail. */
len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
(LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
(LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
&bad);
if (bad)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
}
}
# endif
# ifdef MACOS_CONVERT
else if (flags & FIO_MACROMAN)
{
/*
* Convert UTF-8 or latin1 to Apple MacRoman.
*/
char_u *from;
size_t fromlen;
if (ip->bw_restlen > 0)
{
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
}
else
{
from = buf;
fromlen = len;
}
if (enc2macroman(from, fromlen,
ip->bw_conv_buf, &len, ip->bw_conv_buflen,
ip->bw_rest, &ip->bw_restlen) == FAIL)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
buf = ip->bw_conv_buf;
}
# endif
# ifdef USE_ICONV
if (ip->bw_iconv_fd != (iconv_t)-1)
{
const char *from;
size_t fromlen;
char *to;
size_t tolen;
/* Convert with iconv(). */
if (ip->bw_restlen > 0)
{
char *fp;
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
from = fp;
tolen = ip->bw_conv_buflen - fromlen;
}
else
{
from = (const char *)buf;
fromlen = len;
tolen = ip->bw_conv_buflen;
}
to = (char *)ip->bw_conv_buf;
if (ip->bw_first)
{
size_t save_len = tolen;
/* output the initial shift state sequence */
(void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
/* There is a bug in iconv() on Linux (which appears to be
* wide-spread) which sets "to" to NULL and messes up "tolen".
*/
if (to == NULL)
{
to = (char *)ip->bw_conv_buf;
tolen = save_len;
}
ip->bw_first = FALSE;
}
/*
* If iconv() has an error or there is not enough room, fail.
*/
if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
|| fromlen > CONV_RESTLEN)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
/* copy remainder to ip->bw_rest[] to be used for the next call. */
if (fromlen > 0)
mch_memmove(ip->bw_rest, (void *)from, fromlen);
ip->bw_restlen = (int)fromlen;
buf = ip->bw_conv_buf;
len = (int)((char_u *)to - ip->bw_conv_buf);
}
# endif
}
#endif /* FEAT_MBYTE */
if (ip->bw_fd < 0)
/* Only checking conversion, which is OK if we get here. */
return OK;
#ifdef FEAT_CRYPT
if (flags & FIO_ENCRYPTED)
{
/* Encrypt the data. Do it in-place if possible, otherwise use an
* allocated buffer. */
if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
{
crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
}
else
{
char_u *outbuf;
len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
if (len == 0)
return OK; /* Crypt layer is buffering, will flush later. */
wlen = write_eintr(ip->bw_fd, outbuf, len);
vim_free(outbuf);
return (wlen < len) ? FAIL : OK;
}
}
#endif
wlen = write_eintr(ip->bw_fd, buf, len);
return (wlen < len) ? FAIL : OK;
}
#ifdef FEAT_MBYTE
/*
* Convert a Unicode character to bytes.
* Return TRUE for an error, FALSE when it's OK.
*/
static int
ucs2bytes(
unsigned c, /* in: character */
char_u **pp, /* in/out: pointer to result */
int flags) /* FIO_ flags */
{
char_u *p = *pp;
int error = FALSE;
int cc;
if (flags & FIO_UCS4)
{
if (flags & FIO_ENDIAN_L)
{
*p++ = c;
*p++ = (c >> 8);
*p++ = (c >> 16);
*p++ = (c >> 24);
}
else
{
*p++ = (c >> 24);
*p++ = (c >> 16);
*p++ = (c >> 8);
*p++ = c;
}
}
else if (flags & (FIO_UCS2 | FIO_UTF16))
{
if (c >= 0x10000)
{
if (flags & FIO_UTF16)
{
/* Make two words, ten bits of the character in each. First
* word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
c -= 0x10000;
if (c >= 0x100000)
error = TRUE;
cc = ((c >> 10) & 0x3ff) + 0xd800;
if (flags & FIO_ENDIAN_L)
{
*p++ = cc;
*p++ = ((unsigned)cc >> 8);
}
else
{
*p++ = ((unsigned)cc >> 8);
*p++ = cc;
}
c = (c & 0x3ff) + 0xdc00;
}
else
error = TRUE;
}
if (flags & FIO_ENDIAN_L)
{
*p++ = c;
*p++ = (c >> 8);
}
else
{
*p++ = (c >> 8);
*p++ = c;
}
}
else /* Latin1 */
{
if (c >= 0x100)
{
error = TRUE;
*p++ = 0xBF;
}
else
*p++ = c;
}
*pp = p;
return error;
}
/*
* Return TRUE if file encoding "fenc" requires conversion from or to
* 'encoding'.
*/
static int
need_conversion(char_u *fenc)
{
int same_encoding;
int enc_flags;
int fenc_flags;
if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
{
same_encoding = TRUE;
fenc_flags = 0;
}
else
{
/* Ignore difference between "ansi" and "latin1", "ucs-4" and
* "ucs-4be", etc. */
enc_flags = get_fio_flags(p_enc);
fenc_flags = get_fio_flags(fenc);
same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
}
if (same_encoding)
{
/* Specified encoding matches with 'encoding'. This requires
* conversion when 'encoding' is Unicode but not UTF-8. */
return enc_unicode != 0;
}
/* Encodings differ. However, conversion is not needed when 'enc' is any
* Unicode encoding and the file is UTF-8. */
return !(enc_utf8 && fenc_flags == FIO_UTF8);
}
/*
* Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
* internal conversion.
* if "ptr" is an empty string, use 'encoding'.
*/
static int
get_fio_flags(char_u *ptr)
{
int prop;
if (*ptr == NUL)
ptr = p_enc;
prop = enc_canon_props(ptr);
if (prop & ENC_UNICODE)
{
if (prop & ENC_2BYTE)
{
if (prop & ENC_ENDIAN_L)
return FIO_UCS2 | FIO_ENDIAN_L;
return FIO_UCS2;
}
if (prop & ENC_4BYTE)
{
if (prop & ENC_ENDIAN_L)
return FIO_UCS4 | FIO_ENDIAN_L;
return FIO_UCS4;
}
if (prop & ENC_2WORD)
{
if (prop & ENC_ENDIAN_L)
return FIO_UTF16 | FIO_ENDIAN_L;
return FIO_UTF16;
}
return FIO_UTF8;
}
if (prop & ENC_LATIN1)
return FIO_LATIN1;
/* must be ENC_DBCS, requires iconv() */
return 0;
}
#ifdef WIN3264
/*
* Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
* for the conversion MS-Windows can do for us. Also accept "utf-8".
* Used for conversion between 'encoding' and 'fileencoding'.
*/
static int
get_win_fio_flags(char_u *ptr)
{
int cp;
/* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
if (!enc_utf8 && enc_codepage <= 0)
return 0;
cp = encname2codepage(ptr);
if (cp == 0)
{
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (STRCMP(ptr, "utf-8") == 0)
cp = CP_UTF8;
else
# endif
return 0;
}
return FIO_PUT_CP(cp) | FIO_CODEPAGE;
}
#endif
#ifdef MACOS_CONVERT
/*
* Check "ptr" for a Carbon supported encoding and return the FIO_ flags
* needed for the internal conversion to/from utf-8 or latin1.
*/
static int
get_mac_fio_flags(char_u *ptr)
{
if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
&& (enc_canon_props(ptr) & ENC_MACROMAN))
return FIO_MACROMAN;
return 0;
}
#endif
/*
* Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
* "size" must be at least 2.
* Return the name of the encoding and set "*lenp" to the length.
* Returns NULL when no BOM found.
*/
static char_u *
check_for_bom(
char_u *p,
long size,
int *lenp,
int flags)
{
char *name = NULL;
int len = 2;
if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
&& (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
{
name = "utf-8"; /* EF BB BF */
len = 3;
}
else if (p[0] == 0xff && p[1] == 0xfe)
{
if (size >= 4 && p[2] == 0 && p[3] == 0
&& (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
{
name = "ucs-4le"; /* FF FE 00 00 */
len = 4;
}
else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
name = "ucs-2le"; /* FF FE */
else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
/* utf-16le is preferred, it also works for ucs-2le text */
name = "utf-16le"; /* FF FE */
}
else if (p[0] == 0xfe && p[1] == 0xff
&& (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
{
/* Default to utf-16, it works also for ucs-2 text. */
if (flags == FIO_UCS2)
name = "ucs-2"; /* FE FF */
else
name = "utf-16"; /* FE FF */
}
else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
&& p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
{
name = "ucs-4"; /* 00 00 FE FF */
len = 4;
}
*lenp = len;
return (char_u *)name;
}
/*
* Generate a BOM in "buf[4]" for encoding "name".
* Return the length of the BOM (zero when no BOM).
*/
static int
make_bom(char_u *buf, char_u *name)
{
int flags;
char_u *p;
flags = get_fio_flags(name);
/* Can't put a BOM in a non-Unicode file. */
if (flags == FIO_LATIN1 || flags == 0)
return 0;
if (flags == FIO_UTF8) /* UTF-8 */
{
buf[0] = 0xef;
buf[1] = 0xbb;
buf[2] = 0xbf;
return 3;
}
p = buf;
(void)ucs2bytes(0xfeff, &p, flags);
return (int)(p - buf);
}
#endif
#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* Try to find a shortname by comparing the fullname with the current
* directory.
* Returns "full_path" or pointer into "full_path" if shortened.
*/
char_u *
shorten_fname1(char_u *full_path)
{
char_u *dirname;
char_u *p = full_path;
dirname = alloc(MAXPATHL);
if (dirname == NULL)
return full_path;
if (mch_dirname(dirname, MAXPATHL) == OK)
{
p = shorten_fname(full_path, dirname);
if (p == NULL || *p == NUL)
p = full_path;
}
vim_free(dirname);
return p;
}
#endif
/*
* Try to find a shortname by comparing the fullname with the current
* directory.
* Returns NULL if not shorter name possible, pointer into "full_path"
* otherwise.
*/
char_u *
shorten_fname(char_u *full_path, char_u *dir_name)
{
int len;
char_u *p;
if (full_path == NULL)
return NULL;
len = (int)STRLEN(dir_name);
if (fnamencmp(dir_name, full_path, len) == 0)
{
p = full_path + len;
#if defined(MSWIN)
/*
* MSWIN: when a file is in the root directory, dir_name will end in a
* slash, since C: by itself does not define a specific dir. In this
* case p may already be correct. <negri>
*/
if (!((len > 2) && (*(p - 2) == ':')))
#endif
{
if (vim_ispathsep(*p))
++p;
#ifndef VMS /* the path separator is always part of the path */
else
p = NULL;
#endif
}
}
#if defined(MSWIN)
/*
* When using a file in the current drive, remove the drive name:
* "A:\dir\file" -> "\dir\file". This helps when moving a session file on
* a floppy from "A:\dir" to "B:\dir".
*/
else if (len > 3
&& TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
&& full_path[1] == ':'
&& vim_ispathsep(full_path[2]))
p = full_path + 2;
#endif
else
p = NULL;
return p;
}
/*
* Shorten filenames for all buffers.
* When "force" is TRUE: Use full path from now on for files currently being
* edited, both for file name and swap file name. Try to shorten the file
* names a bit, if safe to do so.
* When "force" is FALSE: Only try to shorten absolute file names.
* For buffers that have buftype "nofile" or "scratch": never change the file
* name.
*/
void
shorten_fnames(int force)
{
char_u dirname[MAXPATHL];
buf_T *buf;
char_u *p;
mch_dirname(dirname, MAXPATHL);
FOR_ALL_BUFFERS(buf)
{
if (buf->b_fname != NULL
#ifdef FEAT_QUICKFIX
&& !bt_nofile(buf)
#endif
&& !path_with_url(buf->b_fname)
&& (force
|| buf->b_sfname == NULL
|| mch_isFullName(buf->b_sfname)))
{
vim_free(buf->b_sfname);
buf->b_sfname = NULL;
p = shorten_fname(buf->b_ffname, dirname);
if (p != NULL)
{
buf->b_sfname = vim_strsave(p);
buf->b_fname = buf->b_sfname;
}
if (p == NULL || buf->b_fname == NULL)
buf->b_fname = buf->b_ffname;
}
/* Always make the swap file name a full path, a "nofile" buffer may
* also have a swap file. */
mf_fullname(buf->b_ml.ml_mfp);
}
status_redraw_all();
redraw_tabline = TRUE;
}
#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
|| defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MAC) \
|| defined(PROTO)
/*
* Shorten all filenames in "fnames[count]" by current directory.
*/
void
shorten_filenames(char_u **fnames, int count)
{
int i;
char_u dirname[MAXPATHL];
char_u *p;
if (fnames == NULL || count < 1)
return;
mch_dirname(dirname, sizeof(dirname));
for (i = 0; i < count; ++i)
{
if ((p = shorten_fname(fnames[i], dirname)) != NULL)
{
/* shorten_fname() returns pointer in given "fnames[i]". If free
* "fnames[i]" first, "p" becomes invalid. So we need to copy
* "p" first then free fnames[i]. */
p = vim_strsave(p);
vim_free(fnames[i]);
fnames[i] = p;
}
}
}
#endif
/*
* add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
* fo_o_h.ext for MSDOS or when shortname option set.
*
* Assumed that fname is a valid name found in the filesystem we assure that
* the return value is a different name and ends in 'ext'.
* "ext" MUST be at most 4 characters long if it starts with a dot, 3
* characters otherwise.
* Space for the returned name is allocated, must be freed later.
* Returns NULL when out of memory.
*/
char_u *
modname(
char_u *fname,
char_u *ext,
int prepend_dot) /* may prepend a '.' to file name */
{
return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
fname, ext, prepend_dot);
}
char_u *
buf_modname(
int shortname, /* use 8.3 file name */
char_u *fname,
char_u *ext,
int prepend_dot) /* may prepend a '.' to file name */
{
char_u *retval;
char_u *s;
char_u *e;
char_u *ptr;
int fnamelen, extlen;
extlen = (int)STRLEN(ext);
/*
* If there is no file name we must get the name of the current directory
* (we need the full path in case :cd is used).
*/
if (fname == NULL || *fname == NUL)
{
retval = alloc((unsigned)(MAXPATHL + extlen + 3));
if (retval == NULL)
return NULL;
if (mch_dirname(retval, MAXPATHL) == FAIL ||
(fnamelen = (int)STRLEN(retval)) == 0)
{
vim_free(retval);
return NULL;
}
if (!after_pathsep(retval, retval + fnamelen))
{
retval[fnamelen++] = PATHSEP;
retval[fnamelen] = NUL;
}
prepend_dot = FALSE; /* nothing to prepend a dot to */
}
else
{
fnamelen = (int)STRLEN(fname);
retval = alloc((unsigned)(fnamelen + extlen + 3));
if (retval == NULL)
return NULL;
STRCPY(retval, fname);
#ifdef VMS
vms_remove_version(retval); /* we do not need versions here */
#endif
}
/*
* search backwards until we hit a '/', '\' or ':' replacing all '.'
* by '_' for MSDOS or when shortname option set and ext starts with a dot.
* Then truncate what is after the '/', '\' or ':' to 8 characters for
* MSDOS and 26 characters for AMIGA, a lot more for UNIX.
*/
for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
{
if (*ext == '.'
#ifdef USE_LONG_FNAME
&& (!USE_LONG_FNAME || shortname)
#else
&& shortname
#endif
)
if (*ptr == '.') /* replace '.' by '_' */
*ptr = '_';
if (vim_ispathsep(*ptr))
{
++ptr;
break;
}
}
/* the file name has at most BASENAMELEN characters. */
if (STRLEN(ptr) > (unsigned)BASENAMELEN)
ptr[BASENAMELEN] = '\0';
s = ptr + STRLEN(ptr);
/*
* For 8.3 file names we may have to reduce the length.
*/
#ifdef USE_LONG_FNAME
if (!USE_LONG_FNAME || shortname)
#else
if (shortname)
#endif
{
/*
* If there is no file name, or the file name ends in '/', and the
* extension starts with '.', put a '_' before the dot, because just
* ".ext" is invalid.
*/
if (fname == NULL || *fname == NUL
|| vim_ispathsep(fname[STRLEN(fname) - 1]))
{
if (*ext == '.')
*s++ = '_';
}
/*
* If the extension starts with '.', truncate the base name at 8
* characters
*/
else if (*ext == '.')
{
if ((size_t)(s - ptr) > (size_t)8)
{
s = ptr + 8;
*s = '\0';
}
}
/*
* If the extension doesn't start with '.', and the file name
* doesn't have an extension yet, append a '.'
*/
else if ((e = vim_strchr(ptr, '.')) == NULL)
*s++ = '.';
/*
* If the extension doesn't start with '.', and there already is an
* extension, it may need to be truncated
*/
else if ((int)STRLEN(e) + extlen > 4)
s = e + 4 - extlen;
}
#if defined(USE_LONG_FNAME) || defined(WIN3264)
/*
* If there is no file name, and the extension starts with '.', put a
* '_' before the dot, because just ".ext" may be invalid if it's on a
* FAT partition, and on HPFS it doesn't matter.
*/
else if ((fname == NULL || *fname == NUL) && *ext == '.')
*s++ = '_';
#endif
/*
* Append the extension.
* ext can start with '.' and cannot exceed 3 more characters.
*/
STRCPY(s, ext);
/*
* Prepend the dot.
*/
if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
#ifdef USE_LONG_FNAME
&& USE_LONG_FNAME
#endif
)
{
STRMOVE(e + 1, e);
*e = '.';
}
/*
* Check that, after appending the extension, the file name is really
* different.
*/
if (fname != NULL && STRCMP(fname, retval) == 0)
{
/* we search for a character that can be replaced by '_' */
while (--s >= ptr)
{
if (*s != '_')
{
*s = '_';
break;
}
}
if (s < ptr) /* fname was "________.<ext>", how tricky! */
*ptr = 'v';
}
return retval;
}
/*
* Like fgets(), but if the file line is too long, it is truncated and the
* rest of the line is thrown away. Returns TRUE for end-of-file.
*/
int
vim_fgets(char_u *buf, int size, FILE *fp)
{
char *eof;
#define FGETS_SIZE 200
char tbuf[FGETS_SIZE];
buf[size - 2] = NUL;
#ifdef USE_CR
eof = fgets_cr((char *)buf, size, fp);
#else
eof = fgets((char *)buf, size, fp);
#endif
if (buf[size - 2] != NUL && buf[size - 2] != '\n')
{
buf[size - 1] = NUL; /* Truncate the line */
/* Now throw away the rest of the line: */
do
{
tbuf[FGETS_SIZE - 2] = NUL;
#ifdef USE_CR
ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
#else
ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
#endif
} while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
}
return (eof == NULL);
}
#if defined(USE_CR) || defined(PROTO)
/*
* Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
* Returns TRUE for end-of-file.
* Only used for the Mac, because it's much slower than vim_fgets().
*/
int
tag_fgets(char_u *buf, int size, FILE *fp)
{
int i = 0;
int c;
int eof = FALSE;
for (;;)
{
c = fgetc(fp);
if (c == EOF)
{
eof = TRUE;
break;
}
if (c == '\r')
{
/* Always store a NL for end-of-line. */
if (i < size - 1)
buf[i++] = '\n';
c = fgetc(fp);
if (c != '\n') /* Macintosh format: single CR. */
ungetc(c, fp);
break;
}
if (i < size - 1)
buf[i++] = c;
if (c == '\n')
break;
}
buf[i] = NUL;
return eof;
}
#endif
/*
* rename() only works if both files are on the same file system, this
* function will (attempts to?) copy the file across if rename fails -- webb
* Return -1 for failure, 0 for success.
*/
int
vim_rename(char_u *from, char_u *to)
{
int fd_in;
int fd_out;
int n;
char *errmsg = NULL;
char *buffer;
#ifdef AMIGA
BPTR flock;
#endif
stat_T st;
long perm;
#ifdef HAVE_ACL
vim_acl_T acl; /* ACL from original file */
#endif
int use_tmp_file = FALSE;
/*
* When the names are identical, there is nothing to do. When they refer
* to the same file (ignoring case and slash/backslash differences) but
* the file name differs we need to go through a temp file.
*/
if (fnamecmp(from, to) == 0)
{
if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
use_tmp_file = TRUE;
else
return 0;
}
/*
* Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
*/
if (mch_stat((char *)from, &st) < 0)
return -1;
#ifdef UNIX
{
stat_T st_to;
/* It's possible for the source and destination to be the same file.
* This happens when "from" and "to" differ in case and are on a FAT32
* filesystem. In that case go through a temp file name. */
if (mch_stat((char *)to, &st_to) >= 0
&& st.st_dev == st_to.st_dev
&& st.st_ino == st_to.st_ino)
use_tmp_file = TRUE;
}
#endif
#ifdef WIN3264
{
BY_HANDLE_FILE_INFORMATION info1, info2;
/* It's possible for the source and destination to be the same file.
* In that case go through a temp file name. This makes rename("foo",
* "./foo") a no-op (in a complicated way). */
if (win32_fileinfo(from, &info1) == FILEINFO_OK
&& win32_fileinfo(to, &info2) == FILEINFO_OK
&& info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
&& info1.nFileIndexHigh == info2.nFileIndexHigh
&& info1.nFileIndexLow == info2.nFileIndexLow)
use_tmp_file = TRUE;
}
#endif
if (use_tmp_file)
{
char tempname[MAXPATHL + 1];
/*
* Find a name that doesn't exist and is in the same directory.
* Rename "from" to "tempname" and then rename "tempname" to "to".
*/
if (STRLEN(from) >= MAXPATHL - 5)
return -1;
STRCPY(tempname, from);
for (n = 123; n < 99999; ++n)
{
sprintf((char *)gettail((char_u *)tempname), "%d", n);
if (mch_stat(tempname, &st) < 0)
{
if (mch_rename((char *)from, tempname) == 0)
{
if (mch_rename(tempname, (char *)to) == 0)
return 0;
/* Strange, the second step failed. Try moving the
* file back and return failure. */
mch_rename(tempname, (char *)from);
return -1;
}
/* If it fails for one temp name it will most likely fail
* for any temp name, give up. */
return -1;
}
}
return -1;
}
/*
* Delete the "to" file, this is required on some systems to make the
* mch_rename() work, on other systems it makes sure that we don't have
* two files when the mch_rename() fails.
*/
#ifdef AMIGA
/*
* With MSDOS-compatible filesystems (crossdos, messydos) it is possible
* that the name of the "to" file is the same as the "from" file, even
* though the names are different. To avoid the chance of accidentally
* deleting the "from" file (horror!) we lock it during the remove.
*
* When used for making a backup before writing the file: This should not
* happen with ":w", because startscript() should detect this problem and
* set buf->b_shortname, causing modname() to return a correct ".bak" file
* name. This problem does exist with ":w filename", but then the
* original file will be somewhere else so the backup isn't really
* important. If autoscripting is off the rename may fail.
*/
flock = Lock((UBYTE *)from, (long)ACCESS_READ);
#endif
mch_remove(to);
#ifdef AMIGA
if (flock)
UnLock(flock);
#endif
/*
* First try a normal rename, return if it works.
*/
if (mch_rename((char *)from, (char *)to) == 0)
return 0;
/*
* Rename() failed, try copying the file.
*/
perm = mch_getperm(from);
#ifdef HAVE_ACL
/* For systems that support ACL: get the ACL from the original file. */
acl = mch_get_acl(from);
#endif
fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
if (fd_in == -1)
{
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
/* Create the new file with same permissions as the original. */
fd_out = mch_open((char *)to,
O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
if (fd_out == -1)
{
close(fd_in);
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
buffer = (char *)alloc(BUFSIZE);
if (buffer == NULL)
{
close(fd_out);
close(fd_in);
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
if (write_eintr(fd_out, buffer, n) != n)
{
errmsg = _("E208: Error writing to \"%s\"");
break;
}
vim_free(buffer);
close(fd_in);
if (close(fd_out) < 0)
errmsg = _("E209: Error closing \"%s\"");
if (n < 0)
{
errmsg = _("E210: Error reading \"%s\"");
to = from;
}
#ifndef UNIX /* for Unix mch_open() already set the permission */
mch_setperm(to, perm);
#endif
#ifdef HAVE_ACL
mch_set_acl(to, acl);
mch_free_acl(acl);
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(from, to);
#endif
if (errmsg != NULL)
{
EMSG2(errmsg, to);
return -1;
}
mch_remove(from);
return 0;
}
static int already_warned = FALSE;
/*
* Check if any not hidden buffer has been changed.
* Postpone the check if there are characters in the stuff buffer, a global
* command is being executed, a mapping is being executed or an autocommand is
* busy.
* Returns TRUE if some message was written (screen should be redrawn and
* cursor positioned).
*/
int
check_timestamps(
int focus) /* called for GUI focus event */
{
buf_T *buf;
int didit = 0;
int n;
/* Don't check timestamps while system() or another low-level function may
* cause us to lose and gain focus. */
if (no_check_timestamps > 0)
return FALSE;
/* Avoid doing a check twice. The OK/Reload dialog can cause a focus
* event and we would keep on checking if the file is steadily growing.
* Do check again after typing something. */
if (focus && did_check_timestamps)
{
need_check_timestamps = TRUE;
return FALSE;
}
if (!stuff_empty() || global_busy || !typebuf_typed()
#ifdef FEAT_AUTOCMD
|| autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
#endif
)
need_check_timestamps = TRUE; /* check later */
else
{
++no_wait_return;
did_check_timestamps = TRUE;
already_warned = FALSE;
FOR_ALL_BUFFERS(buf)
{
/* Only check buffers in a window. */
if (buf->b_nwindows > 0)
{
bufref_T bufref;
set_bufref(&bufref, buf);
n = buf_check_timestamp(buf, focus);
if (didit < n)
didit = n;
if (n > 0 && !bufref_valid(&bufref))
{
/* Autocommands have removed the buffer, start at the
* first one again. */
buf = firstbuf;
continue;
}
}
}
--no_wait_return;
need_check_timestamps = FALSE;
if (need_wait_return && didit == 2)
{
/* make sure msg isn't overwritten */
msg_puts((char_u *)"\n");
out_flush();
}
}
return didit;
}
/*
* Move all the lines from buffer "frombuf" to buffer "tobuf".
* Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
* empty.
*/
static int
move_lines(buf_T *frombuf, buf_T *tobuf)
{
buf_T *tbuf = curbuf;
int retval = OK;
linenr_T lnum;
char_u *p;
/* Copy the lines in "frombuf" to "tobuf". */
curbuf = tobuf;
for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
{
p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
{
vim_free(p);
retval = FAIL;
break;
}
vim_free(p);
}
/* Delete all the lines in "frombuf". */
if (retval != FAIL)
{
curbuf = frombuf;
for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
if (ml_delete(lnum, FALSE) == FAIL)
{
/* Oops! We could try putting back the saved lines, but that
* might fail again... */
retval = FAIL;
break;
}
}
curbuf = tbuf;
return retval;
}
/*
* Check if buffer "buf" has been changed.
* Also check if the file for a new buffer unexpectedly appeared.
* return 1 if a changed buffer was found.
* return 2 if a message has been displayed.
* return 0 otherwise.
*/
int
buf_check_timestamp(
buf_T *buf,
int focus UNUSED) /* called for GUI focus event */
{
stat_T st;
int stat_res;
int retval = 0;
char_u *path;
char_u *tbuf;
char *mesg = NULL;
char *mesg2 = "";
int helpmesg = FALSE;
int reload = FALSE;
char *reason;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
int can_reload = FALSE;
#endif
off_T orig_size = buf->b_orig_size;
int orig_mode = buf->b_orig_mode;
#ifdef FEAT_GUI
int save_mouse_correct = need_mouse_correct;
#endif
#ifdef FEAT_AUTOCMD
static int busy = FALSE;
int n;
char_u *s;
bufref_T bufref;
set_bufref(&bufref, buf);
#endif
/* If there is no file name, the buffer is not loaded, 'buftype' is
* set, we are in the middle of a save or being called recursively: ignore
* this buffer. */
if (buf->b_ffname == NULL
|| buf->b_ml.ml_mfp == NULL
|| *buf->b_p_bt != NUL
|| buf->b_saving
#ifdef FEAT_AUTOCMD
|| busy
#endif
#ifdef FEAT_NETBEANS_INTG
|| isNetbeansBuffer(buf)
#endif
#ifdef FEAT_TERMINAL
|| buf->b_term != NULL
#endif
)
return 0;
if ( !(buf->b_flags & BF_NOTEDITED)
&& buf->b_mtime != 0
&& ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
|| time_differs((long)st.st_mtime, buf->b_mtime)
|| st.st_size != buf->b_orig_size
#ifdef HAVE_ST_MODE
|| (int)st.st_mode != buf->b_orig_mode
#else
|| mch_getperm(buf->b_ffname) != buf->b_orig_mode
#endif
))
{
retval = 1;
/* set b_mtime to stop further warnings (e.g., when executing
* FileChangedShell autocmd) */
if (stat_res < 0)
{
buf->b_mtime = 0;
buf->b_orig_size = 0;
buf->b_orig_mode = 0;
}
else
buf_store_time(buf, &st, buf->b_ffname);
/* Don't do anything for a directory. Might contain the file
* explorer. */
if (mch_isdir(buf->b_fname))
;
/*
* If 'autoread' is set, the buffer has no changes and the file still
* exists, reload the buffer. Use the buffer-local option value if it
* was set, the global option value otherwise.
*/
else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
&& !bufIsChanged(buf) && stat_res >= 0)
reload = TRUE;
else
{
if (stat_res < 0)
reason = "deleted";
else if (bufIsChanged(buf))
reason = "conflict";
else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
reason = "changed";
else if (orig_mode != buf->b_orig_mode)
reason = "mode";
else
reason = "time";
#ifdef FEAT_AUTOCMD
/*
* Only give the warning if there are no FileChangedShell
* autocommands.
* Avoid being called recursively by setting "busy".
*/
busy = TRUE;
# ifdef FEAT_EVAL
set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
# endif
++allbuf_lock;
n = apply_autocmds(EVENT_FILECHANGEDSHELL,
buf->b_fname, buf->b_fname, FALSE, buf);
--allbuf_lock;
busy = FALSE;
if (n)
{
if (!bufref_valid(&bufref))
EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
# ifdef FEAT_EVAL
s = get_vim_var_str(VV_FCS_CHOICE);
if (STRCMP(s, "reload") == 0 && *reason != 'd')
reload = TRUE;
else if (STRCMP(s, "ask") == 0)
n = FALSE;
else
# endif
return 2;
}
if (!n)
#endif
{
if (*reason == 'd')
mesg = _("E211: File \"%s\" no longer available");
else
{
helpmesg = TRUE;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
can_reload = TRUE;
#endif
/*
* Check if the file contents really changed to avoid
* giving a warning when only the timestamp was set (e.g.,
* checked out of CVS). Always warn when the buffer was
* changed.
*/
if (reason[2] == 'n')
{
mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
mesg2 = _("See \":help W12\" for more info.");
}
else if (reason[1] == 'h')
{
mesg = _("W11: Warning: File \"%s\" has changed since editing started");
mesg2 = _("See \":help W11\" for more info.");
}
else if (*reason == 'm')
{
mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
mesg2 = _("See \":help W16\" for more info.");
}
else
/* Only timestamp changed, store it to avoid a warning
* in check_mtime() later. */
buf->b_mtime_read = buf->b_mtime;
}
}
}
}
else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
&& vim_fexists(buf->b_ffname))
{
retval = 1;
mesg = _("W13: Warning: File \"%s\" has been created after editing started");
buf->b_flags |= BF_NEW_W;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
can_reload = TRUE;
#endif
}
if (mesg != NULL)
{
path = home_replace_save(buf, buf->b_fname);
if (path != NULL)
{
if (!helpmesg)
mesg2 = "";
tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
+ STRLEN(mesg2) + 2));
sprintf((char *)tbuf, mesg, path);
#ifdef FEAT_EVAL
/* Set warningmsg here, before the unimportant and output-specific
* mesg2 has been appended. */
set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
#endif
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
if (can_reload)
{
if (*mesg2 != NUL)
{
STRCAT(tbuf, "\n");
STRCAT(tbuf, mesg2);
}
if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
(char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
reload = TRUE;
}
else
#endif
if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
{
if (*mesg2 != NUL)
{
STRCAT(tbuf, "; ");
STRCAT(tbuf, mesg2);
}
EMSG(tbuf);
retval = 2;
}
else
{
# ifdef FEAT_AUTOCMD
if (!autocmd_busy)
# endif
{
msg_start();
msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
if (*mesg2 != NUL)
msg_puts_attr((char_u *)mesg2,
HL_ATTR(HLF_W) + MSG_HIST);
msg_clr_eos();
(void)msg_end();
if (emsg_silent == 0)
{
out_flush();
# ifdef FEAT_GUI
if (!focus)
# endif
/* give the user some time to think about it */
ui_delay(1000L, TRUE);
/* don't redraw and erase the message */
redraw_cmdline = FALSE;
}
}
already_warned = TRUE;
}
vim_free(path);
vim_free(tbuf);
}
}
if (reload)
{
/* Reload the buffer. */
buf_reload(buf, orig_mode);
#ifdef FEAT_PERSISTENT_UNDO
if (buf->b_p_udf && buf->b_ffname != NULL)
{
char_u hash[UNDO_HASH_SIZE];
buf_T *save_curbuf = curbuf;
/* Any existing undo file is unusable, write it now. */
curbuf = buf;
u_compute_hash(hash);
u_write_undo(NULL, FALSE, buf, hash);
curbuf = save_curbuf;
}
#endif
}
#ifdef FEAT_AUTOCMD
/* Trigger FileChangedShell when the file was changed in any way. */
if (bufref_valid(&bufref) && retval != 0)
(void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
buf->b_fname, buf->b_fname, FALSE, buf);
#endif
#ifdef FEAT_GUI
/* restore this in case an autocommand has set it; it would break
* 'mousefocus' */
need_mouse_correct = save_mouse_correct;
#endif
return retval;
}
/*
* Reload a buffer that is already loaded.
* Used when the file was changed outside of Vim.
* "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
* buf->b_orig_mode may have been reset already.
*/
void
buf_reload(buf_T *buf, int orig_mode)
{
exarg_T ea;
pos_T old_cursor;
linenr_T old_topline;
int old_ro = buf->b_p_ro;
buf_T *savebuf;
bufref_T bufref;
int saved = OK;
aco_save_T aco;
int flags = READ_NEW;
/* set curwin/curbuf for "buf" and save some things */
aucmd_prepbuf(&aco, buf);
/* We only want to read the text from the file, not reset the syntax
* highlighting, clear marks, diff status, etc. Force the fileformat
* and encoding to be the same. */
if (prep_exarg(&ea, buf) == OK)
{
old_cursor = curwin->w_cursor;
old_topline = curwin->w_topline;
if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
{
/* Save all the text, so that the reload can be undone.
* Sync first so that this is a separate undo-able action. */
u_sync(FALSE);
saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
flags |= READ_KEEP_UNDO;
}
/*
* To behave like when a new file is edited (matters for
* BufReadPost autocommands) we first need to delete the current
* buffer contents. But if reading the file fails we should keep
* the old contents. Can't use memory only, the file might be
* too big. Use a hidden buffer to move the buffer contents to.
*/
if (BUFEMPTY() || saved == FAIL)
savebuf = NULL;
else
{
/* Allocate a buffer without putting it in the buffer list. */
savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
set_bufref(&bufref, savebuf);
if (savebuf != NULL && buf == curbuf)
{
/* Open the memline. */
curbuf = savebuf;
curwin->w_buffer = savebuf;
saved = ml_open(curbuf);
curbuf = buf;
curwin->w_buffer = buf;
}
if (savebuf == NULL || saved == FAIL || buf != curbuf
|| move_lines(buf, savebuf) == FAIL)
{
EMSG2(_("E462: Could not prepare for reloading \"%s\""),
buf->b_fname);
saved = FAIL;
}
}
if (saved == OK)
{
curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
#ifdef FEAT_AUTOCMD
keep_filetype = TRUE; /* don't detect 'filetype' */
#endif
if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
(linenr_T)0,
(linenr_T)MAXLNUM, &ea, flags) != OK)
{
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!aborting())
#endif
EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
{
/* Put the text back from the save buffer. First
* delete any lines that readfile() added. */
while (!BUFEMPTY())
if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
break;
(void)move_lines(savebuf, buf);
}
}
else if (buf == curbuf) /* "buf" still valid */
{
/* Mark the buffer as unmodified and free undo info. */
unchanged(buf, TRUE);
if ((flags & READ_KEEP_UNDO) == 0)
{
u_blockfree(buf);
u_clearall(buf);
}
else
{
/* Mark all undo states as changed. */
u_unchanged(curbuf);
}
}
}
vim_free(ea.cmd);
if (savebuf != NULL && bufref_valid(&bufref))
wipe_buffer(savebuf, FALSE);
#ifdef FEAT_DIFF
/* Invalidate diff info if necessary. */
diff_invalidate(curbuf);
#endif
/* Restore the topline and cursor position and check it (lines may
* have been removed). */
if (old_topline > curbuf->b_ml.ml_line_count)
curwin->w_topline = curbuf->b_ml.ml_line_count;
else
curwin->w_topline = old_topline;
curwin->w_cursor = old_cursor;
check_cursor();
update_topline();
#ifdef FEAT_AUTOCMD
keep_filetype = FALSE;
#endif
#ifdef FEAT_FOLDING
{
win_T *wp;
tabpage_T *tp;
/* Update folds unless they are defined manually. */
FOR_ALL_TAB_WINDOWS(tp, wp)
if (wp->w_buffer == curwin->w_buffer
&& !foldmethodIsManual(wp))
foldUpdateAll(wp);
}
#endif
/* If the mode didn't change and 'readonly' was set, keep the old
* value; the user probably used the ":view" command. But don't
* reset it, might have had a read error. */
if (orig_mode == curbuf->b_orig_mode)
curbuf->b_p_ro |= old_ro;
/* Modelines must override settings done by autocommands. */
do_modelines(0);
}
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
/* Careful: autocommands may have made "buf" invalid! */
}
void
buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
{
buf->b_mtime = (long)st->st_mtime;
buf->b_orig_size = st->st_size;
#ifdef HAVE_ST_MODE
buf->b_orig_mode = (int)st->st_mode;
#else
buf->b_orig_mode = mch_getperm(fname);
#endif
}
/*
* Adjust the line with missing eol, used for the next write.
* Used for do_filter(), when the input lines for the filter are deleted.
*/
void
write_lnum_adjust(linenr_T offset)
{
if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
curbuf->b_no_eol_lnum += offset;
}
#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
/*
* Delete "name" and everything in it, recursively.
* return 0 for succes, -1 if some file was not deleted.
*/
int
delete_recursive(char_u *name)
{
int result = 0;
char_u **files;
int file_count;
int i;
char_u *exp;
/* A symbolic link to a directory itself is deleted, not the directory it
* points to. */
if (
# if defined(UNIX) || defined(WIN32)
mch_isrealdir(name)
# else
mch_isdir(name)
# endif
)
{
vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
exp = vim_strsave(NameBuff);
if (exp == NULL)
return -1;
if (gen_expand_wildcards(1, &exp, &file_count, &files,
EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
{
for (i = 0; i < file_count; ++i)
if (delete_recursive(files[i]) != 0)
result = -1;
FreeWild(file_count, files);
}
else
result = -1;
vim_free(exp);
(void)mch_rmdir(name);
}
else
result = mch_remove(name) == 0 ? 0 : -1;
return result;
}
#endif
#if defined(TEMPDIRNAMES) || defined(PROTO)
static long temp_count = 0; /* Temp filename counter. */
/*
* Delete the temp directory and all files it contains.
*/
void
vim_deltempdir(void)
{
if (vim_tempdir != NULL)
{
/* remove the trailing path separator */
gettail(vim_tempdir)[-1] = NUL;
delete_recursive(vim_tempdir);
vim_free(vim_tempdir);
vim_tempdir = NULL;
}
}
/*
* Directory "tempdir" was created. Expand this name to a full path and put
* it in "vim_tempdir". This avoids that using ":cd" would confuse us.
* "tempdir" must be no longer than MAXPATHL.
*/
static void
vim_settempdir(char_u *tempdir)
{
char_u *buf;
buf = alloc((unsigned)MAXPATHL + 2);
if (buf != NULL)
{
if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
STRCPY(buf, tempdir);
add_pathsep(buf);
vim_tempdir = vim_strsave(buf);
vim_free(buf);
}
}
#endif
/*
* vim_tempname(): Return a unique name that can be used for a temp file.
*
* The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
* guaranteed to NOT be created.
*
* The returned pointer is to allocated memory.
* The returned pointer is NULL if no valid name was found.
*/
char_u *
vim_tempname(
int extra_char UNUSED, /* char to use in the name instead of '?' */
int keep UNUSED)
{
#ifdef USE_TMPNAM
char_u itmp[L_tmpnam]; /* use tmpnam() */
#else
char_u itmp[TEMPNAMELEN];
#endif
#ifdef TEMPDIRNAMES
static char *(tempdirs[]) = {TEMPDIRNAMES};
int i;
# ifndef EEXIST
stat_T st;
# endif
/*
* This will create a directory for private use by this instance of Vim.
* This is done once, and the same directory is used for all temp files.
* This method avoids security problems because of symlink attacks et al.
* It's also a bit faster, because we only need to check for an existing
* file when creating the directory and not for each temp file.
*/
if (vim_tempdir == NULL)
{
/*
* Try the entries in TEMPDIRNAMES to create the temp directory.
*/
for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
{
# ifndef HAVE_MKDTEMP
size_t itmplen;
long nr;
long off;
# endif
/* Expand $TMP, leave room for "/v1100000/999999999".
* Skip the directory check if the expansion fails. */
expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
if (itmp[0] != '$' && mch_isdir(itmp))
{
/* directory exists */
add_pathsep(itmp);
# ifdef HAVE_MKDTEMP
{
# if defined(UNIX) || defined(VMS)
/* Make sure the umask doesn't remove the executable bit.
* "repl" has been reported to use "177". */
mode_t umask_save = umask(077);
# endif
/* Leave room for filename */
STRCAT(itmp, "vXXXXXX");
if (mkdtemp((char *)itmp) != NULL)
vim_settempdir(itmp);
# if defined(UNIX) || defined(VMS)
(void)umask(umask_save);
# endif
}
# else
/* Get an arbitrary number of up to 6 digits. When it's
* unlikely that it already exists it will be faster,
* otherwise it doesn't matter. The use of mkdir() avoids any
* security problems because of the predictable number. */
nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
itmplen = STRLEN(itmp);
/* Try up to 10000 different values until we find a name that
* doesn't exist. */
for (off = 0; off < 10000L; ++off)
{
int r;
# if defined(UNIX) || defined(VMS)
mode_t umask_save;
# endif
sprintf((char *)itmp + itmplen, "v%ld", nr + off);
# ifndef EEXIST
/* If mkdir() does not set errno to EEXIST, check for
* existing file here. There is a race condition then,
* although it's fail-safe. */
if (mch_stat((char *)itmp, &st) >= 0)
continue;
# endif
# if defined(UNIX) || defined(VMS)
/* Make sure the umask doesn't remove the executable bit.
* "repl" has been reported to use "177". */
umask_save = umask(077);
# endif
r = vim_mkdir(itmp, 0700);
# if defined(UNIX) || defined(VMS)
(void)umask(umask_save);
# endif
if (r == 0)
{
vim_settempdir(itmp);
break;
}
# ifdef EEXIST
/* If the mkdir() didn't fail because the file/dir exists,
* we probably can't create any dir here, try another
* place. */
if (errno != EEXIST)
# endif
break;
}
# endif /* HAVE_MKDTEMP */
if (vim_tempdir != NULL)
break;
}
}
}
if (vim_tempdir != NULL)
{
/* There is no need to check if the file exists, because we own the
* directory and nobody else creates a file in it. */
sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
return vim_strsave(itmp);
}
return NULL;
#else /* TEMPDIRNAMES */
# ifdef WIN3264
char szTempFile[_MAX_PATH + 1];
char buf4[4];
char_u *retval;
char_u *p;
STRCPY(itmp, "");
if (GetTempPath(_MAX_PATH, szTempFile) == 0)
{
szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
szTempFile[1] = NUL;
}
strcpy(buf4, "VIM");
buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
return NULL;
if (!keep)
/* GetTempFileName() will create the file, we don't want that */
(void)DeleteFile((LPSTR)itmp);
/* Backslashes in a temp file name cause problems when filtering with
* "sh". NOTE: This also checks 'shellcmdflag' to help those people who
* didn't set 'shellslash'. */
retval = vim_strsave(itmp);
if (*p_shcf == '-' || p_ssl)
for (p = retval; *p; ++p)
if (*p == '\\')
*p = '/';
return retval;
# else /* WIN3264 */
# ifdef USE_TMPNAM
char_u *p;
/* tmpnam() will make its own name */
p = tmpnam((char *)itmp);
if (p == NULL || *p == NUL)
return NULL;
# else
char_u *p;
# ifdef VMS_TEMPNAM
/* mktemp() is not working on VMS. It seems to be
* a do-nothing function. Therefore we use tempnam().
*/
sprintf((char *)itmp, "VIM%c", extra_char);
p = (char_u *)tempnam("tmp:", (char *)itmp);
if (p != NULL)
{
/* VMS will use '.LIS' if we don't explicitly specify an extension,
* and VIM will then be unable to find the file later */
STRCPY(itmp, p);
STRCAT(itmp, ".txt");
free(p);
}
else
return NULL;
# else
STRCPY(itmp, TEMPNAME);
if ((p = vim_strchr(itmp, '?')) != NULL)
*p = extra_char;
if (mktemp((char *)itmp) == NULL)
return NULL;
# endif
# endif
return vim_strsave(itmp);
# endif /* WIN3264 */
#endif /* TEMPDIRNAMES */
}
#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
/*
* Convert all backslashes in fname to forward slashes in-place, unless when
* it looks like a URL.
*/
void
forward_slash(char_u *fname)
{
char_u *p;
if (path_with_url(fname))
return;
for (p = fname; *p != NUL; ++p)
# ifdef FEAT_MBYTE
/* The Big5 encoding can have '\' in the trail byte. */
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
++p;
else
# endif
if (*p == '\\')
*p = '/';
}
#endif
/*
* Code for automatic commands.
*
* Only included when "FEAT_AUTOCMD" has been defined.
*/
#if defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* The autocommands are stored in a list for each event.
* Autocommands for the same pattern, that are consecutive, are joined
* together, to avoid having to match the pattern too often.
* The result is an array of Autopat lists, which point to AutoCmd lists:
*
* first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
* Autopat.cmds Autopat.cmds
* | |
* V V
* AutoCmd.next AutoCmd.next
* | |
* V V
* AutoCmd.next NULL
* |
* V
* NULL
*
* first_autopat[1] --> Autopat.next --> NULL
* Autopat.cmds
* |
* V
* AutoCmd.next
* |
* V
* NULL
* etc.
*
* The order of AutoCmds is important, this is the order in which they were
* defined and will have to be executed.
*/
typedef struct AutoCmd
{
char_u *cmd; /* The command to be executed (NULL
when command has been removed) */
char nested; /* If autocommands nest here */
char last; /* last command in list */
#ifdef FEAT_EVAL
scid_T scriptID; /* script ID where defined */
#endif
struct AutoCmd *next; /* Next AutoCmd in list */
} AutoCmd;
typedef struct AutoPat
{
char_u *pat; /* pattern as typed (NULL when pattern
has been removed) */
regprog_T *reg_prog; /* compiled regprog for pattern */
AutoCmd *cmds; /* list of commands to do */
struct AutoPat *next; /* next AutoPat in AutoPat list */
int group; /* group ID */
int patlen; /* strlen() of pat */
int buflocal_nr; /* !=0 for buffer-local AutoPat */
char allow_dirs; /* Pattern may match whole path */
char last; /* last pattern for apply_autocmds() */
} AutoPat;
static struct event_name
{
char *name; /* event name */
event_T event; /* event number */
} event_names[] =
{
{"BufAdd", EVENT_BUFADD},
{"BufCreate", EVENT_BUFADD},
{"BufDelete", EVENT_BUFDELETE},
{"BufEnter", EVENT_BUFENTER},
{"BufFilePost", EVENT_BUFFILEPOST},
{"BufFilePre", EVENT_BUFFILEPRE},
{"BufHidden", EVENT_BUFHIDDEN},
{"BufLeave", EVENT_BUFLEAVE},
{"BufNew", EVENT_BUFNEW},
{"BufNewFile", EVENT_BUFNEWFILE},
{"BufRead", EVENT_BUFREADPOST},
{"BufReadCmd", EVENT_BUFREADCMD},
{"BufReadPost", EVENT_BUFREADPOST},
{"BufReadPre", EVENT_BUFREADPRE},
{"BufUnload", EVENT_BUFUNLOAD},
{"BufWinEnter", EVENT_BUFWINENTER},
{"BufWinLeave", EVENT_BUFWINLEAVE},
{"BufWipeout", EVENT_BUFWIPEOUT},
{"BufWrite", EVENT_BUFWRITEPRE},
{"BufWritePost", EVENT_BUFWRITEPOST},
{"BufWritePre", EVENT_BUFWRITEPRE},
{"BufWriteCmd", EVENT_BUFWRITECMD},
{"CmdlineEnter", EVENT_CMDLINEENTER},
{"CmdlineLeave", EVENT_CMDLINELEAVE},
{"CmdwinEnter", EVENT_CMDWINENTER},
{"CmdwinLeave", EVENT_CMDWINLEAVE},
{"CmdUndefined", EVENT_CMDUNDEFINED},
{"ColorScheme", EVENT_COLORSCHEME},
{"CompleteDone", EVENT_COMPLETEDONE},
{"CursorHold", EVENT_CURSORHOLD},
{"CursorHoldI", EVENT_CURSORHOLDI},
{"CursorMoved", EVENT_CURSORMOVED},
{"CursorMovedI", EVENT_CURSORMOVEDI},
{"EncodingChanged", EVENT_ENCODINGCHANGED},
{"FileEncoding", EVENT_ENCODINGCHANGED},
{"FileAppendPost", EVENT_FILEAPPENDPOST},
{"FileAppendPre", EVENT_FILEAPPENDPRE},
{"FileAppendCmd", EVENT_FILEAPPENDCMD},
{"FileChangedShell",EVENT_FILECHANGEDSHELL},
{"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
{"FileChangedRO", EVENT_FILECHANGEDRO},
{"FileReadPost", EVENT_FILEREADPOST},
{"FileReadPre", EVENT_FILEREADPRE},
{"FileReadCmd", EVENT_FILEREADCMD},
{"FileType", EVENT_FILETYPE},
{"FileWritePost", EVENT_FILEWRITEPOST},
{"FileWritePre", EVENT_FILEWRITEPRE},
{"FileWriteCmd", EVENT_FILEWRITECMD},
{"FilterReadPost", EVENT_FILTERREADPOST},
{"FilterReadPre", EVENT_FILTERREADPRE},
{"FilterWritePost", EVENT_FILTERWRITEPOST},
{"FilterWritePre", EVENT_FILTERWRITEPRE},
{"FocusGained", EVENT_FOCUSGAINED},
{"FocusLost", EVENT_FOCUSLOST},
{"FuncUndefined", EVENT_FUNCUNDEFINED},
{"GUIEnter", EVENT_GUIENTER},
{"GUIFailed", EVENT_GUIFAILED},
{"InsertChange", EVENT_INSERTCHANGE},
{"InsertEnter", EVENT_INSERTENTER},
{"InsertLeave", EVENT_INSERTLEAVE},
{"InsertCharPre", EVENT_INSERTCHARPRE},
{"MenuPopup", EVENT_MENUPOPUP},
{"OptionSet", EVENT_OPTIONSET},
{"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
{"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
{"QuitPre", EVENT_QUITPRE},
{"RemoteReply", EVENT_REMOTEREPLY},
{"SessionLoadPost", EVENT_SESSIONLOADPOST},
{"ShellCmdPost", EVENT_SHELLCMDPOST},
{"ShellFilterPost", EVENT_SHELLFILTERPOST},
{"SourcePre", EVENT_SOURCEPRE},
{"SourceCmd", EVENT_SOURCECMD},
{"SpellFileMissing",EVENT_SPELLFILEMISSING},
{"StdinReadPost", EVENT_STDINREADPOST},
{"StdinReadPre", EVENT_STDINREADPRE},
{"SwapExists", EVENT_SWAPEXISTS},
{"Syntax", EVENT_SYNTAX},
{"TabNew", EVENT_TABNEW},
{"TabClosed", EVENT_TABCLOSED},
{"TabEnter", EVENT_TABENTER},
{"TabLeave", EVENT_TABLEAVE},
{"TermChanged", EVENT_TERMCHANGED},
{"TermResponse", EVENT_TERMRESPONSE},
{"TextChanged", EVENT_TEXTCHANGED},
{"TextChangedI", EVENT_TEXTCHANGEDI},
{"User", EVENT_USER},
{"VimEnter", EVENT_VIMENTER},
{"VimLeave", EVENT_VIMLEAVE},
{"VimLeavePre", EVENT_VIMLEAVEPRE},
{"WinNew", EVENT_WINNEW},
{"WinEnter", EVENT_WINENTER},
{"WinLeave", EVENT_WINLEAVE},
{"VimResized", EVENT_VIMRESIZED},
{NULL, (event_T)0}
};
static AutoPat *first_autopat[NUM_EVENTS] =
{
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
/*
* struct used to keep status while executing autocommands for an event.
*/
typedef struct AutoPatCmd
{
AutoPat *curpat; /* next AutoPat to examine */
AutoCmd *nextcmd; /* next AutoCmd to execute */
int group; /* group being used */
char_u *fname; /* fname to match with */
char_u *sfname; /* sfname to match with */
char_u *tail; /* tail of fname */
event_T event; /* current event */
int arg_bufnr; /* initially equal to <abuf>, set to zero when
buf is deleted */
struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
} AutoPatCmd;
static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
/*
* augroups stores a list of autocmd group names.
*/
static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
/* use get_deleted_augroup() to get this */
static char_u *deleted_augroup = NULL;
/*
* The ID of the current group. Group 0 is the default one.
*/
static int current_augroup = AUGROUP_DEFAULT;
static int au_need_clean = FALSE; /* need to delete marked patterns */
static void show_autocmd(AutoPat *ap, event_T event);
static void au_remove_pat(AutoPat *ap);
static void au_remove_cmds(AutoPat *ap);
static void au_cleanup(void);
static int au_new_group(char_u *name);
static void au_del_group(char_u *name);
static event_T event_name2nr(char_u *start, char_u **end);
static char_u *event_nr2name(event_T event);
static char_u *find_end_event(char_u *arg, int have_group);
static int event_ignored(event_T event);
static int au_get_grouparg(char_u **argp);
static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
#endif
static event_T last_event;
static int last_group;
static int autocmd_blocked = 0; /* block all autocmds */
static char_u *
get_deleted_augroup(void)
{
if (deleted_augroup == NULL)
deleted_augroup = (char_u *)_("--Deleted--");
return deleted_augroup;
}
/*
* Show the autocommands for one AutoPat.
*/
static void
show_autocmd(AutoPat *ap, event_T event)
{
AutoCmd *ac;
/* Check for "got_int" (here and at various places below), which is set
* when "q" has been hit for the "--more--" prompt */
if (got_int)
return;
if (ap->pat == NULL) /* pattern has been removed */
return;
msg_putchar('\n');
if (got_int)
return;
if (event != last_event || ap->group != last_group)
{
if (ap->group != AUGROUP_DEFAULT)
{
if (AUGROUP_NAME(ap->group) == NULL)
msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
else
msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
msg_puts((char_u *)" ");
}
msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
last_event = event;
last_group = ap->group;
msg_putchar('\n');
if (got_int)
return;
}
msg_col = 4;
msg_outtrans(ap->pat);
for (ac = ap->cmds; ac != NULL; ac = ac->next)
{
if (ac->cmd != NULL) /* skip removed commands */
{
if (msg_col >= 14)
msg_putchar('\n');
msg_col = 14;
if (got_int)
return;
msg_outtrans(ac->cmd);
#ifdef FEAT_EVAL
if (p_verbose > 0)
last_set_msg(ac->scriptID);
#endif
if (got_int)
return;
if (ac->next != NULL)
{
msg_putchar('\n');
if (got_int)
return;
}
}
}
}
/*
* Mark an autocommand pattern for deletion.
*/
static void
au_remove_pat(AutoPat *ap)
{
vim_free(ap->pat);
ap->pat = NULL;
ap->buflocal_nr = -1;
au_need_clean = TRUE;
}
/*
* Mark all commands for a pattern for deletion.
*/
static void
au_remove_cmds(AutoPat *ap)
{
AutoCmd *ac;
for (ac = ap->cmds; ac != NULL; ac = ac->next)
{
vim_free(ac->cmd);
ac->cmd = NULL;
}
au_need_clean = TRUE;
}
/*
* Cleanup autocommands and patterns that have been deleted.
* This is only done when not executing autocommands.
*/
static void
au_cleanup(void)
{
AutoPat *ap, **prev_ap;
AutoCmd *ac, **prev_ac;
event_T event;
if (autocmd_busy || !au_need_clean)
return;
/* loop over all events */
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
{
/* loop over all autocommand patterns */
prev_ap = &(first_autopat[(int)event]);
for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
{
/* loop over all commands for this pattern */
prev_ac = &(ap->cmds);
for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
{
/* remove the command if the pattern is to be deleted or when
* the command has been marked for deletion */
if (ap->pat == NULL || ac->cmd == NULL)
{
*prev_ac = ac->next;
vim_free(ac->cmd);
vim_free(ac);
}
else
prev_ac = &(ac->next);
}
/* remove the pattern if it has been marked for deletion */
if (ap->pat == NULL)
{
*prev_ap = ap->next;
vim_regfree(ap->reg_prog);
vim_free(ap);
}
else
prev_ap = &(ap->next);
}
}
au_need_clean = FALSE;
}
/*
* Called when buffer is freed, to remove/invalidate related buffer-local
* autocmds.
*/
void
aubuflocal_remove(buf_T *buf)
{
AutoPat *ap;
event_T event;
AutoPatCmd *apc;
/* invalidate currently executing autocommands */
for (apc = active_apc_list; apc; apc = apc->next)
if (buf->b_fnum == apc->arg_bufnr)
apc->arg_bufnr = 0;
/* invalidate buflocals looping through events */
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
/* loop over all autocommand patterns */
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->buflocal_nr == buf->b_fnum)
{
au_remove_pat(ap);
if (p_verbose >= 6)
{
verbose_enter();
smsg((char_u *)
_("auto-removing autocommand: %s <buffer=%d>"),
event_nr2name(event), buf->b_fnum);
verbose_leave();
}
}
au_cleanup();
}
/*
* Add an autocmd group name.
* Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
*/
static int
au_new_group(char_u *name)
{
int i;
i = au_find_group(name);
if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
{
/* First try using a free entry. */
for (i = 0; i < augroups.ga_len; ++i)
if (AUGROUP_NAME(i) == NULL)
break;
if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
return AUGROUP_ERROR;
AUGROUP_NAME(i) = vim_strsave(name);
if (AUGROUP_NAME(i) == NULL)
return AUGROUP_ERROR;
if (i == augroups.ga_len)
++augroups.ga_len;
}
return i;
}
static void
au_del_group(char_u *name)
{
int i;
i = au_find_group(name);
if (i == AUGROUP_ERROR) /* the group doesn't exist */
EMSG2(_("E367: No such group: \"%s\""), name);
else if (i == current_augroup)
EMSG(_("E936: Cannot delete the current group"));
else
{
event_T event;
AutoPat *ap;
int in_use = FALSE;
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
{
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->group == i && ap->pat != NULL)
{
give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
in_use = TRUE;
event = NUM_EVENTS;
break;
}
}
vim_free(AUGROUP_NAME(i));
if (in_use)
{
AUGROUP_NAME(i) = get_deleted_augroup();
}
else
AUGROUP_NAME(i) = NULL;
}
}
/*
* Find the ID of an autocmd group name.
* Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
*/
static int
au_find_group(char_u *name)
{
int i;
for (i = 0; i < augroups.ga_len; ++i)
if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
&& STRCMP(AUGROUP_NAME(i), name) == 0)
return i;
return AUGROUP_ERROR;
}
/*
* Return TRUE if augroup "name" exists.
*/
int
au_has_group(char_u *name)
{
return au_find_group(name) != AUGROUP_ERROR;
}
/*
* ":augroup {name}".
*/
void
do_augroup(char_u *arg, int del_group)
{
int i;
if (del_group)
{
if (*arg == NUL)
EMSG(_(e_argreq));
else
au_del_group(arg);
}
else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
current_augroup = AUGROUP_DEFAULT;
else if (*arg) /* ":aug xxx": switch to group xxx */
{
i = au_new_group(arg);
if (i != AUGROUP_ERROR)
current_augroup = i;
}
else /* ":aug": list the group names */
{
msg_start();
for (i = 0; i < augroups.ga_len; ++i)
{
if (AUGROUP_NAME(i) != NULL)
{
msg_puts(AUGROUP_NAME(i));
msg_puts((char_u *)" ");
}
}
msg_clr_eos();
msg_end();
}
}
#if defined(EXITFREE) || defined(PROTO)
void
free_all_autocmds(void)
{
int i;
char_u *s;
for (current_augroup = -1; current_augroup < augroups.ga_len;
++current_augroup)
do_autocmd((char_u *)"", TRUE);
for (i = 0; i < augroups.ga_len; ++i)
{
s = ((char_u **)(augroups.ga_data))[i];
if (s != get_deleted_augroup())
vim_free(s);
}
ga_clear(&augroups);
}
#endif
/*
* Return the event number for event name "start".
* Return NUM_EVENTS if the event name was not found.
* Return a pointer to the next event name in "end".
*/
static event_T
event_name2nr(char_u *start, char_u **end)
{
char_u *p;
int i;
int len;
/* the event name ends with end of line, '|', a blank or a comma */
for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
;
for (i = 0; event_names[i].name != NULL; ++i)
{
len = (int)STRLEN(event_names[i].name);
if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
break;
}
if (*p == ',')
++p;
*end = p;
if (event_names[i].name == NULL)
return NUM_EVENTS;
return event_names[i].event;
}
/*
* Return the name for event "event".
*/
static char_u *
event_nr2name(event_T event)
{
int i;
for (i = 0; event_names[i].name != NULL; ++i)
if (event_names[i].event == event)
return (char_u *)event_names[i].name;
return (char_u *)"Unknown";
}
/*
* Scan over the events. "*" stands for all events.
*/
static char_u *
find_end_event(
char_u *arg,
int have_group) /* TRUE when group name was found */
{
char_u *pat;
char_u *p;
if (*arg == '*')
{
if (arg[1] && !VIM_ISWHITE(arg[1]))
{
EMSG2(_("E215: Illegal character after *: %s"), arg);
return NULL;
}
pat = arg + 1;
}
else
{
for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
{
if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
{
if (have_group)
EMSG2(_("E216: No such event: %s"), pat);
else
EMSG2(_("E216: No such group or event: %s"), pat);
return NULL;
}
}
}
return pat;
}
/*
* Return TRUE if "event" is included in 'eventignore'.
*/
static int
event_ignored(event_T event)
{
char_u *p = p_ei;
while (*p != NUL)
{
if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
return TRUE;
if (event_name2nr(p, &p) == event)
return TRUE;
}
return FALSE;
}
/*
* Return OK when the contents of p_ei is valid, FAIL otherwise.
*/
int
check_ei(void)
{
char_u *p = p_ei;
while (*p)
{
if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
{
p += 3;
if (*p == ',')
++p;
}
else if (event_name2nr(p, &p) == NUM_EVENTS)
return FAIL;
}
return OK;
}
# if defined(FEAT_SYN_HL) || defined(PROTO)
/*
* Add "what" to 'eventignore' to skip loading syntax highlighting for every
* buffer loaded into the window. "what" must start with a comma.
* Returns the old value of 'eventignore' in allocated memory.
*/
char_u *
au_event_disable(char *what)
{
char_u *new_ei;
char_u *save_ei;
save_ei = vim_strsave(p_ei);
if (save_ei != NULL)
{
new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
if (new_ei != NULL)
{
if (*what == ',' && *p_ei == NUL)
STRCPY(new_ei, what + 1);
else
STRCAT(new_ei, what);
set_string_option_direct((char_u *)"ei", -1, new_ei,
OPT_FREE, SID_NONE);
vim_free(new_ei);
}
}
return save_ei;
}
void
au_event_restore(char_u *old_ei)
{
if (old_ei != NULL)
{
set_string_option_direct((char_u *)"ei", -1, old_ei,
OPT_FREE, SID_NONE);
vim_free(old_ei);
}
}
# endif /* FEAT_SYN_HL */
/*
* do_autocmd() -- implements the :autocmd command. Can be used in the
* following ways:
*
* :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
* will be automatically executed for <event>
* when editing a file matching <pat>, in
* the current group.
* :autocmd <event> <pat> Show the auto-commands associated with
* <event> and <pat>.
* :autocmd <event> Show the auto-commands associated with
* <event>.
* :autocmd Show all auto-commands.
* :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
* <event> and <pat>, and add the command
* <cmd>, for the current group.
* :autocmd! <event> <pat> Remove all auto-commands associated with
* <event> and <pat> for the current group.
* :autocmd! <event> Remove all auto-commands associated with
* <event> for the current group.
* :autocmd! Remove ALL auto-commands for the current
* group.
*
* Multiple events and patterns may be given separated by commas. Here are
* some examples:
* :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
* :autocmd bufleave * set tw=79 nosmartindent ic infercase
*
* :autocmd * *.c show all autocommands for *.c files.
*
* Mostly a {group} argument can optionally appear before <event>.
*/
void
do_autocmd(char_u *arg_in, int forceit)
{
char_u *arg = arg_in;
char_u *pat;
char_u *envpat = NULL;
char_u *cmd;
event_T event;
int need_free = FALSE;
int nested = FALSE;
int group;
if (*arg == '|')
{
arg = (char_u *)"";
group = AUGROUP_ALL; /* no argument, use all groups */
}
else
{
/*
* Check for a legal group name. If not, use AUGROUP_ALL.
*/
group = au_get_grouparg(&arg);
if (arg == NULL) /* out of memory */
return;
}
/*
* Scan over the events.
* If we find an illegal name, return here, don't do anything.
*/
pat = find_end_event(arg, group != AUGROUP_ALL);
if (pat == NULL)
return;
pat = skipwhite(pat);
if (*pat == '|')
{
pat = (char_u *)"";
cmd = (char_u *)"";
}
else
{
/*
* Scan over the pattern. Put a NUL at the end.
*/
cmd = pat;
while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
cmd++;
if (*cmd)
*cmd++ = NUL;
/* Expand environment variables in the pattern. Set 'shellslash', we want
* forward slashes here. */
if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
{
#ifdef BACKSLASH_IN_FILENAME
int p_ssl_save = p_ssl;
p_ssl = TRUE;
#endif
envpat = expand_env_save(pat);
#ifdef BACKSLASH_IN_FILENAME
p_ssl = p_ssl_save;
#endif
if (envpat != NULL)
pat = envpat;
}
/*
* Check for "nested" flag.
*/
cmd = skipwhite(cmd);
if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
{
nested = TRUE;
cmd = skipwhite(cmd + 6);
}
/*
* Find the start of the commands.
* Expand <sfile> in it.
*/
if (*cmd != NUL)
{
cmd = expand_sfile(cmd);
if (cmd == NULL) /* some error */
return;
need_free = TRUE;
}
}
/*
* Print header when showing autocommands.
*/
if (!forceit && *cmd == NUL)
{
/* Highlight title */
MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
}
/*
* Loop over the events.
*/
last_event = (event_T)-1; /* for listing the event name */
last_group = AUGROUP_ERROR; /* for listing the group name */
if (*arg == '*' || *arg == NUL || *arg == '|')
{
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
if (do_autocmd_event(event, pat,
nested, cmd, forceit, group) == FAIL)
break;
}
else
{
while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
if (do_autocmd_event(event_name2nr(arg, &arg), pat,
nested, cmd, forceit, group) == FAIL)
break;
}
if (need_free)
vim_free(cmd);
vim_free(envpat);
}
/*
* Find the group ID in a ":autocmd" or ":doautocmd" argument.
* The "argp" argument is advanced to the following argument.
*
* Returns the group ID, AUGROUP_ERROR for error (out of memory).
*/
static int
au_get_grouparg(char_u **argp)
{
char_u *group_name;
char_u *p;
char_u *arg = *argp;
int group = AUGROUP_ALL;
for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
;
if (p > arg)
{
group_name = vim_strnsave(arg, (int)(p - arg));
if (group_name == NULL) /* out of memory */
return AUGROUP_ERROR;
group = au_find_group(group_name);
if (group == AUGROUP_ERROR)
group = AUGROUP_ALL; /* no match, use all groups */
else
*argp = skipwhite(p); /* match, skip over group name */
vim_free(group_name);
}
return group;
}
/*
* do_autocmd() for one event.
* If *pat == NUL do for all patterns.
* If *cmd == NUL show entries.
* If forceit == TRUE delete entries.
* If group is not AUGROUP_ALL, only use this group.
*/
static int
do_autocmd_event(
event_T event,
char_u *pat,
int nested,
char_u *cmd,
int forceit,
int group)
{
AutoPat *ap;
AutoPat **prev_ap;
AutoCmd *ac;
AutoCmd **prev_ac;
int brace_level;
char_u *endpat;
int findgroup;
int allgroups;
int patlen;
int is_buflocal;
int buflocal_nr;
char_u buflocal_pat[25]; /* for "<buffer=X>" */
if (group == AUGROUP_ALL)
findgroup = current_augroup;
else
findgroup = group;
allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
/*
* Show or delete all patterns for an event.
*/
if (*pat == NUL)
{
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
{
if (forceit) /* delete the AutoPat, if it's in the current group */
{
if (ap->group == findgroup)
au_remove_pat(ap);
}
else if (group == AUGROUP_ALL || ap->group == group)
show_autocmd(ap, event);
}
}
/*
* Loop through all the specified patterns.
*/
for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
{
/*
* Find end of the pattern.
* Watch out for a comma in braces, like "*.\{obj,o\}".
*/
brace_level = 0;
for (endpat = pat; *endpat && (*endpat != ',' || brace_level
|| (endpat > pat && endpat[-1] == '\\')); ++endpat)
{
if (*endpat == '{')
brace_level++;
else if (*endpat == '}')
brace_level--;
}
if (pat == endpat) /* ignore single comma */
continue;
patlen = (int)(endpat - pat);
/*
* detect special <buflocal[=X]> buffer-local patterns
*/
is_buflocal = FALSE;
buflocal_nr = 0;
if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
&& pat[patlen - 1] == '>')
{
/* "<buffer...>": Error will be printed only for addition.
* printing and removing will proceed silently. */
is_buflocal = TRUE;
if (patlen == 8)
/* "<buffer>" */
buflocal_nr = curbuf->b_fnum;
else if (patlen > 9 && pat[7] == '=')
{
if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
/* "<buffer=abuf>" */
buflocal_nr = autocmd_bufnr;
else if (skipdigits(pat + 8) == pat + patlen - 1)
/* "<buffer=123>" */
buflocal_nr = atoi((char *)pat + 8);
}
}
if (is_buflocal)
{
/* normalize pat into standard "<buffer>#N" form */
sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
pat = buflocal_pat; /* can modify pat and patlen */
patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
}
/*
* Find AutoPat entries with this pattern.
*/
prev_ap = &first_autopat[(int)event];
while ((ap = *prev_ap) != NULL)
{
if (ap->pat != NULL)
{
/* Accept a pattern when:
* - a group was specified and it's that group, or a group was
* not specified and it's the current group, or a group was
* not specified and we are listing
* - the length of the pattern matches
* - the pattern matches.
* For <buffer[=X]>, this condition works because we normalize
* all buffer-local patterns.
*/
if ((allgroups || ap->group == findgroup)
&& ap->patlen == patlen
&& STRNCMP(pat, ap->pat, patlen) == 0)
{
/*
* Remove existing autocommands.
* If adding any new autocmd's for this AutoPat, don't
* delete the pattern from the autopat list, append to
* this list.
*/
if (forceit)
{
if (*cmd != NUL && ap->next == NULL)
{
au_remove_cmds(ap);
break;
}
au_remove_pat(ap);
}
/*
* Show autocmd's for this autopat, or buflocals <buffer=X>
*/
else if (*cmd == NUL)
show_autocmd(ap, event);
/*
* Add autocmd to this autopat, if it's the last one.
*/
else if (ap->next == NULL)
break;
}
}
prev_ap = &ap->next;
}
/*
* Add a new command.
*/
if (*cmd != NUL)
{
/*
* If the pattern we want to add a command to does appear at the
* end of the list (or not is not in the list at all), add the
* pattern at the end of the list.
*/
if (ap == NULL)
{
/* refuse to add buffer-local ap if buffer number is invalid */
if (is_buflocal && (buflocal_nr == 0
|| buflist_findnr(buflocal_nr) == NULL))
{
EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
buflocal_nr);
return FAIL;
}
ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
if (ap == NULL)
return FAIL;
ap->pat = vim_strnsave(pat, patlen);
ap->patlen = patlen;
if (ap->pat == NULL)
{
vim_free(ap);
return FAIL;
}
if (is_buflocal)
{
ap->buflocal_nr = buflocal_nr;
ap->reg_prog = NULL;
}
else
{
char_u *reg_pat;
ap->buflocal_nr = 0;
reg_pat = file_pat_to_reg_pat(pat, endpat,
&ap->allow_dirs, TRUE);
if (reg_pat != NULL)
ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
vim_free(reg_pat);
if (reg_pat == NULL || ap->reg_prog == NULL)
{
vim_free(ap->pat);
vim_free(ap);
return FAIL;
}
}
ap->cmds = NULL;
*prev_ap = ap;
ap->next = NULL;
if (group == AUGROUP_ALL)
ap->group = current_augroup;
else
ap->group = group;
}
/*
* Add the autocmd at the end of the AutoCmd list.
*/
prev_ac = &(ap->cmds);
while ((ac = *prev_ac) != NULL)
prev_ac = &ac->next;
ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
if (ac == NULL)
return FAIL;
ac->cmd = vim_strsave(cmd);
#ifdef FEAT_EVAL
ac->scriptID = current_SID;
#endif
if (ac->cmd == NULL)
{
vim_free(ac);
return FAIL;
}
ac->next = NULL;
*prev_ac = ac;
ac->nested = nested;
}
}
au_cleanup(); /* may really delete removed patterns/commands now */
return OK;
}
/*
* Implementation of ":doautocmd [group] event [fname]".
* Return OK for success, FAIL for failure;
*/
int
do_doautocmd(
char_u *arg,
int do_msg, /* give message for no matching autocmds? */
int *did_something)
{
char_u *fname;
int nothing_done = TRUE;
int group;
if (did_something != NULL)
*did_something = FALSE;
/*
* Check for a legal group name. If not, use AUGROUP_ALL.
*/
group = au_get_grouparg(&arg);
if (arg == NULL) /* out of memory */
return FAIL;
if (*arg == '*')
{
EMSG(_("E217: Can't execute autocommands for ALL events"));
return FAIL;
}
/*
* Scan over the events.
* If we find an illegal name, return here, don't do anything.
*/
fname = find_end_event(arg, group != AUGROUP_ALL);
if (fname == NULL)
return FAIL;
fname = skipwhite(fname);
/*
* Loop over the events.
*/
while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
if (apply_autocmds_group(event_name2nr(arg, &arg),
fname, NULL, TRUE, group, curbuf, NULL))
nothing_done = FALSE;
if (nothing_done && do_msg)
MSG(_("No matching autocommands"));
if (did_something != NULL)
*did_something = !nothing_done;
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
}
/*
* ":doautoall": execute autocommands for each loaded buffer.
*/
void
ex_doautoall(exarg_T *eap)
{
int retval;
aco_save_T aco;
buf_T *buf;
bufref_T bufref;
char_u *arg = eap->arg;
int call_do_modelines = check_nomodeline(&arg);
int did_aucmd;
/*
* This is a bit tricky: For some commands curwin->w_buffer needs to be
* equal to curbuf, but for some buffers there may not be a window.
* So we change the buffer for the current window for a moment. This
* gives problems when the autocommands make changes to the list of
* buffers or windows...
*/
FOR_ALL_BUFFERS(buf)
{
if (buf->b_ml.ml_mfp != NULL)
{
/* find a window for this buffer and save some values */
aucmd_prepbuf(&aco, buf);
set_bufref(&bufref, buf);
/* execute the autocommands for this buffer */
retval = do_doautocmd(arg, FALSE, &did_aucmd);
if (call_do_modelines && did_aucmd)
{
/* Execute the modeline settings, but don't set window-local
* options if we are using the current window for another
* buffer. */
do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
}
/* restore the current window */
aucmd_restbuf(&aco);
/* stop if there is some error or buffer was deleted */
if (retval == FAIL || !bufref_valid(&bufref))
break;
}
}
check_cursor(); /* just in case lines got deleted */
}
/*
* Check *argp for <nomodeline>. When it is present return FALSE, otherwise
* return TRUE and advance *argp to after it.
* Thus return TRUE when do_modelines() should be called.
*/
int
check_nomodeline(char_u **argp)
{
if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
{
*argp = skipwhite(*argp + 12);
return FALSE;
}
return TRUE;
}
/*
* Prepare for executing autocommands for (hidden) buffer "buf".
* Search for a visible window containing the current buffer. If there isn't
* one then use "aucmd_win".
* Set "curbuf" and "curwin" to match "buf".
* When FEAT_AUTOCMD is not defined another version is used, see below.
*/
void
aucmd_prepbuf(
aco_save_T *aco, /* structure to save values in */
buf_T *buf) /* new curbuf */
{
win_T *win;
int save_ea;
#ifdef FEAT_AUTOCHDIR
int save_acd;
#endif
/* Find a window that is for the new buffer */
if (buf == curbuf) /* be quick when buf is curbuf */
win = curwin;
else
FOR_ALL_WINDOWS(win)
if (win->w_buffer == buf)
break;
/* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
* back to using the current window. */
if (win == NULL && aucmd_win == NULL)
{
win_alloc_aucmd_win();
if (aucmd_win == NULL)
win = curwin;
}
if (win == NULL && aucmd_win_used)
/* Strange recursive autocommand, fall back to using the current
* window. Expect a few side effects... */
win = curwin;
aco->save_curwin = curwin;
aco->save_curbuf = curbuf;
if (win != NULL)
{
/* There is a window for "buf" in the current tab page, make it the
* curwin. This is preferred, it has the least side effects (esp. if
* "buf" is curbuf). */
aco->use_aucmd_win = FALSE;
curwin = win;
}
else
{
/* There is no window for "buf", use "aucmd_win". To minimize the side
* effects, insert it in the current tab page.
* Anything related to a window (e.g., setting folds) may have
* unexpected results. */
aco->use_aucmd_win = TRUE;
aucmd_win_used = TRUE;
aucmd_win->w_buffer = buf;
aucmd_win->w_s = &buf->b_s;
++buf->b_nwindows;
win_init_empty(aucmd_win); /* set cursor and topline to safe values */
/* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
* win_enter_ext(). */
vim_free(aucmd_win->w_localdir);
aucmd_win->w_localdir = NULL;
aco->globaldir = globaldir;
globaldir = NULL;
/* Split the current window, put the aucmd_win in the upper half.
* We don't want the BufEnter or WinEnter autocommands. */
block_autocmds();
make_snapshot(SNAP_AUCMD_IDX);
save_ea = p_ea;
p_ea = FALSE;
#ifdef FEAT_AUTOCHDIR
/* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
save_acd = p_acd;
p_acd = FALSE;
#endif
(void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
(void)win_comp_pos(); /* recompute window positions */
p_ea = save_ea;
#ifdef FEAT_AUTOCHDIR
p_acd = save_acd;
#endif
unblock_autocmds();
curwin = aucmd_win;
}
curbuf = buf;
aco->new_curwin = curwin;
set_bufref(&aco->new_curbuf, curbuf);
}
/*
* Cleanup after executing autocommands for a (hidden) buffer.
* Restore the window as it was (if possible).
* When FEAT_AUTOCMD is not defined another version is used, see below.
*/
void
aucmd_restbuf(
aco_save_T *aco) /* structure holding saved values */
{
int dummy;
if (aco->use_aucmd_win)
{
--curbuf->b_nwindows;
/* Find "aucmd_win", it can't be closed, but it may be in another tab
* page. Do not trigger autocommands here. */
block_autocmds();
if (curwin != aucmd_win)
{
tabpage_T *tp;
win_T *wp;
FOR_ALL_TAB_WINDOWS(tp, wp)
{
if (wp == aucmd_win)
{
if (tp != curtab)
goto_tabpage_tp(tp, TRUE, TRUE);
win_goto(aucmd_win);
goto win_found;
}
}
}
win_found:
/* Remove the window and frame from the tree of frames. */
(void)winframe_remove(curwin, &dummy, NULL);
win_remove(curwin, NULL);
aucmd_win_used = FALSE;
last_status(FALSE); /* may need to remove last status line */
if (!valid_tabpage_win(curtab))
/* no valid window in current tabpage */
close_tabpage(curtab);
restore_snapshot(SNAP_AUCMD_IDX, FALSE);
(void)win_comp_pos(); /* recompute window positions */
unblock_autocmds();
if (win_valid(aco->save_curwin))
curwin = aco->save_curwin;
else
/* Hmm, original window disappeared. Just use the first one. */
curwin = firstwin;
#ifdef FEAT_EVAL
vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
#endif
curbuf = curwin->w_buffer;
vim_free(globaldir);
globaldir = aco->globaldir;
/* the buffer contents may have changed */
check_cursor();
if (curwin->w_topline > curbuf->b_ml.ml_line_count)
{
curwin->w_topline = curbuf->b_ml.ml_line_count;
#ifdef FEAT_DIFF
curwin->w_topfill = 0;
#endif
}
#if defined(FEAT_GUI)
/* Hide the scrollbars from the aucmd_win and update. */
gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
gui_may_update_scrollbars();
#endif
}
else
{
/* restore curwin */
if (win_valid(aco->save_curwin))
{
/* Restore the buffer which was previously edited by curwin, if
* it was changed, we are still the same window and the buffer is
* valid. */
if (curwin == aco->new_curwin
&& curbuf != aco->new_curbuf.br_buf
&& bufref_valid(&aco->new_curbuf)
&& aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
{
# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
if (curwin->w_s == &curbuf->b_s)
curwin->w_s = &aco->new_curbuf.br_buf->b_s;
# endif
--curbuf->b_nwindows;
curbuf = aco->new_curbuf.br_buf;
curwin->w_buffer = curbuf;
++curbuf->b_nwindows;
}
curwin = aco->save_curwin;
curbuf = curwin->w_buffer;
/* In case the autocommand move the cursor to a position that that
* not exist in curbuf. */
check_cursor();
}
}
}
static int autocmd_nested = FALSE;
/*
* Execute autocommands for "event" and file name "fname".
* Return TRUE if some commands were executed.
*/
int
apply_autocmds(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline */
int force, /* when TRUE, ignore autocmd_busy */
buf_T *buf) /* buffer for <abuf> */
{
return apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, NULL);
}
/*
* Like apply_autocmds(), but with extra "eap" argument. This takes care of
* setting v:filearg.
*/
static int
apply_autocmds_exarg(
event_T event,
char_u *fname,
char_u *fname_io,
int force,
buf_T *buf,
exarg_T *eap)
{
return apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, eap);
}
/*
* Like apply_autocmds(), but handles the caller's retval. If the script
* processing is being aborted or if retval is FAIL when inside a try
* conditional, no autocommands are executed. If otherwise the autocommands
* cause the script to be aborted, retval is set to FAIL.
*/
int
apply_autocmds_retval(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline */
int force, /* when TRUE, ignore autocmd_busy */
buf_T *buf, /* buffer for <abuf> */
int *retval) /* pointer to caller's retval */
{
int did_cmd;
#ifdef FEAT_EVAL
if (should_abort(*retval))
return FALSE;
#endif
did_cmd = apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, NULL);
if (did_cmd
#ifdef FEAT_EVAL
&& aborting()
#endif
)
*retval = FAIL;
return did_cmd;
}
/*
* Return TRUE when there is a CursorHold autocommand defined.
*/
int
has_cursorhold(void)
{
return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
}
/*
* Return TRUE if the CursorHold event can be triggered.
*/
int
trigger_cursorhold(void)
{
int state;
if (!did_cursorhold
&& has_cursorhold()
&& !Recording
&& typebuf.tb_len == 0
#ifdef FEAT_INS_EXPAND
&& !ins_compl_active()
#endif
)
{
state = get_real_state();
if (state == NORMAL_BUSY || (state & INSERT) != 0)
return TRUE;
}
return FALSE;
}
/*
* Return TRUE when there is a CursorMoved autocommand defined.
*/
int
has_cursormoved(void)
{
return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
}
/*
* Return TRUE when there is a CursorMovedI autocommand defined.
*/
int
has_cursormovedI(void)
{
return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
}
/*
* Return TRUE when there is a TextChanged autocommand defined.
*/
int
has_textchanged(void)
{
return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
}
/*
* Return TRUE when there is a TextChangedI autocommand defined.
*/
int
has_textchangedI(void)
{
return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
}
/*
* Return TRUE when there is an InsertCharPre autocommand defined.
*/
int
has_insertcharpre(void)
{
return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
}
/*
* Return TRUE when there is an CmdUndefined autocommand defined.
*/
int
has_cmdundefined(void)
{
return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
}
/*
* Return TRUE when there is an FuncUndefined autocommand defined.
*/
int
has_funcundefined(void)
{
return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
}
/*
* Execute autocommands for "event" and file name "fname".
* Return TRUE if some commands were executed.
*/
static int
apply_autocmds_group(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
use fname */
int force, /* when TRUE, ignore autocmd_busy */
int group, /* group ID, or AUGROUP_ALL */
buf_T *buf, /* buffer for <abuf> */
exarg_T *eap) /* command arguments */
{
char_u *sfname = NULL; /* short file name */
char_u *tail;
int save_changed;
buf_T *old_curbuf;
int retval = FALSE;
char_u *save_sourcing_name;
linenr_T save_sourcing_lnum;
char_u *save_autocmd_fname;
int save_autocmd_fname_full;
int save_autocmd_bufnr;
char_u *save_autocmd_match;
int save_autocmd_busy;
int save_autocmd_nested;
static int nesting = 0;
AutoPatCmd patcmd;
AutoPat *ap;
#ifdef FEAT_EVAL
scid_T save_current_SID;
void *save_funccalp;
char_u *save_cmdarg;
long save_cmdbang;
#endif
static int filechangeshell_busy = FALSE;
#ifdef FEAT_PROFILE
proftime_T wait_time;
#endif
int did_save_redobuff = FALSE;
save_redo_T save_redo;
/*
* Quickly return if there are no autocommands for this event or
* autocommands are blocked.
*/
if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
|| autocmd_blocked > 0)
goto BYPASS_AU;
/*
* When autocommands are busy, new autocommands are only executed when
* explicitly enabled with the "nested" flag.
*/
if (autocmd_busy && !(force || autocmd_nested))
goto BYPASS_AU;
#ifdef FEAT_EVAL
/*
* Quickly return when immediately aborting on error, or when an interrupt
* occurred or an exception was thrown but not caught.
*/
if (aborting())
goto BYPASS_AU;
#endif
/*
* FileChangedShell never nests, because it can create an endless loop.
*/
if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
|| event == EVENT_FILECHANGEDSHELLPOST))
goto BYPASS_AU;
/*
* Ignore events in 'eventignore'.
*/
if (event_ignored(event))
goto BYPASS_AU;
/*
* Allow nesting of autocommands, but restrict the depth, because it's
* possible to create an endless loop.
*/
if (nesting == 10)
{
EMSG(_("E218: autocommand nesting too deep"));
goto BYPASS_AU;
}
/*
* Check if these autocommands are disabled. Used when doing ":all" or
* ":ball".
*/
if ( (autocmd_no_enter
&& (event == EVENT_WINENTER || event == EVENT_BUFENTER))
|| (autocmd_no_leave
&& (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
goto BYPASS_AU;
/*
* Save the autocmd_* variables and info about the current buffer.
*/
save_autocmd_fname = autocmd_fname;
save_autocmd_fname_full = autocmd_fname_full;
save_autocmd_bufnr = autocmd_bufnr;
save_autocmd_match = autocmd_match;
save_autocmd_busy = autocmd_busy;
save_autocmd_nested = autocmd_nested;
save_changed = curbuf->b_changed;
old_curbuf = curbuf;
/*
* Set the file name to be used for <afile>.
* Make a copy to avoid that changing a buffer name or directory makes it
* invalid.
*/
if (fname_io == NULL)
{
if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
autocmd_fname = NULL;
else if (fname != NULL && !ends_excmd(*fname))
autocmd_fname = fname;
else if (buf != NULL)
autocmd_fname = buf->b_ffname;
else
autocmd_fname = NULL;
}
else
autocmd_fname = fname_io;
if (autocmd_fname != NULL)
autocmd_fname = vim_strsave(autocmd_fname);
autocmd_fname_full = FALSE; /* call FullName_save() later */
/*
* Set the buffer number to be used for <abuf>.
*/
if (buf == NULL)
autocmd_bufnr = 0;
else
autocmd_bufnr = buf->b_fnum;
/*
* When the file name is NULL or empty, use the file name of buffer "buf".
* Always use the full path of the file name to match with, in case
* "allow_dirs" is set.
*/
if (fname == NULL || *fname == NUL)
{
if (buf == NULL)
fname = NULL;
else
{
#ifdef FEAT_SYN_HL
if (event == EVENT_SYNTAX)
fname = buf->b_p_syn;
else
#endif
if (event == EVENT_FILETYPE)
fname = buf->b_p_ft;
else
{
if (buf->b_sfname != NULL)
sfname = vim_strsave(buf->b_sfname);
fname = buf->b_ffname;
}
}
if (fname == NULL)
fname = (char_u *)"";
fname = vim_strsave(fname); /* make a copy, so we can change it */
}
else
{
sfname = vim_strsave(fname);
/* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
* ColorScheme or QuickFixCmd* */
if (event == EVENT_FILETYPE
|| event == EVENT_SYNTAX
|| event == EVENT_FUNCUNDEFINED
|| event == EVENT_REMOTEREPLY
|| event == EVENT_SPELLFILEMISSING
|| event == EVENT_QUICKFIXCMDPRE
|| event == EVENT_COLORSCHEME
|| event == EVENT_OPTIONSET
|| event == EVENT_QUICKFIXCMDPOST)
fname = vim_strsave(fname);
else
fname = FullName_save(fname, FALSE);
}
if (fname == NULL) /* out of memory */
{
vim_free(sfname);
retval = FALSE;
goto BYPASS_AU;
}
#ifdef BACKSLASH_IN_FILENAME
/*
* Replace all backslashes with forward slashes. This makes the
* autocommand patterns portable between Unix and MS-DOS.
*/
if (sfname != NULL)
forward_slash(sfname);
forward_slash(fname);
#endif
#ifdef VMS
/* remove version for correct match */
if (sfname != NULL)
vms_remove_version(sfname);
vms_remove_version(fname);
#endif
/*
* Set the name to be used for <amatch>.
*/
autocmd_match = fname;
/* Don't redraw while doing auto commands. */
++RedrawingDisabled;
save_sourcing_name = sourcing_name;
sourcing_name = NULL; /* don't free this one */
save_sourcing_lnum = sourcing_lnum;
sourcing_lnum = 0; /* no line number here */
#ifdef FEAT_EVAL
save_current_SID = current_SID;
# ifdef FEAT_PROFILE
if (do_profiling == PROF_YES)
prof_child_enter(&wait_time); /* doesn't count for the caller itself */
# endif
/* Don't use local function variables, if called from a function */
save_funccalp = save_funccal();
#endif
/*
* When starting to execute autocommands, save the search patterns.
*/
if (!autocmd_busy)
{
save_search_patterns();
#ifdef FEAT_INS_EXPAND
if (!ins_compl_active())
#endif
{
saveRedobuff(&save_redo);
did_save_redobuff = TRUE;
}
did_filetype = keep_filetype;
}
/*
* Note that we are applying autocmds. Some commands need to know.
*/
autocmd_busy = TRUE;
filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
++nesting; /* see matching decrement below */
/* Remember that FileType was triggered. Used for did_filetype(). */
if (event == EVENT_FILETYPE)
did_filetype = TRUE;
tail = gettail(fname);
/* Find first autocommand that matches */
patcmd.curpat = first_autopat[(int)event];
patcmd.nextcmd = NULL;
patcmd.group = group;
patcmd.fname = fname;
patcmd.sfname = sfname;
patcmd.tail = tail;
patcmd.event = event;
patcmd.arg_bufnr = autocmd_bufnr;
patcmd.next = NULL;
auto_next_pat(&patcmd, FALSE);
/* found one, start executing the autocommands */
if (patcmd.curpat != NULL)
{
/* add to active_apc_list */
patcmd.next = active_apc_list;
active_apc_list = &patcmd;
#ifdef FEAT_EVAL
/* set v:cmdarg (only when there is a matching pattern) */
save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
if (eap != NULL)
{
save_cmdarg = set_cmdarg(eap, NULL);
set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
}
else
save_cmdarg = NULL; /* avoid gcc warning */
#endif
retval = TRUE;
/* mark the last pattern, to avoid an endless loop when more patterns
* are added when executing autocommands */
for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
ap->last = FALSE;
ap->last = TRUE;
check_lnums(TRUE); /* make sure cursor and topline are valid */
do_cmdline(NULL, getnextac, (void *)&patcmd,
DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
#ifdef FEAT_EVAL
if (eap != NULL)
{
(void)set_cmdarg(NULL, save_cmdarg);
set_vim_var_nr(VV_CMDBANG, save_cmdbang);
}
#endif
/* delete from active_apc_list */
if (active_apc_list == &patcmd) /* just in case */
active_apc_list = patcmd.next;
}
--RedrawingDisabled;
autocmd_busy = save_autocmd_busy;
filechangeshell_busy = FALSE;
autocmd_nested = save_autocmd_nested;
vim_free(sourcing_name);
sourcing_name = save_sourcing_name;
sourcing_lnum = save_sourcing_lnum;
vim_free(autocmd_fname);
autocmd_fname = save_autocmd_fname;
autocmd_fname_full = save_autocmd_fname_full;
autocmd_bufnr = save_autocmd_bufnr;
autocmd_match = save_autocmd_match;
#ifdef FEAT_EVAL
current_SID = save_current_SID;
restore_funccal(save_funccalp);
# ifdef FEAT_PROFILE
if (do_profiling == PROF_YES)
prof_child_exit(&wait_time);
# endif
#endif
vim_free(fname);
vim_free(sfname);
--nesting; /* see matching increment above */
/*
* When stopping to execute autocommands, restore the search patterns and
* the redo buffer. Free any buffers in the au_pending_free_buf list and
* free any windows in the au_pending_free_win list.
*/
if (!autocmd_busy)
{
restore_search_patterns();
if (did_save_redobuff)
restoreRedobuff(&save_redo);
did_filetype = FALSE;
while (au_pending_free_buf != NULL)
{
buf_T *b = au_pending_free_buf->b_next;
vim_free(au_pending_free_buf);
au_pending_free_buf = b;
}
while (au_pending_free_win != NULL)
{
win_T *w = au_pending_free_win->w_next;
vim_free(au_pending_free_win);
au_pending_free_win = w;
}
}
/*
* Some events don't set or reset the Changed flag.
* Check if still in the same buffer!
*/
if (curbuf == old_curbuf
&& (event == EVENT_BUFREADPOST
|| event == EVENT_BUFWRITEPOST
|| event == EVENT_FILEAPPENDPOST
|| event == EVENT_VIMLEAVE
|| event == EVENT_VIMLEAVEPRE))
{
#ifdef FEAT_TITLE
if (curbuf->b_changed != save_changed)
need_maketitle = TRUE;
#endif
curbuf->b_changed = save_changed;
}
au_cleanup(); /* may really delete removed patterns/commands now */
BYPASS_AU:
/* When wiping out a buffer make sure all its buffer-local autocommands
* are deleted. */
if (event == EVENT_BUFWIPEOUT && buf != NULL)
aubuflocal_remove(buf);
if (retval == OK && event == EVENT_FILETYPE)
au_did_filetype = TRUE;
return retval;
}
# ifdef FEAT_EVAL
static char_u *old_termresponse = NULL;
# endif
/*
* Block triggering autocommands until unblock_autocmd() is called.
* Can be used recursively, so long as it's symmetric.
*/
void
block_autocmds(void)
{
# ifdef FEAT_EVAL
/* Remember the value of v:termresponse. */
if (autocmd_blocked == 0)
old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
# endif
++autocmd_blocked;
}
void
unblock_autocmds(void)
{
--autocmd_blocked;
# ifdef FEAT_EVAL
/* When v:termresponse was set while autocommands were blocked, trigger
* the autocommands now. Esp. useful when executing a shell command
* during startup (vimdiff). */
if (autocmd_blocked == 0
&& get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
# endif
}
int
is_autocmd_blocked(void)
{
return autocmd_blocked != 0;
}
/*
* Find next autocommand pattern that matches.
*/
static void
auto_next_pat(
AutoPatCmd *apc,
int stop_at_last) /* stop when 'last' flag is set */
{
AutoPat *ap;
AutoCmd *cp;
char_u *name;
char *s;
vim_free(sourcing_name);
sourcing_name = NULL;
for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
{
apc->curpat = NULL;
/* Only use a pattern when it has not been removed, has commands and
* the group matches. For buffer-local autocommands only check the
* buffer number. */
if (ap->pat != NULL && ap->cmds != NULL
&& (apc->group == AUGROUP_ALL || apc->group == ap->group))
{
/* execution-condition */
if (ap->buflocal_nr == 0
? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
apc->sfname, apc->tail, ap->allow_dirs))
: ap->buflocal_nr == apc->arg_bufnr)
{
name = event_nr2name(apc->event);
s = _("%s Auto commands for \"%s\"");
sourcing_name = alloc((unsigned)(STRLEN(s)
+ STRLEN(name) + ap->patlen + 1));
if (sourcing_name != NULL)
{
sprintf((char *)sourcing_name, s,
(char *)name, (char *)ap->pat);
if (p_verbose >= 8)
{
verbose_enter();
smsg((char_u *)_("Executing %s"), sourcing_name);
verbose_leave();
}
}
apc->curpat = ap;
apc->nextcmd = ap->cmds;
/* mark last command */
for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
cp->last = FALSE;
cp->last = TRUE;
}
line_breakcheck();
if (apc->curpat != NULL) /* found a match */
break;
}
if (stop_at_last && ap->last)
break;
}
}
/*
* Get next autocommand command.
* Called by do_cmdline() to get the next line for ":if".
* Returns allocated string, or NULL for end of autocommands.
*/
char_u *
getnextac(int c UNUSED, void *cookie, int indent UNUSED)
{
AutoPatCmd *acp = (AutoPatCmd *)cookie;
char_u *retval;
AutoCmd *ac;
/* Can be called again after returning the last line. */
if (acp->curpat == NULL)
return NULL;
/* repeat until we find an autocommand to execute */
for (;;)
{
/* skip removed commands */
while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
if (acp->nextcmd->last)
acp->nextcmd = NULL;
else
acp->nextcmd = acp->nextcmd->next;
if (acp->nextcmd != NULL)
break;
/* at end of commands, find next pattern that matches */
if (acp->curpat->last)
acp->curpat = NULL;
else
acp->curpat = acp->curpat->next;
if (acp->curpat != NULL)
auto_next_pat(acp, TRUE);
if (acp->curpat == NULL)
return NULL;
}
ac = acp->nextcmd;
if (p_verbose >= 9)
{
verbose_enter_scroll();
smsg((char_u *)_("autocommand %s"), ac->cmd);
msg_puts((char_u *)"\n"); /* don't overwrite this either */
verbose_leave_scroll();
}
retval = vim_strsave(ac->cmd);
autocmd_nested = ac->nested;
#ifdef FEAT_EVAL
current_SID = ac->scriptID;
#endif
if (ac->last)
acp->nextcmd = NULL;
else
acp->nextcmd = ac->next;
return retval;
}
/*
* Return TRUE if there is a matching autocommand for "fname".
* To account for buffer-local autocommands, function needs to know
* in which buffer the file will be opened.
*/
int
has_autocmd(event_T event, char_u *sfname, buf_T *buf)
{
AutoPat *ap;
char_u *fname;
char_u *tail = gettail(sfname);
int retval = FALSE;
fname = FullName_save(sfname, FALSE);
if (fname == NULL)
return FALSE;
#ifdef BACKSLASH_IN_FILENAME
/*
* Replace all backslashes with forward slashes. This makes the
* autocommand patterns portable between Unix and MS-DOS.
*/
sfname = vim_strsave(sfname);
if (sfname != NULL)
forward_slash(sfname);
forward_slash(fname);
#endif
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->pat != NULL && ap->cmds != NULL
&& (ap->buflocal_nr == 0
? match_file_pat(NULL, &ap->reg_prog,
fname, sfname, tail, ap->allow_dirs)
: buf != NULL && ap->buflocal_nr == buf->b_fnum
))
{
retval = TRUE;
break;
}
vim_free(fname);
#ifdef BACKSLASH_IN_FILENAME
vim_free(sfname);
#endif
return retval;
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Function given to ExpandGeneric() to obtain the list of autocommand group
* names.
*/
char_u *
get_augroup_name(expand_T *xp UNUSED, int idx)
{
if (idx == augroups.ga_len) /* add "END" add the end */
return (char_u *)"END";
if (idx >= augroups.ga_len) /* end of list */
return NULL;
if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
/* skip deleted entries */
return (char_u *)"";
return AUGROUP_NAME(idx); /* return a name */
}
static int include_groups = FALSE;
char_u *
set_context_in_autocmd(
expand_T *xp,
char_u *arg,
int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
{
char_u *p;
int group;
/* check for a group name, skip it if present */
include_groups = FALSE;
p = arg;
group = au_get_grouparg(&arg);
if (group == AUGROUP_ERROR)
return NULL;
/* If there only is a group name that's what we expand. */
if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
{
arg = p;
group = AUGROUP_ALL;
}
/* skip over event name */
for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
if (*p == ',')
arg = p + 1;
if (*p == NUL)
{
if (group == AUGROUP_ALL)
include_groups = TRUE;
xp->xp_context = EXPAND_EVENTS; /* expand event name */
xp->xp_pattern = arg;
return NULL;
}
/* skip over pattern */
arg = skipwhite(p);
while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
arg++;
if (*arg)
return arg; /* expand (next) command */
if (doautocmd)
xp->xp_context = EXPAND_FILES; /* expand file names */
else
xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
return NULL;
}
/*
* Function given to ExpandGeneric() to obtain the list of event names.
*/
char_u *
get_event_name(expand_T *xp UNUSED, int idx)
{
if (idx < augroups.ga_len) /* First list group names, if wanted */
{
if (!include_groups || AUGROUP_NAME(idx) == NULL
|| AUGROUP_NAME(idx) == get_deleted_augroup())
return (char_u *)""; /* skip deleted entries */
return AUGROUP_NAME(idx); /* return a name */
}
return (char_u *)event_names[idx - augroups.ga_len].name;
}
#endif /* FEAT_CMDL_COMPL */
/*
* Return TRUE if autocmd is supported.
*/
int
autocmd_supported(char_u *name)
{
char_u *p;
return (event_name2nr(name, &p) != NUM_EVENTS);
}
/*
* Return TRUE if an autocommand is defined for a group, event and
* pattern: The group can be omitted to accept any group. "event" and "pattern"
* can be NULL to accept any event and pattern. "pattern" can be NULL to accept
* any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
* Used for:
* exists("#Group") or
* exists("#Group#Event") or
* exists("#Group#Event#pat") or
* exists("#Event") or
* exists("#Event#pat")
*/
int
au_exists(char_u *arg)
{
char_u *arg_save;
char_u *pattern = NULL;
char_u *event_name;
char_u *p;
event_T event;
AutoPat *ap;
buf_T *buflocal_buf = NULL;
int group;
int retval = FALSE;
/* Make a copy so that we can change the '#' chars to a NUL. */
arg_save = vim_strsave(arg);
if (arg_save == NULL)
return FALSE;
p = vim_strchr(arg_save, '#');
if (p != NULL)
*p++ = NUL;
/* First, look for an autocmd group name */
group = au_find_group(arg_save);
if (group == AUGROUP_ERROR)
{
/* Didn't match a group name, assume the first argument is an event. */
group = AUGROUP_ALL;
event_name = arg_save;
}
else
{
if (p == NULL)
{
/* "Group": group name is present and it's recognized */
retval = TRUE;
goto theend;
}
/* Must be "Group#Event" or "Group#Event#pat". */
event_name = p;
p = vim_strchr(event_name, '#');
if (p != NULL)
*p++ = NUL; /* "Group#Event#pat" */
}
pattern = p; /* "pattern" is NULL when there is no pattern */
/* find the index (enum) for the event name */
event = event_name2nr(event_name, &p);
/* return FALSE if the event name is not recognized */
if (event == NUM_EVENTS)
goto theend;
/* Find the first autocommand for this event.
* If there isn't any, return FALSE;
* If there is one and no pattern given, return TRUE; */
ap = first_autopat[(int)event];
if (ap == NULL)
goto theend;
/* if pattern is "<buffer>", special handling is needed which uses curbuf */
/* for pattern "<buffer=N>, fnamecmp() will work fine */
if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
buflocal_buf = curbuf;
/* Check if there is an autocommand with the given pattern. */
for ( ; ap != NULL; ap = ap->next)
/* only use a pattern when it has not been removed and has commands. */
/* For buffer-local autocommands, fnamecmp() works fine. */
if (ap->pat != NULL && ap->cmds != NULL
&& (group == AUGROUP_ALL || ap->group == group)
&& (pattern == NULL
|| (buflocal_buf == NULL
? fnamecmp(ap->pat, pattern) == 0
: ap->buflocal_nr == buflocal_buf->b_fnum)))
{
retval = TRUE;
break;
}
theend:
vim_free(arg_save);
return retval;
}
#else /* FEAT_AUTOCMD */
/*
* Prepare for executing commands for (hidden) buffer "buf".
* This is the non-autocommand version, it simply saves "curbuf" and sets
* "curbuf" and "curwin" to match "buf".
*/
void
aucmd_prepbuf(
aco_save_T *aco, /* structure to save values in */
buf_T *buf) /* new curbuf */
{
aco->save_curbuf = curbuf;
--curbuf->b_nwindows;
curbuf = buf;
curwin->w_buffer = buf;
++curbuf->b_nwindows;
}
/*
* Restore after executing commands for a (hidden) buffer.
* This is the non-autocommand version.
*/
void
aucmd_restbuf(
aco_save_T *aco) /* structure holding saved values */
{
--curbuf->b_nwindows;
curbuf = aco->save_curbuf;
curwin->w_buffer = curbuf;
++curbuf->b_nwindows;
}
#endif /* FEAT_AUTOCMD */
#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
/*
* Try matching a filename with a "pattern" ("prog" is NULL), or use the
* precompiled regprog "prog" ("pattern" is NULL). That avoids calling
* vim_regcomp() often.
* Used for autocommands and 'wildignore'.
* Returns TRUE if there is a match, FALSE otherwise.
*/
static int
match_file_pat(
char_u *pattern, /* pattern to match with */
regprog_T **prog, /* pre-compiled regprog or NULL */
char_u *fname, /* full path of file name */
char_u *sfname, /* short file name or NULL */
char_u *tail, /* tail of path */
int allow_dirs) /* allow matching with dir */
{
regmatch_T regmatch;
int result = FALSE;
regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
if (prog != NULL)
regmatch.regprog = *prog;
else
regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
/*
* Try for a match with the pattern with:
* 1. the full file name, when the pattern has a '/'.
* 2. the short file name, when the pattern has a '/'.
* 3. the tail of the file name, when the pattern has no '/'.
*/
if (regmatch.regprog != NULL
&& ((allow_dirs
&& (vim_regexec(®match, fname, (colnr_T)0)
|| (sfname != NULL
&& vim_regexec(®match, sfname, (colnr_T)0))))
|| (!allow_dirs && vim_regexec(®match, tail, (colnr_T)0))))
result = TRUE;
if (prog != NULL)
*prog = regmatch.regprog;
else
vim_regfree(regmatch.regprog);
return result;
}
#endif
#if defined(FEAT_WILDIGN) || defined(PROTO)
/*
* Return TRUE if a file matches with a pattern in "list".
* "list" is a comma-separated list of patterns, like 'wildignore'.
* "sfname" is the short file name or NULL, "ffname" the long file name.
*/
int
match_file_list(char_u *list, char_u *sfname, char_u *ffname)
{
char_u buf[100];
char_u *tail;
char_u *regpat;
char allow_dirs;
int match;
char_u *p;
tail = gettail(sfname);
/* try all patterns in 'wildignore' */
p = list;
while (*p)
{
copy_option_part(&p, buf, 100, ",");
regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
if (regpat == NULL)
break;
match = match_file_pat(regpat, NULL, ffname, sfname,
tail, (int)allow_dirs);
vim_free(regpat);
if (match)
return TRUE;
}
return FALSE;
}
#endif
/*
* Convert the given pattern "pat" which has shell style wildcards in it, into
* a regular expression, and return the result in allocated memory. If there
* is a directory path separator to be matched, then TRUE is put in
* allow_dirs, otherwise FALSE is put there -- webb.
* Handle backslashes before special characters, like "\*" and "\ ".
*
* Returns NULL when out of memory.
*/
char_u *
file_pat_to_reg_pat(
char_u *pat,
char_u *pat_end, /* first char after pattern or NULL */
char *allow_dirs, /* Result passed back out in here */
int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
{
int size = 2; /* '^' at start, '$' at end */
char_u *endp;
char_u *reg_pat;
char_u *p;
int i;
int nested = 0;
int add_dollar = TRUE;
if (allow_dirs != NULL)
*allow_dirs = FALSE;
if (pat_end == NULL)
pat_end = pat + STRLEN(pat);
for (p = pat; p < pat_end; p++)
{
switch (*p)
{
case '*':
case '.':
case ',':
case '{':
case '}':
case '~':
size += 2; /* extra backslash */
break;
#ifdef BACKSLASH_IN_FILENAME
case '\\':
case '/':
size += 4; /* could become "[\/]" */
break;
#endif
default:
size++;
# ifdef FEAT_MBYTE
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
{
++p;
++size;
}
# endif
break;
}
}
reg_pat = alloc(size + 1);
if (reg_pat == NULL)
return NULL;
i = 0;
if (pat[0] == '*')
while (pat[0] == '*' && pat < pat_end - 1)
pat++;
else
reg_pat[i++] = '^';
endp = pat_end - 1;
if (endp >= pat && *endp == '*')
{
while (endp - pat > 0 && *endp == '*')
endp--;
add_dollar = FALSE;
}
for (p = pat; *p && nested >= 0 && p <= endp; p++)
{
switch (*p)
{
case '*':
reg_pat[i++] = '.';
reg_pat[i++] = '*';
while (p[1] == '*') /* "**" matches like "*" */
++p;
break;
case '.':
case '~':
reg_pat[i++] = '\\';
reg_pat[i++] = *p;
break;
case '?':
reg_pat[i++] = '.';
break;
case '\\':
if (p[1] == NUL)
break;
#ifdef BACKSLASH_IN_FILENAME
if (!no_bslash)
{
/* translate:
* "\x" to "\\x" e.g., "dir\file"
* "\*" to "\\.*" e.g., "dir\*.c"
* "\?" to "\\." e.g., "dir\??.c"
* "\+" to "\+" e.g., "fileX\+.c"
*/
if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
&& p[1] != '+')
{
reg_pat[i++] = '[';
reg_pat[i++] = '\\';
reg_pat[i++] = '/';
reg_pat[i++] = ']';
if (allow_dirs != NULL)
*allow_dirs = TRUE;
break;
}
}
#endif
/* Undo escaping from ExpandEscape():
* foo\?bar -> foo?bar
* foo\%bar -> foo%bar
* foo\,bar -> foo,bar
* foo\ bar -> foo bar
* Don't unescape \, * and others that are also special in a
* regexp.
* An escaped { must be unescaped since we use magic not
* verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
*/
if (*++p == '?'
#ifdef BACKSLASH_IN_FILENAME
&& no_bslash
#endif
)
reg_pat[i++] = '?';
else
if (*p == ',' || *p == '%' || *p == '#'
|| vim_isspace(*p) || *p == '{' || *p == '}')
reg_pat[i++] = *p;
else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
{
reg_pat[i++] = '\\';
reg_pat[i++] = '{';
p += 2;
}
else
{
if (allow_dirs != NULL && vim_ispathsep(*p)
#ifdef BACKSLASH_IN_FILENAME
&& (!no_bslash || *p != '\\')
#endif
)
*allow_dirs = TRUE;
reg_pat[i++] = '\\';
reg_pat[i++] = *p;
}
break;
#ifdef BACKSLASH_IN_FILENAME
case '/':
reg_pat[i++] = '[';
reg_pat[i++] = '\\';
reg_pat[i++] = '/';
reg_pat[i++] = ']';
if (allow_dirs != NULL)
*allow_dirs = TRUE;
break;
#endif
case '{':
reg_pat[i++] = '\\';
reg_pat[i++] = '(';
nested++;
break;
case '}':
reg_pat[i++] = '\\';
reg_pat[i++] = ')';
--nested;
break;
case ',':
if (nested)
{
reg_pat[i++] = '\\';
reg_pat[i++] = '|';
}
else
reg_pat[i++] = ',';
break;
default:
# ifdef FEAT_MBYTE
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
reg_pat[i++] = *p++;
else
# endif
if (allow_dirs != NULL && vim_ispathsep(*p))
*allow_dirs = TRUE;
reg_pat[i++] = *p;
break;
}
}
if (add_dollar)
reg_pat[i++] = '$';
reg_pat[i] = NUL;
if (nested != 0)
{
if (nested < 0)
EMSG(_("E219: Missing {."));
else
EMSG(_("E220: Missing }."));
vim_free(reg_pat);
reg_pat = NULL;
}
return reg_pat;
}
#if defined(EINTR) || defined(PROTO)
/*
* Version of read() that retries when interrupted by EINTR (possibly
* by a SIGWINCH).
*/
long
read_eintr(int fd, void *buf, size_t bufsize)
{
long ret;
for (;;)
{
ret = vim_read(fd, buf, bufsize);
if (ret >= 0 || errno != EINTR)
break;
}
return ret;
}
/*
* Version of write() that retries when interrupted by EINTR (possibly
* by a SIGWINCH).
*/
long
write_eintr(int fd, void *buf, size_t bufsize)
{
long ret = 0;
long wlen;
/* Repeat the write() so long it didn't fail, other than being interrupted
* by a signal. */
while (ret < (long)bufsize)
{
wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
if (wlen < 0)
{
if (errno != EINTR)
break;
}
else
ret += wlen;
}
return ret;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2958_1 |
crossvul-cpp_data_bad_1508_7 | /*
Copyright (C) 2012 ABRT Team
Copyright (C) 2012 Red Hat, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "libabrt.h"
/* I want to use -Werror, but gcc-4.4 throws a curveball:
* "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result"
* and (void) cast is not enough to shut it up! Oh God...
*/
#define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0)
enum {
OPT_v = 1 << 0,
OPT_s = 1 << 1,
OPT_o = 1 << 2,
OPT_d = 1 << 3,
OPT_D = 1 << 4,
OPT_x = 1 << 5,
OPT_m = 1 << 6,
};
/* How many problem dirs to create at most?
* Also causes cooldown sleep if exceeded -
* useful when called from a log watcher.
*/
#define MAX_DUMPED_DD_COUNT 5
static unsigned g_bt_count = 0;
static unsigned g_opts;
static const char *debug_dumps_dir = ".";
static char *skip_pfx(char *p)
{
if (p[0] != '[')
return p;
char *q = strchr(p, ']');
if (!q)
return p;
if (q[1] == ' ')
return q + 2;
return p;
}
static char *list2lines(GList *list)
{
struct strbuf *s = strbuf_new();
while (list)
{
strbuf_append_str(s, (char*)list->data);
strbuf_append_char(s, '\n');
free(list->data);
list = g_list_delete_link(list, list);
}
return strbuf_free_nobuf(s);
}
static void save_bt_to_dump_dir(const char *bt, const char *exe, const char *reason)
{
time_t t = time(NULL);
const char *iso_date = iso_date_string(&t);
/* dump should be readable by all if we're run with -x */
uid_t my_euid = (uid_t)-1L;
mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH;
/* and readable only for the owner otherwise */
if (!(g_opts & OPT_x))
{
mode = DEFAULT_DUMP_DIR_MODE;
my_euid = geteuid();
}
pid_t my_pid = getpid();
char base[sizeof("xorg-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3];
sprintf(base, "xorg-%s-%lu-%u", iso_date, (long)my_pid, g_bt_count);
char *path = concat_path_file(debug_dumps_dir, base);
struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode);
if (dd)
{
dd_create_basic_files(dd, /*uid:*/ my_euid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
dd_save_text(dd, FILENAME_ANALYZER, "xorg");
dd_save_text(dd, FILENAME_TYPE, "xorg");
dd_save_text(dd, FILENAME_REASON, reason);
dd_save_text(dd, FILENAME_BACKTRACE, bt);
/*
* Reporters usually need component name to file a bug.
* It is usually derived from executable.
* We _guess_ X server's executable name as a last resort.
* Better ideas?
*/
if (!exe)
{
exe = "/usr/bin/X";
if (access("/usr/bin/Xorg", X_OK) == 0)
exe = "/usr/bin/Xorg";
}
dd_save_text(dd, FILENAME_EXECUTABLE, exe);
dd_close(dd);
notify_new_path(path);
}
free(path);
}
/* Called after "Backtrace:" line was read.
* Example (yes, stray newline before 'B' is real):
[ 86985.879]<space>
Backtrace:
[ 86985.880] 0: /usr/bin/Xorg (xorg_backtrace+0x2f) [0x462d8f]
[ 86985.880] 1: /usr/bin/Xorg (0x400000+0x67b56) [0x467b56]
[ 86985.880] 2: /lib64/libpthread.so.0 (0x30a5800000+0xf4f0) [0x30a580f4f0]
[ 86985.880] 3: /usr/lib64/xorg/modules/extensions/librecord.so (0x7ff6c225e000+0x26c3) [0x7ff6c22606c3]
[ 86985.880] 4: /usr/bin/Xorg (_CallCallbacks+0x3c) [0x43820c]
[ 86985.880] 5: /usr/bin/Xorg (WriteToClient+0x1f5) [0x466315]
[ 86985.880] 6: /usr/lib64/xorg/modules/extensions/libdri2.so (ProcDRI2WaitMSCReply+0x4f) [0x7ff6c1e4feef]
[ 86985.880] 7: /usr/lib64/xorg/modules/extensions/libdri2.so (DRI2WaitMSCComplete+0x52) [0x7ff6c1e4e6d2]
[ 86985.880] 8: /usr/lib64/xorg/modules/drivers/intel_drv.so (0x7ff6c1bfb000+0x25ae4) [0x7ff6c1c20ae4]
[ 86985.880] 9: /usr/lib64/libdrm.so.2 (drmHandleEvent+0xa3) [0x376b407513]
[ 86985.880] 10: /usr/bin/Xorg (WakeupHandler+0x6b) [0x4379db]
[ 86985.880] 11: /usr/bin/Xorg (WaitForSomething+0x1a9) [0x460289]
[ 86985.880] 12: /usr/bin/Xorg (0x400000+0x3379a) [0x43379a]
[ 86985.880] 13: /usr/bin/Xorg (0x400000+0x22dc5) [0x422dc5]
[ 86985.880] 14: /lib64/libc.so.6 (__libc_start_main+0xed) [0x30a542169d]
[ 86985.880] 15: /usr/bin/Xorg (0x400000+0x230b1) [0x4230b1]
[ 86985.880] Segmentation fault at address 0x7ff6bf09e010
*/
static void process_xorg_bt(void)
{
char *reason = NULL;
char *exe = NULL;
GList *list = NULL;
unsigned cnt = 0;
char *line;
while ((line = xmalloc_fgetline(stdin)) != NULL)
{
char *p = skip_pfx(line);
/* xorg-server-1.12.0/os/osinit.c:
* if (sip->si_code == SI_USER) {
* ErrorF("Recieved signal %d sent by process %ld, uid %ld\n",
* ^^^^^^^^ yes, typo here! Can't grep for this word! :(
* signo, (long) sip->si_pid, (long) sip->si_uid);
* } else {
* switch (signo) {
* case SIGSEGV:
* case SIGBUS:
* case SIGILL:
* case SIGFPE:
* ErrorF("%s at address %p\n", strsignal(signo), sip->si_addr);
*/
if (*p < '0' || *p > '9')
{
if (strstr(p, " at address ") || strstr(p, " sent by process "))
{
overlapping_strcpy(line, p);
reason = line;
line = NULL;
}
/* TODO: Other cases when we have useful reason string? */
break;
}
errno = 0;
char *end;
IGNORE_RESULT(strtoul(p, &end, 10));
if (errno || end == p || *end != ':')
break;
/* This looks like bt line */
/* Guess Xorg server's executable name from it */
if (!exe)
{
char *filename = skip_whitespace(end + 1);
char *filename_end = skip_non_whitespace(filename);
char sv = *filename_end;
*filename_end = '\0';
/* Does it look like "[/usr]/[s]bin/Xfoo"? */
if (strstr(filename, "bin/X"))
exe = xstrdup(filename);
*filename_end = sv;
}
/* Save it to list */
overlapping_strcpy(line, p);
list = g_list_prepend(list, line);
line = NULL;
if (++cnt > 255) /* prevent ridiculously large bts */
break;
}
free(line);
if (list)
{
list = g_list_reverse(list);
char *bt = list2lines(list); /* frees list */
if (g_opts & OPT_o)
printf("%s%s%s\n", bt, reason ? reason : "", reason ? "\n" : "");
if (g_opts & (OPT_d|OPT_D))
if (g_bt_count <= MAX_DUMPED_DD_COUNT)
save_bt_to_dump_dir(bt, exe, reason ? reason : "Xorg server crashed");
free(bt);
}
free(reason);
free(exe);
}
int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [-vsoxm] [-d DIR]/[-D] [FILE]\n"
"\n"
"Extract Xorg crash from FILE (or standard input)"
);
/* Keep OPT_z enums and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_BOOL( 's', NULL, NULL, _("Log to syslog")),
OPT_BOOL( 'o', NULL, NULL, _("Print found crash data on standard output")),
OPT_STRING('d', NULL, &debug_dumps_dir, "DIR", _("Create problem directory in DIR for every crash found")),
OPT_BOOL( 'D', NULL, NULL, _("Same as -d DumpLocation, DumpLocation is specified in abrt.conf")),
OPT_BOOL( 'x', NULL, NULL, _("Make the problem directory world readable")),
OPT_BOOL( 'm', NULL, NULL, _("Print search string(s) to stdout and exit")),
OPT_END()
};
unsigned opts = g_opts = parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
msg_prefix = g_progname;
if ((opts & OPT_s) || getenv("ABRT_SYSLOG"))
{
logmode = LOGMODE_JOURNAL;
}
if (opts & OPT_m)
{
puts("Backtrace");
return 0;
}
if (opts & OPT_D)
{
if (opts & OPT_d)
show_usage_and_die(program_usage_string, program_options);
load_abrt_conf();
debug_dumps_dir = g_settings_dump_location;
g_settings_dump_location = NULL;
free_abrt_conf_data();
}
argv += optind;
if (argv[0])
xmove_fd(xopen(argv[0], O_RDONLY), STDIN_FILENO);
char *line;
while ((line = xmalloc_fgetline(stdin)) != NULL)
{
char *p = skip_pfx(line);
if (strcmp(p, "Backtrace:") == 0)
{
free(line);
g_bt_count++;
process_xorg_bt();
continue;
}
free(line);
}
/* If we are run by a log watcher, this delays log rescan
* (because log watcher waits to us to terminate)
* and possibly prevents dreaded "abrt storm".
*/
if (opts & (OPT_d|OPT_D))
{
if (g_bt_count > MAX_DUMPED_DD_COUNT)
sleep(g_bt_count - MAX_DUMPED_DD_COUNT);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1508_7 |
crossvul-cpp_data_good_2752_0 | /*******************************************************************************
*
* Module Name: nseval - Object evaluation, includes control method execution
*
******************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************
*
* Alternatively, you may choose to be licensed under the terms of the
* following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Alternatively, you may choose to be licensed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
*****************************************************************************/
#include "acpi.h"
#include "accommon.h"
#include "acparser.h"
#include "acinterp.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME ("nseval")
/* Local prototypes */
static void
AcpiNsExecModuleCode (
ACPI_OPERAND_OBJECT *MethodObj,
ACPI_EVALUATE_INFO *Info);
/*******************************************************************************
*
* FUNCTION: AcpiNsEvaluate
*
* PARAMETERS: Info - Evaluation info block, contains these fields
* and more:
* PrefixNode - Prefix or Method/Object Node to execute
* RelativePath - Name of method to execute, If NULL, the
* Node is the object to execute
* Parameters - List of parameters to pass to the method,
* terminated by NULL. Params itself may be
* NULL if no parameters are being passed.
* ParameterType - Type of Parameter list
* ReturnObject - Where to put method's return value (if
* any). If NULL, no value is returned.
* Flags - ACPI_IGNORE_RETURN_VALUE to delete return
*
* RETURN: Status
*
* DESCRIPTION: Execute a control method or return the current value of an
* ACPI namespace object.
*
* MUTEX: Locks interpreter
*
******************************************************************************/
ACPI_STATUS
AcpiNsEvaluate (
ACPI_EVALUATE_INFO *Info)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsEvaluate);
if (!Info)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (!Info->Node)
{
/*
* Get the actual namespace node for the target object if we
* need to. Handles these cases:
*
* 1) Null node, valid pathname from root (absolute path)
* 2) Node and valid pathname (path relative to Node)
* 3) Node, Null pathname
*/
Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname,
ACPI_NS_NO_UPSEARCH, &Info->Node);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
}
/*
* For a method alias, we must grab the actual method node so that
* proper scoping context will be established before execution.
*/
if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS)
{
Info->Node = ACPI_CAST_PTR (
ACPI_NAMESPACE_NODE, Info->Node->Object);
}
/* Complete the info block initialization */
Info->ReturnObject = NULL;
Info->NodeFlags = Info->Node->Flags;
Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node);
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s [%p] Value %p\n",
Info->RelativePathname, Info->Node,
AcpiNsGetAttachedObject (Info->Node)));
/* Get info if we have a predefined name (_HID, etc.) */
Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii);
/* Get the full pathname to the object, for use in warning messages */
Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE);
if (!Info->FullPathname)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Count the number of arguments being passed in */
Info->ParamCount = 0;
if (Info->Parameters)
{
while (Info->Parameters[Info->ParamCount])
{
Info->ParamCount++;
}
/* Warn on impossible argument count */
if (Info->ParamCount > ACPI_METHOD_NUM_ARGS)
{
ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS,
"Excess arguments (%u) - using only %u",
Info->ParamCount, ACPI_METHOD_NUM_ARGS));
Info->ParamCount = ACPI_METHOD_NUM_ARGS;
}
}
/*
* For predefined names: Check that the declared argument count
* matches the ACPI spec -- otherwise this is a BIOS error.
*/
AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node,
Info->Predefined);
/*
* For all names: Check that the incoming argument count for
* this method/object matches the actual ASL/AML definition.
*/
AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node,
Info->ParamCount, Info->Predefined);
/* For predefined names: Typecheck all incoming arguments */
AcpiNsCheckArgumentTypes (Info);
/*
* Three major evaluation cases:
*
* 1) Object types that cannot be evaluated by definition
* 2) The object is a control method -- execute it
* 3) The object is not a method -- just return it's current value
*/
switch (AcpiNsGetType (Info->Node))
{
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_EVENT:
case ACPI_TYPE_MUTEX:
case ACPI_TYPE_REGION:
case ACPI_TYPE_THERMAL:
case ACPI_TYPE_LOCAL_SCOPE:
/*
* 1) Disallow evaluation of certain object types. For these,
* object evaluation is undefined and not supported.
*/
ACPI_ERROR ((AE_INFO,
"%s: Evaluation of object type [%s] is not supported",
Info->FullPathname,
AcpiUtGetTypeName (Info->Node->Type)));
Status = AE_TYPE;
goto Cleanup;
case ACPI_TYPE_METHOD:
/*
* 2) Object is a control method - execute it
*/
/* Verify that there is a method object associated with this node */
if (!Info->ObjDesc)
{
ACPI_ERROR ((AE_INFO, "%s: Method has no attached sub-object",
Info->FullPathname));
Status = AE_NULL_OBJECT;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"**** Execute method [%s] at AML address %p length %X\n",
Info->FullPathname,
Info->ObjDesc->Method.AmlStart + 1,
Info->ObjDesc->Method.AmlLength - 1));
/*
* Any namespace deletion must acquire both the namespace and
* interpreter locks to ensure that no thread is using the portion of
* the namespace that is being deleted.
*
* Execute the method via the interpreter. The interpreter is locked
* here before calling into the AML parser
*/
AcpiExEnterInterpreter ();
Status = AcpiPsExecuteMethod (Info);
AcpiExExitInterpreter ();
break;
default:
/*
* 3) All other non-method objects -- get the current object value
*/
/*
* Some objects require additional resolution steps (e.g., the Node
* may be a field that must be read, etc.) -- we can't just grab
* the object out of the node.
*
* Use ResolveNodeToValue() to get the associated value.
*
* NOTE: we can get away with passing in NULL for a walk state because
* the Node is guaranteed to not be a reference to either a method
* local or a method argument (because this interface is never called
* from a running method.)
*
* Even though we do not directly invoke the interpreter for object
* resolution, we must lock it because we could access an OpRegion.
* The OpRegion access code assumes that the interpreter is locked.
*/
AcpiExEnterInterpreter ();
/* TBD: ResolveNodeToValue has a strange interface, fix */
Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node);
Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR (
ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL);
AcpiExExitInterpreter ();
if (ACPI_FAILURE (Status))
{
Info->ReturnObject = NULL;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Returned object %p [%s]\n",
Info->ReturnObject,
AcpiUtGetObjectTypeName (Info->ReturnObject)));
Status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */
break;
}
/*
* For predefined names, check the return value against the ACPI
* specification. Some incorrect return value types are repaired.
*/
(void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount,
Status, &Info->ReturnObject);
/* Check if there is a return value that must be dealt with */
if (Status == AE_CTRL_RETURN_VALUE)
{
/* If caller does not want the return value, delete it */
if (Info->Flags & ACPI_IGNORE_RETURN_VALUE)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
/* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */
Status = AE_OK;
}
else if (ACPI_FAILURE(Status))
{
/* If ReturnObject exists, delete it */
if (Info->ReturnObject)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,
"*** Completed evaluation of object %s ***\n",
Info->RelativePathname));
Cleanup:
/*
* Namespace was unlocked by the handling AcpiNs* function, so we
* just free the pathname and return
*/
ACPI_FREE (Info->FullPathname);
Info->FullPathname = NULL;
return_ACPI_STATUS (Status);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsExecModuleCodeList
*
* PARAMETERS: None
*
* RETURN: None. Exceptions during method execution are ignored, since
* we cannot abort a table load.
*
* DESCRIPTION: Execute all elements of the global module-level code list.
* Each element is executed as a single control method.
*
******************************************************************************/
void
AcpiNsExecModuleCodeList (
void)
{
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
ACPI_EVALUATE_INFO *Info;
UINT32 MethodCount = 0;
ACPI_FUNCTION_TRACE (NsExecModuleCodeList);
/* Exit now if the list is empty */
Next = AcpiGbl_ModuleCodeList;
if (!Next)
{
return_VOID;
}
/* Allocate the evaluation information block */
Info = ACPI_ALLOCATE (sizeof (ACPI_EVALUATE_INFO));
if (!Info)
{
return_VOID;
}
/* Walk the list, executing each "method" */
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
/* Clear the link field and execute the method */
Prev->Method.Mutex = NULL;
AcpiNsExecModuleCode (Prev, Info);
MethodCount++;
/* Delete the (temporary) method object */
AcpiUtRemoveReference (Prev);
}
ACPI_INFO ((
"Executed %u blocks of module-level executable AML code",
MethodCount));
ACPI_FREE (Info);
AcpiGbl_ModuleCodeList = NULL;
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsExecModuleCode
*
* PARAMETERS: MethodObj - Object container for the module-level code
* Info - Info block for method evaluation
*
* RETURN: None. Exceptions during method execution are ignored, since
* we cannot abort a table load.
*
* DESCRIPTION: Execute a control method containing a block of module-level
* executable AML code. The control method is temporarily
* installed to the root node, then evaluated.
*
******************************************************************************/
static void
AcpiNsExecModuleCode (
ACPI_OPERAND_OBJECT *MethodObj,
ACPI_EVALUATE_INFO *Info)
{
ACPI_OPERAND_OBJECT *ParentObj;
ACPI_NAMESPACE_NODE *ParentNode;
ACPI_OBJECT_TYPE Type;
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsExecModuleCode);
/*
* Get the parent node. We cheat by using the NextObject field
* of the method object descriptor.
*/
ParentNode = ACPI_CAST_PTR (
ACPI_NAMESPACE_NODE, MethodObj->Method.NextObject);
Type = AcpiNsGetType (ParentNode);
/*
* Get the region handler and save it in the method object. We may need
* this if an operation region declaration causes a _REG method to be run.
*
* We can't do this in AcpiPsLinkModuleCode because
* AcpiGbl_RootNode->Object is NULL at PASS1.
*/
if ((Type == ACPI_TYPE_DEVICE) && ParentNode->Object)
{
MethodObj->Method.Dispatch.Handler =
ParentNode->Object->Device.Handler;
}
/* Must clear NextObject (AcpiNsAttachObject needs the field) */
MethodObj->Method.NextObject = NULL;
/* Initialize the evaluation information block */
memset (Info, 0, sizeof (ACPI_EVALUATE_INFO));
Info->PrefixNode = ParentNode;
/*
* Get the currently attached parent object. Add a reference,
* because the ref count will be decreased when the method object
* is installed to the parent node.
*/
ParentObj = AcpiNsGetAttachedObject (ParentNode);
if (ParentObj)
{
AcpiUtAddReference (ParentObj);
}
/* Install the method (module-level code) in the parent node */
Status = AcpiNsAttachObject (ParentNode, MethodObj, ACPI_TYPE_METHOD);
if (ACPI_FAILURE (Status))
{
goto Exit;
}
/* Execute the parent node as a control method */
Status = AcpiNsEvaluate (Info);
ACPI_DEBUG_PRINT ((ACPI_DB_INIT_NAMES,
"Executed module-level code at %p\n",
MethodObj->Method.AmlStart));
/* Delete a possible implicit return value (in slack mode) */
if (Info->ReturnObject)
{
AcpiUtRemoveReference (Info->ReturnObject);
}
/* Detach the temporary method object */
AcpiNsDetachObject (ParentNode);
/* Restore the original parent object */
if (ParentObj)
{
Status = AcpiNsAttachObject (ParentNode, ParentObj, Type);
}
else
{
ParentNode->Type = (UINT8) Type;
}
Exit:
if (ParentObj)
{
AcpiUtRemoveReference (ParentObj);
}
return_VOID;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_2752_0 |
crossvul-cpp_data_good_693_0 | /*
* Copyright (c) 2011-2014 Yubico AB
* Copyright (c) 2011 Tollef Fog Heen <tfheen@err.no>
* All rights reserved.
*
* Author : Fredrik Thulin <fredrik@yubico.com>
* Author : Tollef Fog Heen <tfheen@err.no>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <unistd.h>
#include "util.h"
#if HAVE_CR
/* for yubikey_hex_decode and yubikey_hex_p */
#include <yubikey.h>
#include <ykpbkdf2.h>
#include <ykstatus.h>
#include <ykdef.h>
#endif /* HAVE_CR */
int
get_user_cfgfile_path(const char *common_path, const char *filename, const struct passwd *user, char **fn)
{
/* Getting file from user home directory, e.g. ~/.yubico/challenge, or
* from a system wide directory.
*
* Format is hex(challenge):hex(response):slot num
*/
char *userfile;
size_t len;
if (common_path != NULL) {
len = strlen(common_path) + 1 + strlen(filename) + 1;
if ((userfile = malloc(len)) == NULL) {
return 0;
}
snprintf(userfile, len, "%s/%s", common_path, filename);
*fn = userfile;
return 1;
}
/* No common path provided. Construct path to user's ~/.yubico/filename */
len = strlen(user->pw_dir) + 9 + strlen(filename) + 1;
if ((userfile = malloc(len)) == NULL) {
return 0;
}
snprintf(userfile, len, "%s/.yubico/%s", user->pw_dir, filename);
*fn = userfile;
return 1;
}
/*
* This function will look for users name with valid user token id.
*
* Returns one of AUTH_FOUND, AUTH_NOT_FOUND, AUTH_NO_TOKENS, AUTH_ERROR.
*
* File format is as follows:
* <user-name>:<token_id>:<token_id>
* <user-name>:<token_id>
*
*/
int
check_user_token (const char *authfile,
const char *username,
const char *otp_id,
int verbose,
FILE *debug_file)
{
char buf[1024];
char *s_user, *s_token;
int retval = AUTH_ERROR;
int fd;
struct stat st;
FILE *opwfile;
fd = open(authfile, O_RDONLY, 0);
if (fd < 0) {
if(verbose)
D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
return retval;
}
if (fstat(fd, &st) < 0) {
if(verbose)
D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
close(fd);
return retval;
}
if (!S_ISREG(st.st_mode)) {
if(verbose)
D (debug_file, "%s is not a regular file", authfile);
close(fd);
return retval;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if(verbose)
D (debug_file, "fdopen: %s", strerror(errno));
close(fd);
return retval;
}
retval = AUTH_NO_TOKENS;
while (fgets (buf, 1024, opwfile))
{
char *saveptr = NULL;
if (buf[strlen (buf) - 1] == '\n')
buf[strlen (buf) - 1] = '\0';
if (buf[0] == '#') {
/* This is a comment and we may skip it. */
if(verbose)
D (debug_file, "Skipping comment line: %s", buf);
continue;
}
if(verbose)
D (debug_file, "Authorization line: %s", buf);
s_user = strtok_r (buf, ":", &saveptr);
if (s_user && strcmp (username, s_user) == 0)
{
if(verbose)
D (debug_file, "Matched user: %s", s_user);
retval = AUTH_NOT_FOUND; /* We found at least one line for the user */
do
{
s_token = strtok_r (NULL, ":", &saveptr);
if(verbose)
D (debug_file, "Authorization token: %s", s_token);
if (s_token && otp_id && strcmp (otp_id, s_token) == 0)
{
if(verbose)
D (debug_file, "Match user/token as %s/%s", username, otp_id);
fclose(opwfile);
return AUTH_FOUND;
}
}
while (s_token != NULL);
}
}
fclose (opwfile);
return retval;
}
#if HAVE_CR
/* Fill buf with len bytes of random data */
int generate_random(void *buf, int len)
{
FILE *u;
int res;
u = fopen("/dev/urandom", "r");
if (!u) {
return -1;
}
res = fread(buf, 1, (size_t) len, u);
fclose(u);
return (res != len);
}
int
check_firmware_version(YK_KEY *yk, bool verbose, bool quiet, FILE *debug_file)
{
YK_STATUS *st = ykds_alloc();
if (!yk_get_status(yk, st)) {
free(st);
return 0;
}
if (verbose) {
D(debug_file, "YubiKey Firmware version: %d.%d.%d\n",
ykds_version_major(st),
ykds_version_minor(st),
ykds_version_build(st));
}
if (ykds_version_major(st) < 2 ||
(ykds_version_major(st) == 2
&& ykds_version_minor(st) < 2)) {
if (! quiet)
fprintf(stderr, "Challenge-response not supported before YubiKey 2.2.\n");
free(st);
return 0;
}
free(st);
return 1;
}
int
init_yubikey(YK_KEY **yk)
{
if (!yk_init())
return 0;
if (!(*yk = yk_open_first_key()))
return 0;
return 1;
}
int challenge_response(YK_KEY *yk, int slot,
char *challenge, unsigned int len,
bool hmac, bool may_block, bool verbose,
char *response, unsigned int res_size, unsigned int *res_len)
{
int yk_cmd;
if(hmac == true) {
*res_len = 20;
} else {
*res_len = 16;
}
if (res_size < *res_len) {
return 0;
}
memset(response, 0, res_size);
if (verbose) {
fprintf(stderr, "Sending %u bytes %s challenge to slot %i\n", len, (hmac == true)?"HMAC":"Yubico", slot);
//_yk_hexdump(challenge, len);
}
switch(slot) {
case 1:
yk_cmd = (hmac == true) ? SLOT_CHAL_HMAC1 : SLOT_CHAL_OTP1;
break;
case 2:
yk_cmd = (hmac == true) ? SLOT_CHAL_HMAC2 : SLOT_CHAL_OTP2;
break;
default:
return 0;
}
if(! yk_challenge_response(yk, yk_cmd, may_block, len,
(unsigned char*)challenge, res_size, (unsigned char*)response)) {
return 0;
}
return 1;
}
int
check_user_challenge_file(const char *chalresp_path, const struct passwd *user, FILE *debug_file)
{
/*
* This function will look for users challenge files.
*
* Returns one of AUTH_FOUND, AUTH_NOT_FOUND, AUTH_ERROR
*/
size_t len;
int r;
int ret = AUTH_NOT_FOUND;
char *userfile = NULL;
char *userfile_pattern = NULL;
glob_t userfile_glob;
const char *filename = NULL;
if (! chalresp_path) {
filename = "challenge";
} else {
filename = user->pw_name;
}
/* check for userfile challenge files */
r = get_user_cfgfile_path(chalresp_path, filename, user, &userfile);
if (!r) {
D (debug_file, "Failed to get user cfgfile path");
ret = AUTH_ERROR;
goto out;
}
if (!access(userfile, F_OK)) {
ret = AUTH_FOUND;
goto out;
}
/* check for userfile-* challenge files */
len = strlen(userfile) + 2 + 1;
if ((userfile_pattern = malloc(len)) == NULL) {
D (debug_file, "Failed to allocate memory for userfile pattern: %s", strerror(errno));
ret = AUTH_ERROR;
goto out;
}
snprintf(userfile_pattern, len, "%s-*", userfile);
r = glob(userfile_pattern, 0, NULL, &userfile_glob);
globfree(&userfile_glob);
switch (r) {
case GLOB_NOMATCH:
/* No matches found, so continue */
break;
case 0:
ret = AUTH_FOUND;
goto out;
default:
D (debug_file, "Error while checking for %s challenge files: %s", userfile_pattern, strerror(errno));
ret = AUTH_ERROR;
goto out;
}
out:
free(userfile_pattern);
free(userfile);
return ret;
}
int
get_user_challenge_file(YK_KEY *yk, const char *chalresp_path, const struct passwd *user, char **fn, FILE *debug_file)
{
/* Getting file from user home directory, i.e. ~/.yubico/challenge, or
* from a system wide directory.
*/
/* The challenge to use is located in a file in the user's home directory,
* which therefor can't be encrypted. If an encrypted home directory is used,
* the option chalresp_path can be used to point to a system-wide directory.
*/
const char *filename = NULL; /* not including directory */
char *ptr = NULL;
unsigned int serial = 0;
int ret;
if (! yk_get_serial(yk, 0, 0, &serial)) {
D (debug_file, "Failed to read serial number (serial-api-visible disabled?).");
if (! chalresp_path)
filename = "challenge";
else
filename = user->pw_name;
} else {
/* We have serial number */
/* 0xffffffff == 4294967295 == 10 digits */
size_t len = strlen(chalresp_path == NULL ? "challenge" : user->pw_name) + 1 + 10 + 1;
if ((ptr = malloc(len)) != NULL) {
int res = snprintf(ptr, len, "%s-%u", chalresp_path == NULL ? "challenge" : user->pw_name, serial);
filename = ptr;
if (res < 0 || (unsigned long)res > len) {
/* Not enough space, strangely enough. */
free(ptr);
filename = NULL;
}
}
}
if (filename == NULL)
return 0;
ret = get_user_cfgfile_path (chalresp_path, filename, user, fn);
if(ptr) {
free(ptr);
}
return ret;
}
int
load_chalresp_state(FILE *f, CR_STATE *state, bool verbose, FILE *debug_file)
{
/*
* Load the current challenge and expected response information from a file handle.
*
* Format is hex(challenge):hex(response):slot num
*/
char challenge_hex[CR_CHALLENGE_SIZE * 2 + 1], response_hex[CR_RESPONSE_SIZE * 2 + 1];
char salt_hex[CR_SALT_SIZE * 2 + 1];
unsigned int iterations;
int slot;
int r;
if (! f)
goto out;
/* XXX not ideal with hard coded lengths in this scan string.
* 126 corresponds to twice the size of CR_CHALLENGE_SIZE,
* 40 is twice the size of CR_RESPONSE_SIZE
* (twice because we hex encode the challenge and response)
*/
r = fscanf(f, "v2:%126[0-9a-z]:%40[0-9a-z]:%64[0-9a-z]:%d:%d", challenge_hex, response_hex, salt_hex, &iterations, &slot);
if(r == 5) {
if (! yubikey_hex_p(salt_hex)) {
D(debug_file, "Invalid salt hex input : %s", salt_hex);
goto out;
}
if(verbose) {
D(debug_file, "Challenge: %s, hashed response: %s, salt: %s, iterations: %d, slot: %d",
challenge_hex, response_hex, salt_hex, iterations, slot);
}
yubikey_hex_decode(state->salt, salt_hex, sizeof(state->salt));
state->salt_len = strlen(salt_hex) / 2;
} else {
rewind(f);
r = fscanf(f, "v1:%126[0-9a-z]:%40[0-9a-z]:%d", challenge_hex, response_hex, &slot);
if (r != 3) {
D(debug_file, "Could not parse contents of chalresp_state file (%i)", r);
goto out;
}
if (verbose) {
D(debug_file, "Challenge: %s, expected response: %s, slot: %d", challenge_hex, response_hex, slot);
}
iterations = CR_DEFAULT_ITERATIONS;
}
state->iterations = iterations;
if (! yubikey_hex_p(challenge_hex)) {
D(debug_file, "Invalid challenge hex input : %s", challenge_hex);
goto out;
}
if (! yubikey_hex_p(response_hex)) {
D(debug_file, "Invalid expected response hex input : %s", response_hex);
goto out;
}
if (slot != 1 && slot != 2) {
D(debug_file, "Invalid slot input : %i", slot);
goto out;
}
yubikey_hex_decode(state->challenge, challenge_hex, sizeof(state->challenge));
state->challenge_len = strlen(challenge_hex) / 2;
yubikey_hex_decode(state->response, response_hex, sizeof(state->response));
state->response_len = strlen(response_hex) / 2;
state->slot = slot;
return 1;
out:
return 0;
}
int
write_chalresp_state(FILE *f, CR_STATE *state)
{
char challenge_hex[CR_CHALLENGE_SIZE * 2 + 1], response_hex[CR_RESPONSE_SIZE * 2 + 1];
char salt_hex[CR_SALT_SIZE * 2 + 1], hashed_hex[CR_RESPONSE_SIZE * 2 + 1];
unsigned char salt[CR_SALT_SIZE], hash[CR_RESPONSE_SIZE];
YK_PRF_METHOD prf_method = {20, yk_hmac_sha1};
unsigned int iterations = CR_DEFAULT_ITERATIONS;
int fd;
memset(challenge_hex, 0, sizeof(challenge_hex));
memset(response_hex, 0, sizeof(response_hex));
memset(salt_hex, 0, sizeof(salt_hex));
memset(hashed_hex, 0, sizeof(hashed_hex));
yubikey_hex_encode(challenge_hex, (char *)state->challenge, state->challenge_len);
yubikey_hex_encode(response_hex, (char *)state->response, state->response_len);
if(state->iterations > 0) {
iterations = state->iterations;
}
generate_random(salt, CR_SALT_SIZE);
yk_pbkdf2(response_hex, salt, CR_SALT_SIZE, iterations,
hash, CR_RESPONSE_SIZE, &prf_method);
yubikey_hex_encode(hashed_hex, (char *)hash, CR_RESPONSE_SIZE);
yubikey_hex_encode(salt_hex, (char *)salt, CR_SALT_SIZE);
rewind(f);
fd = fileno(f);
if (fd == -1)
goto out;
if (ftruncate(fd, 0))
goto out;
fprintf(f, "v2:%s:%s:%s:%u:%d\n", challenge_hex, hashed_hex, salt_hex, iterations, state->slot);
if (fflush(f) < 0)
goto out;
if (fsync(fd) < 0)
goto out;
return 1;
out:
return 0;
}
#endif /* HAVE_CR */
size_t filter_result_len(const char *filter, const char *user, char *output) {
const char *part = NULL;
size_t result = 0;
do
{
size_t len;
part = strstr(filter, "%u");
if(part)
len = part - filter;
else
len = strlen(filter);
if (output)
{
strncpy(output, filter, len);
output += len;
}
result += len;
filter += len + 2;
if(part)
{
if(output)
{
strncpy(output, user, strlen(user));
output += strlen(user);
}
result += strlen(user);
}
}
while(part);
if(output)
*output = '\0';
return(result + 1);
}
char *filter_printf(const char *filter, const char *user) {
char *result = malloc(filter_result_len(filter, user, NULL));
filter_result_len(filter, user, result);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_693_0 |
crossvul-cpp_data_good_5060_0 | /*
* X.25 Packet Layer release 002
*
* This is ALPHA test software. This code may break your machine,
* randomly fail to work with new releases, misbehave and/or generally
* screw up. It might even work.
*
* This code REQUIRES 2.1.15 or higher
*
* This module:
* This module is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* History
* X.25 001 Split from x25_subr.c
* mar/20/00 Daniela Squassoni Disabling/enabling of facilities
* negotiation.
* apr/14/05 Shaun Pereira - Allow fast select with no restriction
* on response.
*/
#define pr_fmt(fmt) "X25: " fmt
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/x25.h>
/**
* x25_parse_facilities - Parse facilities from skb into the facilities structs
*
* @skb: sk_buff to parse
* @facilities: Regular facilities, updated as facilities are found
* @dte_facs: ITU DTE facilities, updated as DTE facilities are found
* @vc_fac_mask: mask is updated with all facilities found
*
* Return codes:
* -1 - Parsing error, caller should drop call and clean up
* 0 - Parse OK, this skb has no facilities
* >0 - Parse OK, returns the length of the facilities header
*
*/
int x25_parse_facilities(struct sk_buff *skb, struct x25_facilities *facilities,
struct x25_dte_facilities *dte_facs, unsigned long *vc_fac_mask)
{
unsigned char *p;
unsigned int len;
*vc_fac_mask = 0;
/*
* The kernel knows which facilities were set on an incoming call but
* currently this information is not available to userspace. Here we
* give userspace who read incoming call facilities 0 length to indicate
* it wasn't set.
*/
dte_facs->calling_len = 0;
dte_facs->called_len = 0;
memset(dte_facs->called_ae, '\0', sizeof(dte_facs->called_ae));
memset(dte_facs->calling_ae, '\0', sizeof(dte_facs->calling_ae));
if (!pskb_may_pull(skb, 1))
return 0;
len = skb->data[0];
if (!pskb_may_pull(skb, 1 + len))
return -1;
p = skb->data + 1;
while (len > 0) {
switch (*p & X25_FAC_CLASS_MASK) {
case X25_FAC_CLASS_A:
if (len < 2)
return -1;
switch (*p) {
case X25_FAC_REVERSE:
if((p[1] & 0x81) == 0x81) {
facilities->reverse = p[1] & 0x81;
*vc_fac_mask |= X25_MASK_REVERSE;
break;
}
if((p[1] & 0x01) == 0x01) {
facilities->reverse = p[1] & 0x01;
*vc_fac_mask |= X25_MASK_REVERSE;
break;
}
if((p[1] & 0x80) == 0x80) {
facilities->reverse = p[1] & 0x80;
*vc_fac_mask |= X25_MASK_REVERSE;
break;
}
if(p[1] == 0x00) {
facilities->reverse
= X25_DEFAULT_REVERSE;
*vc_fac_mask |= X25_MASK_REVERSE;
break;
}
case X25_FAC_THROUGHPUT:
facilities->throughput = p[1];
*vc_fac_mask |= X25_MASK_THROUGHPUT;
break;
case X25_MARKER:
break;
default:
pr_debug("unknown facility "
"%02X, value %02X\n",
p[0], p[1]);
break;
}
p += 2;
len -= 2;
break;
case X25_FAC_CLASS_B:
if (len < 3)
return -1;
switch (*p) {
case X25_FAC_PACKET_SIZE:
facilities->pacsize_in = p[1];
facilities->pacsize_out = p[2];
*vc_fac_mask |= X25_MASK_PACKET_SIZE;
break;
case X25_FAC_WINDOW_SIZE:
facilities->winsize_in = p[1];
facilities->winsize_out = p[2];
*vc_fac_mask |= X25_MASK_WINDOW_SIZE;
break;
default:
pr_debug("unknown facility "
"%02X, values %02X, %02X\n",
p[0], p[1], p[2]);
break;
}
p += 3;
len -= 3;
break;
case X25_FAC_CLASS_C:
if (len < 4)
return -1;
pr_debug("unknown facility %02X, "
"values %02X, %02X, %02X\n",
p[0], p[1], p[2], p[3]);
p += 4;
len -= 4;
break;
case X25_FAC_CLASS_D:
if (len < p[1] + 2)
return -1;
switch (*p) {
case X25_FAC_CALLING_AE:
if (p[1] > X25_MAX_DTE_FACIL_LEN || p[1] <= 1)
return -1;
if (p[2] > X25_MAX_AE_LEN)
return -1;
dte_facs->calling_len = p[2];
memcpy(dte_facs->calling_ae, &p[3], p[1] - 1);
*vc_fac_mask |= X25_MASK_CALLING_AE;
break;
case X25_FAC_CALLED_AE:
if (p[1] > X25_MAX_DTE_FACIL_LEN || p[1] <= 1)
return -1;
if (p[2] > X25_MAX_AE_LEN)
return -1;
dte_facs->called_len = p[2];
memcpy(dte_facs->called_ae, &p[3], p[1] - 1);
*vc_fac_mask |= X25_MASK_CALLED_AE;
break;
default:
pr_debug("unknown facility %02X,"
"length %d\n", p[0], p[1]);
break;
}
len -= p[1] + 2;
p += p[1] + 2;
break;
}
}
return p - skb->data;
}
/*
* Create a set of facilities.
*/
int x25_create_facilities(unsigned char *buffer,
struct x25_facilities *facilities,
struct x25_dte_facilities *dte_facs, unsigned long facil_mask)
{
unsigned char *p = buffer + 1;
int len;
if (!facil_mask) {
/*
* Length of the facilities field in call_req or
* call_accept packets
*/
buffer[0] = 0;
len = 1; /* 1 byte for the length field */
return len;
}
if (facilities->reverse && (facil_mask & X25_MASK_REVERSE)) {
*p++ = X25_FAC_REVERSE;
*p++ = facilities->reverse;
}
if (facilities->throughput && (facil_mask & X25_MASK_THROUGHPUT)) {
*p++ = X25_FAC_THROUGHPUT;
*p++ = facilities->throughput;
}
if ((facilities->pacsize_in || facilities->pacsize_out) &&
(facil_mask & X25_MASK_PACKET_SIZE)) {
*p++ = X25_FAC_PACKET_SIZE;
*p++ = facilities->pacsize_in ? : facilities->pacsize_out;
*p++ = facilities->pacsize_out ? : facilities->pacsize_in;
}
if ((facilities->winsize_in || facilities->winsize_out) &&
(facil_mask & X25_MASK_WINDOW_SIZE)) {
*p++ = X25_FAC_WINDOW_SIZE;
*p++ = facilities->winsize_in ? : facilities->winsize_out;
*p++ = facilities->winsize_out ? : facilities->winsize_in;
}
if (facil_mask & (X25_MASK_CALLING_AE|X25_MASK_CALLED_AE)) {
*p++ = X25_MARKER;
*p++ = X25_DTE_SERVICES;
}
if (dte_facs->calling_len && (facil_mask & X25_MASK_CALLING_AE)) {
unsigned int bytecount = (dte_facs->calling_len + 1) >> 1;
*p++ = X25_FAC_CALLING_AE;
*p++ = 1 + bytecount;
*p++ = dte_facs->calling_len;
memcpy(p, dte_facs->calling_ae, bytecount);
p += bytecount;
}
if (dte_facs->called_len && (facil_mask & X25_MASK_CALLED_AE)) {
unsigned int bytecount = (dte_facs->called_len % 2) ?
dte_facs->called_len / 2 + 1 :
dte_facs->called_len / 2;
*p++ = X25_FAC_CALLED_AE;
*p++ = 1 + bytecount;
*p++ = dte_facs->called_len;
memcpy(p, dte_facs->called_ae, bytecount);
p+=bytecount;
}
len = p - buffer;
buffer[0] = len - 1;
return len;
}
/*
* Try to reach a compromise on a set of facilities.
*
* The only real problem is with reverse charging.
*/
int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
memset(dte, 0, sizeof(*dte));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
/*
* Limit values of certain facilities according to the capability of the
* currently attached x25 link.
*/
void x25_limit_facilities(struct x25_facilities *facilities,
struct x25_neigh *nb)
{
if (!nb->extended) {
if (facilities->winsize_in > 7) {
pr_debug("incoming winsize limited to 7\n");
facilities->winsize_in = 7;
}
if (facilities->winsize_out > 7) {
facilities->winsize_out = 7;
pr_debug("outgoing winsize limited to 7\n");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5060_0 |
crossvul-cpp_data_bad_1508_6 | /*
Copyright (C) 2011 ABRT team
Copyright (C) 2011 RedHat Inc
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Authors:
Anton Arapov <anton@redhat.com>
Arjan van de Ven <arjan@linux.intel.com>
*/
#include <syslog.h>
#include "libabrt.h"
/* How many problem dirs to create at most?
* Also causes cooldown sleep with -t if exceeded -
* useful when called from a log watcher.
*/
#define MAX_DUMPED_DD_COUNT 5
static bool world_readable_dump = false;
static bool throttle_dd_creation = false;
static const char *debug_dumps_dir = ".";
#define MAX_SCAN_BLOCK (4*1024*1024)
#define READ_AHEAD (10*1024)
static void scan_syslog_file(GList **oops_list, int fd)
{
struct stat st;
struct stat *statbuf = &st;
/* Try to not allocate an absurd amount of memory */
int sz = MAX_SCAN_BLOCK - READ_AHEAD;
/* If it's a real file, estimate size after cur pos */
off_t cur_pos = lseek(fd, 0, SEEK_CUR);
if (cur_pos >= 0 && fstat(fd, statbuf) == 0 && S_ISREG(statbuf->st_mode))
{
off_t size_to_read = statbuf->st_size - cur_pos;
if (size_to_read >= 0 && sz > size_to_read)
sz = size_to_read;
}
/*
* In theory we have a race here, since someone can spew
* to /var/log/messages before we read it in...
* We try to deal with it by reading READ_AHEAD extra.
*/
sz += READ_AHEAD;
char *buffer = xzalloc(sz);
for (;;)
{
int r = full_read(fd, buffer, sz-1);
if (r <= 0)
break;
log_debug("Read %u bytes", r);
koops_extract_oopses(oops_list, buffer, r);
//TODO: rewind to last newline?
}
free(buffer);
}
static char *list_of_tainted_modules(const char *proc_modules)
{
struct strbuf *result = strbuf_new();
const char *p = proc_modules;
for (;;)
{
const char *end = strchrnul(p, '\n');
const char *paren = strchrnul(p, '(');
/* We look for a line with this format:
* "kvm_intel 126289 0 - Live 0xf829e000 (taint_flags)"
* where taint_flags have letters
* (flags '+' and '-' indicate (un)loading, we must ignore them).
*/
while (++paren < end)
{
if ((unsigned)(toupper(*paren) - 'A') <= 'Z'-'A')
{
strbuf_append_strf(result, result->len == 0 ? "%.*s" : ",%.*s",
(int)(strchrnul(p,' ') - p), p
);
break;
}
if (*paren == ')')
break;
}
if (*end == '\0')
break;
p = end + 1;
}
if (result->len == 0)
{
strbuf_free(result);
return NULL;
}
return strbuf_free_nobuf(result);
}
static void save_oops_data_in_dump_dir(struct dump_dir *dd, char *oops, const char *proc_modules)
{
char *first_line = oops;
char *second_line = (char*)strchr(first_line, '\n'); /* never NULL */
*second_line++ = '\0';
if (first_line[0])
dd_save_text(dd, FILENAME_KERNEL, first_line);
dd_save_text(dd, FILENAME_BACKTRACE, second_line);
/* check if trace doesn't have line: 'Your BIOS is broken' */
if (strstr(second_line, "Your BIOS is broken"))
dd_save_text(dd, FILENAME_NOT_REPORTABLE,
_("A kernel problem occurred because of broken BIOS. "
"Unfortunately, such problems are not fixable by kernel maintainers."));
/* check if trace doesn't have line: 'Your hardware is unsupported' */
else if (strstr(second_line, "Your hardware is unsupported"))
dd_save_text(dd, FILENAME_NOT_REPORTABLE,
_("A kernel problem occurred, but your hardware is unsupported, "
"therefore kernel maintainers are unable to fix this problem."));
else
{
char *tainted_short = kernel_tainted_short(second_line);
if (tainted_short)
{
log_notice("Kernel is tainted '%s'", tainted_short);
dd_save_text(dd, FILENAME_TAINTED_SHORT, tainted_short);
char *tnt_long = kernel_tainted_long(tainted_short);
dd_save_text(dd, FILENAME_TAINTED_LONG, tnt_long);
free(tnt_long);
struct strbuf *reason = strbuf_new();
const char *fmt = _("A kernel problem occurred, but your kernel has been "
"tainted (flags:%s). Kernel maintainers are unable to "
"diagnose tainted reports.");
strbuf_append_strf(reason, fmt, tainted_short);
char *modlist = !proc_modules ? NULL : list_of_tainted_modules(proc_modules);
if (modlist)
{
strbuf_append_strf(reason, _(" Tainted modules: %s."), modlist);
free(modlist);
}
dd_save_text(dd, FILENAME_NOT_REPORTABLE, reason->buf);
strbuf_free(reason);
free(tainted_short);
}
}
// TODO: add "Kernel oops: " prefix, so that all oopses have recognizable FILENAME_REASON?
// kernel oops 1st line may look quite puzzling otherwise...
strchrnul(second_line, '\n')[0] = '\0';
dd_save_text(dd, FILENAME_REASON, second_line);
}
/* returns number of errors */
static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt)
{
unsigned countdown = MAX_DUMPED_DD_COUNT; /* do not report hundreds of oopses */
log_notice("Saving %u oopses as problem dirs", oops_cnt >= countdown ? countdown : oops_cnt);
char *cmdline_str = xmalloc_fopen_fgetline_fclose("/proc/cmdline");
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
char *proc_modules = xmalloc_open_read_close("/proc/modules", /*maxsize:*/ NULL);
char *suspend_stats = xmalloc_open_read_close("/sys/kernel/debug/suspend_stats", /*maxsize:*/ NULL);
time_t t = time(NULL);
const char *iso_date = iso_date_string(&t);
/* dump should be readable by all if we're run with -x */
uid_t my_euid = (uid_t)-1L;
mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH;
/* and readable only for the owner otherwise */
if (!world_readable_dump)
{
mode = DEFAULT_DUMP_DIR_MODE;
my_euid = geteuid();
}
pid_t my_pid = getpid();
unsigned idx = 0;
unsigned errors = 0;
while (idx < oops_cnt)
{
char base[sizeof("oops-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3];
sprintf(base, "oops-%s-%lu-%lu", iso_date, (long)my_pid, (long)idx);
char *path = concat_path_file(debug_dumps_dir, base);
struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode);
if (dd)
{
dd_create_basic_files(dd, /*uid:*/ my_euid, NULL);
save_oops_data_in_dump_dir(dd, (char*)g_list_nth_data(oops_list, idx++), proc_modules);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
dd_save_text(dd, FILENAME_ANALYZER, "Kerneloops");
dd_save_text(dd, FILENAME_TYPE, "Kerneloops");
if (cmdline_str)
dd_save_text(dd, FILENAME_CMDLINE, cmdline_str);
if (proc_modules)
dd_save_text(dd, "proc_modules", proc_modules);
if (fips_enabled && strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
if (suspend_stats)
dd_save_text(dd, "suspend_stats", suspend_stats);
dd_close(dd);
notify_new_path(path);
}
else
errors++;
free(path);
if (--countdown == 0)
break;
if (dd && throttle_dd_creation)
sleep(1);
}
free(cmdline_str);
free(proc_modules);
free(fips_enabled);
free(suspend_stats);
return errors;
}
int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [-vusoxm] [-d DIR]/[-D] [FILE]\n"
"\n"
"Extract oops from FILE (or standard input)"
);
enum {
OPT_v = 1 << 0,
OPT_s = 1 << 1,
OPT_o = 1 << 2,
OPT_d = 1 << 3,
OPT_D = 1 << 4,
OPT_u = 1 << 5,
OPT_x = 1 << 6,
OPT_t = 1 << 7,
OPT_m = 1 << 8,
};
char *problem_dir = NULL;
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_BOOL( 's', NULL, NULL, _("Log to syslog")),
OPT_BOOL( 'o', NULL, NULL, _("Print found oopses on standard output")),
/* oopses don't contain any sensitive info, and even
* the old koops app was showing the oopses to all users
*/
OPT_STRING('d', NULL, &debug_dumps_dir, "DIR", _("Create new problem directory in DIR for every oops found")),
OPT_BOOL( 'D', NULL, NULL, _("Same as -d DumpLocation, DumpLocation is specified in abrt.conf")),
OPT_STRING('u', NULL, &problem_dir, "PROBLEM", _("Save the extracted information in PROBLEM")),
OPT_BOOL( 'x', NULL, NULL, _("Make the problem directory world readable")),
OPT_BOOL( 't', NULL, NULL, _("Throttle problem directory creation to 1 per second")),
OPT_BOOL( 'm', NULL, NULL, _("Print search string(s) to stdout and exit")),
OPT_END()
};
unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
msg_prefix = g_progname;
if ((opts & OPT_s) || getenv("ABRT_SYSLOG"))
{
logmode = LOGMODE_JOURNAL;
}
if (opts & OPT_m)
{
map_string_t *settings = new_map_string();
load_abrt_plugin_conf_file("oops.conf", settings);
int only_fatal_mce = 1;
try_get_map_string_item_as_bool(settings, "OnlyFatalMCE", &only_fatal_mce);
free_map_string(settings);
if (only_fatal_mce)
{
regex_t mce_re;
if (regcomp(&mce_re, "^Machine .*$", REG_NOSUB) != 0)
perror_msg_and_die(_("Failed to compile regex"));
const regex_t *filter[] = { &mce_re, NULL };
koops_print_suspicious_strings_filtered(filter);
regfree(&mce_re);
}
else
koops_print_suspicious_strings();
return 1;
}
if (opts & OPT_D)
{
if (opts & OPT_d)
show_usage_and_die(program_usage_string, program_options);
load_abrt_conf();
debug_dumps_dir = g_settings_dump_location;
g_settings_dump_location = NULL;
free_abrt_conf_data();
}
argv += optind;
if (argv[0])
xmove_fd(xopen(argv[0], O_RDONLY), STDIN_FILENO);
world_readable_dump = (opts & OPT_x);
throttle_dd_creation = (opts & OPT_t);
unsigned errors = 0;
GList *oops_list = NULL;
scan_syslog_file(&oops_list, STDIN_FILENO);
int oops_cnt = g_list_length(oops_list);
if (oops_cnt != 0)
{
log("Found oopses: %d", oops_cnt);
if (opts & OPT_o)
{
int i = 0;
while (i < oops_cnt)
{
char *kernel_bt = (char*)g_list_nth_data(oops_list, i++);
char *tainted_short = kernel_tainted_short(kernel_bt);
if (tainted_short)
log("Kernel is tainted '%s'", tainted_short);
free(tainted_short);
printf("\nVersion: %s", kernel_bt);
}
}
if (opts & (OPT_d|OPT_D))
{
if (opts & OPT_D)
{
load_abrt_conf();
debug_dumps_dir = g_settings_dump_location;
}
log("Creating problem directories");
errors = create_oops_dump_dirs(oops_list, oops_cnt);
if (errors)
log("%d errors while dumping oopses", errors);
/*
* This marker in syslog file prevents us from
* re-parsing old oopses. The only problem is that we
* can't be sure here that the file we are watching
* is the same file where syslog(xxx) stuff ends up.
*/
syslog(LOG_WARNING,
"Reported %u kernel oopses to Abrt",
oops_cnt
);
}
if (opts & OPT_u)
{
log("Updating problem directory");
switch (oops_cnt)
{
case 1:
{
struct dump_dir *dd = dd_opendir(problem_dir, /*open for writing*/0);
if (dd)
{
save_oops_data_in_dump_dir(dd, (char *)oops_list->data, /*no proc modules*/NULL);
dd_close(dd);
}
}
break;
default:
error_msg(_("Can't update the problem: more than one oops found"));
break;
}
}
}
list_free_with_free(oops_list);
//oops_list = NULL;
/* If we are run by a log watcher, this delays log rescan
* (because log watcher waits to us to terminate)
* and possibly prevents dreaded "abrt storm".
*/
int unreported_cnt = oops_cnt - MAX_DUMPED_DD_COUNT;
if (unreported_cnt > 0 && throttle_dd_creation)
{
/* Quadratic throttle time growth, but careful to not overflow in "n*n" */
int n = unreported_cnt > 30 ? 30 : unreported_cnt;
n = n * n;
if (n > 9)
log(_("Sleeping for %d seconds"), n);
sleep(n); /* max 15 mins */
}
return errors;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1508_6 |
crossvul-cpp_data_good_867_0 | /*
* Copyright (C) 2014-2019 Yubico AB - See COPYING
*/
/* Define which PAM interfaces we provide */
#define PAM_SM_AUTH
/* Include PAM headers */
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>
#include <pwd.h>
#include <string.h>
#include <errno.h>
#include "util.h"
/* If secure_getenv is not defined, define it here */
#ifndef HAVE_SECURE_GETENV
char *secure_getenv(const char *);
char *secure_getenv(const char *name) {
(void)name;
return NULL;
}
#endif
static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {
struct stat st;
FILE *file = NULL;
int fd = -1;
int i;
memset(cfg, 0, sizeof(cfg_t));
cfg->debug_file = stderr;
for (i = 0; i < argc; i++) {
if (strncmp(argv[i], "max_devices=", 12) == 0)
sscanf(argv[i], "max_devices=%u", &cfg->max_devs);
if (strcmp(argv[i], "manual") == 0)
cfg->manual = 1;
if (strcmp(argv[i], "debug") == 0)
cfg->debug = 1;
if (strcmp(argv[i], "nouserok") == 0)
cfg->nouserok = 1;
if (strcmp(argv[i], "openasuser") == 0)
cfg->openasuser = 1;
if (strcmp(argv[i], "alwaysok") == 0)
cfg->alwaysok = 1;
if (strcmp(argv[i], "interactive") == 0)
cfg->interactive = 1;
if (strcmp(argv[i], "cue") == 0)
cfg->cue = 1;
if (strcmp(argv[i], "nodetect") == 0)
cfg->nodetect = 1;
if (strncmp(argv[i], "authfile=", 9) == 0)
cfg->auth_file = argv[i] + 9;
if (strncmp(argv[i], "authpending_file=", 17) == 0)
cfg->authpending_file = argv[i] + 17;
if (strncmp(argv[i], "origin=", 7) == 0)
cfg->origin = argv[i] + 7;
if (strncmp(argv[i], "appid=", 6) == 0)
cfg->appid = argv[i] + 6;
if (strncmp(argv[i], "prompt=", 7) == 0)
cfg->prompt = argv[i] + 7;
if (strncmp (argv[i], "debug_file=", 11) == 0) {
const char *filename = argv[i] + 11;
if(strncmp (filename, "stdout", 6) == 0) {
cfg->debug_file = stdout;
}
else if(strncmp (filename, "stderr", 6) == 0) {
cfg->debug_file = stderr;
}
else if( strncmp (filename, "syslog", 6) == 0) {
cfg->debug_file = (FILE *)-1;
}
else {
fd = open(filename, O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY);
if (fd >= 0 && (fstat(fd, &st) == 0) && S_ISREG(st.st_mode)) {
file = fdopen(fd, "a");
if(file != NULL) {
cfg->debug_file = file;
cfg->is_custom_debug_file = 1;
file = NULL;
fd = -1;
}
}
}
}
}
if (cfg->debug) {
D(cfg->debug_file, "called.");
D(cfg->debug_file, "flags %d argc %d", flags, argc);
for (i = 0; i < argc; i++) {
D(cfg->debug_file, "argv[%d]=%s", i, argv[i]);
}
D(cfg->debug_file, "max_devices=%d", cfg->max_devs);
D(cfg->debug_file, "debug=%d", cfg->debug);
D(cfg->debug_file, "interactive=%d", cfg->interactive);
D(cfg->debug_file, "cue=%d", cfg->cue);
D(cfg->debug_file, "nodetect=%d", cfg->nodetect);
D(cfg->debug_file, "manual=%d", cfg->manual);
D(cfg->debug_file, "nouserok=%d", cfg->nouserok);
D(cfg->debug_file, "openasuser=%d", cfg->openasuser);
D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok);
D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)");
D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)");
D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)");
D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)");
D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)");
}
if (fd != -1)
close(fd);
if (file != NULL)
fclose(file);
}
#ifdef DBG
#undef DBG
#endif
#define DBG(...) \
if (cfg->debug) { \
D(cfg->debug_file, __VA_ARGS__); \
}
/* PAM entry point for authentication verification */
int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc,
const char **argv) {
struct passwd *pw = NULL, pw_s;
const char *user = NULL;
cfg_t cfg_st;
cfg_t *cfg = &cfg_st;
char buffer[BUFSIZE];
char *buf = NULL;
char *authfile_dir;
size_t authfile_dir_len;
int pgu_ret, gpn_ret;
int retval = PAM_IGNORE;
device_t *devices = NULL;
unsigned n_devices = 0;
int openasuser;
int should_free_origin = 0;
int should_free_appid = 0;
int should_free_auth_file = 0;
int should_free_authpending_file = 0;
parse_cfg(flags, argc, argv, cfg);
if (!cfg->origin) {
strcpy(buffer, DEFAULT_ORIGIN_PREFIX);
if (gethostname(buffer + strlen(DEFAULT_ORIGIN_PREFIX),
BUFSIZE - strlen(DEFAULT_ORIGIN_PREFIX)) == -1) {
DBG("Unable to get host name");
goto done;
}
DBG("Origin not specified, using \"%s\"", buffer);
cfg->origin = strdup(buffer);
if (!cfg->origin) {
DBG("Unable to allocate memory");
goto done;
} else {
should_free_origin = 1;
}
}
if (!cfg->appid) {
DBG("Appid not specified, using the same value of origin (%s)",
cfg->origin);
cfg->appid = strdup(cfg->origin);
if (!cfg->appid) {
DBG("Unable to allocate memory")
goto done;
} else {
should_free_appid = 1;
}
}
if (cfg->max_devs == 0) {
DBG("Maximum devices number not set. Using default (%d)", MAX_DEVS);
cfg->max_devs = MAX_DEVS;
}
devices = malloc(sizeof(device_t) * cfg->max_devs);
if (!devices) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
pgu_ret = pam_get_user(pamh, &user, NULL);
if (pgu_ret != PAM_SUCCESS || user == NULL) {
DBG("Unable to access user %s", user);
retval = PAM_CONV_ERR;
goto done;
}
DBG("Requesting authentication for user %s", user);
gpn_ret = getpwnam_r(user, &pw_s, buffer, sizeof(buffer), &pw);
if (gpn_ret != 0 || pw == NULL || pw->pw_dir == NULL ||
pw->pw_dir[0] != '/') {
DBG("Unable to retrieve credentials for user %s, (%s)", user,
strerror(errno));
retval = PAM_USER_UNKNOWN;
goto done;
}
DBG("Found user %s", user);
DBG("Home directory for %s is %s", user, pw->pw_dir);
if (!cfg->auth_file) {
buf = NULL;
authfile_dir = secure_getenv(DEFAULT_AUTHFILE_DIR_VAR);
if (!authfile_dir) {
DBG("Variable %s is not set. Using default value ($HOME/.config/)",
DEFAULT_AUTHFILE_DIR_VAR);
authfile_dir_len =
strlen(pw->pw_dir) + strlen("/.config") + strlen(DEFAULT_AUTHFILE) + 1;
buf = malloc(sizeof(char) * (authfile_dir_len));
if (!buf) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
snprintf(buf, authfile_dir_len,
"%s/.config%s", pw->pw_dir, DEFAULT_AUTHFILE);
} else {
DBG("Variable %s set to %s", DEFAULT_AUTHFILE_DIR_VAR, authfile_dir);
authfile_dir_len = strlen(authfile_dir) + strlen(DEFAULT_AUTHFILE) + 1;
buf = malloc(sizeof(char) * (authfile_dir_len));
if (!buf) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
snprintf(buf, authfile_dir_len,
"%s%s", authfile_dir, DEFAULT_AUTHFILE);
}
DBG("Using default authentication file %s", buf);
cfg->auth_file = buf; /* cfg takes ownership */
should_free_auth_file = 1;
buf = NULL;
} else {
DBG("Using authentication file %s", cfg->auth_file);
}
openasuser = geteuid() == 0 && cfg->openasuser;
if (openasuser) {
if (seteuid(pw_s.pw_uid)) {
DBG("Unable to switch user to uid %i", pw_s.pw_uid);
retval = PAM_IGNORE;
goto done;
}
DBG("Switched to uid %i", pw_s.pw_uid);
}
retval = get_devices_from_authfile(cfg->auth_file, user, cfg->max_devs,
cfg->debug, cfg->debug_file,
devices, &n_devices);
if (openasuser) {
if (seteuid(0)) {
DBG("Unable to switch back to uid 0");
retval = PAM_IGNORE;
goto done;
}
DBG("Switched back to uid 0");
}
if (retval != 1) {
// for nouserok; make sure errors in get_devices_from_authfile don't
// result in valid devices
n_devices = 0;
}
if (n_devices == 0) {
if (cfg->nouserok) {
DBG("Found no devices but nouserok specified. Skipping authentication");
retval = PAM_SUCCESS;
goto done;
} else if (retval != 1) {
DBG("Unable to get devices from file %s", cfg->auth_file);
retval = PAM_AUTHINFO_UNAVAIL;
goto done;
} else {
DBG("Found no devices. Aborting.");
retval = PAM_AUTHINFO_UNAVAIL;
goto done;
}
}
// Determine the full path for authpending_file in order to emit touch request notifications
if (!cfg->authpending_file) {
int actual_size = snprintf(buffer, BUFSIZE, DEFAULT_AUTHPENDING_FILE_PATH, getuid());
if (actual_size >= 0 && actual_size < BUFSIZE) {
cfg->authpending_file = strdup(buffer);
}
if (!cfg->authpending_file) {
DBG("Unable to allocate memory for the authpending_file, touch request notifications will not be emitted");
} else {
should_free_authpending_file = 1;
}
} else {
if (strlen(cfg->authpending_file) == 0) {
DBG("authpending_file is set to an empty value, touch request notifications will be disabled");
cfg->authpending_file = NULL;
}
}
int authpending_file_descriptor = -1;
if (cfg->authpending_file) {
DBG("Using file '%s' for emitting touch request notifications", cfg->authpending_file);
// Open (or create) the authpending_file to indicate that we start waiting for a touch
authpending_file_descriptor =
open(cfg->authpending_file, O_RDONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY, 0664);
if (authpending_file_descriptor < 0) {
DBG("Unable to emit 'authentication started' notification by opening the file '%s', (%s)",
cfg->authpending_file, strerror(errno));
}
}
if (cfg->manual == 0) {
if (cfg->interactive) {
converse(pamh, PAM_PROMPT_ECHO_ON,
cfg->prompt != NULL ? cfg->prompt : DEFAULT_PROMPT);
}
retval = do_authentication(cfg, devices, n_devices, pamh);
} else {
retval = do_manual_authentication(cfg, devices, n_devices, pamh);
}
// Close the authpending_file to indicate that we stop waiting for a touch
if (authpending_file_descriptor >= 0) {
if (close(authpending_file_descriptor) < 0) {
DBG("Unable to emit 'authentication stopped' notification by closing the file '%s', (%s)",
cfg->authpending_file, strerror(errno));
}
}
if (retval != 1) {
DBG("do_authentication returned %d", retval);
retval = PAM_AUTH_ERR;
goto done;
}
retval = PAM_SUCCESS;
done:
free_devices(devices, n_devices);
if (buf) {
free(buf);
buf = NULL;
}
if (should_free_origin) {
free((char *) cfg->origin);
cfg->origin = NULL;
}
if (should_free_appid) {
free((char *) cfg->appid);
cfg->appid = NULL;
}
if (should_free_auth_file) {
free((char *) cfg->auth_file);
cfg->auth_file = NULL;
}
if (should_free_authpending_file) {
free((char *) cfg->authpending_file);
cfg->authpending_file = NULL;
}
if (cfg->alwaysok && retval != PAM_SUCCESS) {
DBG("alwaysok needed (otherwise return with %d)", retval);
retval = PAM_SUCCESS;
}
DBG("done. [%s]", pam_strerror(pamh, retval));
if (cfg->is_custom_debug_file) {
fclose(cfg->debug_file);
}
return retval;
}
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc,
const char **argv) {
(void)pamh;
(void)flags;
(void)argc;
(void)argv;
return PAM_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_867_0 |
crossvul-cpp_data_bad_1405_1 | /* tracked memory
*
* 2/11/99 JC
* - from im_open.c and callback.c
* - malloc tracking stuff added
* 11/3/01 JC
* - im_strncpy() added
* 20/4/01 JC
* - im_(v)snprintf() added
* 6/7/05
* - more tracking for DEBUGM
* 20/10/06
* - return NULL for size <= 0
* 11/5/06
* - abort() on malloc() failure with DEBUG
* 20/10/09
* - gtkdoc comment
* 6/11/09
* - im_malloc()/im_free() now call g_try_malloc()/g_free() ... removes
* confusion over whether to use im_free() or g_free() for things like
* im_header_string()
* 21/9/11
* - rename as vips_tracked_malloc() to emphasise difference from
* g_malloc()/g_free()
*/
/*
This file is part of VIPS.
VIPS is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_IO_H
#include <io.h>
#endif /*HAVE_IO_H*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <vips/vips.h>
#include <vips/thread.h>
/**
* SECTION: memory
* @short_description: memory utilities
* @stability: Stable
* @include: vips/vips.h
*
* These functions cover two main areas.
*
* First, some simple utility functions over the underlying
* g_malloc()/g_free() functions. Memory allocated and freeded using these
* functions is interchangeable with any other glib library.
*
* Second, a pair of functions, vips_tracked_malloc() and vips_tracked_free(),
* which are NOT compatible. If you g_free() memory that has been allocated
* with vips_tracked_malloc() you will see crashes.
*
* The tracked functions are
* only suitable for large allocations internal to the library, for example
* pixel buffers. libvips watches the total amount of live tracked memory and
* uses this information to decide when to trim caches.
*/
/* g_assert_not_reached() on memory errors.
#define DEBUG
*/
/* Track malloc/free and open/close.
#define DEBUG_VERBOSE
*/
#ifdef DEBUG
# warning DEBUG on in libsrc/iofuncs/memory.c
#endif /*DEBUG*/
static int vips_tracked_allocs = 0;
static size_t vips_tracked_mem = 0;
static int vips_tracked_files = 0;
static size_t vips_tracked_mem_highwater = 0;
static GMutex *vips_tracked_mutex = NULL;
/**
* VIPS_NEW:
* @OBJ: allocate memory local to @OBJ, or %NULL for no auto-free
* @T: type of thing to allocate
*
* Allocate memory for a thing of type @T. The memory is not
* cleared.
*
* This macro cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_malloc().
*
* Returns: A pointer of type @T *.
*/
/**
* VIPS_ARRAY:
* @OBJ: allocate memory local to @OBJ, or %NULL for no auto-free
* @N: number of @T 's to allocate
* @T: type of thing to allocate
*
* Allocate memory for an array of objects of type @T. The memory is not
* cleared.
*
* This macro cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_malloc().
*
* Returns: A pointer of type @T *.
*/
static void
vips_malloc_cb( VipsObject *object, char *buf )
{
g_free( buf );
}
/**
* vips_malloc:
* @object: (nullable): allocate memory local to this #VipsObject, or %NULL
* @size: number of bytes to allocate
*
* g_malloc() local to @object, that is, the memory will be automatically
* freed for you when the object is closed. If @object is %NULL, you need to
* free the memory explicitly with g_free().
*
* This function cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_tracked_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory.
*/
void *
vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
/**
* vips_strdup:
* @object: (nullable): allocate memory local to this #VipsObject, or %NULL
* @str: string to copy
*
* g_strdup() a string. When @object is freed, the string will be freed for
* you. If @object is %NULL, you need to
* free the memory yourself with g_free().
*
* This function cannot fail.
*
* See also: vips_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory
*/
char *
vips_strdup( VipsObject *object, const char *str )
{
char *str_dup;
str_dup = g_strdup( str );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), str_dup );
object->local_memory += strlen( str );
}
return( str_dup );
}
/**
* vips_free:
* @buf: memory to free
*
* Frees memory with g_free() and returns 0. Handy for callbacks.
*
* See also: vips_malloc().
*
* Returns: 0
*/
int
vips_free( void *buf )
{
g_free( buf );
return( 0 );
}
/**
* vips_tracked_free:
* @s: (transfer full): memory to free
*
* Only use it to free
* memory that was previously allocated with vips_tracked_malloc() with a
* %NULL first argument.
*
* See also: vips_tracked_malloc().
*/
void
vips_tracked_free( void *s )
{
/* Keep the size of the alloc in the previous 16 bytes. Ensures
* alignment rules are kept.
*/
void *start = (void *) ((char *) s - 16);
size_t size = *((size_t *) start);
g_mutex_lock( vips_tracked_mutex );
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_free: %p, %zd bytes\n", s, size );
#endif /*DEBUG_VERBOSE*/
if( vips_tracked_allocs <= 0 )
g_warning( "%s", _( "vips_free: too many frees" ) );
if( vips_tracked_mem < size )
g_warning( "%s", _( "vips_free: too much free" ) );
vips_tracked_mem -= size;
vips_tracked_allocs -= 1;
g_mutex_unlock( vips_tracked_mutex );
g_free( start );
VIPS_GATE_FREE( size );
}
static void
vips_tracked_init_mutex( void )
{
vips_tracked_mutex = vips_g_mutex_new();
}
static void
vips_tracked_init( void )
{
static GOnce vips_tracked_once = G_ONCE_INIT;
VIPS_ONCE( &vips_tracked_once,
(GThreadFunc) vips_tracked_init_mutex, NULL );
}
/**
* vips_tracked_malloc:
* @size: number of bytes to allocate
*
* Allocate an area of memory that will be tracked by vips_tracked_get_mem()
* and friends.
*
* If allocation fails, vips_malloc() returns %NULL and
* sets an error message.
*
* You must only free the memory returned with vips_tracked_free().
*
* See also: vips_tracked_free(), vips_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory, or %NULL on error.
*/
void *
vips_tracked_malloc( size_t size )
{
void *buf;
vips_tracked_init();
/* Need an extra sizeof(size_t) bytes to track
* size of this block. Ask for an extra 16 to make sure we don't break
* alignment rules.
*/
size += 16;
if( !(buf = g_try_malloc( size )) ) {
#ifdef DEBUG
g_assert_not_reached();
#endif /*DEBUG*/
vips_error( "vips_tracked",
_( "out of memory --- size == %dMB" ),
(int) (size / (1024.0 * 1024.0)) );
g_warning( _( "out of memory --- size == %dMB" ),
(int) (size / (1024.0 * 1024.0)) );
return( NULL );
}
g_mutex_lock( vips_tracked_mutex );
*((size_t *)buf) = size;
buf = (void *) ((char *)buf + 16);
vips_tracked_mem += size;
if( vips_tracked_mem > vips_tracked_mem_highwater )
vips_tracked_mem_highwater = vips_tracked_mem;
vips_tracked_allocs += 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_malloc: %p, %zd bytes\n", buf, size );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
VIPS_GATE_MALLOC( size );
return( buf );
}
/**
* vips_tracked_open:
* @pathname: name of file to open
* @flags: flags for open()
* @...: open mode
*
* Exactly as open(2), but the number of files current open via
* vips_tracked_open() is available via vips_tracked_get_files(). This is used
* by the vips operation cache to drop cache when the number of files
* available is low.
*
* You must only close the file descriptor with vips_tracked_close().
*
* See also: vips_tracked_close(), vips_tracked_get_files().
*
* Returns: a file descriptor, or -1 on error.
*/
int
vips_tracked_open( const char *pathname, int flags, ... )
{
int fd;
mode_t mode;
va_list ap;
/* mode_t is promoted to int in ..., so we have to pull it out as an
* int.
*/
va_start( ap, flags );
mode = va_arg( ap, int );
va_end( ap );
if( (fd = vips__open( pathname, flags, mode )) == -1 )
return( -1 );
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
vips_tracked_files += 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_open: %s = %d (%d)\n",
pathname, fd, vips_tracked_files );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
return( fd );
}
/**
* vips_tracked_close:
* @fd: file to close()
*
* Exactly as close(2), but update the number of files currently open via
* vips_tracked_get_files(). This is used
* by the vips operation cache to drop cache when the number of files
* available is low.
*
* You must only close file descriptors opened with vips_tracked_open().
*
* See also: vips_tracked_open(), vips_tracked_get_files().
*
* Returns: a file descriptor, or -1 on error.
*/
int
vips_tracked_close( int fd )
{
int result;
g_mutex_lock( vips_tracked_mutex );
g_assert( vips_tracked_files > 0 );
vips_tracked_files -= 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_close: %d (%d)\n", fd, vips_tracked_files );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
result = close( fd );
return( result );
}
/**
* vips_tracked_get_mem:
*
* Returns the number of bytes currently allocated via vips_malloc() and
* friends. vips uses this figure to decide when to start dropping cache, see
* #VipsOperation.
*
* Returns: the number of currently allocated bytes
*/
size_t
vips_tracked_get_mem( void )
{
size_t mem;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
mem = vips_tracked_mem;
g_mutex_unlock( vips_tracked_mutex );
return( mem );
}
/**
* vips_tracked_get_mem_highwater:
*
* Returns the largest number of bytes simultaneously allocated via
* vips_tracked_malloc(). Handy for estimating max memory requirements for a
* program.
*
* Returns: the largest number of currently allocated bytes
*/
size_t
vips_tracked_get_mem_highwater( void )
{
size_t mx;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
mx = vips_tracked_mem_highwater;
g_mutex_unlock( vips_tracked_mutex );
return( mx );
}
/**
* vips_tracked_get_allocs:
*
* Returns the number of active allocations.
*
* Returns: the number of active allocations
*/
int
vips_tracked_get_allocs( void )
{
int n;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
n = vips_tracked_allocs;
g_mutex_unlock( vips_tracked_mutex );
return( n );
}
/**
* vips_tracked_get_files:
*
* Returns the number of open files.
*
* Returns: the number of open files
*/
int
vips_tracked_get_files( void )
{
int n;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
n = vips_tracked_files;
g_mutex_unlock( vips_tracked_mutex );
return( n );
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1405_1 |
crossvul-cpp_data_good_5048_0 | /*****************************************************************************/
/*
* devio.c -- User space communication with USB devices.
*
* Copyright (C) 1999-2000 Thomas Sailer (sailer@ife.ee.ethz.ch)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* This file implements the usbfs/x/y files, where
* x is the bus number and y the device number.
*
* It allows user space programs/"drivers" to communicate directly
* with USB devices without intervening kernel driver.
*
* Revision history
* 22.12.1999 0.1 Initial release (split from proc_usb.c)
* 04.01.2000 0.2 Turned into its own filesystem
* 30.09.2005 0.3 Fix user-triggerable oops in async URB delivery
* (CAN-2005-3055)
*/
/*****************************************************************************/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/signal.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <linux/usb/hcd.h> /* for usbcore internals */
#include <linux/cdev.h>
#include <linux/notifier.h>
#include <linux/security.h>
#include <linux/user_namespace.h>
#include <linux/scatterlist.h>
#include <linux/uaccess.h>
#include <linux/dma-mapping.h>
#include <asm/byteorder.h>
#include <linux/moduleparam.h>
#include "usb.h"
#define USB_MAXBUS 64
#define USB_DEVICE_MAX (USB_MAXBUS * 128)
#define USB_SG_SIZE 16384 /* split-size for large txs */
/* Mutual exclusion for removal, open, and release */
DEFINE_MUTEX(usbfs_mutex);
struct usb_dev_state {
struct list_head list; /* state list */
struct usb_device *dev;
struct file *file;
spinlock_t lock; /* protects the async urb lists */
struct list_head async_pending;
struct list_head async_completed;
struct list_head memory_list;
wait_queue_head_t wait; /* wake up if a request completed */
unsigned int discsignr;
struct pid *disc_pid;
const struct cred *cred;
void __user *disccontext;
unsigned long ifclaimed;
u32 secid;
u32 disabled_bulk_eps;
bool privileges_dropped;
unsigned long interface_allowed_mask;
};
struct usb_memory {
struct list_head memlist;
int vma_use_count;
int urb_use_count;
u32 size;
void *mem;
dma_addr_t dma_handle;
unsigned long vm_start;
struct usb_dev_state *ps;
};
struct async {
struct list_head asynclist;
struct usb_dev_state *ps;
struct pid *pid;
const struct cred *cred;
unsigned int signr;
unsigned int ifnum;
void __user *userbuffer;
void __user *userurb;
struct urb *urb;
struct usb_memory *usbm;
unsigned int mem_usage;
int status;
u32 secid;
u8 bulk_addr;
u8 bulk_status;
};
static bool usbfs_snoop;
module_param(usbfs_snoop, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(usbfs_snoop, "true to log all usbfs traffic");
static unsigned usbfs_snoop_max = 65536;
module_param(usbfs_snoop_max, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(usbfs_snoop_max,
"maximum number of bytes to print while snooping");
#define snoop(dev, format, arg...) \
do { \
if (usbfs_snoop) \
dev_info(dev, format, ## arg); \
} while (0)
enum snoop_when {
SUBMIT, COMPLETE
};
#define USB_DEVICE_DEV MKDEV(USB_DEVICE_MAJOR, 0)
/* Limit on the total amount of memory we can allocate for transfers */
static unsigned usbfs_memory_mb = 16;
module_param(usbfs_memory_mb, uint, 0644);
MODULE_PARM_DESC(usbfs_memory_mb,
"maximum MB allowed for usbfs buffers (0 = no limit)");
/* Hard limit, necessary to avoid arithmetic overflow */
#define USBFS_XFER_MAX (UINT_MAX / 2 - 1000000)
static atomic_t usbfs_memory_usage; /* Total memory currently allocated */
/* Check whether it's okay to allocate more memory for a transfer */
static int usbfs_increase_memory_usage(unsigned amount)
{
unsigned lim;
/*
* Convert usbfs_memory_mb to bytes, avoiding overflows.
* 0 means use the hard limit (effectively unlimited).
*/
lim = ACCESS_ONCE(usbfs_memory_mb);
if (lim == 0 || lim > (USBFS_XFER_MAX >> 20))
lim = USBFS_XFER_MAX;
else
lim <<= 20;
atomic_add(amount, &usbfs_memory_usage);
if (atomic_read(&usbfs_memory_usage) <= lim)
return 0;
atomic_sub(amount, &usbfs_memory_usage);
return -ENOMEM;
}
/* Memory for a transfer is being deallocated */
static void usbfs_decrease_memory_usage(unsigned amount)
{
atomic_sub(amount, &usbfs_memory_usage);
}
static int connected(struct usb_dev_state *ps)
{
return (!list_empty(&ps->list) &&
ps->dev->state != USB_STATE_NOTATTACHED);
}
static void dec_usb_memory_use_count(struct usb_memory *usbm, int *count)
{
struct usb_dev_state *ps = usbm->ps;
unsigned long flags;
spin_lock_irqsave(&ps->lock, flags);
--*count;
if (usbm->urb_use_count == 0 && usbm->vma_use_count == 0) {
list_del(&usbm->memlist);
spin_unlock_irqrestore(&ps->lock, flags);
usb_free_coherent(ps->dev, usbm->size, usbm->mem,
usbm->dma_handle);
usbfs_decrease_memory_usage(
usbm->size + sizeof(struct usb_memory));
kfree(usbm);
} else {
spin_unlock_irqrestore(&ps->lock, flags);
}
}
static void usbdev_vm_open(struct vm_area_struct *vma)
{
struct usb_memory *usbm = vma->vm_private_data;
unsigned long flags;
spin_lock_irqsave(&usbm->ps->lock, flags);
++usbm->vma_use_count;
spin_unlock_irqrestore(&usbm->ps->lock, flags);
}
static void usbdev_vm_close(struct vm_area_struct *vma)
{
struct usb_memory *usbm = vma->vm_private_data;
dec_usb_memory_use_count(usbm, &usbm->vma_use_count);
}
static struct vm_operations_struct usbdev_vm_ops = {
.open = usbdev_vm_open,
.close = usbdev_vm_close
};
static int usbdev_mmap(struct file *file, struct vm_area_struct *vma)
{
struct usb_memory *usbm = NULL;
struct usb_dev_state *ps = file->private_data;
size_t size = vma->vm_end - vma->vm_start;
void *mem;
unsigned long flags;
dma_addr_t dma_handle;
int ret;
ret = usbfs_increase_memory_usage(size + sizeof(struct usb_memory));
if (ret)
goto error;
usbm = kzalloc(sizeof(struct usb_memory), GFP_KERNEL);
if (!usbm) {
ret = -ENOMEM;
goto error_decrease_mem;
}
mem = usb_alloc_coherent(ps->dev, size, GFP_USER, &dma_handle);
if (!mem) {
ret = -ENOMEM;
goto error_free_usbm;
}
memset(mem, 0, size);
usbm->mem = mem;
usbm->dma_handle = dma_handle;
usbm->size = size;
usbm->ps = ps;
usbm->vm_start = vma->vm_start;
usbm->vma_use_count = 1;
INIT_LIST_HEAD(&usbm->memlist);
if (remap_pfn_range(vma, vma->vm_start,
virt_to_phys(usbm->mem) >> PAGE_SHIFT,
size, vma->vm_page_prot) < 0) {
dec_usb_memory_use_count(usbm, &usbm->vma_use_count);
return -EAGAIN;
}
vma->vm_flags |= VM_IO;
vma->vm_flags |= (VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_ops = &usbdev_vm_ops;
vma->vm_private_data = usbm;
spin_lock_irqsave(&ps->lock, flags);
list_add_tail(&usbm->memlist, &ps->memory_list);
spin_unlock_irqrestore(&ps->lock, flags);
return 0;
error_free_usbm:
kfree(usbm);
error_decrease_mem:
usbfs_decrease_memory_usage(size + sizeof(struct usb_memory));
error:
return ret;
}
static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes,
loff_t *ppos)
{
struct usb_dev_state *ps = file->private_data;
struct usb_device *dev = ps->dev;
ssize_t ret = 0;
unsigned len;
loff_t pos;
int i;
pos = *ppos;
usb_lock_device(dev);
if (!connected(ps)) {
ret = -ENODEV;
goto err;
} else if (pos < 0) {
ret = -EINVAL;
goto err;
}
if (pos < sizeof(struct usb_device_descriptor)) {
/* 18 bytes - fits on the stack */
struct usb_device_descriptor temp_desc;
memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor));
le16_to_cpus(&temp_desc.bcdUSB);
le16_to_cpus(&temp_desc.idVendor);
le16_to_cpus(&temp_desc.idProduct);
le16_to_cpus(&temp_desc.bcdDevice);
len = sizeof(struct usb_device_descriptor) - pos;
if (len > nbytes)
len = nbytes;
if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) {
ret = -EFAULT;
goto err;
}
*ppos += len;
buf += len;
nbytes -= len;
ret += len;
}
pos = sizeof(struct usb_device_descriptor);
for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) {
struct usb_config_descriptor *config =
(struct usb_config_descriptor *)dev->rawdescriptors[i];
unsigned int length = le16_to_cpu(config->wTotalLength);
if (*ppos < pos + length) {
/* The descriptor may claim to be longer than it
* really is. Here is the actual allocated length. */
unsigned alloclen =
le16_to_cpu(dev->config[i].desc.wTotalLength);
len = length - (*ppos - pos);
if (len > nbytes)
len = nbytes;
/* Simply don't write (skip over) unallocated parts */
if (alloclen > (*ppos - pos)) {
alloclen -= (*ppos - pos);
if (copy_to_user(buf,
dev->rawdescriptors[i] + (*ppos - pos),
min(len, alloclen))) {
ret = -EFAULT;
goto err;
}
}
*ppos += len;
buf += len;
nbytes -= len;
ret += len;
}
pos += length;
}
err:
usb_unlock_device(dev);
return ret;
}
/*
* async list handling
*/
static struct async *alloc_async(unsigned int numisoframes)
{
struct async *as;
as = kzalloc(sizeof(struct async), GFP_KERNEL);
if (!as)
return NULL;
as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL);
if (!as->urb) {
kfree(as);
return NULL;
}
return as;
}
static void free_async(struct async *as)
{
int i;
put_pid(as->pid);
if (as->cred)
put_cred(as->cred);
for (i = 0; i < as->urb->num_sgs; i++) {
if (sg_page(&as->urb->sg[i]))
kfree(sg_virt(&as->urb->sg[i]));
}
kfree(as->urb->sg);
if (as->usbm == NULL)
kfree(as->urb->transfer_buffer);
else
dec_usb_memory_use_count(as->usbm, &as->usbm->urb_use_count);
kfree(as->urb->setup_packet);
usb_free_urb(as->urb);
usbfs_decrease_memory_usage(as->mem_usage);
kfree(as);
}
static void async_newpending(struct async *as)
{
struct usb_dev_state *ps = as->ps;
unsigned long flags;
spin_lock_irqsave(&ps->lock, flags);
list_add_tail(&as->asynclist, &ps->async_pending);
spin_unlock_irqrestore(&ps->lock, flags);
}
static void async_removepending(struct async *as)
{
struct usb_dev_state *ps = as->ps;
unsigned long flags;
spin_lock_irqsave(&ps->lock, flags);
list_del_init(&as->asynclist);
spin_unlock_irqrestore(&ps->lock, flags);
}
static struct async *async_getcompleted(struct usb_dev_state *ps)
{
unsigned long flags;
struct async *as = NULL;
spin_lock_irqsave(&ps->lock, flags);
if (!list_empty(&ps->async_completed)) {
as = list_entry(ps->async_completed.next, struct async,
asynclist);
list_del_init(&as->asynclist);
}
spin_unlock_irqrestore(&ps->lock, flags);
return as;
}
static struct async *async_getpending(struct usb_dev_state *ps,
void __user *userurb)
{
struct async *as;
list_for_each_entry(as, &ps->async_pending, asynclist)
if (as->userurb == userurb) {
list_del_init(&as->asynclist);
return as;
}
return NULL;
}
static void snoop_urb(struct usb_device *udev,
void __user *userurb, int pipe, unsigned length,
int timeout_or_status, enum snoop_when when,
unsigned char *data, unsigned data_len)
{
static const char *types[] = {"isoc", "int", "ctrl", "bulk"};
static const char *dirs[] = {"out", "in"};
int ep;
const char *t, *d;
if (!usbfs_snoop)
return;
ep = usb_pipeendpoint(pipe);
t = types[usb_pipetype(pipe)];
d = dirs[!!usb_pipein(pipe)];
if (userurb) { /* Async */
if (when == SUBMIT)
dev_info(&udev->dev, "userurb %p, ep%d %s-%s, "
"length %u\n",
userurb, ep, t, d, length);
else
dev_info(&udev->dev, "userurb %p, ep%d %s-%s, "
"actual_length %u status %d\n",
userurb, ep, t, d, length,
timeout_or_status);
} else {
if (when == SUBMIT)
dev_info(&udev->dev, "ep%d %s-%s, length %u, "
"timeout %d\n",
ep, t, d, length, timeout_or_status);
else
dev_info(&udev->dev, "ep%d %s-%s, actual_length %u, "
"status %d\n",
ep, t, d, length, timeout_or_status);
}
data_len = min(data_len, usbfs_snoop_max);
if (data && data_len > 0) {
print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
data, data_len, 1);
}
}
static void snoop_urb_data(struct urb *urb, unsigned len)
{
int i, size;
len = min(len, usbfs_snoop_max);
if (!usbfs_snoop || len == 0)
return;
if (urb->num_sgs == 0) {
print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
urb->transfer_buffer, len, 1);
return;
}
for (i = 0; i < urb->num_sgs && len; i++) {
size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len;
print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
sg_virt(&urb->sg[i]), size, 1);
len -= size;
}
}
static int copy_urb_data_to_user(u8 __user *userbuffer, struct urb *urb)
{
unsigned i, len, size;
if (urb->number_of_packets > 0) /* Isochronous */
len = urb->transfer_buffer_length;
else /* Non-Isoc */
len = urb->actual_length;
if (urb->num_sgs == 0) {
if (copy_to_user(userbuffer, urb->transfer_buffer, len))
return -EFAULT;
return 0;
}
for (i = 0; i < urb->num_sgs && len; i++) {
size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len;
if (copy_to_user(userbuffer, sg_virt(&urb->sg[i]), size))
return -EFAULT;
userbuffer += size;
len -= size;
}
return 0;
}
#define AS_CONTINUATION 1
#define AS_UNLINK 2
static void cancel_bulk_urbs(struct usb_dev_state *ps, unsigned bulk_addr)
__releases(ps->lock)
__acquires(ps->lock)
{
struct urb *urb;
struct async *as;
/* Mark all the pending URBs that match bulk_addr, up to but not
* including the first one without AS_CONTINUATION. If such an
* URB is encountered then a new transfer has already started so
* the endpoint doesn't need to be disabled; otherwise it does.
*/
list_for_each_entry(as, &ps->async_pending, asynclist) {
if (as->bulk_addr == bulk_addr) {
if (as->bulk_status != AS_CONTINUATION)
goto rescan;
as->bulk_status = AS_UNLINK;
as->bulk_addr = 0;
}
}
ps->disabled_bulk_eps |= (1 << bulk_addr);
/* Now carefully unlink all the marked pending URBs */
rescan:
list_for_each_entry(as, &ps->async_pending, asynclist) {
if (as->bulk_status == AS_UNLINK) {
as->bulk_status = 0; /* Only once */
urb = as->urb;
usb_get_urb(urb);
spin_unlock(&ps->lock); /* Allow completions */
usb_unlink_urb(urb);
usb_put_urb(urb);
spin_lock(&ps->lock);
goto rescan;
}
}
}
static void async_completed(struct urb *urb)
{
struct async *as = urb->context;
struct usb_dev_state *ps = as->ps;
struct siginfo sinfo;
struct pid *pid = NULL;
u32 secid = 0;
const struct cred *cred = NULL;
int signr;
spin_lock(&ps->lock);
list_move_tail(&as->asynclist, &ps->async_completed);
as->status = urb->status;
signr = as->signr;
if (signr) {
memset(&sinfo, 0, sizeof(sinfo));
sinfo.si_signo = as->signr;
sinfo.si_errno = as->status;
sinfo.si_code = SI_ASYNCIO;
sinfo.si_addr = as->userurb;
pid = get_pid(as->pid);
cred = get_cred(as->cred);
secid = as->secid;
}
snoop(&urb->dev->dev, "urb complete\n");
snoop_urb(urb->dev, as->userurb, urb->pipe, urb->actual_length,
as->status, COMPLETE, NULL, 0);
if ((urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN)
snoop_urb_data(urb, urb->actual_length);
if (as->status < 0 && as->bulk_addr && as->status != -ECONNRESET &&
as->status != -ENOENT)
cancel_bulk_urbs(ps, as->bulk_addr);
spin_unlock(&ps->lock);
if (signr) {
kill_pid_info_as_cred(sinfo.si_signo, &sinfo, pid, cred, secid);
put_pid(pid);
put_cred(cred);
}
wake_up(&ps->wait);
}
static void destroy_async(struct usb_dev_state *ps, struct list_head *list)
{
struct urb *urb;
struct async *as;
unsigned long flags;
spin_lock_irqsave(&ps->lock, flags);
while (!list_empty(list)) {
as = list_entry(list->next, struct async, asynclist);
list_del_init(&as->asynclist);
urb = as->urb;
usb_get_urb(urb);
/* drop the spinlock so the completion handler can run */
spin_unlock_irqrestore(&ps->lock, flags);
usb_kill_urb(urb);
usb_put_urb(urb);
spin_lock_irqsave(&ps->lock, flags);
}
spin_unlock_irqrestore(&ps->lock, flags);
}
static void destroy_async_on_interface(struct usb_dev_state *ps,
unsigned int ifnum)
{
struct list_head *p, *q, hitlist;
unsigned long flags;
INIT_LIST_HEAD(&hitlist);
spin_lock_irqsave(&ps->lock, flags);
list_for_each_safe(p, q, &ps->async_pending)
if (ifnum == list_entry(p, struct async, asynclist)->ifnum)
list_move_tail(p, &hitlist);
spin_unlock_irqrestore(&ps->lock, flags);
destroy_async(ps, &hitlist);
}
static void destroy_all_async(struct usb_dev_state *ps)
{
destroy_async(ps, &ps->async_pending);
}
/*
* interface claims are made only at the request of user level code,
* which can also release them (explicitly or by closing files).
* they're also undone when devices disconnect.
*/
static int driver_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return -ENODEV;
}
static void driver_disconnect(struct usb_interface *intf)
{
struct usb_dev_state *ps = usb_get_intfdata(intf);
unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber;
if (!ps)
return;
/* NOTE: this relies on usbcore having canceled and completed
* all pending I/O requests; 2.6 does that.
*/
if (likely(ifnum < 8*sizeof(ps->ifclaimed)))
clear_bit(ifnum, &ps->ifclaimed);
else
dev_warn(&intf->dev, "interface number %u out of range\n",
ifnum);
usb_set_intfdata(intf, NULL);
/* force async requests to complete */
destroy_async_on_interface(ps, ifnum);
}
/* The following routines are merely placeholders. There is no way
* to inform a user task about suspend or resumes.
*/
static int driver_suspend(struct usb_interface *intf, pm_message_t msg)
{
return 0;
}
static int driver_resume(struct usb_interface *intf)
{
return 0;
}
struct usb_driver usbfs_driver = {
.name = "usbfs",
.probe = driver_probe,
.disconnect = driver_disconnect,
.suspend = driver_suspend,
.resume = driver_resume,
};
static int claimintf(struct usb_dev_state *ps, unsigned int ifnum)
{
struct usb_device *dev = ps->dev;
struct usb_interface *intf;
int err;
if (ifnum >= 8*sizeof(ps->ifclaimed))
return -EINVAL;
/* already claimed */
if (test_bit(ifnum, &ps->ifclaimed))
return 0;
if (ps->privileges_dropped &&
!test_bit(ifnum, &ps->interface_allowed_mask))
return -EACCES;
intf = usb_ifnum_to_if(dev, ifnum);
if (!intf)
err = -ENOENT;
else
err = usb_driver_claim_interface(&usbfs_driver, intf, ps);
if (err == 0)
set_bit(ifnum, &ps->ifclaimed);
return err;
}
static int releaseintf(struct usb_dev_state *ps, unsigned int ifnum)
{
struct usb_device *dev;
struct usb_interface *intf;
int err;
err = -EINVAL;
if (ifnum >= 8*sizeof(ps->ifclaimed))
return err;
dev = ps->dev;
intf = usb_ifnum_to_if(dev, ifnum);
if (!intf)
err = -ENOENT;
else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) {
usb_driver_release_interface(&usbfs_driver, intf);
err = 0;
}
return err;
}
static int checkintf(struct usb_dev_state *ps, unsigned int ifnum)
{
if (ps->dev->state != USB_STATE_CONFIGURED)
return -EHOSTUNREACH;
if (ifnum >= 8*sizeof(ps->ifclaimed))
return -EINVAL;
if (test_bit(ifnum, &ps->ifclaimed))
return 0;
/* if not yet claimed, claim it for the driver */
dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim "
"interface %u before use\n", task_pid_nr(current),
current->comm, ifnum);
return claimintf(ps, ifnum);
}
static int findintfep(struct usb_device *dev, unsigned int ep)
{
unsigned int i, j, e;
struct usb_interface *intf;
struct usb_host_interface *alts;
struct usb_endpoint_descriptor *endpt;
if (ep & ~(USB_DIR_IN|0xf))
return -EINVAL;
if (!dev->actconfig)
return -ESRCH;
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
intf = dev->actconfig->interface[i];
for (j = 0; j < intf->num_altsetting; j++) {
alts = &intf->altsetting[j];
for (e = 0; e < alts->desc.bNumEndpoints; e++) {
endpt = &alts->endpoint[e].desc;
if (endpt->bEndpointAddress == ep)
return alts->desc.bInterfaceNumber;
}
}
}
return -ENOENT;
}
static int check_ctrlrecip(struct usb_dev_state *ps, unsigned int requesttype,
unsigned int request, unsigned int index)
{
int ret = 0;
struct usb_host_interface *alt_setting;
if (ps->dev->state != USB_STATE_UNAUTHENTICATED
&& ps->dev->state != USB_STATE_ADDRESS
&& ps->dev->state != USB_STATE_CONFIGURED)
return -EHOSTUNREACH;
if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype))
return 0;
/*
* check for the special corner case 'get_device_id' in the printer
* class specification, which we always want to allow as it is used
* to query things like ink level, etc.
*/
if (requesttype == 0xa1 && request == 0) {
alt_setting = usb_find_alt_setting(ps->dev->actconfig,
index >> 8, index & 0xff);
if (alt_setting
&& alt_setting->desc.bInterfaceClass == USB_CLASS_PRINTER)
return 0;
}
index &= 0xff;
switch (requesttype & USB_RECIP_MASK) {
case USB_RECIP_ENDPOINT:
if ((index & ~USB_DIR_IN) == 0)
return 0;
ret = findintfep(ps->dev, index);
if (ret < 0) {
/*
* Some not fully compliant Win apps seem to get
* index wrong and have the endpoint number here
* rather than the endpoint address (with the
* correct direction). Win does let this through,
* so we'll not reject it here but leave it to
* the device to not break KVM. But we warn.
*/
ret = findintfep(ps->dev, index ^ 0x80);
if (ret >= 0)
dev_info(&ps->dev->dev,
"%s: process %i (%s) requesting ep %02x but needs %02x\n",
__func__, task_pid_nr(current),
current->comm, index, index ^ 0x80);
}
if (ret >= 0)
ret = checkintf(ps, ret);
break;
case USB_RECIP_INTERFACE:
ret = checkintf(ps, index);
break;
}
return ret;
}
static struct usb_host_endpoint *ep_to_host_endpoint(struct usb_device *dev,
unsigned char ep)
{
if (ep & USB_ENDPOINT_DIR_MASK)
return dev->ep_in[ep & USB_ENDPOINT_NUMBER_MASK];
else
return dev->ep_out[ep & USB_ENDPOINT_NUMBER_MASK];
}
static int parse_usbdevfs_streams(struct usb_dev_state *ps,
struct usbdevfs_streams __user *streams,
unsigned int *num_streams_ret,
unsigned int *num_eps_ret,
struct usb_host_endpoint ***eps_ret,
struct usb_interface **intf_ret)
{
unsigned int i, num_streams, num_eps;
struct usb_host_endpoint **eps;
struct usb_interface *intf = NULL;
unsigned char ep;
int ifnum, ret;
if (get_user(num_streams, &streams->num_streams) ||
get_user(num_eps, &streams->num_eps))
return -EFAULT;
if (num_eps < 1 || num_eps > USB_MAXENDPOINTS)
return -EINVAL;
/* The XHCI controller allows max 2 ^ 16 streams */
if (num_streams_ret && (num_streams < 2 || num_streams > 65536))
return -EINVAL;
eps = kmalloc(num_eps * sizeof(*eps), GFP_KERNEL);
if (!eps)
return -ENOMEM;
for (i = 0; i < num_eps; i++) {
if (get_user(ep, &streams->eps[i])) {
ret = -EFAULT;
goto error;
}
eps[i] = ep_to_host_endpoint(ps->dev, ep);
if (!eps[i]) {
ret = -EINVAL;
goto error;
}
/* usb_alloc/free_streams operate on an usb_interface */
ifnum = findintfep(ps->dev, ep);
if (ifnum < 0) {
ret = ifnum;
goto error;
}
if (i == 0) {
ret = checkintf(ps, ifnum);
if (ret < 0)
goto error;
intf = usb_ifnum_to_if(ps->dev, ifnum);
} else {
/* Verify all eps belong to the same interface */
if (ifnum != intf->altsetting->desc.bInterfaceNumber) {
ret = -EINVAL;
goto error;
}
}
}
if (num_streams_ret)
*num_streams_ret = num_streams;
*num_eps_ret = num_eps;
*eps_ret = eps;
*intf_ret = intf;
return 0;
error:
kfree(eps);
return ret;
}
static int match_devt(struct device *dev, void *data)
{
return dev->devt == (dev_t) (unsigned long) data;
}
static struct usb_device *usbdev_lookup_by_devt(dev_t devt)
{
struct device *dev;
dev = bus_find_device(&usb_bus_type, NULL,
(void *) (unsigned long) devt, match_devt);
if (!dev)
return NULL;
return to_usb_device(dev);
}
/*
* file operations
*/
static int usbdev_open(struct inode *inode, struct file *file)
{
struct usb_device *dev = NULL;
struct usb_dev_state *ps;
int ret;
ret = -ENOMEM;
ps = kzalloc(sizeof(struct usb_dev_state), GFP_KERNEL);
if (!ps)
goto out_free_ps;
ret = -ENODEV;
/* Protect against simultaneous removal or release */
mutex_lock(&usbfs_mutex);
/* usbdev device-node */
if (imajor(inode) == USB_DEVICE_MAJOR)
dev = usbdev_lookup_by_devt(inode->i_rdev);
mutex_unlock(&usbfs_mutex);
if (!dev)
goto out_free_ps;
usb_lock_device(dev);
if (dev->state == USB_STATE_NOTATTACHED)
goto out_unlock_device;
ret = usb_autoresume_device(dev);
if (ret)
goto out_unlock_device;
ps->dev = dev;
ps->file = file;
ps->interface_allowed_mask = 0xFFFFFFFF; /* 32 bits */
spin_lock_init(&ps->lock);
INIT_LIST_HEAD(&ps->list);
INIT_LIST_HEAD(&ps->async_pending);
INIT_LIST_HEAD(&ps->async_completed);
INIT_LIST_HEAD(&ps->memory_list);
init_waitqueue_head(&ps->wait);
ps->disc_pid = get_pid(task_pid(current));
ps->cred = get_current_cred();
security_task_getsecid(current, &ps->secid);
smp_wmb();
list_add_tail(&ps->list, &dev->filelist);
file->private_data = ps;
usb_unlock_device(dev);
snoop(&dev->dev, "opened by process %d: %s\n", task_pid_nr(current),
current->comm);
return ret;
out_unlock_device:
usb_unlock_device(dev);
usb_put_dev(dev);
out_free_ps:
kfree(ps);
return ret;
}
static int usbdev_release(struct inode *inode, struct file *file)
{
struct usb_dev_state *ps = file->private_data;
struct usb_device *dev = ps->dev;
unsigned int ifnum;
struct async *as;
usb_lock_device(dev);
usb_hub_release_all_ports(dev, ps);
list_del_init(&ps->list);
for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed);
ifnum++) {
if (test_bit(ifnum, &ps->ifclaimed))
releaseintf(ps, ifnum);
}
destroy_all_async(ps);
usb_autosuspend_device(dev);
usb_unlock_device(dev);
usb_put_dev(dev);
put_pid(ps->disc_pid);
put_cred(ps->cred);
as = async_getcompleted(ps);
while (as) {
free_async(as);
as = async_getcompleted(ps);
}
kfree(ps);
return 0;
}
static int proc_control(struct usb_dev_state *ps, void __user *arg)
{
struct usb_device *dev = ps->dev;
struct usbdevfs_ctrltransfer ctrl;
unsigned int tmo;
unsigned char *tbuf;
unsigned wLength;
int i, pipe, ret;
if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
return -EFAULT;
ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.bRequest,
ctrl.wIndex);
if (ret)
return ret;
wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */
if (wLength > PAGE_SIZE)
return -EINVAL;
ret = usbfs_increase_memory_usage(PAGE_SIZE + sizeof(struct urb) +
sizeof(struct usb_ctrlrequest));
if (ret)
return ret;
tbuf = (unsigned char *)__get_free_page(GFP_KERNEL);
if (!tbuf) {
ret = -ENOMEM;
goto done;
}
tmo = ctrl.timeout;
snoop(&dev->dev, "control urb: bRequestType=%02x "
"bRequest=%02x wValue=%04x "
"wIndex=%04x wLength=%04x\n",
ctrl.bRequestType, ctrl.bRequest, ctrl.wValue,
ctrl.wIndex, ctrl.wLength);
if (ctrl.bRequestType & 0x80) {
if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data,
ctrl.wLength)) {
ret = -EINVAL;
goto done;
}
pipe = usb_rcvctrlpipe(dev, 0);
snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0);
usb_unlock_device(dev);
i = usb_control_msg(dev, pipe, ctrl.bRequest,
ctrl.bRequestType, ctrl.wValue, ctrl.wIndex,
tbuf, ctrl.wLength, tmo);
usb_lock_device(dev);
snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE,
tbuf, max(i, 0));
if ((i > 0) && ctrl.wLength) {
if (copy_to_user(ctrl.data, tbuf, i)) {
ret = -EFAULT;
goto done;
}
}
} else {
if (ctrl.wLength) {
if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) {
ret = -EFAULT;
goto done;
}
}
pipe = usb_sndctrlpipe(dev, 0);
snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT,
tbuf, ctrl.wLength);
usb_unlock_device(dev);
i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest,
ctrl.bRequestType, ctrl.wValue, ctrl.wIndex,
tbuf, ctrl.wLength, tmo);
usb_lock_device(dev);
snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0);
}
if (i < 0 && i != -EPIPE) {
dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL "
"failed cmd %s rqt %u rq %u len %u ret %d\n",
current->comm, ctrl.bRequestType, ctrl.bRequest,
ctrl.wLength, i);
}
ret = i;
done:
free_page((unsigned long) tbuf);
usbfs_decrease_memory_usage(PAGE_SIZE + sizeof(struct urb) +
sizeof(struct usb_ctrlrequest));
return ret;
}
static int proc_bulk(struct usb_dev_state *ps, void __user *arg)
{
struct usb_device *dev = ps->dev;
struct usbdevfs_bulktransfer bulk;
unsigned int tmo, len1, pipe;
int len2;
unsigned char *tbuf;
int i, ret;
if (copy_from_user(&bulk, arg, sizeof(bulk)))
return -EFAULT;
ret = findintfep(ps->dev, bulk.ep);
if (ret < 0)
return ret;
ret = checkintf(ps, ret);
if (ret)
return ret;
if (bulk.ep & USB_DIR_IN)
pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f);
else
pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f);
if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN)))
return -EINVAL;
len1 = bulk.len;
if (len1 >= USBFS_XFER_MAX)
return -EINVAL;
ret = usbfs_increase_memory_usage(len1 + sizeof(struct urb));
if (ret)
return ret;
tbuf = kmalloc(len1, GFP_KERNEL);
if (!tbuf) {
ret = -ENOMEM;
goto done;
}
tmo = bulk.timeout;
if (bulk.ep & 0x80) {
if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) {
ret = -EINVAL;
goto done;
}
snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, NULL, 0);
usb_unlock_device(dev);
i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
usb_lock_device(dev);
snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, tbuf, len2);
if (!i && len2) {
if (copy_to_user(bulk.data, tbuf, len2)) {
ret = -EFAULT;
goto done;
}
}
} else {
if (len1) {
if (copy_from_user(tbuf, bulk.data, len1)) {
ret = -EFAULT;
goto done;
}
}
snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, tbuf, len1);
usb_unlock_device(dev);
i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
usb_lock_device(dev);
snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, NULL, 0);
}
ret = (i < 0 ? i : len2);
done:
kfree(tbuf);
usbfs_decrease_memory_usage(len1 + sizeof(struct urb));
return ret;
}
static void check_reset_of_active_ep(struct usb_device *udev,
unsigned int epnum, char *ioctl_name)
{
struct usb_host_endpoint **eps;
struct usb_host_endpoint *ep;
eps = (epnum & USB_DIR_IN) ? udev->ep_in : udev->ep_out;
ep = eps[epnum & 0x0f];
if (ep && !list_empty(&ep->urb_list))
dev_warn(&udev->dev, "Process %d (%s) called USBDEVFS_%s for active endpoint 0x%02x\n",
task_pid_nr(current), current->comm,
ioctl_name, epnum);
}
static int proc_resetep(struct usb_dev_state *ps, void __user *arg)
{
unsigned int ep;
int ret;
if (get_user(ep, (unsigned int __user *)arg))
return -EFAULT;
ret = findintfep(ps->dev, ep);
if (ret < 0)
return ret;
ret = checkintf(ps, ret);
if (ret)
return ret;
check_reset_of_active_ep(ps->dev, ep, "RESETEP");
usb_reset_endpoint(ps->dev, ep);
return 0;
}
static int proc_clearhalt(struct usb_dev_state *ps, void __user *arg)
{
unsigned int ep;
int pipe;
int ret;
if (get_user(ep, (unsigned int __user *)arg))
return -EFAULT;
ret = findintfep(ps->dev, ep);
if (ret < 0)
return ret;
ret = checkintf(ps, ret);
if (ret)
return ret;
check_reset_of_active_ep(ps->dev, ep, "CLEAR_HALT");
if (ep & USB_DIR_IN)
pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f);
else
pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f);
return usb_clear_halt(ps->dev, pipe);
}
static int proc_getdriver(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_getdriver gd;
struct usb_interface *intf;
int ret;
if (copy_from_user(&gd, arg, sizeof(gd)))
return -EFAULT;
intf = usb_ifnum_to_if(ps->dev, gd.interface);
if (!intf || !intf->dev.driver)
ret = -ENODATA;
else {
strlcpy(gd.driver, intf->dev.driver->name,
sizeof(gd.driver));
ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0);
}
return ret;
}
static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_connectinfo ci;
memset(&ci, 0, sizeof(ci));
ci.devnum = ps->dev->devnum;
ci.slow = ps->dev->speed == USB_SPEED_LOW;
if (copy_to_user(arg, &ci, sizeof(ci)))
return -EFAULT;
return 0;
}
static int proc_resetdevice(struct usb_dev_state *ps)
{
struct usb_host_config *actconfig = ps->dev->actconfig;
struct usb_interface *interface;
int i, number;
/* Don't allow a device reset if the process has dropped the
* privilege to do such things and any of the interfaces are
* currently claimed.
*/
if (ps->privileges_dropped && actconfig) {
for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) {
interface = actconfig->interface[i];
number = interface->cur_altsetting->desc.bInterfaceNumber;
if (usb_interface_claimed(interface) &&
!test_bit(number, &ps->ifclaimed)) {
dev_warn(&ps->dev->dev,
"usbfs: interface %d claimed by %s while '%s' resets device\n",
number, interface->dev.driver->name, current->comm);
return -EACCES;
}
}
}
return usb_reset_device(ps->dev);
}
static int proc_setintf(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_setinterface setintf;
int ret;
if (copy_from_user(&setintf, arg, sizeof(setintf)))
return -EFAULT;
ret = checkintf(ps, setintf.interface);
if (ret)
return ret;
destroy_async_on_interface(ps, setintf.interface);
return usb_set_interface(ps->dev, setintf.interface,
setintf.altsetting);
}
static int proc_setconfig(struct usb_dev_state *ps, void __user *arg)
{
int u;
int status = 0;
struct usb_host_config *actconfig;
if (get_user(u, (int __user *)arg))
return -EFAULT;
actconfig = ps->dev->actconfig;
/* Don't touch the device if any interfaces are claimed.
* It could interfere with other drivers' operations, and if
* an interface is claimed by usbfs it could easily deadlock.
*/
if (actconfig) {
int i;
for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) {
if (usb_interface_claimed(actconfig->interface[i])) {
dev_warn(&ps->dev->dev,
"usbfs: interface %d claimed by %s "
"while '%s' sets config #%d\n",
actconfig->interface[i]
->cur_altsetting
->desc.bInterfaceNumber,
actconfig->interface[i]
->dev.driver->name,
current->comm, u);
status = -EBUSY;
break;
}
}
}
/* SET_CONFIGURATION is often abused as a "cheap" driver reset,
* so avoid usb_set_configuration()'s kick to sysfs
*/
if (status == 0) {
if (actconfig && actconfig->desc.bConfigurationValue == u)
status = usb_reset_configuration(ps->dev);
else
status = usb_set_configuration(ps->dev, u);
}
return status;
}
static struct usb_memory *
find_memory_area(struct usb_dev_state *ps, const struct usbdevfs_urb *uurb)
{
struct usb_memory *usbm = NULL, *iter;
unsigned long flags;
unsigned long uurb_start = (unsigned long)uurb->buffer;
spin_lock_irqsave(&ps->lock, flags);
list_for_each_entry(iter, &ps->memory_list, memlist) {
if (uurb_start >= iter->vm_start &&
uurb_start < iter->vm_start + iter->size) {
if (uurb->buffer_length > iter->vm_start + iter->size -
uurb_start) {
usbm = ERR_PTR(-EINVAL);
} else {
usbm = iter;
usbm->urb_use_count++;
}
break;
}
}
spin_unlock_irqrestore(&ps->lock, flags);
return usbm;
}
static int proc_do_submiturb(struct usb_dev_state *ps, struct usbdevfs_urb *uurb,
struct usbdevfs_iso_packet_desc __user *iso_frame_desc,
void __user *arg)
{
struct usbdevfs_iso_packet_desc *isopkt = NULL;
struct usb_host_endpoint *ep;
struct async *as = NULL;
struct usb_ctrlrequest *dr = NULL;
unsigned int u, totlen, isofrmlen;
int i, ret, is_in, num_sgs = 0, ifnum = -1;
int number_of_packets = 0;
unsigned int stream_id = 0;
void *buf;
if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP |
USBDEVFS_URB_SHORT_NOT_OK |
USBDEVFS_URB_BULK_CONTINUATION |
USBDEVFS_URB_NO_FSBR |
USBDEVFS_URB_ZERO_PACKET |
USBDEVFS_URB_NO_INTERRUPT))
return -EINVAL;
if (uurb->buffer_length > 0 && !uurb->buffer)
return -EINVAL;
if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL &&
(uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) {
ifnum = findintfep(ps->dev, uurb->endpoint);
if (ifnum < 0)
return ifnum;
ret = checkintf(ps, ifnum);
if (ret)
return ret;
}
ep = ep_to_host_endpoint(ps->dev, uurb->endpoint);
if (!ep)
return -ENOENT;
is_in = (uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0;
u = 0;
switch (uurb->type) {
case USBDEVFS_URB_TYPE_CONTROL:
if (!usb_endpoint_xfer_control(&ep->desc))
return -EINVAL;
/* min 8 byte setup packet */
if (uurb->buffer_length < 8)
return -EINVAL;
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
if (!dr)
return -ENOMEM;
if (copy_from_user(dr, uurb->buffer, 8)) {
ret = -EFAULT;
goto error;
}
if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) {
ret = -EINVAL;
goto error;
}
ret = check_ctrlrecip(ps, dr->bRequestType, dr->bRequest,
le16_to_cpup(&dr->wIndex));
if (ret)
goto error;
uurb->buffer_length = le16_to_cpup(&dr->wLength);
uurb->buffer += 8;
if ((dr->bRequestType & USB_DIR_IN) && uurb->buffer_length) {
is_in = 1;
uurb->endpoint |= USB_DIR_IN;
} else {
is_in = 0;
uurb->endpoint &= ~USB_DIR_IN;
}
snoop(&ps->dev->dev, "control urb: bRequestType=%02x "
"bRequest=%02x wValue=%04x "
"wIndex=%04x wLength=%04x\n",
dr->bRequestType, dr->bRequest,
__le16_to_cpup(&dr->wValue),
__le16_to_cpup(&dr->wIndex),
__le16_to_cpup(&dr->wLength));
u = sizeof(struct usb_ctrlrequest);
break;
case USBDEVFS_URB_TYPE_BULK:
switch (usb_endpoint_type(&ep->desc)) {
case USB_ENDPOINT_XFER_CONTROL:
case USB_ENDPOINT_XFER_ISOC:
return -EINVAL;
case USB_ENDPOINT_XFER_INT:
/* allow single-shot interrupt transfers */
uurb->type = USBDEVFS_URB_TYPE_INTERRUPT;
goto interrupt_urb;
}
num_sgs = DIV_ROUND_UP(uurb->buffer_length, USB_SG_SIZE);
if (num_sgs == 1 || num_sgs > ps->dev->bus->sg_tablesize)
num_sgs = 0;
if (ep->streams)
stream_id = uurb->stream_id;
break;
case USBDEVFS_URB_TYPE_INTERRUPT:
if (!usb_endpoint_xfer_int(&ep->desc))
return -EINVAL;
interrupt_urb:
break;
case USBDEVFS_URB_TYPE_ISO:
/* arbitrary limit */
if (uurb->number_of_packets < 1 ||
uurb->number_of_packets > 128)
return -EINVAL;
if (!usb_endpoint_xfer_isoc(&ep->desc))
return -EINVAL;
number_of_packets = uurb->number_of_packets;
isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) *
number_of_packets;
isopkt = memdup_user(iso_frame_desc, isofrmlen);
if (IS_ERR(isopkt)) {
ret = PTR_ERR(isopkt);
isopkt = NULL;
goto error;
}
for (totlen = u = 0; u < number_of_packets; u++) {
/*
* arbitrary limit need for USB 3.0
* bMaxBurst (0~15 allowed, 1~16 packets)
* bmAttributes (bit 1:0, mult 0~2, 1~3 packets)
* sizemax: 1024 * 16 * 3 = 49152
*/
if (isopkt[u].length > 49152) {
ret = -EINVAL;
goto error;
}
totlen += isopkt[u].length;
}
u *= sizeof(struct usb_iso_packet_descriptor);
uurb->buffer_length = totlen;
break;
default:
return -EINVAL;
}
if (uurb->buffer_length >= USBFS_XFER_MAX) {
ret = -EINVAL;
goto error;
}
if (uurb->buffer_length > 0 &&
!access_ok(is_in ? VERIFY_WRITE : VERIFY_READ,
uurb->buffer, uurb->buffer_length)) {
ret = -EFAULT;
goto error;
}
as = alloc_async(number_of_packets);
if (!as) {
ret = -ENOMEM;
goto error;
}
as->usbm = find_memory_area(ps, uurb);
if (IS_ERR(as->usbm)) {
ret = PTR_ERR(as->usbm);
as->usbm = NULL;
goto error;
}
/* do not use SG buffers when memory mapped segments
* are in use
*/
if (as->usbm)
num_sgs = 0;
u += sizeof(struct async) + sizeof(struct urb) + uurb->buffer_length +
num_sgs * sizeof(struct scatterlist);
ret = usbfs_increase_memory_usage(u);
if (ret)
goto error;
as->mem_usage = u;
if (num_sgs) {
as->urb->sg = kmalloc(num_sgs * sizeof(struct scatterlist),
GFP_KERNEL);
if (!as->urb->sg) {
ret = -ENOMEM;
goto error;
}
as->urb->num_sgs = num_sgs;
sg_init_table(as->urb->sg, as->urb->num_sgs);
totlen = uurb->buffer_length;
for (i = 0; i < as->urb->num_sgs; i++) {
u = (totlen > USB_SG_SIZE) ? USB_SG_SIZE : totlen;
buf = kmalloc(u, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto error;
}
sg_set_buf(&as->urb->sg[i], buf, u);
if (!is_in) {
if (copy_from_user(buf, uurb->buffer, u)) {
ret = -EFAULT;
goto error;
}
uurb->buffer += u;
}
totlen -= u;
}
} else if (uurb->buffer_length > 0) {
if (as->usbm) {
unsigned long uurb_start = (unsigned long)uurb->buffer;
as->urb->transfer_buffer = as->usbm->mem +
(uurb_start - as->usbm->vm_start);
} else {
as->urb->transfer_buffer = kmalloc(uurb->buffer_length,
GFP_KERNEL);
if (!as->urb->transfer_buffer) {
ret = -ENOMEM;
goto error;
}
if (!is_in) {
if (copy_from_user(as->urb->transfer_buffer,
uurb->buffer,
uurb->buffer_length)) {
ret = -EFAULT;
goto error;
}
} else if (uurb->type == USBDEVFS_URB_TYPE_ISO) {
/*
* Isochronous input data may end up being
* discontiguous if some of the packets are
* short. Clear the buffer so that the gaps
* don't leak kernel data to userspace.
*/
memset(as->urb->transfer_buffer, 0,
uurb->buffer_length);
}
}
}
as->urb->dev = ps->dev;
as->urb->pipe = (uurb->type << 30) |
__create_pipe(ps->dev, uurb->endpoint & 0xf) |
(uurb->endpoint & USB_DIR_IN);
/* This tedious sequence is necessary because the URB_* flags
* are internal to the kernel and subject to change, whereas
* the USBDEVFS_URB_* flags are a user API and must not be changed.
*/
u = (is_in ? URB_DIR_IN : URB_DIR_OUT);
if (uurb->flags & USBDEVFS_URB_ISO_ASAP)
u |= URB_ISO_ASAP;
if (uurb->flags & USBDEVFS_URB_SHORT_NOT_OK && is_in)
u |= URB_SHORT_NOT_OK;
if (uurb->flags & USBDEVFS_URB_NO_FSBR)
u |= URB_NO_FSBR;
if (uurb->flags & USBDEVFS_URB_ZERO_PACKET)
u |= URB_ZERO_PACKET;
if (uurb->flags & USBDEVFS_URB_NO_INTERRUPT)
u |= URB_NO_INTERRUPT;
as->urb->transfer_flags = u;
as->urb->transfer_buffer_length = uurb->buffer_length;
as->urb->setup_packet = (unsigned char *)dr;
dr = NULL;
as->urb->start_frame = uurb->start_frame;
as->urb->number_of_packets = number_of_packets;
as->urb->stream_id = stream_id;
if (uurb->type == USBDEVFS_URB_TYPE_ISO ||
ps->dev->speed == USB_SPEED_HIGH)
as->urb->interval = 1 << min(15, ep->desc.bInterval - 1);
else
as->urb->interval = ep->desc.bInterval;
as->urb->context = as;
as->urb->complete = async_completed;
for (totlen = u = 0; u < number_of_packets; u++) {
as->urb->iso_frame_desc[u].offset = totlen;
as->urb->iso_frame_desc[u].length = isopkt[u].length;
totlen += isopkt[u].length;
}
kfree(isopkt);
isopkt = NULL;
as->ps = ps;
as->userurb = arg;
if (as->usbm) {
unsigned long uurb_start = (unsigned long)uurb->buffer;
as->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
as->urb->transfer_dma = as->usbm->dma_handle +
(uurb_start - as->usbm->vm_start);
} else if (is_in && uurb->buffer_length > 0)
as->userbuffer = uurb->buffer;
as->signr = uurb->signr;
as->ifnum = ifnum;
as->pid = get_pid(task_pid(current));
as->cred = get_current_cred();
security_task_getsecid(current, &as->secid);
snoop_urb(ps->dev, as->userurb, as->urb->pipe,
as->urb->transfer_buffer_length, 0, SUBMIT,
NULL, 0);
if (!is_in)
snoop_urb_data(as->urb, as->urb->transfer_buffer_length);
async_newpending(as);
if (usb_endpoint_xfer_bulk(&ep->desc)) {
spin_lock_irq(&ps->lock);
/* Not exactly the endpoint address; the direction bit is
* shifted to the 0x10 position so that the value will be
* between 0 and 31.
*/
as->bulk_addr = usb_endpoint_num(&ep->desc) |
((ep->desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK)
>> 3);
/* If this bulk URB is the start of a new transfer, re-enable
* the endpoint. Otherwise mark it as a continuation URB.
*/
if (uurb->flags & USBDEVFS_URB_BULK_CONTINUATION)
as->bulk_status = AS_CONTINUATION;
else
ps->disabled_bulk_eps &= ~(1 << as->bulk_addr);
/* Don't accept continuation URBs if the endpoint is
* disabled because of an earlier error.
*/
if (ps->disabled_bulk_eps & (1 << as->bulk_addr))
ret = -EREMOTEIO;
else
ret = usb_submit_urb(as->urb, GFP_ATOMIC);
spin_unlock_irq(&ps->lock);
} else {
ret = usb_submit_urb(as->urb, GFP_KERNEL);
}
if (ret) {
dev_printk(KERN_DEBUG, &ps->dev->dev,
"usbfs: usb_submit_urb returned %d\n", ret);
snoop_urb(ps->dev, as->userurb, as->urb->pipe,
0, ret, COMPLETE, NULL, 0);
async_removepending(as);
goto error;
}
return 0;
error:
if (as && as->usbm)
dec_usb_memory_use_count(as->usbm, &as->usbm->urb_use_count);
kfree(isopkt);
kfree(dr);
if (as)
free_async(as);
return ret;
}
static int proc_submiturb(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_urb uurb;
if (copy_from_user(&uurb, arg, sizeof(uurb)))
return -EFAULT;
return proc_do_submiturb(ps, &uurb,
(((struct usbdevfs_urb __user *)arg)->iso_frame_desc),
arg);
}
static int proc_unlinkurb(struct usb_dev_state *ps, void __user *arg)
{
struct urb *urb;
struct async *as;
unsigned long flags;
spin_lock_irqsave(&ps->lock, flags);
as = async_getpending(ps, arg);
if (!as) {
spin_unlock_irqrestore(&ps->lock, flags);
return -EINVAL;
}
urb = as->urb;
usb_get_urb(urb);
spin_unlock_irqrestore(&ps->lock, flags);
usb_kill_urb(urb);
usb_put_urb(urb);
return 0;
}
static int processcompl(struct async *as, void __user * __user *arg)
{
struct urb *urb = as->urb;
struct usbdevfs_urb __user *userurb = as->userurb;
void __user *addr = as->userurb;
unsigned int i;
if (as->userbuffer && urb->actual_length) {
if (copy_urb_data_to_user(as->userbuffer, urb))
goto err_out;
}
if (put_user(as->status, &userurb->status))
goto err_out;
if (put_user(urb->actual_length, &userurb->actual_length))
goto err_out;
if (put_user(urb->error_count, &userurb->error_count))
goto err_out;
if (usb_endpoint_xfer_isoc(&urb->ep->desc)) {
for (i = 0; i < urb->number_of_packets; i++) {
if (put_user(urb->iso_frame_desc[i].actual_length,
&userurb->iso_frame_desc[i].actual_length))
goto err_out;
if (put_user(urb->iso_frame_desc[i].status,
&userurb->iso_frame_desc[i].status))
goto err_out;
}
}
if (put_user(addr, (void __user * __user *)arg))
return -EFAULT;
return 0;
err_out:
return -EFAULT;
}
static struct async *reap_as(struct usb_dev_state *ps)
{
DECLARE_WAITQUEUE(wait, current);
struct async *as = NULL;
struct usb_device *dev = ps->dev;
add_wait_queue(&ps->wait, &wait);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
as = async_getcompleted(ps);
if (as || !connected(ps))
break;
if (signal_pending(current))
break;
usb_unlock_device(dev);
schedule();
usb_lock_device(dev);
}
remove_wait_queue(&ps->wait, &wait);
set_current_state(TASK_RUNNING);
return as;
}
static int proc_reapurb(struct usb_dev_state *ps, void __user *arg)
{
struct async *as = reap_as(ps);
if (as) {
int retval;
snoop(&ps->dev->dev, "reap %p\n", as->userurb);
retval = processcompl(as, (void __user * __user *)arg);
free_async(as);
return retval;
}
if (signal_pending(current))
return -EINTR;
return -ENODEV;
}
static int proc_reapurbnonblock(struct usb_dev_state *ps, void __user *arg)
{
int retval;
struct async *as;
as = async_getcompleted(ps);
if (as) {
snoop(&ps->dev->dev, "reap %p\n", as->userurb);
retval = processcompl(as, (void __user * __user *)arg);
free_async(as);
} else {
retval = (connected(ps) ? -EAGAIN : -ENODEV);
}
return retval;
}
#ifdef CONFIG_COMPAT
static int proc_control_compat(struct usb_dev_state *ps,
struct usbdevfs_ctrltransfer32 __user *p32)
{
struct usbdevfs_ctrltransfer __user *p;
__u32 udata;
p = compat_alloc_user_space(sizeof(*p));
if (copy_in_user(p, p32, (sizeof(*p32) - sizeof(compat_caddr_t))) ||
get_user(udata, &p32->data) ||
put_user(compat_ptr(udata), &p->data))
return -EFAULT;
return proc_control(ps, p);
}
static int proc_bulk_compat(struct usb_dev_state *ps,
struct usbdevfs_bulktransfer32 __user *p32)
{
struct usbdevfs_bulktransfer __user *p;
compat_uint_t n;
compat_caddr_t addr;
p = compat_alloc_user_space(sizeof(*p));
if (get_user(n, &p32->ep) || put_user(n, &p->ep) ||
get_user(n, &p32->len) || put_user(n, &p->len) ||
get_user(n, &p32->timeout) || put_user(n, &p->timeout) ||
get_user(addr, &p32->data) || put_user(compat_ptr(addr), &p->data))
return -EFAULT;
return proc_bulk(ps, p);
}
static int proc_disconnectsignal_compat(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_disconnectsignal32 ds;
if (copy_from_user(&ds, arg, sizeof(ds)))
return -EFAULT;
ps->discsignr = ds.signr;
ps->disccontext = compat_ptr(ds.context);
return 0;
}
static int get_urb32(struct usbdevfs_urb *kurb,
struct usbdevfs_urb32 __user *uurb)
{
__u32 uptr;
if (!access_ok(VERIFY_READ, uurb, sizeof(*uurb)) ||
__get_user(kurb->type, &uurb->type) ||
__get_user(kurb->endpoint, &uurb->endpoint) ||
__get_user(kurb->status, &uurb->status) ||
__get_user(kurb->flags, &uurb->flags) ||
__get_user(kurb->buffer_length, &uurb->buffer_length) ||
__get_user(kurb->actual_length, &uurb->actual_length) ||
__get_user(kurb->start_frame, &uurb->start_frame) ||
__get_user(kurb->number_of_packets, &uurb->number_of_packets) ||
__get_user(kurb->error_count, &uurb->error_count) ||
__get_user(kurb->signr, &uurb->signr))
return -EFAULT;
if (__get_user(uptr, &uurb->buffer))
return -EFAULT;
kurb->buffer = compat_ptr(uptr);
if (__get_user(uptr, &uurb->usercontext))
return -EFAULT;
kurb->usercontext = compat_ptr(uptr);
return 0;
}
static int proc_submiturb_compat(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_urb uurb;
if (get_urb32(&uurb, (struct usbdevfs_urb32 __user *)arg))
return -EFAULT;
return proc_do_submiturb(ps, &uurb,
((struct usbdevfs_urb32 __user *)arg)->iso_frame_desc,
arg);
}
static int processcompl_compat(struct async *as, void __user * __user *arg)
{
struct urb *urb = as->urb;
struct usbdevfs_urb32 __user *userurb = as->userurb;
void __user *addr = as->userurb;
unsigned int i;
if (as->userbuffer && urb->actual_length) {
if (copy_urb_data_to_user(as->userbuffer, urb))
return -EFAULT;
}
if (put_user(as->status, &userurb->status))
return -EFAULT;
if (put_user(urb->actual_length, &userurb->actual_length))
return -EFAULT;
if (put_user(urb->error_count, &userurb->error_count))
return -EFAULT;
if (usb_endpoint_xfer_isoc(&urb->ep->desc)) {
for (i = 0; i < urb->number_of_packets; i++) {
if (put_user(urb->iso_frame_desc[i].actual_length,
&userurb->iso_frame_desc[i].actual_length))
return -EFAULT;
if (put_user(urb->iso_frame_desc[i].status,
&userurb->iso_frame_desc[i].status))
return -EFAULT;
}
}
if (put_user(ptr_to_compat(addr), (u32 __user *)arg))
return -EFAULT;
return 0;
}
static int proc_reapurb_compat(struct usb_dev_state *ps, void __user *arg)
{
struct async *as = reap_as(ps);
if (as) {
int retval;
snoop(&ps->dev->dev, "reap %p\n", as->userurb);
retval = processcompl_compat(as, (void __user * __user *)arg);
free_async(as);
return retval;
}
if (signal_pending(current))
return -EINTR;
return -ENODEV;
}
static int proc_reapurbnonblock_compat(struct usb_dev_state *ps, void __user *arg)
{
int retval;
struct async *as;
as = async_getcompleted(ps);
if (as) {
snoop(&ps->dev->dev, "reap %p\n", as->userurb);
retval = processcompl_compat(as, (void __user * __user *)arg);
free_async(as);
} else {
retval = (connected(ps) ? -EAGAIN : -ENODEV);
}
return retval;
}
#endif
static int proc_disconnectsignal(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_disconnectsignal ds;
if (copy_from_user(&ds, arg, sizeof(ds)))
return -EFAULT;
ps->discsignr = ds.signr;
ps->disccontext = ds.context;
return 0;
}
static int proc_claiminterface(struct usb_dev_state *ps, void __user *arg)
{
unsigned int ifnum;
if (get_user(ifnum, (unsigned int __user *)arg))
return -EFAULT;
return claimintf(ps, ifnum);
}
static int proc_releaseinterface(struct usb_dev_state *ps, void __user *arg)
{
unsigned int ifnum;
int ret;
if (get_user(ifnum, (unsigned int __user *)arg))
return -EFAULT;
ret = releaseintf(ps, ifnum);
if (ret < 0)
return ret;
destroy_async_on_interface(ps, ifnum);
return 0;
}
static int proc_ioctl(struct usb_dev_state *ps, struct usbdevfs_ioctl *ctl)
{
int size;
void *buf = NULL;
int retval = 0;
struct usb_interface *intf = NULL;
struct usb_driver *driver = NULL;
if (ps->privileges_dropped)
return -EACCES;
/* alloc buffer */
size = _IOC_SIZE(ctl->ioctl_code);
if (size > 0) {
buf = kmalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
if ((_IOC_DIR(ctl->ioctl_code) & _IOC_WRITE)) {
if (copy_from_user(buf, ctl->data, size)) {
kfree(buf);
return -EFAULT;
}
} else {
memset(buf, 0, size);
}
}
if (!connected(ps)) {
kfree(buf);
return -ENODEV;
}
if (ps->dev->state != USB_STATE_CONFIGURED)
retval = -EHOSTUNREACH;
else if (!(intf = usb_ifnum_to_if(ps->dev, ctl->ifno)))
retval = -EINVAL;
else switch (ctl->ioctl_code) {
/* disconnect kernel driver from interface */
case USBDEVFS_DISCONNECT:
if (intf->dev.driver) {
driver = to_usb_driver(intf->dev.driver);
dev_dbg(&intf->dev, "disconnect by usbfs\n");
usb_driver_release_interface(driver, intf);
} else
retval = -ENODATA;
break;
/* let kernel drivers try to (re)bind to the interface */
case USBDEVFS_CONNECT:
if (!intf->dev.driver)
retval = device_attach(&intf->dev);
else
retval = -EBUSY;
break;
/* talk directly to the interface's driver */
default:
if (intf->dev.driver)
driver = to_usb_driver(intf->dev.driver);
if (driver == NULL || driver->unlocked_ioctl == NULL) {
retval = -ENOTTY;
} else {
retval = driver->unlocked_ioctl(intf, ctl->ioctl_code, buf);
if (retval == -ENOIOCTLCMD)
retval = -ENOTTY;
}
}
/* cleanup and return */
if (retval >= 0
&& (_IOC_DIR(ctl->ioctl_code) & _IOC_READ) != 0
&& size > 0
&& copy_to_user(ctl->data, buf, size) != 0)
retval = -EFAULT;
kfree(buf);
return retval;
}
static int proc_ioctl_default(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_ioctl ctrl;
if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
return -EFAULT;
return proc_ioctl(ps, &ctrl);
}
#ifdef CONFIG_COMPAT
static int proc_ioctl_compat(struct usb_dev_state *ps, compat_uptr_t arg)
{
struct usbdevfs_ioctl32 __user *uioc;
struct usbdevfs_ioctl ctrl;
u32 udata;
uioc = compat_ptr((long)arg);
if (!access_ok(VERIFY_READ, uioc, sizeof(*uioc)) ||
__get_user(ctrl.ifno, &uioc->ifno) ||
__get_user(ctrl.ioctl_code, &uioc->ioctl_code) ||
__get_user(udata, &uioc->data))
return -EFAULT;
ctrl.data = compat_ptr(udata);
return proc_ioctl(ps, &ctrl);
}
#endif
static int proc_claim_port(struct usb_dev_state *ps, void __user *arg)
{
unsigned portnum;
int rc;
if (get_user(portnum, (unsigned __user *) arg))
return -EFAULT;
rc = usb_hub_claim_port(ps->dev, portnum, ps);
if (rc == 0)
snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n",
portnum, task_pid_nr(current), current->comm);
return rc;
}
static int proc_release_port(struct usb_dev_state *ps, void __user *arg)
{
unsigned portnum;
if (get_user(portnum, (unsigned __user *) arg))
return -EFAULT;
return usb_hub_release_port(ps->dev, portnum, ps);
}
static int proc_get_capabilities(struct usb_dev_state *ps, void __user *arg)
{
__u32 caps;
caps = USBDEVFS_CAP_ZERO_PACKET | USBDEVFS_CAP_NO_PACKET_SIZE_LIM |
USBDEVFS_CAP_REAP_AFTER_DISCONNECT | USBDEVFS_CAP_MMAP |
USBDEVFS_CAP_DROP_PRIVILEGES;
if (!ps->dev->bus->no_stop_on_short)
caps |= USBDEVFS_CAP_BULK_CONTINUATION;
if (ps->dev->bus->sg_tablesize)
caps |= USBDEVFS_CAP_BULK_SCATTER_GATHER;
if (put_user(caps, (__u32 __user *)arg))
return -EFAULT;
return 0;
}
static int proc_disconnect_claim(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_disconnect_claim dc;
struct usb_interface *intf;
if (copy_from_user(&dc, arg, sizeof(dc)))
return -EFAULT;
intf = usb_ifnum_to_if(ps->dev, dc.interface);
if (!intf)
return -EINVAL;
if (intf->dev.driver) {
struct usb_driver *driver = to_usb_driver(intf->dev.driver);
if (ps->privileges_dropped)
return -EACCES;
if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_IF_DRIVER) &&
strncmp(dc.driver, intf->dev.driver->name,
sizeof(dc.driver)) != 0)
return -EBUSY;
if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_EXCEPT_DRIVER) &&
strncmp(dc.driver, intf->dev.driver->name,
sizeof(dc.driver)) == 0)
return -EBUSY;
dev_dbg(&intf->dev, "disconnect by usbfs\n");
usb_driver_release_interface(driver, intf);
}
return claimintf(ps, dc.interface);
}
static int proc_alloc_streams(struct usb_dev_state *ps, void __user *arg)
{
unsigned num_streams, num_eps;
struct usb_host_endpoint **eps;
struct usb_interface *intf;
int r;
r = parse_usbdevfs_streams(ps, arg, &num_streams, &num_eps,
&eps, &intf);
if (r)
return r;
destroy_async_on_interface(ps,
intf->altsetting[0].desc.bInterfaceNumber);
r = usb_alloc_streams(intf, eps, num_eps, num_streams, GFP_KERNEL);
kfree(eps);
return r;
}
static int proc_free_streams(struct usb_dev_state *ps, void __user *arg)
{
unsigned num_eps;
struct usb_host_endpoint **eps;
struct usb_interface *intf;
int r;
r = parse_usbdevfs_streams(ps, arg, NULL, &num_eps, &eps, &intf);
if (r)
return r;
destroy_async_on_interface(ps,
intf->altsetting[0].desc.bInterfaceNumber);
r = usb_free_streams(intf, eps, num_eps, GFP_KERNEL);
kfree(eps);
return r;
}
static int proc_drop_privileges(struct usb_dev_state *ps, void __user *arg)
{
u32 data;
if (copy_from_user(&data, arg, sizeof(data)))
return -EFAULT;
/* This is an one way operation. Once privileges are
* dropped, you cannot regain them. You may however reissue
* this ioctl to shrink the allowed interfaces mask.
*/
ps->interface_allowed_mask &= data;
ps->privileges_dropped = true;
return 0;
}
/*
* NOTE: All requests here that have interface numbers as parameters
* are assuming that somehow the configuration has been prevented from
* changing. But there's no mechanism to ensure that...
*/
static long usbdev_do_ioctl(struct file *file, unsigned int cmd,
void __user *p)
{
struct usb_dev_state *ps = file->private_data;
struct inode *inode = file_inode(file);
struct usb_device *dev = ps->dev;
int ret = -ENOTTY;
if (!(file->f_mode & FMODE_WRITE))
return -EPERM;
usb_lock_device(dev);
/* Reap operations are allowed even after disconnection */
switch (cmd) {
case USBDEVFS_REAPURB:
snoop(&dev->dev, "%s: REAPURB\n", __func__);
ret = proc_reapurb(ps, p);
goto done;
case USBDEVFS_REAPURBNDELAY:
snoop(&dev->dev, "%s: REAPURBNDELAY\n", __func__);
ret = proc_reapurbnonblock(ps, p);
goto done;
#ifdef CONFIG_COMPAT
case USBDEVFS_REAPURB32:
snoop(&dev->dev, "%s: REAPURB32\n", __func__);
ret = proc_reapurb_compat(ps, p);
goto done;
case USBDEVFS_REAPURBNDELAY32:
snoop(&dev->dev, "%s: REAPURBNDELAY32\n", __func__);
ret = proc_reapurbnonblock_compat(ps, p);
goto done;
#endif
}
if (!connected(ps)) {
usb_unlock_device(dev);
return -ENODEV;
}
switch (cmd) {
case USBDEVFS_CONTROL:
snoop(&dev->dev, "%s: CONTROL\n", __func__);
ret = proc_control(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_BULK:
snoop(&dev->dev, "%s: BULK\n", __func__);
ret = proc_bulk(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_RESETEP:
snoop(&dev->dev, "%s: RESETEP\n", __func__);
ret = proc_resetep(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_RESET:
snoop(&dev->dev, "%s: RESET\n", __func__);
ret = proc_resetdevice(ps);
break;
case USBDEVFS_CLEAR_HALT:
snoop(&dev->dev, "%s: CLEAR_HALT\n", __func__);
ret = proc_clearhalt(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_GETDRIVER:
snoop(&dev->dev, "%s: GETDRIVER\n", __func__);
ret = proc_getdriver(ps, p);
break;
case USBDEVFS_CONNECTINFO:
snoop(&dev->dev, "%s: CONNECTINFO\n", __func__);
ret = proc_connectinfo(ps, p);
break;
case USBDEVFS_SETINTERFACE:
snoop(&dev->dev, "%s: SETINTERFACE\n", __func__);
ret = proc_setintf(ps, p);
break;
case USBDEVFS_SETCONFIGURATION:
snoop(&dev->dev, "%s: SETCONFIGURATION\n", __func__);
ret = proc_setconfig(ps, p);
break;
case USBDEVFS_SUBMITURB:
snoop(&dev->dev, "%s: SUBMITURB\n", __func__);
ret = proc_submiturb(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
#ifdef CONFIG_COMPAT
case USBDEVFS_CONTROL32:
snoop(&dev->dev, "%s: CONTROL32\n", __func__);
ret = proc_control_compat(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_BULK32:
snoop(&dev->dev, "%s: BULK32\n", __func__);
ret = proc_bulk_compat(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_DISCSIGNAL32:
snoop(&dev->dev, "%s: DISCSIGNAL32\n", __func__);
ret = proc_disconnectsignal_compat(ps, p);
break;
case USBDEVFS_SUBMITURB32:
snoop(&dev->dev, "%s: SUBMITURB32\n", __func__);
ret = proc_submiturb_compat(ps, p);
if (ret >= 0)
inode->i_mtime = CURRENT_TIME;
break;
case USBDEVFS_IOCTL32:
snoop(&dev->dev, "%s: IOCTL32\n", __func__);
ret = proc_ioctl_compat(ps, ptr_to_compat(p));
break;
#endif
case USBDEVFS_DISCARDURB:
snoop(&dev->dev, "%s: DISCARDURB %p\n", __func__, p);
ret = proc_unlinkurb(ps, p);
break;
case USBDEVFS_DISCSIGNAL:
snoop(&dev->dev, "%s: DISCSIGNAL\n", __func__);
ret = proc_disconnectsignal(ps, p);
break;
case USBDEVFS_CLAIMINTERFACE:
snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __func__);
ret = proc_claiminterface(ps, p);
break;
case USBDEVFS_RELEASEINTERFACE:
snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __func__);
ret = proc_releaseinterface(ps, p);
break;
case USBDEVFS_IOCTL:
snoop(&dev->dev, "%s: IOCTL\n", __func__);
ret = proc_ioctl_default(ps, p);
break;
case USBDEVFS_CLAIM_PORT:
snoop(&dev->dev, "%s: CLAIM_PORT\n", __func__);
ret = proc_claim_port(ps, p);
break;
case USBDEVFS_RELEASE_PORT:
snoop(&dev->dev, "%s: RELEASE_PORT\n", __func__);
ret = proc_release_port(ps, p);
break;
case USBDEVFS_GET_CAPABILITIES:
ret = proc_get_capabilities(ps, p);
break;
case USBDEVFS_DISCONNECT_CLAIM:
ret = proc_disconnect_claim(ps, p);
break;
case USBDEVFS_ALLOC_STREAMS:
ret = proc_alloc_streams(ps, p);
break;
case USBDEVFS_FREE_STREAMS:
ret = proc_free_streams(ps, p);
break;
case USBDEVFS_DROP_PRIVILEGES:
ret = proc_drop_privileges(ps, p);
break;
}
done:
usb_unlock_device(dev);
if (ret >= 0)
inode->i_atime = CURRENT_TIME;
return ret;
}
static long usbdev_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret;
ret = usbdev_do_ioctl(file, cmd, (void __user *)arg);
return ret;
}
#ifdef CONFIG_COMPAT
static long usbdev_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret;
ret = usbdev_do_ioctl(file, cmd, compat_ptr(arg));
return ret;
}
#endif
/* No kernel lock - fine */
static unsigned int usbdev_poll(struct file *file,
struct poll_table_struct *wait)
{
struct usb_dev_state *ps = file->private_data;
unsigned int mask = 0;
poll_wait(file, &ps->wait, wait);
if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed))
mask |= POLLOUT | POLLWRNORM;
if (!connected(ps))
mask |= POLLERR | POLLHUP;
return mask;
}
const struct file_operations usbdev_file_operations = {
.owner = THIS_MODULE,
.llseek = no_seek_end_llseek,
.read = usbdev_read,
.poll = usbdev_poll,
.unlocked_ioctl = usbdev_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = usbdev_compat_ioctl,
#endif
.mmap = usbdev_mmap,
.open = usbdev_open,
.release = usbdev_release,
};
static void usbdev_remove(struct usb_device *udev)
{
struct usb_dev_state *ps;
struct siginfo sinfo;
while (!list_empty(&udev->filelist)) {
ps = list_entry(udev->filelist.next, struct usb_dev_state, list);
destroy_all_async(ps);
wake_up_all(&ps->wait);
list_del_init(&ps->list);
if (ps->discsignr) {
memset(&sinfo, 0, sizeof(sinfo));
sinfo.si_signo = ps->discsignr;
sinfo.si_errno = EPIPE;
sinfo.si_code = SI_ASYNCIO;
sinfo.si_addr = ps->disccontext;
kill_pid_info_as_cred(ps->discsignr, &sinfo,
ps->disc_pid, ps->cred, ps->secid);
}
}
}
static int usbdev_notify(struct notifier_block *self,
unsigned long action, void *dev)
{
switch (action) {
case USB_DEVICE_ADD:
break;
case USB_DEVICE_REMOVE:
usbdev_remove(dev);
break;
}
return NOTIFY_OK;
}
static struct notifier_block usbdev_nb = {
.notifier_call = usbdev_notify,
};
static struct cdev usb_device_cdev;
int __init usb_devio_init(void)
{
int retval;
retval = register_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX,
"usb_device");
if (retval) {
printk(KERN_ERR "Unable to register minors for usb_device\n");
goto out;
}
cdev_init(&usb_device_cdev, &usbdev_file_operations);
retval = cdev_add(&usb_device_cdev, USB_DEVICE_DEV, USB_DEVICE_MAX);
if (retval) {
printk(KERN_ERR "Unable to get usb_device major %d\n",
USB_DEVICE_MAJOR);
goto error_cdev;
}
usb_register_notify(&usbdev_nb);
out:
return retval;
error_cdev:
unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX);
goto out;
}
void usb_devio_cleanup(void)
{
usb_unregister_notify(&usbdev_nb);
cdev_del(&usb_device_cdev);
unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5048_0 |
crossvul-cpp_data_bad_1125_3 | /*
* Elliptic curve DSA
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* References:
*
* SEC1 http://www.secg.org/index.php?action=secg,docs_secg
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_ECDSA_C)
#include "mbedtls/ecdsa.h"
#include "mbedtls/asn1write.h"
#include <string.h>
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
#include "mbedtls/hmac_drbg.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/platform_util.h"
/* Parameter validation macros based on platform_util.h */
#define ECDSA_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
#define ECDSA_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#if defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Sub-context for ecdsa_verify()
*/
struct mbedtls_ecdsa_restart_ver
{
mbedtls_mpi u1, u2; /* intermediate values */
enum { /* what to do next? */
ecdsa_ver_init = 0, /* getting started */
ecdsa_ver_muladd, /* muladd step */
} state;
};
/*
* Init verify restart sub-context
*/
static void ecdsa_restart_ver_init( mbedtls_ecdsa_restart_ver_ctx *ctx )
{
mbedtls_mpi_init( &ctx->u1 );
mbedtls_mpi_init( &ctx->u2 );
ctx->state = ecdsa_ver_init;
}
/*
* Free the components of a verify restart sub-context
*/
static void ecdsa_restart_ver_free( mbedtls_ecdsa_restart_ver_ctx *ctx )
{
if( ctx == NULL )
return;
mbedtls_mpi_free( &ctx->u1 );
mbedtls_mpi_free( &ctx->u2 );
ecdsa_restart_ver_init( ctx );
}
/*
* Sub-context for ecdsa_sign()
*/
struct mbedtls_ecdsa_restart_sig
{
int sign_tries;
int key_tries;
mbedtls_mpi k; /* per-signature random */
mbedtls_mpi r; /* r value */
enum { /* what to do next? */
ecdsa_sig_init = 0, /* getting started */
ecdsa_sig_mul, /* doing ecp_mul() */
ecdsa_sig_modn, /* mod N computations */
} state;
};
/*
* Init verify sign sub-context
*/
static void ecdsa_restart_sig_init( mbedtls_ecdsa_restart_sig_ctx *ctx )
{
ctx->sign_tries = 0;
ctx->key_tries = 0;
mbedtls_mpi_init( &ctx->k );
mbedtls_mpi_init( &ctx->r );
ctx->state = ecdsa_sig_init;
}
/*
* Free the components of a sign restart sub-context
*/
static void ecdsa_restart_sig_free( mbedtls_ecdsa_restart_sig_ctx *ctx )
{
if( ctx == NULL )
return;
mbedtls_mpi_free( &ctx->k );
mbedtls_mpi_free( &ctx->r );
}
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/*
* Sub-context for ecdsa_sign_det()
*/
struct mbedtls_ecdsa_restart_det
{
mbedtls_hmac_drbg_context rng_ctx; /* DRBG state */
enum { /* what to do next? */
ecdsa_det_init = 0, /* getting started */
ecdsa_det_sign, /* make signature */
} state;
};
/*
* Init verify sign_det sub-context
*/
static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx )
{
mbedtls_hmac_drbg_init( &ctx->rng_ctx );
ctx->state = ecdsa_det_init;
}
/*
* Free the components of a sign_det restart sub-context
*/
static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx )
{
if( ctx == NULL )
return;
mbedtls_hmac_drbg_free( &ctx->rng_ctx );
ecdsa_restart_det_init( ctx );
}
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
#define ECDSA_RS_ECP &rs_ctx->ecp
/* Utility macro for checking and updating ops budget */
#define ECDSA_BUDGET( ops ) \
MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, &rs_ctx->ecp, ops ) );
/* Call this when entering a function that needs its own sub-context */
#define ECDSA_RS_ENTER( SUB ) do { \
/* reset ops count for this call if top-level */ \
if( rs_ctx != NULL && rs_ctx->ecp.depth++ == 0 ) \
rs_ctx->ecp.ops_done = 0; \
\
/* set up our own sub-context if needed */ \
if( mbedtls_ecp_restart_is_enabled() && \
rs_ctx != NULL && rs_ctx->SUB == NULL ) \
{ \
rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \
if( rs_ctx->SUB == NULL ) \
return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \
\
ecdsa_restart_## SUB ##_init( rs_ctx->SUB ); \
} \
} while( 0 )
/* Call this when leaving a function that needs its own sub-context */
#define ECDSA_RS_LEAVE( SUB ) do { \
/* clear our sub-context when not in progress (done or error) */ \
if( rs_ctx != NULL && rs_ctx->SUB != NULL && \
ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \
{ \
ecdsa_restart_## SUB ##_free( rs_ctx->SUB ); \
mbedtls_free( rs_ctx->SUB ); \
rs_ctx->SUB = NULL; \
} \
\
if( rs_ctx != NULL ) \
rs_ctx->ecp.depth--; \
} while( 0 )
#else /* MBEDTLS_ECP_RESTARTABLE */
#define ECDSA_RS_ECP NULL
#define ECDSA_BUDGET( ops ) /* no-op; for compatibility */
#define ECDSA_RS_ENTER( SUB ) (void) rs_ctx
#define ECDSA_RS_LEAVE( SUB ) (void) rs_ctx
#endif /* MBEDTLS_ECP_RESTARTABLE */
/*
* Derive a suitable integer for group grp from a buffer of length len
* SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3
*/
static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x,
const unsigned char *buf, size_t blen )
{
int ret;
size_t n_size = ( grp->nbits + 7 ) / 8;
size_t use_size = blen > n_size ? n_size : blen;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) );
if( use_size * 8 > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) );
/* While at it, reduce modulo N */
if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) );
cleanup:
return( ret );
}
#if !defined(MBEDTLS_ECDSA_SIGN_ALT)
/*
* Compute ECDSA signature of a hashed message (SEC1 4.1.3)
* Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
*/
static int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
ECDSA_RS_ENTER( sig );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
{
/* redirect to our context */
p_sign_tries = &rs_ctx->sig->sign_tries;
p_key_tries = &rs_ctx->sig->key_tries;
pk = &rs_ctx->sig->k;
pr = &rs_ctx->sig->r;
/* jump to current step */
if( rs_ctx->sig->state == ecdsa_sig_mul )
goto mul;
if( rs_ctx->sig->state == ecdsa_sig_modn )
goto modn;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_mul;
mul:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
f_rng, p_rng, ECDSA_RS_ECP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_modn;
modn:
#endif
/*
* Accounting for everything up to the end of the loop
* (step 6, but checking now avoids saving e and t)
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
mbedtls_mpi_copy( r, pr );
#endif
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
ECDSA_RS_LEAVE( sig );
return( ret );
}
/*
* Compute ECDSA signature of a hashed message
*/
int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
ECDSA_VALIDATE_RET( grp != NULL );
ECDSA_VALIDATE_RET( r != NULL );
ECDSA_VALIDATE_RET( s != NULL );
ECDSA_VALIDATE_RET( d != NULL );
ECDSA_VALIDATE_RET( f_rng != NULL );
ECDSA_VALIDATE_RET( buf != NULL || blen == 0 );
return( ecdsa_sign_restartable( grp, r, s, d, buf, blen,
f_rng, p_rng, NULL ) );
}
#endif /* !MBEDTLS_ECDSA_SIGN_ALT */
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/*
* Deterministic signature wrapper
*/
static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_hmac_drbg_context rng_ctx;
mbedtls_hmac_drbg_context *p_rng = &rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
size_t grp_len = ( grp->nbits + 7 ) / 8;
const mbedtls_md_info_t *md_info;
mbedtls_mpi h;
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
mbedtls_mpi_init( &h );
mbedtls_hmac_drbg_init( &rng_ctx );
ECDSA_RS_ENTER( det );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->det != NULL )
{
/* redirect to our context */
p_rng = &rs_ctx->det->rng_ctx;
/* jump to current step */
if( rs_ctx->det->state == ecdsa_det_sign )
goto sign;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
/* Use private key and message hash (reduced) to initialize HMAC_DRBG */
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );
MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );
mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->det != NULL )
rs_ctx->det->state = ecdsa_det_sign;
sign:
#endif
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, p_rng );
#else
ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, p_rng, rs_ctx );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
cleanup:
mbedtls_hmac_drbg_free( &rng_ctx );
mbedtls_mpi_free( &h );
ECDSA_RS_LEAVE( det );
return( ret );
}
/*
* Deterministic signature wrapper
*/
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg )
{
ECDSA_VALIDATE_RET( grp != NULL );
ECDSA_VALIDATE_RET( r != NULL );
ECDSA_VALIDATE_RET( s != NULL );
ECDSA_VALIDATE_RET( d != NULL );
ECDSA_VALIDATE_RET( buf != NULL || blen == 0 );
return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) );
}
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
/*
* Verify ECDSA signature of hashed message (SEC1 4.1.4)
* Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
*/
static int ecdsa_verify_restartable( mbedtls_ecp_group *grp,
const unsigned char *buf, size_t blen,
const mbedtls_ecp_point *Q,
const mbedtls_mpi *r, const mbedtls_mpi *s,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi e, s_inv, u1, u2;
mbedtls_ecp_point R;
mbedtls_mpi *pu1 = &u1, *pu2 = &u2;
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv );
mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 );
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
ECDSA_RS_ENTER( ver );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ver != NULL )
{
/* redirect to our context */
pu1 = &rs_ctx->ver->u1;
pu2 = &rs_ctx->ver->u2;
/* jump to current step */
if( rs_ctx->ver->state == ecdsa_ver_muladd )
goto muladd;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
/*
* Step 1: make sure r and s are in range 1..n-1
*/
if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 ||
mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
/*
* Step 3: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Step 4: u1 = e / s mod n, u2 = r / s mod n
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2 );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu1, &e, &s_inv ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu1, pu1, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu2, r, &s_inv ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu2, pu2, &grp->N ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ver != NULL )
rs_ctx->ver->state = ecdsa_ver_muladd;
muladd:
#endif
/*
* Step 5: R = u1 G + u2 Q
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd_restartable( grp,
&R, pu1, &grp->G, pu2, Q, ECDSA_RS_ECP ) );
if( mbedtls_ecp_is_zero( &R ) )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
/*
* Step 6: convert xR to an integer (no-op)
* Step 7: reduce xR mod n (gives v)
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) );
/*
* Step 8: check if v (that is, R.X) is equal to r
*/
if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv );
mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 );
ECDSA_RS_LEAVE( ver );
return( ret );
}
/*
* Verify ECDSA signature of hashed message
*/
int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
const unsigned char *buf, size_t blen,
const mbedtls_ecp_point *Q,
const mbedtls_mpi *r,
const mbedtls_mpi *s)
{
ECDSA_VALIDATE_RET( grp != NULL );
ECDSA_VALIDATE_RET( Q != NULL );
ECDSA_VALIDATE_RET( r != NULL );
ECDSA_VALIDATE_RET( s != NULL );
ECDSA_VALIDATE_RET( buf != NULL || blen == 0 );
return( ecdsa_verify_restartable( grp, buf, blen, Q, r, s, NULL ) );
}
#endif /* !MBEDTLS_ECDSA_VERIFY_ALT */
/*
* Convert a signature (given by context) to ASN.1
*/
static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
unsigned char *sig, size_t *slen )
{
int ret;
unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];
unsigned char *p = buf + sizeof( buf );
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
memcpy( sig, p, len );
*slen = len;
return( 0 );
}
/*
* Compute and write signature
*/
int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg, rs_ctx ) );
#else
(void) md_alg;
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#else
MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng, rs_ctx ) );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
/*
* Compute and write signature
*/
int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
return( mbedtls_ecdsa_write_signature_restartable(
ctx, md_alg, hash, hlen, sig, slen, f_rng, p_rng, NULL ) );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED) && \
defined(MBEDTLS_ECDSA_DETERMINISTIC)
int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
mbedtls_md_type_t md_alg )
{
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen,
NULL, NULL ) );
}
#endif
/*
* Read and check signature
*/
int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
const unsigned char *sig, size_t slen )
{
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
return( mbedtls_ecdsa_read_signature_restartable(
ctx, hash, hlen, sig, slen, NULL ) );
}
/*
* Restartable read and check signature
*/
int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
const unsigned char *sig, size_t slen,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
unsigned char *p = (unsigned char *) sig;
const unsigned char *end = sig + slen;
size_t len;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
if( p + len != end )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
goto cleanup;
}
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 )
{
ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
#if defined(MBEDTLS_ECDSA_VERIFY_ALT)
if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen,
&ctx->Q, &r, &s ) ) != 0 )
goto cleanup;
#else
if( ( ret = ecdsa_verify_restartable( &ctx->grp, hash, hlen,
&ctx->Q, &r, &s, rs_ctx ) ) != 0 )
goto cleanup;
#endif /* MBEDTLS_ECDSA_VERIFY_ALT */
/* At this point we know that the buffer starts with a valid signature.
* Return 0 if the buffer just contains the signature, and a specific
* error code if the valid signature is followed by more data. */
if( p != end )
ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
#if !defined(MBEDTLS_ECDSA_GENKEY_ALT)
/*
* Generate key pair
*/
int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = 0;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( f_rng != NULL );
ret = mbedtls_ecp_group_load( &ctx->grp, gid );
if( ret != 0 )
return( ret );
return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d,
&ctx->Q, f_rng, p_rng ) );
}
#endif /* !MBEDTLS_ECDSA_GENKEY_ALT */
/*
* Set context from an mbedtls_ecp_keypair
*/
int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key )
{
int ret;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( key != NULL );
if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||
( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 ||
( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 )
{
mbedtls_ecdsa_free( ctx );
}
return( ret );
}
/*
* Initialize context
*/
void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx )
{
ECDSA_VALIDATE( ctx != NULL );
mbedtls_ecp_keypair_init( ctx );
}
/*
* Free context
*/
void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_ecp_keypair_free( ctx );
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Initialize a restart context
*/
void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx )
{
ECDSA_VALIDATE( ctx != NULL );
mbedtls_ecp_restart_init( &ctx->ecp );
ctx->ver = NULL;
ctx->sig = NULL;
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
ctx->det = NULL;
#endif
}
/*
* Free the components of a restart context
*/
void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx )
{
if( ctx == NULL )
return;
mbedtls_ecp_restart_free( &ctx->ecp );
ecdsa_restart_ver_free( ctx->ver );
mbedtls_free( ctx->ver );
ctx->ver = NULL;
ecdsa_restart_sig_free( ctx->sig );
mbedtls_free( ctx->sig );
ctx->sig = NULL;
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
ecdsa_restart_det_free( ctx->det );
mbedtls_free( ctx->det );
ctx->det = NULL;
#endif
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
#endif /* MBEDTLS_ECDSA_C */
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1125_3 |
crossvul-cpp_data_good_3835_0 | /*
RFCOMM implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* RFCOMM sockets.
*/
#include <linux/export.h>
#include <linux/debugfs.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
#include <net/bluetooth/rfcomm.h>
static const struct proto_ops rfcomm_sock_ops;
static struct bt_sock_list rfcomm_sk_list = {
.lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock)
};
static void rfcomm_sock_close(struct sock *sk);
static void rfcomm_sock_kill(struct sock *sk);
/* ---- DLC callbacks ----
*
* called under rfcomm_dlc_lock()
*/
static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb)
{
struct sock *sk = d->owner;
if (!sk)
return;
atomic_add(skb->len, &sk->sk_rmem_alloc);
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, skb->len);
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
rfcomm_dlc_throttle(d);
}
static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err)
{
struct sock *sk = d->owner, *parent;
unsigned long flags;
if (!sk)
return;
BT_DBG("dlc %p state %ld err %d", d, d->state, err);
local_irq_save(flags);
bh_lock_sock(sk);
if (err)
sk->sk_err = err;
sk->sk_state = d->state;
parent = bt_sk(sk)->parent;
if (parent) {
if (d->state == BT_CLOSED) {
sock_set_flag(sk, SOCK_ZAPPED);
bt_accept_unlink(sk);
}
parent->sk_data_ready(parent, 0);
} else {
if (d->state == BT_CONNECTED)
rfcomm_session_getaddr(d->session, &bt_sk(sk)->src, NULL);
sk->sk_state_change(sk);
}
bh_unlock_sock(sk);
local_irq_restore(flags);
if (parent && sock_flag(sk, SOCK_ZAPPED)) {
/* We have to drop DLC lock here, otherwise
* rfcomm_sock_destruct() will dead lock. */
rfcomm_dlc_unlock(d);
rfcomm_sock_kill(sk);
rfcomm_dlc_lock(d);
}
}
/* ---- Socket functions ---- */
static struct sock *__rfcomm_get_sock_by_addr(u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL;
struct hlist_node *node;
sk_for_each(sk, node, &rfcomm_sk_list.head) {
if (rfcomm_pi(sk)->channel == channel &&
!bacmp(&bt_sk(sk)->src, src))
break;
}
return node ? sk : NULL;
}
/* Find socket with channel and source bdaddr.
* Returns closest match.
*/
static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL, *sk1 = NULL;
struct hlist_node *node;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, node, &rfcomm_sk_list.head) {
if (state && sk->sk_state != state)
continue;
if (rfcomm_pi(sk)->channel == channel) {
/* Exact match. */
if (!bacmp(&bt_sk(sk)->src, src))
break;
/* Closest match */
if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY))
sk1 = sk;
}
}
read_unlock(&rfcomm_sk_list.lock);
return node ? sk : sk1;
}
static void rfcomm_sock_destruct(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p dlc %p", sk, d);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
rfcomm_dlc_lock(d);
rfcomm_pi(sk)->dlc = NULL;
/* Detach DLC if it's owned by this socket */
if (d->owner == sk)
d->owner = NULL;
rfcomm_dlc_unlock(d);
rfcomm_dlc_put(d);
}
static void rfcomm_sock_cleanup_listen(struct sock *parent)
{
struct sock *sk;
BT_DBG("parent %p", parent);
/* Close not yet accepted dlcs */
while ((sk = bt_accept_dequeue(parent, NULL))) {
rfcomm_sock_close(sk);
rfcomm_sock_kill(sk);
}
parent->sk_state = BT_CLOSED;
sock_set_flag(parent, SOCK_ZAPPED);
}
/* Kill socket (only if zapped and orphan)
* Must be called on unlocked socket.
*/
static void rfcomm_sock_kill(struct sock *sk)
{
if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket)
return;
BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt));
/* Kill poor orphan */
bt_sock_unlink(&rfcomm_sk_list, sk);
sock_set_flag(sk, SOCK_DEAD);
sock_put(sk);
}
static void __rfcomm_sock_close(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket);
switch (sk->sk_state) {
case BT_LISTEN:
rfcomm_sock_cleanup_listen(sk);
break;
case BT_CONNECT:
case BT_CONNECT2:
case BT_CONFIG:
case BT_CONNECTED:
rfcomm_dlc_close(d, 0);
default:
sock_set_flag(sk, SOCK_ZAPPED);
break;
}
}
/* Close socket.
* Must be called on unlocked socket.
*/
static void rfcomm_sock_close(struct sock *sk)
{
lock_sock(sk);
__rfcomm_sock_close(sk);
release_sock(sk);
}
static void rfcomm_sock_init(struct sock *sk, struct sock *parent)
{
struct rfcomm_pinfo *pi = rfcomm_pi(sk);
BT_DBG("sk %p", sk);
if (parent) {
sk->sk_type = parent->sk_type;
pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP,
&bt_sk(parent)->flags);
pi->sec_level = rfcomm_pi(parent)->sec_level;
pi->role_switch = rfcomm_pi(parent)->role_switch;
security_sk_clone(parent, sk);
} else {
pi->dlc->defer_setup = 0;
pi->sec_level = BT_SECURITY_LOW;
pi->role_switch = 0;
}
pi->dlc->sec_level = pi->sec_level;
pi->dlc->role_switch = pi->role_switch;
}
static struct proto rfcomm_proto = {
.name = "RFCOMM",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rfcomm_pinfo)
};
static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio)
{
struct rfcomm_dlc *d;
struct sock *sk;
sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto);
if (!sk)
return NULL;
sock_init_data(sock, sk);
INIT_LIST_HEAD(&bt_sk(sk)->accept_q);
d = rfcomm_dlc_alloc(prio);
if (!d) {
sk_free(sk);
return NULL;
}
d->data_ready = rfcomm_sk_data_ready;
d->state_change = rfcomm_sk_state_change;
rfcomm_pi(sk)->dlc = d;
d->owner = sk;
sk->sk_destruct = rfcomm_sock_destruct;
sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT;
sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = proto;
sk->sk_state = BT_OPEN;
bt_sock_link(&rfcomm_sk_list, sk);
BT_DBG("sk %p", sk);
return sk;
}
static int rfcomm_sock_create(struct net *net, struct socket *sock,
int protocol, int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sock->ops = &rfcomm_sock_ops;
sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC);
if (!sk)
return -ENOMEM;
rfcomm_sock_init(sk, NULL);
return 0;
}
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %s", sk, batostr(&sa->rc_bdaddr));
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa->rc_channel && __rfcomm_get_sock_by_addr(sa->rc_channel, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&bt_sk(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int err = 0;
BT_DBG("sk %p", sk);
if (alen < sizeof(struct sockaddr_rc) ||
addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
sk->sk_state = BT_CONNECT;
bacpy(&bt_sk(sk)->dst, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
d->sec_level = rfcomm_pi(sk)->sec_level;
d->role_switch = rfcomm_pi(sk)->role_switch;
err = rfcomm_dlc_open(d, &bt_sk(sk)->src, &sa->rc_bdaddr, sa->rc_channel);
if (!err)
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
if (!rfcomm_pi(sk)->channel) {
bdaddr_t *src = &bt_sk(sk)->src;
u8 channel;
err = -EINVAL;
write_lock(&rfcomm_sk_list.lock);
for (channel = 1; channel < 31; channel++)
if (!__rfcomm_get_sock_by_addr(channel, src)) {
rfcomm_pi(sk)->channel = channel;
err = 0;
break;
}
write_unlock(&rfcomm_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *nsk;
long timeo;
int err = 0;
lock_sock(sk);
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
nsk = bt_accept_dequeue(sk, newsock);
if (nsk)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", nsk);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
memset(sa, 0, sizeof(*sa));
sa->rc_family = AF_BLUETOOTH;
sa->rc_channel = rfcomm_pi(sk)->channel;
if (peer)
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst);
else
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src);
*len = sizeof(struct sockaddr_rc);
return 0;
}
static int rfcomm_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
struct sk_buff *skb;
int sent = 0;
if (test_bit(RFCOMM_DEFER_SETUP, &d->flags))
return -ENOTCONN;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (sk->sk_shutdown & SEND_SHUTDOWN)
return -EPIPE;
BT_DBG("sock %p, sk %p", sock, sk);
lock_sock(sk);
while (len) {
size_t size = min_t(size_t, len, d->mtu);
int err;
skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE,
msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb) {
if (sent == 0)
sent = err;
break;
}
skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE);
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
skb->priority = sk->sk_priority;
err = rfcomm_dlc_send(d, skb);
if (err < 0) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
sent += size;
len -= size;
}
release_sock(sk);
return sent;
}
static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int err = 0;
u32 opt;
BT_DBG("sk %p", sk);
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt & RFCOMM_LM_AUTH)
rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW;
if (opt & RFCOMM_LM_ENCRYPT)
rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM;
if (opt & RFCOMM_LM_SECURE)
rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH;
rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int err = 0;
size_t len;
u32 opt;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = BT_SECURITY_LOW;
len = min_t(unsigned int, sizeof(sec), optlen);
if (copy_from_user((char *) &sec, optval, len)) {
err = -EFAULT;
break;
}
if (sec.level > BT_SECURITY_HIGH) {
err = -EINVAL;
break;
}
rfcomm_pi(sk)->sec_level = sec.level;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt)
set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
else
clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct rfcomm_conninfo cinfo;
struct l2cap_conn *conn = l2cap_pi(sk)->chan->conn;
int len, err = 0;
u32 opt;
BT_DBG("sk %p", sk);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
switch (rfcomm_pi(sk)->sec_level) {
case BT_SECURITY_LOW:
opt = RFCOMM_LM_AUTH;
break;
case BT_SECURITY_MEDIUM:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT;
break;
case BT_SECURITY_HIGH:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT |
RFCOMM_LM_SECURE;
break;
default:
opt = 0;
break;
}
if (rfcomm_pi(sk)->role_switch)
opt |= RFCOMM_LM_MASTER;
if (put_user(opt, (u32 __user *) optval))
err = -EFAULT;
break;
case RFCOMM_CONNINFO:
if (sk->sk_state != BT_CONNECTED &&
!rfcomm_pi(sk)->dlc->defer_setup) {
err = -ENOTCONN;
break;
}
memset(&cinfo, 0, sizeof(cinfo));
cinfo.hci_handle = conn->hcon->handle;
memcpy(cinfo.dev_class, conn->hcon->dev_class, 3);
len = min_t(unsigned int, len, sizeof(cinfo));
if (copy_to_user(optval, (char *) &cinfo, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int len, err = 0;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = rfcomm_pi(sk)->sec_level;
sec.key_size = 0;
len = min_t(unsigned int, len, sizeof(sec));
if (copy_to_user(optval, (char *) &sec, len))
err = -EFAULT;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk __maybe_unused = sock->sk;
int err;
BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg);
err = bt_sock_ioctl(sock, cmd, arg);
if (err == -ENOIOCTLCMD) {
#ifdef CONFIG_BT_RFCOMM_TTY
lock_sock(sk);
err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg);
release_sock(sk);
#else
err = -EOPNOTSUPP;
#endif
}
return err;
}
static int rfcomm_sock_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
lock_sock(sk);
if (!sk->sk_shutdown) {
sk->sk_shutdown = SHUTDOWN_MASK;
__rfcomm_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime)
err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime);
}
release_sock(sk);
return err;
}
static int rfcomm_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
int err;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
err = rfcomm_sock_shutdown(sock, 2);
sock_orphan(sk);
rfcomm_sock_kill(sk);
return err;
}
/* ---- RFCOMM core layer callbacks ----
*
* called under rfcomm_lock()
*/
int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d)
{
struct sock *sk, *parent;
bdaddr_t src, dst;
int result = 0;
BT_DBG("session %p channel %d", s, channel);
rfcomm_session_getaddr(s, &src, &dst);
/* Check if we have socket listening on channel */
parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src);
if (!parent)
return 0;
bh_lock_sock(parent);
/* Check for backlog size */
if (sk_acceptq_is_full(parent)) {
BT_DBG("backlog full %d", parent->sk_ack_backlog);
goto done;
}
sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC);
if (!sk)
goto done;
bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM);
rfcomm_sock_init(sk, parent);
bacpy(&bt_sk(sk)->src, &src);
bacpy(&bt_sk(sk)->dst, &dst);
rfcomm_pi(sk)->channel = channel;
sk->sk_state = BT_CONFIG;
bt_accept_enqueue(parent, sk);
/* Accept connection and return socket DLC */
*d = rfcomm_pi(sk)->dlc;
result = 1;
done:
bh_unlock_sock(parent);
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags))
parent->sk_state_change(parent);
return result;
}
static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p)
{
struct sock *sk;
struct hlist_node *node;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, node, &rfcomm_sk_list.head) {
seq_printf(f, "%s %s %d %d\n",
batostr(&bt_sk(sk)->src),
batostr(&bt_sk(sk)->dst),
sk->sk_state, rfcomm_pi(sk)->channel);
}
read_unlock(&rfcomm_sk_list.lock);
return 0;
}
static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, rfcomm_sock_debugfs_show, inode->i_private);
}
static const struct file_operations rfcomm_sock_debugfs_fops = {
.open = rfcomm_sock_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *rfcomm_sock_debugfs;
static const struct proto_ops rfcomm_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = rfcomm_sock_release,
.bind = rfcomm_sock_bind,
.connect = rfcomm_sock_connect,
.listen = rfcomm_sock_listen,
.accept = rfcomm_sock_accept,
.getname = rfcomm_sock_getname,
.sendmsg = rfcomm_sock_sendmsg,
.recvmsg = rfcomm_sock_recvmsg,
.shutdown = rfcomm_sock_shutdown,
.setsockopt = rfcomm_sock_setsockopt,
.getsockopt = rfcomm_sock_getsockopt,
.ioctl = rfcomm_sock_ioctl,
.poll = bt_sock_poll,
.socketpair = sock_no_socketpair,
.mmap = sock_no_mmap
};
static const struct net_proto_family rfcomm_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = rfcomm_sock_create
};
int __init rfcomm_init_sockets(void)
{
int err;
err = proto_register(&rfcomm_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops);
if (err < 0)
goto error;
if (bt_debugfs) {
rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444,
bt_debugfs, NULL, &rfcomm_sock_debugfs_fops);
if (!rfcomm_sock_debugfs)
BT_ERR("Failed to create RFCOMM debug file");
}
BT_INFO("RFCOMM socket layer initialized");
return 0;
error:
BT_ERR("RFCOMM socket layer registration failed");
proto_unregister(&rfcomm_proto);
return err;
}
void __exit rfcomm_cleanup_sockets(void)
{
debugfs_remove(rfcomm_sock_debugfs);
if (bt_sock_unregister(BTPROTO_RFCOMM) < 0)
BT_ERR("RFCOMM socket layer unregistration failed");
proto_unregister(&rfcomm_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3835_0 |
crossvul-cpp_data_bad_3769_1 | /*
* linux/fs/binfmt_script.c
*
* Copyright (C) 1996 Martin von Löwis
* original #!-checking implemented by tytso.
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/binfmts.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/err.h>
#include <linux/fs.h>
static int load_script(struct linux_binprm *bprm)
{
const char *i_arg, *i_name;
char *cp;
struct file *file;
char interp[BINPRM_BUF_SIZE];
int retval;
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
return -ENOEXEC;
/*
* This section does the #! interpretation.
* Sorta complicated, but hopefully it will work. -TYT
*/
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
bprm->buf[BINPRM_BUF_SIZE - 1] = '\0';
if ((cp = strchr(bprm->buf, '\n')) == NULL)
cp = bprm->buf+BINPRM_BUF_SIZE-1;
*cp = '\0';
while (cp > bprm->buf) {
cp--;
if ((*cp == ' ') || (*cp == '\t'))
*cp = '\0';
else
break;
}
for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++);
if (*cp == '\0')
return -ENOEXEC; /* No interpreter name found */
i_name = cp;
i_arg = NULL;
for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++)
/* nothing */ ;
while ((*cp == ' ') || (*cp == '\t'))
*cp++ = '\0';
if (*cp)
i_arg = cp;
strcpy (interp, i_name);
/*
* OK, we've parsed out the interpreter name and
* (optional) argument.
* Splice in (1) the interpreter's name for argv[0]
* (2) (optional) argument to interpreter
* (3) filename of shell script (replace argv[0])
*
* This is done in reverse order, because of how the
* user environment and arguments are stored.
*/
retval = remove_arg_zero(bprm);
if (retval)
return retval;
retval = copy_strings_kernel(1, &bprm->interp, bprm);
if (retval < 0) return retval;
bprm->argc++;
if (i_arg) {
retval = copy_strings_kernel(1, &i_arg, bprm);
if (retval < 0) return retval;
bprm->argc++;
}
retval = copy_strings_kernel(1, &i_name, bprm);
if (retval) return retval;
bprm->argc++;
bprm->interp = interp;
/*
* OK, now restart the process with the interpreter's dentry.
*/
file = open_exec(interp);
if (IS_ERR(file))
return PTR_ERR(file);
bprm->file = file;
retval = prepare_binprm(bprm);
if (retval < 0)
return retval;
return search_binary_handler(bprm);
}
static struct linux_binfmt script_format = {
.module = THIS_MODULE,
.load_binary = load_script,
};
static int __init init_script_binfmt(void)
{
register_binfmt(&script_format);
return 0;
}
static void __exit exit_script_binfmt(void)
{
unregister_binfmt(&script_format);
}
core_initcall(init_script_binfmt);
module_exit(exit_script_binfmt);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3769_1 |
crossvul-cpp_data_bad_3825_0 | /* xfrm_user.c: User interface to configure xfrm engine.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
*
*/
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/init.h>
#include <linux/security.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/netlink.h>
#include <net/ah.h>
#include <asm/uaccess.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/in6.h>
#endif
static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
{
struct nlattr *rt = attrs[type];
struct xfrm_algo *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_len(algp))
return -EINVAL;
switch (type) {
case XFRMA_ALG_AUTH:
case XFRMA_ALG_CRYPT:
case XFRMA_ALG_COMP:
break;
default:
return -EINVAL;
}
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_auth_trunc(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
struct xfrm_algo_auth *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_auth_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_aead(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
struct xfrm_algo_aead *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < aead_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
xfrm_address_t **addrp)
{
struct nlattr *rt = attrs[type];
if (rt && addrp)
*addrp = nla_data(rt);
}
static inline int verify_sec_ctx_len(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
return -EINVAL;
return 0;
}
static inline int verify_replay(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
if ((p->flags & XFRM_STATE_ESN) && !rt)
return -EINVAL;
if (!rt)
return 0;
if (p->id.proto != IPPROTO_ESP)
return -EINVAL;
if (p->replay_window != 0)
return -EINVAL;
return 0;
}
static int verify_newsa_info(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
int err;
err = -EINVAL;
switch (p->family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
err = -EAFNOSUPPORT;
goto out;
#endif
default:
goto out;
}
err = -EINVAL;
switch (p->id.proto) {
case IPPROTO_AH:
if ((!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC]) ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
case IPPROTO_ESP:
if (attrs[XFRMA_ALG_COMP])
goto out;
if (!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC] &&
!attrs[XFRMA_ALG_CRYPT] &&
!attrs[XFRMA_ALG_AEAD])
goto out;
if ((attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT]) &&
attrs[XFRMA_ALG_AEAD])
goto out;
if (attrs[XFRMA_TFCPAD] &&
p->mode != XFRM_MODE_TUNNEL)
goto out;
break;
case IPPROTO_COMP:
if (!attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
#if IS_ENABLED(CONFIG_IPV6)
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
if (attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ENCAP] ||
attrs[XFRMA_SEC_CTX] ||
attrs[XFRMA_TFCPAD] ||
!attrs[XFRMA_COADDR])
goto out;
break;
#endif
default:
goto out;
}
if ((err = verify_aead(attrs)))
goto out;
if ((err = verify_auth_trunc(attrs)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
goto out;
if ((err = verify_sec_ctx_len(attrs)))
goto out;
if ((err = verify_replay(p, attrs)))
goto out;
err = -EINVAL;
switch (p->mode) {
case XFRM_MODE_TRANSPORT:
case XFRM_MODE_TUNNEL:
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_BEET:
break;
default:
goto out;
}
err = 0;
out:
return err;
}
static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo *ualg;
struct xfrm_algo_auth *p;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
p->alg_key_len = ualg->alg_key_len;
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
*algpp = p;
return 0;
}
static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_auth *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN ||
ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
return -EINVAL;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
if (!p->alg_trunc_len)
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
*algpp = p;
return 0;
}
static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_aead *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
{
int len = 0;
if (xfrm_ctx) {
len += sizeof(struct xfrm_user_sec_ctx);
len += xfrm_ctx->ctx_len;
}
return len;
}
static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&x->id, &p->id, sizeof(x->id));
memcpy(&x->sel, &p->sel, sizeof(x->sel));
memcpy(&x->lft, &p->lft, sizeof(x->lft));
x->props.mode = p->mode;
x->props.replay_window = p->replay_window;
x->props.reqid = p->reqid;
x->props.family = p->family;
memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
x->props.flags = p->flags;
if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
x->sel.family = p->family;
}
/*
* someday when pfkey also has support, we could have the code
* somehow made shareable and move it to xfrm_state.c - JHS
*
*/
static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs)
{
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
if (re) {
struct xfrm_replay_state_esn *replay_esn;
replay_esn = nla_data(re);
memcpy(x->replay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
memcpy(x->preplay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
}
if (rp) {
struct xfrm_replay_state *replay;
replay = nla_data(rp);
memcpy(&x->replay, replay, sizeof(*replay));
memcpy(&x->preplay, replay, sizeof(*replay));
}
if (lt) {
struct xfrm_lifetime_cur *ltime;
ltime = nla_data(lt);
x->curlft.bytes = ltime->bytes;
x->curlft.packets = ltime->packets;
x->curlft.add_time = ltime->add_time;
x->curlft.use_time = ltime->use_time;
}
if (et)
x->replay_maxage = nla_get_u32(et);
if (rt)
x->replay_maxdiff = nla_get_u32(rt);
}
static struct xfrm_state *xfrm_state_construct(struct net *net,
struct xfrm_usersa_info *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto error_no_put;
copy_from_user_state(x, p);
if ((err = attach_aead(&x->aead, &x->props.ealgo,
attrs[XFRMA_ALG_AEAD])))
goto error;
if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH_TRUNC])))
goto error;
if (!x->props.aalgo) {
if ((err = attach_auth(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH])))
goto error;
}
if ((err = attach_one_algo(&x->ealg, &x->props.ealgo,
xfrm_ealg_get_byname,
attrs[XFRMA_ALG_CRYPT])))
goto error;
if ((err = attach_one_algo(&x->calg, &x->props.calgo,
xfrm_calg_get_byname,
attrs[XFRMA_ALG_COMP])))
goto error;
if (attrs[XFRMA_ENCAP]) {
x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
sizeof(*x->encap), GFP_KERNEL);
if (x->encap == NULL)
goto error;
}
if (attrs[XFRMA_TFCPAD])
x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
if (attrs[XFRMA_COADDR]) {
x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
sizeof(*x->coaddr), GFP_KERNEL);
if (x->coaddr == NULL)
goto error;
}
xfrm_mark_get(attrs, &x->mark);
err = __xfrm_init_state(x, false);
if (err)
goto error;
if (attrs[XFRMA_SEC_CTX] &&
security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])))
goto error;
if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
attrs[XFRMA_REPLAY_ESN_VAL])))
goto error;
x->km.seq = p->seq;
x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
/* sysctl_xfrm_aevent_etime is in 100ms units */
x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
if ((err = xfrm_init_replay(x)))
goto error;
/* override default values from above */
xfrm_update_ae_params(x, attrs);
return x;
error:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
error_no_put:
*errp = err;
return NULL;
}
static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_info *p = nlmsg_data(nlh);
struct xfrm_state *x;
int err;
struct km_event c;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newsa_info(p, attrs);
if (err)
return err;
x = xfrm_state_construct(net, p, attrs, &err);
if (!x)
return err;
xfrm_state_hold(x);
if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
security_task_getsecid(current, &sid);
xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
struct xfrm_usersa_id *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = NULL;
struct xfrm_mark m;
int err;
u32 mark = xfrm_mark_get(attrs, &m);
if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
err = -ESRCH;
x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
} else {
xfrm_address_t *saddr = NULL;
verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
if (!saddr) {
err = -EINVAL;
goto out;
}
err = -ESRCH;
x = xfrm_state_lookup_byaddr(net, mark,
&p->daddr, saddr,
p->proto, p->family);
}
out:
if (!x && errp)
*errp = err;
return x;
}
static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err = -ESRCH;
struct km_event c;
struct xfrm_usersa_id *p = nlmsg_data(nlh);
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
return err;
if ((err = security_xfrm_state_delete(x)) != 0)
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
security_task_getsecid(current, &sid);
xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid);
xfrm_state_put(x);
return err;
}
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
struct xfrm_dump_info {
struct sk_buff *in_skb;
struct sk_buff *out_skb;
u32 nlmsg_seq;
u16 nlmsg_flags;
};
static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
{
struct xfrm_user_sec_ctx *uctx;
struct nlattr *attr;
int ctx_size = sizeof(*uctx) + s->ctx_len;
attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
if (attr == NULL)
return -EMSGSIZE;
uctx = nla_data(attr);
uctx->exttype = XFRMA_SEC_CTX;
uctx->len = ctx_size;
uctx->ctx_doi = s->ctx_doi;
uctx->ctx_alg = s->ctx_alg;
uctx->ctx_len = s->ctx_len;
memcpy(uctx + 1, s->ctx_str, s->ctx_len);
return 0;
}
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
/* Don't change this without updating xfrm_sa_len! */
static int copy_to_user_state_extra(struct xfrm_state *x,
struct xfrm_usersa_info *p,
struct sk_buff *skb)
{
int ret = 0;
copy_to_user_state(x, p);
if (x->coaddr) {
ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
if (ret)
goto out;
}
if (x->lastused) {
ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused);
if (ret)
goto out;
}
if (x->aead) {
ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
if (ret)
goto out;
}
if (x->aalg) {
ret = copy_to_user_auth(x->aalg, skb);
if (!ret)
ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC,
xfrm_alg_auth_len(x->aalg), x->aalg);
if (ret)
goto out;
}
if (x->ealg) {
ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
if (ret)
goto out;
}
if (x->calg) {
ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
if (ret)
goto out;
}
if (x->encap) {
ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
if (ret)
goto out;
}
if (x->tfcpad) {
ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
if (ret)
goto out;
}
ret = xfrm_mark_put(skb, &x->mark);
if (ret)
goto out;
if (x->replay_esn) {
ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
if (ret)
goto out;
}
if (x->security)
ret = copy_sec_ctx(x->security, skb);
out:
return ret;
}
static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct xfrm_usersa_info *p;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
err = copy_to_user_state_extra(x, p, skb);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_sa_done(struct netlink_callback *cb)
{
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
xfrm_state_walk_done(walk);
return 0;
}
static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_state_walk_init(walk, 0);
}
(void) xfrm_state_walk(net, walk, dump_one_state, &info);
return skb->len;
}
static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static inline size_t xfrm_spdinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_spdinfo))
+ nla_total_size(sizeof(struct xfrmu_spdhinfo));
}
static int build_spdinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_spdinfo si;
struct xfrmu_spdinfo spc;
struct xfrmu_spdhinfo sph;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_spd_getinfo(net, &si);
spc.incnt = si.incnt;
spc.outcnt = si.outcnt;
spc.fwdcnt = si.fwdcnt;
spc.inscnt = si.inscnt;
spc.outscnt = si.outscnt;
spc.fwdscnt = si.fwdscnt;
sph.spdhcnt = si.spdhcnt;
sph.spdhmcnt = si.spdhmcnt;
err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
if (!err)
err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static inline size_t xfrm_sadinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_sadhinfo))
+ nla_total_size(4); /* XFRMA_SAD_CNT */
}
static int build_sadinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_sadinfo si;
struct xfrmu_sadhinfo sh;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_sad_getinfo(net, &si);
sh.sadhmcnt = si.sadhmcnt;
sh.sadhcnt = si.sadhcnt;
err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
if (!err)
err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_id *p = nlmsg_data(nlh);
struct xfrm_state *x;
struct sk_buff *resp_skb;
int err = -ESRCH;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
goto out_noput;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
}
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_userspi_info(struct xfrm_userspi_info *p)
{
switch (p->info.id.proto) {
case IPPROTO_AH:
case IPPROTO_ESP:
break;
case IPPROTO_COMP:
/* IPCOMP spi is 16-bits. */
if (p->max >= 0x10000)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (p->min > p->max)
return -EINVAL;
return 0;
}
static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct xfrm_userspi_info *p;
struct sk_buff *resp_skb;
xfrm_address_t *daddr;
int family;
int err;
u32 mark;
struct xfrm_mark m;
p = nlmsg_data(nlh);
err = verify_userspi_info(p);
if (err)
goto out_noput;
family = p->info.family;
daddr = &p->info.id.daddr;
x = NULL;
mark = xfrm_mark_get(attrs, &m);
if (p->info.seq) {
x = xfrm_find_acq_byseq(net, mark, p->info.seq);
if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
p->info.id.proto, daddr,
&p->info.saddr, 1,
family);
err = -ENOENT;
if (x == NULL)
goto out_noput;
err = xfrm_alloc_spi(x, p->min, p->max);
if (err)
goto out;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
goto out;
}
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
out:
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_policy_dir(u8 dir)
{
switch (dir) {
case XFRM_POLICY_IN:
case XFRM_POLICY_OUT:
case XFRM_POLICY_FWD:
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_policy_type(u8 type)
{
switch (type) {
case XFRM_POLICY_TYPE_MAIN:
#ifdef CONFIG_XFRM_SUB_POLICY
case XFRM_POLICY_TYPE_SUB:
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
{
switch (p->share) {
case XFRM_SHARE_ANY:
case XFRM_SHARE_SESSION:
case XFRM_SHARE_USER:
case XFRM_SHARE_UNIQUE:
break;
default:
return -EINVAL;
}
switch (p->action) {
case XFRM_POLICY_ALLOW:
case XFRM_POLICY_BLOCK:
break;
default:
return -EINVAL;
}
switch (p->sel.family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
return -EAFNOSUPPORT;
#endif
default:
return -EINVAL;
}
return verify_policy_dir(p->dir);
}
static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
return security_xfrm_policy_alloc(&pol->security, uctx);
}
static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
int nr)
{
int i;
xp->xfrm_nr = nr;
for (i = 0; i < nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
memcpy(&t->saddr, &ut->saddr,
sizeof(xfrm_address_t));
t->reqid = ut->reqid;
t->mode = ut->mode;
t->share = ut->share;
t->optional = ut->optional;
t->aalgos = ut->aalgos;
t->ealgos = ut->ealgos;
t->calgos = ut->calgos;
/* If all masks are ~0, then we allow all algorithms. */
t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
t->encap_family = ut->family;
}
}
static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
{
int i;
if (nr > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < nr; i++) {
/* We never validated the ut->family value, so many
* applications simply leave it at zero. The check was
* never made and ut->family was ignored because all
* templates could be assumed to have the same family as
* the policy itself. Now that we will have ipv4-in-ipv6
* and ipv6-in-ipv4 tunnels, this is no longer true.
*/
if (!ut[i].family)
ut[i].family = family;
switch (ut[i].family) {
case AF_INET:
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
break;
#endif
default:
return -EINVAL;
}
}
return 0;
}
static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_TMPL];
if (!rt) {
pol->xfrm_nr = 0;
} else {
struct xfrm_user_tmpl *utmpl = nla_data(rt);
int nr = nla_len(rt) / sizeof(*utmpl);
int err;
err = validate_tmpl(nr, utmpl, pol->family);
if (err)
return err;
copy_templates(pol, utmpl, nr);
}
return 0;
}
static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
struct xfrm_userpolicy_type *upt;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
if (rt) {
upt = nla_data(rt);
type = upt->type;
}
err = verify_policy_type(type);
if (err)
return err;
*tp = type;
return 0;
}
static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
{
xp->priority = p->priority;
xp->index = p->index;
memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
xp->action = p->action;
xp->flags = p->flags;
xp->family = p->sel.family;
/* XXX xp->share = p->share; */
}
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
{
struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
int err;
if (!xp) {
*errp = -ENOMEM;
return NULL;
}
copy_from_user_policy(xp, p);
err = copy_from_user_policy_type(&xp->type, attrs);
if (err)
goto error;
if (!(err = copy_from_user_tmpl(xp, attrs)))
err = copy_from_user_sec_ctx(xp, attrs);
if (err)
goto error;
xfrm_mark_get(attrs, &xp->mark);
return xp;
error:
*errp = err;
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
struct xfrm_policy *xp;
struct km_event c;
int err;
int excl;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newpolicy_info(p);
if (err)
return err;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
xp = xfrm_policy_construct(net, p, attrs, &err);
if (!xp)
return err;
/* shouldn't excl be based on nlh flags??
* Aha! this is anti-netlink really i.e more pfkey derived
* in netlink excl is a flag and you wouldnt need
* a type XFRM_MSG_UPDPOLICY - JHS */
excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
err = xfrm_policy_insert(p->dir, xp, excl);
security_task_getsecid(current, &sid);
xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid);
if (err) {
security_xfrm_policy_free(xp->security);
kfree(xp);
return err;
}
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
xfrm_pol_put(xp);
return 0;
}
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
{
struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
int i;
if (xp->xfrm_nr == 0)
return 0;
for (i = 0; i < xp->xfrm_nr; i++) {
struct xfrm_user_tmpl *up = &vec[i];
struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
memcpy(&up->id, &kp->id, sizeof(up->id));
up->family = kp->encap_family;
memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
up->reqid = kp->reqid;
up->mode = kp->mode;
up->share = kp->share;
up->optional = kp->optional;
up->aalgos = kp->aalgos;
up->ealgos = kp->ealgos;
up->calgos = kp->calgos;
}
return nla_put(skb, XFRMA_TMPL,
sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
}
static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
{
if (x->security) {
return copy_sec_ctx(x->security, skb);
}
return 0;
}
static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
{
if (xp->security)
return copy_sec_ctx(xp->security, skb);
return 0;
}
static inline size_t userpolicy_type_attrsize(void)
{
#ifdef CONFIG_XFRM_SUB_POLICY
return nla_total_size(sizeof(struct xfrm_userpolicy_type));
#else
return 0;
#endif
}
#ifdef CONFIG_XFRM_SUB_POLICY
static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
struct xfrm_userpolicy_type upt = {
.type = type,
};
return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
}
#else
static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
return 0;
}
#endif
static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct xfrm_userpolicy_info *p;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_policy_done(struct netlink_callback *cb)
{
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
xfrm_policy_walk_done(walk);
return 0;
}
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
struct xfrm_policy *xp,
int dir, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_policy(xp, dir, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_userpolicy_id *p;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct km_event c;
int delete;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
p = nlmsg_data(nlh);
delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel,
ctx, delete, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (!delete) {
struct sk_buff *resp_skb;
resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
NETLINK_CB(skb).pid);
}
} else {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid,
sid);
if (err != 0)
goto out;
c.data.byid = p->index;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
}
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
struct xfrm_usersa_flush *p = nlmsg_data(nlh);
struct xfrm_audit audit_info;
int err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_state_flush(net, p->proto, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.proto = p->proto;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x)
{
size_t replay_size = x->replay_esn ?
xfrm_replay_state_esn_len(x->replay_esn) :
sizeof(struct xfrm_replay_state);
return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
+ nla_total_size(replay_size)
+ nla_total_size(sizeof(struct xfrm_lifetime_cur))
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(4) /* XFRM_AE_RTHR */
+ nla_total_size(4); /* XFRM_AE_ETHR */
}
static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_aevent_id *id;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
if (nlh == NULL)
return -EMSGSIZE;
id = nlmsg_data(nlh);
memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr));
id->sa_id.spi = x->id.spi;
id->sa_id.family = x->props.family;
id->sa_id.proto = x->id.proto;
memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr));
id->reqid = x->props.reqid;
id->flags = c->data.aevent;
if (x->replay_esn) {
err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
} else {
err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
&x->replay);
}
if (err)
goto out_cancel;
err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft);
if (err)
goto out_cancel;
if (id->flags & XFRM_AE_RTHR) {
err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
if (err)
goto out_cancel;
}
if (id->flags & XFRM_AE_ETHR) {
err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
x->replay_maxage * 10 / HZ);
if (err)
goto out_cancel;
}
err = xfrm_mark_put(skb, &x->mark);
if (err)
goto out_cancel;
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct sk_buff *r_skb;
int err;
struct km_event c;
u32 mark;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct xfrm_usersa_id *id = &p->sa_id;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
if (x == NULL)
return -ESRCH;
r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (r_skb == NULL) {
xfrm_state_put(x);
return -ENOMEM;
}
/*
* XXX: is this lock really needed - none of the other
* gets lock (the concern is things getting updated
* while we are still reading) - jhs
*/
spin_lock_bh(&x->lock);
c.data.aevent = p->flags;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
if (build_aevent(r_skb, x, &c) < 0)
BUG();
err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid);
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct km_event c;
int err = - EINVAL;
u32 mark = 0;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
if (!lt && !rp && !re)
return err;
/* pedantic mode - thou shalt sayeth replaceth */
if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
return err;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
if (x == NULL)
return -ESRCH;
if (x->km.state != XFRM_STATE_VALID)
goto out;
err = xfrm_replay_verify_len(x->replay_esn, rp);
if (err)
goto out;
spin_lock_bh(&x->lock);
xfrm_update_ae_params(x, attrs);
spin_unlock_bh(&x->lock);
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.data.aevent = XFRM_AE_CU;
km_state_notify(x, &c);
err = 0;
out:
xfrm_state_put(x);
return err;
}
static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct xfrm_audit audit_info;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_policy_flush(net, type, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.type = type;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_polexpire *up = nlmsg_data(nlh);
struct xfrm_userpolicy_info *p = &up->pol;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err = -ENOENT;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir,
&p->sel, ctx, 0, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (unlikely(xp->walk.dead))
goto out;
err = 0;
if (up->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_policy_delete(xp, p->dir);
xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid);
} else {
// reset the timers here?
WARN(1, "Dont know what to do with soft policy expire\n");
}
km_policy_expired(xp, p->dir, up->hard, current->pid);
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err;
struct xfrm_user_expire *ue = nlmsg_data(nlh);
struct xfrm_usersa_info *p = &ue->state;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
err = -ENOENT;
if (x == NULL)
return err;
spin_lock_bh(&x->lock);
err = -EINVAL;
if (x->km.state != XFRM_STATE_VALID)
goto out;
km_state_expired(x, ue->hard, current->pid);
if (ue->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
__xfrm_state_delete(x);
xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid);
}
err = 0;
out:
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_tmpl *ut;
int i;
struct nlattr *rt = attrs[XFRMA_TMPL];
struct xfrm_mark mark;
struct xfrm_user_acquire *ua = nlmsg_data(nlh);
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto nomem;
xfrm_mark_get(attrs, &mark);
err = verify_newpolicy_info(&ua->policy);
if (err)
goto bad_policy;
/* build an XP */
xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
if (!xp)
goto free_state;
memcpy(&x->id, &ua->id, sizeof(ua->id));
memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
xp->mark.m = x->mark.m = mark.m;
xp->mark.v = x->mark.v = mark.v;
ut = nla_data(rt);
/* extract the templates and for each call km_key */
for (i = 0; i < xp->xfrm_nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&x->id, &t->id, sizeof(x->id));
x->props.mode = t->mode;
x->props.reqid = t->reqid;
x->props.family = ut->family;
t->aalgos = ua->aalgos;
t->ealgos = ua->ealgos;
t->calgos = ua->calgos;
err = km_query(x, t, xp);
}
kfree(x);
kfree(xp);
return 0;
bad_policy:
WARN(1, "BAD policy passed\n");
free_state:
kfree(x);
nomem:
return err;
}
#ifdef CONFIG_XFRM_MIGRATE
static int copy_from_user_migrate(struct xfrm_migrate *ma,
struct xfrm_kmaddress *k,
struct nlattr **attrs, int *num)
{
struct nlattr *rt = attrs[XFRMA_MIGRATE];
struct xfrm_user_migrate *um;
int i, num_migrate;
if (k != NULL) {
struct xfrm_user_kmaddress *uk;
uk = nla_data(attrs[XFRMA_KMADDRESS]);
memcpy(&k->local, &uk->local, sizeof(k->local));
memcpy(&k->remote, &uk->remote, sizeof(k->remote));
k->family = uk->family;
k->reserved = uk->reserved;
}
um = nla_data(rt);
num_migrate = nla_len(rt) / sizeof(*um);
if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++, um++, ma++) {
memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
ma->proto = um->proto;
ma->mode = um->mode;
ma->reqid = um->reqid;
ma->old_family = um->old_family;
ma->new_family = um->new_family;
}
*num = i;
return 0;
}
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress km, *kmp;
u8 type;
int err;
int n = 0;
if (attrs[XFRMA_MIGRATE] == NULL)
return -EINVAL;
kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
if (err)
return err;
if (!n)
return 0;
xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp);
return 0;
}
#else
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
return -ENOPROTOOPT;
}
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
{
struct xfrm_user_migrate um;
memset(&um, 0, sizeof(um));
um.proto = m->proto;
um.mode = m->mode;
um.reqid = m->reqid;
um.old_family = m->old_family;
memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
um.new_family = m->new_family;
memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
}
static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
{
struct xfrm_user_kmaddress uk;
memset(&uk, 0, sizeof(uk));
uk.family = k->family;
uk.reserved = k->reserved;
memcpy(&uk.local, &k->local, sizeof(uk.local));
memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
}
static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma)
{
return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
+ (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
+ nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
+ userpolicy_type_attrsize();
}
static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
int num_migrate, const struct xfrm_kmaddress *k,
const struct xfrm_selector *sel, u8 dir, u8 type)
{
const struct xfrm_migrate *mp;
struct xfrm_userpolicy_id *pol_id;
struct nlmsghdr *nlh;
int i, err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
if (nlh == NULL)
return -EMSGSIZE;
pol_id = nlmsg_data(nlh);
/* copy data from selector, dir, and type to the pol_id */
memset(pol_id, 0, sizeof(*pol_id));
memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
pol_id->dir = dir;
if (k != NULL) {
err = copy_to_user_kmaddress(k, skb);
if (err)
goto out_cancel;
}
err = copy_to_user_policy_type(type, skb);
if (err)
goto out_cancel;
for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
err = copy_to_user_migrate(mp, skb);
if (err)
goto out_cancel;
}
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
struct net *net = &init_net;
struct sk_buff *skb;
skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
/* build migrate */
if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC);
}
#else
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
#define XMSGSIZE(type) sizeof(struct type)
static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32),
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32),
};
#undef XMSGSIZE
static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
[XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)},
[XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)},
[XFRMA_LASTUSED] = { .type = NLA_U64},
[XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)},
[XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) },
[XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) },
[XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) },
[XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) },
[XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) },
[XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) },
[XFRMA_REPLAY_THRESH] = { .type = NLA_U32 },
[XFRMA_ETIMER_THRESH] = { .type = NLA_U32 },
[XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)},
[XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) },
[XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) },
[XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) },
[XFRMA_TFCPAD] = { .type = NLA_U32 },
[XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) },
};
static struct xfrm_link {
int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
int (*dump)(struct sk_buff *, struct netlink_callback *);
int (*done)(struct netlink_callback *);
} xfrm_dispatch[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa },
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
.dump = xfrm_dump_sa,
.done = xfrm_dump_sa_done },
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy },
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
.dump = xfrm_dump_policy,
.done = xfrm_dump_policy_done },
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire },
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa },
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy },
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae },
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae },
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate },
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo },
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo },
};
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
struct xfrm_link *link;
int type, err;
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,
xfrma_policy);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
static void xfrm_netlink_rcv(struct sk_buff *skb)
{
mutex_lock(&xfrm_cfg_mutex);
netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
mutex_unlock(&xfrm_cfg_mutex);
}
static inline size_t xfrm_expire_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
+ nla_total_size(sizeof(struct xfrm_mark));
}
static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
err = xfrm_mark_put(skb, &x->mark);
if (err)
return err;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_expire(skb, x, c) < 0) {
kfree_skb(skb);
return -EMSGSIZE;
}
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
static int xfrm_notify_sa_flush(const struct km_event *c)
{
struct net *net = c->net;
struct xfrm_usersa_flush *p;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
if (nlh == NULL) {
kfree_skb(skb);
return -EMSGSIZE;
}
p = nlmsg_data(nlh);
p->proto = c->data.proto;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
}
static inline size_t xfrm_sa_len(struct xfrm_state *x)
{
size_t l = 0;
if (x->aead)
l += nla_total_size(aead_len(x->aead));
if (x->aalg) {
l += nla_total_size(sizeof(struct xfrm_algo) +
(x->aalg->alg_key_len + 7) / 8);
l += nla_total_size(xfrm_alg_auth_len(x->aalg));
}
if (x->ealg)
l += nla_total_size(xfrm_alg_len(x->ealg));
if (x->calg)
l += nla_total_size(sizeof(*x->calg));
if (x->encap)
l += nla_total_size(sizeof(*x->encap));
if (x->tfcpad)
l += nla_total_size(sizeof(x->tfcpad));
if (x->replay_esn)
l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
if (x->security)
l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
x->security->ctx_len);
if (x->coaddr)
l += nla_total_size(sizeof(*x->coaddr));
/* Must count x->lastused as it may become non-zero behind our back. */
l += nla_total_size(sizeof(u64));
return l;
}
static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct xfrm_usersa_info *p;
struct xfrm_usersa_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = xfrm_sa_len(x);
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELSA) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
len += nla_total_size(sizeof(struct xfrm_mark));
}
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELSA) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
id->spi = x->id.spi;
id->family = x->props.family;
id->proto = x->id.proto;
attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
err = copy_to_user_state_extra(x, p, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_EXPIRE:
return xfrm_exp_state_notify(x, c);
case XFRM_MSG_NEWAE:
return xfrm_aevent_state_notify(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_UPDSA:
case XFRM_MSG_NEWSA:
return xfrm_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return xfrm_notify_sa_flush(c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
c->event);
break;
}
return 0;
}
static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x,
struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(xfrm_user_sec_ctx_size(x->security))
+ userpolicy_type_attrsize();
}
static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
struct xfrm_tmpl *xt, struct xfrm_policy *xp,
int dir)
{
__u32 seq = xfrm_get_acqseq();
struct xfrm_user_acquire *ua;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
if (nlh == NULL)
return -EMSGSIZE;
ua = nlmsg_data(nlh);
memcpy(&ua->id, &x->id, sizeof(ua->id));
memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
copy_to_user_policy(xp, &ua->policy, dir);
ua->aalgos = xt->aalgos;
ua->ealgos = xt->ealgos;
ua->calgos = xt->calgos;
ua->seq = x->km.seq = seq;
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_state_sec_ctx(x, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
struct xfrm_policy *xp, int dir)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_acquire(skb, x, xt, xp, dir) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC);
}
/* User gives us xfrm_user_policy_info followed by an array of 0
* or more templates.
*/
static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
struct xfrm_policy *xp;
int nr;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
if (opt != IPV6_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(*p) ||
verify_newpolicy_info(p))
return NULL;
nr = ((len - sizeof(*p)) / sizeof(*ut));
if (validate_tmpl(nr, ut, p->sel.family))
return NULL;
if (p->dir > XFRM_POLICY_OUT)
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
copy_from_user_policy(xp, p);
xp->type = XFRM_POLICY_TYPE_MAIN;
copy_templates(xp, ut, nr);
*dir = p->dir;
return xp;
}
static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(xfrm_user_sec_ctx_size(xp->security))
+ nla_total_size(sizeof(struct xfrm_mark))
+ userpolicy_type_attrsize();
}
static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
int dir, const struct km_event *c)
{
struct xfrm_user_polexpire *upe;
int hard = c->data.hard;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
if (nlh == NULL)
return -EMSGSIZE;
upe = nlmsg_data(nlh);
copy_to_user_policy(xp, &upe->pol, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
upe->hard = !!hard;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_polexpire(skb, xp, dir, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
struct net *net = xp_net(xp);
struct xfrm_userpolicy_info *p;
struct xfrm_userpolicy_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELPOLICY) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
}
len += userpolicy_type_attrsize();
len += nla_total_size(sizeof(struct xfrm_mark));
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELPOLICY) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memset(id, 0, sizeof(*id));
id->dir = dir;
if (c->data.byid)
id->index = xp->index;
else
memcpy(&id->sel, &xp->selector, sizeof(id->sel));
attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_notify_policy_flush(const struct km_event *c)
{
struct net *net = c->net;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int err;
skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
err = copy_to_user_policy_type(c->data.type, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
case XFRM_MSG_DELPOLICY:
return xfrm_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
return xfrm_notify_policy_flush(c);
case XFRM_MSG_POLEXPIRE:
return xfrm_exp_policy_notify(xp, dir, c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
c->event);
}
return 0;
}
static inline size_t xfrm_report_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
}
static int build_report(struct sk_buff *skb, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct xfrm_user_report *ur;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
if (nlh == NULL)
return -EMSGSIZE;
ur = nlmsg_data(nlh);
ur->proto = proto;
memcpy(&ur->sel, sel, sizeof(ur->sel));
if (addr) {
int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_report(struct net *net, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct sk_buff *skb;
skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_report(skb, proto, sel, addr) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC);
}
static inline size_t xfrm_mapping_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
}
static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
xfrm_address_t *new_saddr, __be16 new_sport)
{
struct xfrm_user_mapping *um;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
if (nlh == NULL)
return -EMSGSIZE;
um = nlmsg_data(nlh);
memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
um->id.spi = x->id.spi;
um->id.family = x->props.family;
um->id.proto = x->id.proto;
memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
um->new_sport = new_sport;
um->old_sport = x->encap->encap_sport;
um->reqid = x->props.reqid;
return nlmsg_end(skb, nlh);
}
static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
__be16 sport)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
if (x->id.proto != IPPROTO_ESP)
return -EINVAL;
if (!x->encap)
return -EINVAL;
skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_mapping(skb, x, ipaddr, sport) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC);
}
static struct xfrm_mgr netlink_mgr = {
.id = "netlink",
.notify = xfrm_send_state_notify,
.acquire = xfrm_send_acquire,
.compile_policy = xfrm_compile_policy,
.notify_policy = xfrm_send_policy_notify,
.report = xfrm_send_report,
.migrate = xfrm_send_migrate,
.new_mapping = xfrm_send_mapping,
};
static int __net_init xfrm_user_net_init(struct net *net)
{
struct sock *nlsk;
struct netlink_kernel_cfg cfg = {
.groups = XFRMNLGRP_MAX,
.input = xfrm_netlink_rcv,
};
nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg);
if (nlsk == NULL)
return -ENOMEM;
net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
rcu_assign_pointer(net->xfrm.nlsk, nlsk);
return 0;
}
static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->xfrm.nlsk_stash);
}
static struct pernet_operations xfrm_user_net_ops = {
.init = xfrm_user_net_init,
.exit_batch = xfrm_user_net_exit,
};
static int __init xfrm_user_init(void)
{
int rv;
printk(KERN_INFO "Initializing XFRM netlink socket\n");
rv = register_pernet_subsys(&xfrm_user_net_ops);
if (rv < 0)
return rv;
rv = xfrm_register_km(&netlink_mgr);
if (rv < 0)
unregister_pernet_subsys(&xfrm_user_net_ops);
return rv;
}
static void __exit xfrm_user_exit(void)
{
xfrm_unregister_km(&netlink_mgr);
unregister_pernet_subsys(&xfrm_user_net_ops);
}
module_init(xfrm_user_init);
module_exit(xfrm_user_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3825_0 |
crossvul-cpp_data_good_1829_4 | /***********************************************************************/
/* */
/* OCaml */
/* */
/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
/* */
/* Copyright 1996 Institut National de Recherche en Informatique et */
/* en Automatique. All rights reserved. This file is distributed */
/* under the terms of the GNU Library General Public License, with */
/* the special exception on linking described in file ../LICENSE. */
/* */
/***********************************************************************/
/* Operations on strings */
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "caml/alloc.h"
#include "caml/fail.h"
#include "caml/mlvalues.h"
#include "caml/misc.h"
/* returns a number of bytes (chars) */
CAMLexport mlsize_t caml_string_length(value s)
{
mlsize_t temp;
temp = Bosize_val(s) - 1;
Assert (Byte (s, temp - Byte (s, temp)) == 0);
return temp - Byte (s, temp);
}
/* returns a value that represents a number of bytes (chars) */
CAMLprim value caml_ml_string_length(value s)
{
mlsize_t temp;
temp = Bosize_val(s) - 1;
Assert (Byte (s, temp - Byte (s, temp)) == 0);
return Val_long(temp - Byte (s, temp));
}
/* [len] is a value that represents a number of bytes (chars) */
CAMLprim value caml_create_string(value len)
{
mlsize_t size = Long_val(len);
if (size > Bsize_wsize (Max_wosize) - 1){
caml_invalid_argument("String.create");
}
return caml_alloc_string(size);
}
CAMLprim value caml_string_get(value str, value index)
{
intnat idx = Long_val(index);
if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error();
return Val_int(Byte_u(str, idx));
}
CAMLprim value caml_string_set(value str, value index, value newval)
{
intnat idx = Long_val(index);
if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error();
Byte_u(str, idx) = Int_val(newval);
return Val_unit;
}
CAMLprim value caml_string_get16(value str, value index)
{
intnat res;
unsigned char b1, b2;
intnat idx = Long_val(index);
if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error();
b1 = Byte_u(str, idx);
b2 = Byte_u(str, idx + 1);
#ifdef ARCH_BIG_ENDIAN
res = b1 << 8 | b2;
#else
res = b2 << 8 | b1;
#endif
return Val_int(res);
}
CAMLprim value caml_string_get32(value str, value index)
{
intnat res;
unsigned char b1, b2, b3, b4;
intnat idx = Long_val(index);
if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error();
b1 = Byte_u(str, idx);
b2 = Byte_u(str, idx + 1);
b3 = Byte_u(str, idx + 2);
b4 = Byte_u(str, idx + 3);
#ifdef ARCH_BIG_ENDIAN
res = b1 << 24 | b2 << 16 | b3 << 8 | b4;
#else
res = b4 << 24 | b3 << 16 | b2 << 8 | b1;
#endif
return caml_copy_int32(res);
}
CAMLprim value caml_string_get64(value str, value index)
{
uint64_t res;
unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
intnat idx = Long_val(index);
if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error();
b1 = Byte_u(str, idx);
b2 = Byte_u(str, idx + 1);
b3 = Byte_u(str, idx + 2);
b4 = Byte_u(str, idx + 3);
b5 = Byte_u(str, idx + 4);
b6 = Byte_u(str, idx + 5);
b7 = Byte_u(str, idx + 6);
b8 = Byte_u(str, idx + 7);
#ifdef ARCH_BIG_ENDIAN
res = (uint64_t) b1 << 56 | (uint64_t) b2 << 48
| (uint64_t) b3 << 40 | (uint64_t) b4 << 32
| (uint64_t) b5 << 24 | (uint64_t) b6 << 16
| (uint64_t) b7 << 8 | (uint64_t) b8;
#else
res = (uint64_t) b8 << 56 | (uint64_t) b7 << 48
| (uint64_t) b6 << 40 | (uint64_t) b5 << 32
| (uint64_t) b4 << 24 | (uint64_t) b3 << 16
| (uint64_t) b2 << 8 | (uint64_t) b1;
#endif
return caml_copy_int64(res);
}
CAMLprim value caml_string_set16(value str, value index, value newval)
{
unsigned char b1, b2;
intnat val;
intnat idx = Long_val(index);
if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error();
val = Long_val(newval);
#ifdef ARCH_BIG_ENDIAN
b1 = 0xFF & val >> 8;
b2 = 0xFF & val;
#else
b2 = 0xFF & val >> 8;
b1 = 0xFF & val;
#endif
Byte_u(str, idx) = b1;
Byte_u(str, idx + 1) = b2;
return Val_unit;
}
CAMLprim value caml_string_set32(value str, value index, value newval)
{
unsigned char b1, b2, b3, b4;
intnat val;
intnat idx = Long_val(index);
if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error();
val = Int32_val(newval);
#ifdef ARCH_BIG_ENDIAN
b1 = 0xFF & val >> 24;
b2 = 0xFF & val >> 16;
b3 = 0xFF & val >> 8;
b4 = 0xFF & val;
#else
b4 = 0xFF & val >> 24;
b3 = 0xFF & val >> 16;
b2 = 0xFF & val >> 8;
b1 = 0xFF & val;
#endif
Byte_u(str, idx) = b1;
Byte_u(str, idx + 1) = b2;
Byte_u(str, idx + 2) = b3;
Byte_u(str, idx + 3) = b4;
return Val_unit;
}
CAMLprim value caml_string_set64(value str, value index, value newval)
{
unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
int64_t val;
intnat idx = Long_val(index);
if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error();
val = Int64_val(newval);
#ifdef ARCH_BIG_ENDIAN
b1 = 0xFF & val >> 56;
b2 = 0xFF & val >> 48;
b3 = 0xFF & val >> 40;
b4 = 0xFF & val >> 32;
b5 = 0xFF & val >> 24;
b6 = 0xFF & val >> 16;
b7 = 0xFF & val >> 8;
b8 = 0xFF & val;
#else
b8 = 0xFF & val >> 56;
b7 = 0xFF & val >> 48;
b6 = 0xFF & val >> 40;
b5 = 0xFF & val >> 32;
b4 = 0xFF & val >> 24;
b3 = 0xFF & val >> 16;
b2 = 0xFF & val >> 8;
b1 = 0xFF & val;
#endif
Byte_u(str, idx) = b1;
Byte_u(str, idx + 1) = b2;
Byte_u(str, idx + 2) = b3;
Byte_u(str, idx + 3) = b4;
Byte_u(str, idx + 4) = b5;
Byte_u(str, idx + 5) = b6;
Byte_u(str, idx + 6) = b7;
Byte_u(str, idx + 7) = b8;
return Val_unit;
}
CAMLprim value caml_string_equal(value s1, value s2)
{
mlsize_t sz1, sz2;
value * p1, * p2;
if (s1 == s2) return Val_true;
sz1 = Wosize_val(s1);
sz2 = Wosize_val(s2);
if (sz1 != sz2) return Val_false;
for(p1 = Op_val(s1), p2 = Op_val(s2); sz1 > 0; sz1--, p1++, p2++)
if (*p1 != *p2) return Val_false;
return Val_true;
}
CAMLprim value caml_string_notequal(value s1, value s2)
{
return Val_not(caml_string_equal(s1, s2));
}
CAMLprim value caml_string_compare(value s1, value s2)
{
mlsize_t len1, len2;
int res;
if (s1 == s2) return Val_int(0);
len1 = caml_string_length(s1);
len2 = caml_string_length(s2);
res = memcmp(String_val(s1), String_val(s2), len1 <= len2 ? len1 : len2);
if (res < 0) return Val_int(-1);
if (res > 0) return Val_int(1);
if (len1 < len2) return Val_int(-1);
if (len1 > len2) return Val_int(1);
return Val_int(0);
}
CAMLprim value caml_string_lessthan(value s1, value s2)
{
return caml_string_compare(s1, s2) < Val_int(0) ? Val_true : Val_false;
}
CAMLprim value caml_string_lessequal(value s1, value s2)
{
return caml_string_compare(s1, s2) <= Val_int(0) ? Val_true : Val_false;
}
CAMLprim value caml_string_greaterthan(value s1, value s2)
{
return caml_string_compare(s1, s2) > Val_int(0) ? Val_true : Val_false;
}
CAMLprim value caml_string_greaterequal(value s1, value s2)
{
return caml_string_compare(s1, s2) >= Val_int(0) ? Val_true : Val_false;
}
CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,
value n)
{
memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Long_val(n));
return Val_unit;
}
CAMLprim value caml_fill_string(value s, value offset, value len, value init)
{
memset(&Byte(s, Long_val(offset)), Int_val(init), Long_val(len));
return Val_unit;
}
CAMLprim value caml_bitvect_test(value bv, value n)
{
intnat pos = Long_val(n);
return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));
}
CAMLexport value caml_alloc_sprintf(const char * format, ...)
{
va_list args;
char buf[64];
int n;
value res;
#ifndef _WIN32
/* C99-compliant implementation */
va_start(args, format);
/* "vsnprintf(dest, sz, format, args)" writes at most "sz" characters
into "dest", including the terminating '\0'.
It returns the number of characters of the formatted string,
excluding the terminating '\0'. */
n = vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
/* Allocate a Caml string with length "n" as computed by vsnprintf. */
res = caml_alloc_string(n);
if (n < sizeof(buf)) {
/* All output characters were written to buf, including the
terminating '\0'. Just copy them to the result. */
memcpy(String_val(res), buf, n);
} else {
/* Re-do the formatting, outputting directly in the Caml string.
Note that caml_alloc_string left room for a '\0' at position n,
so the size passed to vsnprintf is n+1. */
va_start(args, format);
vsnprintf(String_val(res), n + 1, format, args);
va_end(args);
}
return res;
#else
/* Implementation specific to the Microsoft CRT library */
va_start(args, format);
/* "_vsnprintf(dest, sz, format, args)" writes at most "sz" characters
into "dest". Let "len" be the number of characters of the formatted
string.
If "len" < "sz", a null terminator was appended, and "len" is returned.
If "len" == "sz", no null termination, and "len" is returned.
If "len" > "sz", a negative value is returned. */
n = _vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
if (n >= 0 && n <= sizeof(buf)) {
/* All output characters were written to buf.
"n" is the actual length of the output.
Copy the characters to a Caml string of length n. */
res = caml_alloc_string(n);
memcpy(String_val(res), buf, n);
} else {
/* Determine actual length of output, excluding final '\0' */
va_start(args, format);
n = _vscprintf(format, args);
va_end(args);
res = caml_alloc_string(n);
/* Re-do the formatting, outputting directly in the Caml string.
Note that caml_alloc_string left room for a '\0' at position n,
so the size passed to _vsnprintf is n+1. */
va_start(args, format);
_vsnprintf(String_val(res), n + 1, format, args);
va_end(args);
}
return res;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1829_4 |
crossvul-cpp_data_bad_5695_0 | /*
* net/tipc/socket.c: TIPC socket API
*
* Copyright (c) 2001-2007, 2012 Ericsson AB
* Copyright (c) 2004-2008, 2010-2012, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* 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 "core.h"
#include "port.h"
#include <linux/export.h>
#include <net/sock.h>
#define SS_LISTENING -1 /* socket is listening */
#define SS_READY -2 /* socket is connectionless */
#define CONN_OVERLOAD_LIMIT ((TIPC_FLOW_CONTROL_WIN * 2 + 1) * \
SKB_TRUESIZE(TIPC_MAX_USER_MSG_SIZE))
#define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
struct tipc_sock {
struct sock sk;
struct tipc_port *p;
struct tipc_portid peer_name;
unsigned int conn_timeout;
};
#define tipc_sk(sk) ((struct tipc_sock *)(sk))
#define tipc_sk_port(sk) (tipc_sk(sk)->p)
#define tipc_rx_ready(sock) (!skb_queue_empty(&sock->sk->sk_receive_queue) || \
(sock->state == SS_DISCONNECTING))
static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
static void wakeupdispatch(struct tipc_port *tport);
static void tipc_data_ready(struct sock *sk, int len);
static void tipc_write_space(struct sock *sk);
static const struct proto_ops packet_ops;
static const struct proto_ops stream_ops;
static const struct proto_ops msg_ops;
static struct proto tipc_proto;
static int sockets_enabled;
/*
* Revised TIPC socket locking policy:
*
* Most socket operations take the standard socket lock when they start
* and hold it until they finish (or until they need to sleep). Acquiring
* this lock grants the owner exclusive access to the fields of the socket
* data structures, with the exception of the backlog queue. A few socket
* operations can be done without taking the socket lock because they only
* read socket information that never changes during the life of the socket.
*
* Socket operations may acquire the lock for the associated TIPC port if they
* need to perform an operation on the port. If any routine needs to acquire
* both the socket lock and the port lock it must take the socket lock first
* to avoid the risk of deadlock.
*
* The dispatcher handling incoming messages cannot grab the socket lock in
* the standard fashion, since invoked it runs at the BH level and cannot block.
* Instead, it checks to see if the socket lock is currently owned by someone,
* and either handles the message itself or adds it to the socket's backlog
* queue; in the latter case the queued message is processed once the process
* owning the socket lock releases it.
*
* NOTE: Releasing the socket lock while an operation is sleeping overcomes
* the problem of a blocked socket operation preventing any other operations
* from occurring. However, applications must be careful if they have
* multiple threads trying to send (or receive) on the same socket, as these
* operations might interfere with each other. For example, doing a connect
* and a receive at the same time might allow the receive to consume the
* ACK message meant for the connect. While additional work could be done
* to try and overcome this, it doesn't seem to be worthwhile at the present.
*
* NOTE: Releasing the socket lock while an operation is sleeping also ensures
* that another operation that must be performed in a non-blocking manner is
* not delayed for very long because the lock has already been taken.
*
* NOTE: This code assumes that certain fields of a port/socket pair are
* constant over its lifetime; such fields can be examined without taking
* the socket lock and/or port lock, and do not need to be re-read even
* after resuming processing after waiting. These fields include:
* - socket type
* - pointer to socket sk structure (aka tipc_sock structure)
* - pointer to port structure
* - port reference
*/
/**
* advance_rx_queue - discard first buffer in socket receive queue
*
* Caller must hold socket lock
*/
static void advance_rx_queue(struct sock *sk)
{
kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
}
/**
* reject_rx_queue - reject all buffers in socket receive queue
*
* Caller must hold socket lock
*/
static void reject_rx_queue(struct sock *sk)
{
struct sk_buff *buf;
while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
}
/**
* tipc_create - create a TIPC socket
* @net: network namespace (must be default network)
* @sock: pre-allocated socket structure
* @protocol: protocol indicator (must be 0)
* @kern: caused by kernel or by userspace?
*
* This routine creates additional data structures used by the TIPC socket,
* initializes them, and links them together.
*
* Returns 0 on success, errno otherwise
*/
static int tipc_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
const struct proto_ops *ops;
socket_state state;
struct sock *sk;
struct tipc_port *tp_ptr;
/* Validate arguments */
if (unlikely(protocol != 0))
return -EPROTONOSUPPORT;
switch (sock->type) {
case SOCK_STREAM:
ops = &stream_ops;
state = SS_UNCONNECTED;
break;
case SOCK_SEQPACKET:
ops = &packet_ops;
state = SS_UNCONNECTED;
break;
case SOCK_DGRAM:
case SOCK_RDM:
ops = &msg_ops;
state = SS_READY;
break;
default:
return -EPROTOTYPE;
}
/* Allocate socket's protocol area */
sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
if (sk == NULL)
return -ENOMEM;
/* Allocate TIPC port for socket to use */
tp_ptr = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
TIPC_LOW_IMPORTANCE);
if (unlikely(!tp_ptr)) {
sk_free(sk);
return -ENOMEM;
}
/* Finish initializing socket data structures */
sock->ops = ops;
sock->state = state;
sock_init_data(sock, sk);
sk->sk_backlog_rcv = backlog_rcv;
sk->sk_data_ready = tipc_data_ready;
sk->sk_write_space = tipc_write_space;
tipc_sk(sk)->p = tp_ptr;
tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
spin_unlock_bh(tp_ptr->lock);
if (sock->state == SS_READY) {
tipc_set_portunreturnable(tp_ptr->ref, 1);
if (sock->type == SOCK_DGRAM)
tipc_set_portunreliable(tp_ptr->ref, 1);
}
return 0;
}
/**
* release - destroy a TIPC socket
* @sock: socket to destroy
*
* This routine cleans up any messages that are still queued on the socket.
* For DGRAM and RDM socket types, all queued messages are rejected.
* For SEQPACKET and STREAM socket types, the first message is rejected
* and any others are discarded. (If the first message on a STREAM socket
* is partially-read, it is discarded and the next one is rejected instead.)
*
* NOTE: Rejected messages are not necessarily returned to the sender! They
* are returned or discarded according to the "destination droppable" setting
* specified for the message by the sender.
*
* Returns 0 on success, errno otherwise
*/
static int release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct tipc_port *tport;
struct sk_buff *buf;
int res;
/*
* Exit if socket isn't fully initialized (occurs when a failed accept()
* releases a pre-allocated child socket that was never used)
*/
if (sk == NULL)
return 0;
tport = tipc_sk_port(sk);
lock_sock(sk);
/*
* Reject all unreceived messages, except on an active connection
* (which disconnects locally & sends a 'FIN+' to peer)
*/
while (sock->state != SS_DISCONNECTING) {
buf = __skb_dequeue(&sk->sk_receive_queue);
if (buf == NULL)
break;
if (TIPC_SKB_CB(buf)->handle != 0)
kfree_skb(buf);
else {
if ((sock->state == SS_CONNECTING) ||
(sock->state == SS_CONNECTED)) {
sock->state = SS_DISCONNECTING;
tipc_disconnect(tport->ref);
}
tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
}
}
/*
* Delete TIPC port; this ensures no more messages are queued
* (also disconnects an active connection & sends a 'FIN-' to peer)
*/
res = tipc_deleteport(tport->ref);
/* Discard any remaining (connection-based) messages in receive queue */
__skb_queue_purge(&sk->sk_receive_queue);
/* Reject any messages that accumulated in backlog queue */
sock->state = SS_DISCONNECTING;
release_sock(sk);
sock_put(sk);
sock->sk = NULL;
return res;
}
/**
* bind - associate or disassocate TIPC name(s) with a socket
* @sock: socket structure
* @uaddr: socket address describing name(s) and desired operation
* @uaddr_len: size of socket address data structure
*
* Name and name sequence binding is indicated using a positive scope value;
* a negative scope value unbinds the specified name. Specifying no name
* (i.e. a socket address length of 0) unbinds all names from the socket.
*
* Returns 0 on success, errno otherwise
*
* NOTE: This routine doesn't need to take the socket lock since it doesn't
* access any non-constant socket information.
*/
static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
{
struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
u32 portref = tipc_sk_port(sock->sk)->ref;
if (unlikely(!uaddr_len))
return tipc_withdraw(portref, 0, NULL);
if (uaddr_len < sizeof(struct sockaddr_tipc))
return -EINVAL;
if (addr->family != AF_TIPC)
return -EAFNOSUPPORT;
if (addr->addrtype == TIPC_ADDR_NAME)
addr->addr.nameseq.upper = addr->addr.nameseq.lower;
else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
return -EAFNOSUPPORT;
if (addr->addr.nameseq.type < TIPC_RESERVED_TYPES)
return -EACCES;
return (addr->scope > 0) ?
tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
}
/**
* get_name - get port ID of socket or peer socket
* @sock: socket structure
* @uaddr: area for returned socket address
* @uaddr_len: area for returned length of socket address
* @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
*
* Returns 0 on success, errno otherwise
*
* NOTE: This routine doesn't need to take the socket lock since it only
* accesses socket information that is unchanging (or which changes in
* a completely predictable manner).
*/
static int get_name(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
struct tipc_sock *tsock = tipc_sk(sock->sk);
memset(addr, 0, sizeof(*addr));
if (peer) {
if ((sock->state != SS_CONNECTED) &&
((peer != 2) || (sock->state != SS_DISCONNECTING)))
return -ENOTCONN;
addr->addr.id.ref = tsock->peer_name.ref;
addr->addr.id.node = tsock->peer_name.node;
} else {
addr->addr.id.ref = tsock->p->ref;
addr->addr.id.node = tipc_own_addr;
}
*uaddr_len = sizeof(*addr);
addr->addrtype = TIPC_ADDR_ID;
addr->family = AF_TIPC;
addr->scope = 0;
addr->addr.name.domain = 0;
return 0;
}
/**
* poll - read and possibly block on pollmask
* @file: file structure associated with the socket
* @sock: socket for which to calculate the poll bits
* @wait: ???
*
* Returns pollmask value
*
* COMMENTARY:
* It appears that the usual socket locking mechanisms are not useful here
* since the pollmask info is potentially out-of-date the moment this routine
* exits. TCP and other protocols seem to rely on higher level poll routines
* to handle any preventable race conditions, so TIPC will do the same ...
*
* TIPC sets the returned events as follows:
*
* socket state flags set
* ------------ ---------
* unconnected no read flags
* POLLOUT if port is not congested
*
* connecting POLLIN/POLLRDNORM if ACK/NACK in rx queue
* no write flags
*
* connected POLLIN/POLLRDNORM if data in rx queue
* POLLOUT if port is not congested
*
* disconnecting POLLIN/POLLRDNORM/POLLHUP
* no write flags
*
* listening POLLIN if SYN in rx queue
* no write flags
*
* ready POLLIN/POLLRDNORM if data in rx queue
* [connectionless] POLLOUT (since port cannot be congested)
*
* IMPORTANT: The fact that a read or write operation is indicated does NOT
* imply that the operation will succeed, merely that it should be performed
* and will not block.
*/
static unsigned int poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
u32 mask = 0;
sock_poll_wait(file, sk_sleep(sk), wait);
switch ((int)sock->state) {
case SS_UNCONNECTED:
if (!tipc_sk_port(sk)->congested)
mask |= POLLOUT;
break;
case SS_READY:
case SS_CONNECTED:
if (!tipc_sk_port(sk)->congested)
mask |= POLLOUT;
/* fall thru' */
case SS_CONNECTING:
case SS_LISTENING:
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= (POLLIN | POLLRDNORM);
break;
case SS_DISCONNECTING:
mask = (POLLIN | POLLRDNORM | POLLHUP);
break;
}
return mask;
}
/**
* dest_name_check - verify user is permitted to send to specified port name
* @dest: destination address
* @m: descriptor for message to be sent
*
* Prevents restricted configuration commands from being issued by
* unauthorized users.
*
* Returns 0 if permission is granted, otherwise errno
*/
static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
{
struct tipc_cfg_msg_hdr hdr;
if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
return 0;
if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
return 0;
if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
return -EACCES;
if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
return -EMSGSIZE;
if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
return -EFAULT;
if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
return -EACCES;
return 0;
}
/**
* send_msg - send message in connectionless manner
* @iocb: if NULL, indicates that socket lock is already held
* @sock: socket structure
* @m: message to send
* @total_len: length of message
*
* Message must have an destination specified explicitly.
* Used for SOCK_RDM and SOCK_DGRAM messages,
* and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
* (Note: 'SYN+' is prohibited on SOCK_STREAM.)
*
* Returns the number of bytes sent on success, or errno otherwise
*/
static int send_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
int needs_conn;
long timeout_val;
int res = -EINVAL;
if (unlikely(!dest))
return -EDESTADDRREQ;
if (unlikely((m->msg_namelen < sizeof(*dest)) ||
(dest->family != AF_TIPC)))
return -EINVAL;
if (total_len > TIPC_MAX_USER_MSG_SIZE)
return -EMSGSIZE;
if (iocb)
lock_sock(sk);
needs_conn = (sock->state != SS_READY);
if (unlikely(needs_conn)) {
if (sock->state == SS_LISTENING) {
res = -EPIPE;
goto exit;
}
if (sock->state != SS_UNCONNECTED) {
res = -EISCONN;
goto exit;
}
if ((tport->published) ||
((sock->type == SOCK_STREAM) && (total_len != 0))) {
res = -EOPNOTSUPP;
goto exit;
}
if (dest->addrtype == TIPC_ADDR_NAME) {
tport->conn_type = dest->addr.name.name.type;
tport->conn_instance = dest->addr.name.name.instance;
}
/* Abort any pending connection attempts (very unlikely) */
reject_rx_queue(sk);
}
timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
do {
if (dest->addrtype == TIPC_ADDR_NAME) {
res = dest_name_check(dest, m);
if (res)
break;
res = tipc_send2name(tport->ref,
&dest->addr.name.name,
dest->addr.name.domain,
m->msg_iovlen,
m->msg_iov,
total_len);
} else if (dest->addrtype == TIPC_ADDR_ID) {
res = tipc_send2port(tport->ref,
&dest->addr.id,
m->msg_iovlen,
m->msg_iov,
total_len);
} else if (dest->addrtype == TIPC_ADDR_MCAST) {
if (needs_conn) {
res = -EOPNOTSUPP;
break;
}
res = dest_name_check(dest, m);
if (res)
break;
res = tipc_multicast(tport->ref,
&dest->addr.nameseq,
m->msg_iovlen,
m->msg_iov,
total_len);
}
if (likely(res != -ELINKCONG)) {
if (needs_conn && (res >= 0))
sock->state = SS_CONNECTING;
break;
}
if (timeout_val <= 0L) {
res = timeout_val ? timeout_val : -EWOULDBLOCK;
break;
}
release_sock(sk);
timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
!tport->congested, timeout_val);
lock_sock(sk);
} while (1);
exit:
if (iocb)
release_sock(sk);
return res;
}
/**
* send_packet - send a connection-oriented message
* @iocb: if NULL, indicates that socket lock is already held
* @sock: socket structure
* @m: message to send
* @total_len: length of message
*
* Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
*
* Returns the number of bytes sent on success, or errno otherwise
*/
static int send_packet(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
long timeout_val;
int res;
/* Handle implied connection establishment */
if (unlikely(dest))
return send_msg(iocb, sock, m, total_len);
if (total_len > TIPC_MAX_USER_MSG_SIZE)
return -EMSGSIZE;
if (iocb)
lock_sock(sk);
timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
do {
if (unlikely(sock->state != SS_CONNECTED)) {
if (sock->state == SS_DISCONNECTING)
res = -EPIPE;
else
res = -ENOTCONN;
break;
}
res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov,
total_len);
if (likely(res != -ELINKCONG))
break;
if (timeout_val <= 0L) {
res = timeout_val ? timeout_val : -EWOULDBLOCK;
break;
}
release_sock(sk);
timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
(!tport->congested || !tport->connected), timeout_val);
lock_sock(sk);
} while (1);
if (iocb)
release_sock(sk);
return res;
}
/**
* send_stream - send stream-oriented data
* @iocb: (unused)
* @sock: socket structure
* @m: data to send
* @total_len: total length of data to be sent
*
* Used for SOCK_STREAM data.
*
* Returns the number of bytes sent on success (or partial success),
* or errno if no data sent
*/
static int send_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct msghdr my_msg;
struct iovec my_iov;
struct iovec *curr_iov;
int curr_iovlen;
char __user *curr_start;
u32 hdr_size;
int curr_left;
int bytes_to_send;
int bytes_sent;
int res;
lock_sock(sk);
/* Handle special cases where there is no connection */
if (unlikely(sock->state != SS_CONNECTED)) {
if (sock->state == SS_UNCONNECTED) {
res = send_packet(NULL, sock, m, total_len);
goto exit;
} else if (sock->state == SS_DISCONNECTING) {
res = -EPIPE;
goto exit;
} else {
res = -ENOTCONN;
goto exit;
}
}
if (unlikely(m->msg_name)) {
res = -EISCONN;
goto exit;
}
if (total_len > (unsigned int)INT_MAX) {
res = -EMSGSIZE;
goto exit;
}
/*
* Send each iovec entry using one or more messages
*
* Note: This algorithm is good for the most likely case
* (i.e. one large iovec entry), but could be improved to pass sets
* of small iovec entries into send_packet().
*/
curr_iov = m->msg_iov;
curr_iovlen = m->msg_iovlen;
my_msg.msg_iov = &my_iov;
my_msg.msg_iovlen = 1;
my_msg.msg_flags = m->msg_flags;
my_msg.msg_name = NULL;
bytes_sent = 0;
hdr_size = msg_hdr_sz(&tport->phdr);
while (curr_iovlen--) {
curr_start = curr_iov->iov_base;
curr_left = curr_iov->iov_len;
while (curr_left) {
bytes_to_send = tport->max_pkt - hdr_size;
if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
if (curr_left < bytes_to_send)
bytes_to_send = curr_left;
my_iov.iov_base = curr_start;
my_iov.iov_len = bytes_to_send;
res = send_packet(NULL, sock, &my_msg, bytes_to_send);
if (res < 0) {
if (bytes_sent)
res = bytes_sent;
goto exit;
}
curr_left -= bytes_to_send;
curr_start += bytes_to_send;
bytes_sent += bytes_to_send;
}
curr_iov++;
}
res = bytes_sent;
exit:
release_sock(sk);
return res;
}
/**
* auto_connect - complete connection setup to a remote port
* @sock: socket structure
* @msg: peer's response message
*
* Returns 0 on success, errno otherwise
*/
static int auto_connect(struct socket *sock, struct tipc_msg *msg)
{
struct tipc_sock *tsock = tipc_sk(sock->sk);
struct tipc_port *p_ptr;
tsock->peer_name.ref = msg_origport(msg);
tsock->peer_name.node = msg_orignode(msg);
p_ptr = tipc_port_deref(tsock->p->ref);
if (!p_ptr)
return -EINVAL;
__tipc_connect(tsock->p->ref, p_ptr, &tsock->peer_name);
if (msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)
return -EINVAL;
msg_set_importance(&p_ptr->phdr, (u32)msg_importance(msg));
sock->state = SS_CONNECTED;
return 0;
}
/**
* set_orig_addr - capture sender's address for received message
* @m: descriptor for message info
* @msg: received message header
*
* Note: Address is not captured if not requested by receiver.
*/
static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
{
struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
if (addr) {
addr->family = AF_TIPC;
addr->addrtype = TIPC_ADDR_ID;
addr->addr.id.ref = msg_origport(msg);
addr->addr.id.node = msg_orignode(msg);
addr->addr.name.domain = 0; /* could leave uninitialized */
addr->scope = 0; /* could leave uninitialized */
m->msg_namelen = sizeof(struct sockaddr_tipc);
}
}
/**
* anc_data_recv - optionally capture ancillary data for received message
* @m: descriptor for message info
* @msg: received message header
* @tport: TIPC port associated with message
*
* Note: Ancillary data is not captured if not requested by receiver.
*
* Returns 0 if successful, otherwise errno
*/
static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
struct tipc_port *tport)
{
u32 anc_data[3];
u32 err;
u32 dest_type;
int has_name;
int res;
if (likely(m->msg_controllen == 0))
return 0;
/* Optionally capture errored message object(s) */
err = msg ? msg_errcode(msg) : 0;
if (unlikely(err)) {
anc_data[0] = err;
anc_data[1] = msg_data_sz(msg);
res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
if (res)
return res;
if (anc_data[1]) {
res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
msg_data(msg));
if (res)
return res;
}
}
/* Optionally capture message destination object */
dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
switch (dest_type) {
case TIPC_NAMED_MSG:
has_name = 1;
anc_data[0] = msg_nametype(msg);
anc_data[1] = msg_namelower(msg);
anc_data[2] = msg_namelower(msg);
break;
case TIPC_MCAST_MSG:
has_name = 1;
anc_data[0] = msg_nametype(msg);
anc_data[1] = msg_namelower(msg);
anc_data[2] = msg_nameupper(msg);
break;
case TIPC_CONN_MSG:
has_name = (tport->conn_type != 0);
anc_data[0] = tport->conn_type;
anc_data[1] = tport->conn_instance;
anc_data[2] = tport->conn_instance;
break;
default:
has_name = 0;
}
if (has_name) {
res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
if (res)
return res;
}
return 0;
}
/**
* recv_msg - receive packet-oriented message
* @iocb: (unused)
* @m: descriptor for message info
* @buf_len: total size of user buffer area
* @flags: receive flags
*
* Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
* If the complete message doesn't fit in user area, truncate it.
*
* Returns size of returned message data, errno otherwise
*/
static int recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
}
/**
* recv_stream - receive stream-oriented data
* @iocb: (unused)
* @m: descriptor for message info
* @buf_len: total size of user buffer area
* @flags: receive flags
*
* Used for SOCK_STREAM messages only. If not enough data is available
* will optionally wait for more; never truncates data.
*
* Returns size of returned message data, errno otherwise
*/
static int recv_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
int sz_to_copy, target, needed;
int sz_copied = 0;
u32 err;
int res = 0;
/* Catch invalid receive attempts */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely((sock->state == SS_UNCONNECTED) ||
(sock->state == SS_CONNECTING))) {
res = -ENOTCONN;
goto exit;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Optionally capture sender's address & ancillary data of first msg */
if (sz_copied == 0) {
set_orig_addr(m, msg);
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
}
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
sz -= offset;
needed = (buf_len - sz_copied);
sz_to_copy = (sz <= needed) ? sz : needed;
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
m->msg_iov, sz_to_copy);
if (res)
goto exit;
sz_copied += sz_to_copy;
if (sz_to_copy < sz) {
if (!(flags & MSG_PEEK))
TIPC_SKB_CB(buf)->handle =
(void *)(unsigned long)(offset + sz_to_copy);
goto exit;
}
} else {
if (sz_copied != 0)
goto exit; /* can't add error msg to valid data */
if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
/* Loop around if more data is required */
if ((sz_copied < buf_len) && /* didn't get all requested data */
(!skb_queue_empty(&sk->sk_receive_queue) ||
(sz_copied < target)) && /* and more is ready or required */
(!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
(!err)) /* and haven't reached a FIN */
goto restart;
exit:
release_sock(sk);
return sz_copied ? sz_copied : res;
}
/**
* tipc_write_space - wake up thread if port congestion is released
* @sk: socket
*/
static void tipc_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLWRNORM | POLLWRBAND);
rcu_read_unlock();
}
/**
* tipc_data_ready - wake up threads to indicate messages have been received
* @sk: socket
* @len: the length of messages
*/
static void tipc_data_ready(struct sock *sk, int len)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM | POLLRDBAND);
rcu_read_unlock();
}
/**
* filter_connect - Handle all incoming messages for a connection-based socket
* @tsock: TIPC socket
* @msg: message
*
* Returns TIPC error status code and socket error status code
* once it encounters some errors
*/
static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf)
{
struct socket *sock = tsock->sk.sk_socket;
struct tipc_msg *msg = buf_msg(*buf);
struct sock *sk = &tsock->sk;
u32 retval = TIPC_ERR_NO_PORT;
int res;
if (msg_mcast(msg))
return retval;
switch ((int)sock->state) {
case SS_CONNECTED:
/* Accept only connection-based messages sent by peer */
if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) {
if (unlikely(msg_errcode(msg))) {
sock->state = SS_DISCONNECTING;
__tipc_disconnect(tsock->p);
}
retval = TIPC_OK;
}
break;
case SS_CONNECTING:
/* Accept only ACK or NACK message */
if (unlikely(msg_errcode(msg))) {
sock->state = SS_DISCONNECTING;
sk->sk_err = -ECONNREFUSED;
retval = TIPC_OK;
break;
}
if (unlikely(!msg_connected(msg)))
break;
res = auto_connect(sock, msg);
if (res) {
sock->state = SS_DISCONNECTING;
sk->sk_err = res;
retval = TIPC_OK;
break;
}
/* If an incoming message is an 'ACK-', it should be
* discarded here because it doesn't contain useful
* data. In addition, we should try to wake up
* connect() routine if sleeping.
*/
if (msg_data_sz(msg) == 0) {
kfree_skb(*buf);
*buf = NULL;
if (waitqueue_active(sk_sleep(sk)))
wake_up_interruptible(sk_sleep(sk));
}
retval = TIPC_OK;
break;
case SS_LISTENING:
case SS_UNCONNECTED:
/* Accept only SYN message */
if (!msg_connected(msg) && !(msg_errcode(msg)))
retval = TIPC_OK;
break;
case SS_DISCONNECTING:
break;
default:
pr_err("Unknown socket state %u\n", sock->state);
}
return retval;
}
/**
* rcvbuf_limit - get proper overload limit of socket receive queue
* @sk: socket
* @buf: message
*
* For all connection oriented messages, irrespective of importance,
* the default overload value (i.e. 67MB) is set as limit.
*
* For all connectionless messages, by default new queue limits are
* as belows:
*
* TIPC_LOW_IMPORTANCE (5MB)
* TIPC_MEDIUM_IMPORTANCE (10MB)
* TIPC_HIGH_IMPORTANCE (20MB)
* TIPC_CRITICAL_IMPORTANCE (40MB)
*
* Returns overload limit according to corresponding message importance
*/
static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
{
struct tipc_msg *msg = buf_msg(buf);
unsigned int limit;
if (msg_connected(msg))
limit = CONN_OVERLOAD_LIMIT;
else
limit = sk->sk_rcvbuf << (msg_importance(msg) + 5);
return limit;
}
/**
* filter_rcv - validate incoming message
* @sk: socket
* @buf: message
*
* Enqueues message on receive queue if acceptable; optionally handles
* disconnect indication for a connected socket.
*
* Called with socket lock already taken; port lock may also be taken.
*
* Returns TIPC error status code (TIPC_OK if message is not to be rejected)
*/
static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
{
struct socket *sock = sk->sk_socket;
struct tipc_msg *msg = buf_msg(buf);
unsigned int limit = rcvbuf_limit(sk, buf);
u32 res = TIPC_OK;
/* Reject message if it is wrong sort of message for socket */
if (msg_type(msg) > TIPC_DIRECT_MSG)
return TIPC_ERR_NO_PORT;
if (sock->state == SS_READY) {
if (msg_connected(msg))
return TIPC_ERR_NO_PORT;
} else {
res = filter_connect(tipc_sk(sk), &buf);
if (res != TIPC_OK || buf == NULL)
return res;
}
/* Reject message if there isn't room to queue it */
if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
return TIPC_ERR_OVERLOAD;
/* Enqueue message */
TIPC_SKB_CB(buf)->handle = 0;
__skb_queue_tail(&sk->sk_receive_queue, buf);
skb_set_owner_r(buf, sk);
sk->sk_data_ready(sk, 0);
return TIPC_OK;
}
/**
* backlog_rcv - handle incoming message from backlog queue
* @sk: socket
* @buf: message
*
* Caller must hold socket lock, but not port lock.
*
* Returns 0
*/
static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
{
u32 res;
res = filter_rcv(sk, buf);
if (res)
tipc_reject_msg(buf, res);
return 0;
}
/**
* dispatch - handle incoming message
* @tport: TIPC port that received message
* @buf: message
*
* Called with port lock already taken.
*
* Returns TIPC error status code (TIPC_OK if message is not to be rejected)
*/
static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
{
struct sock *sk = (struct sock *)tport->usr_handle;
u32 res;
/*
* Process message if socket is unlocked; otherwise add to backlog queue
*
* This code is based on sk_receive_skb(), but must be distinct from it
* since a TIPC-specific filter/reject mechanism is utilized
*/
bh_lock_sock(sk);
if (!sock_owned_by_user(sk)) {
res = filter_rcv(sk, buf);
} else {
if (sk_add_backlog(sk, buf, rcvbuf_limit(sk, buf)))
res = TIPC_ERR_OVERLOAD;
else
res = TIPC_OK;
}
bh_unlock_sock(sk);
return res;
}
/**
* wakeupdispatch - wake up port after congestion
* @tport: port to wakeup
*
* Called with port lock already taken.
*/
static void wakeupdispatch(struct tipc_port *tport)
{
struct sock *sk = (struct sock *)tport->usr_handle;
sk->sk_write_space(sk);
}
/**
* connect - establish a connection to another TIPC port
* @sock: socket structure
* @dest: socket address for destination port
* @destlen: size of socket address data structure
* @flags: file-related flags associated with socket
*
* Returns 0 on success, errno otherwise
*/
static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
struct msghdr m = {NULL,};
unsigned int timeout;
int res;
lock_sock(sk);
/* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
if (sock->state == SS_READY) {
res = -EOPNOTSUPP;
goto exit;
}
/*
* Reject connection attempt using multicast address
*
* Note: send_msg() validates the rest of the address fields,
* so there's no need to do it here
*/
if (dst->addrtype == TIPC_ADDR_MCAST) {
res = -EINVAL;
goto exit;
}
timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
switch (sock->state) {
case SS_UNCONNECTED:
/* Send a 'SYN-' to destination */
m.msg_name = dest;
m.msg_namelen = destlen;
/* If connect is in non-blocking case, set MSG_DONTWAIT to
* indicate send_msg() is never blocked.
*/
if (!timeout)
m.msg_flags = MSG_DONTWAIT;
res = send_msg(NULL, sock, &m, 0);
if ((res < 0) && (res != -EWOULDBLOCK))
goto exit;
/* Just entered SS_CONNECTING state; the only
* difference is that return value in non-blocking
* case is EINPROGRESS, rather than EALREADY.
*/
res = -EINPROGRESS;
break;
case SS_CONNECTING:
res = -EALREADY;
break;
case SS_CONNECTED:
res = -EISCONN;
break;
default:
res = -EINVAL;
goto exit;
}
if (sock->state == SS_CONNECTING) {
if (!timeout)
goto exit;
/* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
release_sock(sk);
res = wait_event_interruptible_timeout(*sk_sleep(sk),
sock->state != SS_CONNECTING,
timeout ? (long)msecs_to_jiffies(timeout)
: MAX_SCHEDULE_TIMEOUT);
lock_sock(sk);
if (res <= 0) {
if (res == 0)
res = -ETIMEDOUT;
else
; /* leave "res" unchanged */
goto exit;
}
}
if (unlikely(sock->state == SS_DISCONNECTING))
res = sock_error(sk);
else
res = 0;
exit:
release_sock(sk);
return res;
}
/**
* listen - allow socket to listen for incoming connections
* @sock: socket structure
* @len: (unused)
*
* Returns 0 on success, errno otherwise
*/
static int listen(struct socket *sock, int len)
{
struct sock *sk = sock->sk;
int res;
lock_sock(sk);
if (sock->state != SS_UNCONNECTED)
res = -EINVAL;
else {
sock->state = SS_LISTENING;
res = 0;
}
release_sock(sk);
return res;
}
/**
* accept - wait for connection request
* @sock: listening socket
* @newsock: new socket that is to be connected
* @flags: file-related flags associated with socket
*
* Returns 0 on success, errno otherwise
*/
static int accept(struct socket *sock, struct socket *new_sock, int flags)
{
struct sock *new_sk, *sk = sock->sk;
struct sk_buff *buf;
struct tipc_sock *new_tsock;
struct tipc_port *new_tport;
struct tipc_msg *msg;
u32 new_ref;
int res;
lock_sock(sk);
if (sock->state != SS_LISTENING) {
res = -EINVAL;
goto exit;
}
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (flags & O_NONBLOCK) {
res = -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
res = wait_event_interruptible(*sk_sleep(sk),
(!skb_queue_empty(&sk->sk_receive_queue)));
lock_sock(sk);
if (res)
goto exit;
}
buf = skb_peek(&sk->sk_receive_queue);
res = tipc_create(sock_net(sock->sk), new_sock, 0, 0);
if (res)
goto exit;
new_sk = new_sock->sk;
new_tsock = tipc_sk(new_sk);
new_tport = new_tsock->p;
new_ref = new_tport->ref;
msg = buf_msg(buf);
/* we lock on new_sk; but lockdep sees the lock on sk */
lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
/*
* Reject any stray messages received by new socket
* before the socket lock was taken (very, very unlikely)
*/
reject_rx_queue(new_sk);
/* Connect new socket to it's peer */
new_tsock->peer_name.ref = msg_origport(msg);
new_tsock->peer_name.node = msg_orignode(msg);
tipc_connect(new_ref, &new_tsock->peer_name);
new_sock->state = SS_CONNECTED;
tipc_set_portimportance(new_ref, msg_importance(msg));
if (msg_named(msg)) {
new_tport->conn_type = msg_nametype(msg);
new_tport->conn_instance = msg_nameinst(msg);
}
/*
* Respond to 'SYN-' by discarding it & returning 'ACK'-.
* Respond to 'SYN+' by queuing it on new socket.
*/
if (!msg_data_sz(msg)) {
struct msghdr m = {NULL,};
advance_rx_queue(sk);
send_packet(NULL, new_sock, &m, 0);
} else {
__skb_dequeue(&sk->sk_receive_queue);
__skb_queue_head(&new_sk->sk_receive_queue, buf);
skb_set_owner_r(buf, new_sk);
}
release_sock(new_sk);
exit:
release_sock(sk);
return res;
}
/**
* shutdown - shutdown socket connection
* @sock: socket structure
* @how: direction to close (must be SHUT_RDWR)
*
* Terminates connection (if necessary), then purges socket's receive queue.
*
* Returns 0 on success, errno otherwise
*/
static int shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
int res;
if (how != SHUT_RDWR)
return -EINVAL;
lock_sock(sk);
switch (sock->state) {
case SS_CONNECTING:
case SS_CONNECTED:
restart:
/* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
buf = __skb_dequeue(&sk->sk_receive_queue);
if (buf) {
if (TIPC_SKB_CB(buf)->handle != 0) {
kfree_skb(buf);
goto restart;
}
tipc_disconnect(tport->ref);
tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
} else {
tipc_shutdown(tport->ref);
}
sock->state = SS_DISCONNECTING;
/* fall through */
case SS_DISCONNECTING:
/* Discard any unreceived messages */
__skb_queue_purge(&sk->sk_receive_queue);
/* Wake up anyone sleeping in poll */
sk->sk_state_change(sk);
res = 0;
break;
default:
res = -ENOTCONN;
}
release_sock(sk);
return res;
}
/**
* setsockopt - set socket option
* @sock: socket structure
* @lvl: option level
* @opt: option identifier
* @ov: pointer to new option value
* @ol: length of option value
*
* For stream sockets only, accepts and ignores all IPPROTO_TCP options
* (to ease compatibility).
*
* Returns 0 on success, errno otherwise
*/
static int setsockopt(struct socket *sock,
int lvl, int opt, char __user *ov, unsigned int ol)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
u32 value;
int res;
if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
return 0;
if (lvl != SOL_TIPC)
return -ENOPROTOOPT;
if (ol < sizeof(value))
return -EINVAL;
res = get_user(value, (u32 __user *)ov);
if (res)
return res;
lock_sock(sk);
switch (opt) {
case TIPC_IMPORTANCE:
res = tipc_set_portimportance(tport->ref, value);
break;
case TIPC_SRC_DROPPABLE:
if (sock->type != SOCK_STREAM)
res = tipc_set_portunreliable(tport->ref, value);
else
res = -ENOPROTOOPT;
break;
case TIPC_DEST_DROPPABLE:
res = tipc_set_portunreturnable(tport->ref, value);
break;
case TIPC_CONN_TIMEOUT:
tipc_sk(sk)->conn_timeout = value;
/* no need to set "res", since already 0 at this point */
break;
default:
res = -EINVAL;
}
release_sock(sk);
return res;
}
/**
* getsockopt - get socket option
* @sock: socket structure
* @lvl: option level
* @opt: option identifier
* @ov: receptacle for option value
* @ol: receptacle for length of option value
*
* For stream sockets only, returns 0 length result for all IPPROTO_TCP options
* (to ease compatibility).
*
* Returns 0 on success, errno otherwise
*/
static int getsockopt(struct socket *sock,
int lvl, int opt, char __user *ov, int __user *ol)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
int len;
u32 value;
int res;
if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
return put_user(0, ol);
if (lvl != SOL_TIPC)
return -ENOPROTOOPT;
res = get_user(len, ol);
if (res)
return res;
lock_sock(sk);
switch (opt) {
case TIPC_IMPORTANCE:
res = tipc_portimportance(tport->ref, &value);
break;
case TIPC_SRC_DROPPABLE:
res = tipc_portunreliable(tport->ref, &value);
break;
case TIPC_DEST_DROPPABLE:
res = tipc_portunreturnable(tport->ref, &value);
break;
case TIPC_CONN_TIMEOUT:
value = tipc_sk(sk)->conn_timeout;
/* no need to set "res", since already 0 at this point */
break;
case TIPC_NODE_RECVQ_DEPTH:
value = 0; /* was tipc_queue_size, now obsolete */
break;
case TIPC_SOCK_RECVQ_DEPTH:
value = skb_queue_len(&sk->sk_receive_queue);
break;
default:
res = -EINVAL;
}
release_sock(sk);
if (res)
return res; /* "get" failed */
if (len < sizeof(value))
return -EINVAL;
if (copy_to_user(ov, &value, sizeof(value)))
return -EFAULT;
return put_user(sizeof(value), ol);
}
/* Protocol switches for the various types of TIPC sockets */
static const struct proto_ops msg_ops = {
.owner = THIS_MODULE,
.family = AF_TIPC,
.release = release,
.bind = bind,
.connect = connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = get_name,
.poll = poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = shutdown,
.setsockopt = setsockopt,
.getsockopt = getsockopt,
.sendmsg = send_msg,
.recvmsg = recv_msg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage
};
static const struct proto_ops packet_ops = {
.owner = THIS_MODULE,
.family = AF_TIPC,
.release = release,
.bind = bind,
.connect = connect,
.socketpair = sock_no_socketpair,
.accept = accept,
.getname = get_name,
.poll = poll,
.ioctl = sock_no_ioctl,
.listen = listen,
.shutdown = shutdown,
.setsockopt = setsockopt,
.getsockopt = getsockopt,
.sendmsg = send_packet,
.recvmsg = recv_msg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage
};
static const struct proto_ops stream_ops = {
.owner = THIS_MODULE,
.family = AF_TIPC,
.release = release,
.bind = bind,
.connect = connect,
.socketpair = sock_no_socketpair,
.accept = accept,
.getname = get_name,
.poll = poll,
.ioctl = sock_no_ioctl,
.listen = listen,
.shutdown = shutdown,
.setsockopt = setsockopt,
.getsockopt = getsockopt,
.sendmsg = send_stream,
.recvmsg = recv_stream,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage
};
static const struct net_proto_family tipc_family_ops = {
.owner = THIS_MODULE,
.family = AF_TIPC,
.create = tipc_create
};
static struct proto tipc_proto = {
.name = "TIPC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct tipc_sock)
};
/**
* tipc_socket_init - initialize TIPC socket interface
*
* Returns 0 on success, errno otherwise
*/
int tipc_socket_init(void)
{
int res;
res = proto_register(&tipc_proto, 1);
if (res) {
pr_err("Failed to register TIPC protocol type\n");
goto out;
}
res = sock_register(&tipc_family_ops);
if (res) {
pr_err("Failed to register TIPC socket type\n");
proto_unregister(&tipc_proto);
goto out;
}
sockets_enabled = 1;
out:
return res;
}
/**
* tipc_socket_stop - stop TIPC socket interface
*/
void tipc_socket_stop(void)
{
if (!sockets_enabled)
return;
sockets_enabled = 0;
sock_unregister(tipc_family_ops.family);
proto_unregister(&tipc_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_5695_0 |
crossvul-cpp_data_bad_4074_0 |
/*-------------------------------------------------------------------------*/
/**
@file iniparser.c
@author N. Devillard
@brief Parser for ini files.
*/
/*--------------------------------------------------------------------------*/
/*---------------------------- Includes ------------------------------------*/
#include <ctype.h>
#include "iniparser.h"
/*---------------------------- Defines -------------------------------------*/
#define ASCIILINESZ (1024)
#define INI_INVALID_KEY ((char*)-1)
/*---------------------------------------------------------------------------
Private to this module
---------------------------------------------------------------------------*/
/**
* This enum stores the status for each parsed line (internal use only).
*/
typedef enum _line_status_ {
LINE_UNPROCESSED,
LINE_ERROR,
LINE_EMPTY,
LINE_COMMENT,
LINE_SECTION,
LINE_VALUE
} line_status ;
/*-------------------------------------------------------------------------*/
/**
@brief Convert a string to lowercase.
@param in String to convert.
@param out Output buffer.
@param len Size of the out buffer.
@return ptr to the out buffer or NULL if an error occured.
This function convert a string into lowercase.
At most len - 1 elements of the input string will be converted.
*/
/*--------------------------------------------------------------------------*/
static const char * strlwc(const char * in, char *out, unsigned len)
{
unsigned i ;
if (in==NULL || out == NULL || len==0) return NULL ;
i=0 ;
while (in[i] != '\0' && i < len-1) {
out[i] = (char)tolower((int)in[i]);
i++ ;
}
out[i] = '\0';
return out ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Copy string in a newly mallocced area
@param str String to copy.
@return str Copied version of the given string allocated with malloc
Original strdup is not portable, need to implement our own
*/
/*--------------------------------------------------------------------------*/
static char * _strdup(const char *s)
{
char * copy = (char*) malloc(strlen(s));
strcpy(copy, s);
return copy ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Remove blanks at the beginning and the end of a string.
@param str String to parse and alter.
@return unsigned New size of the string.
*/
/*--------------------------------------------------------------------------*/
unsigned strstrip(char * s)
{
char *last = NULL ;
char *dest = s;
if (s==NULL) return 0;
last = s + strlen(s);
while (isspace((int)*s) && *s) s++;
while (last > s) {
if (!isspace((int)*(last-1)))
break ;
last -- ;
}
*last = (char)0;
memmove(dest,s,last - s + 1);
return last - s;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get number of sections in a dictionary
@param d Dictionary to examine
@return int Number of sections found in dictionary
This function returns the number of sections found in a dictionary.
The test to recognize sections is done on the string stored in the
dictionary: a section name is given as "section" whereas a key is
stored as "section:key", thus the test looks for entries that do not
contain a colon.
This clearly fails in the case a section name contains a colon, but
this should simply be avoided.
This function returns -1 in case of error.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getnsec(const dictionary * d)
{
int i ;
int nsec ;
if (d==NULL) return -1 ;
nsec=0 ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (strchr(d->key[i], ':')==NULL) {
nsec ++ ;
}
}
return nsec ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get name for section n in a dictionary.
@param d Dictionary to examine
@param n Section number (from 0 to nsec-1).
@return Pointer to char string
This function locates the n-th section in a dictionary and returns
its name as a pointer to a string statically allocated inside the
dictionary. Do not free or modify the returned string!
This function returns NULL in case of error.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getsecname(const dictionary * d, int n)
{
int i ;
int foundsec ;
if (d==NULL || n<0) return NULL ;
foundsec=0 ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (strchr(d->key[i], ':')==NULL) {
foundsec++ ;
if (foundsec>n)
break ;
}
}
if (foundsec<=n) {
return NULL ;
}
return d->key[i] ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Dump a dictionary to an opened file pointer.
@param d Dictionary to dump.
@param f Opened file pointer to dump to.
@return void
This function prints out the contents of a dictionary, one element by
line, onto the provided file pointer. It is OK to specify @c stderr
or @c stdout as output files. This function is meant for debugging
purposes mostly.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump(const dictionary * d, FILE * f)
{
int i ;
if (d==NULL || f==NULL) return ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (d->val[i]!=NULL) {
fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
} else {
fprintf(f, "[%s]=UNDEF\n", d->key[i]);
}
}
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary to a loadable ini file
@param d Dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given dictionary into a loadable ini file.
It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump_ini(const dictionary * d, FILE * f)
{
int i ;
int nsec ;
const char * secname ;
if (d==NULL || f==NULL) return ;
nsec = iniparser_getnsec(d);
if (nsec<1) {
/* No section in file: dump all keys as they are */
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
}
return ;
}
for (i=0 ; i<nsec ; i++) {
secname = iniparser_getsecname(d, i) ;
iniparser_dumpsection_ini(d, secname, f);
}
fprintf(f, "\n");
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary section to a loadable ini file
@param d Dictionary to dump
@param s Section name of dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given section of a given dictionary into a loadable ini
file. It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dumpsection_ini(const dictionary * d, const char * s, FILE * f)
{
int j ;
char keym[ASCIILINESZ+1];
int seclen ;
if (d==NULL || f==NULL) return ;
if (! iniparser_find_entry(d, s)) return ;
seclen = (int)strlen(s);
fprintf(f, "\n[%s]\n", s);
sprintf(keym, "%s:", s);
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1)) {
fprintf(f,
"%-30s = %s\n",
d->key[j]+seclen+1,
d->val[j] ? d->val[j] : "");
}
}
fprintf(f, "\n");
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@return Number of keys in section
*/
/*--------------------------------------------------------------------------*/
int iniparser_getsecnkeys(const dictionary * d, const char * s)
{
int seclen, nkeys ;
char keym[ASCIILINESZ+1];
int j ;
nkeys = 0;
if (d==NULL) return nkeys;
if (! iniparser_find_entry(d, s)) return nkeys;
seclen = (int)strlen(s);
sprintf(keym, "%s:", s);
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1))
nkeys++;
}
return nkeys;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@param keys Already allocated array to store the keys in
@return The pointer passed as `keys` argument or NULL in case of error
This function queries a dictionary and finds all keys in a given section.
The keys argument should be an array of pointers which size has been
determined by calling `iniparser_getsecnkeys` function prior to this one.
Each pointer in the returned char pointer-to-pointer is pointing to
a string allocated in the dictionary; do not free or modify them.
*/
/*--------------------------------------------------------------------------*/
const char ** iniparser_getseckeys(const dictionary * d, const char * s, const char ** keys)
{
int i, j, seclen ;
char keym[ASCIILINESZ+1];
if (d==NULL || keys==NULL) return NULL;
if (! iniparser_find_entry(d, s)) return NULL;
seclen = (int)strlen(s);
sprintf(keym, "%s:", s);
i = 0;
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1)) {
keys[i] = d->key[j];
i++;
}
}
return keys;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key
@param d Dictionary to search
@param key Key string to look for
@param def Default value to return if key not found.
@return pointer to statically allocated character string
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the pointer passed as 'def' is returned.
The returned char pointer is pointing to a string allocated in
the dictionary, do not free or modify it.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getstring(const dictionary * d, const char * key, const char * def)
{
const char * lc_key ;
const char * sval ;
char tmp_str[ASCIILINESZ+1];
if (d==NULL || key==NULL)
return def ;
lc_key = strlwc(key, tmp_str, sizeof(tmp_str));
sval = dictionary_get(d, lc_key, def);
return sval ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to an int
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
Supported values for integers include the usual C notation
so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
are supported. Examples:
"42" -> 42
"042" -> 34 (octal -> decimal)
"0x42" -> 66 (hexa -> decimal)
Warning: the conversion may overflow in various ways. Conversion is
totally outsourced to strtol(), see the associated man page for overflow
handling.
Credits: Thanks to A. Becker for suggesting strtol()
*/
/*--------------------------------------------------------------------------*/
int iniparser_getint(const dictionary * d, const char * key, int notfound)
{
const char * str ;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
if (str==INI_INVALID_KEY) return notfound ;
return (int)strtol(str, NULL, 0);
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a double
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return double
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
*/
/*--------------------------------------------------------------------------*/
double iniparser_getdouble(const dictionary * d, const char * key, double notfound)
{
const char * str ;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
if (str==INI_INVALID_KEY) return notfound ;
return atof(str);
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a boolean
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
A true boolean is found if one of the following is matched:
- A string starting with 'y'
- A string starting with 'Y'
- A string starting with 't'
- A string starting with 'T'
- A string starting with '1'
A false boolean is found if one of the following is matched:
- A string starting with 'n'
- A string starting with 'N'
- A string starting with 'f'
- A string starting with 'F'
- A string starting with '0'
The notfound value returned if no boolean is identified, does not
necessarily have to be 0 or 1.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getboolean(const dictionary * d, const char * key, int notfound)
{
int ret ;
const char * c ;
c = iniparser_getstring(d, key, INI_INVALID_KEY);
if (c==INI_INVALID_KEY) return notfound ;
if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
ret = 1 ;
} else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
ret = 0 ;
} else {
ret = notfound ;
}
return ret;
}
/*-------------------------------------------------------------------------*/
/**
@brief Finds out if a given entry exists in a dictionary
@param ini Dictionary to search
@param entry Name of the entry to look for
@return integer 1 if entry exists, 0 otherwise
Finds out if a given entry exists in the dictionary. Since sections
are stored as keys with NULL associated values, this is the only way
of querying for the presence of sections in a dictionary.
*/
/*--------------------------------------------------------------------------*/
int iniparser_find_entry(const dictionary * ini, const char * entry)
{
int found=0 ;
if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) {
found = 1 ;
}
return found ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Set an entry in a dictionary.
@param ini Dictionary to modify.
@param entry Entry to modify (entry name)
@param val New value to associate to the entry.
@return int 0 if Ok, -1 otherwise.
If the given entry can be found in the dictionary, it is modified to
contain the provided value. If it cannot be found, the entry is created.
It is Ok to set val to NULL.
*/
/*--------------------------------------------------------------------------*/
int iniparser_set(dictionary * ini, const char * entry, const char * val)
{
char tmp_str[ASCIILINESZ+1];
return dictionary_set(ini, strlwc(entry, tmp_str, sizeof(tmp_str)), val) ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Delete an entry in a dictionary
@param ini Dictionary to modify
@param entry Entry to delete (entry name)
@return void
If the given entry can be found, it is deleted from the dictionary.
*/
/*--------------------------------------------------------------------------*/
void iniparser_unset(dictionary * ini, const char * entry)
{
char tmp_str[ASCIILINESZ+1];
dictionary_unset(ini, strlwc(entry, tmp_str, sizeof(tmp_str)));
}
/*-------------------------------------------------------------------------*/
/**
@brief Load a single line from an INI file
@param input_line Input line, may be concatenated multi-line input
@param section Output space to store section
@param key Output space to store key
@param value Output space to store value
@return line_status value
*/
/*--------------------------------------------------------------------------*/
static line_status iniparser_line(
const char * input_line,
char * section,
char * key,
char * value)
{
line_status sta ;
char * line = NULL;
size_t len ;
line = _strdup(input_line);
len = strstrip(line);
sta = LINE_UNPROCESSED ;
if (len<1) {
/* Empty line */
sta = LINE_EMPTY ;
} else if (line[0]=='#' || line[0]==';') {
/* Comment line */
sta = LINE_COMMENT ;
} else if (line[0]=='[' && line[len-1]==']') {
/* Section name */
sscanf(line, "[%[^]]", section);
strstrip(section);
strlwc(section, section, len);
sta = LINE_SECTION ;
} else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
|| sscanf (line, "%[^=] = '%[^\']'", key, value) == 2
|| sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
/* Usual key=value, with or without comments */
strstrip(key);
strlwc(key, key, len);
strstrip(value);
/*
* sscanf cannot handle '' or "" as empty values
* this is done here
*/
if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
value[0]=0 ;
}
sta = LINE_VALUE ;
} else if (sscanf(line, "%[^=] = %[;#]", key, value)==2
|| sscanf(line, "%[^=] %[=]", key, value) == 2) {
/*
* Special cases:
* key=
* key=;
* key=#
*/
strstrip(key);
strlwc(key, key, len);
value[0]=0 ;
sta = LINE_VALUE ;
} else {
/* Generate syntax error */
sta = LINE_ERROR ;
}
free(line);
return sta ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Parse an ini file and return an allocated dictionary object
@param ininame Name of the ini file to read.
@return Pointer to newly allocated dictionary
This is the parser for ini files. This function is called, providing
the name of the file to be read. It returns a dictionary object that
should not be accessed directly, but through accessor functions
instead.
The returned dictionary must be freed using iniparser_freedict().
*/
/*--------------------------------------------------------------------------*/
dictionary * iniparser_load(const char * ininame)
{
FILE * in ;
char line [ASCIILINESZ+1] ;
char section [ASCIILINESZ+1] ;
char key [ASCIILINESZ+1] ;
char tmp [(ASCIILINESZ * 2) + 1] ;
char val [ASCIILINESZ+1] ;
int last=0 ;
int len ;
int lineno=0 ;
int errs=0;
dictionary * dict ;
if ((in=fopen(ininame, "r"))==NULL) {
fprintf(stderr, "iniparser: cannot open %s\n", ininame);
return NULL ;
}
dict = dictionary_new(0) ;
if (!dict) {
fclose(in);
return NULL ;
}
memset(line, 0, ASCIILINESZ);
memset(section, 0, ASCIILINESZ);
memset(key, 0, ASCIILINESZ);
memset(val, 0, ASCIILINESZ);
last=0 ;
while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
lineno++ ;
len = (int)strlen(line)-1;
if (len==0)
continue;
/* Safety check against buffer overflows */
if (line[len]!='\n' && !feof(in)) {
fprintf(stderr,
"iniparser: input line too long in %s (%d)\n",
ininame,
lineno);
dictionary_del(dict);
fclose(in);
return NULL ;
}
/* Get rid of \n and spaces at end of line */
while ((len>=0) &&
((line[len]=='\n') || (isspace(line[len])))) {
line[len]=0 ;
len-- ;
}
if (len < 0) { /* Line was entirely \n and/or spaces */
len = 0;
}
/* Detect multi-line */
if (line[len]=='\\') {
/* Multi-line value */
last=len ;
continue ;
} else {
last=0 ;
}
switch (iniparser_line(line, section, key, val)) {
case LINE_EMPTY:
case LINE_COMMENT:
break ;
case LINE_SECTION:
errs = dictionary_set(dict, section, NULL);
break ;
case LINE_VALUE:
sprintf(tmp, "%s:%s", section, key);
errs = dictionary_set(dict, tmp, val) ;
break ;
case LINE_ERROR:
fprintf(stderr, "iniparser: syntax error in %s (%d):\n",
ininame,
lineno);
fprintf(stderr, "-> %s\n", line);
errs++ ;
break;
default:
break ;
}
memset(line, 0, ASCIILINESZ);
last=0;
if (errs<0) {
fprintf(stderr, "iniparser: memory allocation failure\n");
break ;
}
}
if (errs) {
dictionary_del(dict);
dict = NULL ;
}
fclose(in);
return dict ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Free all memory associated to an ini dictionary
@param d Dictionary to free
@return void
Free all memory associated to an ini dictionary.
It is mandatory to call this function before the dictionary object
gets out of the current context.
*/
/*--------------------------------------------------------------------------*/
void iniparser_freedict(dictionary * d)
{
dictionary_del(d);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_4074_0 |
crossvul-cpp_data_bad_3823_0 | /* xfrm_user.c: User interface to configure xfrm engine.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
*
*/
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/init.h>
#include <linux/security.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/netlink.h>
#include <net/ah.h>
#include <asm/uaccess.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/in6.h>
#endif
static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
{
struct nlattr *rt = attrs[type];
struct xfrm_algo *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_len(algp))
return -EINVAL;
switch (type) {
case XFRMA_ALG_AUTH:
case XFRMA_ALG_CRYPT:
case XFRMA_ALG_COMP:
break;
default:
return -EINVAL;
}
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_auth_trunc(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
struct xfrm_algo_auth *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_auth_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_aead(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
struct xfrm_algo_aead *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < aead_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
xfrm_address_t **addrp)
{
struct nlattr *rt = attrs[type];
if (rt && addrp)
*addrp = nla_data(rt);
}
static inline int verify_sec_ctx_len(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
return -EINVAL;
return 0;
}
static inline int verify_replay(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
if ((p->flags & XFRM_STATE_ESN) && !rt)
return -EINVAL;
if (!rt)
return 0;
if (p->id.proto != IPPROTO_ESP)
return -EINVAL;
if (p->replay_window != 0)
return -EINVAL;
return 0;
}
static int verify_newsa_info(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
int err;
err = -EINVAL;
switch (p->family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
err = -EAFNOSUPPORT;
goto out;
#endif
default:
goto out;
}
err = -EINVAL;
switch (p->id.proto) {
case IPPROTO_AH:
if ((!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC]) ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
case IPPROTO_ESP:
if (attrs[XFRMA_ALG_COMP])
goto out;
if (!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC] &&
!attrs[XFRMA_ALG_CRYPT] &&
!attrs[XFRMA_ALG_AEAD])
goto out;
if ((attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT]) &&
attrs[XFRMA_ALG_AEAD])
goto out;
if (attrs[XFRMA_TFCPAD] &&
p->mode != XFRM_MODE_TUNNEL)
goto out;
break;
case IPPROTO_COMP:
if (!attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
#if IS_ENABLED(CONFIG_IPV6)
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
if (attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ENCAP] ||
attrs[XFRMA_SEC_CTX] ||
attrs[XFRMA_TFCPAD] ||
!attrs[XFRMA_COADDR])
goto out;
break;
#endif
default:
goto out;
}
if ((err = verify_aead(attrs)))
goto out;
if ((err = verify_auth_trunc(attrs)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
goto out;
if ((err = verify_sec_ctx_len(attrs)))
goto out;
if ((err = verify_replay(p, attrs)))
goto out;
err = -EINVAL;
switch (p->mode) {
case XFRM_MODE_TRANSPORT:
case XFRM_MODE_TUNNEL:
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_BEET:
break;
default:
goto out;
}
err = 0;
out:
return err;
}
static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo *ualg;
struct xfrm_algo_auth *p;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
p->alg_key_len = ualg->alg_key_len;
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
*algpp = p;
return 0;
}
static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_auth *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN ||
ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
return -EINVAL;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
if (!p->alg_trunc_len)
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
*algpp = p;
return 0;
}
static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_aead *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
{
int len = 0;
if (xfrm_ctx) {
len += sizeof(struct xfrm_user_sec_ctx);
len += xfrm_ctx->ctx_len;
}
return len;
}
static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&x->id, &p->id, sizeof(x->id));
memcpy(&x->sel, &p->sel, sizeof(x->sel));
memcpy(&x->lft, &p->lft, sizeof(x->lft));
x->props.mode = p->mode;
x->props.replay_window = p->replay_window;
x->props.reqid = p->reqid;
x->props.family = p->family;
memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
x->props.flags = p->flags;
if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
x->sel.family = p->family;
}
/*
* someday when pfkey also has support, we could have the code
* somehow made shareable and move it to xfrm_state.c - JHS
*
*/
static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs)
{
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
if (re) {
struct xfrm_replay_state_esn *replay_esn;
replay_esn = nla_data(re);
memcpy(x->replay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
memcpy(x->preplay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
}
if (rp) {
struct xfrm_replay_state *replay;
replay = nla_data(rp);
memcpy(&x->replay, replay, sizeof(*replay));
memcpy(&x->preplay, replay, sizeof(*replay));
}
if (lt) {
struct xfrm_lifetime_cur *ltime;
ltime = nla_data(lt);
x->curlft.bytes = ltime->bytes;
x->curlft.packets = ltime->packets;
x->curlft.add_time = ltime->add_time;
x->curlft.use_time = ltime->use_time;
}
if (et)
x->replay_maxage = nla_get_u32(et);
if (rt)
x->replay_maxdiff = nla_get_u32(rt);
}
static struct xfrm_state *xfrm_state_construct(struct net *net,
struct xfrm_usersa_info *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto error_no_put;
copy_from_user_state(x, p);
if ((err = attach_aead(&x->aead, &x->props.ealgo,
attrs[XFRMA_ALG_AEAD])))
goto error;
if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH_TRUNC])))
goto error;
if (!x->props.aalgo) {
if ((err = attach_auth(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH])))
goto error;
}
if ((err = attach_one_algo(&x->ealg, &x->props.ealgo,
xfrm_ealg_get_byname,
attrs[XFRMA_ALG_CRYPT])))
goto error;
if ((err = attach_one_algo(&x->calg, &x->props.calgo,
xfrm_calg_get_byname,
attrs[XFRMA_ALG_COMP])))
goto error;
if (attrs[XFRMA_ENCAP]) {
x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
sizeof(*x->encap), GFP_KERNEL);
if (x->encap == NULL)
goto error;
}
if (attrs[XFRMA_TFCPAD])
x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
if (attrs[XFRMA_COADDR]) {
x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
sizeof(*x->coaddr), GFP_KERNEL);
if (x->coaddr == NULL)
goto error;
}
xfrm_mark_get(attrs, &x->mark);
err = __xfrm_init_state(x, false);
if (err)
goto error;
if (attrs[XFRMA_SEC_CTX] &&
security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])))
goto error;
if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
attrs[XFRMA_REPLAY_ESN_VAL])))
goto error;
x->km.seq = p->seq;
x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
/* sysctl_xfrm_aevent_etime is in 100ms units */
x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
if ((err = xfrm_init_replay(x)))
goto error;
/* override default values from above */
xfrm_update_ae_params(x, attrs);
return x;
error:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
error_no_put:
*errp = err;
return NULL;
}
static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_info *p = nlmsg_data(nlh);
struct xfrm_state *x;
int err;
struct km_event c;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newsa_info(p, attrs);
if (err)
return err;
x = xfrm_state_construct(net, p, attrs, &err);
if (!x)
return err;
xfrm_state_hold(x);
if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
security_task_getsecid(current, &sid);
xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
struct xfrm_usersa_id *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = NULL;
struct xfrm_mark m;
int err;
u32 mark = xfrm_mark_get(attrs, &m);
if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
err = -ESRCH;
x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
} else {
xfrm_address_t *saddr = NULL;
verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
if (!saddr) {
err = -EINVAL;
goto out;
}
err = -ESRCH;
x = xfrm_state_lookup_byaddr(net, mark,
&p->daddr, saddr,
p->proto, p->family);
}
out:
if (!x && errp)
*errp = err;
return x;
}
static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err = -ESRCH;
struct km_event c;
struct xfrm_usersa_id *p = nlmsg_data(nlh);
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
return err;
if ((err = security_xfrm_state_delete(x)) != 0)
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
security_task_getsecid(current, &sid);
xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid);
xfrm_state_put(x);
return err;
}
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memset(p, 0, sizeof(*p));
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
struct xfrm_dump_info {
struct sk_buff *in_skb;
struct sk_buff *out_skb;
u32 nlmsg_seq;
u16 nlmsg_flags;
};
static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
{
struct xfrm_user_sec_ctx *uctx;
struct nlattr *attr;
int ctx_size = sizeof(*uctx) + s->ctx_len;
attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
if (attr == NULL)
return -EMSGSIZE;
uctx = nla_data(attr);
uctx->exttype = XFRMA_SEC_CTX;
uctx->len = ctx_size;
uctx->ctx_doi = s->ctx_doi;
uctx->ctx_alg = s->ctx_alg;
uctx->ctx_len = s->ctx_len;
memcpy(uctx + 1, s->ctx_str, s->ctx_len);
return 0;
}
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
/* Don't change this without updating xfrm_sa_len! */
static int copy_to_user_state_extra(struct xfrm_state *x,
struct xfrm_usersa_info *p,
struct sk_buff *skb)
{
int ret = 0;
copy_to_user_state(x, p);
if (x->coaddr) {
ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
if (ret)
goto out;
}
if (x->lastused) {
ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused);
if (ret)
goto out;
}
if (x->aead) {
ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
if (ret)
goto out;
}
if (x->aalg) {
ret = copy_to_user_auth(x->aalg, skb);
if (!ret)
ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC,
xfrm_alg_auth_len(x->aalg), x->aalg);
if (ret)
goto out;
}
if (x->ealg) {
ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
if (ret)
goto out;
}
if (x->calg) {
ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
if (ret)
goto out;
}
if (x->encap) {
ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
if (ret)
goto out;
}
if (x->tfcpad) {
ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
if (ret)
goto out;
}
ret = xfrm_mark_put(skb, &x->mark);
if (ret)
goto out;
if (x->replay_esn) {
ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
if (ret)
goto out;
}
if (x->security)
ret = copy_sec_ctx(x->security, skb);
out:
return ret;
}
static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct xfrm_usersa_info *p;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
err = copy_to_user_state_extra(x, p, skb);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_sa_done(struct netlink_callback *cb)
{
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
xfrm_state_walk_done(walk);
return 0;
}
static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_state_walk_init(walk, 0);
}
(void) xfrm_state_walk(net, walk, dump_one_state, &info);
return skb->len;
}
static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static inline size_t xfrm_spdinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_spdinfo))
+ nla_total_size(sizeof(struct xfrmu_spdhinfo));
}
static int build_spdinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_spdinfo si;
struct xfrmu_spdinfo spc;
struct xfrmu_spdhinfo sph;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_spd_getinfo(net, &si);
spc.incnt = si.incnt;
spc.outcnt = si.outcnt;
spc.fwdcnt = si.fwdcnt;
spc.inscnt = si.inscnt;
spc.outscnt = si.outscnt;
spc.fwdscnt = si.fwdscnt;
sph.spdhcnt = si.spdhcnt;
sph.spdhmcnt = si.spdhmcnt;
err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
if (!err)
err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static inline size_t xfrm_sadinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_sadhinfo))
+ nla_total_size(4); /* XFRMA_SAD_CNT */
}
static int build_sadinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_sadinfo si;
struct xfrmu_sadhinfo sh;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_sad_getinfo(net, &si);
sh.sadhmcnt = si.sadhmcnt;
sh.sadhcnt = si.sadhcnt;
err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
if (!err)
err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_id *p = nlmsg_data(nlh);
struct xfrm_state *x;
struct sk_buff *resp_skb;
int err = -ESRCH;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
goto out_noput;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
}
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_userspi_info(struct xfrm_userspi_info *p)
{
switch (p->info.id.proto) {
case IPPROTO_AH:
case IPPROTO_ESP:
break;
case IPPROTO_COMP:
/* IPCOMP spi is 16-bits. */
if (p->max >= 0x10000)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (p->min > p->max)
return -EINVAL;
return 0;
}
static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct xfrm_userspi_info *p;
struct sk_buff *resp_skb;
xfrm_address_t *daddr;
int family;
int err;
u32 mark;
struct xfrm_mark m;
p = nlmsg_data(nlh);
err = verify_userspi_info(p);
if (err)
goto out_noput;
family = p->info.family;
daddr = &p->info.id.daddr;
x = NULL;
mark = xfrm_mark_get(attrs, &m);
if (p->info.seq) {
x = xfrm_find_acq_byseq(net, mark, p->info.seq);
if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
p->info.id.proto, daddr,
&p->info.saddr, 1,
family);
err = -ENOENT;
if (x == NULL)
goto out_noput;
err = xfrm_alloc_spi(x, p->min, p->max);
if (err)
goto out;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
goto out;
}
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
out:
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_policy_dir(u8 dir)
{
switch (dir) {
case XFRM_POLICY_IN:
case XFRM_POLICY_OUT:
case XFRM_POLICY_FWD:
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_policy_type(u8 type)
{
switch (type) {
case XFRM_POLICY_TYPE_MAIN:
#ifdef CONFIG_XFRM_SUB_POLICY
case XFRM_POLICY_TYPE_SUB:
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
{
switch (p->share) {
case XFRM_SHARE_ANY:
case XFRM_SHARE_SESSION:
case XFRM_SHARE_USER:
case XFRM_SHARE_UNIQUE:
break;
default:
return -EINVAL;
}
switch (p->action) {
case XFRM_POLICY_ALLOW:
case XFRM_POLICY_BLOCK:
break;
default:
return -EINVAL;
}
switch (p->sel.family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
return -EAFNOSUPPORT;
#endif
default:
return -EINVAL;
}
return verify_policy_dir(p->dir);
}
static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
return security_xfrm_policy_alloc(&pol->security, uctx);
}
static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
int nr)
{
int i;
xp->xfrm_nr = nr;
for (i = 0; i < nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
memcpy(&t->saddr, &ut->saddr,
sizeof(xfrm_address_t));
t->reqid = ut->reqid;
t->mode = ut->mode;
t->share = ut->share;
t->optional = ut->optional;
t->aalgos = ut->aalgos;
t->ealgos = ut->ealgos;
t->calgos = ut->calgos;
/* If all masks are ~0, then we allow all algorithms. */
t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
t->encap_family = ut->family;
}
}
static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
{
int i;
if (nr > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < nr; i++) {
/* We never validated the ut->family value, so many
* applications simply leave it at zero. The check was
* never made and ut->family was ignored because all
* templates could be assumed to have the same family as
* the policy itself. Now that we will have ipv4-in-ipv6
* and ipv6-in-ipv4 tunnels, this is no longer true.
*/
if (!ut[i].family)
ut[i].family = family;
switch (ut[i].family) {
case AF_INET:
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
break;
#endif
default:
return -EINVAL;
}
}
return 0;
}
static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_TMPL];
if (!rt) {
pol->xfrm_nr = 0;
} else {
struct xfrm_user_tmpl *utmpl = nla_data(rt);
int nr = nla_len(rt) / sizeof(*utmpl);
int err;
err = validate_tmpl(nr, utmpl, pol->family);
if (err)
return err;
copy_templates(pol, utmpl, nr);
}
return 0;
}
static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
struct xfrm_userpolicy_type *upt;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
if (rt) {
upt = nla_data(rt);
type = upt->type;
}
err = verify_policy_type(type);
if (err)
return err;
*tp = type;
return 0;
}
static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
{
xp->priority = p->priority;
xp->index = p->index;
memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
xp->action = p->action;
xp->flags = p->flags;
xp->family = p->sel.family;
/* XXX xp->share = p->share; */
}
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memset(p, 0, sizeof(*p));
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
{
struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
int err;
if (!xp) {
*errp = -ENOMEM;
return NULL;
}
copy_from_user_policy(xp, p);
err = copy_from_user_policy_type(&xp->type, attrs);
if (err)
goto error;
if (!(err = copy_from_user_tmpl(xp, attrs)))
err = copy_from_user_sec_ctx(xp, attrs);
if (err)
goto error;
xfrm_mark_get(attrs, &xp->mark);
return xp;
error:
*errp = err;
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
struct xfrm_policy *xp;
struct km_event c;
int err;
int excl;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newpolicy_info(p);
if (err)
return err;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
xp = xfrm_policy_construct(net, p, attrs, &err);
if (!xp)
return err;
/* shouldn't excl be based on nlh flags??
* Aha! this is anti-netlink really i.e more pfkey derived
* in netlink excl is a flag and you wouldnt need
* a type XFRM_MSG_UPDPOLICY - JHS */
excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
err = xfrm_policy_insert(p->dir, xp, excl);
security_task_getsecid(current, &sid);
xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid);
if (err) {
security_xfrm_policy_free(xp->security);
kfree(xp);
return err;
}
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
xfrm_pol_put(xp);
return 0;
}
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
{
struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
int i;
if (xp->xfrm_nr == 0)
return 0;
for (i = 0; i < xp->xfrm_nr; i++) {
struct xfrm_user_tmpl *up = &vec[i];
struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
memcpy(&up->id, &kp->id, sizeof(up->id));
up->family = kp->encap_family;
memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
up->reqid = kp->reqid;
up->mode = kp->mode;
up->share = kp->share;
up->optional = kp->optional;
up->aalgos = kp->aalgos;
up->ealgos = kp->ealgos;
up->calgos = kp->calgos;
}
return nla_put(skb, XFRMA_TMPL,
sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
}
static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
{
if (x->security) {
return copy_sec_ctx(x->security, skb);
}
return 0;
}
static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
{
if (xp->security)
return copy_sec_ctx(xp->security, skb);
return 0;
}
static inline size_t userpolicy_type_attrsize(void)
{
#ifdef CONFIG_XFRM_SUB_POLICY
return nla_total_size(sizeof(struct xfrm_userpolicy_type));
#else
return 0;
#endif
}
#ifdef CONFIG_XFRM_SUB_POLICY
static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
struct xfrm_userpolicy_type upt = {
.type = type,
};
return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
}
#else
static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
return 0;
}
#endif
static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct xfrm_userpolicy_info *p;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_policy_done(struct netlink_callback *cb)
{
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
xfrm_policy_walk_done(walk);
return 0;
}
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
struct xfrm_policy *xp,
int dir, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_policy(xp, dir, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_userpolicy_id *p;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct km_event c;
int delete;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
p = nlmsg_data(nlh);
delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel,
ctx, delete, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (!delete) {
struct sk_buff *resp_skb;
resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
NETLINK_CB(skb).pid);
}
} else {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid,
sid);
if (err != 0)
goto out;
c.data.byid = p->index;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
}
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
struct xfrm_usersa_flush *p = nlmsg_data(nlh);
struct xfrm_audit audit_info;
int err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_state_flush(net, p->proto, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.proto = p->proto;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x)
{
size_t replay_size = x->replay_esn ?
xfrm_replay_state_esn_len(x->replay_esn) :
sizeof(struct xfrm_replay_state);
return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
+ nla_total_size(replay_size)
+ nla_total_size(sizeof(struct xfrm_lifetime_cur))
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(4) /* XFRM_AE_RTHR */
+ nla_total_size(4); /* XFRM_AE_ETHR */
}
static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_aevent_id *id;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
if (nlh == NULL)
return -EMSGSIZE;
id = nlmsg_data(nlh);
memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr));
id->sa_id.spi = x->id.spi;
id->sa_id.family = x->props.family;
id->sa_id.proto = x->id.proto;
memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr));
id->reqid = x->props.reqid;
id->flags = c->data.aevent;
if (x->replay_esn) {
err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
} else {
err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
&x->replay);
}
if (err)
goto out_cancel;
err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft);
if (err)
goto out_cancel;
if (id->flags & XFRM_AE_RTHR) {
err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
if (err)
goto out_cancel;
}
if (id->flags & XFRM_AE_ETHR) {
err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
x->replay_maxage * 10 / HZ);
if (err)
goto out_cancel;
}
err = xfrm_mark_put(skb, &x->mark);
if (err)
goto out_cancel;
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct sk_buff *r_skb;
int err;
struct km_event c;
u32 mark;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct xfrm_usersa_id *id = &p->sa_id;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
if (x == NULL)
return -ESRCH;
r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (r_skb == NULL) {
xfrm_state_put(x);
return -ENOMEM;
}
/*
* XXX: is this lock really needed - none of the other
* gets lock (the concern is things getting updated
* while we are still reading) - jhs
*/
spin_lock_bh(&x->lock);
c.data.aevent = p->flags;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
if (build_aevent(r_skb, x, &c) < 0)
BUG();
err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid);
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct km_event c;
int err = - EINVAL;
u32 mark = 0;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
if (!lt && !rp && !re)
return err;
/* pedantic mode - thou shalt sayeth replaceth */
if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
return err;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
if (x == NULL)
return -ESRCH;
if (x->km.state != XFRM_STATE_VALID)
goto out;
err = xfrm_replay_verify_len(x->replay_esn, rp);
if (err)
goto out;
spin_lock_bh(&x->lock);
xfrm_update_ae_params(x, attrs);
spin_unlock_bh(&x->lock);
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.data.aevent = XFRM_AE_CU;
km_state_notify(x, &c);
err = 0;
out:
xfrm_state_put(x);
return err;
}
static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct xfrm_audit audit_info;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_policy_flush(net, type, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.type = type;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_polexpire *up = nlmsg_data(nlh);
struct xfrm_userpolicy_info *p = &up->pol;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err = -ENOENT;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir,
&p->sel, ctx, 0, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (unlikely(xp->walk.dead))
goto out;
err = 0;
if (up->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_policy_delete(xp, p->dir);
xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid);
} else {
// reset the timers here?
WARN(1, "Dont know what to do with soft policy expire\n");
}
km_policy_expired(xp, p->dir, up->hard, current->pid);
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err;
struct xfrm_user_expire *ue = nlmsg_data(nlh);
struct xfrm_usersa_info *p = &ue->state;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
err = -ENOENT;
if (x == NULL)
return err;
spin_lock_bh(&x->lock);
err = -EINVAL;
if (x->km.state != XFRM_STATE_VALID)
goto out;
km_state_expired(x, ue->hard, current->pid);
if (ue->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
__xfrm_state_delete(x);
xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid);
}
err = 0;
out:
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_tmpl *ut;
int i;
struct nlattr *rt = attrs[XFRMA_TMPL];
struct xfrm_mark mark;
struct xfrm_user_acquire *ua = nlmsg_data(nlh);
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto nomem;
xfrm_mark_get(attrs, &mark);
err = verify_newpolicy_info(&ua->policy);
if (err)
goto bad_policy;
/* build an XP */
xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
if (!xp)
goto free_state;
memcpy(&x->id, &ua->id, sizeof(ua->id));
memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
xp->mark.m = x->mark.m = mark.m;
xp->mark.v = x->mark.v = mark.v;
ut = nla_data(rt);
/* extract the templates and for each call km_key */
for (i = 0; i < xp->xfrm_nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&x->id, &t->id, sizeof(x->id));
x->props.mode = t->mode;
x->props.reqid = t->reqid;
x->props.family = ut->family;
t->aalgos = ua->aalgos;
t->ealgos = ua->ealgos;
t->calgos = ua->calgos;
err = km_query(x, t, xp);
}
kfree(x);
kfree(xp);
return 0;
bad_policy:
WARN(1, "BAD policy passed\n");
free_state:
kfree(x);
nomem:
return err;
}
#ifdef CONFIG_XFRM_MIGRATE
static int copy_from_user_migrate(struct xfrm_migrate *ma,
struct xfrm_kmaddress *k,
struct nlattr **attrs, int *num)
{
struct nlattr *rt = attrs[XFRMA_MIGRATE];
struct xfrm_user_migrate *um;
int i, num_migrate;
if (k != NULL) {
struct xfrm_user_kmaddress *uk;
uk = nla_data(attrs[XFRMA_KMADDRESS]);
memcpy(&k->local, &uk->local, sizeof(k->local));
memcpy(&k->remote, &uk->remote, sizeof(k->remote));
k->family = uk->family;
k->reserved = uk->reserved;
}
um = nla_data(rt);
num_migrate = nla_len(rt) / sizeof(*um);
if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++, um++, ma++) {
memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
ma->proto = um->proto;
ma->mode = um->mode;
ma->reqid = um->reqid;
ma->old_family = um->old_family;
ma->new_family = um->new_family;
}
*num = i;
return 0;
}
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress km, *kmp;
u8 type;
int err;
int n = 0;
if (attrs[XFRMA_MIGRATE] == NULL)
return -EINVAL;
kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
if (err)
return err;
if (!n)
return 0;
xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp);
return 0;
}
#else
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
return -ENOPROTOOPT;
}
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
{
struct xfrm_user_migrate um;
memset(&um, 0, sizeof(um));
um.proto = m->proto;
um.mode = m->mode;
um.reqid = m->reqid;
um.old_family = m->old_family;
memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
um.new_family = m->new_family;
memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
}
static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
{
struct xfrm_user_kmaddress uk;
memset(&uk, 0, sizeof(uk));
uk.family = k->family;
uk.reserved = k->reserved;
memcpy(&uk.local, &k->local, sizeof(uk.local));
memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
}
static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma)
{
return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
+ (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
+ nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
+ userpolicy_type_attrsize();
}
static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
int num_migrate, const struct xfrm_kmaddress *k,
const struct xfrm_selector *sel, u8 dir, u8 type)
{
const struct xfrm_migrate *mp;
struct xfrm_userpolicy_id *pol_id;
struct nlmsghdr *nlh;
int i, err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
if (nlh == NULL)
return -EMSGSIZE;
pol_id = nlmsg_data(nlh);
/* copy data from selector, dir, and type to the pol_id */
memset(pol_id, 0, sizeof(*pol_id));
memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
pol_id->dir = dir;
if (k != NULL) {
err = copy_to_user_kmaddress(k, skb);
if (err)
goto out_cancel;
}
err = copy_to_user_policy_type(type, skb);
if (err)
goto out_cancel;
for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
err = copy_to_user_migrate(mp, skb);
if (err)
goto out_cancel;
}
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
struct net *net = &init_net;
struct sk_buff *skb;
skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
/* build migrate */
if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC);
}
#else
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
#define XMSGSIZE(type) sizeof(struct type)
static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32),
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32),
};
#undef XMSGSIZE
static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
[XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)},
[XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)},
[XFRMA_LASTUSED] = { .type = NLA_U64},
[XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)},
[XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) },
[XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) },
[XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) },
[XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) },
[XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) },
[XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) },
[XFRMA_REPLAY_THRESH] = { .type = NLA_U32 },
[XFRMA_ETIMER_THRESH] = { .type = NLA_U32 },
[XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)},
[XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) },
[XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) },
[XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) },
[XFRMA_TFCPAD] = { .type = NLA_U32 },
[XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) },
};
static struct xfrm_link {
int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
int (*dump)(struct sk_buff *, struct netlink_callback *);
int (*done)(struct netlink_callback *);
} xfrm_dispatch[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa },
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
.dump = xfrm_dump_sa,
.done = xfrm_dump_sa_done },
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy },
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
.dump = xfrm_dump_policy,
.done = xfrm_dump_policy_done },
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire },
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa },
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy },
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae },
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae },
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate },
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo },
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo },
};
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
struct xfrm_link *link;
int type, err;
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,
xfrma_policy);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
static void xfrm_netlink_rcv(struct sk_buff *skb)
{
mutex_lock(&xfrm_cfg_mutex);
netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
mutex_unlock(&xfrm_cfg_mutex);
}
static inline size_t xfrm_expire_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
+ nla_total_size(sizeof(struct xfrm_mark));
}
static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
err = xfrm_mark_put(skb, &x->mark);
if (err)
return err;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_expire(skb, x, c) < 0) {
kfree_skb(skb);
return -EMSGSIZE;
}
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
static int xfrm_notify_sa_flush(const struct km_event *c)
{
struct net *net = c->net;
struct xfrm_usersa_flush *p;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
if (nlh == NULL) {
kfree_skb(skb);
return -EMSGSIZE;
}
p = nlmsg_data(nlh);
p->proto = c->data.proto;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
}
static inline size_t xfrm_sa_len(struct xfrm_state *x)
{
size_t l = 0;
if (x->aead)
l += nla_total_size(aead_len(x->aead));
if (x->aalg) {
l += nla_total_size(sizeof(struct xfrm_algo) +
(x->aalg->alg_key_len + 7) / 8);
l += nla_total_size(xfrm_alg_auth_len(x->aalg));
}
if (x->ealg)
l += nla_total_size(xfrm_alg_len(x->ealg));
if (x->calg)
l += nla_total_size(sizeof(*x->calg));
if (x->encap)
l += nla_total_size(sizeof(*x->encap));
if (x->tfcpad)
l += nla_total_size(sizeof(x->tfcpad));
if (x->replay_esn)
l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
if (x->security)
l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
x->security->ctx_len);
if (x->coaddr)
l += nla_total_size(sizeof(*x->coaddr));
/* Must count x->lastused as it may become non-zero behind our back. */
l += nla_total_size(sizeof(u64));
return l;
}
static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct xfrm_usersa_info *p;
struct xfrm_usersa_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = xfrm_sa_len(x);
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELSA) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
len += nla_total_size(sizeof(struct xfrm_mark));
}
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELSA) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
id->spi = x->id.spi;
id->family = x->props.family;
id->proto = x->id.proto;
attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
err = copy_to_user_state_extra(x, p, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_EXPIRE:
return xfrm_exp_state_notify(x, c);
case XFRM_MSG_NEWAE:
return xfrm_aevent_state_notify(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_UPDSA:
case XFRM_MSG_NEWSA:
return xfrm_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return xfrm_notify_sa_flush(c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
c->event);
break;
}
return 0;
}
static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x,
struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(xfrm_user_sec_ctx_size(x->security))
+ userpolicy_type_attrsize();
}
static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
struct xfrm_tmpl *xt, struct xfrm_policy *xp,
int dir)
{
__u32 seq = xfrm_get_acqseq();
struct xfrm_user_acquire *ua;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
if (nlh == NULL)
return -EMSGSIZE;
ua = nlmsg_data(nlh);
memcpy(&ua->id, &x->id, sizeof(ua->id));
memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
copy_to_user_policy(xp, &ua->policy, dir);
ua->aalgos = xt->aalgos;
ua->ealgos = xt->ealgos;
ua->calgos = xt->calgos;
ua->seq = x->km.seq = seq;
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_state_sec_ctx(x, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
struct xfrm_policy *xp, int dir)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_acquire(skb, x, xt, xp, dir) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC);
}
/* User gives us xfrm_user_policy_info followed by an array of 0
* or more templates.
*/
static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
struct xfrm_policy *xp;
int nr;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
if (opt != IPV6_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(*p) ||
verify_newpolicy_info(p))
return NULL;
nr = ((len - sizeof(*p)) / sizeof(*ut));
if (validate_tmpl(nr, ut, p->sel.family))
return NULL;
if (p->dir > XFRM_POLICY_OUT)
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
copy_from_user_policy(xp, p);
xp->type = XFRM_POLICY_TYPE_MAIN;
copy_templates(xp, ut, nr);
*dir = p->dir;
return xp;
}
static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(xfrm_user_sec_ctx_size(xp->security))
+ nla_total_size(sizeof(struct xfrm_mark))
+ userpolicy_type_attrsize();
}
static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
int dir, const struct km_event *c)
{
struct xfrm_user_polexpire *upe;
int hard = c->data.hard;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
if (nlh == NULL)
return -EMSGSIZE;
upe = nlmsg_data(nlh);
copy_to_user_policy(xp, &upe->pol, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
upe->hard = !!hard;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_polexpire(skb, xp, dir, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
struct net *net = xp_net(xp);
struct xfrm_userpolicy_info *p;
struct xfrm_userpolicy_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELPOLICY) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
}
len += userpolicy_type_attrsize();
len += nla_total_size(sizeof(struct xfrm_mark));
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELPOLICY) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memset(id, 0, sizeof(*id));
id->dir = dir;
if (c->data.byid)
id->index = xp->index;
else
memcpy(&id->sel, &xp->selector, sizeof(id->sel));
attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_notify_policy_flush(const struct km_event *c)
{
struct net *net = c->net;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int err;
skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
err = copy_to_user_policy_type(c->data.type, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
case XFRM_MSG_DELPOLICY:
return xfrm_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
return xfrm_notify_policy_flush(c);
case XFRM_MSG_POLEXPIRE:
return xfrm_exp_policy_notify(xp, dir, c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
c->event);
}
return 0;
}
static inline size_t xfrm_report_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
}
static int build_report(struct sk_buff *skb, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct xfrm_user_report *ur;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
if (nlh == NULL)
return -EMSGSIZE;
ur = nlmsg_data(nlh);
ur->proto = proto;
memcpy(&ur->sel, sel, sizeof(ur->sel));
if (addr) {
int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_report(struct net *net, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct sk_buff *skb;
skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_report(skb, proto, sel, addr) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC);
}
static inline size_t xfrm_mapping_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
}
static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
xfrm_address_t *new_saddr, __be16 new_sport)
{
struct xfrm_user_mapping *um;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
if (nlh == NULL)
return -EMSGSIZE;
um = nlmsg_data(nlh);
memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
um->id.spi = x->id.spi;
um->id.family = x->props.family;
um->id.proto = x->id.proto;
memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
um->new_sport = new_sport;
um->old_sport = x->encap->encap_sport;
um->reqid = x->props.reqid;
return nlmsg_end(skb, nlh);
}
static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
__be16 sport)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
if (x->id.proto != IPPROTO_ESP)
return -EINVAL;
if (!x->encap)
return -EINVAL;
skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_mapping(skb, x, ipaddr, sport) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC);
}
static struct xfrm_mgr netlink_mgr = {
.id = "netlink",
.notify = xfrm_send_state_notify,
.acquire = xfrm_send_acquire,
.compile_policy = xfrm_compile_policy,
.notify_policy = xfrm_send_policy_notify,
.report = xfrm_send_report,
.migrate = xfrm_send_migrate,
.new_mapping = xfrm_send_mapping,
};
static int __net_init xfrm_user_net_init(struct net *net)
{
struct sock *nlsk;
struct netlink_kernel_cfg cfg = {
.groups = XFRMNLGRP_MAX,
.input = xfrm_netlink_rcv,
};
nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg);
if (nlsk == NULL)
return -ENOMEM;
net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
rcu_assign_pointer(net->xfrm.nlsk, nlsk);
return 0;
}
static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->xfrm.nlsk_stash);
}
static struct pernet_operations xfrm_user_net_ops = {
.init = xfrm_user_net_init,
.exit_batch = xfrm_user_net_exit,
};
static int __init xfrm_user_init(void)
{
int rv;
printk(KERN_INFO "Initializing XFRM netlink socket\n");
rv = register_pernet_subsys(&xfrm_user_net_ops);
if (rv < 0)
return rv;
rv = xfrm_register_km(&netlink_mgr);
if (rv < 0)
unregister_pernet_subsys(&xfrm_user_net_ops);
return rv;
}
static void __exit xfrm_user_exit(void)
{
xfrm_unregister_km(&netlink_mgr);
unregister_pernet_subsys(&xfrm_user_net_ops);
}
module_init(xfrm_user_init);
module_exit(xfrm_user_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3823_0 |
crossvul-cpp_data_bad_837_0 | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
* Written by Alex Tomas <alex@clusterfs.com>
*
* Architecture independence:
* Copyright (c) 2005, Bull S.A.
* Written by Pierre Peiffer <pierre.peiffer@bull.net>
*/
/*
* Extents support for EXT4
*
* TODO:
* - ext4*_error() should be used in some situations
* - analyze all BUG()/BUG_ON(), use -EIO where appropriate
* - smart tree reduction
*/
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/jbd2.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/fiemap.h>
#include <linux/backing-dev.h>
#include "ext4_jbd2.h"
#include "ext4_extents.h"
#include "xattr.h"
#include <trace/events/ext4.h>
/*
* used by extent splitting.
*/
#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
due to ENOSPC */
#define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
#define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
#define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
#define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
static __le32 ext4_extent_block_csum(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
EXT4_EXTENT_TAIL_OFFSET(eh));
return cpu_to_le32(csum);
}
static int ext4_extent_block_csum_verify(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
et = find_ext4_extent_tail(eh);
if (et->et_checksum != ext4_extent_block_csum(inode, eh))
return 0;
return 1;
}
static void ext4_extent_block_csum_set(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
et = find_ext4_extent_tail(eh);
et->et_checksum = ext4_extent_block_csum(inode, eh);
}
static int ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags);
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags);
static int ext4_find_delayed_extent(struct inode *inode,
struct extent_status *newes);
static int ext4_ext_truncate_extend_restart(handle_t *handle,
struct inode *inode,
int needed)
{
int err;
if (!ext4_handle_valid(handle))
return 0;
if (handle->h_buffer_credits >= needed)
return 0;
/*
* If we need to extend the journal get a few extra blocks
* while we're at it for efficiency's sake.
*/
needed += 3;
err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
if (err <= 0)
return err;
err = ext4_truncate_restart_trans(handle, inode, needed);
if (err == 0)
err = -EAGAIN;
return err;
}
/*
* could return:
* - EROFS
* - ENOMEM
*/
static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
if (path->p_bh) {
/* path points to block */
BUFFER_TRACE(path->p_bh, "get_write_access");
return ext4_journal_get_write_access(handle, path->p_bh);
}
/* path points to leaf/index in inode body */
/* we use in-core data, no need to protect them */
return 0;
}
/*
* could return:
* - EROFS
* - ENOMEM
* - EIO
*/
int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
struct inode *inode, struct ext4_ext_path *path)
{
int err;
WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
if (path->p_bh) {
ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
/* path points to block */
err = __ext4_handle_dirty_metadata(where, line, handle,
inode, path->p_bh);
} else {
/* path points to leaf/index in inode body */
err = ext4_mark_inode_dirty(handle, inode);
}
return err;
}
static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t block)
{
if (path) {
int depth = path->p_depth;
struct ext4_extent *ex;
/*
* Try to predict block placement assuming that we are
* filling in a file which will eventually be
* non-sparse --- i.e., in the case of libbfd writing
* an ELF object sections out-of-order but in a way
* the eventually results in a contiguous object or
* executable file, or some database extending a table
* space file. However, this is actually somewhat
* non-ideal if we are writing a sparse file such as
* qemu or KVM writing a raw image file that is going
* to stay fairly sparse, since it will end up
* fragmenting the file system's free space. Maybe we
* should have some hueristics or some way to allow
* userspace to pass a hint to file system,
* especially if the latter case turns out to be
* common.
*/
ex = path[depth].p_ext;
if (ex) {
ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
if (block > ext_block)
return ext_pblk + (block - ext_block);
else
return ext_pblk - (ext_block - block);
}
/* it looks like index is empty;
* try to find starting block from index itself */
if (path[depth].p_bh)
return path[depth].p_bh->b_blocknr;
}
/* OK. use inode's group */
return ext4_inode_to_goal_block(inode);
}
/*
* Allocation for a meta data block
*/
static ext4_fsblk_t
ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex, int *err, unsigned int flags)
{
ext4_fsblk_t goal, newblock;
goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, err);
return newblock;
}
static inline int ext4_ext_space_block(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 6)
size = 6;
#endif
return size;
}
static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 5)
size = 5;
#endif
return size;
}
static inline int ext4_ext_space_root(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 3)
size = 3;
#endif
return size;
}
static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 4)
size = 4;
#endif
return size;
}
static inline int
ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath, ext4_lblk_t lblk,
int nofail)
{
struct ext4_ext_path *path = *ppath;
int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
(nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
}
/*
* Calculate the number of metadata blocks needed
* to allocate @blocks
* Worse case is one block per extent
*/
int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
{
struct ext4_inode_info *ei = EXT4_I(inode);
int idxs;
idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent_idx));
/*
* If the new delayed allocation block is contiguous with the
* previous da block, it can share index blocks with the
* previous block, so we only need to allocate a new index
* block every idxs leaf blocks. At ldxs**2 blocks, we need
* an additional index block, and at ldxs**3 blocks, yet
* another index blocks.
*/
if (ei->i_da_metadata_calc_len &&
ei->i_da_metadata_calc_last_lblock+1 == lblock) {
int num = 0;
if ((ei->i_da_metadata_calc_len % idxs) == 0)
num++;
if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
num++;
if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
num++;
ei->i_da_metadata_calc_len = 0;
} else
ei->i_da_metadata_calc_len++;
ei->i_da_metadata_calc_last_lblock++;
return num;
}
/*
* In the worst case we need a new set of index blocks at
* every level of the inode's extent tree.
*/
ei->i_da_metadata_calc_len = 1;
ei->i_da_metadata_calc_last_lblock = lblock;
return ext_depth(inode) + 1;
}
static int
ext4_ext_max_entries(struct inode *inode, int depth)
{
int max;
if (depth == ext_depth(inode)) {
if (depth == 0)
max = ext4_ext_space_root(inode, 1);
else
max = ext4_ext_space_root_idx(inode, 1);
} else {
if (depth == 0)
max = ext4_ext_space_block(inode, 1);
else
max = ext4_ext_space_block_idx(inode, 1);
}
return max;
}
static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
{
ext4_fsblk_t block = ext4_ext_pblock(ext);
int len = ext4_ext_get_actual_len(ext);
ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
/*
* We allow neither:
* - zero length
* - overflow/wrap-around
*/
if (lblock + len <= lblock)
return 0;
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
}
static int ext4_valid_extent_idx(struct inode *inode,
struct ext4_extent_idx *ext_idx)
{
ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
}
static int ext4_valid_extent_entries(struct inode *inode,
struct ext4_extent_header *eh,
int depth)
{
unsigned short entries;
if (eh->eh_entries == 0)
return 1;
entries = le16_to_cpu(eh->eh_entries);
if (depth == 0) {
/* leaf entries */
struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
ext4_fsblk_t pblock = 0;
ext4_lblk_t lblock = 0;
ext4_lblk_t prev = 0;
int len = 0;
while (entries) {
if (!ext4_valid_extent(inode, ext))
return 0;
/* Check for overlapping extents */
lblock = le32_to_cpu(ext->ee_block);
len = ext4_ext_get_actual_len(ext);
if ((lblock <= prev) && prev) {
pblock = ext4_ext_pblock(ext);
es->s_last_error_block = cpu_to_le64(pblock);
return 0;
}
ext++;
entries--;
prev = lblock + len - 1;
}
} else {
struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
while (entries) {
if (!ext4_valid_extent_idx(inode, ext_idx))
return 0;
ext_idx++;
entries--;
}
}
return 1;
}
static int __ext4_ext_check(const char *function, unsigned int line,
struct inode *inode, struct ext4_extent_header *eh,
int depth, ext4_fsblk_t pblk)
{
const char *error_msg;
int max = 0, err = -EFSCORRUPTED;
if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
error_msg = "invalid magic";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
error_msg = "unexpected eh_depth";
goto corrupted;
}
if (unlikely(eh->eh_max == 0)) {
error_msg = "invalid eh_max";
goto corrupted;
}
max = ext4_ext_max_entries(inode, depth);
if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
error_msg = "too large eh_max";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
error_msg = "invalid eh_entries";
goto corrupted;
}
if (!ext4_valid_extent_entries(inode, eh, depth)) {
error_msg = "invalid extent entries";
goto corrupted;
}
if (unlikely(depth > 32)) {
error_msg = "too large eh_depth";
goto corrupted;
}
/* Verify checksum on non-root extent tree nodes */
if (ext_depth(inode) != depth &&
!ext4_extent_block_csum_verify(inode, eh)) {
error_msg = "extent tree corrupted";
err = -EFSBADCRC;
goto corrupted;
}
return 0;
corrupted:
ext4_error_inode(inode, function, line, 0,
"pblk %llu bad header/extent: %s - magic %x, "
"entries %u, max %u(%u), depth %u(%u)",
(unsigned long long) pblk, error_msg,
le16_to_cpu(eh->eh_magic),
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
max, le16_to_cpu(eh->eh_depth), depth);
return err;
}
#define ext4_ext_check(inode, eh, depth, pblk) \
__ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
int ext4_ext_check_inode(struct inode *inode)
{
return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
}
static struct buffer_head *
__read_extent_tree_block(const char *function, unsigned int line,
struct inode *inode, ext4_fsblk_t pblk, int depth,
int flags)
{
struct buffer_head *bh;
int err;
bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return ERR_PTR(-ENOMEM);
if (!bh_uptodate_or_lock(bh)) {
trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
err = bh_submit_read(bh);
if (err < 0)
goto errout;
}
if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
return bh;
err = __ext4_ext_check(function, line, inode,
ext_block_hdr(bh), depth, pblk);
if (err)
goto errout;
set_buffer_verified(bh);
/*
* If this is a leaf block, cache all of its entries
*/
if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
struct ext4_extent_header *eh = ext_block_hdr(bh);
struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
ext4_lblk_t prev = 0;
int i;
for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
unsigned int status = EXTENT_STATUS_WRITTEN;
ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
int len = ext4_ext_get_actual_len(ex);
if (prev && (prev != lblk))
ext4_es_cache_extent(inode, prev,
lblk - prev, ~0,
EXTENT_STATUS_HOLE);
if (ext4_ext_is_unwritten(ex))
status = EXTENT_STATUS_UNWRITTEN;
ext4_es_cache_extent(inode, lblk, len,
ext4_ext_pblock(ex), status);
prev = lblk + len;
}
}
return bh;
errout:
put_bh(bh);
return ERR_PTR(err);
}
#define read_extent_tree_block(inode, pblk, depth, flags) \
__read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
(depth), (flags))
/*
* This function is called to cache a file's extent information in the
* extent status tree
*/
int ext4_ext_precache(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_ext_path *path = NULL;
struct buffer_head *bh;
int i = 0, depth, ret = 0;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return 0; /* not an extent-mapped inode */
down_read(&ei->i_data_sem);
depth = ext_depth(inode);
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (path == NULL) {
up_read(&ei->i_data_sem);
return -ENOMEM;
}
/* Don't cache anything if there are no external extent blocks */
if (depth == 0)
goto out;
path[0].p_hdr = ext_inode_hdr(inode);
ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
if (ret)
goto out;
path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
while (i >= 0) {
/*
* If this is a leaf block or we've reached the end of
* the index block, go up
*/
if ((i == depth) ||
path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
bh = read_extent_tree_block(inode,
ext4_idx_pblock(path[i].p_idx++),
depth - i - 1,
EXT4_EX_FORCE_CACHE);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
break;
}
i++;
path[i].p_bh = bh;
path[i].p_hdr = ext_block_hdr(bh);
path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
}
ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
out:
up_read(&ei->i_data_sem);
ext4_ext_drop_refs(path);
kfree(path);
return ret;
}
#ifdef EXT_DEBUG
static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
{
int k, l = path->p_depth;
ext_debug("path:");
for (k = 0; k <= l; k++, path++) {
if (path->p_idx) {
ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
} else if (path->p_ext) {
ext_debug(" %d:[%d]%d:%llu ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext),
ext4_ext_pblock(path->p_ext));
} else
ext_debug(" []");
}
ext_debug("\n");
}
static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
{
int depth = ext_depth(inode);
struct ext4_extent_header *eh;
struct ext4_extent *ex;
int i;
if (!path)
return;
eh = path[depth].p_hdr;
ex = EXT_FIRST_EXTENT(eh);
ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
}
ext_debug("\n");
}
static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
ext4_fsblk_t newblock, int level)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
if (depth != level) {
struct ext4_extent_idx *idx;
idx = path[level].p_idx;
while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
ext_debug("%d: move %d:%llu in new index %llu\n", level,
le32_to_cpu(idx->ei_block),
ext4_idx_pblock(idx),
newblock);
idx++;
}
return;
}
ex = path[depth].p_ext;
while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
le32_to_cpu(ex->ee_block),
ext4_ext_pblock(ex),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
newblock);
ex++;
}
}
#else
#define ext4_ext_show_path(inode, path)
#define ext4_ext_show_leaf(inode, path)
#define ext4_ext_show_move(inode, path, newblock, level)
#endif
void ext4_ext_drop_refs(struct ext4_ext_path *path)
{
int depth, i;
if (!path)
return;
depth = path->p_depth;
for (i = 0; i <= depth; i++, path++)
if (path->p_bh) {
brelse(path->p_bh);
path->p_bh = NULL;
}
}
/*
* ext4_ext_binsearch_idx:
* binary search for the closest index of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch_idx(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent_idx *r, *l, *m;
ext_debug("binsearch for %u(idx): ", block);
l = EXT_FIRST_INDEX(eh) + 1;
r = EXT_LAST_INDEX(eh);
while (l <= r) {
m = l + (r - l) / 2;
if (block < le32_to_cpu(m->ei_block))
r = m - 1;
else
l = m + 1;
ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
m, le32_to_cpu(m->ei_block),
r, le32_to_cpu(r->ei_block));
}
path->p_idx = l - 1;
ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent_idx *chix, *ix;
int k;
chix = ix = EXT_FIRST_INDEX(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
if (k != 0 &&
le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
printk(KERN_DEBUG "k=%d, ix=0x%p, "
"first=0x%p\n", k,
ix, EXT_FIRST_INDEX(eh));
printk(KERN_DEBUG "%u <= %u\n",
le32_to_cpu(ix->ei_block),
le32_to_cpu(ix[-1].ei_block));
}
BUG_ON(k && le32_to_cpu(ix->ei_block)
<= le32_to_cpu(ix[-1].ei_block));
if (block < le32_to_cpu(ix->ei_block))
break;
chix = ix;
}
BUG_ON(chix != path->p_idx);
}
#endif
}
/*
* ext4_ext_binsearch:
* binary search for closest extent of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent *r, *l, *m;
if (eh->eh_entries == 0) {
/*
* this leaf is empty:
* we get such a leaf in split/add case
*/
return;
}
ext_debug("binsearch for %u: ", block);
l = EXT_FIRST_EXTENT(eh) + 1;
r = EXT_LAST_EXTENT(eh);
while (l <= r) {
m = l + (r - l) / 2;
if (block < le32_to_cpu(m->ee_block))
r = m - 1;
else
l = m + 1;
ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
m, le32_to_cpu(m->ee_block),
r, le32_to_cpu(r->ee_block));
}
path->p_ext = l - 1;
ext_debug(" -> %d:%llu:[%d]%d ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_pblock(path->p_ext),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent *chex, *ex;
int k;
chex = ex = EXT_FIRST_EXTENT(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
BUG_ON(k && le32_to_cpu(ex->ee_block)
<= le32_to_cpu(ex[-1].ee_block));
if (block < le32_to_cpu(ex->ee_block))
break;
chex = ex;
}
BUG_ON(chex != path->p_ext);
}
#endif
}
int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
{
struct ext4_extent_header *eh;
eh = ext_inode_hdr(inode);
eh->eh_depth = 0;
eh->eh_entries = 0;
eh->eh_magic = EXT4_EXT_MAGIC;
eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
ext4_mark_inode_dirty(handle, inode);
return 0;
}
struct ext4_ext_path *
ext4_find_extent(struct inode *inode, ext4_lblk_t block,
struct ext4_ext_path **orig_path, int flags)
{
struct ext4_extent_header *eh;
struct buffer_head *bh;
struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
short int depth, i, ppos = 0;
int ret;
eh = ext_inode_hdr(inode);
depth = ext_depth(inode);
if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
depth);
ret = -EFSCORRUPTED;
goto err;
}
if (path) {
ext4_ext_drop_refs(path);
if (depth > path[0].p_maxdepth) {
kfree(path);
*orig_path = path = NULL;
}
}
if (!path) {
/* account possible depth increase */
path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (unlikely(!path))
return ERR_PTR(-ENOMEM);
path[0].p_maxdepth = depth + 1;
}
path[0].p_hdr = eh;
path[0].p_bh = NULL;
i = depth;
/* walk through the tree */
while (i) {
ext_debug("depth %d: num %d, max %d\n",
ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
ext4_ext_binsearch_idx(inode, path + ppos, block);
path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
flags);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
goto err;
}
eh = ext_block_hdr(bh);
ppos++;
path[ppos].p_bh = bh;
path[ppos].p_hdr = eh;
}
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
path[ppos].p_idx = NULL;
/* find extent */
ext4_ext_binsearch(inode, path + ppos, block);
/* if not an empty leaf */
if (path[ppos].p_ext)
path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
ext4_ext_show_path(inode, path);
return path;
err:
ext4_ext_drop_refs(path);
kfree(path);
if (orig_path)
*orig_path = NULL;
return ERR_PTR(ret);
}
/*
* ext4_ext_insert_index:
* insert new index [@logical;@ptr] into the block at @curp;
* check where to insert: before @curp or after @curp
*/
static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
struct ext4_ext_path *curp,
int logical, ext4_fsblk_t ptr)
{
struct ext4_extent_idx *ix;
int len, err;
err = ext4_ext_get_access(handle, inode, curp);
if (err)
return err;
if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
EXT4_ERROR_INODE(inode,
"logical %d == ei_block %d!",
logical, le32_to_cpu(curp->p_idx->ei_block));
return -EFSCORRUPTED;
}
if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
>= le16_to_cpu(curp->p_hdr->eh_max))) {
EXT4_ERROR_INODE(inode,
"eh_entries %d >= eh_max %d!",
le16_to_cpu(curp->p_hdr->eh_entries),
le16_to_cpu(curp->p_hdr->eh_max));
return -EFSCORRUPTED;
}
if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
/* insert after */
ext_debug("insert new index %d after: %llu\n", logical, ptr);
ix = curp->p_idx + 1;
} else {
/* insert before */
ext_debug("insert new index %d before: %llu\n", logical, ptr);
ix = curp->p_idx;
}
len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
BUG_ON(len < 0);
if (len > 0) {
ext_debug("insert new index %d: "
"move %d indices from 0x%p to 0x%p\n",
logical, len, ix, ix + 1);
memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
}
if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
return -EFSCORRUPTED;
}
ix->ei_block = cpu_to_le32(logical);
ext4_idx_store_pblock(ix, ptr);
le16_add_cpu(&curp->p_hdr->eh_entries, 1);
if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
return -EFSCORRUPTED;
}
err = ext4_ext_dirty(handle, inode, curp);
ext4_std_error(inode->i_sb, err);
return err;
}
/*
* ext4_ext_split:
* inserts new subtree into the path, using free index entry
* at depth @at:
* - allocates all needed blocks (new leaf and all intermediate index blocks)
* - makes decision where to split
* - moves remaining extents and index entries (right to the split point)
* into the newly allocated blocks
* - initializes subtree
*/
static int ext4_ext_split(handle_t *handle, struct inode *inode,
unsigned int flags,
struct ext4_ext_path *path,
struct ext4_extent *newext, int at)
{
struct buffer_head *bh = NULL;
int depth = ext_depth(inode);
struct ext4_extent_header *neh;
struct ext4_extent_idx *fidx;
int i = at, k, m, a;
ext4_fsblk_t newblock, oldblock;
__le32 border;
ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
int err = 0;
/* make decision: where to split? */
/* FIXME: now decision is simplest: at current extent */
/* if current leaf will be split, then we should use
* border from split point */
if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
return -EFSCORRUPTED;
}
if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
border = path[depth].p_ext[1].ee_block;
ext_debug("leaf will be split."
" next leaf starts at %d\n",
le32_to_cpu(border));
} else {
border = newext->ee_block;
ext_debug("leaf will be added."
" next leaf starts at %d\n",
le32_to_cpu(border));
}
/*
* If error occurs, then we break processing
* and mark filesystem read-only. index won't
* be inserted and tree will be in consistent
* state. Next mount will repair buffers too.
*/
/*
* Get array to track all allocated blocks.
* We need this to handle errors and free blocks
* upon them.
*/
ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
if (!ablocks)
return -ENOMEM;
/* allocate all needed blocks */
ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
for (a = 0; a < depth - at; a++) {
newblock = ext4_ext_new_meta_block(handle, inode, path,
newext, &err, flags);
if (newblock == 0)
goto cleanup;
ablocks[a] = newblock;
}
/* initialize new leaf */
newblock = ablocks[--a];
if (unlikely(newblock == 0)) {
EXT4_ERROR_INODE(inode, "newblock == 0!");
err = -EFSCORRUPTED;
goto cleanup;
}
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = 0;
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_depth = 0;
/* move remainder of path[depth] to the new leaf */
if (unlikely(path[depth].p_hdr->eh_entries !=
path[depth].p_hdr->eh_max)) {
EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
path[depth].p_hdr->eh_entries,
path[depth].p_hdr->eh_max);
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy from next extent */
m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
ext4_ext_show_move(inode, path, newblock, depth);
if (m) {
struct ext4_extent *ex;
ex = EXT_FIRST_EXTENT(neh);
memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
le16_add_cpu(&neh->eh_entries, m);
}
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old leaf */
if (m) {
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto cleanup;
}
/* create intermediate indexes */
k = depth - at - 1;
if (unlikely(k < 0)) {
EXT4_ERROR_INODE(inode, "k %d < 0!", k);
err = -EFSCORRUPTED;
goto cleanup;
}
if (k)
ext_debug("create %d intermediate indices\n", k);
/* insert new index into current index block */
/* current depth stored in i var */
i = depth - 1;
while (k--) {
oldblock = newblock;
newblock = ablocks[--a];
bh = sb_getblk(inode->i_sb, newblock);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = cpu_to_le16(1);
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
neh->eh_depth = cpu_to_le16(depth - i);
fidx = EXT_FIRST_INDEX(neh);
fidx->ei_block = border;
ext4_idx_store_pblock(fidx, oldblock);
ext_debug("int.index at %d (block %llu): %u -> %llu\n",
i, newblock, le32_to_cpu(border), oldblock);
/* move remainder of path[i] to the new index block */
if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
EXT_LAST_INDEX(path[i].p_hdr))) {
EXT4_ERROR_INODE(inode,
"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
le32_to_cpu(path[i].p_ext->ee_block));
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy indexes */
m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
EXT_MAX_INDEX(path[i].p_hdr));
ext4_ext_show_move(inode, path, newblock, i);
if (m) {
memmove(++fidx, path[i].p_idx,
sizeof(struct ext4_extent_idx) * m);
le16_add_cpu(&neh->eh_entries, m);
}
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old index */
if (m) {
err = ext4_ext_get_access(handle, inode, path + i);
if (err)
goto cleanup;
le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + i);
if (err)
goto cleanup;
}
i--;
}
/* insert new index */
err = ext4_ext_insert_index(handle, inode, path + at,
le32_to_cpu(border), newblock);
cleanup:
if (bh) {
if (buffer_locked(bh))
unlock_buffer(bh);
brelse(bh);
}
if (err) {
/* free all allocated blocks in error case */
for (i = 0; i < depth; i++) {
if (!ablocks[i])
continue;
ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
EXT4_FREE_BLOCKS_METADATA);
}
}
kfree(ablocks);
return err;
}
/*
* ext4_ext_grow_indepth:
* implements tree growing procedure:
* - allocates new block
* - moves top-level data (index block or leaf) into the new block
* - initializes new top-level, creating index that points to the
* just created block
*/
static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
unsigned int flags)
{
struct ext4_extent_header *neh;
struct buffer_head *bh;
ext4_fsblk_t newblock, goal = 0;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
int err = 0;
/* Try to prepend new index to old one */
if (ext_depth(inode))
goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
if (goal > le32_to_cpu(es->s_first_data_block)) {
flags |= EXT4_MB_HINT_TRY_GOAL;
goal--;
} else
goal = ext4_inode_to_goal_block(inode);
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, &err);
if (newblock == 0)
return err;
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return -ENOMEM;
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err) {
unlock_buffer(bh);
goto out;
}
/* move top-level index/leaf into new block */
memmove(bh->b_data, EXT4_I(inode)->i_data,
sizeof(EXT4_I(inode)->i_data));
/* set size of new block */
neh = ext_block_hdr(bh);
/* old root could have indexes or leaves
* so calculate e_max right way */
if (ext_depth(inode))
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
else
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto out;
/* Update top-level index: num,max,pointer */
neh = ext_inode_hdr(inode);
neh->eh_entries = cpu_to_le16(1);
ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
if (neh->eh_depth == 0) {
/* Root extent block becomes index block */
neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
EXT_FIRST_INDEX(neh)->ei_block =
EXT_FIRST_EXTENT(neh)->ee_block;
}
ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
le16_add_cpu(&neh->eh_depth, 1);
ext4_mark_inode_dirty(handle, inode);
out:
brelse(bh);
return err;
}
/*
* ext4_ext_create_new_leaf:
* finds empty index and adds new leaf.
* if no free index is found, then it requests in-depth growing.
*/
static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
unsigned int mb_flags,
unsigned int gb_flags,
struct ext4_ext_path **ppath,
struct ext4_extent *newext)
{
struct ext4_ext_path *path = *ppath;
struct ext4_ext_path *curp;
int depth, i, err = 0;
repeat:
i = depth = ext_depth(inode);
/* walk up to the tree and look for free index entry */
curp = path + depth;
while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
i--;
curp--;
}
/* we use already allocated block for index block,
* so subsequent data blocks should be contiguous */
if (EXT_HAS_FREE_INDEX(curp)) {
/* if we found index with free entry, then use that
* entry: create all needed subtree and add new leaf */
err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path))
err = PTR_ERR(path);
} else {
/* tree is full, time to grow in depth */
err = ext4_ext_grow_indepth(handle, inode, mb_flags);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
/*
* only first (depth 0 -> 1) produces free space;
* in all other cases we have to split the grown tree
*/
depth = ext_depth(inode);
if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
/* now we need to split */
goto repeat;
}
}
out:
return err;
}
/*
* search the closest allocated block to the left for *logical
* and returns it at @logical + it's physical address at @phys
* if *logical is the smallest allocated block, the function
* returns 0 at @phys
* return value contains 0 (success) or error code
*/
static int ext4_ext_search_left(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys)
{
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
int depth, ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
*logical, le32_to_cpu(ex->ee_block));
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
depth);
return -EFSCORRUPTED;
}
}
return 0;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
*phys = ext4_ext_pblock(ex) + ee_len - 1;
return 0;
}
/*
* search the closest allocated block to the right for *logical
* and returns it at @logical + it's physical address at @phys
* if *logical is the largest allocated block, the function
* returns 0 at @phys
* return value contains 0 (success) or error code
*/
static int ext4_ext_search_right(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys,
struct ext4_extent **ret_ex)
{
struct buffer_head *bh = NULL;
struct ext4_extent_header *eh;
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
ext4_fsblk_t block;
int depth; /* Note, NOT eh_depth; depth from top of tree */
int ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"first_extent(path[%d].p_hdr) != ex",
depth);
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix != EXT_FIRST_INDEX *logical %d!",
*logical);
return -EFSCORRUPTED;
}
}
goto found_extent;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
/* next allocated block in this leaf */
ex++;
goto found_extent;
}
/* go up and search for index to the right */
while (--depth >= 0) {
ix = path[depth].p_idx;
if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
goto got_index;
}
/* we've gone up to the root and found no index to the right */
return 0;
got_index:
/* we've found index to the right, let's
* follow it and find the closest allocated
* block to the right */
ix++;
block = ext4_idx_pblock(ix);
while (++depth < path->p_depth) {
/* subtract from p_depth to get proper eh_depth */
bh = read_extent_tree_block(inode, block,
path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ix = EXT_FIRST_INDEX(eh);
block = ext4_idx_pblock(ix);
put_bh(bh);
}
bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ex = EXT_FIRST_EXTENT(eh);
found_extent:
*logical = le32_to_cpu(ex->ee_block);
*phys = ext4_ext_pblock(ex);
*ret_ex = ex;
if (bh)
put_bh(bh);
return 0;
}
/*
* ext4_ext_next_allocated_block:
* returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
* NOTE: it considers block number from index entry as
* allocated block. Thus, index entries have to be consistent
* with leaves.
*/
ext4_lblk_t
ext4_ext_next_allocated_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
if (depth == 0 && path->p_ext == NULL)
return EXT_MAX_BLOCKS;
while (depth >= 0) {
if (depth == path->p_depth) {
/* leaf */
if (path[depth].p_ext &&
path[depth].p_ext !=
EXT_LAST_EXTENT(path[depth].p_hdr))
return le32_to_cpu(path[depth].p_ext[1].ee_block);
} else {
/* index */
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return le32_to_cpu(path[depth].p_idx[1].ei_block);
}
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_next_leaf_block:
* returns first allocated block from next leaf or EXT_MAX_BLOCKS
*/
static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
/* zero-tree has no leaf blocks at all */
if (depth == 0)
return EXT_MAX_BLOCKS;
/* go to index block */
depth--;
while (depth >= 0) {
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return (ext4_lblk_t)
le32_to_cpu(path[depth].p_idx[1].ei_block);
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_correct_indexes:
* if leaf gets modified and modified extent is first in the leaf,
* then we have to correct all indexes above.
* TODO: do we need to correct tree in all cases?
*/
static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent_header *eh;
int depth = ext_depth(inode);
struct ext4_extent *ex;
__le32 border;
int k, err = 0;
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
if (unlikely(ex == NULL || eh == NULL)) {
EXT4_ERROR_INODE(inode,
"ex %p == NULL or eh %p == NULL", ex, eh);
return -EFSCORRUPTED;
}
if (depth == 0) {
/* there is no tree at all */
return 0;
}
if (ex != EXT_FIRST_EXTENT(eh)) {
/* we correct tree if first leaf got modified only */
return 0;
}
/*
* TODO: we need correction if border is smaller than current one
*/
k = depth - 1;
border = path[depth].p_ext->ee_block;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
return err;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
return err;
while (k--) {
/* change all left-side indexes */
if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
break;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
break;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
break;
}
return err;
}
int
ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
struct ext4_extent *ex2)
{
unsigned short ext1_ee_len, ext2_ee_len;
if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
return 0;
ext1_ee_len = ext4_ext_get_actual_len(ex1);
ext2_ee_len = ext4_ext_get_actual_len(ex2);
if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
le32_to_cpu(ex2->ee_block))
return 0;
/*
* To allow future support for preallocated extents to be added
* as an RO_COMPAT feature, refuse to merge to extents if
* this can result in the top bit of ee_len being set.
*/
if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
return 0;
/*
* The check for IO to unwritten extent is somewhat racy as we
* increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
* dropping i_data_sem. But reserved blocks should save us in that
* case.
*/
if (ext4_ext_is_unwritten(ex1) &&
(ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
atomic_read(&EXT4_I(inode)->i_unwritten) ||
(ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
return 0;
#ifdef AGGRESSIVE_TEST
if (ext1_ee_len >= 4)
return 0;
#endif
if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
return 1;
return 0;
}
/*
* This function tries to merge the "ex" extent to the next extent in the tree.
* It always tries to merge towards right. If you want to merge towards
* left, pass "ex - 1" as argument instead of "ex".
* Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
* 1 if they got merged.
*/
static int ext4_ext_try_to_merge_right(struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex)
{
struct ext4_extent_header *eh;
unsigned int depth, len;
int merge_done = 0, unwritten;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
while (ex < EXT_LAST_EXTENT(eh)) {
if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
break;
/* merge with next extent! */
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(ex + 1));
if (unwritten)
ext4_ext_mark_unwritten(ex);
if (ex + 1 < EXT_LAST_EXTENT(eh)) {
len = (EXT_LAST_EXTENT(eh) - ex - 1)
* sizeof(struct ext4_extent);
memmove(ex + 1, ex + 2, len);
}
le16_add_cpu(&eh->eh_entries, -1);
merge_done = 1;
WARN_ON(eh->eh_entries == 0);
if (!eh->eh_entries)
EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
}
return merge_done;
}
/*
* This function does a very simple check to see if we can collapse
* an extent tree with a single extent tree leaf block into the inode.
*/
static void ext4_ext_try_to_merge_up(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path)
{
size_t s;
unsigned max_root = ext4_ext_space_root(inode, 0);
ext4_fsblk_t blk;
if ((path[0].p_depth != 1) ||
(le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
(le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
return;
/*
* We need to modify the block allocation bitmap and the block
* group descriptor to release the extent tree block. If we
* can't get the journal credits, give up.
*/
if (ext4_journal_extend(handle, 2))
return;
/*
* Copy the extent data up to the inode
*/
blk = ext4_idx_pblock(path[0].p_idx);
s = le16_to_cpu(path[1].p_hdr->eh_entries) *
sizeof(struct ext4_extent_idx);
s += sizeof(struct ext4_extent_header);
path[1].p_maxdepth = path[0].p_maxdepth;
memcpy(path[0].p_hdr, path[1].p_hdr, s);
path[0].p_depth = 0;
path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
path[0].p_hdr->eh_max = cpu_to_le16(max_root);
brelse(path[1].p_bh);
ext4_free_blocks(handle, inode, NULL, blk, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
}
/*
* This function tries to merge the @ex extent to neighbours in the tree.
* return 1 if merge left else 0.
*/
static void ext4_ext_try_to_merge(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex) {
struct ext4_extent_header *eh;
unsigned int depth;
int merge_done = 0;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
if (ex > EXT_FIRST_EXTENT(eh))
merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
if (!merge_done)
(void) ext4_ext_try_to_merge_right(inode, path, ex);
ext4_ext_try_to_merge_up(handle, inode, path);
}
/*
* check if a portion of the "newext" extent overlaps with an
* existing extent.
*
* If there is an overlap discovered, it updates the length of the newext
* such that there will be no overlap, and then returns 1.
* If there is no overlap found, it returns 0.
*/
static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
struct inode *inode,
struct ext4_extent *newext,
struct ext4_ext_path *path)
{
ext4_lblk_t b1, b2;
unsigned int depth, len1;
unsigned int ret = 0;
b1 = le32_to_cpu(newext->ee_block);
len1 = ext4_ext_get_actual_len(newext);
depth = ext_depth(inode);
if (!path[depth].p_ext)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
/*
* get the next allocated block if the extent in the path
* is before the requested block(s)
*/
if (b2 < b1) {
b2 = ext4_ext_next_allocated_block(path);
if (b2 == EXT_MAX_BLOCKS)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, b2);
}
/* check for wrap through zero on extent logical start block*/
if (b1 + len1 < b1) {
len1 = EXT_MAX_BLOCKS - b1;
newext->ee_len = cpu_to_le16(len1);
ret = 1;
}
/* check for overlap */
if (b1 + len1 > b2) {
newext->ee_len = cpu_to_le16(b2 - b1);
ret = 1;
}
out:
return ret;
}
/*
* ext4_ext_insert_extent:
* tries to merge requsted extent into the existing extent or
* inserts requested extent as new one into the tree,
* creating new leaf in the no-space case.
*/
int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_extent *newext, int gb_flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
int mb_flags = 0, unwritten;
if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
mb_flags |= EXT4_MB_DELALLOC_RESERVED;
if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
return -EFSCORRUPTED;
}
depth = ext_depth(inode);
ex = path[depth].p_ext;
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* try to insert block into found extent and return */
if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
/*
* Try to see whether we should rather test the extent on
* right from ex, or from the left of ex. This is because
* ext4_find_extent() can return either extent on the
* left, or on the right from the searched position. This
* will make merging more effective.
*/
if (ex < EXT_LAST_EXTENT(eh) &&
(le32_to_cpu(ex->ee_block) +
ext4_ext_get_actual_len(ex) <
le32_to_cpu(newext->ee_block))) {
ex += 1;
goto prepend;
} else if ((ex > EXT_FIRST_EXTENT(eh)) &&
(le32_to_cpu(newext->ee_block) +
ext4_ext_get_actual_len(newext) <
le32_to_cpu(ex->ee_block)))
ex -= 1;
/* Try to append newex to the ex */
if (ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug("append [%d]%d block to %u:[%d]%d"
"(from %llu)\n",
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
prepend:
/* Try to prepend newex to the ex */
if (ext4_can_extents_be_merged(inode, newext, ex)) {
ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
"(from %llu)\n",
le32_to_cpu(newext->ee_block),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_block = newext->ee_block;
ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
}
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = EXT_MAX_BLOCKS;
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
next = ext4_ext_next_leaf_block(path);
if (next != EXT_MAX_BLOCKS) {
ext_debug("next leaf block - %u\n", next);
BUG_ON(npath != NULL);
npath = ext4_find_extent(inode, next, NULL, 0);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug("next leaf isn't full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto has_space;
}
ext_debug("next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
mb_flags |= EXT4_MB_USE_RESERVED;
err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
ppath, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext));
nearex = EXT_FIRST_EXTENT(eh);
} else {
if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* Insert after */
ext_debug("insert %u:%llu:[%d]%d before: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
nearex++;
} else {
/* Insert before */
BUG_ON(newext->ee_block == nearex->ee_block);
ext_debug("insert %u:%llu:[%d]%d after: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
}
len = EXT_LAST_EXTENT(eh) - nearex + 1;
if (len > 0) {
ext_debug("insert %u:%llu:[%d]%d: "
"move %d extents from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
len, nearex, nearex + 1);
memmove(nearex + 1, nearex,
len * sizeof(struct ext4_extent));
}
}
le16_add_cpu(&eh->eh_entries, 1);
path[depth].p_ext = nearex;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents */
if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, nearex);
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
cleanup:
ext4_ext_drop_refs(npath);
kfree(npath);
return err;
}
static int ext4_fill_fiemap_extents(struct inode *inode,
ext4_lblk_t block, ext4_lblk_t num,
struct fiemap_extent_info *fieinfo)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ex;
struct extent_status es;
ext4_lblk_t next, next_del, start = 0, end = 0;
ext4_lblk_t last = block + num;
int exists, depth = 0, err = 0;
unsigned int flags = 0;
unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
while (block < last && block != EXT_MAX_BLOCKS) {
num = last - block;
/* find extent for this block */
down_read(&EXT4_I(inode)->i_data_sem);
path = ext4_find_extent(inode, block, &path, 0);
if (IS_ERR(path)) {
up_read(&EXT4_I(inode)->i_data_sem);
err = PTR_ERR(path);
path = NULL;
break;
}
depth = ext_depth(inode);
if (unlikely(path[depth].p_hdr == NULL)) {
up_read(&EXT4_I(inode)->i_data_sem);
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
err = -EFSCORRUPTED;
break;
}
ex = path[depth].p_ext;
next = ext4_ext_next_allocated_block(path);
flags = 0;
exists = 0;
if (!ex) {
/* there is no extent yet, so try to allocate
* all requested space */
start = block;
end = block + num;
} else if (le32_to_cpu(ex->ee_block) > block) {
/* need to allocate space before found extent */
start = block;
end = le32_to_cpu(ex->ee_block);
if (block + num < end)
end = block + num;
} else if (block >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
/* need to allocate space after found extent */
start = block;
end = block + num;
if (end >= next)
end = next;
} else if (block >= le32_to_cpu(ex->ee_block)) {
/*
* some part of requested space is covered
* by found extent
*/
start = block;
end = le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex);
if (block + num < end)
end = block + num;
exists = 1;
} else {
BUG();
}
BUG_ON(end <= start);
if (!exists) {
es.es_lblk = start;
es.es_len = end - start;
es.es_pblk = 0;
} else {
es.es_lblk = le32_to_cpu(ex->ee_block);
es.es_len = ext4_ext_get_actual_len(ex);
es.es_pblk = ext4_ext_pblock(ex);
if (ext4_ext_is_unwritten(ex))
flags |= FIEMAP_EXTENT_UNWRITTEN;
}
/*
* Find delayed extent and update es accordingly. We call
* it even in !exists case to find out whether es is the
* last existing extent or not.
*/
next_del = ext4_find_delayed_extent(inode, &es);
if (!exists && next_del) {
exists = 1;
flags |= (FIEMAP_EXTENT_DELALLOC |
FIEMAP_EXTENT_UNKNOWN);
}
up_read(&EXT4_I(inode)->i_data_sem);
if (unlikely(es.es_len == 0)) {
EXT4_ERROR_INODE(inode, "es.es_len == 0");
err = -EFSCORRUPTED;
break;
}
/*
* This is possible iff next == next_del == EXT_MAX_BLOCKS.
* we need to check next == EXT_MAX_BLOCKS because it is
* possible that an extent is with unwritten and delayed
* status due to when an extent is delayed allocated and
* is allocated by fallocate status tree will track both of
* them in a extent.
*
* So we could return a unwritten and delayed extent, and
* its block is equal to 'next'.
*/
if (next == next_del && next == EXT_MAX_BLOCKS) {
flags |= FIEMAP_EXTENT_LAST;
if (unlikely(next_del != EXT_MAX_BLOCKS ||
next != EXT_MAX_BLOCKS)) {
EXT4_ERROR_INODE(inode,
"next extent == %u, next "
"delalloc extent = %u",
next, next_del);
err = -EFSCORRUPTED;
break;
}
}
if (exists) {
err = fiemap_fill_next_extent(fieinfo,
(__u64)es.es_lblk << blksize_bits,
(__u64)es.es_pblk << blksize_bits,
(__u64)es.es_len << blksize_bits,
flags);
if (err < 0)
break;
if (err == 1) {
err = 0;
break;
}
}
block = es.es_lblk + es.es_len;
}
ext4_ext_drop_refs(path);
kfree(path);
return err;
}
/*
* ext4_ext_determine_hole - determine hole around given block
* @inode: inode we lookup in
* @path: path in extent tree to @lblk
* @lblk: pointer to logical block around which we want to determine hole
*
* Determine hole length (and start if easily possible) around given logical
* block. We don't try too hard to find the beginning of the hole but @path
* actually points to extent before @lblk, we provide it.
*
* The function returns the length of a hole starting at @lblk. We update @lblk
* to the beginning of the hole if we managed to find it.
*/
static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *lblk)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
ext4_lblk_t len;
ex = path[depth].p_ext;
if (ex == NULL) {
/* there is no extent yet, so gap is [0;-] */
*lblk = 0;
len = EXT_MAX_BLOCKS;
} else if (*lblk < le32_to_cpu(ex->ee_block)) {
len = le32_to_cpu(ex->ee_block) - *lblk;
} else if (*lblk >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
ext4_lblk_t next;
*lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
next = ext4_ext_next_allocated_block(path);
BUG_ON(next == *lblk);
len = next - *lblk;
} else {
BUG();
}
return len;
}
/*
* ext4_ext_put_gap_in_cache:
* calculate boundaries of the gap that the requested block fits into
* and cache this gap
*/
static void
ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
ext4_lblk_t hole_len)
{
struct extent_status es;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
hole_start + hole_len - 1, &es);
if (es.es_len) {
/* There's delayed extent containing lblock? */
if (es.es_lblk <= hole_start)
return;
hole_len = min(es.es_lblk - hole_start, hole_len);
}
ext_debug(" -> %u:%u\n", hole_start, hole_len);
ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
EXTENT_STATUS_HOLE);
}
/*
* ext4_ext_rm_idx:
* removes index from the index block.
*/
static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path, int depth)
{
int err;
ext4_fsblk_t leaf;
/* free index block */
depth--;
path = path + depth;
leaf = ext4_idx_pblock(path->p_idx);
if (unlikely(path->p_hdr->eh_entries == 0)) {
EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
return -EFSCORRUPTED;
}
err = ext4_ext_get_access(handle, inode, path);
if (err)
return err;
if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
len *= sizeof(struct ext4_extent_idx);
memmove(path->p_idx, path->p_idx + 1, len);
}
le16_add_cpu(&path->p_hdr->eh_entries, -1);
err = ext4_ext_dirty(handle, inode, path);
if (err)
return err;
ext_debug("index is empty, remove it, free block %llu\n", leaf);
trace_ext4_ext_rm_idx(inode, leaf);
ext4_free_blocks(handle, inode, NULL, leaf, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
while (--depth >= 0) {
if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
break;
path--;
err = ext4_ext_get_access(handle, inode, path);
if (err)
break;
path->p_idx->ei_block = (path+1)->p_idx->ei_block;
err = ext4_ext_dirty(handle, inode, path);
if (err)
break;
}
return err;
}
/*
* ext4_ext_calc_credits_for_single_extent:
* This routine returns max. credits that needed to insert an extent
* to the extent tree.
* When pass the actual path, the caller should calculate credits
* under i_data_sem.
*/
int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
struct ext4_ext_path *path)
{
if (path) {
int depth = ext_depth(inode);
int ret = 0;
/* probably there is space in leaf? */
if (le16_to_cpu(path[depth].p_hdr->eh_entries)
< le16_to_cpu(path[depth].p_hdr->eh_max)) {
/*
* There are some space in the leaf tree, no
* need to account for leaf block credit
*
* bitmaps and block group descriptor blocks
* and other metadata blocks still need to be
* accounted.
*/
/* 1 bitmap, 1 block group descriptor */
ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
return ret;
}
}
return ext4_chunk_trans_blocks(inode, nrblocks);
}
/*
* How many index/leaf blocks need to change/allocate to add @extents extents?
*
* If we add a single extent, then in the worse case, each tree level
* index/leaf need to be changed in case of the tree split.
*
* If more extents are inserted, they could cause the whole tree split more
* than once, but this is really rare.
*/
int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
{
int index;
int depth;
/* If we are converting the inline data, only one is needed here. */
if (ext4_has_inline_data(inode))
return 1;
depth = ext_depth(inode);
if (extents <= 1)
index = depth * 2;
else
index = depth * 3;
return index;
}
static inline int get_default_free_blocks_flags(struct inode *inode)
{
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
else if (ext4_should_journal_data(inode))
return EXT4_FREE_BLOCKS_FORGET;
return 0;
}
/*
* ext4_rereserve_cluster - increment the reserved cluster count when
* freeing a cluster with a pending reservation
*
* @inode - file containing the cluster
* @lblk - logical block in cluster to be reserved
*
* Increments the reserved cluster count and adjusts quota in a bigalloc
* file system when freeing a partial cluster containing at least one
* delayed and unwritten block. A partial cluster meeting that
* requirement will have a pending reservation. If so, the
* RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
* defer reserved and allocated space accounting to a subsequent call
* to this function.
*/
static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
spin_lock(&ei->i_block_reservation_lock);
ei->i_reserved_data_blocks++;
percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
spin_unlock(&ei->i_block_reservation_lock);
percpu_counter_add(&sbi->s_freeclusters_counter, 1);
ext4_remove_pending(inode, lblk);
}
static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
struct ext4_extent *ex,
struct partial_cluster *partial,
ext4_lblk_t from, ext4_lblk_t to)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
ext4_fsblk_t last_pblk, pblk;
ext4_lblk_t num;
int flags;
/* only extent tail removal is allowed */
if (from < le32_to_cpu(ex->ee_block) ||
to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
ext4_error(sbi->s_sb,
"strange request: removal(2) %u-%u from %u:%u",
from, to, le32_to_cpu(ex->ee_block), ee_len);
return 0;
}
#ifdef EXTENTS_STATS
spin_lock(&sbi->s_ext_stats_lock);
sbi->s_ext_blocks += ee_len;
sbi->s_ext_extents++;
if (ee_len < sbi->s_ext_min)
sbi->s_ext_min = ee_len;
if (ee_len > sbi->s_ext_max)
sbi->s_ext_max = ee_len;
if (ext_depth(inode) > sbi->s_depth_max)
sbi->s_depth_max = ext_depth(inode);
spin_unlock(&sbi->s_ext_stats_lock);
#endif
trace_ext4_remove_blocks(inode, ex, from, to, partial);
/*
* if we have a partial cluster, and it's different from the
* cluster of the last block in the extent, we free it
*/
last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
if (partial->state != initial &&
partial->pclu != EXT4_B2C(sbi, last_pblk)) {
if (partial->state == tofree) {
flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
num = le32_to_cpu(ex->ee_block) + ee_len - from;
pblk = ext4_ext_pblock(ex) + ee_len - num;
/*
* We free the partial cluster at the end of the extent (if any),
* unless the cluster is used by another extent (partial_cluster
* state is nofree). If a partial cluster exists here, it must be
* shared with the last block in the extent.
*/
flags = get_default_free_blocks_flags(inode);
/* partial, left end cluster aligned, right end unaligned */
if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
(EXT4_LBLK_CMASK(sbi, to) >= from) &&
(partial->state != nofree)) {
if (ext4_is_pending(inode, to))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_PBLK_CMASK(sbi, last_pblk),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, to);
partial->state = initial;
flags = get_default_free_blocks_flags(inode);
}
flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
/*
* For bigalloc file systems, we never free a partial cluster
* at the beginning of the extent. Instead, we check to see if we
* need to free it on a subsequent call to ext4_remove_blocks,
* or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
*/
flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
/* reset the partial cluster if we've freed past it */
if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
partial->state = initial;
/*
* If we've freed the entire extent but the beginning is not left
* cluster aligned and is not marked as ineligible for freeing we
* record the partial cluster at the beginning of the extent. It
* wasn't freed by the preceding ext4_free_blocks() call, and we
* need to look farther to the left to determine if it's to be freed
* (not shared with another extent). Else, reset the partial
* cluster - we're either done freeing or the beginning of the
* extent is left cluster aligned.
*/
if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
if (partial->state == initial) {
partial->pclu = EXT4_B2C(sbi, pblk);
partial->lblk = from;
partial->state = tofree;
}
} else {
partial->state = initial;
}
return 0;
}
/*
* ext4_ext_rm_leaf() Removes the extents associated with the
* blocks appearing between "start" and "end". Both "start"
* and "end" must appear in the same extent or EIO is returned.
*
* @handle: The journal handle
* @inode: The files inode
* @path: The path to the leaf
* @partial_cluster: The cluster which we'll have to free if all extents
* has been released from it. However, if this value is
* negative, it's a cluster just to the right of the
* punched region and it must not be freed.
* @start: The first block to remove
* @end: The last block to remove
*/
static int
ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct partial_cluster *partial,
ext4_lblk_t start, ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int err = 0, correct_index = 0;
int depth = ext_depth(inode), credits;
struct ext4_extent_header *eh;
ext4_lblk_t a, b;
unsigned num;
ext4_lblk_t ex_ee_block;
unsigned short ex_ee_len;
unsigned unwritten = 0;
struct ext4_extent *ex;
ext4_fsblk_t pblk;
/* the header must be checked already in ext4_ext_remove_space() */
ext_debug("truncate since %u in leaf to %u\n", start, end);
if (!path[depth].p_hdr)
path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* find where to start removing */
ex = path[depth].p_ext;
if (!ex)
ex = EXT_LAST_EXTENT(eh);
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_rm_leaf(inode, start, ex, partial);
while (ex >= EXT_FIRST_EXTENT(eh) &&
ex_ee_block + ex_ee_len > start) {
if (ext4_ext_is_unwritten(ex))
unwritten = 1;
else
unwritten = 0;
ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
unwritten, ex_ee_len);
path[depth].p_ext = ex;
a = ex_ee_block > start ? ex_ee_block : start;
b = ex_ee_block+ex_ee_len - 1 < end ?
ex_ee_block+ex_ee_len - 1 : end;
ext_debug(" border %u:%u\n", a, b);
/* If this extent is beyond the end of the hole, skip it */
if (end < ex_ee_block) {
/*
* We're going to skip this extent and move to another,
* so note that its first cluster is in use to avoid
* freeing it when removing blocks. Eventually, the
* right edge of the truncated/punched region will
* be just to the left.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex);
partial->pclu = EXT4_B2C(sbi, pblk);
partial->state = nofree;
}
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
continue;
} else if (b != ex_ee_block + ex_ee_len - 1) {
EXT4_ERROR_INODE(inode,
"can not handle truncate %u:%u "
"on extent %u:%u",
start, end, ex_ee_block,
ex_ee_block + ex_ee_len - 1);
err = -EFSCORRUPTED;
goto out;
} else if (a != ex_ee_block) {
/* remove tail of the extent */
num = a - ex_ee_block;
} else {
/* remove whole extent: excellent! */
num = 0;
}
/*
* 3 for leaf, sb, and inode plus 2 (bmap and group
* descriptor) for each block group; assume two block
* groups plus ex_ee_len/blocks_per_block_group for
* the worst case
*/
credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
if (ex == EXT_FIRST_EXTENT(eh)) {
correct_index = 1;
credits += (ext_depth(inode)) + 1;
}
credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
err = ext4_ext_truncate_extend_restart(handle, inode, credits);
if (err)
goto out;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
if (err)
goto out;
if (num == 0)
/* this extent is removed; mark slot entirely unused */
ext4_ext_store_pblock(ex, 0);
ex->ee_len = cpu_to_le16(num);
/*
* Do not mark unwritten if all the blocks in the
* extent have been removed.
*/
if (unwritten && num)
ext4_ext_mark_unwritten(ex);
/*
* If the extent was completely released,
* we need to remove it from the leaf
*/
if (num == 0) {
if (end != EXT_MAX_BLOCKS - 1) {
/*
* For hole punching, we need to scoot all the
* extents up when an extent is removed so that
* we dont have blank extents in the middle
*/
memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
sizeof(struct ext4_extent));
/* Now get rid of the one at the end */
memset(EXT_LAST_EXTENT(eh), 0,
sizeof(struct ext4_extent));
}
le16_add_cpu(&eh->eh_entries, -1);
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
ext4_ext_pblock(ex));
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
}
if (correct_index && eh->eh_entries)
err = ext4_ext_correct_indexes(handle, inode, path);
/*
* If there's a partial cluster and at least one extent remains in
* the leaf, free the partial cluster if it isn't shared with the
* current extent. If it is shared with the current extent
* we reset the partial cluster because we've reached the start of the
* truncated/punched region and we're done removing blocks.
*/
if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
if (partial->pclu != EXT4_B2C(sbi, pblk)) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
/* if this leaf is free, then we should
* remove it from index block above */
if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
err = ext4_ext_rm_idx(handle, inode, path, depth);
out:
return err;
}
/*
* ext4_ext_more_to_rm:
* returns 1 if current index has to be freed (even partial)
*/
static int
ext4_ext_more_to_rm(struct ext4_ext_path *path)
{
BUG_ON(path->p_idx == NULL);
if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
return 0;
/*
* if truncate on deeper level happened, it wasn't partial,
* so we have to consider current index for truncation
*/
if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
return 0;
return 1;
}
int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int depth = ext_depth(inode);
struct ext4_ext_path *path = NULL;
struct partial_cluster partial;
handle_t *handle;
int i = 0, err = 0;
partial.pclu = 0;
partial.lblk = 0;
partial.state = initial;
ext_debug("truncate since %u to %u\n", start, end);
/* probably first extent we're gonna free will be last in block */
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
again:
trace_ext4_ext_remove_space(inode, start, end, depth);
/*
* Check if we are removing extents inside the extent tree. If that
* is the case, we are going to punch a hole inside the extent tree
* so we have to check whether we need to split the extent covering
* the last block to remove so we can easily remove the part of it
* in ext4_ext_rm_leaf().
*/
if (end < EXT_MAX_BLOCKS - 1) {
struct ext4_extent *ex;
ext4_lblk_t ee_block, ex_end, lblk;
ext4_fsblk_t pblk;
/* find extent for or closest extent to this block */
path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path)) {
ext4_journal_stop(handle);
return PTR_ERR(path);
}
depth = ext_depth(inode);
/* Leaf not may not exist only if inode has no blocks at all */
ex = path[depth].p_ext;
if (!ex) {
if (depth) {
EXT4_ERROR_INODE(inode,
"path[%d].p_hdr == NULL",
depth);
err = -EFSCORRUPTED;
}
goto out;
}
ee_block = le32_to_cpu(ex->ee_block);
ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
/*
* See if the last block is inside the extent, if so split
* the extent at 'end' block so we can easily remove the
* tail of the first part of the split extent in
* ext4_ext_rm_leaf().
*/
if (end >= ee_block && end < ex_end) {
/*
* If we're going to split the extent, note that
* the cluster containing the block after 'end' is
* in use to avoid freeing it when removing blocks.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
/*
* Split the extent in two so that 'end' is the last
* block in the first new extent. Also we should not
* fail removing space due to ENOSPC so try to use
* reserved block if that happens.
*/
err = ext4_force_split_extent_at(handle, inode, &path,
end + 1, 1);
if (err < 0)
goto out;
} else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
partial.state == initial) {
/*
* If we're punching, there's an extent to the right.
* If the partial cluster hasn't been set, set it to
* that extent's first cluster and its state to nofree
* so it won't be freed should it contain blocks to be
* removed. If it's already set (tofree/nofree), we're
* retrying and keep the original partial cluster info
* so a cluster marked tofree as a result of earlier
* extent removal is not lost.
*/
lblk = ex_end + 1;
err = ext4_ext_search_right(inode, path, &lblk, &pblk,
&ex);
if (err)
goto out;
if (pblk) {
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
}
}
/*
* We start scanning from right side, freeing all the blocks
* after i_size and walking into the tree depth-wise.
*/
depth = ext_depth(inode);
if (path) {
int k = i = depth;
while (--k > 0)
path[k].p_block =
le16_to_cpu(path[k].p_hdr->eh_entries)+1;
} else {
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (path == NULL) {
ext4_journal_stop(handle);
return -ENOMEM;
}
path[0].p_maxdepth = path[0].p_depth = depth;
path[0].p_hdr = ext_inode_hdr(inode);
i = 0;
if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
err = -EFSCORRUPTED;
goto out;
}
}
err = 0;
while (i >= 0 && err == 0) {
if (i == depth) {
/* this is leaf block */
err = ext4_ext_rm_leaf(handle, inode, path,
&partial, start, end);
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
/* this is index block */
if (!path[i].p_hdr) {
ext_debug("initialize header\n");
path[i].p_hdr = ext_block_hdr(path[i].p_bh);
}
if (!path[i].p_idx) {
/* this level hasn't been touched yet */
path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
ext_debug("init index ptr: hdr 0x%p, num %d\n",
path[i].p_hdr,
le16_to_cpu(path[i].p_hdr->eh_entries));
} else {
/* we were already here, see at next index */
path[i].p_idx--;
}
ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
i, EXT_FIRST_INDEX(path[i].p_hdr),
path[i].p_idx);
if (ext4_ext_more_to_rm(path + i)) {
struct buffer_head *bh;
/* go to the next level */
ext_debug("move to level %d (block %llu)\n",
i + 1, ext4_idx_pblock(path[i].p_idx));
memset(path + i + 1, 0, sizeof(*path));
bh = read_extent_tree_block(inode,
ext4_idx_pblock(path[i].p_idx), depth - i - 1,
EXT4_EX_NOCACHE);
if (IS_ERR(bh)) {
/* should we reset i_size? */
err = PTR_ERR(bh);
break;
}
/* Yield here to deal with large extent trees.
* Should be a no-op if we did IO above. */
cond_resched();
if (WARN_ON(i + 1 > depth)) {
err = -EFSCORRUPTED;
break;
}
path[i + 1].p_bh = bh;
/* save actual number of indexes since this
* number is changed at the next iteration */
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
i++;
} else {
/* we finished processing this index, go up */
if (path[i].p_hdr->eh_entries == 0 && i > 0) {
/* index is empty, remove it;
* handle must be already prepared by the
* truncatei_leaf() */
err = ext4_ext_rm_idx(handle, inode, path, i);
}
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
ext_debug("return to level %d\n", i);
}
}
trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
path->p_hdr->eh_entries);
/*
* if there's a partial cluster and we have removed the first extent
* in the file, then we also free the partial cluster, if any
*/
if (partial.state == tofree && err == 0) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial.lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial.pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial.lblk);
partial.state = initial;
}
/* TODO: flexible tree reduction should be here */
if (path->p_hdr->eh_entries == 0) {
/*
* truncate to zero freed all the tree,
* so we need to correct eh_depth
*/
err = ext4_ext_get_access(handle, inode, path);
if (err == 0) {
ext_inode_hdr(inode)->eh_depth = 0;
ext_inode_hdr(inode)->eh_max =
cpu_to_le16(ext4_ext_space_root(inode, 0));
err = ext4_ext_dirty(handle, inode, path);
}
}
out:
ext4_ext_drop_refs(path);
kfree(path);
path = NULL;
if (err == -EAGAIN)
goto again;
ext4_journal_stop(handle);
return err;
}
/*
* called at mount time
*/
void ext4_ext_init(struct super_block *sb)
{
/*
* possible initialization would be here
*/
if (ext4_has_feature_extents(sb)) {
#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
printk(KERN_INFO "EXT4-fs: file extents enabled"
#ifdef AGGRESSIVE_TEST
", aggressive tests"
#endif
#ifdef CHECK_BINSEARCH
", check binsearch"
#endif
#ifdef EXTENTS_STATS
", stats"
#endif
"\n");
#endif
#ifdef EXTENTS_STATS
spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
EXT4_SB(sb)->s_ext_min = 1 << 30;
EXT4_SB(sb)->s_ext_max = 0;
#endif
}
}
/*
* called at umount time
*/
void ext4_ext_release(struct super_block *sb)
{
if (!ext4_has_feature_extents(sb))
return;
#ifdef EXTENTS_STATS
if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
struct ext4_sb_info *sbi = EXT4_SB(sb);
printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
sbi->s_ext_blocks, sbi->s_ext_extents,
sbi->s_ext_blocks / sbi->s_ext_extents);
printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
}
#endif
}
static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
{
ext4_lblk_t ee_block;
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
if (ee_len == 0)
return 0;
return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
EXTENT_STATUS_WRITTEN);
}
/* FIXME!! we need to try to merge to left or right after zero-out */
static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
{
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
ee_len);
}
/*
* ext4_split_extent_at() splits an extent at given block.
*
* @handle: the journal handle
* @inode: the file inode
* @path: the path to the extent
* @split: the logical block where the extent is splitted.
* @split_flags: indicates if the extent could be zeroout if split fails, and
* the states(init or unwritten) of new extents.
* @flags: flags used to insert new extent to extent tree.
*
*
* Splits extent [a, b] into two extents [a, @split) and [@split, b], states
* of which are deterimined by split_flag.
*
* There are two cases:
* a> the extent are splitted into two extent.
* b> split is not needed, and just mark the extent.
*
* return 0 on success.
*/
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_fsblk_t newblock;
ext4_lblk_t ee_block;
struct ext4_extent *ex, newex, orig_ex, zero_ex;
struct ext4_extent *ex2 = NULL;
unsigned int ee_len, depth;
int err = 0;
BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
(EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
ext_debug("ext4_split_extents_at: inode %lu, logical"
"block %llu\n", inode->i_ino, (unsigned long long)split);
ext4_ext_show_leaf(inode, path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
newblock = split - ee_block + ext4_ext_pblock(ex);
BUG_ON(split < ee_block || split >= (ee_block + ee_len));
BUG_ON(!ext4_ext_is_unwritten(ex) &&
split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (split == ee_block) {
/*
* case b: block @split is the block that the extent begins with
* then we just change the state of the extent, and splitting
* is not needed.
*/
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex);
else
ext4_ext_mark_initialized(ex);
if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
}
/* case a */
memcpy(&orig_ex, ex, sizeof(orig_ex));
ex->ee_len = cpu_to_le16(split - ee_block);
if (split_flag & EXT4_EXT_MARK_UNWRIT1)
ext4_ext_mark_unwritten(ex);
/*
* path may lead to new leaf, not to original leaf any more
* after ext4_ext_insert_extent() returns,
*/
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto fix_extent_len;
ex2 = &newex;
ex2->ee_block = cpu_to_le32(split);
ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
ext4_ext_store_pblock(ex2, newblock);
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex2);
err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
if (split_flag & EXT4_EXT_DATA_VALID1) {
err = ext4_ext_zeroout(inode, ex2);
zero_ex.ee_block = ex2->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex2));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex2));
} else {
err = ext4_ext_zeroout(inode, ex);
zero_ex.ee_block = ex->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex));
}
} else {
err = ext4_ext_zeroout(inode, &orig_ex);
zero_ex.ee_block = orig_ex.ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(&orig_ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(&orig_ex));
}
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_len = cpu_to_le16(ee_len);
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (err)
goto fix_extent_len;
/* update extent status tree */
err = ext4_zeroout_es(inode, &zero_ex);
goto out;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err;
fix_extent_len:
ex->ee_len = orig_ex.ee_len;
ext4_ext_dirty(handle, inode, path + path->p_depth);
return err;
}
/*
* ext4_split_extents() splits an extent and mark extent which is covered
* by @map as split_flags indicates
*
* It may result in splitting the extent into multiple extents (up to three)
* There are three possibilities:
* a> There is no split required
* b> Splits in two extents: Split is happening at either end of the extent
* c> Splits in three extents: Somone is splitting in middle of the extent
*
*/
static int ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len, depth;
int err = 0;
int unwritten;
int split_flag1, flags1;
int allocated = map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
unwritten = ext4_ext_is_unwritten(ex);
if (map->m_lblk + map->m_len < ee_block + ee_len) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
if (unwritten)
split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
if (split_flag & EXT4_EXT_DATA_VALID2)
split_flag1 |= EXT4_EXT_DATA_VALID1;
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk + map->m_len, split_flag1, flags1);
if (err)
goto out;
} else {
allocated = ee_len - (map->m_lblk - ee_block);
}
/*
* Update path is required because previous ext4_split_extent_at() may
* result in split of original leaf or extent zeroout.
*/
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
unwritten = ext4_ext_is_unwritten(ex);
split_flag1 = 0;
if (map->m_lblk >= ee_block) {
split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
if (unwritten) {
split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT2);
}
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk, split_flag1, flags);
if (err)
goto out;
}
ext4_ext_show_leaf(inode, path);
out:
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() if someone tries to write
* to an unwritten extent. It may result in splitting the unwritten
* extent into multiple extents (up to three - one initialized and two
* unwritten).
* There are three possibilities:
* a> There is no split required: Entire extent should be initialized
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* Pre-conditions:
* - The extent pointed to by 'path' is unwritten.
* - The extent pointed to by 'path' contains a superset
* of the logical span [map->m_lblk, map->m_lblk + map->m_len).
*
* Post-conditions on success:
* - the returned value is the number of blocks beyond map->l_lblk
* that are allocated and initialized.
* It is guaranteed to be >= map->m_len.
*/
static int ext4_ext_convert_to_initialized(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_sb_info *sbi;
struct ext4_extent_header *eh;
struct ext4_map_blocks split_map;
struct ext4_extent zero_ex1, zero_ex2;
struct ext4_extent *ex, *abut_ex;
ext4_lblk_t ee_block, eof_block;
unsigned int ee_len, depth, map_len = map->m_len;
int allocated = 0, max_zeroout = 0;
int err = 0;
int split_flag = EXT4_EXT_DATA_VALID2;
ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map_len);
sbi = EXT4_SB(inode->i_sb);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map_len)
eof_block = map->m_lblk + map_len;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
zero_ex1.ee_len = 0;
zero_ex2.ee_len = 0;
trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
/* Pre-conditions */
BUG_ON(!ext4_ext_is_unwritten(ex));
BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
/*
* Attempt to transfer newly initialized blocks from the currently
* unwritten extent to its neighbor. This is much cheaper
* than an insertion followed by a merge as those involve costly
* memmove() calls. Transferring to the left is the common case in
* steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
* followed by append writes.
*
* Limitations of the current logic:
* - L1: we do not deal with writes covering the whole extent.
* This would require removing the extent if the transfer
* is possible.
* - L2: we only attempt to merge with an extent stored in the
* same extent tree node.
*/
if ((map->m_lblk == ee_block) &&
/* See if we can merge left */
(map_len < ee_len) && /*L1*/
(ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
ext4_lblk_t prev_lblk;
ext4_fsblk_t prev_pblk, ee_pblk;
unsigned int prev_len;
abut_ex = ex - 1;
prev_lblk = le32_to_cpu(abut_ex->ee_block);
prev_len = ext4_ext_get_actual_len(abut_ex);
prev_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((prev_lblk + prev_len) == ee_block) && /*C2*/
((prev_pblk + prev_len) == ee_pblk) && /*C3*/
(prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of ex by 'map_len' blocks */
ex->ee_block = cpu_to_le32(ee_block + map_len);
ext4_ext_store_pblock(ex, ee_pblk + map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
} else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
(map_len < ee_len) && /*L1*/
ex < EXT_LAST_EXTENT(eh)) { /*L2*/
/* See if we can merge right */
ext4_lblk_t next_lblk;
ext4_fsblk_t next_pblk, ee_pblk;
unsigned int next_len;
abut_ex = ex + 1;
next_lblk = le32_to_cpu(abut_ex->ee_block);
next_len = ext4_ext_get_actual_len(abut_ex);
next_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((map->m_lblk + map_len) == next_lblk) && /*C2*/
((ee_pblk + ee_len) == next_pblk) && /*C3*/
(next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of abut_ex by 'map_len' blocks */
abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(next_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
}
if (allocated) {
/* Mark the block containing both extents as dirty */
ext4_ext_dirty(handle, inode, path + depth);
/* Update path to point to the right extent */
path[depth].p_ext = abut_ex;
goto out;
} else
allocated = ee_len - (map->m_lblk - ee_block);
WARN_ON(map->m_lblk < ee_block);
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully inside i_size or new_size.
*/
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
if (EXT4_EXT_MAY_ZEROOUT & split_flag)
max_zeroout = sbi->s_extent_max_zeroout_kb >>
(inode->i_sb->s_blocksize_bits - 10);
if (IS_ENCRYPTED(inode))
max_zeroout = 0;
/*
* five cases:
* 1. split the extent into three extents.
* 2. split the extent into two extents, zeroout the head of the first
* extent.
* 3. split the extent into two extents, zeroout the tail of the second
* extent.
* 4. split the extent into two extents with out zeroout.
* 5. no splitting needed, just possibly zeroout the head and / or the
* tail of the extent.
*/
split_map.m_lblk = map->m_lblk;
split_map.m_len = map->m_len;
if (max_zeroout && (allocated > split_map.m_len)) {
if (allocated <= max_zeroout) {
/* case 3 or 5 */
zero_ex1.ee_block =
cpu_to_le32(split_map.m_lblk +
split_map.m_len);
zero_ex1.ee_len =
cpu_to_le16(allocated - split_map.m_len);
ext4_ext_store_pblock(&zero_ex1,
ext4_ext_pblock(ex) + split_map.m_lblk +
split_map.m_len - ee_block);
err = ext4_ext_zeroout(inode, &zero_ex1);
if (err)
goto out;
split_map.m_len = allocated;
}
if (split_map.m_lblk - ee_block + split_map.m_len <
max_zeroout) {
/* case 2 or 5 */
if (split_map.m_lblk != ee_block) {
zero_ex2.ee_block = ex->ee_block;
zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
ee_block);
ext4_ext_store_pblock(&zero_ex2,
ext4_ext_pblock(ex));
err = ext4_ext_zeroout(inode, &zero_ex2);
if (err)
goto out;
}
split_map.m_len += split_map.m_lblk - ee_block;
split_map.m_lblk = ee_block;
allocated = map->m_len;
}
}
err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
flags);
if (err > 0)
err = 0;
out:
/* If we have gotten a failure, don't zero out status tree */
if (!err) {
err = ext4_zeroout_es(inode, &zero_ex1);
if (!err)
err = ext4_zeroout_es(inode, &zero_ex2);
}
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() from
* ext4_get_blocks_dio_write() when DIO to write
* to an unwritten extent.
*
* Writing to an unwritten extent may result in splitting the unwritten
* extent into multiple initialized/unwritten extents (up to three)
* There are three possibilities:
* a> There is no split required: Entire extent should be unwritten
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* This works the same way in the case of initialized -> unwritten conversion.
*
* One of more index blocks maybe needed if the extent tree grow after
* the unwritten extent split. To prevent ENOSPC occur at the IO
* complete, we need to split the unwritten extent before DIO submit
* the IO. The unwritten extent called at this time will be split
* into three unwritten extent(at most). After IO complete, the part
* being filled will be convert to initialized by the end_io callback function
* via ext4_convert_unwritten_extents().
*
* Returns the size of unwritten extent to be written on success.
*/
static int ext4_split_convert_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
__func__, inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
/* Convert to unwritten */
if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
split_flag |= EXT4_EXT_DATA_VALID1;
/* Convert to initialized */
} else if (flags & EXT4_GET_BLOCKS_CONVERT) {
split_flag |= ee_block + ee_len <= eof_block ?
EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
}
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
}
static int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)ee_block, ee_len);
/* If extent is larger than requested it is a clear sign that we still
* have some extent state machine issues left. So extent_split is still
* required.
* TODO: Once all related issues will be fixed this situation should be
* illegal.
*/
if (ee_block != map->m_lblk || ee_len > map->m_len) {
#ifdef EXT4_DEBUG
ext4_warning("Inode (%ld) finished: extent logical block %llu,"
" len %u; IO logical block %llu, len %u",
inode->i_ino, (unsigned long long)ee_block, ee_len,
(unsigned long long)map->m_lblk, map->m_len);
#endif
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
/*
* Handle EOFBLOCKS_FL flag, clearing it if necessary
*/
static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
ext4_lblk_t lblk,
struct ext4_ext_path *path,
unsigned int len)
{
int i, depth;
struct ext4_extent_header *eh;
struct ext4_extent *last_ex;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
return 0;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
/*
* We're going to remove EOFBLOCKS_FL entirely in future so we
* do not care for this case anymore. Simply remove the flag
* if there are no extents.
*/
if (unlikely(!eh->eh_entries))
goto out;
last_ex = EXT_LAST_EXTENT(eh);
/*
* We should clear the EOFBLOCKS_FL flag if we are writing the
* last block in the last extent in the file. We test this by
* first checking to see if the caller to
* ext4_ext_get_blocks() was interested in the last block (or
* a block beyond the last block) in the current extent. If
* this turns out to be false, we can bail out from this
* function immediately.
*/
if (lblk + len < le32_to_cpu(last_ex->ee_block) +
ext4_ext_get_actual_len(last_ex))
return 0;
/*
* If the caller does appear to be planning to write at or
* beyond the end of the current extent, we then test to see
* if the current extent is the last extent in the file, by
* checking to make sure it was reached via the rightmost node
* at each level of the tree.
*/
for (i = depth-1; i >= 0; i--)
if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
return 0;
out:
ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
return ext4_mark_inode_dirty(handle, inode);
}
static int
convert_initialized_extent(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
unsigned int allocated)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
/*
* Make sure that the extent is no bigger than we support with
* unwritten extent
*/
if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug("%s: inode %lu, logical"
"block %llu, max_blocks %u\n", __func__, inode->i_ino,
(unsigned long long)ee_block, ee_len);
if (ee_block != map->m_lblk || ee_len > map->m_len) {
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/* first mark the extent as unwritten */
ext4_ext_mark_unwritten(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (err)
return err;
ext4_ext_show_leaf(inode, path);
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
if (err)
return err;
map->m_flags |= EXT4_MAP_UNWRITTEN;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
return allocated;
}
static int
ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
struct ext4_ext_path *path = *ppath;
int ret = 0;
int err = 0;
ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
"block %llu, max_blocks %u, flags %x, allocated %u\n",
inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/*
* When writing into unwritten space, we should not fail to
* allocate metadata blocks for the new extent block if needed.
*/
flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
allocated, newblock);
/* get_block() before submit the IO, split the extent */
if (flags & EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_convert_extents(handle, inode, map, ppath,
flags | EXT4_GET_BLOCKS_CONVERT);
if (ret <= 0)
goto out;
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if (flags & EXT4_GET_BLOCKS_CONVERT) {
if (flags & EXT4_GET_BLOCKS_ZERO) {
if (allocated > map->m_len)
allocated = map->m_len;
err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
allocated);
if (err < 0)
goto out2;
}
ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
ppath);
if (ret >= 0) {
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, map->m_len);
} else
err = ret;
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto map_out;
}
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
map->m_len);
if (err < 0)
goto out2;
}
out1:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_pblk = newblock;
map->m_len = allocated;
out2:
return err ? err : allocated;
}
/*
* get_implied_cluster_alloc - check to see if the requested
* allocation (in the map structure) overlaps with a cluster already
* allocated in an extent.
* @sb The filesystem superblock structure
* @map The requested lblk->pblk mapping
* @ex The extent structure which might contain an implied
* cluster allocation
*
* This function is called by ext4_ext_map_blocks() after we failed to
* find blocks that were already in the inode's extent tree. Hence,
* we know that the beginning of the requested region cannot overlap
* the extent from the inode's extent tree. There are three cases we
* want to catch. The first is this case:
*
* |--- cluster # N--|
* |--- extent ---| |---- requested region ---|
* |==========|
*
* The second case that we need to test for is this one:
*
* |--------- cluster # N ----------------|
* |--- requested region --| |------- extent ----|
* |=======================|
*
* The third case is when the requested region lies between two extents
* within the same cluster:
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*
* In each of the above cases, we need to set the map->m_pblk and
* map->m_len so it corresponds to the return the extent labelled as
* "|====|" from cluster #N, since it is already in use for data in
* cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
* signal to ext4_ext_map_blocks() that map->m_pblk should be treated
* as a new "allocated" block region. Otherwise, we will return 0 and
* ext4_ext_map_blocks() will then allocate one or more new clusters
* by calling ext4_mb_new_blocks().
*/
static int get_implied_cluster_alloc(struct super_block *sb,
struct ext4_map_blocks *map,
struct ext4_extent *ex,
struct ext4_ext_path *path)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ext4_lblk_t ex_cluster_start, ex_cluster_end;
ext4_lblk_t rr_cluster_start;
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
/* The extent passed in that we are trying to match */
ex_cluster_start = EXT4_B2C(sbi, ee_block);
ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
/* The requested region passed into ext4_map_blocks() */
rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
if ((rr_cluster_start == ex_cluster_end) ||
(rr_cluster_start == ex_cluster_start)) {
if (rr_cluster_start == ex_cluster_end)
ee_start += ee_len - 1;
map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
map->m_len = min(map->m_len,
(unsigned) sbi->s_cluster_ratio - c_offset);
/*
* Check for and handle this case:
*
* |--------- cluster # N-------------|
* |------- extent ----|
* |--- requested region ---|
* |===========|
*/
if (map->m_lblk < ee_block)
map->m_len = min(map->m_len, ee_block - map->m_lblk);
/*
* Check for the case where there is already another allocated
* block to the right of 'ex' but before the end of the cluster.
*
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*/
if (map->m_lblk > ee_block) {
ext4_lblk_t next = ext4_ext_next_allocated_block(path);
map->m_len = min(map->m_len, next - map->m_lblk);
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
return 1;
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
return 0;
}
/*
* Block allocation/map/preallocation routine for extents based files
*
*
* Need to be called with
* down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
* (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
*
* return > 0, number of of blocks already mapped/allocated
* if create == 0 and these are pre-allocated blocks
* buffer head is unmapped
* otherwise blocks are mapped
*
* return = 0, if plain look up failed (blocks have not been allocated)
* buffer head is unmapped
*
* return < 0, error case.
*/
int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent newex, *ex, *ex2;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_fsblk_t newblock = 0;
int free_on_err = 0, err = 0, depth, ret;
unsigned int allocated = 0, offset = 0;
unsigned int allocated_clusters = 0;
struct ext4_allocation_request ar;
ext4_lblk_t cluster_offset;
bool map_from_cluster = false;
ext_debug("blocks %u/%u requested for inode %lu\n",
map->m_lblk, map->m_len, inode->i_ino);
trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
/* find extent for this block */
path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out2;
}
depth = ext_depth(inode);
/*
* consistent leaf must not be empty;
* this situation is possible, though, _during_ tree modification;
* this is why assert can't be put in ext4_find_extent()
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode, "bad extent address "
"lblock: %lu, depth: %d pblock %lld",
(unsigned long) map->m_lblk, depth,
path[depth].p_block);
err = -EFSCORRUPTED;
goto out2;
}
ex = path[depth].p_ext;
if (ex) {
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len;
/*
* unwritten extents are treated as holes, except that
* we split out initialized portions during a write.
*/
ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
/* if found extent covers block, simply return it */
if (in_range(map->m_lblk, ee_block, ee_len)) {
newblock = map->m_lblk - ee_block + ee_start;
/* number of remaining blocks in the extent */
allocated = ee_len - (map->m_lblk - ee_block);
ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
ee_block, ee_len, newblock);
/*
* If the extent is initialized check whether the
* caller wants to convert it to unwritten.
*/
if ((!ext4_ext_is_unwritten(ex)) &&
(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
allocated = convert_initialized_extent(
handle, inode, map, &path,
allocated);
goto out2;
} else if (!ext4_ext_is_unwritten(ex))
goto out;
ret = ext4_ext_handle_unwritten_extents(
handle, inode, map, &path, flags,
allocated, newblock);
if (ret < 0)
err = ret;
else
allocated = ret;
goto out2;
}
}
/*
* requested block isn't allocated yet;
* we couldn't try to create block if create flag is zero
*/
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
ext4_lblk_t hole_start, hole_len;
hole_start = map->m_lblk;
hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
/*
* put just found gap into cache to speed up
* subsequent requests
*/
ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
/* Update hole_len to reflect hole size after map->m_lblk */
if (hole_start != map->m_lblk)
hole_len -= map->m_lblk - hole_start;
map->m_pblk = 0;
map->m_len = min_t(unsigned int, map->m_len, hole_len);
goto out2;
}
/*
* Okay, we need to do block allocation.
*/
newex.ee_block = cpu_to_le32(map->m_lblk);
cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
/*
* If we are doing bigalloc, check to see if the extent returned
* by ext4_find_extent() implies a cluster we can use.
*/
if (cluster_offset && ex &&
get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/* find neighbour allocated blocks */
ar.lleft = map->m_lblk;
err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
if (err)
goto out2;
ar.lright = map->m_lblk;
ex2 = NULL;
err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
if (err)
goto out2;
/* Check if the extent after searching to the right implies a
* cluster we can use. */
if ((sbi->s_cluster_ratio > 1) && ex2 &&
get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/*
* See if request is beyond maximum number of blocks we can have in
* a single extent. For an initialized extent this limit is
* EXT_INIT_MAX_LEN and for an unwritten extent this limit is
* EXT_UNWRITTEN_MAX_LEN.
*/
if (map->m_len > EXT_INIT_MAX_LEN &&
!(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_INIT_MAX_LEN;
else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_UNWRITTEN_MAX_LEN;
/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
newex.ee_len = cpu_to_le16(map->m_len);
err = ext4_ext_check_overlap(sbi, inode, &newex, path);
if (err)
allocated = ext4_ext_get_actual_len(&newex);
else
allocated = map->m_len;
/* allocate new block */
ar.inode = inode;
ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
ar.logical = map->m_lblk;
/*
* We calculate the offset from the beginning of the cluster
* for the logical block number, since when we allocate a
* physical cluster, the physical block should start at the
* same offset from the beginning of the cluster. This is
* needed so that future calls to get_implied_cluster_alloc()
* work correctly.
*/
offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
ar.goal -= offset;
ar.logical -= offset;
if (S_ISREG(inode->i_mode))
ar.flags = EXT4_MB_HINT_DATA;
else
/* disable in-core preallocation for non-regular files */
ar.flags = 0;
if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
ar.flags |= EXT4_MB_HINT_NOPREALLOC;
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ar.flags |= EXT4_MB_DELALLOC_RESERVED;
if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
ar.flags |= EXT4_MB_USE_RESERVED;
newblock = ext4_mb_new_blocks(handle, &ar, &err);
if (!newblock)
goto out2;
ext_debug("allocate new block: goal %llu, found %llu/%u\n",
ar.goal, newblock, allocated);
free_on_err = 1;
allocated_clusters = ar.len;
ar.len = EXT4_C2B(sbi, ar.len) - offset;
if (ar.len > allocated)
ar.len = allocated;
got_allocated_blocks:
/* try to insert new extent into found leaf and return */
ext4_ext_store_pblock(&newex, newblock + offset);
newex.ee_len = cpu_to_le16(ar.len);
/* Mark unwritten */
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
ext4_ext_mark_unwritten(&newex);
map->m_flags |= EXT4_MAP_UNWRITTEN;
}
err = 0;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, ar.len);
if (!err)
err = ext4_ext_insert_extent(handle, inode, &path,
&newex, flags);
if (err && free_on_err) {
int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
/* free data blocks we just allocated */
/* not a good idea to call discard here directly,
* but otherwise we'd need to call it every free() */
ext4_discard_preallocations(inode);
ext4_free_blocks(handle, inode, NULL, newblock,
EXT4_C2B(sbi, allocated_clusters), fb_flags);
goto out2;
}
/* previous routine could use block we allocated */
newblock = ext4_ext_pblock(&newex);
allocated = ext4_ext_get_actual_len(&newex);
if (allocated > map->m_len)
allocated = map->m_len;
map->m_flags |= EXT4_MAP_NEW;
/*
* Reduce the reserved cluster count to reflect successful deferred
* allocation of delayed allocated clusters or direct allocation of
* clusters discovered to be delayed allocated. Once allocated, a
* cluster is not included in the reserved count.
*/
if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
/*
* When allocating delayed allocated clusters, simply
* reduce the reserved cluster count and claim quota
*/
ext4_da_update_reserve_space(inode, allocated_clusters,
1);
} else {
ext4_lblk_t lblk, len;
unsigned int n;
/*
* When allocating non-delayed allocated clusters
* (from fallocate, filemap, DIO, or clusters
* allocated when delalloc has been disabled by
* ext4_nonda_switch), reduce the reserved cluster
* count by the number of allocated clusters that
* have previously been delayed allocated. Quota
* has been claimed by ext4_mb_new_blocks() above,
* so release the quota reservations made for any
* previously delayed allocated clusters.
*/
lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
len = allocated_clusters << sbi->s_cluster_bits;
n = ext4_es_delayed_clu(inode, lblk, len);
if (n > 0)
ext4_da_update_reserve_space(inode, (int) n, 0);
}
}
/*
* Cache the extent and update transaction to commit on fdatasync only
* when it is _not_ an unwritten extent.
*/
if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
else
ext4_update_inode_fsync_trans(handle, inode, 0);
out:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
map->m_len = allocated;
out2:
ext4_ext_drop_refs(path);
kfree(path);
trace_ext4_ext_map_blocks_exit(inode, flags, map,
err ? err : allocated);
return err ? err : allocated;
}
int ext4_ext_truncate(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t last_block;
int err = 0;
/*
* TODO: optimization is possible here.
* Probably we need not scan at all,
* because page truncation is enough.
*/
/* we have to know where to truncate from in crash case */
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_mark_inode_dirty(handle, inode);
if (err)
return err;
last_block = (inode->i_size + sb->s_blocksize - 1)
>> EXT4_BLOCK_SIZE_BITS(sb);
retry:
err = ext4_es_remove_extent(inode, last_block,
EXT_MAX_BLOCKS - last_block);
if (err == -ENOMEM) {
cond_resched();
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto retry;
}
if (err)
return err;
return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
}
static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
ext4_lblk_t len, loff_t new_size,
int flags)
{
struct inode *inode = file_inode(file);
handle_t *handle;
int ret = 0;
int ret2 = 0;
int retries = 0;
int depth = 0;
struct ext4_map_blocks map;
unsigned int credits;
loff_t epos;
BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
map.m_lblk = offset;
map.m_len = len;
/*
* Don't normalize the request if it can fit in one extent so
* that it doesn't get unnecessarily split into multiple
* extents.
*/
if (len <= EXT_UNWRITTEN_MAX_LEN)
flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
retry:
while (ret >= 0 && len) {
/*
* Recalculate credits when extent tree depth changes.
*/
if (depth != ext_depth(inode)) {
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
}
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
ret = ext4_map_blocks(handle, inode, &map, flags);
if (ret <= 0) {
ext4_debug("inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ext4_mark_inode_dirty(handle, inode);
ret2 = ext4_journal_stop(handle);
break;
}
map.m_lblk += ret;
map.m_len = len = len - ret;
epos = (loff_t)map.m_lblk << inode->i_blkbits;
inode->i_ctime = current_time(inode);
if (new_size) {
if (epos > new_size)
epos = new_size;
if (ext4_update_inode_size(inode, epos) & 0x1)
inode->i_mtime = inode->i_ctime;
} else {
if (epos > inode->i_size)
ext4_set_inode_flag(inode,
EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
ret2 = ext4_journal_stop(handle);
if (ret2)
break;
}
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries)) {
ret = 0;
goto retry;
}
return ret > 0 ? ret2 : ret;
}
static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
inode_lock(inode);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > i_size_read(inode) ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Wait all existing dio workers, newcomers will block on i_mutex */
inode_dio_wait(inode);
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/*
* Prevent page faults from reinstantiating pages we have
* released from page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret) {
up_write(&EXT4_I(inode)->i_mmap_sem);
goto out_mutex;
}
ret = ext4_update_disksize_before_punch(inode, offset, len);
if (ret) {
up_write(&EXT4_I(inode)->i_mmap_sem);
goto out_mutex;
}
/* Now release the pages and zero block aligned part of pages */
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = current_time(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags);
up_write(&EXT4_I(inode)->i_mmap_sem);
if (ret)
goto out_mutex;
}
if (!partial_begin && !partial_end)
goto out_mutex;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_mutex;
}
inode->i_mtime = inode->i_ctime = current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* preallocate space for a file. This implements ext4's fallocate file
* operation, which gets called from sys_fallocate system call.
* For block-mapped files, posix_fallocate should fall back to the method
* of writing zeroes to the required new blocks (the same behavior which is
* expected for file systems which do not support fallocate() system call).
*/
long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
loff_t new_size = 0;
unsigned int max_blocks;
int ret = 0;
int flags;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
/*
* Encrypted inodes can't handle collapse range or insert
* range since we would need to re-encrypt blocks with a
* different IV or XTS tweak (which are based on the logical
* block number).
*
* XXX It's not clear why zero range isn't working, but we'll
* leave it disabled for encrypted inodes for now. This is a
* bug we should fix....
*/
if (IS_ENCRYPTED(inode) &&
(mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
FALLOC_FL_ZERO_RANGE)))
return -EOPNOTSUPP;
/* Return error if mode is not supported */
if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
FALLOC_FL_INSERT_RANGE))
return -EOPNOTSUPP;
if (mode & FALLOC_FL_PUNCH_HOLE)
return ext4_punch_hole(inode, offset, len);
ret = ext4_convert_inline_data(inode);
if (ret)
return ret;
if (mode & FALLOC_FL_COLLAPSE_RANGE)
return ext4_collapse_range(inode, offset, len);
if (mode & FALLOC_FL_INSERT_RANGE)
return ext4_insert_range(inode, offset, len);
if (mode & FALLOC_FL_ZERO_RANGE)
return ext4_zero_range(file, offset, len, mode);
trace_ext4_fallocate_enter(inode, offset, len, mode);
lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
inode_lock(inode);
/*
* We only support preallocation for extent-based files only
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > i_size_read(inode) ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out;
}
/* Wait all existing dio workers, newcomers will block on i_mutex */
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
if (ret)
goto out;
if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
EXT4_I(inode)->i_sync_tid);
}
out:
inode_unlock(inode);
trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
return ret;
}
/*
* This function convert a range of blocks to written extents
* The caller of this function will pass the start offset and the size.
* all unwritten extents within this range will be converted to
* written extents.
*
* This function is called from the direct IO end io call back
* function, to convert the fallocated extents after IO is completed.
* Returns 0 on success.
*/
int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
loff_t offset, ssize_t len)
{
unsigned int max_blocks;
int ret = 0;
int ret2 = 0;
struct ext4_map_blocks map;
unsigned int credits, blkbits = inode->i_blkbits;
map.m_lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
/*
* This is somewhat ugly but the idea is clear: When transaction is
* reserved, everything goes into it. Otherwise we rather start several
* smaller transactions for conversion of each extent separately.
*/
if (handle) {
handle = ext4_journal_start_reserved(handle,
EXT4_HT_EXT_CONVERT);
if (IS_ERR(handle))
return PTR_ERR(handle);
credits = 0;
} else {
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, max_blocks);
}
while (ret >= 0 && ret < max_blocks) {
map.m_lblk += ret;
map.m_len = (max_blocks -= ret);
if (credits) {
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
}
ret = ext4_map_blocks(handle, inode, &map,
EXT4_GET_BLOCKS_IO_CONVERT_EXT);
if (ret <= 0)
ext4_warning(inode->i_sb,
"inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ext4_mark_inode_dirty(handle, inode);
if (credits)
ret2 = ext4_journal_stop(handle);
if (ret <= 0 || ret2)
break;
}
if (!credits)
ret2 = ext4_journal_stop(handle);
return ret > 0 ? ret2 : ret;
}
/*
* If newes is not existing extent (newes->ec_pblk equals zero) find
* delayed extent at start of newes and update newes accordingly and
* return start of the next delayed extent.
*
* If newes is existing extent (newes->ec_pblk is not equal zero)
* return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
* extent found. Leave newes unmodified.
*/
static int ext4_find_delayed_extent(struct inode *inode,
struct extent_status *newes)
{
struct extent_status es;
ext4_lblk_t block, next_del;
if (newes->es_pblk == 0) {
ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
newes->es_lblk,
newes->es_lblk + newes->es_len - 1,
&es);
/*
* No extent in extent-tree contains block @newes->es_pblk,
* then the block may stay in 1)a hole or 2)delayed-extent.
*/
if (es.es_len == 0)
/* A hole found. */
return 0;
if (es.es_lblk > newes->es_lblk) {
/* A hole found. */
newes->es_len = min(es.es_lblk - newes->es_lblk,
newes->es_len);
return 0;
}
newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
}
block = newes->es_lblk + newes->es_len;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed, block,
EXT_MAX_BLOCKS, &es);
if (es.es_len == 0)
next_del = EXT_MAX_BLOCKS;
else
next_del = es.es_lblk;
return next_del;
}
/* fiemap flags we can handle specified here */
#define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
static int ext4_xattr_fiemap(struct inode *inode,
struct fiemap_extent_info *fieinfo)
{
__u64 physical = 0;
__u64 length;
__u32 flags = FIEMAP_EXTENT_LAST;
int blockbits = inode->i_sb->s_blocksize_bits;
int error = 0;
/* in-inode? */
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
struct ext4_iloc iloc;
int offset; /* offset of xattr in inode */
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
physical = (__u64)iloc.bh->b_blocknr << blockbits;
offset = EXT4_GOOD_OLD_INODE_SIZE +
EXT4_I(inode)->i_extra_isize;
physical += offset;
length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
flags |= FIEMAP_EXTENT_DATA_INLINE;
brelse(iloc.bh);
} else { /* external block */
physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
length = inode->i_sb->s_blocksize;
}
if (physical)
error = fiemap_fill_next_extent(fieinfo, 0, physical,
length, flags);
return (error < 0 ? error : 0);
}
int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
ext4_lblk_t start_blk;
int error = 0;
if (ext4_has_inline_data(inode)) {
int has_inline = 1;
error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
start, len);
if (has_inline)
return error;
}
if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
error = ext4_ext_precache(inode);
if (error)
return error;
}
/* fallback to generic here if not in extents fmt */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
return generic_block_fiemap(inode, fieinfo, start, len,
ext4_get_block);
if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
return -EBADR;
if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
error = ext4_xattr_fiemap(inode, fieinfo);
} else {
ext4_lblk_t len_blks;
__u64 last_blk;
start_blk = start >> inode->i_sb->s_blocksize_bits;
last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
if (last_blk >= EXT_MAX_BLOCKS)
last_blk = EXT_MAX_BLOCKS-1;
len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
/*
* Walk the extent tree gathering extent information
* and pushing extents back to the user.
*/
error = ext4_fill_fiemap_extents(inode, start_blk,
len_blks, fieinfo);
}
return error;
}
/*
* ext4_access_path:
* Function to access the path buffer for marking it dirty.
* It also checks if there are sufficient credits left in the journal handle
* to update path.
*/
static int
ext4_access_path(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
int credits, err;
if (!ext4_handle_valid(handle))
return 0;
/*
* Check if need to extend journal credits
* 3 for leaf, sb, and inode plus 2 (bmap and group
* descriptor) for each block group; assume two block
* groups
*/
if (handle->h_buffer_credits < 7) {
credits = ext4_writepage_trans_blocks(inode);
err = ext4_ext_truncate_extend_restart(handle, inode, credits);
/* EAGAIN is success */
if (err && err != -EAGAIN)
return err;
}
err = ext4_ext_get_access(handle, inode, path);
return err;
}
/*
* ext4_ext_shift_path_extents:
* Shift the extents of a path structure lying between path[depth].p_ext
* and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
* if it is right shift or left shift operation.
*/
static int
ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
struct inode *inode, handle_t *handle,
enum SHIFT_DIRECTION SHIFT)
{
int depth, err = 0;
struct ext4_extent *ex_start, *ex_last;
bool update = 0;
depth = path->p_depth;
while (depth >= 0) {
if (depth == path->p_depth) {
ex_start = path[depth].p_ext;
if (!ex_start)
return -EFSCORRUPTED;
ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
err = ext4_access_path(handle, inode, path + depth);
if (err)
goto out;
if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
update = 1;
while (ex_start <= ex_last) {
if (SHIFT == SHIFT_LEFT) {
le32_add_cpu(&ex_start->ee_block,
-shift);
/* Try to merge to the left. */
if ((ex_start >
EXT_FIRST_EXTENT(path[depth].p_hdr))
&&
ext4_ext_try_to_merge_right(inode,
path, ex_start - 1))
ex_last--;
else
ex_start++;
} else {
le32_add_cpu(&ex_last->ee_block, shift);
ext4_ext_try_to_merge_right(inode, path,
ex_last);
ex_last--;
}
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
if (--depth < 0 || !update)
break;
}
/* Update index too */
err = ext4_access_path(handle, inode, path + depth);
if (err)
goto out;
if (SHIFT == SHIFT_LEFT)
le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
else
le32_add_cpu(&path[depth].p_idx->ei_block, shift);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
/* we are done if current index is not a starting index */
if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
break;
depth--;
}
out:
return err;
}
/*
* ext4_ext_shift_extents:
* All the extents which lies in the range from @start to the last allocated
* block for the @inode are shifted either towards left or right (depending
* upon @SHIFT) by @shift blocks.
* On success, 0 is returned, error otherwise.
*/
static int
ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
ext4_lblk_t start, ext4_lblk_t shift,
enum SHIFT_DIRECTION SHIFT)
{
struct ext4_ext_path *path;
int ret = 0, depth;
struct ext4_extent *extent;
ext4_lblk_t stop, *iterator, ex_start, ex_end;
/* Let path point to the last extent */
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent)
goto out;
stop = le32_to_cpu(extent->ee_block);
/*
* For left shifts, make sure the hole on the left is big enough to
* accommodate the shift. For right shifts, make sure the last extent
* won't be shifted beyond EXT_MAX_BLOCKS.
*/
if (SHIFT == SHIFT_LEFT) {
path = ext4_find_extent(inode, start - 1, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (extent) {
ex_start = le32_to_cpu(extent->ee_block);
ex_end = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
ex_start = 0;
ex_end = 0;
}
if ((start == ex_start && shift > ex_start) ||
(shift > start - ex_end)) {
ret = -EINVAL;
goto out;
}
} else {
if (shift > EXT_MAX_BLOCKS -
(stop + ext4_ext_get_actual_len(extent))) {
ret = -EINVAL;
goto out;
}
}
/*
* In case of left shift, iterator points to start and it is increased
* till we reach stop. In case of right shift, iterator points to stop
* and it is decreased till we reach start.
*/
if (SHIFT == SHIFT_LEFT)
iterator = &start;
else
iterator = &stop;
/*
* Its safe to start updating extents. Start and stop are unsigned, so
* in case of right shift if extent with 0 block is reached, iterator
* becomes NULL to indicate the end of the loop.
*/
while (iterator && start <= stop) {
path = ext4_find_extent(inode, *iterator, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) *iterator);
return -EFSCORRUPTED;
}
if (SHIFT == SHIFT_LEFT && *iterator >
le32_to_cpu(extent->ee_block)) {
/* Hole, move to the next extent */
if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
path[depth].p_ext++;
} else {
*iterator = ext4_ext_next_allocated_block(path);
continue;
}
}
if (SHIFT == SHIFT_LEFT) {
extent = EXT_LAST_EXTENT(path[depth].p_hdr);
*iterator = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
if (le32_to_cpu(extent->ee_block) > 0)
*iterator = le32_to_cpu(extent->ee_block) - 1;
else
/* Beginning is reached, end of the loop */
iterator = NULL;
/* Update path extent in case we need to stop */
while (le32_to_cpu(extent->ee_block) < start)
extent++;
path[depth].p_ext = extent;
}
ret = ext4_ext_shift_path_extents(path, shift, inode,
handle, SHIFT);
if (ret)
break;
}
out:
ext4_ext_drop_refs(path);
kfree(path);
return ret;
}
/*
* ext4_collapse_range:
* This implements the fallocate's collapse range functionality for ext4
* Returns: 0 and non-zero on error.
*/
int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t punch_start, punch_stop;
handle_t *handle;
unsigned int credits;
loff_t new_size, ioffset;
int ret;
/*
* We need to test this early because xfstests assumes that a
* collapse range of (0, 1) will return EOPNOTSUPP if the file
* system does not support collapse range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Collapse range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
trace_ext4_collapse_range(inode, offset, len);
punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
inode_lock(inode);
/*
* There is no need to overlap collapse range with EOF, in which case
* it is effectively a truncate operation
*/
if (offset + len >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down offset to be aligned with page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/*
* Write tail of the last page before removed range since it will get
* removed from the page cache below.
*/
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
if (ret)
goto out_mmap;
/*
* Write data that will be shifted to preserve them when discarding
* page cache below. We are also protected from pages becoming dirty
* by i_mmap_sem.
*/
ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, punch_start,
EXT_MAX_BLOCKS - punch_start);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ext4_discard_preallocations(inode);
ret = ext4_ext_shift_extents(inode, handle, punch_stop,
punch_stop - punch_start, SHIFT_LEFT);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
new_size = i_size_read(inode) - len;
i_size_write(inode, new_size);
EXT4_I(inode)->i_disksize = new_size;
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode->i_ctime = current_time(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* ext4_insert_range:
* This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
* The data blocks starting from @offset to the EOF are shifted by @len
* towards right to create a hole in the @inode. Inode size is increased
* by len bytes.
* Returns 0 on success, error otherwise.
*/
int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
handle_t *handle;
struct ext4_ext_path *path;
struct ext4_extent *extent;
ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
unsigned int credits, ee_len;
int ret = 0, depth, split_flag = 0;
loff_t ioffset;
/*
* We need to test this early because xfstests assumes that an
* insert range of (0, 1) will return EOPNOTSUPP if the file
* system does not support insert range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Insert range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_insert_range(inode, offset, len);
offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
inode_lock(inode);
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Check for wrap through zero */
if (inode->i_size + len > inode->i_sb->s_maxbytes) {
ret = -EFBIG;
goto out_mutex;
}
/* Offset should be less than i_size */
if (offset >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down to align start offset to page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
/* Expand file to avoid data loss if there is error while shifting */
inode->i_size += len;
EXT4_I(inode)->i_disksize += len;
inode->i_mtime = inode->i_ctime = current_time(inode);
ret = ext4_mark_inode_dirty(handle, inode);
if (ret)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
path = ext4_find_extent(inode, offset_lblk, NULL, 0);
if (IS_ERR(path)) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
depth = ext_depth(inode);
extent = path[depth].p_ext;
if (extent) {
ee_start_lblk = le32_to_cpu(extent->ee_block);
ee_len = ext4_ext_get_actual_len(extent);
/*
* If offset_lblk is not the starting block of extent, split
* the extent @offset_lblk
*/
if ((offset_lblk > ee_start_lblk) &&
(offset_lblk < (ee_start_lblk + ee_len))) {
if (ext4_ext_is_unwritten(extent))
split_flag = EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
ret = ext4_split_extent_at(handle, inode, &path,
offset_lblk, split_flag,
EXT4_EX_NOCACHE |
EXT4_GET_BLOCKS_PRE_IO |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
}
ext4_ext_drop_refs(path);
kfree(path);
if (ret < 0) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
} else {
ext4_ext_drop_refs(path);
kfree(path);
}
ret = ext4_es_remove_extent(inode, offset_lblk,
EXT_MAX_BLOCKS - offset_lblk);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
/*
* if offset_lblk lies in a hole which is at start of file, use
* ee_start_lblk to shift extents
*/
ret = ext4_ext_shift_extents(inode, handle,
ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
len_lblk, SHIFT_RIGHT);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
out_mutex:
inode_unlock(inode);
return ret;
}
/**
* ext4_swap_extents - Swap extents between two inodes
*
* @inode1: First inode
* @inode2: Second inode
* @lblk1: Start block for first inode
* @lblk2: Start block for second inode
* @count: Number of blocks to swap
* @unwritten: Mark second inode's extents as unwritten after swap
* @erp: Pointer to save error value
*
* This helper routine does exactly what is promise "swap extents". All other
* stuff such as page-cache locking consistency, bh mapping consistency or
* extent's data copying must be performed by caller.
* Locking:
* i_mutex is held for both inodes
* i_data_sem is locked for write for both inodes
* Assumptions:
* All pages from requested range are locked for both inodes
*/
int
ext4_swap_extents(handle_t *handle, struct inode *inode1,
struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
ext4_lblk_t count, int unwritten, int *erp)
{
struct ext4_ext_path *path1 = NULL;
struct ext4_ext_path *path2 = NULL;
int replaced_count = 0;
BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
BUG_ON(!inode_is_locked(inode1));
BUG_ON(!inode_is_locked(inode2));
*erp = ext4_es_remove_extent(inode1, lblk1, count);
if (unlikely(*erp))
return 0;
*erp = ext4_es_remove_extent(inode2, lblk2, count);
if (unlikely(*erp))
return 0;
while (count) {
struct ext4_extent *ex1, *ex2, tmp_ex;
ext4_lblk_t e1_blk, e2_blk;
int e1_len, e2_len, len;
int split = 0;
path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path1)) {
*erp = PTR_ERR(path1);
path1 = NULL;
finish:
count = 0;
goto repeat;
}
path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path2)) {
*erp = PTR_ERR(path2);
path2 = NULL;
goto finish;
}
ex1 = path1[path1->p_depth].p_ext;
ex2 = path2[path2->p_depth].p_ext;
/* Do we have somthing to swap ? */
if (unlikely(!ex2 || !ex1))
goto finish;
e1_blk = le32_to_cpu(ex1->ee_block);
e2_blk = le32_to_cpu(ex2->ee_block);
e1_len = ext4_ext_get_actual_len(ex1);
e2_len = ext4_ext_get_actual_len(ex2);
/* Hole handling */
if (!in_range(lblk1, e1_blk, e1_len) ||
!in_range(lblk2, e2_blk, e2_len)) {
ext4_lblk_t next1, next2;
/* if hole after extent, then go to next extent */
next1 = ext4_ext_next_allocated_block(path1);
next2 = ext4_ext_next_allocated_block(path2);
/* If hole before extent, then shift to that extent */
if (e1_blk > lblk1)
next1 = e1_blk;
if (e2_blk > lblk2)
next2 = e2_blk;
/* Do we have something to swap */
if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
goto finish;
/* Move to the rightest boundary */
len = next1 - lblk1;
if (len < next2 - lblk2)
len = next2 - lblk2;
if (len > count)
len = count;
lblk1 += len;
lblk2 += len;
count -= len;
goto repeat;
}
/* Prepare left boundary */
if (e1_blk < lblk1) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1, 0);
if (unlikely(*erp))
goto finish;
}
if (e2_blk < lblk2) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2, 0);
if (unlikely(*erp))
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
/* Prepare right boundary */
len = count;
if (len > e1_blk + e1_len - lblk1)
len = e1_blk + e1_len - lblk1;
if (len > e2_blk + e2_len - lblk2)
len = e2_blk + e2_len - lblk2;
if (len != e1_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1 + len, 0);
if (unlikely(*erp))
goto finish;
}
if (len != e2_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2 + len, 0);
if (*erp)
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
BUG_ON(e2_len != e1_len);
*erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
if (unlikely(*erp))
goto finish;
/* Both extents are fully inside boundaries. Swap it now */
tmp_ex = *ex1;
ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
ex1->ee_len = cpu_to_le16(e2_len);
ex2->ee_len = cpu_to_le16(e1_len);
if (unwritten)
ext4_ext_mark_unwritten(ex2);
if (ext4_ext_is_unwritten(&tmp_ex))
ext4_ext_mark_unwritten(ex1);
ext4_ext_try_to_merge(handle, inode2, path2, ex2);
ext4_ext_try_to_merge(handle, inode1, path1, ex1);
*erp = ext4_ext_dirty(handle, inode2, path2 +
path2->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_dirty(handle, inode1, path1 +
path1->p_depth);
/*
* Looks scarry ah..? second inode already points to new blocks,
* and it was successfully dirtied. But luckily error may happen
* only due to journal error, so full transaction will be
* aborted anyway.
*/
if (unlikely(*erp))
goto finish;
lblk1 += len;
lblk2 += len;
replaced_count += len;
count -= len;
repeat:
ext4_ext_drop_refs(path1);
kfree(path1);
ext4_ext_drop_refs(path2);
kfree(path2);
path1 = path2 = NULL;
}
return replaced_count;
}
/*
* ext4_clu_mapped - determine whether any block in a logical cluster has
* been mapped to a physical cluster
*
* @inode - file containing the logical cluster
* @lclu - logical cluster of interest
*
* Returns 1 if any block in the logical cluster is mapped, signifying
* that a physical cluster has been allocated for it. Otherwise,
* returns 0. Can also return negative error codes. Derived from
* ext4_ext_map_blocks().
*/
int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_ext_path *path;
int depth, mapped = 0, err = 0;
struct ext4_extent *extent;
ext4_lblk_t first_lblk, first_lclu, last_lclu;
/* search for the extent closest to the first block in the cluster */
path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out;
}
depth = ext_depth(inode);
/*
* A consistent leaf must not be empty. This situation is possible,
* though, _during_ tree modification, and it's why an assert can't
* be put in ext4_find_extent().
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode,
"bad extent address - lblock: %lu, depth: %d, pblock: %lld",
(unsigned long) EXT4_C2B(sbi, lclu),
depth, path[depth].p_block);
err = -EFSCORRUPTED;
goto out;
}
extent = path[depth].p_ext;
/* can't be mapped if the extent tree is empty */
if (extent == NULL)
goto out;
first_lblk = le32_to_cpu(extent->ee_block);
first_lclu = EXT4_B2C(sbi, first_lblk);
/*
* Three possible outcomes at this point - found extent spanning
* the target cluster, to the left of the target cluster, or to the
* right of the target cluster. The first two cases are handled here.
* The last case indicates the target cluster is not mapped.
*/
if (lclu >= first_lclu) {
last_lclu = EXT4_B2C(sbi, first_lblk +
ext4_ext_get_actual_len(extent) - 1);
if (lclu <= last_lclu) {
mapped = 1;
} else {
first_lblk = ext4_ext_next_allocated_block(path);
first_lclu = EXT4_B2C(sbi, first_lblk);
if (lclu == first_lclu)
mapped = 1;
}
}
out:
ext4_ext_drop_refs(path);
kfree(path);
return err ? err : mapped;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_837_0 |
crossvul-cpp_data_bad_2426_0 | /*
* kernel/sched/core.c
*
* Kernel scheduler and related syscalls
*
* Copyright (C) 1991-2002 Linus Torvalds
*
* 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
* make semaphores SMP safe
* 1998-11-19 Implemented schedule_timeout() and related stuff
* by Andrea Arcangeli
* 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
* hybrid priority-list and round-robin design with
* an array-switch method of distributing timeslices
* and per-CPU runqueues. Cleanups and useful suggestions
* by Davide Libenzi, preemptible kernel bits by Robert Love.
* 2003-09-03 Interactivity tuning by Con Kolivas.
* 2004-04-02 Scheduler domains code by Nick Piggin
* 2007-04-15 Work begun on replacing all interactivity tuning with a
* fair scheduling design by Con Kolivas.
* 2007-05-05 Load balancing (smp-nice) and other improvements
* by Peter Williams
* 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
* 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
* 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
* Thomas Gleixner, Mike Kravetz
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/nmi.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/highmem.h>
#include <asm/mmu_context.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/kernel_stat.h>
#include <linux/debug_locks.h>
#include <linux/perf_event.h>
#include <linux/security.h>
#include <linux/notifier.h>
#include <linux/profile.h>
#include <linux/freezer.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/pid_namespace.h>
#include <linux/smp.h>
#include <linux/threads.h>
#include <linux/timer.h>
#include <linux/rcupdate.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/percpu.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sysctl.h>
#include <linux/syscalls.h>
#include <linux/times.h>
#include <linux/tsacct_kern.h>
#include <linux/kprobes.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/pagemap.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/debugfs.h>
#include <linux/ctype.h>
#include <linux/ftrace.h>
#include <linux/slab.h>
#include <linux/init_task.h>
#include <linux/binfmts.h>
#include <linux/context_tracking.h>
#include <asm/switch_to.h>
#include <asm/tlb.h>
#include <asm/irq_regs.h>
#include <asm/mutex.h>
#ifdef CONFIG_PARAVIRT
#include <asm/paravirt.h>
#endif
#include "sched.h"
#include "../workqueue_internal.h"
#include "../smpboot.h"
#define CREATE_TRACE_POINTS
#include <trace/events/sched.h>
void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
{
unsigned long delta;
ktime_t soft, hard, now;
for (;;) {
if (hrtimer_active(period_timer))
break;
now = hrtimer_cb_get_time(period_timer);
hrtimer_forward(period_timer, now, period);
soft = hrtimer_get_softexpires(period_timer);
hard = hrtimer_get_expires(period_timer);
delta = ktime_to_ns(ktime_sub(hard, soft));
__hrtimer_start_range_ns(period_timer, soft, delta,
HRTIMER_MODE_ABS_PINNED, 0);
}
}
DEFINE_MUTEX(sched_domains_mutex);
DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
static void update_rq_clock_task(struct rq *rq, s64 delta);
void update_rq_clock(struct rq *rq)
{
s64 delta;
if (rq->skip_clock_update > 0)
return;
delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
rq->clock += delta;
update_rq_clock_task(rq, delta);
}
/*
* Debugging: various feature bits
*/
#define SCHED_FEAT(name, enabled) \
(1UL << __SCHED_FEAT_##name) * enabled |
const_debug unsigned int sysctl_sched_features =
#include "features.h"
0;
#undef SCHED_FEAT
#ifdef CONFIG_SCHED_DEBUG
#define SCHED_FEAT(name, enabled) \
#name ,
static const char * const sched_feat_names[] = {
#include "features.h"
};
#undef SCHED_FEAT
static int sched_feat_show(struct seq_file *m, void *v)
{
int i;
for (i = 0; i < __SCHED_FEAT_NR; i++) {
if (!(sysctl_sched_features & (1UL << i)))
seq_puts(m, "NO_");
seq_printf(m, "%s ", sched_feat_names[i]);
}
seq_puts(m, "\n");
return 0;
}
#ifdef HAVE_JUMP_LABEL
#define jump_label_key__true STATIC_KEY_INIT_TRUE
#define jump_label_key__false STATIC_KEY_INIT_FALSE
#define SCHED_FEAT(name, enabled) \
jump_label_key__##enabled ,
struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
#include "features.h"
};
#undef SCHED_FEAT
static void sched_feat_disable(int i)
{
if (static_key_enabled(&sched_feat_keys[i]))
static_key_slow_dec(&sched_feat_keys[i]);
}
static void sched_feat_enable(int i)
{
if (!static_key_enabled(&sched_feat_keys[i]))
static_key_slow_inc(&sched_feat_keys[i]);
}
#else
static void sched_feat_disable(int i) { };
static void sched_feat_enable(int i) { };
#endif /* HAVE_JUMP_LABEL */
static int sched_feat_set(char *cmp)
{
int i;
int neg = 0;
if (strncmp(cmp, "NO_", 3) == 0) {
neg = 1;
cmp += 3;
}
for (i = 0; i < __SCHED_FEAT_NR; i++) {
if (strcmp(cmp, sched_feat_names[i]) == 0) {
if (neg) {
sysctl_sched_features &= ~(1UL << i);
sched_feat_disable(i);
} else {
sysctl_sched_features |= (1UL << i);
sched_feat_enable(i);
}
break;
}
}
return i;
}
static ssize_t
sched_feat_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
char *cmp;
int i;
if (cnt > 63)
cnt = 63;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
cmp = strstrip(buf);
i = sched_feat_set(cmp);
if (i == __SCHED_FEAT_NR)
return -EINVAL;
*ppos += cnt;
return cnt;
}
static int sched_feat_open(struct inode *inode, struct file *filp)
{
return single_open(filp, sched_feat_show, NULL);
}
static const struct file_operations sched_feat_fops = {
.open = sched_feat_open,
.write = sched_feat_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static __init int sched_init_debug(void)
{
debugfs_create_file("sched_features", 0644, NULL, NULL,
&sched_feat_fops);
return 0;
}
late_initcall(sched_init_debug);
#endif /* CONFIG_SCHED_DEBUG */
/*
* Number of tasks to iterate in a single balance run.
* Limited because this is done with IRQs disabled.
*/
const_debug unsigned int sysctl_sched_nr_migrate = 32;
/*
* period over which we average the RT time consumption, measured
* in ms.
*
* default: 1s
*/
const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
/*
* period over which we measure -rt task cpu usage in us.
* default: 1s
*/
unsigned int sysctl_sched_rt_period = 1000000;
__read_mostly int scheduler_running;
/*
* part of the period that we allow rt tasks to run in us.
* default: 0.95s
*/
int sysctl_sched_rt_runtime = 950000;
/*
* __task_rq_lock - lock the rq @p resides on.
*/
static inline struct rq *__task_rq_lock(struct task_struct *p)
__acquires(rq->lock)
{
struct rq *rq;
lockdep_assert_held(&p->pi_lock);
for (;;) {
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p)))
return rq;
raw_spin_unlock(&rq->lock);
}
}
/*
* task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
*/
static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
__acquires(p->pi_lock)
__acquires(rq->lock)
{
struct rq *rq;
for (;;) {
raw_spin_lock_irqsave(&p->pi_lock, *flags);
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p)))
return rq;
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
}
}
static void __task_rq_unlock(struct rq *rq)
__releases(rq->lock)
{
raw_spin_unlock(&rq->lock);
}
static inline void
task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
__releases(rq->lock)
__releases(p->pi_lock)
{
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
}
/*
* this_rq_lock - lock this runqueue and disable interrupts.
*/
static struct rq *this_rq_lock(void)
__acquires(rq->lock)
{
struct rq *rq;
local_irq_disable();
rq = this_rq();
raw_spin_lock(&rq->lock);
return rq;
}
#ifdef CONFIG_SCHED_HRTICK
/*
* Use HR-timers to deliver accurate preemption points.
*/
static void hrtick_clear(struct rq *rq)
{
if (hrtimer_active(&rq->hrtick_timer))
hrtimer_cancel(&rq->hrtick_timer);
}
/*
* High-resolution timer tick.
* Runs from hardirq context with interrupts disabled.
*/
static enum hrtimer_restart hrtick(struct hrtimer *timer)
{
struct rq *rq = container_of(timer, struct rq, hrtick_timer);
WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
rq->curr->sched_class->task_tick(rq, rq->curr, 1);
raw_spin_unlock(&rq->lock);
return HRTIMER_NORESTART;
}
#ifdef CONFIG_SMP
static int __hrtick_restart(struct rq *rq)
{
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t time = hrtimer_get_softexpires(timer);
return __hrtimer_start_range_ns(timer, time, 0, HRTIMER_MODE_ABS_PINNED, 0);
}
/*
* called from hardirq (IPI) context
*/
static void __hrtick_start(void *arg)
{
struct rq *rq = arg;
raw_spin_lock(&rq->lock);
__hrtick_restart(rq);
rq->hrtick_csd_pending = 0;
raw_spin_unlock(&rq->lock);
}
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
hrtimer_set_expires(timer, time);
if (rq == this_rq()) {
__hrtick_restart(rq);
} else if (!rq->hrtick_csd_pending) {
__smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
rq->hrtick_csd_pending = 1;
}
}
static int
hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
int cpu = (int)(long)hcpu;
switch (action) {
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DOWN_PREPARE:
case CPU_DOWN_PREPARE_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
hrtick_clear(cpu_rq(cpu));
return NOTIFY_OK;
}
return NOTIFY_DONE;
}
static __init void init_hrtick(void)
{
hotcpu_notifier(hotplug_hrtick, 0);
}
#else
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
__hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
HRTIMER_MODE_REL_PINNED, 0);
}
static inline void init_hrtick(void)
{
}
#endif /* CONFIG_SMP */
static void init_rq_hrtick(struct rq *rq)
{
#ifdef CONFIG_SMP
rq->hrtick_csd_pending = 0;
rq->hrtick_csd.flags = 0;
rq->hrtick_csd.func = __hrtick_start;
rq->hrtick_csd.info = rq;
#endif
hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rq->hrtick_timer.function = hrtick;
}
#else /* CONFIG_SCHED_HRTICK */
static inline void hrtick_clear(struct rq *rq)
{
}
static inline void init_rq_hrtick(struct rq *rq)
{
}
static inline void init_hrtick(void)
{
}
#endif /* CONFIG_SCHED_HRTICK */
/*
* resched_task - mark a task 'to be rescheduled now'.
*
* On UP this means the setting of the need_resched flag, on SMP it
* might also involve a cross-CPU call to trigger the scheduler on
* the target CPU.
*/
void resched_task(struct task_struct *p)
{
int cpu;
lockdep_assert_held(&task_rq(p)->lock);
if (test_tsk_need_resched(p))
return;
set_tsk_need_resched(p);
cpu = task_cpu(p);
if (cpu == smp_processor_id()) {
set_preempt_need_resched();
return;
}
/* NEED_RESCHED must be visible before we test polling */
smp_mb();
if (!tsk_is_polling(p))
smp_send_reschedule(cpu);
}
void resched_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
if (!raw_spin_trylock_irqsave(&rq->lock, flags))
return;
resched_task(cpu_curr(cpu));
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
#ifdef CONFIG_SMP
#ifdef CONFIG_NO_HZ_COMMON
/*
* In the semi idle case, use the nearest busy cpu for migrating timers
* from an idle cpu. This is good for power-savings.
*
* We don't do similar optimization for completely idle system, as
* selecting an idle cpu will add more delays to the timers than intended
* (as that cpu's timer base may not be uptodate wrt jiffies etc).
*/
int get_nohz_timer_target(void)
{
int cpu = smp_processor_id();
int i;
struct sched_domain *sd;
rcu_read_lock();
for_each_domain(cpu, sd) {
for_each_cpu(i, sched_domain_span(sd)) {
if (!idle_cpu(i)) {
cpu = i;
goto unlock;
}
}
}
unlock:
rcu_read_unlock();
return cpu;
}
/*
* When add_timer_on() enqueues a timer into the timer wheel of an
* idle CPU then this timer might expire before the next timer event
* which is scheduled to wake up that CPU. In case of a completely
* idle system the next event might even be infinite time into the
* future. wake_up_idle_cpu() ensures that the CPU is woken up and
* leaves the inner idle loop so the newly added timer is taken into
* account when the CPU goes back to idle and evaluates the timer
* wheel for the next timer event.
*/
static void wake_up_idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (cpu == smp_processor_id())
return;
/*
* This is safe, as this function is called with the timer
* wheel base lock of (cpu) held. When the CPU is on the way
* to idle and has not yet set rq->curr to idle then it will
* be serialized on the timer wheel base lock and take the new
* timer into account automatically.
*/
if (rq->curr != rq->idle)
return;
/*
* We can set TIF_RESCHED on the idle task of the other CPU
* lockless. The worst case is that the other CPU runs the
* idle task through an additional NOOP schedule()
*/
set_tsk_need_resched(rq->idle);
/* NEED_RESCHED must be visible before we test polling */
smp_mb();
if (!tsk_is_polling(rq->idle))
smp_send_reschedule(cpu);
}
static bool wake_up_full_nohz_cpu(int cpu)
{
if (tick_nohz_full_cpu(cpu)) {
if (cpu != smp_processor_id() ||
tick_nohz_tick_stopped())
smp_send_reschedule(cpu);
return true;
}
return false;
}
void wake_up_nohz_cpu(int cpu)
{
if (!wake_up_full_nohz_cpu(cpu))
wake_up_idle_cpu(cpu);
}
static inline bool got_nohz_idle_kick(void)
{
int cpu = smp_processor_id();
if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
return false;
if (idle_cpu(cpu) && !need_resched())
return true;
/*
* We can't run Idle Load Balance on this CPU for this time so we
* cancel it and clear NOHZ_BALANCE_KICK
*/
clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
return false;
}
#else /* CONFIG_NO_HZ_COMMON */
static inline bool got_nohz_idle_kick(void)
{
return false;
}
#endif /* CONFIG_NO_HZ_COMMON */
#ifdef CONFIG_NO_HZ_FULL
bool sched_can_stop_tick(void)
{
struct rq *rq;
rq = this_rq();
/* Make sure rq->nr_running update is visible after the IPI */
smp_rmb();
/* More than one running task need preemption */
if (rq->nr_running > 1)
return false;
return true;
}
#endif /* CONFIG_NO_HZ_FULL */
void sched_avg_update(struct rq *rq)
{
s64 period = sched_avg_period();
while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
/*
* Inline assembly required to prevent the compiler
* optimising this loop into a divmod call.
* See __iter_div_u64_rem() for another example of this.
*/
asm("" : "+rm" (rq->age_stamp));
rq->age_stamp += period;
rq->rt_avg /= 2;
}
}
#endif /* CONFIG_SMP */
#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
/*
* Iterate task_group tree rooted at *from, calling @down when first entering a
* node and @up when leaving it for the final time.
*
* Caller must hold rcu_lock or sufficient equivalent.
*/
int walk_tg_tree_from(struct task_group *from,
tg_visitor down, tg_visitor up, void *data)
{
struct task_group *parent, *child;
int ret;
parent = from;
down:
ret = (*down)(parent, data);
if (ret)
goto out;
list_for_each_entry_rcu(child, &parent->children, siblings) {
parent = child;
goto down;
up:
continue;
}
ret = (*up)(parent, data);
if (ret || parent == from)
goto out;
child = parent;
parent = parent->parent;
if (parent)
goto up;
out:
return ret;
}
int tg_nop(struct task_group *tg, void *data)
{
return 0;
}
#endif
static void set_load_weight(struct task_struct *p)
{
int prio = p->static_prio - MAX_RT_PRIO;
struct load_weight *load = &p->se.load;
/*
* SCHED_IDLE tasks get minimal weight:
*/
if (p->policy == SCHED_IDLE) {
load->weight = scale_load(WEIGHT_IDLEPRIO);
load->inv_weight = WMULT_IDLEPRIO;
return;
}
load->weight = scale_load(prio_to_weight[prio]);
load->inv_weight = prio_to_wmult[prio];
}
static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
sched_info_queued(rq, p);
p->sched_class->enqueue_task(rq, p, flags);
}
static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
sched_info_dequeued(rq, p);
p->sched_class->dequeue_task(rq, p, flags);
}
void activate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible--;
enqueue_task(rq, p, flags);
}
void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible++;
dequeue_task(rq, p, flags);
}
static void update_rq_clock_task(struct rq *rq, s64 delta)
{
/*
* In theory, the compile should just see 0 here, and optimize out the call
* to sched_rt_avg_update. But I don't trust it...
*/
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
s64 steal = 0, irq_delta = 0;
#endif
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
/*
* Since irq_time is only updated on {soft,}irq_exit, we might run into
* this case when a previous update_rq_clock() happened inside a
* {soft,}irq region.
*
* When this happens, we stop ->clock_task and only update the
* prev_irq_time stamp to account for the part that fit, so that a next
* update will consume the rest. This ensures ->clock_task is
* monotonic.
*
* It does however cause some slight miss-attribution of {soft,}irq
* time, a more accurate solution would be to update the irq_time using
* the current rq->clock timestamp, except that would require using
* atomic ops.
*/
if (irq_delta > delta)
irq_delta = delta;
rq->prev_irq_time += irq_delta;
delta -= irq_delta;
#endif
#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
if (static_key_false((¶virt_steal_rq_enabled))) {
u64 st;
steal = paravirt_steal_clock(cpu_of(rq));
steal -= rq->prev_steal_time_rq;
if (unlikely(steal > delta))
steal = delta;
st = steal_ticks(steal);
steal = st * TICK_NSEC;
rq->prev_steal_time_rq += steal;
delta -= steal;
}
#endif
rq->clock_task += delta;
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
sched_rt_avg_update(rq, irq_delta + steal);
#endif
}
void sched_set_stop_task(int cpu, struct task_struct *stop)
{
struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
struct task_struct *old_stop = cpu_rq(cpu)->stop;
if (stop) {
/*
* Make it appear like a SCHED_FIFO task, its something
* userspace knows about and won't get confused about.
*
* Also, it will make PI more or less work without too
* much confusion -- but then, stop work should not
* rely on PI working anyway.
*/
sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
stop->sched_class = &stop_sched_class;
}
cpu_rq(cpu)->stop = stop;
if (old_stop) {
/*
* Reset it back to a normal scheduling class so that
* it can die in pieces.
*/
old_stop->sched_class = &rt_sched_class;
}
}
/*
* __normal_prio - return the priority that is based on the static prio
*/
static inline int __normal_prio(struct task_struct *p)
{
return p->static_prio;
}
/*
* Calculate the expected normal priority: i.e. priority
* without taking RT-inheritance into account. Might be
* boosted by interactivity modifiers. Changes upon fork,
* setprio syscalls, and whenever the interactivity
* estimator recalculates.
*/
static inline int normal_prio(struct task_struct *p)
{
int prio;
if (task_has_dl_policy(p))
prio = MAX_DL_PRIO-1;
else if (task_has_rt_policy(p))
prio = MAX_RT_PRIO-1 - p->rt_priority;
else
prio = __normal_prio(p);
return prio;
}
/*
* Calculate the current priority, i.e. the priority
* taken into account by the scheduler. This value might
* be boosted by RT tasks, or might be boosted by
* interactivity modifiers. Will be RT if the task got
* RT-boosted. If not then it returns p->normal_prio.
*/
static int effective_prio(struct task_struct *p)
{
p->normal_prio = normal_prio(p);
/*
* If we are RT tasks or we were boosted to RT priority,
* keep the priority unchanged. Otherwise, update priority
* to the normal priority:
*/
if (!rt_prio(p->prio))
return p->normal_prio;
return p->prio;
}
/**
* task_curr - is this task currently executing on a CPU?
* @p: the task in question.
*
* Return: 1 if the task is currently executing. 0 otherwise.
*/
inline int task_curr(const struct task_struct *p)
{
return cpu_curr(task_cpu(p)) == p;
}
static inline void check_class_changed(struct rq *rq, struct task_struct *p,
const struct sched_class *prev_class,
int oldprio)
{
if (prev_class != p->sched_class) {
if (prev_class->switched_from)
prev_class->switched_from(rq, p);
p->sched_class->switched_to(rq, p);
} else if (oldprio != p->prio || dl_task(p))
p->sched_class->prio_changed(rq, p, oldprio);
}
void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_task(rq->curr);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
rq->skip_clock_update = 1;
}
#ifdef CONFIG_SMP
void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
{
#ifdef CONFIG_SCHED_DEBUG
/*
* We should never call set_task_cpu() on a blocked task,
* ttwu() will sort out the placement.
*/
WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
!(task_preempt_count(p) & PREEMPT_ACTIVE));
#ifdef CONFIG_LOCKDEP
/*
* The caller should hold either p->pi_lock or rq->lock, when changing
* a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
*
* sched_move_task() holds both and thus holding either pins the cgroup,
* see task_group().
*
* Furthermore, all task_rq users should acquire both locks, see
* task_rq_lock().
*/
WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
lockdep_is_held(&task_rq(p)->lock)));
#endif
#endif
trace_sched_migrate_task(p, new_cpu);
if (task_cpu(p) != new_cpu) {
if (p->sched_class->migrate_task_rq)
p->sched_class->migrate_task_rq(p, new_cpu);
p->se.nr_migrations++;
perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
}
__set_task_cpu(p, new_cpu);
}
static void __migrate_swap_task(struct task_struct *p, int cpu)
{
if (p->on_rq) {
struct rq *src_rq, *dst_rq;
src_rq = task_rq(p);
dst_rq = cpu_rq(cpu);
deactivate_task(src_rq, p, 0);
set_task_cpu(p, cpu);
activate_task(dst_rq, p, 0);
check_preempt_curr(dst_rq, p, 0);
} else {
/*
* Task isn't running anymore; make it appear like we migrated
* it before it went to sleep. This means on wakeup we make the
* previous cpu our targer instead of where it really is.
*/
p->wake_cpu = cpu;
}
}
struct migration_swap_arg {
struct task_struct *src_task, *dst_task;
int src_cpu, dst_cpu;
};
static int migrate_swap_stop(void *data)
{
struct migration_swap_arg *arg = data;
struct rq *src_rq, *dst_rq;
int ret = -EAGAIN;
src_rq = cpu_rq(arg->src_cpu);
dst_rq = cpu_rq(arg->dst_cpu);
double_raw_lock(&arg->src_task->pi_lock,
&arg->dst_task->pi_lock);
double_rq_lock(src_rq, dst_rq);
if (task_cpu(arg->dst_task) != arg->dst_cpu)
goto unlock;
if (task_cpu(arg->src_task) != arg->src_cpu)
goto unlock;
if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
goto unlock;
if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
goto unlock;
__migrate_swap_task(arg->src_task, arg->dst_cpu);
__migrate_swap_task(arg->dst_task, arg->src_cpu);
ret = 0;
unlock:
double_rq_unlock(src_rq, dst_rq);
raw_spin_unlock(&arg->dst_task->pi_lock);
raw_spin_unlock(&arg->src_task->pi_lock);
return ret;
}
/*
* Cross migrate two tasks
*/
int migrate_swap(struct task_struct *cur, struct task_struct *p)
{
struct migration_swap_arg arg;
int ret = -EINVAL;
arg = (struct migration_swap_arg){
.src_task = cur,
.src_cpu = task_cpu(cur),
.dst_task = p,
.dst_cpu = task_cpu(p),
};
if (arg.src_cpu == arg.dst_cpu)
goto out;
/*
* These three tests are all lockless; this is OK since all of them
* will be re-checked with proper locks held further down the line.
*/
if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
goto out;
if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
goto out;
if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
goto out;
trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
out:
return ret;
}
struct migration_arg {
struct task_struct *task;
int dest_cpu;
};
static int migration_cpu_stop(void *data);
/*
* wait_task_inactive - wait for a thread to unschedule.
*
* If @match_state is nonzero, it's the @p->state value just checked and
* not expected to change. If it changes, i.e. @p might have woken up,
* then return zero. When we succeed in waiting for @p to be off its CPU,
* we return a positive number (its total switch count). If a second call
* a short while later returns the same number, the caller can be sure that
* @p has remained unscheduled the whole time.
*
* The caller must ensure that the task *will* unschedule sometime soon,
* else this function might spin for a *long* time. This function can't
* be called with interrupts off, or it may introduce deadlock with
* smp_call_function() if an IPI is sent by the same process we are
* waiting to become inactive.
*/
unsigned long wait_task_inactive(struct task_struct *p, long match_state)
{
unsigned long flags;
int running, on_rq;
unsigned long ncsw;
struct rq *rq;
for (;;) {
/*
* We do the initial early heuristics without holding
* any task-queue locks at all. We'll only try to get
* the runqueue lock when things look like they will
* work out!
*/
rq = task_rq(p);
/*
* If the task is actively running on another CPU
* still, just relax and busy-wait without holding
* any locks.
*
* NOTE! Since we don't hold any locks, it's not
* even sure that "rq" stays as the right runqueue!
* But we don't care, since "task_running()" will
* return false if the runqueue has changed and p
* is actually now running somewhere else!
*/
while (task_running(rq, p)) {
if (match_state && unlikely(p->state != match_state))
return 0;
cpu_relax();
}
/*
* Ok, time to look more closely! We need the rq
* lock now, to be *sure*. If we're wrong, we'll
* just go back and repeat.
*/
rq = task_rq_lock(p, &flags);
trace_sched_wait_task(p);
running = task_running(rq, p);
on_rq = p->on_rq;
ncsw = 0;
if (!match_state || p->state == match_state)
ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
task_rq_unlock(rq, p, &flags);
/*
* If it changed from the expected state, bail out now.
*/
if (unlikely(!ncsw))
break;
/*
* Was it really running after all now that we
* checked with the proper locks actually held?
*
* Oops. Go back and try again..
*/
if (unlikely(running)) {
cpu_relax();
continue;
}
/*
* It's not enough that it's not actively running,
* it must be off the runqueue _entirely_, and not
* preempted!
*
* So if it was still runnable (but just not actively
* running right now), it's preempted, and we should
* yield - it could be a while.
*/
if (unlikely(on_rq)) {
ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&to, HRTIMER_MODE_REL);
continue;
}
/*
* Ahh, all good. It wasn't running, and it wasn't
* runnable, which means that it will never become
* running in the future either. We're all done!
*/
break;
}
return ncsw;
}
/***
* kick_process - kick a running thread to enter/exit the kernel
* @p: the to-be-kicked thread
*
* Cause a process which is running on another CPU to enter
* kernel-mode, without any delay. (to get signals handled.)
*
* NOTE: this function doesn't have to take the runqueue lock,
* because all it wants to ensure is that the remote task enters
* the kernel. If the IPI races and the task has been migrated
* to another CPU then no harm is done and the purpose has been
* achieved as well.
*/
void kick_process(struct task_struct *p)
{
int cpu;
preempt_disable();
cpu = task_cpu(p);
if ((cpu != smp_processor_id()) && task_curr(p))
smp_send_reschedule(cpu);
preempt_enable();
}
EXPORT_SYMBOL_GPL(kick_process);
#endif /* CONFIG_SMP */
#ifdef CONFIG_SMP
/*
* ->cpus_allowed is protected by both rq->lock and p->pi_lock
*/
static int select_fallback_rq(int cpu, struct task_struct *p)
{
int nid = cpu_to_node(cpu);
const struct cpumask *nodemask = NULL;
enum { cpuset, possible, fail } state = cpuset;
int dest_cpu;
/*
* If the node that the cpu is on has been offlined, cpu_to_node()
* will return -1. There is no cpu on the node, and we should
* select the cpu on the other node.
*/
if (nid != -1) {
nodemask = cpumask_of_node(nid);
/* Look for allowed, online CPU in same node. */
for_each_cpu(dest_cpu, nodemask) {
if (!cpu_online(dest_cpu))
continue;
if (!cpu_active(dest_cpu))
continue;
if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return dest_cpu;
}
}
for (;;) {
/* Any allowed, online CPU? */
for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
if (!cpu_online(dest_cpu))
continue;
if (!cpu_active(dest_cpu))
continue;
goto out;
}
switch (state) {
case cpuset:
/* No more Mr. Nice Guy. */
cpuset_cpus_allowed_fallback(p);
state = possible;
break;
case possible:
do_set_cpus_allowed(p, cpu_possible_mask);
state = fail;
break;
case fail:
BUG();
break;
}
}
out:
if (state != cpuset) {
/*
* Don't tell them about moving exiting tasks or
* kernel threads (both mm NULL), since they never
* leave kernel.
*/
if (p->mm && printk_ratelimit()) {
printk_sched("process %d (%s) no longer affine to cpu%d\n",
task_pid_nr(p), p->comm, cpu);
}
}
return dest_cpu;
}
/*
* The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
*/
static inline
int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
{
cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
/*
* In order not to call set_task_cpu() on a blocking task we need
* to rely on ttwu() to place the task on a valid ->cpus_allowed
* cpu.
*
* Since this is common to all placement strategies, this lives here.
*
* [ this allows ->select_task() to simply return task_cpu(p) and
* not worry about this generic constraint ]
*/
if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
!cpu_online(cpu)))
cpu = select_fallback_rq(task_cpu(p), p);
return cpu;
}
static void update_avg(u64 *avg, u64 sample)
{
s64 diff = sample - *avg;
*avg += diff >> 3;
}
#endif
static void
ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
{
#ifdef CONFIG_SCHEDSTATS
struct rq *rq = this_rq();
#ifdef CONFIG_SMP
int this_cpu = smp_processor_id();
if (cpu == this_cpu) {
schedstat_inc(rq, ttwu_local);
schedstat_inc(p, se.statistics.nr_wakeups_local);
} else {
struct sched_domain *sd;
schedstat_inc(p, se.statistics.nr_wakeups_remote);
rcu_read_lock();
for_each_domain(this_cpu, sd) {
if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
schedstat_inc(sd, ttwu_wake_remote);
break;
}
}
rcu_read_unlock();
}
if (wake_flags & WF_MIGRATED)
schedstat_inc(p, se.statistics.nr_wakeups_migrate);
#endif /* CONFIG_SMP */
schedstat_inc(rq, ttwu_count);
schedstat_inc(p, se.statistics.nr_wakeups);
if (wake_flags & WF_SYNC)
schedstat_inc(p, se.statistics.nr_wakeups_sync);
#endif /* CONFIG_SCHEDSTATS */
}
static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
{
activate_task(rq, p, en_flags);
p->on_rq = 1;
/* if a worker is waking up, notify workqueue */
if (p->flags & PF_WQ_WORKER)
wq_worker_waking_up(p, cpu_of(rq));
}
/*
* Mark the task runnable and perform wakeup-preemption.
*/
static void
ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
{
check_preempt_curr(rq, p, wake_flags);
trace_sched_wakeup(p, true);
p->state = TASK_RUNNING;
#ifdef CONFIG_SMP
if (p->sched_class->task_woken)
p->sched_class->task_woken(rq, p);
if (rq->idle_stamp) {
u64 delta = rq_clock(rq) - rq->idle_stamp;
u64 max = 2*rq->max_idle_balance_cost;
update_avg(&rq->avg_idle, delta);
if (rq->avg_idle > max)
rq->avg_idle = max;
rq->idle_stamp = 0;
}
#endif
}
static void
ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
{
#ifdef CONFIG_SMP
if (p->sched_contributes_to_load)
rq->nr_uninterruptible--;
#endif
ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
ttwu_do_wakeup(rq, p, wake_flags);
}
/*
* Called in case the task @p isn't fully descheduled from its runqueue,
* in this case we must do a remote wakeup. Its a 'light' wakeup though,
* since all we need to do is flip p->state to TASK_RUNNING, since
* the task is still ->on_rq.
*/
static int ttwu_remote(struct task_struct *p, int wake_flags)
{
struct rq *rq;
int ret = 0;
rq = __task_rq_lock(p);
if (p->on_rq) {
/* check_preempt_curr() may use rq clock */
update_rq_clock(rq);
ttwu_do_wakeup(rq, p, wake_flags);
ret = 1;
}
__task_rq_unlock(rq);
return ret;
}
#ifdef CONFIG_SMP
static void sched_ttwu_pending(void)
{
struct rq *rq = this_rq();
struct llist_node *llist = llist_del_all(&rq->wake_list);
struct task_struct *p;
raw_spin_lock(&rq->lock);
while (llist) {
p = llist_entry(llist, struct task_struct, wake_entry);
llist = llist_next(llist);
ttwu_do_activate(rq, p, 0);
}
raw_spin_unlock(&rq->lock);
}
void scheduler_ipi(void)
{
/*
* Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
* TIF_NEED_RESCHED remotely (for the first time) will also send
* this IPI.
*/
preempt_fold_need_resched();
if (llist_empty(&this_rq()->wake_list)
&& !tick_nohz_full_cpu(smp_processor_id())
&& !got_nohz_idle_kick())
return;
/*
* Not all reschedule IPI handlers call irq_enter/irq_exit, since
* traditionally all their work was done from the interrupt return
* path. Now that we actually do some work, we need to make sure
* we do call them.
*
* Some archs already do call them, luckily irq_enter/exit nest
* properly.
*
* Arguably we should visit all archs and update all handlers,
* however a fair share of IPIs are still resched only so this would
* somewhat pessimize the simple resched case.
*/
irq_enter();
tick_nohz_full_check();
sched_ttwu_pending();
/*
* Check if someone kicked us for doing the nohz idle load balance.
*/
if (unlikely(got_nohz_idle_kick())) {
this_rq()->idle_balance = 1;
raise_softirq_irqoff(SCHED_SOFTIRQ);
}
irq_exit();
}
static void ttwu_queue_remote(struct task_struct *p, int cpu)
{
if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
smp_send_reschedule(cpu);
}
bool cpus_share_cache(int this_cpu, int that_cpu)
{
return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
}
#endif /* CONFIG_SMP */
static void ttwu_queue(struct task_struct *p, int cpu)
{
struct rq *rq = cpu_rq(cpu);
#if defined(CONFIG_SMP)
if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
sched_clock_cpu(cpu); /* sync clocks x-cpu */
ttwu_queue_remote(p, cpu);
return;
}
#endif
raw_spin_lock(&rq->lock);
ttwu_do_activate(rq, p, 0);
raw_spin_unlock(&rq->lock);
}
/**
* try_to_wake_up - wake up a thread
* @p: the thread to be awakened
* @state: the mask of task states that can be woken
* @wake_flags: wake modifier flags (WF_*)
*
* Put it on the run-queue if it's not already there. The "current"
* thread is always on the run-queue (except when the actual
* re-schedule is in progress), and as such you're allowed to do
* the simpler "current->state = TASK_RUNNING" to mark yourself
* runnable without the overhead of this.
*
* Return: %true if @p was woken up, %false if it was already running.
* or @state didn't match @p's state.
*/
static int
try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
{
unsigned long flags;
int cpu, success = 0;
/*
* If we are going to wake up a thread waiting for CONDITION we
* need to ensure that CONDITION=1 done by the caller can not be
* reordered with p->state check below. This pairs with mb() in
* set_current_state() the waiting thread does.
*/
smp_mb__before_spinlock();
raw_spin_lock_irqsave(&p->pi_lock, flags);
if (!(p->state & state))
goto out;
success = 1; /* we're going to change ->state */
cpu = task_cpu(p);
if (p->on_rq && ttwu_remote(p, wake_flags))
goto stat;
#ifdef CONFIG_SMP
/*
* If the owning (remote) cpu is still in the middle of schedule() with
* this task as prev, wait until its done referencing the task.
*/
while (p->on_cpu)
cpu_relax();
/*
* Pairs with the smp_wmb() in finish_lock_switch().
*/
smp_rmb();
p->sched_contributes_to_load = !!task_contributes_to_load(p);
p->state = TASK_WAKING;
if (p->sched_class->task_waking)
p->sched_class->task_waking(p);
cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
if (task_cpu(p) != cpu) {
wake_flags |= WF_MIGRATED;
set_task_cpu(p, cpu);
}
#endif /* CONFIG_SMP */
ttwu_queue(p, cpu);
stat:
ttwu_stat(p, cpu, wake_flags);
out:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
return success;
}
/**
* try_to_wake_up_local - try to wake up a local task with rq lock held
* @p: the thread to be awakened
*
* Put @p on the run-queue if it's not already there. The caller must
* ensure that this_rq() is locked, @p is bound to this_rq() and not
* the current task.
*/
static void try_to_wake_up_local(struct task_struct *p)
{
struct rq *rq = task_rq(p);
if (WARN_ON_ONCE(rq != this_rq()) ||
WARN_ON_ONCE(p == current))
return;
lockdep_assert_held(&rq->lock);
if (!raw_spin_trylock(&p->pi_lock)) {
raw_spin_unlock(&rq->lock);
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
}
if (!(p->state & TASK_NORMAL))
goto out;
if (!p->on_rq)
ttwu_activate(rq, p, ENQUEUE_WAKEUP);
ttwu_do_wakeup(rq, p, 0);
ttwu_stat(p, smp_processor_id(), 0);
out:
raw_spin_unlock(&p->pi_lock);
}
/**
* wake_up_process - Wake up a specific process
* @p: The process to be woken up.
*
* Attempt to wake up the nominated process and move it to the set of runnable
* processes.
*
* Return: 1 if the process was woken up, 0 if it was already running.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
int wake_up_process(struct task_struct *p)
{
WARN_ON(task_is_stopped_or_traced(p));
return try_to_wake_up(p, TASK_NORMAL, 0);
}
EXPORT_SYMBOL(wake_up_process);
int wake_up_state(struct task_struct *p, unsigned int state)
{
return try_to_wake_up(p, state, 0);
}
/*
* Perform scheduler related setup for a newly forked process p.
* p is forked by current.
*
* __sched_fork() is basic setup used by init_idle() too:
*/
static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
{
p->on_rq = 0;
p->se.on_rq = 0;
p->se.exec_start = 0;
p->se.sum_exec_runtime = 0;
p->se.prev_sum_exec_runtime = 0;
p->se.nr_migrations = 0;
p->se.vruntime = 0;
INIT_LIST_HEAD(&p->se.group_node);
#ifdef CONFIG_SCHEDSTATS
memset(&p->se.statistics, 0, sizeof(p->se.statistics));
#endif
RB_CLEAR_NODE(&p->dl.rb_node);
hrtimer_init(&p->dl.dl_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
p->dl.dl_runtime = p->dl.runtime = 0;
p->dl.dl_deadline = p->dl.deadline = 0;
p->dl.dl_period = 0;
p->dl.flags = 0;
INIT_LIST_HEAD(&p->rt.run_list);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&p->preempt_notifiers);
#endif
#ifdef CONFIG_NUMA_BALANCING
if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
p->mm->numa_scan_seq = 0;
}
if (clone_flags & CLONE_VM)
p->numa_preferred_nid = current->numa_preferred_nid;
else
p->numa_preferred_nid = -1;
p->node_stamp = 0ULL;
p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
p->numa_scan_period = sysctl_numa_balancing_scan_delay;
p->numa_work.next = &p->numa_work;
p->numa_faults = NULL;
p->numa_faults_buffer = NULL;
INIT_LIST_HEAD(&p->numa_entry);
p->numa_group = NULL;
#endif /* CONFIG_NUMA_BALANCING */
}
#ifdef CONFIG_NUMA_BALANCING
#ifdef CONFIG_SCHED_DEBUG
void set_numabalancing_state(bool enabled)
{
if (enabled)
sched_feat_set("NUMA");
else
sched_feat_set("NO_NUMA");
}
#else
__read_mostly bool numabalancing_enabled;
void set_numabalancing_state(bool enabled)
{
numabalancing_enabled = enabled;
}
#endif /* CONFIG_SCHED_DEBUG */
#ifdef CONFIG_PROC_SYSCTL
int sysctl_numa_balancing(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
int err;
int state = numabalancing_enabled;
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &state;
err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
if (err < 0)
return err;
if (write)
set_numabalancing_state(state);
return err;
}
#endif
#endif
/*
* fork()/clone()-time setup:
*/
int sched_fork(unsigned long clone_flags, struct task_struct *p)
{
unsigned long flags;
int cpu = get_cpu();
__sched_fork(clone_flags, p);
/*
* We mark the process as running here. This guarantees that
* nobody will actually run it, and a signal or other external
* event cannot wake it up and insert it on the runqueue either.
*/
p->state = TASK_RUNNING;
/*
* Make sure we do not leak PI boosting priority to the child.
*/
p->prio = current->normal_prio;
/*
* Revert to default priority/policy on fork if requested.
*/
if (unlikely(p->sched_reset_on_fork)) {
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->policy = SCHED_NORMAL;
p->static_prio = NICE_TO_PRIO(0);
p->rt_priority = 0;
} else if (PRIO_TO_NICE(p->static_prio) < 0)
p->static_prio = NICE_TO_PRIO(0);
p->prio = p->normal_prio = __normal_prio(p);
set_load_weight(p);
/*
* We don't need the reset flag anymore after the fork. It has
* fulfilled its duty:
*/
p->sched_reset_on_fork = 0;
}
if (dl_prio(p->prio)) {
put_cpu();
return -EAGAIN;
} else if (rt_prio(p->prio)) {
p->sched_class = &rt_sched_class;
} else {
p->sched_class = &fair_sched_class;
}
if (p->sched_class->task_fork)
p->sched_class->task_fork(p);
/*
* The child is not yet in the pid-hash so no cgroup attach races,
* and the cgroup is pinned to this child due to cgroup_fork()
* is ran before sched_fork().
*
* Silence PROVE_RCU.
*/
raw_spin_lock_irqsave(&p->pi_lock, flags);
set_task_cpu(p, cpu);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
if (likely(sched_info_on()))
memset(&p->sched_info, 0, sizeof(p->sched_info));
#endif
#if defined(CONFIG_SMP)
p->on_cpu = 0;
#endif
init_task_preempt_count(p);
#ifdef CONFIG_SMP
plist_node_init(&p->pushable_tasks, MAX_PRIO);
RB_CLEAR_NODE(&p->pushable_dl_tasks);
#endif
put_cpu();
return 0;
}
unsigned long to_ratio(u64 period, u64 runtime)
{
if (runtime == RUNTIME_INF)
return 1ULL << 20;
/*
* Doing this here saves a lot of checks in all
* the calling paths, and returning zero seems
* safe for them anyway.
*/
if (period == 0)
return 0;
return div64_u64(runtime << 20, period);
}
#ifdef CONFIG_SMP
inline struct dl_bw *dl_bw_of(int i)
{
return &cpu_rq(i)->rd->dl_bw;
}
static inline int dl_bw_cpus(int i)
{
struct root_domain *rd = cpu_rq(i)->rd;
int cpus = 0;
for_each_cpu_and(i, rd->span, cpu_active_mask)
cpus++;
return cpus;
}
#else
inline struct dl_bw *dl_bw_of(int i)
{
return &cpu_rq(i)->dl.dl_bw;
}
static inline int dl_bw_cpus(int i)
{
return 1;
}
#endif
static inline
void __dl_clear(struct dl_bw *dl_b, u64 tsk_bw)
{
dl_b->total_bw -= tsk_bw;
}
static inline
void __dl_add(struct dl_bw *dl_b, u64 tsk_bw)
{
dl_b->total_bw += tsk_bw;
}
static inline
bool __dl_overflow(struct dl_bw *dl_b, int cpus, u64 old_bw, u64 new_bw)
{
return dl_b->bw != -1 &&
dl_b->bw * cpus < dl_b->total_bw - old_bw + new_bw;
}
/*
* We must be sure that accepting a new task (or allowing changing the
* parameters of an existing one) is consistent with the bandwidth
* constraints. If yes, this function also accordingly updates the currently
* allocated bandwidth to reflect the new situation.
*
* This function is called while holding p's rq->lock.
*/
static int dl_overflow(struct task_struct *p, int policy,
const struct sched_attr *attr)
{
struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
u64 period = attr->sched_period ?: attr->sched_deadline;
u64 runtime = attr->sched_runtime;
u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
int cpus, err = -1;
if (new_bw == p->dl.dl_bw)
return 0;
/*
* Either if a task, enters, leave, or stays -deadline but changes
* its parameters, we may need to update accordingly the total
* allocated bandwidth of the container.
*/
raw_spin_lock(&dl_b->lock);
cpus = dl_bw_cpus(task_cpu(p));
if (dl_policy(policy) && !task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, 0, new_bw)) {
__dl_add(dl_b, new_bw);
err = 0;
} else if (dl_policy(policy) && task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
__dl_clear(dl_b, p->dl.dl_bw);
__dl_add(dl_b, new_bw);
err = 0;
} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
__dl_clear(dl_b, p->dl.dl_bw);
err = 0;
}
raw_spin_unlock(&dl_b->lock);
return err;
}
extern void init_dl_bw(struct dl_bw *dl_b);
/*
* wake_up_new_task - wake up a newly created task for the first time.
*
* This function will do some initial scheduler statistics housekeeping
* that must be done for every newly created context, then puts the task
* on the runqueue and wakes it.
*/
void wake_up_new_task(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
raw_spin_lock_irqsave(&p->pi_lock, flags);
#ifdef CONFIG_SMP
/*
* Fork balancing, do it here and not earlier because:
* - cpus_allowed can change in the fork path
* - any previously selected cpu might disappear through hotplug
*/
set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
#endif
/* Initialize new task's runnable average */
init_task_runnable_average(p);
rq = __task_rq_lock(p);
activate_task(rq, p, 0);
p->on_rq = 1;
trace_sched_wakeup_new(p, true);
check_preempt_curr(rq, p, WF_FORK);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken)
p->sched_class->task_woken(rq, p);
#endif
task_rq_unlock(rq, p, &flags);
}
#ifdef CONFIG_PREEMPT_NOTIFIERS
/**
* preempt_notifier_register - tell me when current is being preempted & rescheduled
* @notifier: notifier struct to register
*/
void preempt_notifier_register(struct preempt_notifier *notifier)
{
hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
}
EXPORT_SYMBOL_GPL(preempt_notifier_register);
/**
* preempt_notifier_unregister - no longer interested in preemption notifications
* @notifier: notifier struct to unregister
*
* This is safe to call from within a preemption notifier.
*/
void preempt_notifier_unregister(struct preempt_notifier *notifier)
{
hlist_del(¬ifier->link);
}
EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_in(notifier, raw_smp_processor_id());
}
static void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_out(notifier, next);
}
#else /* !CONFIG_PREEMPT_NOTIFIERS */
static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
}
static void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
}
#endif /* CONFIG_PREEMPT_NOTIFIERS */
/**
* prepare_task_switch - prepare to switch tasks
* @rq: the runqueue preparing to switch
* @prev: the current task that is being switched out
* @next: the task we are going to switch to.
*
* This is called with the rq lock held and interrupts off. It must
* be paired with a subsequent finish_task_switch after the context
* switch.
*
* prepare_task_switch sets up locking and calls architecture specific
* hooks.
*/
static inline void
prepare_task_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
trace_sched_switch(prev, next);
sched_info_switch(rq, prev, next);
perf_event_task_sched_out(prev, next);
fire_sched_out_preempt_notifiers(prev, next);
prepare_lock_switch(rq, next);
prepare_arch_switch(next);
}
/**
* finish_task_switch - clean up after a task-switch
* @rq: runqueue associated with task-switch
* @prev: the thread we just switched away from.
*
* finish_task_switch must be called after the context switch, paired
* with a prepare_task_switch call before the context switch.
* finish_task_switch will reconcile locking set up by prepare_task_switch,
* and do any other architecture-specific cleanup actions.
*
* Note that we may have delayed dropping an mm in context_switch(). If
* so, we finish that here outside of the runqueue lock. (Doing it
* with the lock held can cause deadlocks; see schedule() for
* details.)
*/
static void finish_task_switch(struct rq *rq, struct task_struct *prev)
__releases(rq->lock)
{
struct mm_struct *mm = rq->prev_mm;
long prev_state;
rq->prev_mm = NULL;
/*
* A task struct has one reference for the use as "current".
* If a task dies, then it sets TASK_DEAD in tsk->state and calls
* schedule one last time. The schedule call will never return, and
* the scheduled task must drop that reference.
* The test for TASK_DEAD must occur while the runqueue locks are
* still held, otherwise prev could be scheduled on another cpu, die
* there before we look at prev->state, and then the reference would
* be dropped twice.
* Manfred Spraul <manfred@colorfullife.com>
*/
prev_state = prev->state;
vtime_task_switch(prev);
finish_arch_switch(prev);
perf_event_task_sched_in(prev, current);
finish_lock_switch(rq, prev);
finish_arch_post_lock_switch();
fire_sched_in_preempt_notifiers(current);
if (mm)
mmdrop(mm);
if (unlikely(prev_state == TASK_DEAD)) {
task_numa_free(prev);
if (prev->sched_class->task_dead)
prev->sched_class->task_dead(prev);
/*
* Remove function-return probe instances associated with this
* task and put them back on the free list.
*/
kprobe_flush_task(prev);
put_task_struct(prev);
}
tick_nohz_task_switch(current);
}
#ifdef CONFIG_SMP
/* assumes rq->lock is held */
static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
{
if (prev->sched_class->pre_schedule)
prev->sched_class->pre_schedule(rq, prev);
}
/* rq->lock is NOT held, but preemption is disabled */
static inline void post_schedule(struct rq *rq)
{
if (rq->post_schedule) {
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->curr->sched_class->post_schedule)
rq->curr->sched_class->post_schedule(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
rq->post_schedule = 0;
}
}
#else
static inline void pre_schedule(struct rq *rq, struct task_struct *p)
{
}
static inline void post_schedule(struct rq *rq)
{
}
#endif
/**
* schedule_tail - first thing a freshly forked thread must call.
* @prev: the thread we just switched away from.
*/
asmlinkage void schedule_tail(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq = this_rq();
finish_task_switch(rq, prev);
/*
* FIXME: do we need to worry about rq being invalidated by the
* task_switch?
*/
post_schedule(rq);
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
/* In this case, finish_task_switch does not reenable preemption */
preempt_enable();
#endif
if (current->set_child_tid)
put_user(task_pid_vnr(current), current->set_child_tid);
}
/*
* context_switch - switch to the new MM and the new
* thread's register state.
*/
static inline void
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
struct mm_struct *mm, *oldmm;
prepare_task_switch(rq, prev, next);
mm = next->mm;
oldmm = prev->active_mm;
/*
* For paravirt, this is coupled with an exit in switch_to to
* combine the page table reload and the switch backend into
* one hypercall.
*/
arch_start_context_switch(prev);
if (!mm) {
next->active_mm = oldmm;
atomic_inc(&oldmm->mm_count);
enter_lazy_tlb(oldmm, next);
} else
switch_mm(oldmm, mm, next);
if (!prev->mm) {
prev->active_mm = NULL;
rq->prev_mm = oldmm;
}
/*
* Since the runqueue lock will be released by the next
* task (which is an invalid locking op but in the case
* of the scheduler it's an obvious special-case), so we
* do an early lockdep release here:
*/
#ifndef __ARCH_WANT_UNLOCKED_CTXSW
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
#endif
context_tracking_task_switch(prev, next);
/* Here we just switch the register state and the stack. */
switch_to(prev, next, prev);
barrier();
/*
* this_rq must be evaluated again because prev may have moved
* CPUs since it called schedule(), thus the 'rq' on its stack
* frame will be invalid.
*/
finish_task_switch(this_rq(), prev);
}
/*
* nr_running and nr_context_switches:
*
* externally visible scheduler statistics: current number of runnable
* threads, total number of context switches performed since bootup.
*/
unsigned long nr_running(void)
{
unsigned long i, sum = 0;
for_each_online_cpu(i)
sum += cpu_rq(i)->nr_running;
return sum;
}
unsigned long long nr_context_switches(void)
{
int i;
unsigned long long sum = 0;
for_each_possible_cpu(i)
sum += cpu_rq(i)->nr_switches;
return sum;
}
unsigned long nr_iowait(void)
{
unsigned long i, sum = 0;
for_each_possible_cpu(i)
sum += atomic_read(&cpu_rq(i)->nr_iowait);
return sum;
}
unsigned long nr_iowait_cpu(int cpu)
{
struct rq *this = cpu_rq(cpu);
return atomic_read(&this->nr_iowait);
}
#ifdef CONFIG_SMP
/*
* sched_exec - execve() is a valuable balancing opportunity, because at
* this point the task has the smallest effective memory and cache footprint.
*/
void sched_exec(void)
{
struct task_struct *p = current;
unsigned long flags;
int dest_cpu;
raw_spin_lock_irqsave(&p->pi_lock, flags);
dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
if (dest_cpu == smp_processor_id())
goto unlock;
if (likely(cpu_active(dest_cpu))) {
struct migration_arg arg = { p, dest_cpu };
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
return;
}
unlock:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
}
#endif
DEFINE_PER_CPU(struct kernel_stat, kstat);
DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
EXPORT_PER_CPU_SYMBOL(kstat);
EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
/*
* Return any ns on the sched_clock that have not yet been accounted in
* @p in case that task is currently running.
*
* Called with task_rq_lock() held on @rq.
*/
static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
{
u64 ns = 0;
if (task_current(rq, p)) {
update_rq_clock(rq);
ns = rq_clock_task(rq) - p->se.exec_start;
if ((s64)ns < 0)
ns = 0;
}
return ns;
}
unsigned long long task_delta_exec(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
rq = task_rq_lock(p, &flags);
ns = do_task_delta_exec(p, rq);
task_rq_unlock(rq, p, &flags);
return ns;
}
/*
* Return accounted runtime for the task.
* In case the task is currently running, return the runtime plus current's
* pending runtime that have not been accounted yet.
*/
unsigned long long task_sched_runtime(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
/*
* 64-bit doesn't need locks to atomically read a 64bit value.
* So we have a optimization chance when the task's delta_exec is 0.
* Reading ->on_cpu is racy, but this is ok.
*
* If we race with it leaving cpu, we'll take a lock. So we're correct.
* If we race with it entering cpu, unaccounted time is 0. This is
* indistinguishable from the read occurring a few cycles earlier.
*/
if (!p->on_cpu)
return p->se.sum_exec_runtime;
#endif
rq = task_rq_lock(p, &flags);
ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
task_rq_unlock(rq, p, &flags);
return ns;
}
/*
* This function gets called by the timer code, with HZ frequency.
* We call it with interrupts disabled.
*/
void scheduler_tick(void)
{
int cpu = smp_processor_id();
struct rq *rq = cpu_rq(cpu);
struct task_struct *curr = rq->curr;
sched_clock_tick();
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
curr->sched_class->task_tick(rq, curr, 0);
update_cpu_load_active(rq);
raw_spin_unlock(&rq->lock);
perf_event_task_tick();
#ifdef CONFIG_SMP
rq->idle_balance = idle_cpu(cpu);
trigger_load_balance(rq);
#endif
rq_last_tick_reset(rq);
}
#ifdef CONFIG_NO_HZ_FULL
/**
* scheduler_tick_max_deferment
*
* Keep at least one tick per second when a single
* active task is running because the scheduler doesn't
* yet completely support full dynticks environment.
*
* This makes sure that uptime, CFS vruntime, load
* balancing, etc... continue to move forward, even
* with a very low granularity.
*
* Return: Maximum deferment in nanoseconds.
*/
u64 scheduler_tick_max_deferment(void)
{
struct rq *rq = this_rq();
unsigned long next, now = ACCESS_ONCE(jiffies);
next = rq->last_sched_tick + HZ;
if (time_before_eq(next, now))
return 0;
return jiffies_to_nsecs(next - now);
}
#endif
notrace unsigned long get_parent_ip(unsigned long addr)
{
if (in_lock_functions(addr)) {
addr = CALLER_ADDR2;
if (in_lock_functions(addr))
addr = CALLER_ADDR3;
}
return addr;
}
#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
defined(CONFIG_PREEMPT_TRACER))
void __kprobes preempt_count_add(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
return;
#endif
__preempt_count_add(val);
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Spinlock count overflowing soon?
*/
DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
PREEMPT_MASK - 10);
#endif
if (preempt_count() == val)
trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
}
EXPORT_SYMBOL(preempt_count_add);
void __kprobes preempt_count_sub(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
return;
/*
* Is the spinlock portion underflowing?
*/
if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
!(preempt_count() & PREEMPT_MASK)))
return;
#endif
if (preempt_count() == val)
trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
__preempt_count_sub(val);
}
EXPORT_SYMBOL(preempt_count_sub);
#endif
/*
* Print scheduling while atomic bug:
*/
static noinline void __schedule_bug(struct task_struct *prev)
{
if (oops_in_progress)
return;
printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
prev->comm, prev->pid, preempt_count());
debug_show_held_locks(prev);
print_modules();
if (irqs_disabled())
print_irqtrace_events(prev);
dump_stack();
add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
}
/*
* Various schedule()-time debugging checks and statistics:
*/
static inline void schedule_debug(struct task_struct *prev)
{
/*
* Test if we are atomic. Since do_exit() needs to call into
* schedule() atomically, we ignore that path. Otherwise whine
* if we are scheduling when we should not.
*/
if (unlikely(in_atomic_preempt_off() && prev->state != TASK_DEAD))
__schedule_bug(prev);
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
static void put_prev_task(struct rq *rq, struct task_struct *prev)
{
if (prev->on_rq || rq->skip_clock_update < 0)
update_rq_clock(rq);
prev->sched_class->put_prev_task(rq, prev);
}
/*
* Pick up the highest-prio task:
*/
static inline struct task_struct *
pick_next_task(struct rq *rq)
{
const struct sched_class *class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
p = fair_sched_class.pick_next_task(rq);
if (likely(p))
return p;
}
for_each_class(class) {
p = class->pick_next_task(rq);
if (p)
return p;
}
BUG(); /* the idle class will always have a runnable task */
}
/*
* __schedule() is the main scheduler function.
*
* The main means of driving the scheduler and thus entering this function are:
*
* 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
*
* 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
* paths. For example, see arch/x86/entry_64.S.
*
* To drive preemption between tasks, the scheduler sets the flag in timer
* interrupt handler scheduler_tick().
*
* 3. Wakeups don't really cause entry into schedule(). They add a
* task to the run-queue and that's it.
*
* Now, if the new task added to the run-queue preempts the current
* task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
* called on the nearest possible occasion:
*
* - If the kernel is preemptible (CONFIG_PREEMPT=y):
*
* - in syscall or exception context, at the next outmost
* preempt_enable(). (this might be as soon as the wake_up()'s
* spin_unlock()!)
*
* - in IRQ context, return from interrupt-handler to
* preemptible context
*
* - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
* then at the next:
*
* - cond_resched() call
* - explicit schedule() call
* - return from syscall or exception to user-space
* - return from interrupt-handler to user-space
*/
static void __sched __schedule(void)
{
struct task_struct *prev, *next;
unsigned long *switch_count;
struct rq *rq;
int cpu;
need_resched:
preempt_disable();
cpu = smp_processor_id();
rq = cpu_rq(cpu);
rcu_note_context_switch(cpu);
prev = rq->curr;
schedule_debug(prev);
if (sched_feat(HRTICK))
hrtick_clear(rq);
/*
* Make sure that signal_pending_state()->signal_pending() below
* can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
* done by the caller to avoid the race with signal_wake_up().
*/
smp_mb__before_spinlock();
raw_spin_lock_irq(&rq->lock);
switch_count = &prev->nivcsw;
if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
if (unlikely(signal_pending_state(prev->state, prev))) {
prev->state = TASK_RUNNING;
} else {
deactivate_task(rq, prev, DEQUEUE_SLEEP);
prev->on_rq = 0;
/*
* If a worker went to sleep, notify and ask workqueue
* whether it wants to wake up a task to maintain
* concurrency.
*/
if (prev->flags & PF_WQ_WORKER) {
struct task_struct *to_wakeup;
to_wakeup = wq_worker_sleeping(prev, cpu);
if (to_wakeup)
try_to_wake_up_local(to_wakeup);
}
}
switch_count = &prev->nvcsw;
}
pre_schedule(rq, prev);
if (unlikely(!rq->nr_running))
idle_balance(cpu, rq);
put_prev_task(rq, prev);
next = pick_next_task(rq);
clear_tsk_need_resched(prev);
clear_preempt_need_resched();
rq->skip_clock_update = 0;
if (likely(prev != next)) {
rq->nr_switches++;
rq->curr = next;
++*switch_count;
context_switch(rq, prev, next); /* unlocks the rq */
/*
* The context switch have flipped the stack from under us
* and restored the local variables which were saved when
* this task called schedule() in the past. prev == current
* is still correct, but it can be moved to another cpu/rq.
*/
cpu = smp_processor_id();
rq = cpu_rq(cpu);
} else
raw_spin_unlock_irq(&rq->lock);
post_schedule(rq);
sched_preempt_enable_no_resched();
if (need_resched())
goto need_resched;
}
static inline void sched_submit_work(struct task_struct *tsk)
{
if (!tsk->state || tsk_is_pi_blocked(tsk))
return;
/*
* If we are going to sleep and we have plugged IO queued,
* make sure to submit it to avoid deadlocks.
*/
if (blk_needs_flush_plug(tsk))
blk_schedule_flush_plug(tsk);
}
asmlinkage void __sched schedule(void)
{
struct task_struct *tsk = current;
sched_submit_work(tsk);
__schedule();
}
EXPORT_SYMBOL(schedule);
#ifdef CONFIG_CONTEXT_TRACKING
asmlinkage void __sched schedule_user(void)
{
/*
* If we come here after a random call to set_need_resched(),
* or we have been woken up remotely but the IPI has not yet arrived,
* we haven't yet exited the RCU idle mode. Do it here manually until
* we find a better solution.
*/
user_exit();
schedule();
user_enter();
}
#endif
/**
* schedule_preempt_disabled - called with preemption disabled
*
* Returns with preemption disabled. Note: preempt_count must be 1
*/
void __sched schedule_preempt_disabled(void)
{
sched_preempt_enable_no_resched();
schedule();
preempt_disable();
}
#ifdef CONFIG_PREEMPT
/*
* this is the entry point to schedule() from in-kernel preemption
* off of preempt_enable. Kernel preemptions off return from interrupt
* occur there and call schedule directly.
*/
asmlinkage void __sched notrace preempt_schedule(void)
{
/*
* If there is a non-zero preempt_count or interrupts are disabled,
* we do not want to preempt the current task. Just return..
*/
if (likely(!preemptible()))
return;
do {
__preempt_count_add(PREEMPT_ACTIVE);
__schedule();
__preempt_count_sub(PREEMPT_ACTIVE);
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
barrier();
} while (need_resched());
}
EXPORT_SYMBOL(preempt_schedule);
#endif /* CONFIG_PREEMPT */
/*
* this is the entry point to schedule() from kernel preemption
* off of irq context.
* Note, that this is called and return with irqs disabled. This will
* protect us against recursive calling from irq.
*/
asmlinkage void __sched preempt_schedule_irq(void)
{
enum ctx_state prev_state;
/* Catch callers which need to be fixed */
BUG_ON(preempt_count() || !irqs_disabled());
prev_state = exception_enter();
do {
__preempt_count_add(PREEMPT_ACTIVE);
local_irq_enable();
__schedule();
local_irq_disable();
__preempt_count_sub(PREEMPT_ACTIVE);
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
barrier();
} while (need_resched());
exception_exit(prev_state);
}
int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
void *key)
{
return try_to_wake_up(curr->private, mode, wake_flags);
}
EXPORT_SYMBOL(default_wake_function);
static long __sched
sleep_on_common(wait_queue_head_t *q, int state, long timeout)
{
unsigned long flags;
wait_queue_t wait;
init_waitqueue_entry(&wait, current);
__set_current_state(state);
spin_lock_irqsave(&q->lock, flags);
__add_wait_queue(q, &wait);
spin_unlock(&q->lock);
timeout = schedule_timeout(timeout);
spin_lock_irq(&q->lock);
__remove_wait_queue(q, &wait);
spin_unlock_irqrestore(&q->lock, flags);
return timeout;
}
void __sched interruptible_sleep_on(wait_queue_head_t *q)
{
sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}
EXPORT_SYMBOL(interruptible_sleep_on);
long __sched
interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
{
return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
}
EXPORT_SYMBOL(interruptible_sleep_on_timeout);
void __sched sleep_on(wait_queue_head_t *q)
{
sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}
EXPORT_SYMBOL(sleep_on);
long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
{
return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
}
EXPORT_SYMBOL(sleep_on_timeout);
#ifdef CONFIG_RT_MUTEXES
/*
* rt_mutex_setprio - set the current priority of a task
* @p: task
* @prio: prio value (kernel-internal form)
*
* This function changes the 'effective' priority of a task. It does
* not touch ->normal_prio like __setscheduler().
*
* Used by the rt_mutex code to implement priority inheritance logic.
*/
void rt_mutex_setprio(struct task_struct *p, int prio)
{
int oldprio, on_rq, running, enqueue_flag = 0;
struct rq *rq;
const struct sched_class *prev_class;
BUG_ON(prio > MAX_PRIO);
rq = __task_rq_lock(p);
/*
* Idle task boosting is a nono in general. There is one
* exception, when PREEMPT_RT and NOHZ is active:
*
* The idle task calls get_next_timer_interrupt() and holds
* the timer wheel base->lock on the CPU and another CPU wants
* to access the timer (probably to cancel it). We can safely
* ignore the boosting request, as the idle CPU runs this code
* with interrupts disabled and will complete the lock
* protected section without being interrupted. So there is no
* real need to boost.
*/
if (unlikely(p == rq->idle)) {
WARN_ON(p != rq->curr);
WARN_ON(p->pi_blocked_on);
goto out_unlock;
}
trace_sched_pi_setprio(p, prio);
p->pi_top_task = rt_mutex_get_top_task(p);
oldprio = p->prio;
prev_class = p->sched_class;
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
/*
* Boosting condition are:
* 1. -rt task is running and holds mutex A
* --> -dl task blocks on mutex A
*
* 2. -dl task is running and holds mutex A
* --> -dl task blocks on mutex A and could preempt the
* running task
*/
if (dl_prio(prio)) {
if (!dl_prio(p->normal_prio) || (p->pi_top_task &&
dl_entity_preempt(&p->pi_top_task->dl, &p->dl))) {
p->dl.dl_boosted = 1;
p->dl.dl_throttled = 0;
enqueue_flag = ENQUEUE_REPLENISH;
} else
p->dl.dl_boosted = 0;
p->sched_class = &dl_sched_class;
} else if (rt_prio(prio)) {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
if (oldprio < prio)
enqueue_flag = ENQUEUE_HEAD;
p->sched_class = &rt_sched_class;
} else {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
p->sched_class = &fair_sched_class;
}
p->prio = prio;
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, enqueue_flag);
check_class_changed(rq, p, prev_class, oldprio);
out_unlock:
__task_rq_unlock(rq);
}
#endif
void set_user_nice(struct task_struct *p, long nice)
{
int old_prio, delta, on_rq;
unsigned long flags;
struct rq *rq;
if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &flags);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
*/
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
on_rq = p->on_rq;
if (on_rq)
dequeue_task(rq, p, 0);
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
if (on_rq) {
enqueue_task(rq, p, 0);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_task(rq->curr);
}
out_unlock:
task_rq_unlock(rq, p, &flags);
}
EXPORT_SYMBOL(set_user_nice);
/*
* can_nice - check if a task can reduce its nice value
* @p: task
* @nice: nice value
*/
int can_nice(const struct task_struct *p, const int nice)
{
/* convert nice value [19,-20] to rlimit style value [1,40] */
int nice_rlim = 20 - nice;
return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
capable(CAP_SYS_NICE));
}
#ifdef __ARCH_WANT_SYS_NICE
/*
* sys_nice - change the priority of the current process.
* @increment: priority increment
*
* sys_setpriority is a more generic, but much slower function that
* does similar things.
*/
SYSCALL_DEFINE1(nice, int, increment)
{
long nice, retval;
/*
* Setpriority might change our priority at the same moment.
* We don't have to worry. Conceptually one call occurs first
* and we have a single winner.
*/
if (increment < -40)
increment = -40;
if (increment > 40)
increment = 40;
nice = TASK_NICE(current) + increment;
if (nice < -20)
nice = -20;
if (nice > 19)
nice = 19;
if (increment < 0 && !can_nice(current, nice))
return -EPERM;
retval = security_task_setnice(current, nice);
if (retval)
return retval;
set_user_nice(current, nice);
return 0;
}
#endif
/**
* task_prio - return the priority value of a given task.
* @p: the task in question.
*
* Return: The priority value as seen by users in /proc.
* RT tasks are offset by -200. Normal tasks are centered
* around 0, value goes from -16 to +15.
*/
int task_prio(const struct task_struct *p)
{
return p->prio - MAX_RT_PRIO;
}
/**
* task_nice - return the nice value of a given task.
* @p: the task in question.
*
* Return: The nice value [ -20 ... 0 ... 19 ].
*/
int task_nice(const struct task_struct *p)
{
return TASK_NICE(p);
}
EXPORT_SYMBOL(task_nice);
/**
* idle_cpu - is a given cpu idle currently?
* @cpu: the processor in question.
*
* Return: 1 if the CPU is currently idle. 0 otherwise.
*/
int idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (rq->curr != rq->idle)
return 0;
if (rq->nr_running)
return 0;
#ifdef CONFIG_SMP
if (!llist_empty(&rq->wake_list))
return 0;
#endif
return 1;
}
/**
* idle_task - return the idle task for a given cpu.
* @cpu: the processor in question.
*
* Return: The idle task for the cpu @cpu.
*/
struct task_struct *idle_task(int cpu)
{
return cpu_rq(cpu)->idle;
}
/**
* find_process_by_pid - find a process with a matching PID value.
* @pid: the pid in question.
*
* The task of @pid, if found. %NULL otherwise.
*/
static struct task_struct *find_process_by_pid(pid_t pid)
{
return pid ? find_task_by_vpid(pid) : current;
}
/*
* This function initializes the sched_dl_entity of a newly becoming
* SCHED_DEADLINE task.
*
* Only the static values are considered here, the actual runtime and the
* absolute deadline will be properly calculated when the task is enqueued
* for the first time with its new policy.
*/
static void
__setparam_dl(struct task_struct *p, const struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
init_dl_task_timer(dl_se);
dl_se->dl_runtime = attr->sched_runtime;
dl_se->dl_deadline = attr->sched_deadline;
dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
dl_se->flags = attr->sched_flags;
dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
dl_se->dl_throttled = 0;
dl_se->dl_new = 1;
}
/* Actually do priority change: must hold pi & rq lock. */
static void __setscheduler(struct rq *rq, struct task_struct *p,
const struct sched_attr *attr)
{
int policy = attr->sched_policy;
if (policy == -1) /* setparam */
policy = p->policy;
p->policy = policy;
if (dl_policy(policy))
__setparam_dl(p, attr);
else if (fair_policy(policy))
p->static_prio = NICE_TO_PRIO(attr->sched_nice);
/*
* __sched_setscheduler() ensures attr->sched_priority == 0 when
* !rt_policy. Always setting this ensures that things like
* getparam()/getattr() don't report silly values for !rt tasks.
*/
p->rt_priority = attr->sched_priority;
p->normal_prio = normal_prio(p);
p->prio = rt_mutex_getprio(p);
if (dl_prio(p->prio))
p->sched_class = &dl_sched_class;
else if (rt_prio(p->prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
set_load_weight(p);
}
static void
__getparam_dl(struct task_struct *p, struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
attr->sched_priority = p->rt_priority;
attr->sched_runtime = dl_se->dl_runtime;
attr->sched_deadline = dl_se->dl_deadline;
attr->sched_period = dl_se->dl_period;
attr->sched_flags = dl_se->flags;
}
/*
* This function validates the new parameters of a -deadline task.
* We ask for the deadline not being zero, and greater or equal
* than the runtime, as well as the period of being zero or
* greater than deadline. Furthermore, we have to be sure that
* user parameters are above the internal resolution (1us); we
* check sched_runtime only since it is always the smaller one.
*/
static bool
__checkparam_dl(const struct sched_attr *attr)
{
return attr && attr->sched_deadline != 0 &&
(attr->sched_period == 0 ||
(s64)(attr->sched_period - attr->sched_deadline) >= 0) &&
(s64)(attr->sched_deadline - attr->sched_runtime ) >= 0 &&
attr->sched_runtime >= (2 << (DL_SCALE - 1));
}
/*
* check the target process has a UID that matches the current process's
*/
static bool check_same_owner(struct task_struct *p)
{
const struct cred *cred = current_cred(), *pcred;
bool match;
rcu_read_lock();
pcred = __task_cred(p);
match = (uid_eq(cred->euid, pcred->euid) ||
uid_eq(cred->euid, pcred->uid));
rcu_read_unlock();
return match;
}
static int __sched_setscheduler(struct task_struct *p,
const struct sched_attr *attr,
bool user)
{
int retval, oldprio, oldpolicy = -1, on_rq, running;
int policy = attr->sched_policy;
unsigned long flags;
const struct sched_class *prev_class;
struct rq *rq;
int reset_on_fork;
/* may grab non-irq protected spin_locks */
BUG_ON(in_interrupt());
recheck:
/* double check policy once rq lock held */
if (policy < 0) {
reset_on_fork = p->sched_reset_on_fork;
policy = oldpolicy = p->policy;
} else {
reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
if (policy != SCHED_DEADLINE &&
policy != SCHED_FIFO && policy != SCHED_RR &&
policy != SCHED_NORMAL && policy != SCHED_BATCH &&
policy != SCHED_IDLE)
return -EINVAL;
}
if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
return -EINVAL;
/*
* Valid priorities for SCHED_FIFO and SCHED_RR are
* 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
* SCHED_BATCH and SCHED_IDLE is 0.
*/
if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
(!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
return -EINVAL;
if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
(rt_policy(policy) != (attr->sched_priority != 0)))
return -EINVAL;
/*
* Allow unprivileged RT tasks to decrease priority:
*/
if (user && !capable(CAP_SYS_NICE)) {
if (fair_policy(policy)) {
if (attr->sched_nice < TASK_NICE(p) &&
!can_nice(p, attr->sched_nice))
return -EPERM;
}
if (rt_policy(policy)) {
unsigned long rlim_rtprio =
task_rlimit(p, RLIMIT_RTPRIO);
/* can't set/change the rt policy */
if (policy != p->policy && !rlim_rtprio)
return -EPERM;
/* can't increase priority */
if (attr->sched_priority > p->rt_priority &&
attr->sched_priority > rlim_rtprio)
return -EPERM;
}
/*
* Treat SCHED_IDLE as nice 20. Only allow a switch to
* SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
*/
if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
if (!can_nice(p, TASK_NICE(p)))
return -EPERM;
}
/* can't change other user's priorities */
if (!check_same_owner(p))
return -EPERM;
/* Normal users shall not reset the sched_reset_on_fork flag */
if (p->sched_reset_on_fork && !reset_on_fork)
return -EPERM;
}
if (user) {
retval = security_task_setscheduler(p);
if (retval)
return retval;
}
/*
* make sure no PI-waiters arrive (or leave) while we are
* changing the priority of the task:
*
* To be able to change p->policy safely, the appropriate
* runqueue lock must be held.
*/
rq = task_rq_lock(p, &flags);
/*
* Changing the policy of the stop threads its a very bad idea
*/
if (p == rq->stop) {
task_rq_unlock(rq, p, &flags);
return -EINVAL;
}
/*
* If not changing anything there's no need to proceed further:
*/
if (unlikely(policy == p->policy)) {
if (fair_policy(policy) && attr->sched_nice != TASK_NICE(p))
goto change;
if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
goto change;
if (dl_policy(policy))
goto change;
task_rq_unlock(rq, p, &flags);
return 0;
}
change:
if (user) {
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Do not allow realtime tasks into groups that have no runtime
* assigned.
*/
if (rt_bandwidth_enabled() && rt_policy(policy) &&
task_group(p)->rt_bandwidth.rt_runtime == 0 &&
!task_group_is_autogroup(task_group(p))) {
task_rq_unlock(rq, p, &flags);
return -EPERM;
}
#endif
#ifdef CONFIG_SMP
if (dl_bandwidth_enabled() && dl_policy(policy)) {
cpumask_t *span = rq->rd->span;
/*
* Don't allow tasks with an affinity mask smaller than
* the entire root_domain to become SCHED_DEADLINE. We
* will also fail if there's no bandwidth available.
*/
if (!cpumask_subset(span, &p->cpus_allowed) ||
rq->rd->dl_bw.bw == 0) {
task_rq_unlock(rq, p, &flags);
return -EPERM;
}
}
#endif
}
/* recheck policy now with rq lock held */
if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
policy = oldpolicy = -1;
task_rq_unlock(rq, p, &flags);
goto recheck;
}
/*
* If setscheduling to SCHED_DEADLINE (or changing the parameters
* of a SCHED_DEADLINE task) we need to check if enough bandwidth
* is available.
*/
if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
task_rq_unlock(rq, p, &flags);
return -EBUSY;
}
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
p->sched_reset_on_fork = reset_on_fork;
oldprio = p->prio;
prev_class = p->sched_class;
__setscheduler(rq, p, attr);
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, 0);
check_class_changed(rq, p, prev_class, oldprio);
task_rq_unlock(rq, p, &flags);
rt_mutex_adjust_pi(p);
return 0;
}
static int _sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param, bool check)
{
struct sched_attr attr = {
.sched_policy = policy,
.sched_priority = param->sched_priority,
.sched_nice = PRIO_TO_NICE(p->static_prio),
};
/*
* Fixup the legacy SCHED_RESET_ON_FORK hack
*/
if (policy & SCHED_RESET_ON_FORK) {
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
policy &= ~SCHED_RESET_ON_FORK;
attr.sched_policy = policy;
}
return __sched_setscheduler(p, &attr, check);
}
/**
* sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*
* NOTE that the task may be already dead.
*/
int sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, true);
}
EXPORT_SYMBOL_GPL(sched_setscheduler);
int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
{
return __sched_setscheduler(p, attr, true);
}
EXPORT_SYMBOL_GPL(sched_setattr);
/**
* sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Just like sched_setscheduler, only don't bother checking if the
* current context has permission. For example, this is needed in
* stop_machine(): we create temporary high priority worker threads,
* but our caller might not have that capability.
*
* Return: 0 on success. An error code otherwise.
*/
int sched_setscheduler_nocheck(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, false);
}
static int
do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
{
struct sched_param lparam;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
return -EFAULT;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setscheduler(p, policy, &lparam);
rcu_read_unlock();
return retval;
}
/*
* Mimics kernel/events/core.c perf_copy_attr().
*/
static int sched_copy_attr(struct sched_attr __user *uattr,
struct sched_attr *attr)
{
u32 size;
int ret;
if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
return -EFAULT;
/*
* zero the full structure, so that a short copy will be nice.
*/
memset(attr, 0, sizeof(*attr));
ret = get_user(size, &uattr->size);
if (ret)
return ret;
if (size > PAGE_SIZE) /* silly large */
goto err_size;
if (!size) /* abi compat */
size = SCHED_ATTR_SIZE_VER0;
if (size < SCHED_ATTR_SIZE_VER0)
goto err_size;
/*
* If we're handed a bigger struct than we know of,
* ensure all the unknown bits are 0 - i.e. new
* user-space does not rely on any kernel feature
* extensions we dont know about yet.
*/
if (size > sizeof(*attr)) {
unsigned char __user *addr;
unsigned char __user *end;
unsigned char val;
addr = (void __user *)uattr + sizeof(*attr);
end = (void __user *)uattr + size;
for (; addr < end; addr++) {
ret = get_user(val, addr);
if (ret)
return ret;
if (val)
goto err_size;
}
size = sizeof(*attr);
}
ret = copy_from_user(attr, uattr, size);
if (ret)
return -EFAULT;
/*
* XXX: do we want to be lenient like existing syscalls; or do we want
* to be strict and return an error on out-of-bounds values?
*/
attr->sched_nice = clamp(attr->sched_nice, -20, 19);
out:
return ret;
err_size:
put_user(sizeof(*attr), &uattr->size);
ret = -E2BIG;
goto out;
}
/**
* sys_sched_setscheduler - set/change the scheduler policy and RT priority
* @pid: the pid in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
struct sched_param __user *, param)
{
/* negative values for policy are not valid */
if (policy < 0)
return -EINVAL;
return do_sched_setscheduler(pid, policy, param);
}
/**
* sys_sched_setparam - set/change the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
{
return do_sched_setscheduler(pid, -1, param);
}
/**
* sys_sched_setattr - same as above, but with extended sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
*/
SYSCALL_DEFINE2(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr)
{
struct sched_attr attr;
struct task_struct *p;
int retval;
if (!uattr || pid < 0)
return -EINVAL;
if (sched_copy_attr(uattr, &attr))
return -EFAULT;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setattr(p, &attr);
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getscheduler - get the policy (scheduling class) of a thread
* @pid: the pid in question.
*
* Return: On success, the policy of the thread. Otherwise, a negative error
* code.
*/
SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
{
struct task_struct *p;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (p) {
retval = security_task_getscheduler(p);
if (!retval)
retval = p->policy
| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
}
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getparam - get the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the RT priority.
*
* Return: On success, 0 and the RT priority is in @param. Otherwise, an error
* code.
*/
SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
{
struct sched_param lp;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
if (task_has_dl_policy(p)) {
retval = -EINVAL;
goto out_unlock;
}
lp.sched_priority = p->rt_priority;
rcu_read_unlock();
/*
* This one might sleep, we cannot do it with a spinlock held ...
*/
retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static int sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
goto err_size;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, usize);
if (ret)
return -EFAULT;
out:
return ret;
err_size:
ret = -E2BIG;
goto out;
}
/**
* sys_sched_getattr - similar to sched_getparam, but with sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
* @size: sizeof(attr) for fwd/bwd comp.
*/
SYSCALL_DEFINE3(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
unsigned int, size)
{
struct sched_attr attr = {
.size = sizeof(struct sched_attr),
};
struct task_struct *p;
int retval;
if (!uattr || pid < 0 || size > PAGE_SIZE ||
size < SCHED_ATTR_SIZE_VER0)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
attr.sched_policy = p->policy;
if (p->sched_reset_on_fork)
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
if (task_has_dl_policy(p))
__getparam_dl(p, &attr);
else if (task_has_rt_policy(p))
attr.sched_priority = p->rt_priority;
else
attr.sched_nice = TASK_NICE(p);
rcu_read_unlock();
retval = sched_read_attr(uattr, &attr, size);
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
{
cpumask_var_t cpus_allowed, new_mask;
struct task_struct *p;
int retval;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p) {
rcu_read_unlock();
return -ESRCH;
}
/* Prevent p going away */
get_task_struct(p);
rcu_read_unlock();
if (p->flags & PF_NO_SETAFFINITY) {
retval = -EINVAL;
goto out_put_task;
}
if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_put_task;
}
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_cpus_allowed;
}
retval = -EPERM;
if (!check_same_owner(p)) {
rcu_read_lock();
if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
rcu_read_unlock();
goto out_unlock;
}
rcu_read_unlock();
}
retval = security_task_setscheduler(p);
if (retval)
goto out_unlock;
cpuset_cpus_allowed(p, cpus_allowed);
cpumask_and(new_mask, in_mask, cpus_allowed);
/*
* Since bandwidth control happens on root_domain basis,
* if admission test is enabled, we only admit -deadline
* tasks allowed to run on all the CPUs in the task's
* root_domain.
*/
#ifdef CONFIG_SMP
if (task_has_dl_policy(p)) {
const struct cpumask *span = task_rq(p)->rd->span;
if (dl_bandwidth_enabled() && !cpumask_subset(span, new_mask)) {
retval = -EBUSY;
goto out_unlock;
}
}
#endif
again:
retval = set_cpus_allowed_ptr(p, new_mask);
if (!retval) {
cpuset_cpus_allowed(p, cpus_allowed);
if (!cpumask_subset(new_mask, cpus_allowed)) {
/*
* We must have raced with a concurrent cpuset
* update. Just reset the cpus_allowed to the
* cpuset's cpus_allowed
*/
cpumask_copy(new_mask, cpus_allowed);
goto again;
}
}
out_unlock:
free_cpumask_var(new_mask);
out_free_cpus_allowed:
free_cpumask_var(cpus_allowed);
out_put_task:
put_task_struct(p);
return retval;
}
static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
struct cpumask *new_mask)
{
if (len < cpumask_size())
cpumask_clear(new_mask);
else if (len > cpumask_size())
len = cpumask_size();
return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
}
/**
* sys_sched_setaffinity - set the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to the new cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
cpumask_var_t new_mask;
int retval;
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
return -ENOMEM;
retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
if (retval == 0)
retval = sched_setaffinity(pid, new_mask);
free_cpumask_var(new_mask);
return retval;
}
long sched_getaffinity(pid_t pid, struct cpumask *mask)
{
struct task_struct *p;
unsigned long flags;
int retval;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
raw_spin_lock_irqsave(&p->pi_lock, flags);
cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getaffinity - get the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to hold the current cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
int ret;
cpumask_var_t mask;
if ((len * BITS_PER_BYTE) < nr_cpu_ids)
return -EINVAL;
if (len & (sizeof(unsigned long)-1))
return -EINVAL;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
ret = sched_getaffinity(pid, mask);
if (ret == 0) {
size_t retlen = min_t(size_t, len, cpumask_size());
if (copy_to_user(user_mask_ptr, mask, retlen))
ret = -EFAULT;
else
ret = retlen;
}
free_cpumask_var(mask);
return ret;
}
/**
* sys_sched_yield - yield the current processor to other threads.
*
* This function yields the current CPU to other tasks. If there are no
* other threads running on this CPU then this function will return.
*
* Return: 0.
*/
SYSCALL_DEFINE0(sched_yield)
{
struct rq *rq = this_rq_lock();
schedstat_inc(rq, yld_count);
current->sched_class->yield_task(rq);
/*
* Since we are going to call schedule() anyway, there's
* no need to preempt or enable interrupts:
*/
__release(rq->lock);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
do_raw_spin_unlock(&rq->lock);
sched_preempt_enable_no_resched();
schedule();
return 0;
}
static void __cond_resched(void)
{
__preempt_count_add(PREEMPT_ACTIVE);
__schedule();
__preempt_count_sub(PREEMPT_ACTIVE);
}
int __sched _cond_resched(void)
{
if (should_resched()) {
__cond_resched();
return 1;
}
return 0;
}
EXPORT_SYMBOL(_cond_resched);
/*
* __cond_resched_lock() - if a reschedule is pending, drop the given lock,
* call schedule, and on return reacquire the lock.
*
* This works OK both with and without CONFIG_PREEMPT. We do strange low-level
* operations here to prevent schedule() from being called twice (once via
* spin_unlock(), once by hand).
*/
int __cond_resched_lock(spinlock_t *lock)
{
int resched = should_resched();
int ret = 0;
lockdep_assert_held(lock);
if (spin_needbreak(lock) || resched) {
spin_unlock(lock);
if (resched)
__cond_resched();
else
cpu_relax();
ret = 1;
spin_lock(lock);
}
return ret;
}
EXPORT_SYMBOL(__cond_resched_lock);
int __sched __cond_resched_softirq(void)
{
BUG_ON(!in_softirq());
if (should_resched()) {
local_bh_enable();
__cond_resched();
local_bh_disable();
return 1;
}
return 0;
}
EXPORT_SYMBOL(__cond_resched_softirq);
/**
* yield - yield the current processor to other threads.
*
* Do not ever use this function, there's a 99% chance you're doing it wrong.
*
* The scheduler is at all times free to pick the calling task as the most
* eligible task to run, if removing the yield() call from your code breaks
* it, its already broken.
*
* Typical broken usage is:
*
* while (!event)
* yield();
*
* where one assumes that yield() will let 'the other' process run that will
* make event true. If the current task is a SCHED_FIFO task that will never
* happen. Never use yield() as a progress guarantee!!
*
* If you want to use yield() to wait for something, use wait_event().
* If you want to use yield() to be 'nice' for others, use cond_resched().
* If you still want to use yield(), do not!
*/
void __sched yield(void)
{
set_current_state(TASK_RUNNING);
sys_sched_yield();
}
EXPORT_SYMBOL(yield);
/**
* yield_to - yield the current processor to another thread in
* your thread group, or accelerate that thread toward the
* processor it's on.
* @p: target task
* @preempt: whether task preemption is allowed or not
*
* It's the caller's job to ensure that the target task struct
* can't go away on us before we can do any checks.
*
* Return:
* true (>0) if we indeed boosted the target task.
* false (0) if we failed to boost the target.
* -ESRCH if there's no task to yield to.
*/
bool __sched yield_to(struct task_struct *p, bool preempt)
{
struct task_struct *curr = current;
struct rq *rq, *p_rq;
unsigned long flags;
int yielded = 0;
local_irq_save(flags);
rq = this_rq();
again:
p_rq = task_rq(p);
/*
* If we're the only runnable task on the rq and target rq also
* has only one task, there's absolutely no point in yielding.
*/
if (rq->nr_running == 1 && p_rq->nr_running == 1) {
yielded = -ESRCH;
goto out_irq;
}
double_rq_lock(rq, p_rq);
if (task_rq(p) != p_rq) {
double_rq_unlock(rq, p_rq);
goto again;
}
if (!curr->sched_class->yield_to_task)
goto out_unlock;
if (curr->sched_class != p->sched_class)
goto out_unlock;
if (task_running(p_rq, p) || p->state)
goto out_unlock;
yielded = curr->sched_class->yield_to_task(rq, p, preempt);
if (yielded) {
schedstat_inc(rq, yld_count);
/*
* Make p's CPU reschedule; pick_next_entity takes care of
* fairness.
*/
if (preempt && rq != p_rq)
resched_task(p_rq->curr);
}
out_unlock:
double_rq_unlock(rq, p_rq);
out_irq:
local_irq_restore(flags);
if (yielded > 0)
schedule();
return yielded;
}
EXPORT_SYMBOL_GPL(yield_to);
/*
* This task is about to go to sleep on IO. Increment rq->nr_iowait so
* that process accounting knows that this is a task in IO wait state.
*/
void __sched io_schedule(void)
{
struct rq *rq = raw_rq();
delayacct_blkio_start();
atomic_inc(&rq->nr_iowait);
blk_flush_plug(current);
current->in_iowait = 1;
schedule();
current->in_iowait = 0;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
}
EXPORT_SYMBOL(io_schedule);
long __sched io_schedule_timeout(long timeout)
{
struct rq *rq = raw_rq();
long ret;
delayacct_blkio_start();
atomic_inc(&rq->nr_iowait);
blk_flush_plug(current);
current->in_iowait = 1;
ret = schedule_timeout(timeout);
current->in_iowait = 0;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
return ret;
}
/**
* sys_sched_get_priority_max - return maximum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the maximum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = MAX_USER_RT_PRIO-1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
break;
}
return ret;
}
/**
* sys_sched_get_priority_min - return minimum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the minimum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = 1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
}
return ret;
}
/**
* sys_sched_rr_get_interval - return the default timeslice of a process.
* @pid: pid of the process.
* @interval: userspace pointer to the timeslice value.
*
* this syscall writes the default timeslice value of a given process
* into the user-space timespec buffer. A value of '0' means infinity.
*
* Return: On success, 0 and the timeslice is in @interval. Otherwise,
* an error code.
*/
SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
struct timespec __user *, interval)
{
struct task_struct *p;
unsigned int time_slice;
unsigned long flags;
struct rq *rq;
int retval;
struct timespec t;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
rq = task_rq_lock(p, &flags);
time_slice = 0;
if (p->sched_class->get_rr_interval)
time_slice = p->sched_class->get_rr_interval(rq, p);
task_rq_unlock(rq, p, &flags);
rcu_read_unlock();
jiffies_to_timespec(time_slice, &t);
retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
void sched_show_task(struct task_struct *p)
{
unsigned long free = 0;
int ppid;
unsigned state;
state = p->state ? __ffs(p->state) + 1 : 0;
printk(KERN_INFO "%-15.15s %c", p->comm,
state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
#if BITS_PER_LONG == 32
if (state == TASK_RUNNING)
printk(KERN_CONT " running ");
else
printk(KERN_CONT " %08lx ", thread_saved_pc(p));
#else
if (state == TASK_RUNNING)
printk(KERN_CONT " running task ");
else
printk(KERN_CONT " %016lx ", thread_saved_pc(p));
#endif
#ifdef CONFIG_DEBUG_STACK_USAGE
free = stack_not_used(p);
#endif
rcu_read_lock();
ppid = task_pid_nr(rcu_dereference(p->real_parent));
rcu_read_unlock();
printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
task_pid_nr(p), ppid,
(unsigned long)task_thread_info(p)->flags);
print_worker_info(KERN_INFO, p);
show_stack(p, NULL);
}
void show_state_filter(unsigned long state_filter)
{
struct task_struct *g, *p;
#if BITS_PER_LONG == 32
printk(KERN_INFO
" task PC stack pid father\n");
#else
printk(KERN_INFO
" task PC stack pid father\n");
#endif
rcu_read_lock();
do_each_thread(g, p) {
/*
* reset the NMI-timeout, listing all files on a slow
* console might take a lot of time:
*/
touch_nmi_watchdog();
if (!state_filter || (p->state & state_filter))
sched_show_task(p);
} while_each_thread(g, p);
touch_all_softlockup_watchdogs();
#ifdef CONFIG_SCHED_DEBUG
sysrq_sched_debug_show();
#endif
rcu_read_unlock();
/*
* Only show locks if all tasks are dumped:
*/
if (!state_filter)
debug_show_all_locks();
}
void init_idle_bootup_task(struct task_struct *idle)
{
idle->sched_class = &idle_sched_class;
}
/**
* init_idle - set up an idle thread for a given CPU
* @idle: task in question
* @cpu: cpu the idle task belongs to
*
* NOTE: this function does not set the idle thread's NEED_RESCHED
* flag, to make booting more robust.
*/
void init_idle(struct task_struct *idle, int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
__sched_fork(0, idle);
idle->state = TASK_RUNNING;
idle->se.exec_start = sched_clock();
do_set_cpus_allowed(idle, cpumask_of(cpu));
/*
* We're having a chicken and egg problem, even though we are
* holding rq->lock, the cpu isn't yet set to this cpu so the
* lockdep check in task_group() will fail.
*
* Similar case to sched_fork(). / Alternatively we could
* use task_rq_lock() here and obtain the other rq->lock.
*
* Silence PROVE_RCU
*/
rcu_read_lock();
__set_task_cpu(idle, cpu);
rcu_read_unlock();
rq->curr = rq->idle = idle;
#if defined(CONFIG_SMP)
idle->on_cpu = 1;
#endif
raw_spin_unlock_irqrestore(&rq->lock, flags);
/* Set the preempt count _outside_ the spinlocks! */
init_idle_preempt_count(idle, cpu);
/*
* The idle tasks have their own, simple scheduling class:
*/
idle->sched_class = &idle_sched_class;
ftrace_graph_init_idle_task(idle, cpu);
vtime_init_idle(idle, cpu);
#if defined(CONFIG_SMP)
sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
#endif
}
#ifdef CONFIG_SMP
void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
{
if (p->sched_class && p->sched_class->set_cpus_allowed)
p->sched_class->set_cpus_allowed(p, new_mask);
cpumask_copy(&p->cpus_allowed, new_mask);
p->nr_cpus_allowed = cpumask_weight(new_mask);
}
/*
* This is how migration works:
*
* 1) we invoke migration_cpu_stop() on the target CPU using
* stop_one_cpu().
* 2) stopper starts to run (implicitly forcing the migrated thread
* off the CPU)
* 3) it checks whether the migrated task is still in the wrong runqueue.
* 4) if it's in the wrong runqueue then the migration thread removes
* it and puts it into the right queue.
* 5) stopper completes and stop_one_cpu() returns and the migration
* is done.
*/
/*
* Change a given task's CPU affinity. Migrate the thread to a
* proper CPU and schedule it away if the CPU it's executing on
* is removed from the allowed bitmask.
*
* NOTE: the caller must have a valid reference to the task, the
* task must not exit() & deallocate itself prematurely. The
* call is not atomic; no spinlocks may be held.
*/
int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
{
unsigned long flags;
struct rq *rq;
unsigned int dest_cpu;
int ret = 0;
rq = task_rq_lock(p, &flags);
if (cpumask_equal(&p->cpus_allowed, new_mask))
goto out;
if (!cpumask_intersects(new_mask, cpu_active_mask)) {
ret = -EINVAL;
goto out;
}
do_set_cpus_allowed(p, new_mask);
/* Can the task run on the task's current CPU? If so, we're done */
if (cpumask_test_cpu(task_cpu(p), new_mask))
goto out;
dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
if (p->on_rq) {
struct migration_arg arg = { p, dest_cpu };
/* Need help from migration thread: drop lock and wait. */
task_rq_unlock(rq, p, &flags);
stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
tlb_migrate_finish(p->mm);
return 0;
}
out:
task_rq_unlock(rq, p, &flags);
return ret;
}
EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
/*
* Move (not current) task off this cpu, onto dest cpu. We're doing
* this because either it can't run here any more (set_cpus_allowed()
* away from this CPU, or CPU going down), or because we're
* attempting to rebalance this task on exec (sched_exec).
*
* So we race with normal scheduler movements, but that's OK, as long
* as the task is no longer on this CPU.
*
* Returns non-zero if task was successfully migrated.
*/
static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
{
struct rq *rq_dest, *rq_src;
int ret = 0;
if (unlikely(!cpu_active(dest_cpu)))
return ret;
rq_src = cpu_rq(src_cpu);
rq_dest = cpu_rq(dest_cpu);
raw_spin_lock(&p->pi_lock);
double_rq_lock(rq_src, rq_dest);
/* Already moved. */
if (task_cpu(p) != src_cpu)
goto done;
/* Affinity changed (again). */
if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
goto fail;
/*
* If we're not on a rq, the next wake-up will ensure we're
* placed properly.
*/
if (p->on_rq) {
dequeue_task(rq_src, p, 0);
set_task_cpu(p, dest_cpu);
enqueue_task(rq_dest, p, 0);
check_preempt_curr(rq_dest, p, 0);
}
done:
ret = 1;
fail:
double_rq_unlock(rq_src, rq_dest);
raw_spin_unlock(&p->pi_lock);
return ret;
}
#ifdef CONFIG_NUMA_BALANCING
/* Migrate current task p to target_cpu */
int migrate_task_to(struct task_struct *p, int target_cpu)
{
struct migration_arg arg = { p, target_cpu };
int curr_cpu = task_cpu(p);
if (curr_cpu == target_cpu)
return 0;
if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
return -EINVAL;
/* TODO: This is not properly updating schedstats */
trace_sched_move_numa(p, curr_cpu, target_cpu);
return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
}
/*
* Requeue a task on a given node and accurately track the number of NUMA
* tasks on the runqueues
*/
void sched_setnuma(struct task_struct *p, int nid)
{
struct rq *rq;
unsigned long flags;
bool on_rq, running;
rq = task_rq_lock(p, &flags);
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
p->numa_preferred_nid = nid;
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, 0);
task_rq_unlock(rq, p, &flags);
}
#endif
/*
* migration_cpu_stop - this will be executed by a highprio stopper thread
* and performs thread migration by bumping thread off CPU then
* 'pushing' onto another runqueue.
*/
static int migration_cpu_stop(void *data)
{
struct migration_arg *arg = data;
/*
* The original target cpu might have gone down and we might
* be on another cpu but it doesn't matter.
*/
local_irq_disable();
__migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
local_irq_enable();
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
/*
* Ensures that the idle task is using init_mm right before its cpu goes
* offline.
*/
void idle_task_exit(void)
{
struct mm_struct *mm = current->active_mm;
BUG_ON(cpu_online(smp_processor_id()));
if (mm != &init_mm)
switch_mm(mm, &init_mm, current);
mmdrop(mm);
}
/*
* Since this CPU is going 'away' for a while, fold any nr_active delta
* we might have. Assumes we're called after migrate_tasks() so that the
* nr_active count is stable.
*
* Also see the comment "Global load-average calculations".
*/
static void calc_load_migrate(struct rq *rq)
{
long delta = calc_load_fold_active(rq);
if (delta)
atomic_long_add(delta, &calc_load_tasks);
}
/*
* Migrate all tasks from the rq, sleeping tasks will be migrated by
* try_to_wake_up()->select_task_rq().
*
* Called with rq->lock held even though we'er in stop_machine() and
* there's no concurrency possible, we hold the required locks anyway
* because of lock validation efforts.
*/
static void migrate_tasks(unsigned int dead_cpu)
{
struct rq *rq = cpu_rq(dead_cpu);
struct task_struct *next, *stop = rq->stop;
int dest_cpu;
/*
* Fudge the rq selection such that the below task selection loop
* doesn't get stuck on the currently eligible stop task.
*
* We're currently inside stop_machine() and the rq is either stuck
* in the stop_machine_cpu_stop() loop, or we're executing this code,
* either way we should never end up calling schedule() until we're
* done here.
*/
rq->stop = NULL;
/*
* put_prev_task() and pick_next_task() sched
* class method both need to have an up-to-date
* value of rq->clock[_task]
*/
update_rq_clock(rq);
for ( ; ; ) {
/*
* There's this thread running, bail when that's the only
* remaining thread.
*/
if (rq->nr_running == 1)
break;
next = pick_next_task(rq);
BUG_ON(!next);
next->sched_class->put_prev_task(rq, next);
/* Find suitable destination for @next, with force if needed. */
dest_cpu = select_fallback_rq(dead_cpu, next);
raw_spin_unlock(&rq->lock);
__migrate_task(next, dead_cpu, dest_cpu);
raw_spin_lock(&rq->lock);
}
rq->stop = stop;
}
#endif /* CONFIG_HOTPLUG_CPU */
#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
static struct ctl_table sd_ctl_dir[] = {
{
.procname = "sched_domain",
.mode = 0555,
},
{}
};
static struct ctl_table sd_ctl_root[] = {
{
.procname = "kernel",
.mode = 0555,
.child = sd_ctl_dir,
},
{}
};
static struct ctl_table *sd_alloc_ctl_entry(int n)
{
struct ctl_table *entry =
kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
return entry;
}
static void sd_free_ctl_entry(struct ctl_table **tablep)
{
struct ctl_table *entry;
/*
* In the intermediate directories, both the child directory and
* procname are dynamically allocated and could fail but the mode
* will always be set. In the lowest directory the names are
* static strings and all have proc handlers.
*/
for (entry = *tablep; entry->mode; entry++) {
if (entry->child)
sd_free_ctl_entry(&entry->child);
if (entry->proc_handler == NULL)
kfree(entry->procname);
}
kfree(*tablep);
*tablep = NULL;
}
static int min_load_idx = 0;
static int max_load_idx = CPU_LOAD_IDX_MAX-1;
static void
set_table_entry(struct ctl_table *entry,
const char *procname, void *data, int maxlen,
umode_t mode, proc_handler *proc_handler,
bool load_idx)
{
entry->procname = procname;
entry->data = data;
entry->maxlen = maxlen;
entry->mode = mode;
entry->proc_handler = proc_handler;
if (load_idx) {
entry->extra1 = &min_load_idx;
entry->extra2 = &max_load_idx;
}
}
static struct ctl_table *
sd_alloc_ctl_domain_table(struct sched_domain *sd)
{
struct ctl_table *table = sd_alloc_ctl_entry(13);
if (table == NULL)
return NULL;
set_table_entry(&table[0], "min_interval", &sd->min_interval,
sizeof(long), 0644, proc_doulongvec_minmax, false);
set_table_entry(&table[1], "max_interval", &sd->max_interval,
sizeof(long), 0644, proc_doulongvec_minmax, false);
set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[9], "cache_nice_tries",
&sd->cache_nice_tries,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[10], "flags", &sd->flags,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[11], "name", sd->name,
CORENAME_MAX_SIZE, 0444, proc_dostring, false);
/* &table[12] is terminator */
return table;
}
static struct ctl_table *sd_alloc_ctl_cpu_table(int cpu)
{
struct ctl_table *entry, *table;
struct sched_domain *sd;
int domain_num = 0, i;
char buf[32];
for_each_domain(cpu, sd)
domain_num++;
entry = table = sd_alloc_ctl_entry(domain_num + 1);
if (table == NULL)
return NULL;
i = 0;
for_each_domain(cpu, sd) {
snprintf(buf, 32, "domain%d", i);
entry->procname = kstrdup(buf, GFP_KERNEL);
entry->mode = 0555;
entry->child = sd_alloc_ctl_domain_table(sd);
entry++;
i++;
}
return table;
}
static struct ctl_table_header *sd_sysctl_header;
static void register_sched_domain_sysctl(void)
{
int i, cpu_num = num_possible_cpus();
struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
char buf[32];
WARN_ON(sd_ctl_dir[0].child);
sd_ctl_dir[0].child = entry;
if (entry == NULL)
return;
for_each_possible_cpu(i) {
snprintf(buf, 32, "cpu%d", i);
entry->procname = kstrdup(buf, GFP_KERNEL);
entry->mode = 0555;
entry->child = sd_alloc_ctl_cpu_table(i);
entry++;
}
WARN_ON(sd_sysctl_header);
sd_sysctl_header = register_sysctl_table(sd_ctl_root);
}
/* may be called multiple times per register */
static void unregister_sched_domain_sysctl(void)
{
if (sd_sysctl_header)
unregister_sysctl_table(sd_sysctl_header);
sd_sysctl_header = NULL;
if (sd_ctl_dir[0].child)
sd_free_ctl_entry(&sd_ctl_dir[0].child);
}
#else
static void register_sched_domain_sysctl(void)
{
}
static void unregister_sched_domain_sysctl(void)
{
}
#endif
static void set_rq_online(struct rq *rq)
{
if (!rq->online) {
const struct sched_class *class;
cpumask_set_cpu(rq->cpu, rq->rd->online);
rq->online = 1;
for_each_class(class) {
if (class->rq_online)
class->rq_online(rq);
}
}
}
static void set_rq_offline(struct rq *rq)
{
if (rq->online) {
const struct sched_class *class;
for_each_class(class) {
if (class->rq_offline)
class->rq_offline(rq);
}
cpumask_clear_cpu(rq->cpu, rq->rd->online);
rq->online = 0;
}
}
/*
* migration_call - callback that gets triggered when a CPU is added.
* Here we can start up the necessary migration thread for the new CPU.
*/
static int
migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
int cpu = (long)hcpu;
unsigned long flags;
struct rq *rq = cpu_rq(cpu);
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_UP_PREPARE:
rq->calc_load_update = calc_load_update;
break;
case CPU_ONLINE:
/* Update our root-domain */
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_online(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_DYING:
sched_ttwu_pending();
/* Update our root-domain */
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_offline(rq);
}
migrate_tasks(cpu);
BUG_ON(rq->nr_running != 1); /* the migration thread */
raw_spin_unlock_irqrestore(&rq->lock, flags);
break;
case CPU_DEAD:
calc_load_migrate(rq);
break;
#endif
}
update_max_interval();
return NOTIFY_OK;
}
/*
* Register at high priority so that task migration (migrate_all_tasks)
* happens before everything else. This has to be lower priority than
* the notifier in the perf_event subsystem, though.
*/
static struct notifier_block migration_notifier = {
.notifier_call = migration_call,
.priority = CPU_PRI_MIGRATION,
};
static int sched_cpu_active(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_STARTING:
case CPU_DOWN_FAILED:
set_cpu_active((long)hcpu, true);
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static int sched_cpu_inactive(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned long flags;
long cpu = (long)hcpu;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DOWN_PREPARE:
set_cpu_active(cpu, false);
/* explicitly allow suspend */
if (!(action & CPU_TASKS_FROZEN)) {
struct dl_bw *dl_b = dl_bw_of(cpu);
bool overflow;
int cpus;
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(cpu);
overflow = __dl_overflow(dl_b, cpus, 0, 0);
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
if (overflow)
return notifier_from_errno(-EBUSY);
}
return NOTIFY_OK;
}
return NOTIFY_DONE;
}
static int __init migration_init(void)
{
void *cpu = (void *)(long)smp_processor_id();
int err;
/* Initialize migration for the boot CPU */
err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
BUG_ON(err == NOTIFY_BAD);
migration_call(&migration_notifier, CPU_ONLINE, cpu);
register_cpu_notifier(&migration_notifier);
/* Register cpu active notifiers */
cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
return 0;
}
early_initcall(migration_init);
#endif
#ifdef CONFIG_SMP
static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
#ifdef CONFIG_SCHED_DEBUG
static __read_mostly int sched_debug_enabled;
static int __init sched_debug_setup(char *str)
{
sched_debug_enabled = 1;
return 0;
}
early_param("sched_debug", sched_debug_setup);
static inline bool sched_debug(void)
{
return sched_debug_enabled;
}
static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
struct cpumask *groupmask)
{
struct sched_group *group = sd->groups;
char str[256];
cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
cpumask_clear(groupmask);
printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
if (!(sd->flags & SD_LOAD_BALANCE)) {
printk("does not load-balance\n");
if (sd->parent)
printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
" has parent");
return -1;
}
printk(KERN_CONT "span %s level %s\n", str, sd->name);
if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
printk(KERN_ERR "ERROR: domain->span does not contain "
"CPU%d\n", cpu);
}
if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
printk(KERN_ERR "ERROR: domain->groups does not contain"
" CPU%d\n", cpu);
}
printk(KERN_DEBUG "%*s groups:", level + 1, "");
do {
if (!group) {
printk("\n");
printk(KERN_ERR "ERROR: group is NULL\n");
break;
}
/*
* Even though we initialize ->power to something semi-sane,
* we leave power_orig unset. This allows us to detect if
* domain iteration is still funny without causing /0 traps.
*/
if (!group->sgp->power_orig) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: domain->cpu_power not "
"set\n");
break;
}
if (!cpumask_weight(sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: empty group\n");
break;
}
if (!(sd->flags & SD_OVERLAP) &&
cpumask_intersects(groupmask, sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: repeated CPUs\n");
break;
}
cpumask_or(groupmask, groupmask, sched_group_cpus(group));
cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
printk(KERN_CONT " %s", str);
if (group->sgp->power != SCHED_POWER_SCALE) {
printk(KERN_CONT " (cpu_power = %d)",
group->sgp->power);
}
group = group->next;
} while (group != sd->groups);
printk(KERN_CONT "\n");
if (!cpumask_equal(sched_domain_span(sd), groupmask))
printk(KERN_ERR "ERROR: groups don't span domain->span\n");
if (sd->parent &&
!cpumask_subset(groupmask, sched_domain_span(sd->parent)))
printk(KERN_ERR "ERROR: parent span is not a superset "
"of domain->span\n");
return 0;
}
static void sched_domain_debug(struct sched_domain *sd, int cpu)
{
int level = 0;
if (!sched_debug_enabled)
return;
if (!sd) {
printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
return;
}
printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
for (;;) {
if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
break;
level++;
sd = sd->parent;
if (!sd)
break;
}
}
#else /* !CONFIG_SCHED_DEBUG */
# define sched_domain_debug(sd, cpu) do { } while (0)
static inline bool sched_debug(void)
{
return false;
}
#endif /* CONFIG_SCHED_DEBUG */
static int sd_degenerate(struct sched_domain *sd)
{
if (cpumask_weight(sched_domain_span(sd)) == 1)
return 1;
/* Following flags need at least 2 groups */
if (sd->flags & (SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUPOWER |
SD_SHARE_PKG_RESOURCES)) {
if (sd->groups != sd->groups->next)
return 0;
}
/* Following flags don't use groups */
if (sd->flags & (SD_WAKE_AFFINE))
return 0;
return 1;
}
static int
sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
{
unsigned long cflags = sd->flags, pflags = parent->flags;
if (sd_degenerate(parent))
return 1;
if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
return 0;
/* Flags needing groups don't count if only 1 group in parent */
if (parent->groups == parent->groups->next) {
pflags &= ~(SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUPOWER |
SD_SHARE_PKG_RESOURCES |
SD_PREFER_SIBLING);
if (nr_node_ids == 1)
pflags &= ~SD_SERIALIZE;
}
if (~cflags & pflags)
return 0;
return 1;
}
static void free_rootdomain(struct rcu_head *rcu)
{
struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
cpupri_cleanup(&rd->cpupri);
cpudl_cleanup(&rd->cpudl);
free_cpumask_var(rd->dlo_mask);
free_cpumask_var(rd->rto_mask);
free_cpumask_var(rd->online);
free_cpumask_var(rd->span);
kfree(rd);
}
static void rq_attach_root(struct rq *rq, struct root_domain *rd)
{
struct root_domain *old_rd = NULL;
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
old_rd = rq->rd;
if (cpumask_test_cpu(rq->cpu, old_rd->online))
set_rq_offline(rq);
cpumask_clear_cpu(rq->cpu, old_rd->span);
/*
* If we dont want to free the old_rd yet then
* set old_rd to NULL to skip the freeing later
* in this function:
*/
if (!atomic_dec_and_test(&old_rd->refcount))
old_rd = NULL;
}
atomic_inc(&rd->refcount);
rq->rd = rd;
cpumask_set_cpu(rq->cpu, rd->span);
if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
set_rq_online(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
if (old_rd)
call_rcu_sched(&old_rd->rcu, free_rootdomain);
}
static int init_rootdomain(struct root_domain *rd)
{
memset(rd, 0, sizeof(*rd));
if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
goto out;
if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
goto free_span;
if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
goto free_online;
if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
goto free_dlo_mask;
init_dl_bw(&rd->dl_bw);
if (cpudl_init(&rd->cpudl) != 0)
goto free_dlo_mask;
if (cpupri_init(&rd->cpupri) != 0)
goto free_rto_mask;
return 0;
free_rto_mask:
free_cpumask_var(rd->rto_mask);
free_dlo_mask:
free_cpumask_var(rd->dlo_mask);
free_online:
free_cpumask_var(rd->online);
free_span:
free_cpumask_var(rd->span);
out:
return -ENOMEM;
}
/*
* By default the system creates a single root-domain with all cpus as
* members (mimicking the global state we have today).
*/
struct root_domain def_root_domain;
static void init_defrootdomain(void)
{
init_rootdomain(&def_root_domain);
atomic_set(&def_root_domain.refcount, 1);
}
static struct root_domain *alloc_rootdomain(void)
{
struct root_domain *rd;
rd = kmalloc(sizeof(*rd), GFP_KERNEL);
if (!rd)
return NULL;
if (init_rootdomain(rd) != 0) {
kfree(rd);
return NULL;
}
return rd;
}
static void free_sched_groups(struct sched_group *sg, int free_sgp)
{
struct sched_group *tmp, *first;
if (!sg)
return;
first = sg;
do {
tmp = sg->next;
if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
kfree(sg->sgp);
kfree(sg);
sg = tmp;
} while (sg != first);
}
static void free_sched_domain(struct rcu_head *rcu)
{
struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
/*
* If its an overlapping domain it has private groups, iterate and
* nuke them all.
*/
if (sd->flags & SD_OVERLAP) {
free_sched_groups(sd->groups, 1);
} else if (atomic_dec_and_test(&sd->groups->ref)) {
kfree(sd->groups->sgp);
kfree(sd->groups);
}
kfree(sd);
}
static void destroy_sched_domain(struct sched_domain *sd, int cpu)
{
call_rcu(&sd->rcu, free_sched_domain);
}
static void destroy_sched_domains(struct sched_domain *sd, int cpu)
{
for (; sd; sd = sd->parent)
destroy_sched_domain(sd, cpu);
}
/*
* Keep a special pointer to the highest sched_domain that has
* SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
* allows us to avoid some pointer chasing select_idle_sibling().
*
* Also keep a unique ID per domain (we use the first cpu number in
* the cpumask of the domain), this allows us to quickly tell if
* two cpus are in the same cache domain, see cpus_share_cache().
*/
DEFINE_PER_CPU(struct sched_domain *, sd_llc);
DEFINE_PER_CPU(int, sd_llc_size);
DEFINE_PER_CPU(int, sd_llc_id);
DEFINE_PER_CPU(struct sched_domain *, sd_numa);
DEFINE_PER_CPU(struct sched_domain *, sd_busy);
DEFINE_PER_CPU(struct sched_domain *, sd_asym);
static void update_top_cache_domain(int cpu)
{
struct sched_domain *sd;
struct sched_domain *busy_sd = NULL;
int id = cpu;
int size = 1;
sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
if (sd) {
id = cpumask_first(sched_domain_span(sd));
size = cpumask_weight(sched_domain_span(sd));
busy_sd = sd->parent; /* sd_busy */
}
rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
per_cpu(sd_llc_size, cpu) = size;
per_cpu(sd_llc_id, cpu) = id;
sd = lowest_flag_domain(cpu, SD_NUMA);
rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
}
/*
* Attach the domain 'sd' to 'cpu' as its base domain. Callers must
* hold the hotplug lock.
*/
static void
cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct sched_domain *tmp;
/* Remove the sched domains which do not contribute to scheduling. */
for (tmp = sd; tmp; ) {
struct sched_domain *parent = tmp->parent;
if (!parent)
break;
if (sd_parent_degenerate(tmp, parent)) {
tmp->parent = parent->parent;
if (parent->parent)
parent->parent->child = tmp;
/*
* Transfer SD_PREFER_SIBLING down in case of a
* degenerate parent; the spans match for this
* so the property transfers.
*/
if (parent->flags & SD_PREFER_SIBLING)
tmp->flags |= SD_PREFER_SIBLING;
destroy_sched_domain(parent, cpu);
} else
tmp = tmp->parent;
}
if (sd && sd_degenerate(sd)) {
tmp = sd;
sd = sd->parent;
destroy_sched_domain(tmp, cpu);
if (sd)
sd->child = NULL;
}
sched_domain_debug(sd, cpu);
rq_attach_root(rq, rd);
tmp = rq->sd;
rcu_assign_pointer(rq->sd, sd);
destroy_sched_domains(tmp, cpu);
update_top_cache_domain(cpu);
}
/* cpus with isolated domains */
static cpumask_var_t cpu_isolated_map;
/* Setup the mask of cpus configured for isolated domains */
static int __init isolated_cpu_setup(char *str)
{
alloc_bootmem_cpumask_var(&cpu_isolated_map);
cpulist_parse(str, cpu_isolated_map);
return 1;
}
__setup("isolcpus=", isolated_cpu_setup);
static const struct cpumask *cpu_cpu_mask(int cpu)
{
return cpumask_of_node(cpu_to_node(cpu));
}
struct sd_data {
struct sched_domain **__percpu sd;
struct sched_group **__percpu sg;
struct sched_group_power **__percpu sgp;
};
struct s_data {
struct sched_domain ** __percpu sd;
struct root_domain *rd;
};
enum s_alloc {
sa_rootdomain,
sa_sd,
sa_sd_storage,
sa_none,
};
struct sched_domain_topology_level;
typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
#define SDTL_OVERLAP 0x01
struct sched_domain_topology_level {
sched_domain_init_f init;
sched_domain_mask_f mask;
int flags;
int numa_level;
struct sd_data data;
};
/*
* Build an iteration mask that can exclude certain CPUs from the upwards
* domain traversal.
*
* Asymmetric node setups can result in situations where the domain tree is of
* unequal depth, make sure to skip domains that already cover the entire
* range.
*
* In that case build_sched_domains() will have terminated the iteration early
* and our sibling sd spans will be empty. Domains should always include the
* cpu they're built on, so check that.
*
*/
static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
{
const struct cpumask *span = sched_domain_span(sd);
struct sd_data *sdd = sd->private;
struct sched_domain *sibling;
int i;
for_each_cpu(i, span) {
sibling = *per_cpu_ptr(sdd->sd, i);
if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
continue;
cpumask_set_cpu(i, sched_group_mask(sg));
}
}
/*
* Return the canonical balance cpu for this group, this is the first cpu
* of this group that's also in the iteration mask.
*/
int group_balance_cpu(struct sched_group *sg)
{
return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
}
static int
build_overlap_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered = sched_domains_tmpmask;
struct sd_data *sdd = sd->private;
struct sched_domain *child;
int i;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct cpumask *sg_span;
if (cpumask_test_cpu(i, covered))
continue;
child = *per_cpu_ptr(sdd->sd, i);
/* See the comment near build_group_mask(). */
if (!cpumask_test_cpu(i, sched_domain_span(child)))
continue;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(cpu));
if (!sg)
goto fail;
sg_span = sched_group_cpus(sg);
if (child->child) {
child = child->child;
cpumask_copy(sg_span, sched_domain_span(child));
} else
cpumask_set_cpu(i, sg_span);
cpumask_or(covered, covered, sg_span);
sg->sgp = *per_cpu_ptr(sdd->sgp, i);
if (atomic_inc_return(&sg->sgp->ref) == 1)
build_group_mask(sd, sg);
/*
* Initialize sgp->power such that even if we mess up the
* domains and no possible iteration will get us here, we won't
* die on a /0 trap.
*/
sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span);
sg->sgp->power_orig = sg->sgp->power;
/*
* Make sure the first group of this domain contains the
* canonical balance cpu. Otherwise the sched_domain iteration
* breaks. See update_sg_lb_stats().
*/
if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
group_balance_cpu(sg) == cpu)
groups = sg;
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
last->next = first;
}
sd->groups = groups;
return 0;
fail:
free_sched_groups(first, 0);
return -ENOMEM;
}
static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
{
struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
struct sched_domain *child = sd->child;
if (child)
cpu = cpumask_first(sched_domain_span(child));
if (sg) {
*sg = *per_cpu_ptr(sdd->sg, cpu);
(*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
}
return cpu;
}
/*
* build_sched_groups will build a circular linked list of the groups
* covered by the given span, and will set each group's ->cpumask correctly,
* and ->cpu_power to 0.
*
* Assumes the sched_domain tree is fully constructed
*/
static int
build_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL;
struct sd_data *sdd = sd->private;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered;
int i;
get_group(cpu, sdd, &sd->groups);
atomic_inc(&sd->groups->ref);
if (cpu != cpumask_first(span))
return 0;
lockdep_assert_held(&sched_domains_mutex);
covered = sched_domains_tmpmask;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct sched_group *sg;
int group, j;
if (cpumask_test_cpu(i, covered))
continue;
group = get_group(i, sdd, &sg);
cpumask_clear(sched_group_cpus(sg));
sg->sgp->power = 0;
cpumask_setall(sched_group_mask(sg));
for_each_cpu(j, span) {
if (get_group(j, sdd, NULL) != group)
continue;
cpumask_set_cpu(j, covered);
cpumask_set_cpu(j, sched_group_cpus(sg));
}
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
}
last->next = first;
return 0;
}
/*
* Initialize sched groups cpu_power.
*
* cpu_power indicates the capacity of sched group, which is used while
* distributing the load between different sched groups in a sched domain.
* Typically cpu_power for all the groups in a sched domain will be same unless
* there are asymmetries in the topology. If there are asymmetries, group
* having more cpu_power will pickup more load compared to the group having
* less cpu_power.
*/
static void init_sched_groups_power(int cpu, struct sched_domain *sd)
{
struct sched_group *sg = sd->groups;
WARN_ON(!sg);
do {
sg->group_weight = cpumask_weight(sched_group_cpus(sg));
sg = sg->next;
} while (sg != sd->groups);
if (cpu != group_balance_cpu(sg))
return;
update_group_power(sd, cpu);
atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
}
int __weak arch_sd_sibling_asym_packing(void)
{
return 0*SD_ASYM_PACKING;
}
/*
* Initializers for schedule domains
* Non-inlined to reduce accumulated stack pressure in build_sched_domains()
*/
#ifdef CONFIG_SCHED_DEBUG
# define SD_INIT_NAME(sd, type) sd->name = #type
#else
# define SD_INIT_NAME(sd, type) do { } while (0)
#endif
#define SD_INIT_FUNC(type) \
static noinline struct sched_domain * \
sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
{ \
struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
*sd = SD_##type##_INIT; \
SD_INIT_NAME(sd, type); \
sd->private = &tl->data; \
return sd; \
}
SD_INIT_FUNC(CPU)
#ifdef CONFIG_SCHED_SMT
SD_INIT_FUNC(SIBLING)
#endif
#ifdef CONFIG_SCHED_MC
SD_INIT_FUNC(MC)
#endif
#ifdef CONFIG_SCHED_BOOK
SD_INIT_FUNC(BOOK)
#endif
static int default_relax_domain_level = -1;
int sched_domain_level_max;
static int __init setup_relax_domain_level(char *str)
{
if (kstrtoint(str, 0, &default_relax_domain_level))
pr_warn("Unable to set relax_domain_level\n");
return 1;
}
__setup("relax_domain_level=", setup_relax_domain_level);
static void set_domain_attribute(struct sched_domain *sd,
struct sched_domain_attr *attr)
{
int request;
if (!attr || attr->relax_domain_level < 0) {
if (default_relax_domain_level < 0)
return;
else
request = default_relax_domain_level;
} else
request = attr->relax_domain_level;
if (request < sd->level) {
/* turn off idle balance on this domain */
sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
} else {
/* turn on idle balance on this domain */
sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
}
}
static void __sdt_free(const struct cpumask *cpu_map);
static int __sdt_alloc(const struct cpumask *cpu_map);
static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
const struct cpumask *cpu_map)
{
switch (what) {
case sa_rootdomain:
if (!atomic_read(&d->rd->refcount))
free_rootdomain(&d->rd->rcu); /* fall through */
case sa_sd:
free_percpu(d->sd); /* fall through */
case sa_sd_storage:
__sdt_free(cpu_map); /* fall through */
case sa_none:
break;
}
}
static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
const struct cpumask *cpu_map)
{
memset(d, 0, sizeof(*d));
if (__sdt_alloc(cpu_map))
return sa_sd_storage;
d->sd = alloc_percpu(struct sched_domain *);
if (!d->sd)
return sa_sd_storage;
d->rd = alloc_rootdomain();
if (!d->rd)
return sa_sd;
return sa_rootdomain;
}
/*
* NULL the sd_data elements we've used to build the sched_domain and
* sched_group structure so that the subsequent __free_domain_allocs()
* will not free the data we're using.
*/
static void claim_allocations(int cpu, struct sched_domain *sd)
{
struct sd_data *sdd = sd->private;
WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
*per_cpu_ptr(sdd->sd, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
*per_cpu_ptr(sdd->sg, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
*per_cpu_ptr(sdd->sgp, cpu) = NULL;
}
#ifdef CONFIG_SCHED_SMT
static const struct cpumask *cpu_smt_mask(int cpu)
{
return topology_thread_cpumask(cpu);
}
#endif
/*
* Topology list, bottom-up.
*/
static struct sched_domain_topology_level default_topology[] = {
#ifdef CONFIG_SCHED_SMT
{ sd_init_SIBLING, cpu_smt_mask, },
#endif
#ifdef CONFIG_SCHED_MC
{ sd_init_MC, cpu_coregroup_mask, },
#endif
#ifdef CONFIG_SCHED_BOOK
{ sd_init_BOOK, cpu_book_mask, },
#endif
{ sd_init_CPU, cpu_cpu_mask, },
{ NULL, },
};
static struct sched_domain_topology_level *sched_domain_topology = default_topology;
#define for_each_sd_topology(tl) \
for (tl = sched_domain_topology; tl->init; tl++)
#ifdef CONFIG_NUMA
static int sched_domains_numa_levels;
static int *sched_domains_numa_distance;
static struct cpumask ***sched_domains_numa_masks;
static int sched_domains_curr_level;
static inline int sd_local_flags(int level)
{
if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE)
return 0;
return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE;
}
static struct sched_domain *
sd_numa_init(struct sched_domain_topology_level *tl, int cpu)
{
struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
int level = tl->numa_level;
int sd_weight = cpumask_weight(
sched_domains_numa_masks[level][cpu_to_node(cpu)]);
*sd = (struct sched_domain){
.min_interval = sd_weight,
.max_interval = 2*sd_weight,
.busy_factor = 32,
.imbalance_pct = 125,
.cache_nice_tries = 2,
.busy_idx = 3,
.idle_idx = 2,
.newidle_idx = 0,
.wake_idx = 0,
.forkexec_idx = 0,
.flags = 1*SD_LOAD_BALANCE
| 1*SD_BALANCE_NEWIDLE
| 0*SD_BALANCE_EXEC
| 0*SD_BALANCE_FORK
| 0*SD_BALANCE_WAKE
| 0*SD_WAKE_AFFINE
| 0*SD_SHARE_CPUPOWER
| 0*SD_SHARE_PKG_RESOURCES
| 1*SD_SERIALIZE
| 0*SD_PREFER_SIBLING
| 1*SD_NUMA
| sd_local_flags(level)
,
.last_balance = jiffies,
.balance_interval = sd_weight,
};
SD_INIT_NAME(sd, NUMA);
sd->private = &tl->data;
/*
* Ugly hack to pass state to sd_numa_mask()...
*/
sched_domains_curr_level = tl->numa_level;
return sd;
}
static const struct cpumask *sd_numa_mask(int cpu)
{
return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
}
static void sched_numa_warn(const char *str)
{
static int done = false;
int i,j;
if (done)
return;
done = true;
printk(KERN_WARNING "ERROR: %s\n\n", str);
for (i = 0; i < nr_node_ids; i++) {
printk(KERN_WARNING " ");
for (j = 0; j < nr_node_ids; j++)
printk(KERN_CONT "%02d ", node_distance(i,j));
printk(KERN_CONT "\n");
}
printk(KERN_WARNING "\n");
}
static bool find_numa_distance(int distance)
{
int i;
if (distance == node_distance(0, 0))
return true;
for (i = 0; i < sched_domains_numa_levels; i++) {
if (sched_domains_numa_distance[i] == distance)
return true;
}
return false;
}
static void sched_init_numa(void)
{
int next_distance, curr_distance = node_distance(0, 0);
struct sched_domain_topology_level *tl;
int level = 0;
int i, j, k;
sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
if (!sched_domains_numa_distance)
return;
/*
* O(nr_nodes^2) deduplicating selection sort -- in order to find the
* unique distances in the node_distance() table.
*
* Assumes node_distance(0,j) includes all distances in
* node_distance(i,j) in order to avoid cubic time.
*/
next_distance = curr_distance;
for (i = 0; i < nr_node_ids; i++) {
for (j = 0; j < nr_node_ids; j++) {
for (k = 0; k < nr_node_ids; k++) {
int distance = node_distance(i, k);
if (distance > curr_distance &&
(distance < next_distance ||
next_distance == curr_distance))
next_distance = distance;
/*
* While not a strong assumption it would be nice to know
* about cases where if node A is connected to B, B is not
* equally connected to A.
*/
if (sched_debug() && node_distance(k, i) != distance)
sched_numa_warn("Node-distance not symmetric");
if (sched_debug() && i && !find_numa_distance(distance))
sched_numa_warn("Node-0 not representative");
}
if (next_distance != curr_distance) {
sched_domains_numa_distance[level++] = next_distance;
sched_domains_numa_levels = level;
curr_distance = next_distance;
} else break;
}
/*
* In case of sched_debug() we verify the above assumption.
*/
if (!sched_debug())
break;
}
/*
* 'level' contains the number of unique distances, excluding the
* identity distance node_distance(i,i).
*
* The sched_domains_numa_distance[] array includes the actual distance
* numbers.
*/
/*
* Here, we should temporarily reset sched_domains_numa_levels to 0.
* If it fails to allocate memory for array sched_domains_numa_masks[][],
* the array will contain less then 'level' members. This could be
* dangerous when we use it to iterate array sched_domains_numa_masks[][]
* in other functions.
*
* We reset it to 'level' at the end of this function.
*/
sched_domains_numa_levels = 0;
sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
if (!sched_domains_numa_masks)
return;
/*
* Now for each level, construct a mask per node which contains all
* cpus of nodes that are that many hops away from us.
*/
for (i = 0; i < level; i++) {
sched_domains_numa_masks[i] =
kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
if (!sched_domains_numa_masks[i])
return;
for (j = 0; j < nr_node_ids; j++) {
struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
if (!mask)
return;
sched_domains_numa_masks[i][j] = mask;
for (k = 0; k < nr_node_ids; k++) {
if (node_distance(j, k) > sched_domains_numa_distance[i])
continue;
cpumask_or(mask, mask, cpumask_of_node(k));
}
}
}
tl = kzalloc((ARRAY_SIZE(default_topology) + level) *
sizeof(struct sched_domain_topology_level), GFP_KERNEL);
if (!tl)
return;
/*
* Copy the default topology bits..
*/
for (i = 0; default_topology[i].init; i++)
tl[i] = default_topology[i];
/*
* .. and append 'j' levels of NUMA goodness.
*/
for (j = 0; j < level; i++, j++) {
tl[i] = (struct sched_domain_topology_level){
.init = sd_numa_init,
.mask = sd_numa_mask,
.flags = SDTL_OVERLAP,
.numa_level = j,
};
}
sched_domain_topology = tl;
sched_domains_numa_levels = level;
}
static void sched_domains_numa_masks_set(int cpu)
{
int i, j;
int node = cpu_to_node(cpu);
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++) {
if (node_distance(j, node) <= sched_domains_numa_distance[i])
cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
}
static void sched_domains_numa_masks_clear(int cpu)
{
int i, j;
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++)
cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
/*
* Update sched_domains_numa_masks[level][node] array when new cpus
* are onlined.
*/
static int sched_domains_numa_masks_update(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
int cpu = (long)hcpu;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_ONLINE:
sched_domains_numa_masks_set(cpu);
break;
case CPU_DEAD:
sched_domains_numa_masks_clear(cpu);
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
#else
static inline void sched_init_numa(void)
{
}
static int sched_domains_numa_masks_update(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
return 0;
}
#endif /* CONFIG_NUMA */
static int __sdt_alloc(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
sdd->sd = alloc_percpu(struct sched_domain *);
if (!sdd->sd)
return -ENOMEM;
sdd->sg = alloc_percpu(struct sched_group *);
if (!sdd->sg)
return -ENOMEM;
sdd->sgp = alloc_percpu(struct sched_group_power *);
if (!sdd->sgp)
return -ENOMEM;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
struct sched_group *sg;
struct sched_group_power *sgp;
sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sd)
return -ENOMEM;
*per_cpu_ptr(sdd->sd, j) = sd;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sg)
return -ENOMEM;
sg->next = sg;
*per_cpu_ptr(sdd->sg, j) = sg;
sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sgp)
return -ENOMEM;
*per_cpu_ptr(sdd->sgp, j) = sgp;
}
}
return 0;
}
static void __sdt_free(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
if (sdd->sd) {
sd = *per_cpu_ptr(sdd->sd, j);
if (sd && (sd->flags & SD_OVERLAP))
free_sched_groups(sd->groups, 0);
kfree(*per_cpu_ptr(sdd->sd, j));
}
if (sdd->sg)
kfree(*per_cpu_ptr(sdd->sg, j));
if (sdd->sgp)
kfree(*per_cpu_ptr(sdd->sgp, j));
}
free_percpu(sdd->sd);
sdd->sd = NULL;
free_percpu(sdd->sg);
sdd->sg = NULL;
free_percpu(sdd->sgp);
sdd->sgp = NULL;
}
}
struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
const struct cpumask *cpu_map, struct sched_domain_attr *attr,
struct sched_domain *child, int cpu)
{
struct sched_domain *sd = tl->init(tl, cpu);
if (!sd)
return child;
cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
if (child) {
sd->level = child->level + 1;
sched_domain_level_max = max(sched_domain_level_max, sd->level);
child->parent = sd;
sd->child = child;
}
set_domain_attribute(sd, attr);
return sd;
}
/*
* Build sched domains for a given set of cpus and attach the sched domains
* to the individual cpus
*/
static int build_sched_domains(const struct cpumask *cpu_map,
struct sched_domain_attr *attr)
{
enum s_alloc alloc_state;
struct sched_domain *sd;
struct s_data d;
int i, ret = -ENOMEM;
alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
if (alloc_state != sa_rootdomain)
goto error;
/* Set up domains for cpus specified by the cpu_map. */
for_each_cpu(i, cpu_map) {
struct sched_domain_topology_level *tl;
sd = NULL;
for_each_sd_topology(tl) {
sd = build_sched_domain(tl, cpu_map, attr, sd, i);
if (tl == sched_domain_topology)
*per_cpu_ptr(d.sd, i) = sd;
if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
sd->flags |= SD_OVERLAP;
if (cpumask_equal(cpu_map, sched_domain_span(sd)))
break;
}
}
/* Build the groups for the domains */
for_each_cpu(i, cpu_map) {
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
sd->span_weight = cpumask_weight(sched_domain_span(sd));
if (sd->flags & SD_OVERLAP) {
if (build_overlap_sched_groups(sd, i))
goto error;
} else {
if (build_sched_groups(sd, i))
goto error;
}
}
}
/* Calculate CPU power for physical packages and nodes */
for (i = nr_cpumask_bits-1; i >= 0; i--) {
if (!cpumask_test_cpu(i, cpu_map))
continue;
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
claim_allocations(i, sd);
init_sched_groups_power(i, sd);
}
}
/* Attach the domains */
rcu_read_lock();
for_each_cpu(i, cpu_map) {
sd = *per_cpu_ptr(d.sd, i);
cpu_attach_domain(sd, d.rd, i);
}
rcu_read_unlock();
ret = 0;
error:
__free_domain_allocs(&d, alloc_state, cpu_map);
return ret;
}
static cpumask_var_t *doms_cur; /* current sched domains */
static int ndoms_cur; /* number of sched domains in 'doms_cur' */
static struct sched_domain_attr *dattr_cur;
/* attribues of custom domains in 'doms_cur' */
/*
* Special case: If a kmalloc of a doms_cur partition (array of
* cpumask) fails, then fallback to a single sched domain,
* as determined by the single cpumask fallback_doms.
*/
static cpumask_var_t fallback_doms;
/*
* arch_update_cpu_topology lets virtualized architectures update the
* cpu core maps. It is supposed to return 1 if the topology changed
* or 0 if it stayed the same.
*/
int __attribute__((weak)) arch_update_cpu_topology(void)
{
return 0;
}
cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
{
int i;
cpumask_var_t *doms;
doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
if (!doms)
return NULL;
for (i = 0; i < ndoms; i++) {
if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
free_sched_domains(doms, i);
return NULL;
}
}
return doms;
}
void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
{
unsigned int i;
for (i = 0; i < ndoms; i++)
free_cpumask_var(doms[i]);
kfree(doms);
}
/*
* Set up scheduler domains and groups. Callers must hold the hotplug lock.
* For now this just excludes isolated cpus, but could be used to
* exclude other special cases in the future.
*/
static int init_sched_domains(const struct cpumask *cpu_map)
{
int err;
arch_update_cpu_topology();
ndoms_cur = 1;
doms_cur = alloc_sched_domains(ndoms_cur);
if (!doms_cur)
doms_cur = &fallback_doms;
cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
err = build_sched_domains(doms_cur[0], NULL);
register_sched_domain_sysctl();
return err;
}
/*
* Detach sched domains from a group of cpus specified in cpu_map
* These cpus will now be attached to the NULL domain
*/
static void detach_destroy_domains(const struct cpumask *cpu_map)
{
int i;
rcu_read_lock();
for_each_cpu(i, cpu_map)
cpu_attach_domain(NULL, &def_root_domain, i);
rcu_read_unlock();
}
/* handle null as "default" */
static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
struct sched_domain_attr *new, int idx_new)
{
struct sched_domain_attr tmp;
/* fast path */
if (!new && !cur)
return 1;
tmp = SD_ATTR_INIT;
return !memcmp(cur ? (cur + idx_cur) : &tmp,
new ? (new + idx_new) : &tmp,
sizeof(struct sched_domain_attr));
}
/*
* Partition sched domains as specified by the 'ndoms_new'
* cpumasks in the array doms_new[] of cpumasks. This compares
* doms_new[] to the current sched domain partitioning, doms_cur[].
* It destroys each deleted domain and builds each new domain.
*
* 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
* The masks don't intersect (don't overlap.) We should setup one
* sched domain for each mask. CPUs not in any of the cpumasks will
* not be load balanced. If the same cpumask appears both in the
* current 'doms_cur' domains and in the new 'doms_new', we can leave
* it as it is.
*
* The passed in 'doms_new' should be allocated using
* alloc_sched_domains. This routine takes ownership of it and will
* free_sched_domains it when done with it. If the caller failed the
* alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
* and partition_sched_domains() will fallback to the single partition
* 'fallback_doms', it also forces the domains to be rebuilt.
*
* If doms_new == NULL it will be replaced with cpu_online_mask.
* ndoms_new == 0 is a special case for destroying existing domains,
* and it will not create the default domain.
*
* Call with hotplug lock held
*/
void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new)
{
int i, j, n;
int new_topology;
mutex_lock(&sched_domains_mutex);
/* always unregister in case we don't destroy any domains */
unregister_sched_domain_sysctl();
/* Let architecture update cpu core mappings. */
new_topology = arch_update_cpu_topology();
n = doms_new ? ndoms_new : 0;
/* Destroy deleted domains */
for (i = 0; i < ndoms_cur; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_cur[i], doms_new[j])
&& dattrs_equal(dattr_cur, i, dattr_new, j))
goto match1;
}
/* no match - a current sched domain not in new doms_new[] */
detach_destroy_domains(doms_cur[i]);
match1:
;
}
n = ndoms_cur;
if (doms_new == NULL) {
n = 0;
doms_new = &fallback_doms;
cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
WARN_ON_ONCE(dattr_new);
}
/* Build new domains */
for (i = 0; i < ndoms_new; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_new[i], doms_cur[j])
&& dattrs_equal(dattr_new, i, dattr_cur, j))
goto match2;
}
/* no match - add a new doms_new */
build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
match2:
;
}
/* Remember the new sched domains */
if (doms_cur != &fallback_doms)
free_sched_domains(doms_cur, ndoms_cur);
kfree(dattr_cur); /* kfree(NULL) is safe */
doms_cur = doms_new;
dattr_cur = dattr_new;
ndoms_cur = ndoms_new;
register_sched_domain_sysctl();
mutex_unlock(&sched_domains_mutex);
}
static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
/*
* Update cpusets according to cpu_active mask. If cpusets are
* disabled, cpuset_update_active_cpus() becomes a simple wrapper
* around partition_sched_domains().
*
* If we come here as part of a suspend/resume, don't touch cpusets because we
* want to restore it back to its original state upon resume anyway.
*/
static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
switch (action) {
case CPU_ONLINE_FROZEN:
case CPU_DOWN_FAILED_FROZEN:
/*
* num_cpus_frozen tracks how many CPUs are involved in suspend
* resume sequence. As long as this is not the last online
* operation in the resume sequence, just build a single sched
* domain, ignoring cpusets.
*/
num_cpus_frozen--;
if (likely(num_cpus_frozen)) {
partition_sched_domains(1, NULL, NULL);
break;
}
/*
* This is the last CPU online operation. So fall through and
* restore the original sched domains by considering the
* cpuset configurations.
*/
case CPU_ONLINE:
case CPU_DOWN_FAILED:
cpuset_update_active_cpus(true);
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
switch (action) {
case CPU_DOWN_PREPARE:
cpuset_update_active_cpus(false);
break;
case CPU_DOWN_PREPARE_FROZEN:
num_cpus_frozen++;
partition_sched_domains(1, NULL, NULL);
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
void __init sched_init_smp(void)
{
cpumask_var_t non_isolated_cpus;
alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
sched_init_numa();
/*
* There's no userspace yet to cause hotplug operations; hence all the
* cpu masks are stable and all blatant races in the below code cannot
* happen.
*/
mutex_lock(&sched_domains_mutex);
init_sched_domains(cpu_active_mask);
cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
if (cpumask_empty(non_isolated_cpus))
cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
mutex_unlock(&sched_domains_mutex);
hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
init_hrtick();
/* Move init over to a non-isolated CPU */
if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
BUG();
sched_init_granularity();
free_cpumask_var(non_isolated_cpus);
init_sched_rt_class();
init_sched_dl_class();
}
#else
void __init sched_init_smp(void)
{
sched_init_granularity();
}
#endif /* CONFIG_SMP */
const_debug unsigned int sysctl_timer_migration = 1;
int in_sched_functions(unsigned long addr)
{
return in_lock_functions(addr) ||
(addr >= (unsigned long)__sched_text_start
&& addr < (unsigned long)__sched_text_end);
}
#ifdef CONFIG_CGROUP_SCHED
/*
* Default task group.
* Every task in system belongs to this group at bootup.
*/
struct task_group root_task_group;
LIST_HEAD(task_groups);
#endif
DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
void __init sched_init(void)
{
int i, j;
unsigned long alloc_size = 0, ptr;
#ifdef CONFIG_FAIR_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_RT_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_CPUMASK_OFFSTACK
alloc_size += num_possible_cpus() * cpumask_size();
#endif
if (alloc_size) {
ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.se = (struct sched_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.cfs_rq = (struct cfs_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
root_task_group.rt_se = (struct sched_rt_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.rt_rq = (struct rt_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CPUMASK_OFFSTACK
for_each_possible_cpu(i) {
per_cpu(load_balance_mask, i) = (void *)ptr;
ptr += cpumask_size();
}
#endif /* CONFIG_CPUMASK_OFFSTACK */
}
init_rt_bandwidth(&def_rt_bandwidth,
global_rt_period(), global_rt_runtime());
init_dl_bandwidth(&def_dl_bandwidth,
global_rt_period(), global_rt_runtime());
#ifdef CONFIG_SMP
init_defrootdomain();
#endif
#ifdef CONFIG_RT_GROUP_SCHED
init_rt_bandwidth(&root_task_group.rt_bandwidth,
global_rt_period(), global_rt_runtime());
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CGROUP_SCHED
list_add(&root_task_group.list, &task_groups);
INIT_LIST_HEAD(&root_task_group.children);
INIT_LIST_HEAD(&root_task_group.siblings);
autogroup_init(&init_task);
#endif /* CONFIG_CGROUP_SCHED */
for_each_possible_cpu(i) {
struct rq *rq;
rq = cpu_rq(i);
raw_spin_lock_init(&rq->lock);
rq->nr_running = 0;
rq->calc_load_active = 0;
rq->calc_load_update = jiffies + LOAD_FREQ;
init_cfs_rq(&rq->cfs);
init_rt_rq(&rq->rt, rq);
init_dl_rq(&rq->dl, rq);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.shares = ROOT_TASK_GROUP_LOAD;
INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
/*
* How much cpu bandwidth does root_task_group get?
*
* In case of task-groups formed thr' the cgroup filesystem, it
* gets 100% of the cpu resources in the system. This overall
* system cpu resource is divided among the tasks of
* root_task_group and its child task-groups in a fair manner,
* based on each entity's (task or task-group's) weight
* (se->load.weight).
*
* In other words, if root_task_group has 10 tasks of weight
* 1024) and two child groups A0 and A1 (of weight 1024 each),
* then A0's share of the cpu resource is:
*
* A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
*
* We achieve this by letting root_task_group's tasks sit
* directly in rq->cfs (i.e root_task_group->se[] = NULL).
*/
init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
#endif /* CONFIG_FAIR_GROUP_SCHED */
rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
#ifdef CONFIG_RT_GROUP_SCHED
INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
#endif
for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
rq->cpu_load[j] = 0;
rq->last_load_update_tick = jiffies;
#ifdef CONFIG_SMP
rq->sd = NULL;
rq->rd = NULL;
rq->cpu_power = SCHED_POWER_SCALE;
rq->post_schedule = 0;
rq->active_balance = 0;
rq->next_balance = jiffies;
rq->push_cpu = 0;
rq->cpu = i;
rq->online = 0;
rq->idle_stamp = 0;
rq->avg_idle = 2*sysctl_sched_migration_cost;
rq->max_idle_balance_cost = sysctl_sched_migration_cost;
INIT_LIST_HEAD(&rq->cfs_tasks);
rq_attach_root(rq, &def_root_domain);
#ifdef CONFIG_NO_HZ_COMMON
rq->nohz_flags = 0;
#endif
#ifdef CONFIG_NO_HZ_FULL
rq->last_sched_tick = 0;
#endif
#endif
init_rq_hrtick(rq);
atomic_set(&rq->nr_iowait, 0);
}
set_load_weight(&init_task);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&init_task.preempt_notifiers);
#endif
/*
* The boot idle thread does lazy MMU switching as well:
*/
atomic_inc(&init_mm.mm_count);
enter_lazy_tlb(&init_mm, current);
/*
* Make us the idle thread. Technically, schedule() should not be
* called from this thread, however somewhere below it might be,
* but because we are the idle thread, we just pick up running again
* when this runqueue becomes "idle".
*/
init_idle(current, smp_processor_id());
calc_load_update = jiffies + LOAD_FREQ;
/*
* During early bootup we pretend to be a normal task:
*/
current->sched_class = &fair_sched_class;
#ifdef CONFIG_SMP
zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
/* May be allocated at isolcpus cmdline parse time */
if (cpu_isolated_map == NULL)
zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
idle_thread_set_boot_cpu();
#endif
init_sched_fair_class();
scheduler_running = 1;
}
#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
static inline int preempt_count_equals(int preempt_offset)
{
int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
return (nested == preempt_offset);
}
void __might_sleep(const char *file, int line, int preempt_offset)
{
static unsigned long prev_jiffy; /* ratelimiting */
rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
system_state != SYSTEM_RUNNING || oops_in_progress)
return;
if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
return;
prev_jiffy = jiffies;
printk(KERN_ERR
"BUG: sleeping function called from invalid context at %s:%d\n",
file, line);
printk(KERN_ERR
"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
in_atomic(), irqs_disabled(),
current->pid, current->comm);
debug_show_held_locks(current);
if (irqs_disabled())
print_irqtrace_events(current);
dump_stack();
}
EXPORT_SYMBOL(__might_sleep);
#endif
#ifdef CONFIG_MAGIC_SYSRQ
static void normalize_task(struct rq *rq, struct task_struct *p)
{
const struct sched_class *prev_class = p->sched_class;
struct sched_attr attr = {
.sched_policy = SCHED_NORMAL,
};
int old_prio = p->prio;
int on_rq;
on_rq = p->on_rq;
if (on_rq)
dequeue_task(rq, p, 0);
__setscheduler(rq, p, &attr);
if (on_rq) {
enqueue_task(rq, p, 0);
resched_task(rq->curr);
}
check_class_changed(rq, p, prev_class, old_prio);
}
void normalize_rt_tasks(void)
{
struct task_struct *g, *p;
unsigned long flags;
struct rq *rq;
read_lock_irqsave(&tasklist_lock, flags);
do_each_thread(g, p) {
/*
* Only normalize user tasks:
*/
if (!p->mm)
continue;
p->se.exec_start = 0;
#ifdef CONFIG_SCHEDSTATS
p->se.statistics.wait_start = 0;
p->se.statistics.sleep_start = 0;
p->se.statistics.block_start = 0;
#endif
if (!dl_task(p) && !rt_task(p)) {
/*
* Renice negative nice level userspace
* tasks back to 0:
*/
if (TASK_NICE(p) < 0 && p->mm)
set_user_nice(p, 0);
continue;
}
raw_spin_lock(&p->pi_lock);
rq = __task_rq_lock(p);
normalize_task(rq, p);
__task_rq_unlock(rq);
raw_spin_unlock(&p->pi_lock);
} while_each_thread(g, p);
read_unlock_irqrestore(&tasklist_lock, flags);
}
#endif /* CONFIG_MAGIC_SYSRQ */
#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
/*
* These functions are only useful for the IA64 MCA handling, or kdb.
*
* They can only be called when the whole system has been
* stopped - every CPU needs to be quiescent, and no scheduling
* activity can take place. Using them for anything else would
* be a serious bug, and as a result, they aren't even visible
* under any other configuration.
*/
/**
* curr_task - return the current task for a given cpu.
* @cpu: the processor in question.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*
* Return: The current task for @cpu.
*/
struct task_struct *curr_task(int cpu)
{
return cpu_curr(cpu);
}
#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
#ifdef CONFIG_IA64
/**
* set_curr_task - set the current task for a given cpu.
* @cpu: the processor in question.
* @p: the task pointer to set.
*
* Description: This function must only be used when non-maskable interrupts
* are serviced on a separate stack. It allows the architecture to switch the
* notion of the current task on a cpu in a non-blocking manner. This function
* must be called with all CPU's synchronized, and interrupts disabled, the
* and caller must save the original value of the current task (see
* curr_task() above) and restore that value before reenabling interrupts and
* re-starting the system.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*/
void set_curr_task(int cpu, struct task_struct *p)
{
cpu_curr(cpu) = p;
}
#endif
#ifdef CONFIG_CGROUP_SCHED
/* task_group_lock serializes the addition/removal of task groups */
static DEFINE_SPINLOCK(task_group_lock);
static void free_sched_group(struct task_group *tg)
{
free_fair_sched_group(tg);
free_rt_sched_group(tg);
autogroup_free(tg);
kfree(tg);
}
/* allocate runqueue etc for a new task group */
struct task_group *sched_create_group(struct task_group *parent)
{
struct task_group *tg;
tg = kzalloc(sizeof(*tg), GFP_KERNEL);
if (!tg)
return ERR_PTR(-ENOMEM);
if (!alloc_fair_sched_group(tg, parent))
goto err;
if (!alloc_rt_sched_group(tg, parent))
goto err;
return tg;
err:
free_sched_group(tg);
return ERR_PTR(-ENOMEM);
}
void sched_online_group(struct task_group *tg, struct task_group *parent)
{
unsigned long flags;
spin_lock_irqsave(&task_group_lock, flags);
list_add_rcu(&tg->list, &task_groups);
WARN_ON(!parent); /* root should already exist */
tg->parent = parent;
INIT_LIST_HEAD(&tg->children);
list_add_rcu(&tg->siblings, &parent->children);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* rcu callback to free various structures associated with a task group */
static void free_sched_group_rcu(struct rcu_head *rhp)
{
/* now it should be safe to free those cfs_rqs */
free_sched_group(container_of(rhp, struct task_group, rcu));
}
/* Destroy runqueue etc associated with a task group */
void sched_destroy_group(struct task_group *tg)
{
/* wait for possible concurrent references to cfs_rqs complete */
call_rcu(&tg->rcu, free_sched_group_rcu);
}
void sched_offline_group(struct task_group *tg)
{
unsigned long flags;
int i;
/* end participation in shares distribution */
for_each_possible_cpu(i)
unregister_fair_sched_group(tg, i);
spin_lock_irqsave(&task_group_lock, flags);
list_del_rcu(&tg->list);
list_del_rcu(&tg->siblings);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* change task's runqueue when it moves between groups.
* The caller of this function should have put the task in its new group
* by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
* reflect its new group.
*/
void sched_move_task(struct task_struct *tsk)
{
struct task_group *tg;
int on_rq, running;
unsigned long flags;
struct rq *rq;
rq = task_rq_lock(tsk, &flags);
running = task_current(rq, tsk);
on_rq = tsk->on_rq;
if (on_rq)
dequeue_task(rq, tsk, 0);
if (unlikely(running))
tsk->sched_class->put_prev_task(rq, tsk);
tg = container_of(task_css_check(tsk, cpu_cgroup_subsys_id,
lockdep_is_held(&tsk->sighand->siglock)),
struct task_group, css);
tg = autogroup_task_group(tsk, tg);
tsk->sched_task_group = tg;
#ifdef CONFIG_FAIR_GROUP_SCHED
if (tsk->sched_class->task_move_group)
tsk->sched_class->task_move_group(tsk, on_rq);
else
#endif
set_task_rq(tsk, task_cpu(tsk));
if (unlikely(running))
tsk->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, tsk, 0);
task_rq_unlock(rq, tsk, &flags);
}
#endif /* CONFIG_CGROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Ensure that the real time constraints are schedulable.
*/
static DEFINE_MUTEX(rt_constraints_mutex);
/* Must be called with tasklist_lock held */
static inline int tg_has_rt_tasks(struct task_group *tg)
{
struct task_struct *g, *p;
do_each_thread(g, p) {
if (rt_task(p) && task_rq(p)->rt.tg == tg)
return 1;
} while_each_thread(g, p);
return 0;
}
struct rt_schedulable_data {
struct task_group *tg;
u64 rt_period;
u64 rt_runtime;
};
static int tg_rt_schedulable(struct task_group *tg, void *data)
{
struct rt_schedulable_data *d = data;
struct task_group *child;
unsigned long total, sum = 0;
u64 period, runtime;
period = ktime_to_ns(tg->rt_bandwidth.rt_period);
runtime = tg->rt_bandwidth.rt_runtime;
if (tg == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
/*
* Cannot have more runtime than the period.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
/*
* Ensure we don't starve existing RT tasks.
*/
if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
return -EBUSY;
total = to_ratio(period, runtime);
/*
* Nobody can have more than the global setting allows.
*/
if (total > to_ratio(global_rt_period(), global_rt_runtime()))
return -EINVAL;
/*
* The sum of our children's runtime should not exceed our own.
*/
list_for_each_entry_rcu(child, &tg->children, siblings) {
period = ktime_to_ns(child->rt_bandwidth.rt_period);
runtime = child->rt_bandwidth.rt_runtime;
if (child == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
sum += to_ratio(period, runtime);
}
if (sum > total)
return -EINVAL;
return 0;
}
static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
{
int ret;
struct rt_schedulable_data data = {
.tg = tg,
.rt_period = period,
.rt_runtime = runtime,
};
rcu_read_lock();
ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int tg_set_rt_bandwidth(struct task_group *tg,
u64 rt_period, u64 rt_runtime)
{
int i, err = 0;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
err = __rt_schedulable(tg, rt_period, rt_runtime);
if (err)
goto unlock;
raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
tg->rt_bandwidth.rt_runtime = rt_runtime;
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = tg->rt_rq[i];
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_runtime;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
unlock:
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return err;
}
static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_runtime(struct task_group *tg)
{
u64 rt_runtime_us;
if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
return -1;
rt_runtime_us = tg->rt_bandwidth.rt_runtime;
do_div(rt_runtime_us, NSEC_PER_USEC);
return rt_runtime_us;
}
static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
{
u64 rt_runtime, rt_period;
rt_period = (u64)rt_period_us * NSEC_PER_USEC;
rt_runtime = tg->rt_bandwidth.rt_runtime;
if (rt_period == 0)
return -EINVAL;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_period(struct task_group *tg)
{
u64 rt_period_us;
rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
do_div(rt_period_us, NSEC_PER_USEC);
return rt_period_us;
}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int sched_rt_global_constraints(void)
{
int ret = 0;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
ret = __rt_schedulable(NULL, 0, 0);
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return ret;
}
static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
{
/* Don't accept realtime tasks when there is no way for them to run */
if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
return 0;
return 1;
}
#else /* !CONFIG_RT_GROUP_SCHED */
static int sched_rt_global_constraints(void)
{
unsigned long flags;
int i, ret = 0;
raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = &cpu_rq(i)->rt;
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = global_rt_runtime();
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
return ret;
}
#endif /* CONFIG_RT_GROUP_SCHED */
static int sched_dl_global_constraints(void)
{
u64 runtime = global_rt_runtime();
u64 period = global_rt_period();
u64 new_bw = to_ratio(period, runtime);
int cpu, ret = 0;
unsigned long flags;
/*
* Here we want to check the bandwidth not being set to some
* value smaller than the currently allocated bandwidth in
* any of the root_domains.
*
* FIXME: Cycling on all the CPUs is overdoing, but simpler than
* cycling on root_domains... Discussion on different/better
* solutions is welcome!
*/
for_each_possible_cpu(cpu) {
struct dl_bw *dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
if (new_bw < dl_b->total_bw)
ret = -EBUSY;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
if (ret)
break;
}
return ret;
}
static void sched_dl_do_global(void)
{
u64 new_bw = -1;
int cpu;
unsigned long flags;
def_dl_bandwidth.dl_period = global_rt_period();
def_dl_bandwidth.dl_runtime = global_rt_runtime();
if (global_rt_runtime() != RUNTIME_INF)
new_bw = to_ratio(global_rt_period(), global_rt_runtime());
/*
* FIXME: As above...
*/
for_each_possible_cpu(cpu) {
struct dl_bw *dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
dl_b->bw = new_bw;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
}
}
static int sched_rt_global_validate(void)
{
if (sysctl_sched_rt_period <= 0)
return -EINVAL;
if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
(sysctl_sched_rt_runtime > sysctl_sched_rt_period))
return -EINVAL;
return 0;
}
static void sched_rt_do_global(void)
{
def_rt_bandwidth.rt_runtime = global_rt_runtime();
def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
}
int sched_rt_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int old_period, old_runtime;
static DEFINE_MUTEX(mutex);
int ret;
mutex_lock(&mutex);
old_period = sysctl_sched_rt_period;
old_runtime = sysctl_sched_rt_runtime;
ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (!ret && write) {
ret = sched_rt_global_validate();
if (ret)
goto undo;
ret = sched_rt_global_constraints();
if (ret)
goto undo;
ret = sched_dl_global_constraints();
if (ret)
goto undo;
sched_rt_do_global();
sched_dl_do_global();
}
if (0) {
undo:
sysctl_sched_rt_period = old_period;
sysctl_sched_rt_runtime = old_runtime;
}
mutex_unlock(&mutex);
return ret;
}
int sched_rr_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
static DEFINE_MUTEX(mutex);
mutex_lock(&mutex);
ret = proc_dointvec(table, write, buffer, lenp, ppos);
/* make sure that internally we keep jiffies */
/* also, writing zero resets timeslice to default */
if (!ret && write) {
sched_rr_timeslice = sched_rr_timeslice <= 0 ?
RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
}
mutex_unlock(&mutex);
return ret;
}
#ifdef CONFIG_CGROUP_SCHED
static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
{
return css ? container_of(css, struct task_group, css) : NULL;
}
static struct cgroup_subsys_state *
cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct task_group *parent = css_tg(parent_css);
struct task_group *tg;
if (!parent) {
/* This is early initialization for the top cgroup */
return &root_task_group.css;
}
tg = sched_create_group(parent);
if (IS_ERR(tg))
return ERR_PTR(-ENOMEM);
return &tg->css;
}
static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
struct task_group *parent = css_tg(css_parent(css));
if (parent)
sched_online_group(tg, parent);
return 0;
}
static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
sched_destroy_group(tg);
}
static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
sched_offline_group(tg);
}
static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
struct task_struct *task;
cgroup_taskset_for_each(task, css, tset) {
#ifdef CONFIG_RT_GROUP_SCHED
if (!sched_rt_can_attach(css_tg(css), task))
return -EINVAL;
#else
/* We don't support RT-tasks being in separate groups */
if (task->sched_class != &fair_sched_class)
return -EINVAL;
#endif
}
return 0;
}
static void cpu_cgroup_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
struct task_struct *task;
cgroup_taskset_for_each(task, css, tset)
sched_move_task(task);
}
static void cpu_cgroup_exit(struct cgroup_subsys_state *css,
struct cgroup_subsys_state *old_css,
struct task_struct *task)
{
/*
* cgroup_exit() is called in the copy_process() failure path.
* Ignore this case since the task hasn't ran yet, this avoids
* trying to poke a half freed task state from generic code.
*/
if (!(task->flags & PF_EXITING))
return;
sched_move_task(task);
}
#ifdef CONFIG_FAIR_GROUP_SCHED
static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 shareval)
{
return sched_group_set_shares(css_tg(css), scale_load(shareval));
}
static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
struct task_group *tg = css_tg(css);
return (u64) scale_load_down(tg->shares);
}
#ifdef CONFIG_CFS_BANDWIDTH
static DEFINE_MUTEX(cfs_constraints_mutex);
const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
{
int i, ret = 0, runtime_enabled, runtime_was_enabled;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
if (tg == &root_task_group)
return -EINVAL;
/*
* Ensure we have at some amount of bandwidth every period. This is
* to prevent reaching a state of large arrears when throttled via
* entity_tick() resulting in prolonged exit starvation.
*/
if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
return -EINVAL;
/*
* Likewise, bound things on the otherside by preventing insane quota
* periods. This also allows us to normalize in computing quota
* feasibility.
*/
if (period > max_cfs_quota_period)
return -EINVAL;
mutex_lock(&cfs_constraints_mutex);
ret = __cfs_schedulable(tg, period, quota);
if (ret)
goto out_unlock;
runtime_enabled = quota != RUNTIME_INF;
runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
/*
* If we need to toggle cfs_bandwidth_used, off->on must occur
* before making related changes, and on->off must occur afterwards
*/
if (runtime_enabled && !runtime_was_enabled)
cfs_bandwidth_usage_inc();
raw_spin_lock_irq(&cfs_b->lock);
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
__refill_cfs_bandwidth_runtime(cfs_b);
/* restart the period timer (if active) to handle new period expiry */
if (runtime_enabled && cfs_b->timer_active) {
/* force a reprogram */
cfs_b->timer_active = 0;
__start_cfs_bandwidth(cfs_b);
}
raw_spin_unlock_irq(&cfs_b->lock);
for_each_possible_cpu(i) {
struct cfs_rq *cfs_rq = tg->cfs_rq[i];
struct rq *rq = cfs_rq->rq;
raw_spin_lock_irq(&rq->lock);
cfs_rq->runtime_enabled = runtime_enabled;
cfs_rq->runtime_remaining = 0;
if (cfs_rq->throttled)
unthrottle_cfs_rq(cfs_rq);
raw_spin_unlock_irq(&rq->lock);
}
if (runtime_was_enabled && !runtime_enabled)
cfs_bandwidth_usage_dec();
out_unlock:
mutex_unlock(&cfs_constraints_mutex);
return ret;
}
int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
{
u64 quota, period;
period = ktime_to_ns(tg->cfs_bandwidth.period);
if (cfs_quota_us < 0)
quota = RUNTIME_INF;
else
quota = (u64)cfs_quota_us * NSEC_PER_USEC;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_quota(struct task_group *tg)
{
u64 quota_us;
if (tg->cfs_bandwidth.quota == RUNTIME_INF)
return -1;
quota_us = tg->cfs_bandwidth.quota;
do_div(quota_us, NSEC_PER_USEC);
return quota_us;
}
int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
{
u64 quota, period;
period = (u64)cfs_period_us * NSEC_PER_USEC;
quota = tg->cfs_bandwidth.quota;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_period(struct task_group *tg)
{
u64 cfs_period_us;
cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
do_div(cfs_period_us, NSEC_PER_USEC);
return cfs_period_us;
}
static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_quota(css_tg(css));
}
static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
struct cftype *cftype, s64 cfs_quota_us)
{
return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
}
static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_period(css_tg(css));
}
static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 cfs_period_us)
{
return tg_set_cfs_period(css_tg(css), cfs_period_us);
}
struct cfs_schedulable_data {
struct task_group *tg;
u64 period, quota;
};
/*
* normalize group quota/period to be quota/max_period
* note: units are usecs
*/
static u64 normalize_cfs_quota(struct task_group *tg,
struct cfs_schedulable_data *d)
{
u64 quota, period;
if (tg == d->tg) {
period = d->period;
quota = d->quota;
} else {
period = tg_get_cfs_period(tg);
quota = tg_get_cfs_quota(tg);
}
/* note: these should typically be equivalent */
if (quota == RUNTIME_INF || quota == -1)
return RUNTIME_INF;
return to_ratio(period, quota);
}
static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
{
struct cfs_schedulable_data *d = data;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
s64 quota = 0, parent_quota = -1;
if (!tg->parent) {
quota = RUNTIME_INF;
} else {
struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
quota = normalize_cfs_quota(tg, d);
parent_quota = parent_b->hierarchal_quota;
/*
* ensure max(child_quota) <= parent_quota, inherit when no
* limit is set
*/
if (quota == RUNTIME_INF)
quota = parent_quota;
else if (parent_quota != RUNTIME_INF && quota > parent_quota)
return -EINVAL;
}
cfs_b->hierarchal_quota = quota;
return 0;
}
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
{
int ret;
struct cfs_schedulable_data data = {
.tg = tg,
.period = period,
.quota = quota,
};
if (quota != RUNTIME_INF) {
do_div(data.period, NSEC_PER_USEC);
do_div(data.quota, NSEC_PER_USEC);
}
rcu_read_lock();
ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int cpu_stats_show(struct seq_file *sf, void *v)
{
struct task_group *tg = css_tg(seq_css(sf));
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
return 0;
}
#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
struct cftype *cft, s64 val)
{
return sched_group_set_rt_runtime(css_tg(css), val);
}
static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_runtime(css_tg(css));
}
static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 rt_period_us)
{
return sched_group_set_rt_period(css_tg(css), rt_period_us);
}
static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_period(css_tg(css));
}
#endif /* CONFIG_RT_GROUP_SCHED */
static struct cftype cpu_files[] = {
#ifdef CONFIG_FAIR_GROUP_SCHED
{
.name = "shares",
.read_u64 = cpu_shares_read_u64,
.write_u64 = cpu_shares_write_u64,
},
#endif
#ifdef CONFIG_CFS_BANDWIDTH
{
.name = "cfs_quota_us",
.read_s64 = cpu_cfs_quota_read_s64,
.write_s64 = cpu_cfs_quota_write_s64,
},
{
.name = "cfs_period_us",
.read_u64 = cpu_cfs_period_read_u64,
.write_u64 = cpu_cfs_period_write_u64,
},
{
.name = "stat",
.seq_show = cpu_stats_show,
},
#endif
#ifdef CONFIG_RT_GROUP_SCHED
{
.name = "rt_runtime_us",
.read_s64 = cpu_rt_runtime_read,
.write_s64 = cpu_rt_runtime_write,
},
{
.name = "rt_period_us",
.read_u64 = cpu_rt_period_read_uint,
.write_u64 = cpu_rt_period_write_uint,
},
#endif
{ } /* terminate */
};
struct cgroup_subsys cpu_cgroup_subsys = {
.name = "cpu",
.css_alloc = cpu_cgroup_css_alloc,
.css_free = cpu_cgroup_css_free,
.css_online = cpu_cgroup_css_online,
.css_offline = cpu_cgroup_css_offline,
.can_attach = cpu_cgroup_can_attach,
.attach = cpu_cgroup_attach,
.exit = cpu_cgroup_exit,
.subsys_id = cpu_cgroup_subsys_id,
.base_cftypes = cpu_files,
.early_init = 1,
};
#endif /* CONFIG_CGROUP_SCHED */
void dump_cpu_task(int cpu)
{
pr_info("Task dump for CPU %d:\n", cpu);
sched_show_task(cpu_curr(cpu));
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2426_0 |
crossvul-cpp_data_good_432_0 | /* linux/drivers/cdrom/cdrom.c
Copyright (c) 1996, 1997 David A. van Leeuwen.
Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org>
Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk>
May be copied or modified under the terms of the GNU General Public
License. See linux/COPYING for more information.
Uniform CD-ROM driver for Linux.
See Documentation/cdrom/cdrom-standard.tex for usage information.
The routines in the file provide a uniform interface between the
software that uses CD-ROMs and the various low-level drivers that
actually talk to the hardware. Suggestions are welcome.
Patches that work are more welcome though. ;-)
To Do List:
----------------------------------
-- Modify sysctl/proc interface. I plan on having one directory per
drive, with entries for outputing general drive information, and sysctl
based tunable parameters such as whether the tray should auto-close for
that drive. Suggestions (or patches) for this welcome!
Revision History
----------------------------------
1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl>
-- Initial version by David A. van Leeuwen. I don't have a detailed
changelog for the 1.x series, David?
2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org>
-- New maintainer! As David A. van Leeuwen has been too busy to actively
maintain and improve this driver, I am now carrying on the torch. If
you have a problem with this driver, please feel free to contact me.
-- Added (rudimentary) sysctl interface. I realize this is really weak
right now, and is _very_ badly implemented. It will be improved...
-- Modified CDROM_DISC_STATUS so that it is now incorporated into
the Uniform CD-ROM driver via the cdrom_count_tracks function.
The cdrom_count_tracks function helps resolve some of the false
assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check
for the correct media type when mounting or playing audio from a CD.
-- Remove the calls to verify_area and only use the copy_from_user and
copy_to_user stuff, since these calls now provide their own memory
checking with the 2.1.x kernels.
-- Major update to return codes so that errors from low-level drivers
are passed on through (thanks to Gerd Knorr for pointing out this
problem).
-- Made it so if a function isn't implemented in a low-level driver,
ENOSYS is now returned instead of EINVAL.
-- Simplified some complex logic so that the source code is easier to read.
-- Other stuff I probably forgot to mention (lots of changes).
2.01 to 2.11 Dec 1997-Jan 1998
-- TO-DO! Write changelogs for 2.01 to 2.12.
2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that
copy_*_user does not return EFAULT on error, but instead returns the number
of bytes not copied. I was returning whatever non-zero stuff came back from
the copy_*_user functions directly, which would result in strange errors.
2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed
of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing
this out and providing a simple fix.
-- Fixed the procfs-unload-module bug with the fill_inode procfs callback.
thanks to Andrea Arcangeli
-- Fixed it so that the /proc entry now also shows up when cdrom is
compiled into the kernel. Before it only worked when loaded as a module.
2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in cdrom_media_changed and handling of reporting that
the media had changed for devices that _don't_ implement media_changed.
Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug.
-- Made a few things more pedanticly correct.
2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk>
-- New maintainers! Erik was too busy to continue the work on the driver,
so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk>
will do their best to follow in his footsteps
2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk>
-- Check if drive is capable of doing what we ask before blindly changing
cdi->options in various ioctl.
-- Added version to proc entry.
2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed an error in open_for_data where we would sometimes not return
the correct error value. Thanks Huba Gaspar <huba@softcell.hu>.
-- Fixed module usage count - usage was based on /proc/sys/dev
instead of /proc/sys/dev/cdrom. This could lead to an oops when other
modules had entries in dev. Feb 02 - real bug was in sysctl.c where
dev would be removed even though it was used. cdrom.c just illuminated
that bug.
2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk>
-- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has
been "rewritten" because capabilities and options aren't in sync. They
should be...
-- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way.
-- Added CDROM_RESET ioctl.
-- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly.
-- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs
from parsing /proc/sys/dev/cdrom/info.
2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk>
-- Check capability mask from low level driver when counting tracks as
per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>.
2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk>
-- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of
CDC_CLOSE_TRAY.
-- proc info didn't mask against capabilities mask.
3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk>
-- Unified audio ioctl handling across CD-ROM drivers. A lot of the
code was duplicated before. Drives that support the generic packet
interface are now being fed packets from here instead.
-- First attempt at adding support for MMC2 commands - for DVD and
CD-R(W) drives. Only the DVD parts are in now - the interface used is
the same as for the audio ioctls.
-- ioctl cleanups. if a drive couldn't play audio, it didn't get
a change to perform device specific ioctls as well.
-- Defined CDROM_CAN(CDC_XXX) for checking the capabilities.
-- Put in sysctl files for autoclose, autoeject, check_media, debug,
and lock.
-- /proc/sys/dev/cdrom/info has been updated to also contain info about
CD-Rx and DVD capabilities.
-- Now default to checking media type.
-- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for
doing this anyway, with the generic_packet addition.
3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk>
-- Fix up the sysctl handling so that the option flags get set
correctly.
-- Fix up ioctl handling so the device specific ones actually get
called :).
3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed volume control on SCSI drives (or others with longer audio
page).
-- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath
<andrewtv@usa.net> for telling me and for having defined the various
DVD structures and ioctls in the first place! He designed the original
DVD patches for ide-cd and while I rearranged and unified them, the
interface is still the same.
3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk>
-- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only
CDROMREADTOCENTRY and CDROMREADTOCHDR are left.
-- Moved the CDROMREADxxx ioctls in here.
-- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls
and exported functions.
-- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands
to now read GPCMD_ for the new generic packet interface. All low level
drivers are updated as well.
-- Various other cleanups.
3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed a couple of possible memory leaks (if an operation failed and
we didn't free the buffer before returning the error).
-- Integrated Uniform CD Changer handling from Richard Sharman
<rsharman@pobox.com>.
-- Defined CD_DVD and CD_CHANGER log levels.
-- Fixed the CDROMREADxxx ioctls.
-- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few
drives supported it. We lose the index part, however.
-- Small modifications to accommodate opens of /dev/hdc1, required
for ide-cd to handle multisession discs.
-- Export cdrom_mode_sense and cdrom_mode_select.
-- init_cdrom_command() for setting up a cgc command.
3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk>
-- Changed the interface for CDROM_SEND_PACKET. Before it was virtually
impossible to send the drive data in a sensible way.
-- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and
dvd_read_manufact.
-- Added setup of write mode for packet writing.
-- Fixed CDDA ripping with cdda2wav - accept much larger requests of
number of frames and split the reads in blocks of 8.
3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk>
-- Added support for changing the region of DVD drives.
-- Added sense data to generic command.
3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de>
-- Do same "read header length" trick in cdrom_get_disc_info() as
we do in cdrom_get_track_info() -- some drive don't obey specs and
fail if they can't supply the full Mt Fuji size table.
-- Deleted stuff related to setting up write modes. It has a different
home now.
-- Clear header length in mode_select unconditionally.
-- Removed the register_disk() that was added, not needed here.
3.08 May 1, 2000 - Jens Axboe <axboe@suse.de>
-- Fix direction flag in setup_send_key and setup_report_key. This
gave some SCSI adapters problems.
-- Always return -EROFS for write opens
-- Convert to module_init/module_exit style init and remove some
of the #ifdef MODULE stuff
-- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid,
DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and
dvd_do_auth passed uninitialized data to drive because init_cdrom_command
did not clear a 0 sized buffer.
3.09 May 12, 2000 - Jens Axboe <axboe@suse.de>
-- Fix Video-CD on SCSI drives that don't support READ_CD command. In
that case switch block size and issue plain READ_10 again, then switch
back.
3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de>
-- Fix volume control on CD's - old SCSI-II drives now use their own
code, as doing MODE6 stuff in here is really not my intention.
-- Use READ_DISC_INFO for more reliable end-of-disc.
3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de>
-- Fix bug in getting rpc phase 2 region info.
-- Reinstate "correct" CDROMPLAYTRKIND
3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de>
-- Use quiet bit on packet commands not known to work
3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de>
-- Various fixes and lots of cleanups not listed :-)
-- Locking fixes
-- Mt Rainier support
-- DVD-RAM write open fixes
Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov
<appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units.
Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW
2.4.x patch by Andy Polyakov <appro@fy.chalmers.se>
-------------------------------------------------------------------------*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define REVISION "Revision: 3.20"
#define VERSION "Id: cdrom.c 3.20 2003/12/17"
/* I use an error-log mask to give fine grain control over the type of
messages dumped to the system logs. The available masks include: */
#define CD_NOTHING 0x0
#define CD_WARNING 0x1
#define CD_REG_UNREG 0x2
#define CD_DO_IOCTL 0x4
#define CD_OPEN 0x8
#define CD_CLOSE 0x10
#define CD_COUNT_TRACKS 0x20
#define CD_CHANGER 0x40
#define CD_DVD 0x80
/* Define this to remove _all_ the debugging messages */
/* #define ERRLOGMASK CD_NOTHING */
#define ERRLOGMASK CD_WARNING
/* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */
/* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/major.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/cdrom.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/blkpg.h>
#include <linux/init.h>
#include <linux/fcntl.h>
#include <linux/blkdev.h>
#include <linux/times.h>
#include <linux/uaccess.h>
#include <scsi/scsi_common.h>
#include <scsi/scsi_request.h>
/* used to tell the module to turn on full debugging messages */
static bool debug;
/* default compatibility mode */
static bool autoclose=1;
static bool autoeject;
static bool lockdoor = 1;
/* will we ever get to use this... sigh. */
static bool check_media_type;
/* automatically restart mrw format */
static bool mrw_format_restart = 1;
module_param(debug, bool, 0);
module_param(autoclose, bool, 0);
module_param(autoeject, bool, 0);
module_param(lockdoor, bool, 0);
module_param(check_media_type, bool, 0);
module_param(mrw_format_restart, bool, 0);
static DEFINE_MUTEX(cdrom_mutex);
static const char *mrw_format_status[] = {
"not mrw",
"bgformat inactive",
"bgformat active",
"mrw complete",
};
static const char *mrw_address_space[] = { "DMA", "GAA" };
#if (ERRLOGMASK != CD_NOTHING)
#define cd_dbg(type, fmt, ...) \
do { \
if ((ERRLOGMASK & type) || debug == 1) \
pr_debug(fmt, ##__VA_ARGS__); \
} while (0)
#else
#define cd_dbg(type, fmt, ...) \
do { \
if (0 && (ERRLOGMASK & type) || debug == 1) \
pr_debug(fmt, ##__VA_ARGS__); \
} while (0)
#endif
/* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in
a lot of places. This macro makes the code more clear. */
#define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type))
/*
* Another popular OS uses 7 seconds as the hard timeout for default
* commands, so it is a good choice for us as well.
*/
#define CDROM_DEF_TIMEOUT (7 * HZ)
/* Not-exported routines. */
static void cdrom_sysctl_register(void);
static LIST_HEAD(cdrom_list);
int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
if (cgc->sshdr) {
cgc->sshdr->sense_key = 0x05;
cgc->sshdr->asc = 0x20;
cgc->sshdr->ascq = 0x00;
}
cgc->stat = -EIO;
return -EIO;
}
EXPORT_SYMBOL(cdrom_dummy_generic_packet);
static int cdrom_flush_cache(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_FLUSH_CACHE;
cgc.timeout = 5 * 60 * HZ;
return cdi->ops->generic_packet(cdi, &cgc);
}
/* requires CD R/RW */
static int cdrom_get_disc_info(struct cdrom_device_info *cdi,
disc_information *di)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
int ret, buflen;
/* set up command and get the disc info */
init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_DISC_INFO;
cgc.cmd[8] = cgc.buflen = 2;
cgc.quiet = 1;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* not all drives have the same disc_info length, so requeue
* packet with the length the drive tells us it can supply
*/
buflen = be16_to_cpu(di->disc_information_length) +
sizeof(di->disc_information_length);
if (buflen > sizeof(disc_information))
buflen = sizeof(disc_information);
cgc.cmd[8] = cgc.buflen = buflen;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* return actual fill size */
return buflen;
}
/* This macro makes sure we don't have to check on cdrom_device_ops
* existence in the run-time routines below. Change_capability is a
* hack to have the capability flags defined const, while we can still
* change it here without gcc complaining at every line.
*/
#define ENSURE(call, bits) \
do { \
if (cdo->call == NULL) \
*change_capability &= ~(bits); \
} while (0)
/*
* the first prototypes used 0x2c as the page code for the mrw mode page,
* subsequently this was changed to 0x03. probe the one used by this drive
*/
static int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[16];
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.timeout = HZ;
cgc.quiet = 1;
if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) {
cdi->mrw_mode_page = MRW_MODE_PC;
return 0;
} else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) {
cdi->mrw_mode_page = MRW_MODE_PC_PRE1;
return 0;
}
return 1;
}
static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write)
{
struct packet_command cgc;
struct mrw_feature_desc *mfd;
unsigned char buffer[16];
int ret;
*write = 0;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[3] = CDF_MRW;
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
mfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)];
if (be16_to_cpu(mfd->feature_code) != CDF_MRW)
return 1;
*write = mfd->write;
if ((ret = cdrom_mrw_probe_pc(cdi))) {
*write = 0;
return ret;
}
return 0;
}
static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont)
{
struct packet_command cgc;
unsigned char buffer[12];
int ret;
pr_info("%sstarting format\n", cont ? "Re" : "");
/*
* FmtData bit set (bit 4), format type is 1
*/
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE);
cgc.cmd[0] = GPCMD_FORMAT_UNIT;
cgc.cmd[1] = (1 << 4) | 1;
cgc.timeout = 5 * 60 * HZ;
/*
* 4 byte format list header, 8 byte format list descriptor
*/
buffer[1] = 1 << 1;
buffer[3] = 8;
/*
* nr_blocks field
*/
buffer[4] = 0xff;
buffer[5] = 0xff;
buffer[6] = 0xff;
buffer[7] = 0xff;
buffer[8] = 0x24 << 2;
buffer[11] = cont;
ret = cdi->ops->generic_packet(cdi, &cgc);
if (ret)
pr_info("bgformat failed\n");
return ret;
}
static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed)
{
struct packet_command cgc;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
/*
* Session = 1, Track = 0
*/
cgc.cmd[1] = !!immed;
cgc.cmd[2] = 1 << 1;
cgc.timeout = 5 * 60 * HZ;
return cdi->ops->generic_packet(cdi, &cgc);
}
static int cdrom_mrw_exit(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type))
return 1;
ret = 0;
if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) {
pr_info("issuing MRW background format suspend\n");
ret = cdrom_mrw_bgformat_susp(cdi, 0);
}
if (!ret && cdi->media_written)
ret = cdrom_flush_cache(cdi);
return ret;
}
static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
{
struct packet_command cgc;
struct mode_page_header *mph;
char buffer[16];
int ret, offset, size;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.buffer = buffer;
cgc.buflen = sizeof(buffer);
ret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0);
if (ret)
return ret;
mph = (struct mode_page_header *)buffer;
offset = be16_to_cpu(mph->desc_length);
size = be16_to_cpu(mph->mode_data_length) + 2;
buffer[offset + 3] = space;
cgc.buflen = size;
ret = cdrom_mode_select(cdi, &cgc);
if (ret)
return ret;
pr_info("%s: mrw address space %s selected\n",
cdi->name, mrw_address_space[space]);
return 0;
}
int register_cdrom(struct cdrom_device_info *cdi)
{
static char banner_printed;
const struct cdrom_device_ops *cdo = cdi->ops;
int *change_capability = (int *)&cdo->capability; /* hack */
cd_dbg(CD_OPEN, "entering register_cdrom\n");
if (cdo->open == NULL || cdo->release == NULL)
return -EINVAL;
if (!banner_printed) {
pr_info("Uniform CD-ROM driver " REVISION "\n");
banner_printed = 1;
cdrom_sysctl_register();
}
ENSURE(drive_status, CDC_DRIVE_STATUS);
if (cdo->check_events == NULL && cdo->media_changed == NULL)
*change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC);
ENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY);
ENSURE(lock_door, CDC_LOCK);
ENSURE(select_speed, CDC_SELECT_SPEED);
ENSURE(get_last_session, CDC_MULTI_SESSION);
ENSURE(get_mcn, CDC_MCN);
ENSURE(reset, CDC_RESET);
ENSURE(generic_packet, CDC_GENERIC_PACKET);
cdi->mc_flags = 0;
cdi->options = CDO_USE_FFLAGS;
if (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY))
cdi->options |= (int) CDO_AUTO_CLOSE;
if (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY))
cdi->options |= (int) CDO_AUTO_EJECT;
if (lockdoor == 1)
cdi->options |= (int) CDO_LOCK;
if (check_media_type == 1)
cdi->options |= (int) CDO_CHECK_TYPE;
if (CDROM_CAN(CDC_MRW_W))
cdi->exit = cdrom_mrw_exit;
if (cdi->disk)
cdi->cdda_method = CDDA_BPC_FULL;
else
cdi->cdda_method = CDDA_OLD;
WARN_ON(!cdo->generic_packet);
cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" registered\n", cdi->name);
mutex_lock(&cdrom_mutex);
list_add(&cdi->list, &cdrom_list);
mutex_unlock(&cdrom_mutex);
return 0;
}
#undef ENSURE
void unregister_cdrom(struct cdrom_device_info *cdi)
{
cd_dbg(CD_OPEN, "entering unregister_cdrom\n");
mutex_lock(&cdrom_mutex);
list_del(&cdi->list);
mutex_unlock(&cdrom_mutex);
if (cdi->exit)
cdi->exit(cdi);
cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" unregistered\n", cdi->name);
}
int cdrom_get_media_event(struct cdrom_device_info *cdi,
struct media_event_desc *med)
{
struct packet_command cgc;
unsigned char buffer[8];
struct event_header *eh = (struct event_header *)buffer;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION;
cgc.cmd[1] = 1; /* IMMED */
cgc.cmd[4] = 1 << 4; /* media event */
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if (cdi->ops->generic_packet(cdi, &cgc))
return 1;
if (be16_to_cpu(eh->data_len) < sizeof(*med))
return 1;
if (eh->nea || eh->notification_class != 0x4)
return 1;
memcpy(med, &buffer[sizeof(*eh)], sizeof(*med));
return 0;
}
static int cdrom_get_random_writable(struct cdrom_device_info *cdi,
struct rwrt_feature_desc *rfd)
{
struct packet_command cgc;
char buffer[24];
int ret;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION; /* often 0x46 */
cgc.cmd[3] = CDF_RWRT; /* often 0x0020 */
cgc.cmd[8] = sizeof(buffer); /* often 0x18 */
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));
return 0;
}
static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[16];
__be16 *feature_code;
int ret;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[3] = CDF_HWDM;
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
feature_code = (__be16 *) &buffer[sizeof(struct feature_header)];
if (be16_to_cpu(*feature_code) == CDF_HWDM)
return 0;
return 1;
}
static int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write)
{
struct rwrt_feature_desc rfd;
int ret;
*write = 0;
if ((ret = cdrom_get_random_writable(cdi, &rfd)))
return ret;
if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
*write = 1;
return 0;
}
static int cdrom_media_erasable(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di), n_first_track))
return -1;
return di.erasable;
}
/*
* FIXME: check RO bit
*/
static int cdrom_dvdram_open_write(struct cdrom_device_info *cdi)
{
int ret = cdrom_media_erasable(cdi);
/*
* allow writable open if media info read worked and media is
* erasable, _or_ if it fails since not all drives support it
*/
if (!ret)
return 1;
return 0;
}
static int cdrom_mrw_open_write(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
/*
* always reset to DMA lba space on open
*/
if (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) {
pr_err("failed setting lba address space\n");
return 1;
}
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di),disc_type))
return 1;
if (!di.erasable)
return 1;
/*
* mrw_status
* 0 - not MRW formatted
* 1 - MRW bgformat started, but not running or complete
* 2 - MRW bgformat in progress
* 3 - MRW formatting complete
*/
ret = 0;
pr_info("open: mrw_status '%s'\n", mrw_format_status[di.mrw_status]);
if (!di.mrw_status)
ret = 1;
else if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE &&
mrw_format_restart)
ret = cdrom_mrw_bgformat(cdi, 1);
return ret;
}
static int mo_open_write(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[255];
int ret;
init_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ);
cgc.quiet = 1;
/*
* obtain write protect information as per
* drivers/scsi/sd.c:sd_read_write_protect_flag
*/
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
if (ret)
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0);
if (ret) {
cgc.buflen = 255;
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
}
/* drive gave us no info, let the user go ahead */
if (ret)
return 0;
return buffer[3] & 0x80;
}
static int cdrom_ram_open_write(struct cdrom_device_info *cdi)
{
struct rwrt_feature_desc rfd;
int ret;
if ((ret = cdrom_has_defect_mgt(cdi)))
return ret;
if ((ret = cdrom_get_random_writable(cdi, &rfd)))
return ret;
else if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
ret = !rfd.curr;
cd_dbg(CD_OPEN, "can open for random write\n");
return ret;
}
static void cdrom_mmc3_profile(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[32];
int ret, mmc3_profile;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[1] = 0;
cgc.cmd[2] = cgc.cmd[3] = 0; /* Starting Feature Number */
cgc.cmd[8] = sizeof(buffer); /* Allocation Length */
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
mmc3_profile = 0xffff;
else
mmc3_profile = (buffer[6] << 8) | buffer[7];
cdi->mmc3_profile = mmc3_profile;
}
static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi)
{
switch (cdi->mmc3_profile) {
case 0x12: /* DVD-RAM */
case 0x1A: /* DVD+RW */
case 0x43: /* BD-RE */
return 0;
default:
return 1;
}
}
/*
* returns 0 for ok to open write, non-0 to disallow
*/
static int cdrom_open_write(struct cdrom_device_info *cdi)
{
int mrw, mrw_write, ram_write;
int ret = 1;
mrw = 0;
if (!cdrom_is_mrw(cdi, &mrw_write))
mrw = 1;
if (CDROM_CAN(CDC_MO_DRIVE))
ram_write = 1;
else
(void) cdrom_is_random_writable(cdi, &ram_write);
if (mrw)
cdi->mask &= ~CDC_MRW;
else
cdi->mask |= CDC_MRW;
if (mrw_write)
cdi->mask &= ~CDC_MRW_W;
else
cdi->mask |= CDC_MRW_W;
if (ram_write)
cdi->mask &= ~CDC_RAM;
else
cdi->mask |= CDC_RAM;
if (CDROM_CAN(CDC_MRW_W))
ret = cdrom_mrw_open_write(cdi);
else if (CDROM_CAN(CDC_DVD_RAM))
ret = cdrom_dvdram_open_write(cdi);
else if (CDROM_CAN(CDC_RAM) &&
!CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE))
ret = cdrom_ram_open_write(cdi);
else if (CDROM_CAN(CDC_MO_DRIVE))
ret = mo_open_write(cdi);
else if (!cdrom_is_dvd_rw(cdi))
ret = 0;
return ret;
}
static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
if (cdi->mmc3_profile != 0x1a) {
cd_dbg(CD_CLOSE, "%s: No DVD+RW\n", cdi->name);
return;
}
if (!cdi->media_written) {
cd_dbg(CD_CLOSE, "%s: DVD+RW media clean\n", cdi->name);
return;
}
pr_info("%s: dirty DVD+RW media, \"finalizing\"\n", cdi->name);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_FLUSH_CACHE;
cgc.timeout = 30*HZ;
cdi->ops->generic_packet(cdi, &cgc);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
cgc.timeout = 3000*HZ;
cgc.quiet = 1;
cdi->ops->generic_packet(cdi, &cgc);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
cgc.cmd[2] = 2; /* Close session */
cgc.quiet = 1;
cgc.timeout = 3000*HZ;
cdi->ops->generic_packet(cdi, &cgc);
cdi->media_written = 0;
}
static int cdrom_close_write(struct cdrom_device_info *cdi)
{
#if 0
return cdrom_flush_cache(cdi);
#else
return 0;
#endif
}
/* badly broken, I know. Is due for a fixup anytime. */
static void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks)
{
struct cdrom_tochdr header;
struct cdrom_tocentry entry;
int ret, i;
tracks->data = 0;
tracks->audio = 0;
tracks->cdi = 0;
tracks->xa = 0;
tracks->error = 0;
cd_dbg(CD_COUNT_TRACKS, "entering cdrom_count_tracks\n");
/* Grab the TOC header so we can see how many tracks there are */
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);
if (ret) {
if (ret == -ENOMEDIUM)
tracks->error = CDS_NO_DISC;
else
tracks->error = CDS_NO_INFO;
return;
}
/* check what type of tracks are on this disc */
entry.cdte_format = CDROM_MSF;
for (i = header.cdth_trk0; i <= header.cdth_trk1; i++) {
entry.cdte_track = i;
if (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) {
tracks->error = CDS_NO_INFO;
return;
}
if (entry.cdte_ctrl & CDROM_DATA_TRACK) {
if (entry.cdte_format == 0x10)
tracks->cdi++;
else if (entry.cdte_format == 0x20)
tracks->xa++;
else
tracks->data++;
} else {
tracks->audio++;
}
cd_dbg(CD_COUNT_TRACKS, "track %d: format=%d, ctrl=%d\n",
i, entry.cdte_format, entry.cdte_ctrl);
}
cd_dbg(CD_COUNT_TRACKS, "disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\n",
header.cdth_trk1, tracks->audio, tracks->data,
tracks->cdi, tracks->xa);
}
static
int open_for_data(struct cdrom_device_info *cdi)
{
int ret;
const struct cdrom_device_ops *cdo = cdi->ops;
tracktype tracks;
cd_dbg(CD_OPEN, "entering open_for_data\n");
/* Check if the driver can report drive status. If it can, we
can do clever things. If it can't, well, we at least tried! */
if (cdo->drive_status != NULL) {
ret = cdo->drive_status(cdi, CDSL_CURRENT);
cd_dbg(CD_OPEN, "drive_status=%d\n", ret);
if (ret == CDS_TRAY_OPEN) {
cd_dbg(CD_OPEN, "the tray is open...\n");
/* can/may i close it? */
if (CDROM_CAN(CDC_CLOSE_TRAY) &&
cdi->options & CDO_AUTO_CLOSE) {
cd_dbg(CD_OPEN, "trying to close the tray\n");
ret=cdo->tray_move(cdi,0);
if (ret) {
cd_dbg(CD_OPEN, "bummer. tried to close the tray but failed.\n");
/* Ignore the error from the low
level driver. We don't care why it
couldn't close the tray. We only care
that there is no disc in the drive,
since that is the _REAL_ problem here.*/
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
} else {
cd_dbg(CD_OPEN, "bummer. this drive can't close the tray.\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
/* Ok, the door should be closed now.. Check again */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n");
cd_dbg(CD_OPEN, "tray might not contain a medium\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
cd_dbg(CD_OPEN, "the tray is now closed\n");
}
/* the door should be closed now, check for the disc */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if (ret!=CDS_DISC_OK) {
ret = -ENOMEDIUM;
goto clean_up_and_return;
}
}
cdrom_count_tracks(cdi, &tracks);
if (tracks.error == CDS_NO_DISC) {
cd_dbg(CD_OPEN, "bummer. no disc.\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
/* CD-Players which don't use O_NONBLOCK, workman
* for example, need bit CDO_CHECK_TYPE cleared! */
if (tracks.data==0) {
if (cdi->options & CDO_CHECK_TYPE) {
/* give people a warning shot, now that CDO_CHECK_TYPE
is the default case! */
cd_dbg(CD_OPEN, "bummer. wrong media type.\n");
cd_dbg(CD_WARNING, "pid %d must open device O_NONBLOCK!\n",
(unsigned int)task_pid_nr(current));
ret=-EMEDIUMTYPE;
goto clean_up_and_return;
}
else {
cd_dbg(CD_OPEN, "wrong media type, but CDO_CHECK_TYPE not set\n");
}
}
cd_dbg(CD_OPEN, "all seems well, opening the devicen");
/* all seems well, we can open the device */
ret = cdo->open(cdi, 0); /* open for data */
cd_dbg(CD_OPEN, "opening the device gave me %d\n", ret);
/* After all this careful checking, we shouldn't have problems
opening the device, but we don't want the device locked if
this somehow fails... */
if (ret) {
cd_dbg(CD_OPEN, "open device failed\n");
goto clean_up_and_return;
}
if (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) {
cdo->lock_door(cdi, 1);
cd_dbg(CD_OPEN, "door locked\n");
}
cd_dbg(CD_OPEN, "device opened successfully\n");
return ret;
/* Something failed. Try to unlock the drive, because some drivers
(notably ide-cd) lock the drive after every command. This produced
a nasty bug where after mount failed, the drive would remain locked!
This ensures that the drive gets unlocked after a mount fails. This
is a goto to avoid bloating the driver with redundant code. */
clean_up_and_return:
cd_dbg(CD_OPEN, "open failed\n");
if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {
cdo->lock_door(cdi, 0);
cd_dbg(CD_OPEN, "door unlocked\n");
}
return ret;
}
/* We use the open-option O_NONBLOCK to indicate that the
* purpose of opening is only for subsequent ioctl() calls; no device
* integrity checks are performed.
*
* We hope that all cd-player programs will adopt this convention. It
* is in their own interest: device control becomes a lot easier
* this way.
*/
int cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev,
fmode_t mode)
{
int ret;
cd_dbg(CD_OPEN, "entering cdrom_open\n");
/* if this was a O_NONBLOCK open and we should honor the flags,
* do a quick open without drive/disc integrity checks. */
cdi->use_count++;
if ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) {
ret = cdi->ops->open(cdi, 1);
} else {
ret = open_for_data(cdi);
if (ret)
goto err;
cdrom_mmc3_profile(cdi);
if (mode & FMODE_WRITE) {
ret = -EROFS;
if (cdrom_open_write(cdi))
goto err_release;
if (!CDROM_CAN(CDC_RAM))
goto err_release;
ret = 0;
cdi->media_written = 0;
}
}
if (ret)
goto err;
cd_dbg(CD_OPEN, "Use count for \"/dev/%s\" now %d\n",
cdi->name, cdi->use_count);
return 0;
err_release:
if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {
cdi->ops->lock_door(cdi, 0);
cd_dbg(CD_OPEN, "door unlocked\n");
}
cdi->ops->release(cdi);
err:
cdi->use_count--;
return ret;
}
/* This code is similar to that in open_for_data. The routine is called
whenever an audio play operation is requested.
*/
static int check_for_audio_disc(struct cdrom_device_info *cdi,
const struct cdrom_device_ops *cdo)
{
int ret;
tracktype tracks;
cd_dbg(CD_OPEN, "entering check_for_audio_disc\n");
if (!(cdi->options & CDO_CHECK_TYPE))
return 0;
if (cdo->drive_status != NULL) {
ret = cdo->drive_status(cdi, CDSL_CURRENT);
cd_dbg(CD_OPEN, "drive_status=%d\n", ret);
if (ret == CDS_TRAY_OPEN) {
cd_dbg(CD_OPEN, "the tray is open...\n");
/* can/may i close it? */
if (CDROM_CAN(CDC_CLOSE_TRAY) &&
cdi->options & CDO_AUTO_CLOSE) {
cd_dbg(CD_OPEN, "trying to close the tray\n");
ret=cdo->tray_move(cdi,0);
if (ret) {
cd_dbg(CD_OPEN, "bummer. tried to close tray but failed.\n");
/* Ignore the error from the low
level driver. We don't care why it
couldn't close the tray. We only care
that there is no disc in the drive,
since that is the _REAL_ problem here.*/
return -ENOMEDIUM;
}
} else {
cd_dbg(CD_OPEN, "bummer. this driver can't close the tray.\n");
return -ENOMEDIUM;
}
/* Ok, the door should be closed now.. Check again */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n");
return -ENOMEDIUM;
}
if (ret!=CDS_DISC_OK) {
cd_dbg(CD_OPEN, "bummer. disc isn't ready.\n");
return -EIO;
}
cd_dbg(CD_OPEN, "the tray is now closed\n");
}
}
cdrom_count_tracks(cdi, &tracks);
if (tracks.error)
return(tracks.error);
if (tracks.audio==0)
return -EMEDIUMTYPE;
return 0;
}
void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode)
{
const struct cdrom_device_ops *cdo = cdi->ops;
int opened_for_data;
cd_dbg(CD_CLOSE, "entering cdrom_release\n");
if (cdi->use_count > 0)
cdi->use_count--;
if (cdi->use_count == 0) {
cd_dbg(CD_CLOSE, "Use count for \"/dev/%s\" now zero\n",
cdi->name);
cdrom_dvd_rw_close_write(cdi);
if ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) {
cd_dbg(CD_CLOSE, "Unlocking door!\n");
cdo->lock_door(cdi, 0);
}
}
opened_for_data = !(cdi->options & CDO_USE_FFLAGS) ||
!(mode & FMODE_NDELAY);
/*
* flush cache on last write release
*/
if (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data)
cdrom_close_write(cdi);
cdo->release(cdi);
if (cdi->use_count == 0) { /* last process that closes dev*/
if (opened_for_data &&
cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY))
cdo->tray_move(cdi, 1);
}
}
static int cdrom_read_mech_status(struct cdrom_device_info *cdi,
struct cdrom_changer_info *buf)
{
struct packet_command cgc;
const struct cdrom_device_ops *cdo = cdi->ops;
int length;
/*
* Sanyo changer isn't spec compliant (doesn't use regular change
* LOAD_UNLOAD command, and it doesn't implement the mech status
* command below
*/
if (cdi->sanyo_slot) {
buf->hdr.nslots = 3;
buf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot;
for (length = 0; length < 3; length++) {
buf->slots[length].disc_present = 1;
buf->slots[length].change = 0;
}
return 0;
}
length = sizeof(struct cdrom_mechstat_header) +
cdi->capacity * sizeof(struct cdrom_slot);
init_cdrom_command(&cgc, buf, length, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_MECHANISM_STATUS;
cgc.cmd[8] = (length >> 8) & 0xff;
cgc.cmd[9] = length & 0xff;
return cdo->generic_packet(cdi, &cgc);
}
static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_CHANGER, "entering cdrom_slot_status()\n");
if (cdi->sanyo_slot)
return CDS_NO_INFO;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((ret = cdrom_read_mech_status(cdi, info)))
goto out_free;
if (info->slots[slot].disc_present)
ret = CDS_DISC_OK;
else
ret = CDS_NO_DISC;
out_free:
kfree(info);
return ret;
}
/* Return the number of slots for an ATAPI/SCSI cdrom,
* return 1 if not a changer.
*/
int cdrom_number_of_slots(struct cdrom_device_info *cdi)
{
int status;
int nslots = 1;
struct cdrom_changer_info *info;
cd_dbg(CD_CHANGER, "entering cdrom_number_of_slots()\n");
/* cdrom_read_mech_status requires a valid value for capacity: */
cdi->capacity = 0;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((status = cdrom_read_mech_status(cdi, info)) == 0)
nslots = info->hdr.nslots;
kfree(info);
return nslots;
}
/* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */
static int cdrom_load_unload(struct cdrom_device_info *cdi, int slot)
{
struct packet_command cgc;
cd_dbg(CD_CHANGER, "entering cdrom_load_unload()\n");
if (cdi->sanyo_slot && slot < 0)
return 0;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_LOAD_UNLOAD;
cgc.cmd[4] = 2 + (slot >= 0);
cgc.cmd[8] = slot;
cgc.timeout = 60 * HZ;
/* The Sanyo 3 CD changer uses byte 7 of the
GPCMD_TEST_UNIT_READY to command to switch CDs instead of
using the GPCMD_LOAD_UNLOAD opcode. */
if (cdi->sanyo_slot && -1 < slot) {
cgc.cmd[0] = GPCMD_TEST_UNIT_READY;
cgc.cmd[7] = slot;
cgc.cmd[4] = cgc.cmd[8] = 0;
cdi->sanyo_slot = slot ? slot : 3;
}
return cdi->ops->generic_packet(cdi, &cgc);
}
static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot)
{
struct cdrom_changer_info *info;
int curslot;
int ret;
cd_dbg(CD_CHANGER, "entering cdrom_select_disc()\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -EDRIVE_CANT_DO_THIS;
if (cdi->ops->check_events)
cdi->ops->check_events(cdi, 0, slot);
else
cdi->ops->media_changed(cdi, slot);
if (slot == CDSL_NONE) {
/* set media changed bits, on both queues */
cdi->mc_flags = 0x3;
return cdrom_load_unload(cdi, -1);
}
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((ret = cdrom_read_mech_status(cdi, info))) {
kfree(info);
return ret;
}
curslot = info->hdr.curslot;
kfree(info);
if (cdi->use_count > 1 || cdi->keeplocked) {
if (slot == CDSL_CURRENT) {
return curslot;
} else {
return -EBUSY;
}
}
/* Specifying CDSL_CURRENT will attempt to load the currnet slot,
which is useful if it had been previously unloaded.
Whether it can or not, it returns the current slot.
Similarly, if slot happens to be the current one, we still
try and load it. */
if (slot == CDSL_CURRENT)
slot = curslot;
/* set media changed bits on both queues */
cdi->mc_flags = 0x3;
if ((ret = cdrom_load_unload(cdi, slot)))
return ret;
return slot;
}
/*
* As cdrom implements an extra ioctl consumer for media changed
* event, it needs to buffer ->check_events() output, such that event
* is not lost for both the usual VFS and ioctl paths.
* cdi->{vfs|ioctl}_events are used to buffer pending events for each
* path.
*
* XXX: Locking is non-existent. cdi->ops->check_events() can be
* called in parallel and buffering fields are accessed without any
* exclusion. The original media_changed code had the same problem.
* It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl
* and remove this cruft altogether. It doesn't have much usefulness
* at this point.
*/
static void cdrom_update_events(struct cdrom_device_info *cdi,
unsigned int clearing)
{
unsigned int events;
events = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT);
cdi->vfs_events |= events;
cdi->ioctl_events |= events;
}
unsigned int cdrom_check_events(struct cdrom_device_info *cdi,
unsigned int clearing)
{
unsigned int events;
cdrom_update_events(cdi, clearing);
events = cdi->vfs_events;
cdi->vfs_events = 0;
return events;
}
EXPORT_SYMBOL(cdrom_check_events);
/* We want to make media_changed accessible to the user through an
* ioctl. The main problem now is that we must double-buffer the
* low-level implementation, to assure that the VFS and the user both
* see a medium change once.
*/
static
int media_changed(struct cdrom_device_info *cdi, int queue)
{
unsigned int mask = (1 << (queue & 1));
int ret = !!(cdi->mc_flags & mask);
bool changed;
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return ret;
/* changed since last call? */
if (cdi->ops->check_events) {
BUG_ON(!queue); /* shouldn't be called from VFS path */
cdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE);
changed = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE;
cdi->ioctl_events = 0;
} else
changed = cdi->ops->media_changed(cdi, CDSL_CURRENT);
if (changed) {
cdi->mc_flags = 0x3; /* set bit on both queues */
ret |= 1;
cdi->media_written = 0;
}
cdi->mc_flags &= ~mask; /* clear bit */
return ret;
}
int cdrom_media_changed(struct cdrom_device_info *cdi)
{
/* This talks to the VFS, which doesn't like errors - just 1 or 0.
* Returning "0" is always safe (media hasn't been changed). Do that
* if the low-level cdrom driver dosn't support media changed. */
if (cdi == NULL || cdi->ops->media_changed == NULL)
return 0;
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return 0;
return media_changed(cdi, 0);
}
/* Requests to the low-level drivers will /always/ be done in the
following format convention:
CDROM_LBA: all data-related requests.
CDROM_MSF: all audio-related requests.
However, a low-level implementation is allowed to refuse this
request, and return information in its own favorite format.
It doesn't make sense /at all/ to ask for a play_audio in LBA
format, or ask for multi-session info in MSF format. However, for
backward compatibility these format requests will be satisfied, but
the requests to the low-level drivers will be sanitized in the more
meaningful format indicated above.
*/
static
void sanitize_format(union cdrom_addr *addr,
u_char * curr, u_char requested)
{
if (*curr == requested)
return; /* nothing to be done! */
if (requested == CDROM_LBA) {
addr->lba = (int) addr->msf.frame +
75 * (addr->msf.second - 2 + 60 * addr->msf.minute);
} else { /* CDROM_MSF */
int lba = addr->lba;
addr->msf.frame = lba % 75;
lba /= 75;
lba += 2;
addr->msf.second = lba % 60;
addr->msf.minute = lba / 60;
}
*curr = requested;
}
void init_cdrom_command(struct packet_command *cgc, void *buf, int len,
int type)
{
memset(cgc, 0, sizeof(struct packet_command));
if (buf)
memset(buf, 0, len);
cgc->buffer = (char *) buf;
cgc->buflen = len;
cgc->data_direction = type;
cgc->timeout = CDROM_DEF_TIMEOUT;
}
/* DVD handling */
#define copy_key(dest,src) memcpy((dest), (src), sizeof(dvd_key))
#define copy_chal(dest,src) memcpy((dest), (src), sizeof(dvd_challenge))
static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type)
{
cgc->cmd[0] = GPCMD_REPORT_KEY;
cgc->cmd[10] = type | (agid << 6);
switch (type) {
case 0: case 8: case 5: {
cgc->buflen = 8;
break;
}
case 1: {
cgc->buflen = 16;
break;
}
case 2: case 4: {
cgc->buflen = 12;
break;
}
}
cgc->cmd[9] = cgc->buflen;
cgc->data_direction = CGC_DATA_READ;
}
static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type)
{
cgc->cmd[0] = GPCMD_SEND_KEY;
cgc->cmd[10] = type | (agid << 6);
switch (type) {
case 1: {
cgc->buflen = 16;
break;
}
case 3: {
cgc->buflen = 12;
break;
}
case 6: {
cgc->buflen = 8;
break;
}
}
cgc->cmd[9] = cgc->buflen;
cgc->data_direction = CGC_DATA_WRITE;
}
static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai)
{
int ret;
u_char buf[20];
struct packet_command cgc;
const struct cdrom_device_ops *cdo = cdi->ops;
rpc_state_t rpc_state;
memset(buf, 0, sizeof(buf));
init_cdrom_command(&cgc, buf, 0, CGC_DATA_READ);
switch (ai->type) {
/* LU data send */
case DVD_LU_SEND_AGID:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_AGID\n");
cgc.quiet = 1;
setup_report_key(&cgc, ai->lsa.agid, 0);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lsa.agid = buf[7] >> 6;
/* Returning data, let host change state */
break;
case DVD_LU_SEND_KEY1:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_KEY1\n");
setup_report_key(&cgc, ai->lsk.agid, 2);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
copy_key(ai->lsk.key, &buf[4]);
/* Returning data, let host change state */
break;
case DVD_LU_SEND_CHALLENGE:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_CHALLENGE\n");
setup_report_key(&cgc, ai->lsc.agid, 1);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
copy_chal(ai->lsc.chal, &buf[4]);
/* Returning data, let host change state */
break;
/* Post-auth key */
case DVD_LU_SEND_TITLE_KEY:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_TITLE_KEY\n");
cgc.quiet = 1;
setup_report_key(&cgc, ai->lstk.agid, 4);
cgc.cmd[5] = ai->lstk.lba;
cgc.cmd[4] = ai->lstk.lba >> 8;
cgc.cmd[3] = ai->lstk.lba >> 16;
cgc.cmd[2] = ai->lstk.lba >> 24;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lstk.cpm = (buf[4] >> 7) & 1;
ai->lstk.cp_sec = (buf[4] >> 6) & 1;
ai->lstk.cgms = (buf[4] >> 4) & 3;
copy_key(ai->lstk.title_key, &buf[5]);
/* Returning data, let host change state */
break;
case DVD_LU_SEND_ASF:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_ASF\n");
setup_report_key(&cgc, ai->lsasf.agid, 5);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lsasf.asf = buf[7] & 1;
break;
/* LU data receive (LU changes state) */
case DVD_HOST_SEND_CHALLENGE:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_CHALLENGE\n");
setup_send_key(&cgc, ai->hsc.agid, 1);
buf[1] = 0xe;
copy_chal(&buf[4], ai->hsc.chal);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->type = DVD_LU_SEND_KEY1;
break;
case DVD_HOST_SEND_KEY2:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_KEY2\n");
setup_send_key(&cgc, ai->hsk.agid, 3);
buf[1] = 0xa;
copy_key(&buf[4], ai->hsk.key);
if ((ret = cdo->generic_packet(cdi, &cgc))) {
ai->type = DVD_AUTH_FAILURE;
return ret;
}
ai->type = DVD_AUTH_ESTABLISHED;
break;
/* Misc */
case DVD_INVALIDATE_AGID:
cgc.quiet = 1;
cd_dbg(CD_DVD, "entering DVD_INVALIDATE_AGID\n");
setup_report_key(&cgc, ai->lsa.agid, 0x3f);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
break;
/* Get region settings */
case DVD_LU_SEND_RPC_STATE:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_RPC_STATE\n");
setup_report_key(&cgc, 0, 8);
memset(&rpc_state, 0, sizeof(rpc_state_t));
cgc.buffer = (char *) &rpc_state;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lrpcs.type = rpc_state.type_code;
ai->lrpcs.vra = rpc_state.vra;
ai->lrpcs.ucca = rpc_state.ucca;
ai->lrpcs.region_mask = rpc_state.region_mask;
ai->lrpcs.rpc_scheme = rpc_state.rpc_scheme;
break;
/* Set region settings */
case DVD_HOST_SEND_RPC_STATE:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_RPC_STATE\n");
setup_send_key(&cgc, 0, 6);
buf[1] = 6;
buf[4] = ai->hrpcs.pdrc;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
break;
default:
cd_dbg(CD_WARNING, "Invalid DVD key ioctl (%d)\n", ai->type);
return -ENOTTY;
}
return 0;
}
static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
unsigned char buf[21], *base;
struct dvd_layer *layer;
const struct cdrom_device_ops *cdo = cdi->ops;
int ret, layer_num = s->physical.layer_num;
if (layer_num >= DVD_LAYERS)
return -EINVAL;
init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[6] = layer_num;
cgc->cmd[7] = s->type;
cgc->cmd[9] = cgc->buflen & 0xff;
/*
* refrain from reporting errors on non-existing layers (mainly)
*/
cgc->quiet = 1;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
return ret;
base = &buf[4];
layer = &s->physical.layer[layer_num];
/*
* place the data... really ugly, but at least we won't have to
* worry about endianess in userspace.
*/
memset(layer, 0, sizeof(*layer));
layer->book_version = base[0] & 0xf;
layer->book_type = base[0] >> 4;
layer->min_rate = base[1] & 0xf;
layer->disc_size = base[1] >> 4;
layer->layer_type = base[2] & 0xf;
layer->track_path = (base[2] >> 4) & 1;
layer->nlayers = (base[2] >> 5) & 3;
layer->track_density = base[3] & 0xf;
layer->linear_density = base[3] >> 4;
layer->start_sector = base[5] << 16 | base[6] << 8 | base[7];
layer->end_sector = base[9] << 16 | base[10] << 8 | base[11];
layer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15];
layer->bca = base[16] >> 7;
return 0;
}
static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret;
u_char buf[8];
const struct cdrom_device_ops *cdo = cdi->ops;
init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[6] = s->copyright.layer_num;
cgc->cmd[7] = s->type;
cgc->cmd[8] = cgc->buflen >> 8;
cgc->cmd[9] = cgc->buflen & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
return ret;
s->copyright.cpst = buf[4];
s->copyright.rmi = buf[5];
return 0;
}
static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret, size;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
size = sizeof(s->disckey.value) + 4;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[8] = size >> 8;
cgc->cmd[9] = size & 0xff;
cgc->cmd[10] = s->disckey.agid << 6;
ret = cdo->generic_packet(cdi, cgc);
if (!ret)
memcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value));
kfree(buf);
return ret;
}
static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret, size = 4 + 188;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[9] = cgc->buflen & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
goto out;
s->bca.len = buf[0] << 8 | buf[1];
if (s->bca.len < 12 || s->bca.len > 188) {
cd_dbg(CD_WARNING, "Received invalid BCA length (%d)\n",
s->bca.len);
ret = -EIO;
goto out;
}
memcpy(s->bca.value, &buf[4], s->bca.len);
ret = 0;
out:
kfree(buf);
return ret;
}
static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret = 0, size;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
size = sizeof(s->manufact.value) + 4;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[8] = size >> 8;
cgc->cmd[9] = size & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
goto out;
s->manufact.len = buf[0] << 8 | buf[1];
if (s->manufact.len < 0) {
cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d)\n",
s->manufact.len);
ret = -EIO;
} else {
if (s->manufact.len > 2048) {
cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d): truncating to 2048\n",
s->manufact.len);
s->manufact.len = 2048;
}
memcpy(s->manufact.value, &buf[4], s->manufact.len);
}
out:
kfree(buf);
return ret;
}
static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
switch (s->type) {
case DVD_STRUCT_PHYSICAL:
return dvd_read_physical(cdi, s, cgc);
case DVD_STRUCT_COPYRIGHT:
return dvd_read_copyright(cdi, s, cgc);
case DVD_STRUCT_DISCKEY:
return dvd_read_disckey(cdi, s, cgc);
case DVD_STRUCT_BCA:
return dvd_read_bca(cdi, s, cgc);
case DVD_STRUCT_MANUFACT:
return dvd_read_manufact(cdi, s, cgc);
default:
cd_dbg(CD_WARNING, ": Invalid DVD structure read requested (%d)\n",
s->type);
return -EINVAL;
}
}
int cdrom_mode_sense(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int page_code, int page_control)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_MODE_SENSE_10;
cgc->cmd[2] = page_code | (page_control << 6);
cgc->cmd[7] = cgc->buflen >> 8;
cgc->cmd[8] = cgc->buflen & 0xff;
cgc->data_direction = CGC_DATA_READ;
return cdo->generic_packet(cdi, cgc);
}
int cdrom_mode_select(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(cgc->cmd, 0, sizeof(cgc->cmd));
memset(cgc->buffer, 0, 2);
cgc->cmd[0] = GPCMD_MODE_SELECT_10;
cgc->cmd[1] = 0x10; /* PF */
cgc->cmd[7] = cgc->buflen >> 8;
cgc->cmd[8] = cgc->buflen & 0xff;
cgc->data_direction = CGC_DATA_WRITE;
return cdo->generic_packet(cdi, cgc);
}
static int cdrom_read_subchannel(struct cdrom_device_info *cdi,
struct cdrom_subchnl *subchnl, int mcn)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
char buffer[32];
int ret;
init_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_SUBCHANNEL;
cgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */
cgc.cmd[2] = 0x40; /* request subQ data */
cgc.cmd[3] = mcn ? 2 : 1;
cgc.cmd[8] = 16;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
subchnl->cdsc_audiostatus = cgc.buffer[1];
subchnl->cdsc_ctrl = cgc.buffer[5] & 0xf;
subchnl->cdsc_trk = cgc.buffer[6];
subchnl->cdsc_ind = cgc.buffer[7];
if (subchnl->cdsc_format == CDROM_LBA) {
subchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) |
(cgc.buffer[9] << 16) |
(cgc.buffer[10] << 8) |
(cgc.buffer[11]));
subchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) |
(cgc.buffer[13] << 16) |
(cgc.buffer[14] << 8) |
(cgc.buffer[15]));
} else {
subchnl->cdsc_reladdr.msf.minute = cgc.buffer[13];
subchnl->cdsc_reladdr.msf.second = cgc.buffer[14];
subchnl->cdsc_reladdr.msf.frame = cgc.buffer[15];
subchnl->cdsc_absaddr.msf.minute = cgc.buffer[9];
subchnl->cdsc_absaddr.msf.second = cgc.buffer[10];
subchnl->cdsc_absaddr.msf.frame = cgc.buffer[11];
}
return 0;
}
/*
* Specific READ_10 interface
*/
static int cdrom_read_cd(struct cdrom_device_info *cdi,
struct packet_command *cgc, int lba,
int blocksize, int nblocks)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(&cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_READ_10;
cgc->cmd[2] = (lba >> 24) & 0xff;
cgc->cmd[3] = (lba >> 16) & 0xff;
cgc->cmd[4] = (lba >> 8) & 0xff;
cgc->cmd[5] = lba & 0xff;
cgc->cmd[6] = (nblocks >> 16) & 0xff;
cgc->cmd[7] = (nblocks >> 8) & 0xff;
cgc->cmd[8] = nblocks & 0xff;
cgc->buflen = blocksize * nblocks;
return cdo->generic_packet(cdi, cgc);
}
/* very generic interface for reading the various types of blocks */
static int cdrom_read_block(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int lba, int nblocks, int format, int blksize)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(&cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_READ_CD;
/* expected sector size - cdda,mode1,etc. */
cgc->cmd[1] = format << 2;
/* starting address */
cgc->cmd[2] = (lba >> 24) & 0xff;
cgc->cmd[3] = (lba >> 16) & 0xff;
cgc->cmd[4] = (lba >> 8) & 0xff;
cgc->cmd[5] = lba & 0xff;
/* number of blocks */
cgc->cmd[6] = (nblocks >> 16) & 0xff;
cgc->cmd[7] = (nblocks >> 8) & 0xff;
cgc->cmd[8] = nblocks & 0xff;
cgc->buflen = blksize * nblocks;
/* set the header info returned */
switch (blksize) {
case CD_FRAMESIZE_RAW0 : cgc->cmd[9] = 0x58; break;
case CD_FRAMESIZE_RAW1 : cgc->cmd[9] = 0x78; break;
case CD_FRAMESIZE_RAW : cgc->cmd[9] = 0xf8; break;
default : cgc->cmd[9] = 0x10;
}
return cdo->generic_packet(cdi, cgc);
}
static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
struct packet_command cgc;
int ret = 0;
int nr;
cdi->last_sense = 0;
memset(&cgc, 0, sizeof(cgc));
/*
* start with will ra.nframes size, back down if alloc fails
*/
nr = nframes;
do {
cgc.buffer = kmalloc_array(nr, CD_FRAMESIZE_RAW, GFP_KERNEL);
if (cgc.buffer)
break;
nr >>= 1;
} while (nr);
if (!nr)
return -ENOMEM;
cgc.data_direction = CGC_DATA_READ;
while (nframes > 0) {
if (nr > nframes)
nr = nframes;
ret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW);
if (ret)
break;
if (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) {
ret = -EFAULT;
break;
}
ubuf += CD_FRAMESIZE_RAW * nr;
nframes -= nr;
lba += nr;
}
kfree(cgc.buffer);
return ret;
}
static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
struct request_queue *q = cdi->disk->queue;
struct request *rq;
struct scsi_request *req;
struct bio *bio;
unsigned int len;
int nr, ret = 0;
if (!q)
return -ENXIO;
if (!blk_queue_scsi_passthrough(q)) {
WARN_ONCE(true,
"Attempt read CDDA info through a non-SCSI queue\n");
return -EINVAL;
}
cdi->last_sense = 0;
while (nframes) {
nr = nframes;
if (cdi->cdda_method == CDDA_BPC_SINGLE)
nr = 1;
if (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9))
nr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW;
len = nr * CD_FRAMESIZE_RAW;
rq = blk_get_request(q, REQ_OP_SCSI_IN, 0);
if (IS_ERR(rq)) {
ret = PTR_ERR(rq);
break;
}
req = scsi_req(rq);
ret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL);
if (ret) {
blk_put_request(rq);
break;
}
req->cmd[0] = GPCMD_READ_CD;
req->cmd[1] = 1 << 2;
req->cmd[2] = (lba >> 24) & 0xff;
req->cmd[3] = (lba >> 16) & 0xff;
req->cmd[4] = (lba >> 8) & 0xff;
req->cmd[5] = lba & 0xff;
req->cmd[6] = (nr >> 16) & 0xff;
req->cmd[7] = (nr >> 8) & 0xff;
req->cmd[8] = nr & 0xff;
req->cmd[9] = 0xf8;
req->cmd_len = 12;
rq->timeout = 60 * HZ;
bio = rq->bio;
blk_execute_rq(q, cdi->disk, rq, 0);
if (scsi_req(rq)->result) {
struct scsi_sense_hdr sshdr;
ret = -EIO;
scsi_normalize_sense(req->sense, req->sense_len,
&sshdr);
cdi->last_sense = sshdr.sense_key;
}
if (blk_rq_unmap_user(bio))
ret = -EFAULT;
blk_put_request(rq);
if (ret)
break;
nframes -= nr;
lba += nr;
ubuf += len;
}
return ret;
}
static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
int ret;
if (cdi->cdda_method == CDDA_OLD)
return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);
retry:
/*
* for anything else than success and io error, we need to retry
*/
ret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes);
if (!ret || ret != -EIO)
return ret;
/*
* I've seen drives get sense 4/8/3 udma crc errors on multi
* frame dma, so drop to single frame dma if we need to
*/
if (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) {
pr_info("dropping to single frame dma\n");
cdi->cdda_method = CDDA_BPC_SINGLE;
goto retry;
}
/*
* so we have an io error of some sort with multi frame dma. if the
* condition wasn't a hardware error
* problems, not for any error
*/
if (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b)
return ret;
pr_info("dropping to old style cdda (sense=%x)\n", cdi->last_sense);
cdi->cdda_method = CDDA_OLD;
return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);
}
static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_multisession ms_info;
u8 requested_format;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMMULTISESSION\n");
if (!(cdi->ops->capability & CDC_MULTI_SESSION))
return -ENOSYS;
if (copy_from_user(&ms_info, argp, sizeof(ms_info)))
return -EFAULT;
requested_format = ms_info.addr_format;
if (requested_format != CDROM_MSF && requested_format != CDROM_LBA)
return -EINVAL;
ms_info.addr_format = CDROM_LBA;
ret = cdi->ops->get_last_session(cdi, &ms_info);
if (ret)
return ret;
sanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format);
if (copy_to_user(argp, &ms_info, sizeof(ms_info)))
return -EFAULT;
cd_dbg(CD_DO_IOCTL, "CDROMMULTISESSION successful\n");
return 0;
}
static int cdrom_ioctl_eject(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT\n");
if (!CDROM_CAN(CDC_OPEN_TRAY))
return -ENOSYS;
if (cdi->use_count != 1 || cdi->keeplocked)
return -EBUSY;
if (CDROM_CAN(CDC_LOCK)) {
int ret = cdi->ops->lock_door(cdi, 0);
if (ret)
return ret;
}
return cdi->ops->tray_move(cdi, 1);
}
static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n");
if (!CDROM_CAN(CDC_CLOSE_TRAY))
return -ENOSYS;
return cdi->ops->tray_move(cdi, 0);
}
static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT_SW\n");
if (!CDROM_CAN(CDC_OPEN_TRAY))
return -ENOSYS;
if (cdi->keeplocked)
return -EBUSY;
cdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT);
if (arg)
cdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT;
return 0;
}
static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,
unsigned long arg)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n");
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return -ENOSYS;
/* cannot select disc or select current disc */
if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)
return media_changed(cdi, 1);
if (arg >= cdi->capacity)
return -EINVAL;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
ret = cdrom_read_mech_status(cdi, info);
if (!ret)
ret = info->slots[arg].change;
kfree(info);
return ret;
}
static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SET_OPTIONS\n");
/*
* Options need to be in sync with capability.
* Too late for that, so we have to check each one separately.
*/
switch (arg) {
case CDO_USE_FFLAGS:
case CDO_CHECK_TYPE:
break;
case CDO_LOCK:
if (!CDROM_CAN(CDC_LOCK))
return -ENOSYS;
break;
case 0:
return cdi->options;
/* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */
default:
if (!CDROM_CAN(arg))
return -ENOSYS;
}
cdi->options |= (int) arg;
return cdi->options;
}
static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_CLEAR_OPTIONS\n");
cdi->options &= ~(int) arg;
return cdi->options;
}
static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_SPEED\n");
if (!CDROM_CAN(CDC_SELECT_SPEED))
return -ENOSYS;
return cdi->ops->select_speed(cdi, arg);
}
static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -ENOSYS;
if (arg != CDSL_CURRENT && arg != CDSL_NONE) {
if (arg >= cdi->capacity)
return -EINVAL;
}
/*
* ->select_disc is a hook to allow a driver-specific way of
* seleting disc. However, since there is no equivalent hook for
* cdrom_slot_status this may not actually be useful...
*/
if (cdi->ops->select_disc)
return cdi->ops->select_disc(cdi, arg);
cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n");
return cdrom_select_disc(cdi, arg);
}
static int cdrom_ioctl_reset(struct cdrom_device_info *cdi,
struct block_device *bdev)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_RESET\n");
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (!CDROM_CAN(CDC_RESET))
return -ENOSYS;
invalidate_bdev(bdev);
return cdi->ops->reset(cdi);
}
static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "%socking door\n", arg ? "L" : "Unl");
if (!CDROM_CAN(CDC_LOCK))
return -EDRIVE_CANT_DO_THIS;
cdi->keeplocked = arg ? 1 : 0;
/*
* Don't unlock the door on multiple opens by default, but allow
* root to do so.
*/
if (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN))
return -EBUSY;
return cdi->ops->lock_door(cdi, arg);
}
static int cdrom_ioctl_debug(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "%sabling debug\n", arg ? "En" : "Dis");
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
debug = arg ? 1 : 0;
return debug;
}
static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_CAPABILITY\n");
return (cdi->ops->capability & ~cdi->mask);
}
/*
* The following function is implemented, although very few audio
* discs give Universal Product Code information, which should just be
* the Medium Catalog Number on the box. Note, that the way the code
* is written on the CD is /not/ uniform across all discs!
*/
static int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_mcn mcn;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_MCN\n");
if (!(cdi->ops->capability & CDC_MCN))
return -ENOSYS;
ret = cdi->ops->get_mcn(cdi, &mcn);
if (ret)
return ret;
if (copy_to_user(argp, &mcn, sizeof(mcn)))
return -EFAULT;
cd_dbg(CD_DO_IOCTL, "CDROM_GET_MCN successful\n");
return 0;
}
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n");
if (!(cdi->ops->capability & CDC_DRIVE_STATUS))
return -ENOSYS;
if (!CDROM_CAN(CDC_SELECT_DISC) ||
(arg == CDSL_CURRENT || arg == CDSL_NONE))
return cdi->ops->drive_status(cdi, CDSL_CURRENT);
if (arg >= cdi->capacity)
return -EINVAL;
return cdrom_slot_status(cdi, arg);
}
/*
* Ok, this is where problems start. The current interface for the
* CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that
* CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this
* is often the case, it is also very common for CDs to have some tracks
* with data, and some tracks with audio. Just because I feel like it,
* I declare the following to be the best way to cope. If the CD has ANY
* data tracks on it, it will be returned as a data CD. If it has any XA
* tracks, I will return it as that. Now I could simplify this interface
* by combining these returns with the above, but this more clearly
* demonstrates the problem with the current interface. Too bad this
* wasn't designed to use bitmasks... -Erik
*
* Well, now we have the option CDS_MIXED: a mixed-type CD.
* User level programmers might feel the ioctl is not very useful.
* ---david
*/
static int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi)
{
tracktype tracks;
cd_dbg(CD_DO_IOCTL, "entering CDROM_DISC_STATUS\n");
cdrom_count_tracks(cdi, &tracks);
if (tracks.error)
return tracks.error;
/* Policy mode on */
if (tracks.audio > 0) {
if (!tracks.data && !tracks.cdi && !tracks.xa)
return CDS_AUDIO;
else
return CDS_MIXED;
}
if (tracks.cdi > 0)
return CDS_XA_2_2;
if (tracks.xa > 0)
return CDS_XA_2_1;
if (tracks.data > 0)
return CDS_DATA_1;
/* Policy mode off */
cd_dbg(CD_WARNING, "This disc doesn't have any tracks I recognize!\n");
return CDS_NO_INFO;
}
static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n");
return cdi->capacity;
}
static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_subchnl q;
u8 requested, back;
int ret;
/* cd_dbg(CD_DO_IOCTL,"entering CDROMSUBCHNL\n");*/
if (copy_from_user(&q, argp, sizeof(q)))
return -EFAULT;
requested = q.cdsc_format;
if (requested != CDROM_MSF && requested != CDROM_LBA)
return -EINVAL;
q.cdsc_format = CDROM_MSF;
ret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q);
if (ret)
return ret;
back = q.cdsc_format; /* local copy */
sanitize_format(&q.cdsc_absaddr, &back, requested);
sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
if (copy_to_user(argp, &q, sizeof(q)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */
return 0;
}
static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_tochdr header;
int ret;
/* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCHDR\n"); */
if (copy_from_user(&header, argp, sizeof(header)))
return -EFAULT;
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);
if (ret)
return ret;
if (copy_to_user(argp, &header, sizeof(header)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCHDR successful\n"); */
return 0;
}
static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_tocentry entry;
u8 requested_format;
int ret;
/* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCENTRY\n"); */
if (copy_from_user(&entry, argp, sizeof(entry)))
return -EFAULT;
requested_format = entry.cdte_format;
if (requested_format != CDROM_MSF && requested_format != CDROM_LBA)
return -EINVAL;
/* make interface to low-level uniform */
entry.cdte_format = CDROM_MSF;
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry);
if (ret)
return ret;
sanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format);
if (copy_to_user(argp, &entry, sizeof(entry)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCENTRY successful\n"); */
return 0;
}
static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_msf msf;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&msf, argp, sizeof(msf)))
return -EFAULT;
return cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf);
}
static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_ti ti;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYTRKIND\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&ti, argp, sizeof(ti)))
return -EFAULT;
ret = check_for_audio_disc(cdi, cdi->ops);
if (ret)
return ret;
return cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti);
}
static int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_volctrl volume;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLCTRL\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&volume, argp, sizeof(volume)))
return -EFAULT;
return cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume);
}
static int cdrom_ioctl_volread(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_volctrl volume;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLREAD\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
ret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume);
if (ret)
return ret;
if (copy_to_user(argp, &volume, sizeof(volume)))
return -EFAULT;
return 0;
}
static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi,
unsigned int cmd)
{
int ret;
cd_dbg(CD_DO_IOCTL, "doing audio ioctl (start/stop/pause/resume)\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
ret = check_for_audio_disc(cdi, cdi->ops);
if (ret)
return ret;
return cdi->ops->audio_ioctl(cdi, cmd, NULL);
}
/*
* Required when we need to use READ_10 to issue other than 2048 block
* reads
*/
static int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
struct modesel_head mh;
memset(&mh, 0, sizeof(mh));
mh.block_desc_length = 0x08;
mh.block_length_med = (size >> 8) & 0xff;
mh.block_length_lo = size & 0xff;
memset(&cgc, 0, sizeof(cgc));
cgc.cmd[0] = 0x15;
cgc.cmd[1] = 1 << 4;
cgc.cmd[4] = 12;
cgc.buflen = sizeof(mh);
cgc.buffer = (char *) &mh;
cgc.data_direction = CGC_DATA_WRITE;
mh.block_desc_length = 0x08;
mh.block_length_med = (size >> 8) & 0xff;
mh.block_length_lo = size & 0xff;
return cdo->generic_packet(cdi, &cgc);
}
static int cdrom_get_track_info(struct cdrom_device_info *cdi,
__u16 track, __u8 type, track_information *ti)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
int ret, buflen;
init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
cgc.cmd[1] = type & 3;
cgc.cmd[4] = (track & 0xff00) >> 8;
cgc.cmd[5] = track & 0xff;
cgc.cmd[8] = 8;
cgc.quiet = 1;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
buflen = be16_to_cpu(ti->track_information_length) +
sizeof(ti->track_information_length);
if (buflen > sizeof(track_information))
buflen = sizeof(track_information);
cgc.cmd[8] = cgc.buflen = buflen;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* return actual fill size */
return buflen;
}
/* return the last written block on the CD-R media. this is for the udf
file system. */
int cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written)
{
struct cdrom_tocentry toc;
disc_information di;
track_information ti;
__u32 last_track;
int ret = -1, ti_size;
if (!CDROM_CAN(CDC_GENERIC_PACKET))
goto use_toc;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < (int)(offsetof(typeof(di), last_track_lsb)
+ sizeof(di.last_track_lsb)))
goto use_toc;
/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
last_track = (di.last_track_msb << 8) | di.last_track_lsb;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < (int)offsetof(typeof(ti), track_start))
goto use_toc;
/* if this track is blank, try the previous. */
if (ti.blank) {
if (last_track == 1)
goto use_toc;
last_track--;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
}
if (ti_size < (int)(offsetof(typeof(ti), track_size)
+ sizeof(ti.track_size)))
goto use_toc;
/* if last recorded field is valid, return it. */
if (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address)
+ sizeof(ti.last_rec_address))) {
*last_written = be32_to_cpu(ti.last_rec_address);
} else {
/* make it up instead */
*last_written = be32_to_cpu(ti.track_start) +
be32_to_cpu(ti.track_size);
if (ti.free_blocks)
*last_written -= (be32_to_cpu(ti.free_blocks) + 7);
}
return 0;
/* this is where we end up if the drive either can't do a
GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if
it doesn't give enough information or fails. then we return
the toc contents. */
use_toc:
toc.cdte_format = CDROM_MSF;
toc.cdte_track = CDROM_LEADOUT;
if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc)))
return ret;
sanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA);
*last_written = toc.cdte_addr.lba;
return 0;
}
/* return the next writable block. also for udf file system. */
static int cdrom_get_next_writable(struct cdrom_device_info *cdi,
long *next_writable)
{
disc_information di;
track_information ti;
__u16 last_track;
int ret, ti_size;
if (!CDROM_CAN(CDC_GENERIC_PACKET))
goto use_last_written;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di), last_track_lsb)
+ sizeof(di.last_track_lsb))
goto use_last_written;
/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
last_track = (di.last_track_msb << 8) | di.last_track_lsb;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start))
goto use_last_written;
/* if this track is blank, try the previous. */
if (ti.blank) {
if (last_track == 1)
goto use_last_written;
last_track--;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < 0)
goto use_last_written;
}
/* if next recordable address field is valid, use it. */
if (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable)
+ sizeof(ti.next_writable)) {
*next_writable = be32_to_cpu(ti.next_writable);
return 0;
}
use_last_written:
ret = cdrom_get_last_written(cdi, next_writable);
if (ret) {
*next_writable = 0;
return ret;
} else {
*next_writable += 7;
return 0;
}
}
static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc,
int cmd)
{
struct scsi_sense_hdr sshdr;
struct cdrom_msf msf;
int blocksize = 0, format = 0, lba;
int ret;
switch (cmd) {
case CDROMREADRAW:
blocksize = CD_FRAMESIZE_RAW;
break;
case CDROMREADMODE1:
blocksize = CD_FRAMESIZE;
format = 2;
break;
case CDROMREADMODE2:
blocksize = CD_FRAMESIZE_RAW0;
break;
}
if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))
return -EFAULT;
lba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0);
/* FIXME: we need upper bound checking, too!! */
if (lba < 0)
return -EINVAL;
cgc->buffer = kzalloc(blocksize, GFP_KERNEL);
if (cgc->buffer == NULL)
return -ENOMEM;
memset(&sshdr, 0, sizeof(sshdr));
cgc->sshdr = &sshdr;
cgc->data_direction = CGC_DATA_READ;
ret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize);
if (ret && sshdr.sense_key == 0x05 &&
sshdr.asc == 0x20 &&
sshdr.ascq == 0x00) {
/*
* SCSI-II devices are not required to support
* READ_CD, so let's try switching block size
*/
/* FIXME: switch back again... */
ret = cdrom_switch_blocksize(cdi, blocksize);
if (ret)
goto out;
cgc->sshdr = NULL;
ret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1);
ret |= cdrom_switch_blocksize(cdi, blocksize);
}
if (!ret && copy_to_user(arg, cgc->buffer, blocksize))
ret = -EFAULT;
out:
kfree(cgc->buffer);
return ret;
}
static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi,
void __user *arg)
{
struct cdrom_read_audio ra;
int lba;
if (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg,
sizeof(ra)))
return -EFAULT;
if (ra.addr_format == CDROM_MSF)
lba = msf_to_lba(ra.addr.msf.minute,
ra.addr.msf.second,
ra.addr.msf.frame);
else if (ra.addr_format == CDROM_LBA)
lba = ra.addr.lba;
else
return -EINVAL;
/* FIXME: we need upper bound checking, too!! */
if (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES)
return -EINVAL;
return cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes);
}
static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
struct cdrom_subchnl q;
u_char requested, back;
if (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q)))
return -EFAULT;
requested = q.cdsc_format;
if (!((requested == CDROM_MSF) ||
(requested == CDROM_LBA)))
return -EINVAL;
ret = cdrom_read_subchannel(cdi, &q, 0);
if (ret)
return ret;
back = q.cdsc_format; /* local copy */
sanitize_format(&q.cdsc_absaddr, &back, requested);
sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
if (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */
return 0;
}
static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct cdrom_msf msf;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))
return -EFAULT;
cgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF;
cgc->cmd[3] = msf.cdmsf_min0;
cgc->cmd[4] = msf.cdmsf_sec0;
cgc->cmd[5] = msf.cdmsf_frame0;
cgc->cmd[6] = msf.cdmsf_min1;
cgc->cmd[7] = msf.cdmsf_sec1;
cgc->cmd[8] = msf.cdmsf_frame1;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct cdrom_blk blk;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYBLK\n");
if (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk)))
return -EFAULT;
cgc->cmd[0] = GPCMD_PLAY_AUDIO_10;
cgc->cmd[2] = (blk.from >> 24) & 0xff;
cgc->cmd[3] = (blk.from >> 16) & 0xff;
cgc->cmd[4] = (blk.from >> 8) & 0xff;
cgc->cmd[5] = blk.from & 0xff;
cgc->cmd[7] = (blk.len >> 8) & 0xff;
cgc->cmd[8] = blk.len & 0xff;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc,
unsigned int cmd)
{
struct cdrom_volctrl volctrl;
unsigned char buffer[32];
char mask[sizeof(buffer)];
unsigned short offset;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLUME\n");
if (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg,
sizeof(volctrl)))
return -EFAULT;
cgc->buffer = buffer;
cgc->buflen = 24;
ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0);
if (ret)
return ret;
/* originally the code depended on buffer[1] to determine
how much data is available for transfer. buffer[1] is
unfortunately ambigious and the only reliable way seem
to be to simply skip over the block descriptor... */
offset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6));
if (offset + 16 > sizeof(buffer))
return -E2BIG;
if (offset + 16 > cgc->buflen) {
cgc->buflen = offset + 16;
ret = cdrom_mode_sense(cdi, cgc,
GPMODE_AUDIO_CTL_PAGE, 0);
if (ret)
return ret;
}
/* sanity check */
if ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE ||
buffer[offset + 1] < 14)
return -EINVAL;
/* now we have the current volume settings. if it was only
a CDROMVOLREAD, return these values */
if (cmd == CDROMVOLREAD) {
volctrl.channel0 = buffer[offset+9];
volctrl.channel1 = buffer[offset+11];
volctrl.channel2 = buffer[offset+13];
volctrl.channel3 = buffer[offset+15];
if (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl,
sizeof(volctrl)))
return -EFAULT;
return 0;
}
/* get the volume mask */
cgc->buffer = mask;
ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1);
if (ret)
return ret;
buffer[offset + 9] = volctrl.channel0 & mask[offset + 9];
buffer[offset + 11] = volctrl.channel1 & mask[offset + 11];
buffer[offset + 13] = volctrl.channel2 & mask[offset + 13];
buffer[offset + 15] = volctrl.channel3 & mask[offset + 15];
/* set volume */
cgc->buffer = buffer + offset - 8;
memset(cgc->buffer, 0, 8);
return cdrom_mode_select(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int cmd)
{
const struct cdrom_device_ops *cdo = cdi->ops;
cd_dbg(CD_DO_IOCTL, "entering CDROMSTART/CDROMSTOP\n");
cgc->cmd[0] = GPCMD_START_STOP_UNIT;
cgc->cmd[1] = 1;
cgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int cmd)
{
const struct cdrom_device_ops *cdo = cdi->ops;
cd_dbg(CD_DO_IOCTL, "entering CDROMPAUSE/CDROMRESUME\n");
cgc->cmd[0] = GPCMD_PAUSE_RESUME;
cgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
int ret;
dvd_struct *s;
int size = sizeof(dvd_struct);
if (!CDROM_CAN(CDC_DVD))
return -ENOSYS;
s = memdup_user(arg, size);
if (IS_ERR(s))
return PTR_ERR(s);
cd_dbg(CD_DO_IOCTL, "entering DVD_READ_STRUCT\n");
ret = dvd_read_struct(cdi, s, cgc);
if (ret)
goto out;
if (copy_to_user(arg, s, size))
ret = -EFAULT;
out:
kfree(s);
return ret;
}
static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
dvd_authinfo ai;
if (!CDROM_CAN(CDC_DVD))
return -ENOSYS;
cd_dbg(CD_DO_IOCTL, "entering DVD_AUTH\n");
if (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai)))
return -EFAULT;
ret = dvd_do_auth(cdi, &ai);
if (ret)
return ret;
if (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai)))
return -EFAULT;
return 0;
}
static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
long next = 0;
cd_dbg(CD_DO_IOCTL, "entering CDROM_NEXT_WRITABLE\n");
ret = cdrom_get_next_writable(cdi, &next);
if (ret)
return ret;
if (copy_to_user((long __user *)arg, &next, sizeof(next)))
return -EFAULT;
return 0;
}
static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
long last = 0;
cd_dbg(CD_DO_IOCTL, "entering CDROM_LAST_WRITTEN\n");
ret = cdrom_get_last_written(cdi, &last);
if (ret)
return ret;
if (copy_to_user((long __user *)arg, &last, sizeof(last)))
return -EFAULT;
return 0;
}
static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,
unsigned long arg)
{
struct packet_command cgc;
void __user *userptr = (void __user *)arg;
memset(&cgc, 0, sizeof(cgc));
/* build a unified command and queue it through
cdo->generic_packet() */
switch (cmd) {
case CDROMREADRAW:
case CDROMREADMODE1:
case CDROMREADMODE2:
return mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd);
case CDROMREADAUDIO:
return mmc_ioctl_cdrom_read_audio(cdi, userptr);
case CDROMSUBCHNL:
return mmc_ioctl_cdrom_subchannel(cdi, userptr);
case CDROMPLAYMSF:
return mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc);
case CDROMPLAYBLK:
return mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc);
case CDROMVOLCTRL:
case CDROMVOLREAD:
return mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd);
case CDROMSTART:
case CDROMSTOP:
return mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd);
case CDROMPAUSE:
case CDROMRESUME:
return mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd);
case DVD_READ_STRUCT:
return mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc);
case DVD_AUTH:
return mmc_ioctl_dvd_auth(cdi, userptr);
case CDROM_NEXT_WRITABLE:
return mmc_ioctl_cdrom_next_writable(cdi, userptr);
case CDROM_LAST_WRITTEN:
return mmc_ioctl_cdrom_last_written(cdi, userptr);
}
return -ENOTTY;
}
/*
* Just about every imaginable ioctl is supported in the Uniform layer
* these days.
* ATAPI / SCSI specific code now mainly resides in mmc_ioctl().
*/
int cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev,
fmode_t mode, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int ret;
/*
* Try the generic SCSI command ioctl's first.
*/
ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp);
if (ret != -ENOTTY)
return ret;
switch (cmd) {
case CDROMMULTISESSION:
return cdrom_ioctl_multisession(cdi, argp);
case CDROMEJECT:
return cdrom_ioctl_eject(cdi);
case CDROMCLOSETRAY:
return cdrom_ioctl_closetray(cdi);
case CDROMEJECT_SW:
return cdrom_ioctl_eject_sw(cdi, arg);
case CDROM_MEDIA_CHANGED:
return cdrom_ioctl_media_changed(cdi, arg);
case CDROM_SET_OPTIONS:
return cdrom_ioctl_set_options(cdi, arg);
case CDROM_CLEAR_OPTIONS:
return cdrom_ioctl_clear_options(cdi, arg);
case CDROM_SELECT_SPEED:
return cdrom_ioctl_select_speed(cdi, arg);
case CDROM_SELECT_DISC:
return cdrom_ioctl_select_disc(cdi, arg);
case CDROMRESET:
return cdrom_ioctl_reset(cdi, bdev);
case CDROM_LOCKDOOR:
return cdrom_ioctl_lock_door(cdi, arg);
case CDROM_DEBUG:
return cdrom_ioctl_debug(cdi, arg);
case CDROM_GET_CAPABILITY:
return cdrom_ioctl_get_capability(cdi);
case CDROM_GET_MCN:
return cdrom_ioctl_get_mcn(cdi, argp);
case CDROM_DRIVE_STATUS:
return cdrom_ioctl_drive_status(cdi, arg);
case CDROM_DISC_STATUS:
return cdrom_ioctl_disc_status(cdi);
case CDROM_CHANGER_NSLOTS:
return cdrom_ioctl_changer_nslots(cdi);
}
/*
* Use the ioctls that are implemented through the generic_packet()
* interface. this may look at bit funny, but if -ENOTTY is
* returned that particular ioctl is not implemented and we
* let it go through the device specific ones.
*/
if (CDROM_CAN(CDC_GENERIC_PACKET)) {
ret = mmc_ioctl(cdi, cmd, arg);
if (ret != -ENOTTY)
return ret;
}
/*
* Note: most of the cd_dbg() calls are commented out here,
* because they fill up the sys log when CD players poll
* the drive.
*/
switch (cmd) {
case CDROMSUBCHNL:
return cdrom_ioctl_get_subchnl(cdi, argp);
case CDROMREADTOCHDR:
return cdrom_ioctl_read_tochdr(cdi, argp);
case CDROMREADTOCENTRY:
return cdrom_ioctl_read_tocentry(cdi, argp);
case CDROMPLAYMSF:
return cdrom_ioctl_play_msf(cdi, argp);
case CDROMPLAYTRKIND:
return cdrom_ioctl_play_trkind(cdi, argp);
case CDROMVOLCTRL:
return cdrom_ioctl_volctrl(cdi, argp);
case CDROMVOLREAD:
return cdrom_ioctl_volread(cdi, argp);
case CDROMSTART:
case CDROMSTOP:
case CDROMPAUSE:
case CDROMRESUME:
return cdrom_ioctl_audioctl(cdi, cmd);
}
return -ENOSYS;
}
EXPORT_SYMBOL(cdrom_get_last_written);
EXPORT_SYMBOL(register_cdrom);
EXPORT_SYMBOL(unregister_cdrom);
EXPORT_SYMBOL(cdrom_open);
EXPORT_SYMBOL(cdrom_release);
EXPORT_SYMBOL(cdrom_ioctl);
EXPORT_SYMBOL(cdrom_media_changed);
EXPORT_SYMBOL(cdrom_number_of_slots);
EXPORT_SYMBOL(cdrom_mode_select);
EXPORT_SYMBOL(cdrom_mode_sense);
EXPORT_SYMBOL(init_cdrom_command);
EXPORT_SYMBOL(cdrom_get_media_event);
#ifdef CONFIG_SYSCTL
#define CDROM_STR_SIZE 1000
static struct cdrom_sysctl_settings {
char info[CDROM_STR_SIZE]; /* general info */
int autoclose; /* close tray upon mount, etc */
int autoeject; /* eject on umount */
int debug; /* turn on debugging messages */
int lock; /* lock the door on device open */
int check; /* check media type */
} cdrom_sysctl_settings;
enum cdrom_print_option {
CTL_NAME,
CTL_SPEED,
CTL_SLOTS,
CTL_CAPABILITY
};
static int cdrom_print_info(const char *header, int val, char *info,
int *pos, enum cdrom_print_option option)
{
const int max_size = sizeof(cdrom_sysctl_settings.info);
struct cdrom_device_info *cdi;
int ret;
ret = scnprintf(info + *pos, max_size - *pos, header);
if (!ret)
return 1;
*pos += ret;
list_for_each_entry(cdi, &cdrom_list, list) {
switch (option) {
case CTL_NAME:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%s", cdi->name);
break;
case CTL_SPEED:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", cdi->speed);
break;
case CTL_SLOTS:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", cdi->capacity);
break;
case CTL_CAPABILITY:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", CDROM_CAN(val) != 0);
break;
default:
pr_info("invalid option%d\n", option);
return 1;
}
if (!ret)
return 1;
*pos += ret;
}
return 0;
}
static int cdrom_sysctl_info(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int pos;
char *info = cdrom_sysctl_settings.info;
const int max_size = sizeof(cdrom_sysctl_settings.info);
if (!*lenp || (*ppos && !write)) {
*lenp = 0;
return 0;
}
mutex_lock(&cdrom_mutex);
pos = sprintf(info, "CD-ROM information, " VERSION "\n");
if (cdrom_print_info("\ndrive name:\t", 0, info, &pos, CTL_NAME))
goto done;
if (cdrom_print_info("\ndrive speed:\t", 0, info, &pos, CTL_SPEED))
goto done;
if (cdrom_print_info("\ndrive # of slots:", 0, info, &pos, CTL_SLOTS))
goto done;
if (cdrom_print_info("\nCan close tray:\t",
CDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan open tray:\t",
CDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan lock tray:\t",
CDC_LOCK, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan change speed:",
CDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan select disk:",
CDC_SELECT_DISC, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read multisession:",
CDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read MCN:\t",
CDC_MCN, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nReports media changed:",
CDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan play audio:\t",
CDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write CD-R:\t",
CDC_CD_R, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write CD-RW:",
CDC_CD_RW, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read DVD:\t",
CDC_DVD, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write DVD-R:",
CDC_DVD_R, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write DVD-RAM:",
CDC_DVD_RAM, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read MRW:\t",
CDC_MRW, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write MRW:\t",
CDC_MRW_W, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write RAM:\t",
CDC_RAM, info, &pos, CTL_CAPABILITY))
goto done;
if (!scnprintf(info + pos, max_size - pos, "\n\n"))
goto done;
doit:
mutex_unlock(&cdrom_mutex);
return proc_dostring(ctl, write, buffer, lenp, ppos);
done:
pr_info("info buffer too small\n");
goto doit;
}
/* Unfortunately, per device settings are not implemented through
procfs/sysctl yet. When they are, this will naturally disappear. For now
just update all drives. Later this will become the template on which
new registered drives will be based. */
static void cdrom_update_settings(void)
{
struct cdrom_device_info *cdi;
mutex_lock(&cdrom_mutex);
list_for_each_entry(cdi, &cdrom_list, list) {
if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY))
cdi->options |= CDO_AUTO_CLOSE;
else if (!autoclose)
cdi->options &= ~CDO_AUTO_CLOSE;
if (autoeject && CDROM_CAN(CDC_OPEN_TRAY))
cdi->options |= CDO_AUTO_EJECT;
else if (!autoeject)
cdi->options &= ~CDO_AUTO_EJECT;
if (lockdoor && CDROM_CAN(CDC_LOCK))
cdi->options |= CDO_LOCK;
else if (!lockdoor)
cdi->options &= ~CDO_LOCK;
if (check_media_type)
cdi->options |= CDO_CHECK_TYPE;
else
cdi->options &= ~CDO_CHECK_TYPE;
}
mutex_unlock(&cdrom_mutex);
}
static int cdrom_sysctl_handler(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int ret;
ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
if (write) {
/* we only care for 1 or 0. */
autoclose = !!cdrom_sysctl_settings.autoclose;
autoeject = !!cdrom_sysctl_settings.autoeject;
debug = !!cdrom_sysctl_settings.debug;
lockdoor = !!cdrom_sysctl_settings.lock;
check_media_type = !!cdrom_sysctl_settings.check;
/* update the option flags according to the changes. we
don't have per device options through sysctl yet,
but we will have and then this will disappear. */
cdrom_update_settings();
}
return ret;
}
/* Place files in /proc/sys/dev/cdrom */
static struct ctl_table cdrom_table[] = {
{
.procname = "info",
.data = &cdrom_sysctl_settings.info,
.maxlen = CDROM_STR_SIZE,
.mode = 0444,
.proc_handler = cdrom_sysctl_info,
},
{
.procname = "autoclose",
.data = &cdrom_sysctl_settings.autoclose,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "autoeject",
.data = &cdrom_sysctl_settings.autoeject,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "debug",
.data = &cdrom_sysctl_settings.debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "lock",
.data = &cdrom_sysctl_settings.lock,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "check_media",
.data = &cdrom_sysctl_settings.check,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler
},
{ }
};
static struct ctl_table cdrom_cdrom_table[] = {
{
.procname = "cdrom",
.maxlen = 0,
.mode = 0555,
.child = cdrom_table,
},
{ }
};
/* Make sure that /proc/sys/dev is there */
static struct ctl_table cdrom_root_table[] = {
{
.procname = "dev",
.maxlen = 0,
.mode = 0555,
.child = cdrom_cdrom_table,
},
{ }
};
static struct ctl_table_header *cdrom_sysctl_header;
static void cdrom_sysctl_register(void)
{
static int initialized;
if (initialized == 1)
return;
cdrom_sysctl_header = register_sysctl_table(cdrom_root_table);
/* set the defaults */
cdrom_sysctl_settings.autoclose = autoclose;
cdrom_sysctl_settings.autoeject = autoeject;
cdrom_sysctl_settings.debug = debug;
cdrom_sysctl_settings.lock = lockdoor;
cdrom_sysctl_settings.check = check_media_type;
initialized = 1;
}
static void cdrom_sysctl_unregister(void)
{
if (cdrom_sysctl_header)
unregister_sysctl_table(cdrom_sysctl_header);
}
#else /* CONFIG_SYSCTL */
static void cdrom_sysctl_register(void)
{
}
static void cdrom_sysctl_unregister(void)
{
}
#endif /* CONFIG_SYSCTL */
static int __init cdrom_init(void)
{
cdrom_sysctl_register();
return 0;
}
static void __exit cdrom_exit(void)
{
pr_info("Uniform CD-ROM driver unloaded\n");
cdrom_sysctl_unregister();
}
module_init(cdrom_init);
module_exit(cdrom_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_432_0 |
crossvul-cpp_data_good_3769_2 | /*
* linux/fs/exec.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* #!-checking implemented by tytso.
*/
/*
* Demand-loading implemented 01.12.91 - no need to read anything but
* the header into memory. The inode of the executable is put into
* "current->executable", and page faults do the actual loading. Clean.
*
* Once more I can proudly say that linux stood up to being changed: it
* was less than 2 hours work to get demand-loading completely implemented.
*
* Demand loading changed July 1993 by Eric Youngdale. Use mmap instead,
* current->executable is only used by the procfs. This allows a dispatch
* table to check for several different types of binary formats. We keep
* trying until we recognize the file or we run out of supported binary
* formats.
*/
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/mm.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/swap.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/perf_event.h>
#include <linux/highmem.h>
#include <linux/spinlock.h>
#include <linux/key.h>
#include <linux/personality.h>
#include <linux/binfmts.h>
#include <linux/utsname.h>
#include <linux/pid_namespace.h>
#include <linux/module.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/audit.h>
#include <linux/tracehook.h>
#include <linux/kmod.h>
#include <linux/fsnotify.h>
#include <linux/fs_struct.h>
#include <linux/pipe_fs_i.h>
#include <linux/oom.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/tlb.h>
#include <trace/events/task.h>
#include "internal.h"
#include "coredump.h"
#include <trace/events/sched.h>
int suid_dumpable = 0;
static LIST_HEAD(formats);
static DEFINE_RWLOCK(binfmt_lock);
void __register_binfmt(struct linux_binfmt * fmt, int insert)
{
BUG_ON(!fmt);
write_lock(&binfmt_lock);
insert ? list_add(&fmt->lh, &formats) :
list_add_tail(&fmt->lh, &formats);
write_unlock(&binfmt_lock);
}
EXPORT_SYMBOL(__register_binfmt);
void unregister_binfmt(struct linux_binfmt * fmt)
{
write_lock(&binfmt_lock);
list_del(&fmt->lh);
write_unlock(&binfmt_lock);
}
EXPORT_SYMBOL(unregister_binfmt);
static inline void put_binfmt(struct linux_binfmt * fmt)
{
module_put(fmt->module);
}
/*
* Note that a shared library must be both readable and executable due to
* security reasons.
*
* Also note that we take the address to load from from the file itself.
*/
SYSCALL_DEFINE1(uselib, const char __user *, library)
{
struct file *file;
struct filename *tmp = getname(library);
int error = PTR_ERR(tmp);
static const struct open_flags uselib_flags = {
.open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
.acc_mode = MAY_READ | MAY_EXEC | MAY_OPEN,
.intent = LOOKUP_OPEN
};
if (IS_ERR(tmp))
goto out;
file = do_filp_open(AT_FDCWD, tmp, &uselib_flags, LOOKUP_FOLLOW);
putname(tmp);
error = PTR_ERR(file);
if (IS_ERR(file))
goto out;
error = -EINVAL;
if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
goto exit;
error = -EACCES;
if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
goto exit;
fsnotify_open(file);
error = -ENOEXEC;
if(file->f_op) {
struct linux_binfmt * fmt;
read_lock(&binfmt_lock);
list_for_each_entry(fmt, &formats, lh) {
if (!fmt->load_shlib)
continue;
if (!try_module_get(fmt->module))
continue;
read_unlock(&binfmt_lock);
error = fmt->load_shlib(file);
read_lock(&binfmt_lock);
put_binfmt(fmt);
if (error != -ENOEXEC)
break;
}
read_unlock(&binfmt_lock);
}
exit:
fput(file);
out:
return error;
}
#ifdef CONFIG_MMU
/*
* The nascent bprm->mm is not visible until exec_mmap() but it can
* use a lot of memory, account these pages in current->mm temporary
* for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we
* change the counter back via acct_arg_size(0).
*/
static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
{
struct mm_struct *mm = current->mm;
long diff = (long)(pages - bprm->vma_pages);
if (!mm || !diff)
return;
bprm->vma_pages = pages;
add_mm_counter(mm, MM_ANONPAGES, diff);
}
static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
int write)
{
struct page *page;
int ret;
#ifdef CONFIG_STACK_GROWSUP
if (write) {
ret = expand_downwards(bprm->vma, pos);
if (ret < 0)
return NULL;
}
#endif
ret = get_user_pages(current, bprm->mm, pos,
1, write, 1, &page, NULL);
if (ret <= 0)
return NULL;
if (write) {
unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
struct rlimit *rlim;
acct_arg_size(bprm, size / PAGE_SIZE);
/*
* We've historically supported up to 32 pages (ARG_MAX)
* of argument strings even with small stacks
*/
if (size <= ARG_MAX)
return page;
/*
* Limit to 1/4-th the stack size for the argv+env strings.
* This ensures that:
* - the remaining binfmt code will not run out of stack space,
* - the program will have a reasonable amount of stack left
* to work from.
*/
rlim = current->signal->rlim;
if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur) / 4) {
put_page(page);
return NULL;
}
}
return page;
}
static void put_arg_page(struct page *page)
{
put_page(page);
}
static void free_arg_page(struct linux_binprm *bprm, int i)
{
}
static void free_arg_pages(struct linux_binprm *bprm)
{
}
static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
struct page *page)
{
flush_cache_page(bprm->vma, pos, page_to_pfn(page));
}
static int __bprm_mm_init(struct linux_binprm *bprm)
{
int err;
struct vm_area_struct *vma = NULL;
struct mm_struct *mm = bprm->mm;
bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (!vma)
return -ENOMEM;
down_write(&mm->mmap_sem);
vma->vm_mm = mm;
/*
* Place the stack at the largest stack address the architecture
* supports. Later, we'll move this to an appropriate place. We don't
* use STACK_TOP because that can depend on attributes which aren't
* configured yet.
*/
BUILD_BUG_ON(VM_STACK_FLAGS & VM_STACK_INCOMPLETE_SETUP);
vma->vm_end = STACK_TOP_MAX;
vma->vm_start = vma->vm_end - PAGE_SIZE;
vma->vm_flags = VM_STACK_FLAGS | VM_STACK_INCOMPLETE_SETUP;
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
INIT_LIST_HEAD(&vma->anon_vma_chain);
err = insert_vm_struct(mm, vma);
if (err)
goto err;
mm->stack_vm = mm->total_vm = 1;
up_write(&mm->mmap_sem);
bprm->p = vma->vm_end - sizeof(void *);
return 0;
err:
up_write(&mm->mmap_sem);
bprm->vma = NULL;
kmem_cache_free(vm_area_cachep, vma);
return err;
}
static bool valid_arg_len(struct linux_binprm *bprm, long len)
{
return len <= MAX_ARG_STRLEN;
}
#else
static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
{
}
static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
int write)
{
struct page *page;
page = bprm->page[pos / PAGE_SIZE];
if (!page && write) {
page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
if (!page)
return NULL;
bprm->page[pos / PAGE_SIZE] = page;
}
return page;
}
static void put_arg_page(struct page *page)
{
}
static void free_arg_page(struct linux_binprm *bprm, int i)
{
if (bprm->page[i]) {
__free_page(bprm->page[i]);
bprm->page[i] = NULL;
}
}
static void free_arg_pages(struct linux_binprm *bprm)
{
int i;
for (i = 0; i < MAX_ARG_PAGES; i++)
free_arg_page(bprm, i);
}
static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
struct page *page)
{
}
static int __bprm_mm_init(struct linux_binprm *bprm)
{
bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
return 0;
}
static bool valid_arg_len(struct linux_binprm *bprm, long len)
{
return len <= bprm->p;
}
#endif /* CONFIG_MMU */
/*
* Create a new mm_struct and populate it with a temporary stack
* vm_area_struct. We don't have enough context at this point to set the stack
* flags, permissions, and offset, so we use temporary values. We'll update
* them later in setup_arg_pages().
*/
int bprm_mm_init(struct linux_binprm *bprm)
{
int err;
struct mm_struct *mm = NULL;
bprm->mm = mm = mm_alloc();
err = -ENOMEM;
if (!mm)
goto err;
err = init_new_context(current, mm);
if (err)
goto err;
err = __bprm_mm_init(bprm);
if (err)
goto err;
return 0;
err:
if (mm) {
bprm->mm = NULL;
mmdrop(mm);
}
return err;
}
struct user_arg_ptr {
#ifdef CONFIG_COMPAT
bool is_compat;
#endif
union {
const char __user *const __user *native;
#ifdef CONFIG_COMPAT
const compat_uptr_t __user *compat;
#endif
} ptr;
};
static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr)
{
const char __user *native;
#ifdef CONFIG_COMPAT
if (unlikely(argv.is_compat)) {
compat_uptr_t compat;
if (get_user(compat, argv.ptr.compat + nr))
return ERR_PTR(-EFAULT);
return compat_ptr(compat);
}
#endif
if (get_user(native, argv.ptr.native + nr))
return ERR_PTR(-EFAULT);
return native;
}
/*
* count() counts the number of strings in array ARGV.
*/
static int count(struct user_arg_ptr argv, int max)
{
int i = 0;
if (argv.ptr.native != NULL) {
for (;;) {
const char __user *p = get_user_arg_ptr(argv, i);
if (!p)
break;
if (IS_ERR(p))
return -EFAULT;
if (i++ >= max)
return -E2BIG;
if (fatal_signal_pending(current))
return -ERESTARTNOHAND;
cond_resched();
}
}
return i;
}
/*
* 'copy_strings()' copies argument/environment strings from the old
* processes's memory to the new process's stack. The call to get_user_pages()
* ensures the destination page is created and not swapped out.
*/
static int copy_strings(int argc, struct user_arg_ptr argv,
struct linux_binprm *bprm)
{
struct page *kmapped_page = NULL;
char *kaddr = NULL;
unsigned long kpos = 0;
int ret;
while (argc-- > 0) {
const char __user *str;
int len;
unsigned long pos;
ret = -EFAULT;
str = get_user_arg_ptr(argv, argc);
if (IS_ERR(str))
goto out;
len = strnlen_user(str, MAX_ARG_STRLEN);
if (!len)
goto out;
ret = -E2BIG;
if (!valid_arg_len(bprm, len))
goto out;
/* We're going to work our way backwords. */
pos = bprm->p;
str += len;
bprm->p -= len;
while (len > 0) {
int offset, bytes_to_copy;
if (fatal_signal_pending(current)) {
ret = -ERESTARTNOHAND;
goto out;
}
cond_resched();
offset = pos % PAGE_SIZE;
if (offset == 0)
offset = PAGE_SIZE;
bytes_to_copy = offset;
if (bytes_to_copy > len)
bytes_to_copy = len;
offset -= bytes_to_copy;
pos -= bytes_to_copy;
str -= bytes_to_copy;
len -= bytes_to_copy;
if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
struct page *page;
page = get_arg_page(bprm, pos, 1);
if (!page) {
ret = -E2BIG;
goto out;
}
if (kmapped_page) {
flush_kernel_dcache_page(kmapped_page);
kunmap(kmapped_page);
put_arg_page(kmapped_page);
}
kmapped_page = page;
kaddr = kmap(kmapped_page);
kpos = pos & PAGE_MASK;
flush_arg_page(bprm, kpos, kmapped_page);
}
if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
ret = -EFAULT;
goto out;
}
}
}
ret = 0;
out:
if (kmapped_page) {
flush_kernel_dcache_page(kmapped_page);
kunmap(kmapped_page);
put_arg_page(kmapped_page);
}
return ret;
}
/*
* Like copy_strings, but get argv and its values from kernel memory.
*/
int copy_strings_kernel(int argc, const char *const *__argv,
struct linux_binprm *bprm)
{
int r;
mm_segment_t oldfs = get_fs();
struct user_arg_ptr argv = {
.ptr.native = (const char __user *const __user *)__argv,
};
set_fs(KERNEL_DS);
r = copy_strings(argc, argv, bprm);
set_fs(oldfs);
return r;
}
EXPORT_SYMBOL(copy_strings_kernel);
#ifdef CONFIG_MMU
/*
* During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once
* the binfmt code determines where the new stack should reside, we shift it to
* its final location. The process proceeds as follows:
*
* 1) Use shift to calculate the new vma endpoints.
* 2) Extend vma to cover both the old and new ranges. This ensures the
* arguments passed to subsequent functions are consistent.
* 3) Move vma's page tables to the new range.
* 4) Free up any cleared pgd range.
* 5) Shrink the vma to cover only the new range.
*/
static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long old_start = vma->vm_start;
unsigned long old_end = vma->vm_end;
unsigned long length = old_end - old_start;
unsigned long new_start = old_start - shift;
unsigned long new_end = old_end - shift;
struct mmu_gather tlb;
BUG_ON(new_start > new_end);
/*
* ensure there are no vmas between where we want to go
* and where we are
*/
if (vma != find_vma(mm, new_start))
return -EFAULT;
/*
* cover the whole range: [new_start, old_end)
*/
if (vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL))
return -ENOMEM;
/*
* move the page tables downwards, on failure we rely on
* process cleanup to remove whatever mess we made.
*/
if (length != move_page_tables(vma, old_start,
vma, new_start, length, false))
return -ENOMEM;
lru_add_drain();
tlb_gather_mmu(&tlb, mm, 0);
if (new_end > old_start) {
/*
* when the old and new regions overlap clear from new_end.
*/
free_pgd_range(&tlb, new_end, old_end, new_end,
vma->vm_next ? vma->vm_next->vm_start : 0);
} else {
/*
* otherwise, clean from old_start; this is done to not touch
* the address space in [new_end, old_start) some architectures
* have constraints on va-space that make this illegal (IA64) -
* for the others its just a little faster.
*/
free_pgd_range(&tlb, old_start, old_end, new_end,
vma->vm_next ? vma->vm_next->vm_start : 0);
}
tlb_finish_mmu(&tlb, new_end, old_end);
/*
* Shrink the vma to just the new range. Always succeeds.
*/
vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL);
return 0;
}
/*
* Finalizes the stack vm_area_struct. The flags and permissions are updated,
* the stack is optionally relocated, and some extra space is added.
*/
int setup_arg_pages(struct linux_binprm *bprm,
unsigned long stack_top,
int executable_stack)
{
unsigned long ret;
unsigned long stack_shift;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = bprm->vma;
struct vm_area_struct *prev = NULL;
unsigned long vm_flags;
unsigned long stack_base;
unsigned long stack_size;
unsigned long stack_expand;
unsigned long rlim_stack;
#ifdef CONFIG_STACK_GROWSUP
/* Limit stack size to 1GB */
stack_base = rlimit_max(RLIMIT_STACK);
if (stack_base > (1 << 30))
stack_base = 1 << 30;
/* Make sure we didn't let the argument array grow too large. */
if (vma->vm_end - vma->vm_start > stack_base)
return -ENOMEM;
stack_base = PAGE_ALIGN(stack_top - stack_base);
stack_shift = vma->vm_start - stack_base;
mm->arg_start = bprm->p - stack_shift;
bprm->p = vma->vm_end - stack_shift;
#else
stack_top = arch_align_stack(stack_top);
stack_top = PAGE_ALIGN(stack_top);
if (unlikely(stack_top < mmap_min_addr) ||
unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr))
return -ENOMEM;
stack_shift = vma->vm_end - stack_top;
bprm->p -= stack_shift;
mm->arg_start = bprm->p;
#endif
if (bprm->loader)
bprm->loader -= stack_shift;
bprm->exec -= stack_shift;
down_write(&mm->mmap_sem);
vm_flags = VM_STACK_FLAGS;
/*
* Adjust stack execute permissions; explicitly enable for
* EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
* (arch default) otherwise.
*/
if (unlikely(executable_stack == EXSTACK_ENABLE_X))
vm_flags |= VM_EXEC;
else if (executable_stack == EXSTACK_DISABLE_X)
vm_flags &= ~VM_EXEC;
vm_flags |= mm->def_flags;
vm_flags |= VM_STACK_INCOMPLETE_SETUP;
ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end,
vm_flags);
if (ret)
goto out_unlock;
BUG_ON(prev != vma);
/* Move stack pages down in memory. */
if (stack_shift) {
ret = shift_arg_pages(vma, stack_shift);
if (ret)
goto out_unlock;
}
/* mprotect_fixup is overkill to remove the temporary stack flags */
vma->vm_flags &= ~VM_STACK_INCOMPLETE_SETUP;
stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */
stack_size = vma->vm_end - vma->vm_start;
/*
* Align this down to a page boundary as expand_stack
* will align it up.
*/
rlim_stack = rlimit(RLIMIT_STACK) & PAGE_MASK;
#ifdef CONFIG_STACK_GROWSUP
if (stack_size + stack_expand > rlim_stack)
stack_base = vma->vm_start + rlim_stack;
else
stack_base = vma->vm_end + stack_expand;
#else
if (stack_size + stack_expand > rlim_stack)
stack_base = vma->vm_end - rlim_stack;
else
stack_base = vma->vm_start - stack_expand;
#endif
current->mm->start_stack = bprm->p;
ret = expand_stack(vma, stack_base);
if (ret)
ret = -EFAULT;
out_unlock:
up_write(&mm->mmap_sem);
return ret;
}
EXPORT_SYMBOL(setup_arg_pages);
#endif /* CONFIG_MMU */
struct file *open_exec(const char *name)
{
struct file *file;
int err;
struct filename tmp = { .name = name };
static const struct open_flags open_exec_flags = {
.open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
.acc_mode = MAY_EXEC | MAY_OPEN,
.intent = LOOKUP_OPEN
};
file = do_filp_open(AT_FDCWD, &tmp, &open_exec_flags, LOOKUP_FOLLOW);
if (IS_ERR(file))
goto out;
err = -EACCES;
if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
goto exit;
if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
goto exit;
fsnotify_open(file);
err = deny_write_access(file);
if (err)
goto exit;
out:
return file;
exit:
fput(file);
return ERR_PTR(err);
}
EXPORT_SYMBOL(open_exec);
int kernel_read(struct file *file, loff_t offset,
char *addr, unsigned long count)
{
mm_segment_t old_fs;
loff_t pos = offset;
int result;
old_fs = get_fs();
set_fs(get_ds());
/* The cast to a user pointer is valid due to the set_fs() */
result = vfs_read(file, (void __user *)addr, count, &pos);
set_fs(old_fs);
return result;
}
EXPORT_SYMBOL(kernel_read);
static int exec_mmap(struct mm_struct *mm)
{
struct task_struct *tsk;
struct mm_struct * old_mm, *active_mm;
/* Notify parent that we're no longer interested in the old VM */
tsk = current;
old_mm = current->mm;
mm_release(tsk, old_mm);
if (old_mm) {
sync_mm_rss(old_mm);
/*
* Make sure that if there is a core dump in progress
* for the old mm, we get out and die instead of going
* through with the exec. We must hold mmap_sem around
* checking core_state and changing tsk->mm.
*/
down_read(&old_mm->mmap_sem);
if (unlikely(old_mm->core_state)) {
up_read(&old_mm->mmap_sem);
return -EINTR;
}
}
task_lock(tsk);
active_mm = tsk->active_mm;
tsk->mm = mm;
tsk->active_mm = mm;
activate_mm(active_mm, mm);
task_unlock(tsk);
arch_pick_mmap_layout(mm);
if (old_mm) {
up_read(&old_mm->mmap_sem);
BUG_ON(active_mm != old_mm);
setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
mm_update_next_owner(old_mm);
mmput(old_mm);
return 0;
}
mmdrop(active_mm);
return 0;
}
/*
* This function makes sure the current process has its own signal table,
* so that flush_signal_handlers can later reset the handlers without
* disturbing other processes. (Other processes might share the signal
* table via the CLONE_SIGHAND option to clone().)
*/
static int de_thread(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
struct sighand_struct *oldsighand = tsk->sighand;
spinlock_t *lock = &oldsighand->siglock;
if (thread_group_empty(tsk))
goto no_thread_group;
/*
* Kill all other threads in the thread group.
*/
spin_lock_irq(lock);
if (signal_group_exit(sig)) {
/*
* Another group action in progress, just
* return so that the signal is processed.
*/
spin_unlock_irq(lock);
return -EAGAIN;
}
sig->group_exit_task = tsk;
sig->notify_count = zap_other_threads(tsk);
if (!thread_group_leader(tsk))
sig->notify_count--;
while (sig->notify_count) {
__set_current_state(TASK_KILLABLE);
spin_unlock_irq(lock);
schedule();
if (unlikely(__fatal_signal_pending(tsk)))
goto killed;
spin_lock_irq(lock);
}
spin_unlock_irq(lock);
/*
* At this point all other threads have exited, all we have to
* do is to wait for the thread group leader to become inactive,
* and to assume its PID:
*/
if (!thread_group_leader(tsk)) {
struct task_struct *leader = tsk->group_leader;
sig->notify_count = -1; /* for exit_notify() */
for (;;) {
write_lock_irq(&tasklist_lock);
if (likely(leader->exit_state))
break;
__set_current_state(TASK_KILLABLE);
write_unlock_irq(&tasklist_lock);
schedule();
if (unlikely(__fatal_signal_pending(tsk)))
goto killed;
}
/*
* The only record we have of the real-time age of a
* process, regardless of execs it's done, is start_time.
* All the past CPU time is accumulated in signal_struct
* from sister threads now dead. But in this non-leader
* exec, nothing survives from the original leader thread,
* whose birth marks the true age of this process now.
* When we take on its identity by switching to its PID, we
* also take its birthdate (always earlier than our own).
*/
tsk->start_time = leader->start_time;
BUG_ON(!same_thread_group(leader, tsk));
BUG_ON(has_group_leader_pid(tsk));
/*
* An exec() starts a new thread group with the
* TGID of the previous thread group. Rehash the
* two threads with a switched PID, and release
* the former thread group leader:
*/
/* Become a process group leader with the old leader's pid.
* The old leader becomes a thread of the this thread group.
* Note: The old leader also uses this pid until release_task
* is called. Odd but simple and correct.
*/
detach_pid(tsk, PIDTYPE_PID);
tsk->pid = leader->pid;
attach_pid(tsk, PIDTYPE_PID, task_pid(leader));
transfer_pid(leader, tsk, PIDTYPE_PGID);
transfer_pid(leader, tsk, PIDTYPE_SID);
list_replace_rcu(&leader->tasks, &tsk->tasks);
list_replace_init(&leader->sibling, &tsk->sibling);
tsk->group_leader = tsk;
leader->group_leader = tsk;
tsk->exit_signal = SIGCHLD;
leader->exit_signal = -1;
BUG_ON(leader->exit_state != EXIT_ZOMBIE);
leader->exit_state = EXIT_DEAD;
/*
* We are going to release_task()->ptrace_unlink() silently,
* the tracer can sleep in do_wait(). EXIT_DEAD guarantees
* the tracer wont't block again waiting for this thread.
*/
if (unlikely(leader->ptrace))
__wake_up_parent(leader, leader->parent);
write_unlock_irq(&tasklist_lock);
release_task(leader);
}
sig->group_exit_task = NULL;
sig->notify_count = 0;
no_thread_group:
/* we have changed execution domain */
tsk->exit_signal = SIGCHLD;
exit_itimers(sig);
flush_itimer_signals();
if (atomic_read(&oldsighand->count) != 1) {
struct sighand_struct *newsighand;
/*
* This ->sighand is shared with the CLONE_SIGHAND
* but not CLONE_THREAD task, switch to the new one.
*/
newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
if (!newsighand)
return -ENOMEM;
atomic_set(&newsighand->count, 1);
memcpy(newsighand->action, oldsighand->action,
sizeof(newsighand->action));
write_lock_irq(&tasklist_lock);
spin_lock(&oldsighand->siglock);
rcu_assign_pointer(tsk->sighand, newsighand);
spin_unlock(&oldsighand->siglock);
write_unlock_irq(&tasklist_lock);
__cleanup_sighand(oldsighand);
}
BUG_ON(!thread_group_leader(tsk));
return 0;
killed:
/* protects against exit_notify() and __exit_signal() */
read_lock(&tasklist_lock);
sig->group_exit_task = NULL;
sig->notify_count = 0;
read_unlock(&tasklist_lock);
return -EAGAIN;
}
char *get_task_comm(char *buf, struct task_struct *tsk)
{
/* buf must be at least sizeof(tsk->comm) in size */
task_lock(tsk);
strncpy(buf, tsk->comm, sizeof(tsk->comm));
task_unlock(tsk);
return buf;
}
EXPORT_SYMBOL_GPL(get_task_comm);
/*
* These functions flushes out all traces of the currently running executable
* so that a new one can be started
*/
void set_task_comm(struct task_struct *tsk, char *buf)
{
task_lock(tsk);
trace_task_rename(tsk, buf);
/*
* Threads may access current->comm without holding
* the task lock, so write the string carefully.
* Readers without a lock may see incomplete new
* names but are safe from non-terminating string reads.
*/
memset(tsk->comm, 0, TASK_COMM_LEN);
wmb();
strlcpy(tsk->comm, buf, sizeof(tsk->comm));
task_unlock(tsk);
perf_event_comm(tsk);
}
static void filename_to_taskname(char *tcomm, const char *fn, unsigned int len)
{
int i, ch;
/* Copies the binary name from after last slash */
for (i = 0; (ch = *(fn++)) != '\0';) {
if (ch == '/')
i = 0; /* overwrite what we wrote */
else
if (i < len - 1)
tcomm[i++] = ch;
}
tcomm[i] = '\0';
}
int flush_old_exec(struct linux_binprm * bprm)
{
int retval;
/*
* Make sure we have a private signal table and that
* we are unassociated from the previous thread group.
*/
retval = de_thread(current);
if (retval)
goto out;
set_mm_exe_file(bprm->mm, bprm->file);
filename_to_taskname(bprm->tcomm, bprm->filename, sizeof(bprm->tcomm));
/*
* Release all of the old mmap stuff
*/
acct_arg_size(bprm, 0);
retval = exec_mmap(bprm->mm);
if (retval)
goto out;
bprm->mm = NULL; /* We're using it now */
set_fs(USER_DS);
current->flags &=
~(PF_RANDOMIZE | PF_FORKNOEXEC | PF_KTHREAD | PF_NOFREEZE);
flush_thread();
current->personality &= ~bprm->per_clear;
return 0;
out:
return retval;
}
EXPORT_SYMBOL(flush_old_exec);
void would_dump(struct linux_binprm *bprm, struct file *file)
{
if (inode_permission(file->f_path.dentry->d_inode, MAY_READ) < 0)
bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP;
}
EXPORT_SYMBOL(would_dump);
void setup_new_exec(struct linux_binprm * bprm)
{
arch_pick_mmap_layout(current->mm);
/* This is the point of no return */
current->sas_ss_sp = current->sas_ss_size = 0;
if (uid_eq(current_euid(), current_uid()) && gid_eq(current_egid(), current_gid()))
set_dumpable(current->mm, SUID_DUMPABLE_ENABLED);
else
set_dumpable(current->mm, suid_dumpable);
set_task_comm(current, bprm->tcomm);
/* Set the new mm task size. We have to do that late because it may
* depend on TIF_32BIT which is only updated in flush_thread() on
* some architectures like powerpc
*/
current->mm->task_size = TASK_SIZE;
/* install the new credentials */
if (!uid_eq(bprm->cred->uid, current_euid()) ||
!gid_eq(bprm->cred->gid, current_egid())) {
current->pdeath_signal = 0;
} else {
would_dump(bprm, bprm->file);
if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)
set_dumpable(current->mm, suid_dumpable);
}
/*
* Flush performance counters when crossing a
* security domain:
*/
if (!get_dumpable(current->mm))
perf_event_exit_task(current);
/* An exec changes our domain. We are no longer part of the thread
group */
current->self_exec_id++;
flush_signal_handlers(current, 0);
do_close_on_exec(current->files);
}
EXPORT_SYMBOL(setup_new_exec);
/*
* Prepare credentials and lock ->cred_guard_mutex.
* install_exec_creds() commits the new creds and drops the lock.
* Or, if exec fails before, free_bprm() should release ->cred and
* and unlock.
*/
int prepare_bprm_creds(struct linux_binprm *bprm)
{
if (mutex_lock_interruptible(¤t->signal->cred_guard_mutex))
return -ERESTARTNOINTR;
bprm->cred = prepare_exec_creds();
if (likely(bprm->cred))
return 0;
mutex_unlock(¤t->signal->cred_guard_mutex);
return -ENOMEM;
}
void free_bprm(struct linux_binprm *bprm)
{
free_arg_pages(bprm);
if (bprm->cred) {
mutex_unlock(¤t->signal->cred_guard_mutex);
abort_creds(bprm->cred);
}
/* If a binfmt changed the interp, free it. */
if (bprm->interp != bprm->filename)
kfree(bprm->interp);
kfree(bprm);
}
int bprm_change_interp(char *interp, struct linux_binprm *bprm)
{
/* If a binfmt changed the interp, free it first. */
if (bprm->interp != bprm->filename)
kfree(bprm->interp);
bprm->interp = kstrdup(interp, GFP_KERNEL);
if (!bprm->interp)
return -ENOMEM;
return 0;
}
EXPORT_SYMBOL(bprm_change_interp);
/*
* install the new credentials for this executable
*/
void install_exec_creds(struct linux_binprm *bprm)
{
security_bprm_committing_creds(bprm);
commit_creds(bprm->cred);
bprm->cred = NULL;
/*
* cred_guard_mutex must be held at least to this point to prevent
* ptrace_attach() from altering our determination of the task's
* credentials; any time after this it may be unlocked.
*/
security_bprm_committed_creds(bprm);
mutex_unlock(¤t->signal->cred_guard_mutex);
}
EXPORT_SYMBOL(install_exec_creds);
/*
* determine how safe it is to execute the proposed program
* - the caller must hold ->cred_guard_mutex to protect against
* PTRACE_ATTACH
*/
static int check_unsafe_exec(struct linux_binprm *bprm)
{
struct task_struct *p = current, *t;
unsigned n_fs;
int res = 0;
if (p->ptrace) {
if (p->ptrace & PT_PTRACE_CAP)
bprm->unsafe |= LSM_UNSAFE_PTRACE_CAP;
else
bprm->unsafe |= LSM_UNSAFE_PTRACE;
}
/*
* This isn't strictly necessary, but it makes it harder for LSMs to
* mess up.
*/
if (current->no_new_privs)
bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS;
n_fs = 1;
spin_lock(&p->fs->lock);
rcu_read_lock();
for (t = next_thread(p); t != p; t = next_thread(t)) {
if (t->fs == p->fs)
n_fs++;
}
rcu_read_unlock();
if (p->fs->users > n_fs) {
bprm->unsafe |= LSM_UNSAFE_SHARE;
} else {
res = -EAGAIN;
if (!p->fs->in_exec) {
p->fs->in_exec = 1;
res = 1;
}
}
spin_unlock(&p->fs->lock);
return res;
}
/*
* Fill the binprm structure from the inode.
* Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
*
* This may be called multiple times for binary chains (scripts for example).
*/
int prepare_binprm(struct linux_binprm *bprm)
{
umode_t mode;
struct inode * inode = bprm->file->f_path.dentry->d_inode;
int retval;
mode = inode->i_mode;
if (bprm->file->f_op == NULL)
return -EACCES;
/* clear any previous set[ug]id data from a previous binary */
bprm->cred->euid = current_euid();
bprm->cred->egid = current_egid();
if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) &&
!current->no_new_privs &&
kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) &&
kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) {
/* Set-uid? */
if (mode & S_ISUID) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->euid = inode->i_uid;
}
/* Set-gid? */
/*
* If setgid is set but no group execute bit then this
* is a candidate for mandatory locking, not a setgid
* executable.
*/
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->egid = inode->i_gid;
}
}
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
EXPORT_SYMBOL(prepare_binprm);
/*
* Arguments are '\0' separated strings found at the location bprm->p
* points to; chop off the first by relocating brpm->p to right after
* the first '\0' encountered.
*/
int remove_arg_zero(struct linux_binprm *bprm)
{
int ret = 0;
unsigned long offset;
char *kaddr;
struct page *page;
if (!bprm->argc)
return 0;
do {
offset = bprm->p & ~PAGE_MASK;
page = get_arg_page(bprm, bprm->p, 0);
if (!page) {
ret = -EFAULT;
goto out;
}
kaddr = kmap_atomic(page);
for (; offset < PAGE_SIZE && kaddr[offset];
offset++, bprm->p++)
;
kunmap_atomic(kaddr);
put_arg_page(page);
if (offset == PAGE_SIZE)
free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1);
} while (offset == PAGE_SIZE);
bprm->p++;
bprm->argc--;
ret = 0;
out:
return ret;
}
EXPORT_SYMBOL(remove_arg_zero);
/*
* cycle the list of binary formats handler, until one recognizes the image
*/
int search_binary_handler(struct linux_binprm *bprm)
{
unsigned int depth = bprm->recursion_depth;
int try,retval;
struct linux_binfmt *fmt;
pid_t old_pid, old_vpid;
/* This allows 4 levels of binfmt rewrites before failing hard. */
if (depth > 5)
return -ELOOP;
retval = security_bprm_check(bprm);
if (retval)
return retval;
retval = audit_bprm(bprm);
if (retval)
return retval;
/* Need to fetch pid before load_binary changes it */
old_pid = current->pid;
rcu_read_lock();
old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent));
rcu_read_unlock();
retval = -ENOENT;
for (try=0; try<2; try++) {
read_lock(&binfmt_lock);
list_for_each_entry(fmt, &formats, lh) {
int (*fn)(struct linux_binprm *) = fmt->load_binary;
if (!fn)
continue;
if (!try_module_get(fmt->module))
continue;
read_unlock(&binfmt_lock);
bprm->recursion_depth = depth + 1;
retval = fn(bprm);
bprm->recursion_depth = depth;
if (retval >= 0) {
if (depth == 0) {
trace_sched_process_exec(current, old_pid, bprm);
ptrace_event(PTRACE_EVENT_EXEC, old_vpid);
}
put_binfmt(fmt);
allow_write_access(bprm->file);
if (bprm->file)
fput(bprm->file);
bprm->file = NULL;
current->did_exec = 1;
proc_exec_connector(current);
return retval;
}
read_lock(&binfmt_lock);
put_binfmt(fmt);
if (retval != -ENOEXEC || bprm->mm == NULL)
break;
if (!bprm->file) {
read_unlock(&binfmt_lock);
return retval;
}
}
read_unlock(&binfmt_lock);
#ifdef CONFIG_MODULES
if (retval != -ENOEXEC || bprm->mm == NULL) {
break;
} else {
#define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
if (printable(bprm->buf[0]) &&
printable(bprm->buf[1]) &&
printable(bprm->buf[2]) &&
printable(bprm->buf[3]))
break; /* -ENOEXEC */
if (try)
break; /* -ENOEXEC */
request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
}
#else
break;
#endif
}
return retval;
}
EXPORT_SYMBOL(search_binary_handler);
/*
* sys_execve() executes a new program.
*/
static int do_execve_common(const char *filename,
struct user_arg_ptr argv,
struct user_arg_ptr envp)
{
struct linux_binprm *bprm;
struct file *file;
struct files_struct *displaced;
bool clear_in_exec;
int retval;
const struct cred *cred = current_cred();
/*
* We move the actual failure in case of RLIMIT_NPROC excess from
* set*uid() to execve() because too many poorly written programs
* don't check setuid() return code. Here we additionally recheck
* whether NPROC limit is still exceeded.
*/
if ((current->flags & PF_NPROC_EXCEEDED) &&
atomic_read(&cred->user->processes) > rlimit(RLIMIT_NPROC)) {
retval = -EAGAIN;
goto out_ret;
}
/* We're below the limit (still or again), so we don't want to make
* further execve() calls fail. */
current->flags &= ~PF_NPROC_EXCEEDED;
retval = unshare_files(&displaced);
if (retval)
goto out_ret;
retval = -ENOMEM;
bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
if (!bprm)
goto out_files;
retval = prepare_bprm_creds(bprm);
if (retval)
goto out_free;
retval = check_unsafe_exec(bprm);
if (retval < 0)
goto out_free;
clear_in_exec = retval;
current->in_execve = 1;
file = open_exec(filename);
retval = PTR_ERR(file);
if (IS_ERR(file))
goto out_unmark;
sched_exec();
bprm->file = file;
bprm->filename = filename;
bprm->interp = filename;
retval = bprm_mm_init(bprm);
if (retval)
goto out_file;
bprm->argc = count(argv, MAX_ARG_STRINGS);
if ((retval = bprm->argc) < 0)
goto out;
bprm->envc = count(envp, MAX_ARG_STRINGS);
if ((retval = bprm->envc) < 0)
goto out;
retval = prepare_binprm(bprm);
if (retval < 0)
goto out;
retval = copy_strings_kernel(1, &bprm->filename, bprm);
if (retval < 0)
goto out;
bprm->exec = bprm->p;
retval = copy_strings(bprm->envc, envp, bprm);
if (retval < 0)
goto out;
retval = copy_strings(bprm->argc, argv, bprm);
if (retval < 0)
goto out;
retval = search_binary_handler(bprm);
if (retval < 0)
goto out;
/* execve succeeded */
current->fs->in_exec = 0;
current->in_execve = 0;
acct_update_integrals(current);
free_bprm(bprm);
if (displaced)
put_files_struct(displaced);
return retval;
out:
if (bprm->mm) {
acct_arg_size(bprm, 0);
mmput(bprm->mm);
}
out_file:
if (bprm->file) {
allow_write_access(bprm->file);
fput(bprm->file);
}
out_unmark:
if (clear_in_exec)
current->fs->in_exec = 0;
current->in_execve = 0;
out_free:
free_bprm(bprm);
out_files:
if (displaced)
reset_files_struct(displaced);
out_ret:
return retval;
}
int do_execve(const char *filename,
const char __user *const __user *__argv,
const char __user *const __user *__envp)
{
struct user_arg_ptr argv = { .ptr.native = __argv };
struct user_arg_ptr envp = { .ptr.native = __envp };
return do_execve_common(filename, argv, envp);
}
#ifdef CONFIG_COMPAT
static int compat_do_execve(const char *filename,
const compat_uptr_t __user *__argv,
const compat_uptr_t __user *__envp)
{
struct user_arg_ptr argv = {
.is_compat = true,
.ptr.compat = __argv,
};
struct user_arg_ptr envp = {
.is_compat = true,
.ptr.compat = __envp,
};
return do_execve_common(filename, argv, envp);
}
#endif
void set_binfmt(struct linux_binfmt *new)
{
struct mm_struct *mm = current->mm;
if (mm->binfmt)
module_put(mm->binfmt->module);
mm->binfmt = new;
if (new)
__module_get(new->module);
}
EXPORT_SYMBOL(set_binfmt);
/*
* set_dumpable converts traditional three-value dumpable to two flags and
* stores them into mm->flags. It modifies lower two bits of mm->flags, but
* these bits are not changed atomically. So get_dumpable can observe the
* intermediate state. To avoid doing unexpected behavior, get get_dumpable
* return either old dumpable or new one by paying attention to the order of
* modifying the bits.
*
* dumpable | mm->flags (binary)
* old new | initial interim final
* ---------+-----------------------
* 0 1 | 00 01 01
* 0 2 | 00 10(*) 11
* 1 0 | 01 00 00
* 1 2 | 01 11 11
* 2 0 | 11 10(*) 00
* 2 1 | 11 11 01
*
* (*) get_dumpable regards interim value of 10 as 11.
*/
void set_dumpable(struct mm_struct *mm, int value)
{
switch (value) {
case SUID_DUMPABLE_DISABLED:
clear_bit(MMF_DUMPABLE, &mm->flags);
smp_wmb();
clear_bit(MMF_DUMP_SECURELY, &mm->flags);
break;
case SUID_DUMPABLE_ENABLED:
set_bit(MMF_DUMPABLE, &mm->flags);
smp_wmb();
clear_bit(MMF_DUMP_SECURELY, &mm->flags);
break;
case SUID_DUMPABLE_SAFE:
set_bit(MMF_DUMP_SECURELY, &mm->flags);
smp_wmb();
set_bit(MMF_DUMPABLE, &mm->flags);
break;
}
}
int __get_dumpable(unsigned long mm_flags)
{
int ret;
ret = mm_flags & MMF_DUMPABLE_MASK;
return (ret > SUID_DUMPABLE_ENABLED) ? SUID_DUMPABLE_SAFE : ret;
}
int get_dumpable(struct mm_struct *mm)
{
return __get_dumpable(mm->flags);
}
#ifdef __ARCH_WANT_SYS_EXECVE
SYSCALL_DEFINE3(execve,
const char __user *, filename,
const char __user *const __user *, argv,
const char __user *const __user *, envp)
{
struct filename *path = getname(filename);
int error = PTR_ERR(path);
if (!IS_ERR(path)) {
error = do_execve(path->name, argv, envp);
putname(path);
}
return error;
}
#ifdef CONFIG_COMPAT
asmlinkage long compat_sys_execve(const char __user * filename,
const compat_uptr_t __user * argv,
const compat_uptr_t __user * envp)
{
struct filename *path = getname(filename);
int error = PTR_ERR(path);
if (!IS_ERR(path)) {
error = compat_do_execve(path->name, argv, envp);
putname(path);
}
return error;
}
#endif
#endif
#ifdef __ARCH_WANT_KERNEL_EXECVE
int kernel_execve(const char *filename,
const char *const argv[],
const char *const envp[])
{
int ret = do_execve(filename,
(const char __user *const __user *)argv,
(const char __user *const __user *)envp);
if (ret < 0)
return ret;
/*
* We were successful. We won't be returning to our caller, but
* instead to user space by manipulating the kernel stack.
*/
ret_from_kernel_execve(current_pt_regs());
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3769_2 |
crossvul-cpp_data_bad_2375_1 | /* lib/rpc/svc_auth_gss.c */
/*
Copyright (c) 2000 The Regents of the University of Michigan.
All rights reserved.
Copyright (c) 2000 Dug Song <dugsong@UMICH.EDU>.
All rights reserved, all wrongs reversed.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Id: svc_auth_gss.c,v 1.28 2002/10/15 21:29:36 kwc Exp
*/
#include "k5-platform.h"
#include <gssrpc/rpc.h>
#include <gssrpc/auth_gssapi.h>
#ifdef HAVE_HEIMDAL
#include <gssapi.h>
#define gss_nt_service_name GSS_C_NT_HOSTBASED_SERVICE
#else
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_generic.h>
#endif
#ifdef DEBUG_GSSAPI
int svc_debug_gss = DEBUG_GSSAPI;
#endif
#ifdef SPKM
#ifndef OID_EQ
#define g_OID_equal(o1,o2) \
(((o1)->length == (o2)->length) && \
((o1)->elements != 0) && ((o2)->elements != 0) && \
(memcmp((o1)->elements,(o2)->elements,(int) (o1)->length) == 0))
#define OID_EQ 1
#endif /* OID_EQ */
extern const gss_OID_desc * const gss_mech_spkm3;
#endif /* SPKM */
extern SVCAUTH svc_auth_none;
/*
* from mit-krb5-1.2.1 mechglue/mglueP.h:
* Array of context IDs typed by mechanism OID
*/
typedef struct gss_union_ctx_id_t {
gss_OID mech_type;
gss_ctx_id_t internal_ctx_id;
} gss_union_ctx_id_desc, *gss_union_ctx_id_t;
static auth_gssapi_log_badauth_func log_badauth = NULL;
static caddr_t log_badauth_data = NULL;
static auth_gssapi_log_badauth2_func log_badauth2 = NULL;
static caddr_t log_badauth2_data = NULL;
static auth_gssapi_log_badverf_func log_badverf = NULL;
static caddr_t log_badverf_data = NULL;
static auth_gssapi_log_miscerr_func log_miscerr = NULL;
static caddr_t log_miscerr_data = NULL;
#define LOG_MISCERR(arg) if (log_miscerr) \
(*log_miscerr)(rqst, msg, arg, log_miscerr_data)
static bool_t svcauth_gss_destroy(SVCAUTH *);
static bool_t svcauth_gss_wrap(SVCAUTH *, XDR *, xdrproc_t, caddr_t);
static bool_t svcauth_gss_unwrap(SVCAUTH *, XDR *, xdrproc_t, caddr_t);
static bool_t svcauth_gss_nextverf(struct svc_req *, u_int);
struct svc_auth_ops svc_auth_gss_ops = {
svcauth_gss_wrap,
svcauth_gss_unwrap,
svcauth_gss_destroy
};
struct svc_rpc_gss_data {
bool_t established; /* context established */
gss_ctx_id_t ctx; /* context id */
struct rpc_gss_sec sec; /* security triple */
gss_buffer_desc cname; /* GSS client name */
u_int seq; /* sequence number */
u_int win; /* sequence window */
u_int seqlast; /* last sequence number */
uint32_t seqmask; /* bitmask of seqnums */
gss_name_t client_name; /* unparsed name string */
gss_buffer_desc checksum; /* so we can free it */
};
#define SVCAUTH_PRIVATE(auth) \
(*(struct svc_rpc_gss_data **)&(auth)->svc_ah_private)
/* Global server credentials. */
gss_cred_id_t svcauth_gss_creds;
static gss_name_t svcauth_gss_name = NULL;
bool_t
svcauth_gss_set_svc_name(gss_name_t name)
{
OM_uint32 maj_stat, min_stat;
log_debug("in svcauth_gss_set_svc_name()");
if (svcauth_gss_name != NULL) {
maj_stat = gss_release_name(&min_stat, &svcauth_gss_name);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_release_name", maj_stat, min_stat);
return (FALSE);
}
svcauth_gss_name = NULL;
}
if (svcauth_gss_name == GSS_C_NO_NAME)
return (TRUE);
maj_stat = gss_duplicate_name(&min_stat, name, &svcauth_gss_name);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_duplicate_name", maj_stat, min_stat);
return (FALSE);
}
return (TRUE);
}
static bool_t
svcauth_gss_acquire_cred(void)
{
OM_uint32 maj_stat, min_stat;
log_debug("in svcauth_gss_acquire_cred()");
maj_stat = gss_acquire_cred(&min_stat, svcauth_gss_name, 0,
GSS_C_NULL_OID_SET, GSS_C_ACCEPT,
&svcauth_gss_creds, NULL, NULL);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_acquire_cred", maj_stat, min_stat);
return (FALSE);
}
return (TRUE);
}
static bool_t
svcauth_gss_release_cred(void)
{
OM_uint32 maj_stat, min_stat;
log_debug("in svcauth_gss_release_cred()");
maj_stat = gss_release_cred(&min_stat, &svcauth_gss_creds);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_release_cred", maj_stat, min_stat);
return (FALSE);
}
svcauth_gss_creds = NULL;
return (TRUE);
}
/* Invoke log_badauth callbacks for an authentication failure. */
static void
badauth(OM_uint32 maj, OM_uint32 minor, SVCXPRT *xprt)
{
if (log_badauth != NULL)
(*log_badauth)(maj, minor, &xprt->xp_raddr, log_badauth_data);
if (log_badauth2 != NULL)
(*log_badauth2)(maj, minor, xprt, log_badauth2_data);
}
static bool_t
svcauth_gss_accept_sec_context(struct svc_req *rqst,
struct rpc_gss_init_res *gr)
{
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
gss_buffer_desc recv_tok, seqbuf;
gss_OID mech;
OM_uint32 maj_stat = 0, min_stat = 0, ret_flags, seq;
log_debug("in svcauth_gss_accept_context()");
gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gr, 0, sizeof(*gr));
/* Deserialize arguments. */
memset(&recv_tok, 0, sizeof(recv_tok));
if (!svc_getargs(rqst->rq_xprt, xdr_rpc_gss_init_args,
(caddr_t)&recv_tok))
return (FALSE);
gr->gr_major = gss_accept_sec_context(&gr->gr_minor,
&gd->ctx,
svcauth_gss_creds,
&recv_tok,
GSS_C_NO_CHANNEL_BINDINGS,
&gd->client_name,
&mech,
&gr->gr_token,
&ret_flags,
NULL,
NULL);
svc_freeargs(rqst->rq_xprt, xdr_rpc_gss_init_args, (caddr_t)&recv_tok);
log_status("accept_sec_context", gr->gr_major, gr->gr_minor);
if (gr->gr_major != GSS_S_COMPLETE &&
gr->gr_major != GSS_S_CONTINUE_NEEDED) {
badauth(gr->gr_major, gr->gr_minor, rqst->rq_xprt);
gd->ctx = GSS_C_NO_CONTEXT;
goto errout;
}
/*
* ANDROS: krb5 mechglue returns ctx of size 8 - two pointers,
* one to the mechanism oid, one to the internal_ctx_id
*/
if ((gr->gr_ctx.value = mem_alloc(sizeof(gss_union_ctx_id_desc))) == NULL) {
fprintf(stderr, "svcauth_gss_accept_context: out of memory\n");
goto errout;
}
memcpy(gr->gr_ctx.value, gd->ctx, sizeof(gss_union_ctx_id_desc));
gr->gr_ctx.length = sizeof(gss_union_ctx_id_desc);
/* gr->gr_win = 0x00000005; ANDROS: for debugging linux kernel version... */
gr->gr_win = sizeof(gd->seqmask) * 8;
/* Save client info. */
gd->sec.mech = mech;
gd->sec.qop = GSS_C_QOP_DEFAULT;
gd->sec.svc = gc->gc_svc;
gd->seq = gc->gc_seq;
gd->win = gr->gr_win;
if (gr->gr_major == GSS_S_COMPLETE) {
#ifdef SPKM
/* spkm3: no src_name (anonymous) */
if(!g_OID_equal(gss_mech_spkm3, mech)) {
#endif
maj_stat = gss_display_name(&min_stat, gd->client_name,
&gd->cname, &gd->sec.mech);
#ifdef SPKM
}
#endif
if (maj_stat != GSS_S_COMPLETE) {
log_status("display_name", maj_stat, min_stat);
goto errout;
}
#ifdef DEBUG
#ifdef HAVE_HEIMDAL
log_debug("accepted context for %.*s with "
"<mech {}, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
gd->sec.qop, gd->sec.svc);
#else
{
gss_buffer_desc mechname;
gss_oid_to_str(&min_stat, mech, &mechname);
log_debug("accepted context for %.*s with "
"<mech %.*s, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
mechname.length, (char *)mechname.value,
gd->sec.qop, gd->sec.svc);
gss_release_buffer(&min_stat, &mechname);
}
#endif
#endif /* DEBUG */
seq = htonl(gr->gr_win);
seqbuf.value = &seq;
seqbuf.length = sizeof(seq);
gss_release_buffer(&min_stat, &gd->checksum);
maj_stat = gss_sign(&min_stat, gd->ctx, GSS_C_QOP_DEFAULT,
&seqbuf, &gd->checksum);
if (maj_stat != GSS_S_COMPLETE) {
goto errout;
}
rqst->rq_xprt->xp_verf.oa_flavor = RPCSEC_GSS;
rqst->rq_xprt->xp_verf.oa_base = gd->checksum.value;
rqst->rq_xprt->xp_verf.oa_length = gd->checksum.length;
}
return (TRUE);
errout:
gss_release_buffer(&min_stat, &gr->gr_token);
return (FALSE);
}
static bool_t
svcauth_gss_validate(struct svc_req *rqst, struct svc_rpc_gss_data *gd, struct rpc_msg *msg)
{
struct opaque_auth *oa;
gss_buffer_desc rpcbuf, checksum;
OM_uint32 maj_stat, min_stat, qop_state;
u_char rpchdr[128];
int32_t *buf;
log_debug("in svcauth_gss_validate()");
memset(rpchdr, 0, sizeof(rpchdr));
/* XXX - Reconstruct RPC header for signing (from xdr_callmsg). */
oa = &msg->rm_call.cb_cred;
if (oa->oa_length > MAX_AUTH_BYTES)
return (FALSE);
/* 8 XDR units from the IXDR macro calls. */
if (sizeof(rpchdr) < (8 * BYTES_PER_XDR_UNIT +
RNDUP(oa->oa_length)))
return (FALSE);
buf = (int32_t *)(void *)rpchdr;
IXDR_PUT_LONG(buf, msg->rm_xid);
IXDR_PUT_ENUM(buf, msg->rm_direction);
IXDR_PUT_LONG(buf, msg->rm_call.cb_rpcvers);
IXDR_PUT_LONG(buf, msg->rm_call.cb_prog);
IXDR_PUT_LONG(buf, msg->rm_call.cb_vers);
IXDR_PUT_LONG(buf, msg->rm_call.cb_proc);
IXDR_PUT_ENUM(buf, oa->oa_flavor);
IXDR_PUT_LONG(buf, oa->oa_length);
if (oa->oa_length) {
memcpy((caddr_t)buf, oa->oa_base, oa->oa_length);
buf += RNDUP(oa->oa_length) / sizeof(int32_t);
}
rpcbuf.value = rpchdr;
rpcbuf.length = (u_char *)buf - rpchdr;
checksum.value = msg->rm_call.cb_verf.oa_base;
checksum.length = msg->rm_call.cb_verf.oa_length;
maj_stat = gss_verify_mic(&min_stat, gd->ctx, &rpcbuf, &checksum,
&qop_state);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_verify_mic", maj_stat, min_stat);
if (log_badverf != NULL)
(*log_badverf)(gd->client_name,
svcauth_gss_name,
rqst, msg, log_badverf_data);
return (FALSE);
}
return (TRUE);
}
static bool_t
svcauth_gss_nextverf(struct svc_req *rqst, u_int num)
{
struct svc_rpc_gss_data *gd;
gss_buffer_desc signbuf;
OM_uint32 maj_stat, min_stat;
log_debug("in svcauth_gss_nextverf()");
if (rqst->rq_xprt->xp_auth == NULL)
return (FALSE);
gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
gss_release_buffer(&min_stat, &gd->checksum);
signbuf.value = #
signbuf.length = sizeof(num);
maj_stat = gss_get_mic(&min_stat, gd->ctx, gd->sec.qop,
&signbuf, &gd->checksum);
if (maj_stat != GSS_S_COMPLETE) {
log_status("gss_get_mic", maj_stat, min_stat);
return (FALSE);
}
rqst->rq_xprt->xp_verf.oa_flavor = RPCSEC_GSS;
rqst->rq_xprt->xp_verf.oa_base = (caddr_t)gd->checksum.value;
rqst->rq_xprt->xp_verf.oa_length = (u_int)gd->checksum.length;
return (TRUE);
}
enum auth_stat
gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
mem_free(gr.gr_ctx.value,
sizeof(gss_union_ctx_id_desc));
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc));
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
static bool_t
svcauth_gss_destroy(SVCAUTH *auth)
{
struct svc_rpc_gss_data *gd;
OM_uint32 min_stat;
log_debug("in svcauth_gss_destroy()");
gd = SVCAUTH_PRIVATE(auth);
gss_delete_sec_context(&min_stat, &gd->ctx, GSS_C_NO_BUFFER);
gss_release_buffer(&min_stat, &gd->cname);
gss_release_buffer(&min_stat, &gd->checksum);
if (gd->client_name)
gss_release_name(&min_stat, &gd->client_name);
mem_free(gd, sizeof(*gd));
mem_free(auth, sizeof(*auth));
return (TRUE);
}
static bool_t
svcauth_gss_wrap(SVCAUTH *auth, XDR *xdrs, xdrproc_t xdr_func, caddr_t xdr_ptr)
{
struct svc_rpc_gss_data *gd;
log_debug("in svcauth_gss_wrap()");
gd = SVCAUTH_PRIVATE(auth);
if (!gd->established || gd->sec.svc == RPCSEC_GSS_SVC_NONE) {
return ((*xdr_func)(xdrs, xdr_ptr));
}
return (xdr_rpc_gss_data(xdrs, xdr_func, xdr_ptr,
gd->ctx, gd->sec.qop,
gd->sec.svc, gd->seq));
}
static bool_t
svcauth_gss_unwrap(SVCAUTH *auth, XDR *xdrs, xdrproc_t xdr_func, caddr_t xdr_ptr)
{
struct svc_rpc_gss_data *gd;
log_debug("in svcauth_gss_unwrap()");
gd = SVCAUTH_PRIVATE(auth);
if (!gd->established || gd->sec.svc == RPCSEC_GSS_SVC_NONE) {
return ((*xdr_func)(xdrs, xdr_ptr));
}
return (xdr_rpc_gss_data(xdrs, xdr_func, xdr_ptr,
gd->ctx, gd->sec.qop,
gd->sec.svc, gd->seq));
}
char *
svcauth_gss_get_principal(SVCAUTH *auth)
{
struct svc_rpc_gss_data *gd;
char *pname;
gd = SVCAUTH_PRIVATE(auth);
if (gd->cname.length == 0 || gd->cname.length >= SIZE_MAX)
return (NULL);
if ((pname = malloc(gd->cname.length + 1)) == NULL)
return (NULL);
memcpy(pname, gd->cname.value, gd->cname.length);
pname[gd->cname.length] = '\0';
return (pname);
}
/*
* Function: svcauth_gss_set_log_badauth_func
*
* Purpose: sets the logging function called when an invalid RPC call
* arrives
*
* See functional specifications.
*/
void svcauth_gss_set_log_badauth_func(
auth_gssapi_log_badauth_func func,
caddr_t data)
{
log_badauth = func;
log_badauth_data = data;
}
void
svcauth_gss_set_log_badauth2_func(auth_gssapi_log_badauth2_func func,
caddr_t data)
{
log_badauth2 = func;
log_badauth2_data = data;
}
/*
* Function: svcauth_gss_set_log_badverf_func
*
* Purpose: sets the logging function called when an invalid RPC call
* arrives
*
* See functional specifications.
*/
void svcauth_gss_set_log_badverf_func(
auth_gssapi_log_badverf_func func,
caddr_t data)
{
log_badverf = func;
log_badverf_data = data;
}
/*
* Function: svcauth_gss_set_log_miscerr_func
*
* Purpose: sets the logging function called when a miscellaneous
* AUTH_GSSAPI error occurs
*
* See functional specifications.
*/
void svcauth_gss_set_log_miscerr_func(
auth_gssapi_log_miscerr_func func,
caddr_t data)
{
log_miscerr = func;
log_miscerr_data = data;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2375_1 |
crossvul-cpp_data_bad_5636_1 | /*
* OpenVPN -- An application to securely tunnel IP networks
* over a single TCP/UDP port, with support for SSL/TLS-based
* session authentication and key exchange,
* packet encryption, packet authentication, and
* packet compression.
*
* Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
* Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see the file COPYING included with this
* distribution); if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_MSC_VER)
#include "config-msvc.h"
#endif
#include "syshead.h"
#ifdef ENABLE_CRYPTO
#include "crypto.h"
#include "error.h"
#include "misc.h"
#include "memdbg.h"
/*
* Encryption and Compression Routines.
*
* On entry, buf contains the input data and length.
* On exit, it should be set to the output data and length.
*
* If buf->len is <= 0 we should return
* If buf->len is set to 0 on exit it tells the caller to ignore the packet.
*
* work is a workspace buffer we are given of size BUF_SIZE.
* work may be used to return output data, or the input buffer
* may be modified and returned as output. If output data is
* returned in work, the data should start after FRAME_HEADROOM bytes
* of padding to leave room for downstream routines to prepend.
*
* Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
* by all routines (encryption, decryption, compression, and decompression).
*
* Note that the buf_prepend return will assert if we try to
* make a header bigger than FRAME_HEADROOM. This should not
* happen unless the frame parameters are wrong.
*/
#define CRYPT_ERROR(format) \
do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
void
openvpn_encrypt (struct buffer *buf, struct buffer work,
const struct crypto_options *opt,
const struct frame* frame)
{
struct gc_arena gc;
gc_init (&gc);
if (buf->len > 0 && opt->key_ctx_bi)
{
struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
/* Do Encrypt from buf -> work */
if (ctx->cipher)
{
uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH];
const int iv_size = cipher_ctx_iv_length (ctx->cipher);
const unsigned int mode = cipher_ctx_mode (ctx->cipher);
int outlen;
if (mode == OPENVPN_MODE_CBC)
{
CLEAR (iv_buf);
/* generate pseudo-random IV */
if (opt->flags & CO_USE_IV)
prng_bytes (iv_buf, iv_size);
/* Put packet ID in plaintext buffer or IV, depending on cipher mode */
if (opt->packet_id)
{
struct packet_id_net pin;
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
}
}
else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
{
struct packet_id_net pin;
struct buffer b;
ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */
ASSERT (opt->packet_id); /* for this mode. */
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true);
memset (iv_buf, 0, iv_size);
buf_set_write (&b, iv_buf, iv_size);
ASSERT (packet_id_write (&pin, &b, true, false));
}
else /* We only support CBC, CFB, or OFB modes right now */
{
ASSERT (0);
}
/* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
/* set the IV pseudo-randomly */
if (opt->flags & CO_USE_IV)
dmsg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
dmsg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
format_hex (BPTR (buf), BLEN (buf), 80, &gc));
/* cipher_ctx was already initialized with key & keylen */
ASSERT (cipher_ctx_reset(ctx->cipher, iv_buf));
/* Buffer overflow check */
if (!buf_safe (&work, buf->len + cipher_ctx_block_size(ctx->cipher)))
{
msg (D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
buf->capacity,
buf->offset,
buf->len,
work.capacity,
work.offset,
work.len,
cipher_ctx_block_size (ctx->cipher));
goto err;
}
/* Encrypt packet ID, payload */
ASSERT (cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
work.len += outlen;
/* Flush the encryption buffer */
ASSERT(cipher_ctx_final(ctx->cipher, BPTR (&work) + outlen, &outlen));
work.len += outlen;
ASSERT (outlen == iv_size);
/* prepend the IV to the ciphertext */
if (opt->flags & CO_USE_IV)
{
uint8_t *output = buf_prepend (&work, iv_size);
ASSERT (output);
memcpy (output, iv_buf, iv_size);
}
dmsg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
format_hex (BPTR (&work), BLEN (&work), 80, &gc));
}
else /* No Encryption */
{
if (opt->packet_id)
{
struct packet_id_net pin;
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
}
work = *buf;
}
/* HMAC the ciphertext (or plaintext if !cipher) */
if (ctx->hmac)
{
uint8_t *output = NULL;
hmac_ctx_reset (ctx->hmac);
hmac_ctx_update (ctx->hmac, BPTR(&work), BLEN(&work));
output = buf_prepend (&work, hmac_ctx_size(ctx->hmac));
ASSERT (output);
hmac_ctx_final (ctx->hmac, output);
}
*buf = work;
}
gc_free (&gc);
return;
err:
crypto_clear_error();
buf->len = 0;
gc_free (&gc);
return;
}
/*
* If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
*
* Set buf->len to 0 and return false on decrypt error.
*
* On success, buf is set to point to plaintext, true
* is returned.
*/
bool
openvpn_decrypt (struct buffer *buf, struct buffer work,
const struct crypto_options *opt,
const struct frame* frame)
{
static const char error_prefix[] = "Authenticate/Decrypt packet error";
struct gc_arena gc;
gc_init (&gc);
if (buf->len > 0 && opt->key_ctx_bi)
{
struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
struct packet_id_net pin;
bool have_pin = false;
/* Verify the HMAC */
if (ctx->hmac)
{
int hmac_len;
uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
hmac_ctx_reset(ctx->hmac);
/* Assume the length of the input HMAC */
hmac_len = hmac_ctx_size (ctx->hmac);
/* Authentication fails if insufficient data in packet for HMAC */
if (buf->len < hmac_len)
CRYPT_ERROR ("missing authentication info");
hmac_ctx_update (ctx->hmac, BPTR (buf) + hmac_len, BLEN (buf) - hmac_len);
hmac_ctx_final (ctx->hmac, local_hmac);
/* Compare locally computed HMAC with packet HMAC */
if (memcmp (local_hmac, BPTR (buf), hmac_len))
CRYPT_ERROR ("packet HMAC authentication failed");
ASSERT (buf_advance (buf, hmac_len));
}
/* Decrypt packet ID + payload */
if (ctx->cipher)
{
const unsigned int mode = cipher_ctx_mode (ctx->cipher);
const int iv_size = cipher_ctx_iv_length (ctx->cipher);
uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH];
int outlen;
/* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT)));
/* use IV if user requested it */
CLEAR (iv_buf);
if (opt->flags & CO_USE_IV)
{
if (buf->len < iv_size)
CRYPT_ERROR ("missing IV info");
memcpy (iv_buf, BPTR (buf), iv_size);
ASSERT (buf_advance (buf, iv_size));
}
/* show the IV's initial state */
if (opt->flags & CO_USE_IV)
dmsg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
if (buf->len < 1)
CRYPT_ERROR ("missing payload");
/* ctx->cipher was already initialized with key & keylen */
if (!cipher_ctx_reset (ctx->cipher, iv_buf))
CRYPT_ERROR ("cipher init failed");
/* Buffer overflow check (should never happen) */
if (!buf_safe (&work, buf->len))
CRYPT_ERROR ("buffer overflow");
/* Decrypt packet ID, payload */
if (!cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
CRYPT_ERROR ("cipher update failed");
work.len += outlen;
/* Flush the decryption buffer */
if (!cipher_ctx_final (ctx->cipher, BPTR (&work) + outlen, &outlen))
CRYPT_ERROR ("cipher final failed");
work.len += outlen;
dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s",
format_hex (BPTR (&work), BLEN (&work), 80, &gc));
/* Get packet ID from plaintext buffer or IV, depending on cipher mode */
{
if (mode == OPENVPN_MODE_CBC)
{
if (opt->packet_id)
{
if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
CRYPT_ERROR ("error reading CBC packet-id");
have_pin = true;
}
}
else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
{
struct buffer b;
ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */
ASSERT (opt->packet_id); /* for this mode. */
buf_set_read (&b, iv_buf, iv_size);
if (!packet_id_read (&pin, &b, true))
CRYPT_ERROR ("error reading CFB/OFB packet-id");
have_pin = true;
}
else /* We only support CBC, CFB, or OFB modes right now */
{
ASSERT (0);
}
}
}
else
{
work = *buf;
if (opt->packet_id)
{
if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
CRYPT_ERROR ("error reading packet-id");
have_pin = !BOOL_CAST (opt->flags & CO_IGNORE_PACKET_ID);
}
}
if (have_pin)
{
packet_id_reap_test (&opt->packet_id->rec);
if (packet_id_test (&opt->packet_id->rec, &pin))
{
packet_id_add (&opt->packet_id->rec, &pin);
if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM))
packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
}
else
{
if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS))
msg (D_REPLAY_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings",
error_prefix, packet_id_net_print (&pin, true, &gc));
goto error_exit;
}
}
*buf = work;
}
gc_free (&gc);
return true;
error_exit:
crypto_clear_error();
buf->len = 0;
gc_free (&gc);
return false;
}
/*
* How many bytes will we add to frame buffer for a given
* set of crypto options?
*/
void
crypto_adjust_frame_parameters(struct frame *frame,
const struct key_type* kt,
bool cipher_defined,
bool use_iv,
bool packet_id,
bool packet_id_long_form)
{
frame_add_to_extra_frame (frame,
(packet_id ? packet_id_size (packet_id_long_form) : 0) +
((cipher_defined && use_iv) ? cipher_kt_iv_size (kt->cipher) : 0) +
(cipher_defined ? cipher_kt_block_size (kt->cipher) : 0) + /* worst case padding expansion */
kt->hmac_length);
}
/*
* Build a struct key_type.
*/
void
init_key_type (struct key_type *kt, const char *ciphername,
bool ciphername_defined, const char *authname,
bool authname_defined, int keysize,
bool cfb_ofb_allowed, bool warn)
{
CLEAR (*kt);
if (ciphername && ciphername_defined)
{
kt->cipher = cipher_kt_get (translate_cipher_name_from_openvpn(ciphername));
kt->cipher_length = cipher_kt_key_size (kt->cipher);
if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
kt->cipher_length = keysize;
/* check legal cipher mode */
{
const unsigned int mode = cipher_kt_mode (kt->cipher);
if (!(mode == OPENVPN_MODE_CBC
#ifdef ALLOW_NON_CBC_CIPHERS
|| (cfb_ofb_allowed && (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB))
#endif
))
#ifdef ENABLE_SMALL
msg (M_FATAL, "Cipher '%s' mode not supported", ciphername);
#else
msg (M_FATAL, "Cipher '%s' uses a mode not supported by " PACKAGE_NAME " in your current configuration. CBC mode is always supported, while CFB and OFB modes are supported only when using SSL/TLS authentication and key exchange mode, and when " PACKAGE_NAME " has been built with ALLOW_NON_CBC_CIPHERS.", ciphername);
#endif
}
}
else
{
if (warn)
msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
}
if (authname && authname_defined)
{
kt->digest = md_kt_get (authname);
kt->hmac_length = md_kt_size (kt->digest);
}
else
{
if (warn)
msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
}
}
/* given a key and key_type, build a key_ctx */
void
init_key_ctx (struct key_ctx *ctx, struct key *key,
const struct key_type *kt, int enc,
const char *prefix)
{
struct gc_arena gc = gc_new ();
CLEAR (*ctx);
if (kt->cipher && kt->cipher_length > 0)
{
ALLOC_OBJ(ctx->cipher, cipher_ctx_t);
cipher_ctx_init (ctx->cipher, key->cipher, kt->cipher_length,
kt->cipher, enc);
msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
prefix,
cipher_kt_name(kt->cipher),
kt->cipher_length *8);
dmsg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
format_hex (key->cipher, kt->cipher_length, 0, &gc));
dmsg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
prefix,
cipher_kt_block_size(kt->cipher),
cipher_kt_iv_size(kt->cipher));
}
if (kt->digest && kt->hmac_length > 0)
{
ALLOC_OBJ(ctx->hmac, hmac_ctx_t);
hmac_ctx_init (ctx->hmac, key->hmac, kt->hmac_length, kt->digest);
msg (D_HANDSHAKE,
"%s: Using %d bit message hash '%s' for HMAC authentication",
prefix, md_kt_size(kt->digest) * 8, md_kt_name(kt->digest));
dmsg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
format_hex (key->hmac, kt->hmac_length, 0, &gc));
dmsg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
prefix,
md_kt_size(kt->digest),
hmac_ctx_size(ctx->hmac));
}
gc_free (&gc);
}
void
free_key_ctx (struct key_ctx *ctx)
{
if (ctx->cipher)
{
cipher_ctx_cleanup(ctx->cipher);
free(ctx->cipher);
ctx->cipher = NULL;
}
if (ctx->hmac)
{
hmac_ctx_cleanup(ctx->hmac);
free(ctx->hmac);
ctx->hmac = NULL;
}
}
void
free_key_ctx_bi (struct key_ctx_bi *ctx)
{
free_key_ctx(&ctx->encrypt);
free_key_ctx(&ctx->decrypt);
}
static bool
key_is_zero (struct key *key, const struct key_type *kt)
{
int i;
for (i = 0; i < kt->cipher_length; ++i)
if (key->cipher[i])
return false;
msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
return true;
}
/*
* Make sure that cipher key is a valid key for current key_type.
*/
bool
check_key (struct key *key, const struct key_type *kt)
{
if (kt->cipher)
{
/*
* Check for zero key
*/
if (key_is_zero(key, kt))
return false;
/*
* Check for weak or semi-weak DES keys.
*/
{
const int ndc = key_des_num_cblocks (kt->cipher);
if (ndc)
return key_des_check (key->cipher, kt->cipher_length, ndc);
else
return true;
}
}
return true;
}
/*
* Make safe mutations to key to ensure it is valid,
* such as ensuring correct parity on DES keys.
*
* This routine cannot guarantee it will generate a good
* key. You must always call check_key after this routine
* to make sure.
*/
void
fixup_key (struct key *key, const struct key_type *kt)
{
struct gc_arena gc = gc_new ();
if (kt->cipher)
{
#ifdef ENABLE_DEBUG
const struct key orig = *key;
#endif
const int ndc = key_des_num_cblocks (kt->cipher);
if (ndc)
key_des_fixup (key->cipher, kt->cipher_length, ndc);
#ifdef ENABLE_DEBUG
if (check_debug_level (D_CRYPTO_DEBUG))
{
if (memcmp (orig.cipher, key->cipher, kt->cipher_length))
dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
format_hex (orig.cipher, kt->cipher_length, 0, &gc),
format_hex (key->cipher, kt->cipher_length, 0, &gc));
}
#endif
}
gc_free (&gc);
}
void
check_replay_iv_consistency (const struct key_type *kt, bool packet_id, bool use_iv)
{
if (cfb_ofb_mode (kt) && !(packet_id && use_iv))
msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
}
bool
cfb_ofb_mode (const struct key_type* kt)
{
if (kt && kt->cipher) {
const unsigned int mode = cipher_kt_mode (kt->cipher);
return mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB;
}
return false;
}
/*
* Generate a random key. If key_type is provided, make
* sure generated key is valid for key_type.
*/
void
generate_key_random (struct key *key, const struct key_type *kt)
{
int cipher_len = MAX_CIPHER_KEY_LENGTH;
int hmac_len = MAX_HMAC_KEY_LENGTH;
struct gc_arena gc = gc_new ();
do {
CLEAR (*key);
if (kt)
{
if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
cipher_len = kt->cipher_length;
if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
hmac_len = kt->hmac_length;
}
if (!rand_bytes (key->cipher, cipher_len)
|| !rand_bytes (key->hmac, hmac_len))
msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation");
dmsg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0, &gc));
dmsg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0, &gc));
if (kt)
fixup_key (key, kt);
} while (kt && !check_key (key, kt));
gc_free (&gc);
}
/*
* Print key material
*/
void
key2_print (const struct key2* k,
const struct key_type *kt,
const char* prefix0,
const char* prefix1)
{
struct gc_arena gc = gc_new ();
ASSERT (k->n == 2);
dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
prefix0,
format_hex (k->keys[0].cipher, kt->cipher_length, 0, &gc));
dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
prefix0,
format_hex (k->keys[0].hmac, kt->hmac_length, 0, &gc));
dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
prefix1,
format_hex (k->keys[1].cipher, kt->cipher_length, 0, &gc));
dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
prefix1,
format_hex (k->keys[1].hmac, kt->hmac_length, 0, &gc));
gc_free (&gc);
}
void
test_crypto (const struct crypto_options *co, struct frame* frame)
{
int i, j;
struct gc_arena gc = gc_new ();
struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame), &gc);
struct buffer work = alloc_buf_gc (BUF_SIZE (frame), &gc);
struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
struct buffer buf = clear_buf();
/* init work */
ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
{
update_time ();
msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
/*
* Load src with random data.
*/
ASSERT (buf_init (&src, 0));
ASSERT (i <= src.capacity);
src.len = i;
ASSERT (rand_bytes (BPTR (&src), BLEN (&src)));
/* copy source to input buf */
buf = work;
memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
/* encrypt */
openvpn_encrypt (&buf, encrypt_workspace, co, frame);
/* decrypt */
openvpn_decrypt (&buf, decrypt_workspace, co, frame);
/* compare */
if (buf.len != src.len)
msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
for (j = 0; j < i; ++j)
{
const uint8_t in = *(BPTR (&src) + j);
const uint8_t out = *(BPTR (&buf) + j);
if (in != out)
msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
}
}
msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
gc_free (&gc);
}
#ifdef ENABLE_SSL
void
get_tls_handshake_key (const struct key_type *key_type,
struct key_ctx_bi *ctx,
const char *passphrase_file,
const int key_direction,
const unsigned int flags)
{
if (passphrase_file && key_type->hmac_length)
{
struct key2 key2;
struct key_type kt = *key_type;
struct key_direction_state kds;
/* for control channel we are only authenticating, not encrypting */
kt.cipher_length = 0;
kt.cipher = NULL;
if (flags & GHK_INLINE)
{
/* key was specified inline, key text is in passphrase_file */
read_key_file (&key2, passphrase_file, RKF_INLINE|RKF_MUST_SUCCEED);
/* succeeded? */
if (key2.n == 2)
msg (M_INFO, "Control Channel Authentication: tls-auth using INLINE static key file");
else
msg (M_FATAL, "INLINE tls-auth file lacks the requisite 2 keys");
}
else
{
/* first try to parse as an OpenVPN static key file */
read_key_file (&key2, passphrase_file, 0);
/* succeeded? */
if (key2.n == 2)
{
msg (M_INFO,
"Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
passphrase_file);
}
else
{
int hash_size;
CLEAR (key2);
/* failed, now try to get hash from a freeform file */
hash_size = read_passphrase_hash (passphrase_file,
kt.digest,
key2.keys[0].hmac,
MAX_HMAC_KEY_LENGTH);
ASSERT (hash_size == kt.hmac_length);
/* suceeded */
key2.n = 1;
msg (M_INFO,
"Control Channel Authentication: using '%s' as a free-form passphrase file",
passphrase_file);
}
}
/* handle key direction */
key_direction_state_init (&kds, key_direction);
must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
/* initialize hmac key in both directions */
init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, OPENVPN_OP_ENCRYPT,
"Outgoing Control Channel Authentication");
init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, OPENVPN_OP_DECRYPT,
"Incoming Control Channel Authentication");
CLEAR (key2);
}
else
{
CLEAR (*ctx);
}
}
#endif
/* header and footer for static key file */
static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----";
static const char static_key_foot[] = "-----END OpenVPN Static key V1-----";
static const char printable_char_fmt[] =
"Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
static const char unprintable_char_fmt[] =
"Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
/* read key from file */
void
read_key_file (struct key2 *key2, const char *file, const unsigned int flags)
{
struct gc_arena gc = gc_new ();
struct buffer in;
int fd, size;
uint8_t hex_byte[3] = {0, 0, 0};
const char *error_filename = file;
/* parse info */
const unsigned char *cp;
int hb_index = 0;
int line_num = 1;
int line_index = 0;
int match = 0;
/* output */
uint8_t* out = (uint8_t*) &key2->keys;
const int keylen = sizeof (key2->keys);
int count = 0;
/* parse states */
# define PARSE_INITIAL 0
# define PARSE_HEAD 1
# define PARSE_DATA 2
# define PARSE_DATA_COMPLETE 3
# define PARSE_FOOT 4
# define PARSE_FINISHED 5
int state = PARSE_INITIAL;
/* constants */
const int hlen = strlen (static_key_head);
const int flen = strlen (static_key_foot);
const int onekeylen = sizeof (key2->keys[0]);
CLEAR (*key2);
/*
* Key can be provided as a filename in 'file' or if RKF_INLINE
* is set, the actual key data itself in ascii form.
*/
if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
{
size = strlen (file) + 1;
buf_set_read (&in, (const uint8_t *)file, size);
error_filename = INLINE_FILE_TAG;
}
else /* 'file' is a filename which refers to a file containing the ascii key */
{
in = alloc_buf_gc (2048, &gc);
fd = platform_open (file, O_RDONLY, 0);
if (fd == -1)
msg (M_ERR, "Cannot open file key file '%s'", file);
size = read (fd, in.data, in.capacity);
if (size < 0)
msg (M_FATAL, "Read error on key file ('%s')", file);
if (size == in.capacity)
msg (M_FATAL, "Key file ('%s') can be a maximum of %d bytes", file, (int)in.capacity);
close (fd);
}
cp = (unsigned char *)in.data;
while (size > 0)
{
const unsigned char c = *cp;
#if 0
msg (M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
c, (int)c, state, line_num, line_index, match, count);
#endif
if (c == '\n')
{
line_index = match = 0;
++line_num;
}
else
{
/* first char of new line */
if (!line_index)
{
/* first char of line after header line? */
if (state == PARSE_HEAD)
state = PARSE_DATA;
/* first char of footer */
if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
state = PARSE_FOOT;
}
/* compare read chars with header line */
if (state == PARSE_INITIAL)
{
if (line_index < hlen && c == static_key_head[line_index])
{
if (++match == hlen)
state = PARSE_HEAD;
}
}
/* compare read chars with footer line */
if (state == PARSE_FOOT)
{
if (line_index < flen && c == static_key_foot[line_index])
{
if (++match == flen)
state = PARSE_FINISHED;
}
}
/* reading key */
if (state == PARSE_DATA)
{
if (isxdigit(c))
{
ASSERT (hb_index >= 0 && hb_index < 2);
hex_byte[hb_index++] = c;
if (hb_index == 2)
{
unsigned int u;
ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
*out++ = u;
hb_index = 0;
if (++count == keylen)
state = PARSE_DATA_COMPLETE;
}
}
else if (isspace(c))
;
else
{
msg (M_FATAL,
(isprint (c) ? printable_char_fmt : unprintable_char_fmt),
c, line_num, error_filename, count, onekeylen, keylen);
}
}
++line_index;
}
++cp;
--size;
}
/*
* Normally we will read either 1 or 2 keys from file.
*/
key2->n = count / onekeylen;
ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
if (flags & RKF_MUST_SUCCEED)
{
if (!key2->n)
msg (M_FATAL, "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
error_filename, count, onekeylen, keylen);
if (state != PARSE_FINISHED)
msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
error_filename, count, onekeylen, keylen);
}
/* zero file read buffer if not an inline file */
if (!(flags & RKF_INLINE))
buf_clear (&in);
if (key2->n)
warn_if_group_others_accessible (error_filename);
#if 0
/* DEBUGGING */
{
int i;
printf ("KEY READ, n=%d\n", key2->n);
for (i = 0; i < (int) SIZE (key2->keys); ++i)
{
/* format key as ascii */
const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
sizeof (key2->keys[i]),
0,
16,
"\n",
&gc);
printf ("[%d]\n%s\n\n", i, fmt);
}
}
#endif
/* pop our garbage collection level */
gc_free (&gc);
}
int
read_passphrase_hash (const char *passphrase_file,
const md_kt_t *digest,
uint8_t *output,
int len)
{
unsigned int outlen = 0;
md_ctx_t md;
ASSERT (len >= md_kt_size(digest));
memset (output, 0, len);
md_ctx_init(&md, digest);
/* read passphrase file */
{
const int min_passphrase_size = 8;
uint8_t buf[64];
int total_size = 0;
int fd = platform_open (passphrase_file, O_RDONLY, 0);
if (fd == -1)
msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
for (;;)
{
int size = read (fd, buf, sizeof (buf));
if (size == 0)
break;
if (size == -1)
msg (M_ERR, "Read error on passphrase file: '%s'",
passphrase_file);
md_ctx_update(&md, buf, size);
total_size += size;
}
close (fd);
warn_if_group_others_accessible (passphrase_file);
if (total_size < min_passphrase_size)
msg (M_FATAL,
"Passphrase file '%s' is too small (must have at least %d characters)",
passphrase_file, min_passphrase_size);
}
md_ctx_final(&md, output);
md_ctx_cleanup(&md);
return md_kt_size(digest);
}
/*
* Write key to file, return number of random bits
* written.
*/
int
write_key_file (const int nkeys, const char *filename)
{
struct gc_arena gc = gc_new ();
int fd, i;
int nbits = 0;
/* must be large enough to hold full key file */
struct buffer out = alloc_buf_gc (2048, &gc);
struct buffer nbits_head_text = alloc_buf_gc (128, &gc);
/* how to format the ascii file representation of key */
const int bytes_per_line = 16;
/* open key file */
fd = platform_open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd == -1)
msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
buf_printf (&out, "%s\n", static_key_head);
for (i = 0; i < nkeys; ++i)
{
struct key key;
char* fmt;
/* generate random bits */
generate_key_random (&key, NULL);
/* format key as ascii */
fmt = format_hex_ex ((const uint8_t*)&key,
sizeof (key),
0,
bytes_per_line,
"\n",
&gc);
/* increment random bits counter */
nbits += sizeof (key) * 8;
/* write to holding buffer */
buf_printf (&out, "%s\n", fmt);
/* zero memory which held key component (will be freed by GC) */
memset (fmt, 0, strlen(fmt));
CLEAR (key);
}
buf_printf (&out, "%s\n", static_key_foot);
/* write number of bits */
buf_printf (&nbits_head_text, "#\n# %d bit OpenVPN static key\n#\n", nbits);
buf_write_string_file (&nbits_head_text, filename, fd);
/* write key file, now formatted in out, to file */
buf_write_string_file (&out, filename, fd);
if (close (fd))
msg (M_ERR, "Close error on shared secret file %s", filename);
/* zero memory which held file content (memory will be freed by GC) */
buf_clear (&out);
/* pop our garbage collection level */
gc_free (&gc);
return nbits;
}
void
must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
{
if (key2->n < n)
{
#ifdef ENABLE_SMALL
msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
#else
msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE " --genkey --secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter", filename, option, key2->n, n, option);
#endif
}
}
int
ascii2keydirection (int msglevel, const char *str)
{
if (!str)
return KEY_DIRECTION_BIDIRECTIONAL;
else if (!strcmp (str, "0"))
return KEY_DIRECTION_NORMAL;
else if (!strcmp (str, "1"))
return KEY_DIRECTION_INVERSE;
else
{
msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
return -1;
}
return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
}
const char *
keydirection2ascii (int kd, bool remote)
{
if (kd == KEY_DIRECTION_BIDIRECTIONAL)
return NULL;
else if (kd == KEY_DIRECTION_NORMAL)
return remote ? "1" : "0";
else if (kd == KEY_DIRECTION_INVERSE)
return remote ? "0" : "1";
else
{
ASSERT (0);
}
return NULL; /* NOTREACHED */
}
void
key_direction_state_init (struct key_direction_state *kds, int key_direction)
{
CLEAR (*kds);
switch (key_direction)
{
case KEY_DIRECTION_NORMAL:
kds->out_key = 0;
kds->in_key = 1;
kds->need_keys = 2;
break;
case KEY_DIRECTION_INVERSE:
kds->out_key = 1;
kds->in_key = 0;
kds->need_keys = 2;
break;
case KEY_DIRECTION_BIDIRECTIONAL:
kds->out_key = 0;
kds->in_key = 0;
kds->need_keys = 1;
break;
default:
ASSERT (0);
}
}
void
verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
{
int i;
for (i = 0; i < key2->n; ++i)
{
/* Fix parity for DES keys and make sure not a weak key */
fixup_key (&key2->keys[i], kt);
/* This should be a very improbable failure */
if (!check_key (&key2->keys[i], kt))
msg (M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
i+1, shared_secret_file);
}
}
/* given a key and key_type, write key to buffer */
bool
write_key (const struct key *key, const struct key_type *kt,
struct buffer *buf)
{
ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
&& kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
if (!buf_write (buf, &kt->cipher_length, 1))
return false;
if (!buf_write (buf, &kt->hmac_length, 1))
return false;
if (!buf_write (buf, key->cipher, kt->cipher_length))
return false;
if (!buf_write (buf, key->hmac, kt->hmac_length))
return false;
return true;
}
/*
* Given a key_type and buffer, read key from buffer.
* Return: 1 on success
* -1 read failure
* 0 on key length mismatch
*/
int
read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
{
uint8_t cipher_length;
uint8_t hmac_length;
CLEAR (*key);
if (!buf_read (buf, &cipher_length, 1))
goto read_err;
if (!buf_read (buf, &hmac_length, 1))
goto read_err;
if (!buf_read (buf, key->cipher, cipher_length))
goto read_err;
if (!buf_read (buf, key->hmac, hmac_length))
goto read_err;
if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
goto key_len_err;
return 1;
read_err:
msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
return -1;
key_len_err:
msg (D_TLS_ERRORS,
"TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
return 0;
}
/*
* Random number functions, used in cases where we want
* reasonably strong cryptographic random number generation
* without depleting our entropy pool. Used for random
* IV values and a number of other miscellaneous tasks.
*/
static uint8_t *nonce_data = NULL; /* GLOBAL */
static const md_kt_t *nonce_md = NULL; /* GLOBAL */
static int nonce_secret_len = 0; /* GLOBAL */
/* Reset the nonce value, also done periodically to refresh entropy */
static void
prng_reset_nonce ()
{
const int size = md_kt_size (nonce_md) + nonce_secret_len;
#if 1 /* Must be 1 for real usage */
if (!rand_bytes (nonce_data, size))
msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG");
#else
/* Only for testing -- will cause a predictable PRNG sequence */
{
int i;
for (i = 0; i < size; ++i)
nonce_data[i] = (uint8_t) i;
}
#endif
}
void
prng_init (const char *md_name, const int nonce_secret_len_parm)
{
prng_uninit ();
nonce_md = md_name ? md_kt_get (md_name) : NULL;
if (nonce_md)
{
ASSERT (nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX);
nonce_secret_len = nonce_secret_len_parm;
{
const int size = md_kt_size(nonce_md) + nonce_secret_len;
dmsg (D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", md_kt_name(nonce_md), size);
nonce_data = (uint8_t*) malloc (size);
check_malloc_return (nonce_data);
prng_reset_nonce();
}
}
}
void
prng_uninit (void)
{
free (nonce_data);
nonce_data = NULL;
nonce_md = NULL;
nonce_secret_len = 0;
}
void
prng_bytes (uint8_t *output, int len)
{
static size_t processed = 0;
if (nonce_md)
{
const int md_size = md_kt_size (nonce_md);
while (len > 0)
{
unsigned int outlen = 0;
const int blen = min_int (len, md_size);
md_full(nonce_md, nonce_data, md_size + nonce_secret_len, nonce_data);
memcpy (output, nonce_data, blen);
output += blen;
len -= blen;
/* Ensure that random data is reset regularly */
processed += blen;
if(processed > PRNG_NONCE_RESET_BYTES) {
prng_reset_nonce();
processed = 0;
}
}
}
else
rand_bytes (output, len);
}
/* an analogue to the random() function, but use prng_bytes */
long int
get_random()
{
long int l;
prng_bytes ((unsigned char *)&l, sizeof(l));
if (l < 0)
l = -l;
return l;
}
#ifndef ENABLE_SSL
void
init_ssl_lib (void)
{
crypto_init_lib ();
}
void
free_ssl_lib (void)
{
crypto_uninit_lib ();
prng_uninit();
}
#endif /* ENABLE_SSL */
/*
* md5 functions
*/
const char *
md5sum (uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc)
{
uint8_t digest[MD5_DIGEST_LENGTH];
const md_kt_t *md5_kt = md_kt_get("MD5");
md_full(md5_kt, buf, len, digest);
return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars, gc);
}
void
md5_state_init (struct md5_state *s)
{
const md_kt_t *md5_kt = md_kt_get("MD5");
md_ctx_init(&s->ctx, md5_kt);
}
void
md5_state_update (struct md5_state *s, void *data, size_t len)
{
md_ctx_update(&s->ctx, data, len);
}
void
md5_state_final (struct md5_state *s, struct md5_digest *out)
{
md_ctx_final(&s->ctx, out->digest);
md_ctx_cleanup(&s->ctx);
}
void
md5_digest_clear (struct md5_digest *digest)
{
CLEAR (*digest);
}
bool
md5_digest_defined (const struct md5_digest *digest)
{
int i;
for (i = 0; i < MD5_DIGEST_LENGTH; ++i)
if (digest->digest[i])
return true;
return false;
}
bool
md5_digest_equal (const struct md5_digest *d1, const struct md5_digest *d2)
{
return memcmp(d1->digest, d2->digest, MD5_DIGEST_LENGTH) == 0;
}
#endif /* ENABLE_CRYPTO */
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_5636_1 |
crossvul-cpp_data_bad_2958_3 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
#include "vim.h"
#ifdef AMIGA
# include <time.h> /* for time() */
#endif
/*
* Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)
* It has been changed beyond recognition since then.
*
* Differences between version 7.4 and 8.x can be found with ":help version8".
* Differences between version 6.4 and 7.x can be found with ":help version7".
* Differences between version 5.8 and 6.x can be found with ":help version6".
* Differences between version 4.x and 5.x can be found with ":help version5".
* Differences between version 3.0 and 4.x can be found with ":help version4".
* All the remarks about older versions have been removed, they are not very
* interesting.
*/
#include "version.h"
char *Version = VIM_VERSION_SHORT;
static char *mediumVersion = VIM_VERSION_MEDIUM;
#if defined(HAVE_DATE_TIME) || defined(PROTO)
# if (defined(VMS) && defined(VAXC)) || defined(PROTO)
char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)
+ sizeof(__TIME__) + 3];
void
make_version(void)
{
/*
* Construct the long version string. Necessary because
* VAX C can't catenate strings in the preprocessor.
*/
strcpy(longVersion, VIM_VERSION_LONG_DATE);
strcat(longVersion, __DATE__);
strcat(longVersion, " ");
strcat(longVersion, __TIME__);
strcat(longVersion, ")");
}
# else
char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")";
# endif
#else
char *longVersion = VIM_VERSION_LONG;
#endif
static void list_features(void);
static void version_msg(char *s);
static char *(features[]) =
{
#ifdef HAVE_ACL
"+acl",
#else
"-acl",
#endif
#ifdef AMIGA /* only for Amiga systems */
# ifdef FEAT_ARP
"+ARP",
# else
"-ARP",
# endif
#endif
#ifdef FEAT_ARABIC
"+arabic",
#else
"-arabic",
#endif
#ifdef FEAT_AUTOCMD
"+autocmd",
#else
"-autocmd",
#endif
#ifdef FEAT_BEVAL
"+balloon_eval",
#else
"-balloon_eval",
#endif
#ifdef FEAT_BROWSE
"+browse",
#else
"-browse",
#endif
#ifdef NO_BUILTIN_TCAPS
"-builtin_terms",
#endif
#ifdef SOME_BUILTIN_TCAPS
"+builtin_terms",
#endif
#ifdef ALL_BUILTIN_TCAPS
"++builtin_terms",
#endif
#ifdef FEAT_BYTEOFF
"+byte_offset",
#else
"-byte_offset",
#endif
#ifdef FEAT_JOB_CHANNEL
"+channel",
#else
"-channel",
#endif
#ifdef FEAT_CINDENT
"+cindent",
#else
"-cindent",
#endif
#ifdef FEAT_CLIENTSERVER
"+clientserver",
#else
"-clientserver",
#endif
#ifdef FEAT_CLIPBOARD
"+clipboard",
#else
"-clipboard",
#endif
#ifdef FEAT_CMDL_COMPL
"+cmdline_compl",
#else
"-cmdline_compl",
#endif
#ifdef FEAT_CMDHIST
"+cmdline_hist",
#else
"-cmdline_hist",
#endif
#ifdef FEAT_CMDL_INFO
"+cmdline_info",
#else
"-cmdline_info",
#endif
#ifdef FEAT_COMMENTS
"+comments",
#else
"-comments",
#endif
#ifdef FEAT_CONCEAL
"+conceal",
#else
"-conceal",
#endif
#ifdef FEAT_CRYPT
"+cryptv",
#else
"-cryptv",
#endif
#ifdef FEAT_CSCOPE
"+cscope",
#else
"-cscope",
#endif
#ifdef FEAT_CURSORBIND
"+cursorbind",
#else
"-cursorbind",
#endif
#ifdef CURSOR_SHAPE
"+cursorshape",
#else
"-cursorshape",
#endif
#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)
"+dialog_con_gui",
#else
# if defined(FEAT_CON_DIALOG)
"+dialog_con",
# else
# if defined(FEAT_GUI_DIALOG)
"+dialog_gui",
# else
"-dialog",
# endif
# endif
#endif
#ifdef FEAT_DIFF
"+diff",
#else
"-diff",
#endif
#ifdef FEAT_DIGRAPHS
"+digraphs",
#else
"-digraphs",
#endif
#ifdef FEAT_GUI_W32
# ifdef FEAT_DIRECTX
"+directx",
# else
"-directx",
# endif
#endif
#ifdef FEAT_DND
"+dnd",
#else
"-dnd",
#endif
#ifdef EBCDIC
"+ebcdic",
#else
"-ebcdic",
#endif
#ifdef FEAT_EMACS_TAGS
"+emacs_tags",
#else
"-emacs_tags",
#endif
#ifdef FEAT_EVAL
"+eval",
#else
"-eval",
#endif
"+ex_extra",
#ifdef FEAT_SEARCH_EXTRA
"+extra_search",
#else
"-extra_search",
#endif
#ifdef FEAT_FKMAP
"+farsi",
#else
"-farsi",
#endif
#ifdef FEAT_SEARCHPATH
"+file_in_path",
#else
"-file_in_path",
#endif
#ifdef FEAT_FIND_ID
"+find_in_path",
#else
"-find_in_path",
#endif
#ifdef FEAT_FLOAT
"+float",
#else
"-float",
#endif
#ifdef FEAT_FOLDING
"+folding",
#else
"-folding",
#endif
#ifdef FEAT_FOOTER
"+footer",
#else
"-footer",
#endif
/* only interesting on Unix systems */
#if !defined(USE_SYSTEM) && defined(UNIX)
"+fork()",
#endif
#ifdef FEAT_GETTEXT
# ifdef DYNAMIC_GETTEXT
"+gettext/dyn",
# else
"+gettext",
# endif
#else
"-gettext",
#endif
#ifdef FEAT_HANGULIN
"+hangul_input",
#else
"-hangul_input",
#endif
#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)
# ifdef DYNAMIC_ICONV
"+iconv/dyn",
# else
"+iconv",
# endif
#else
"-iconv",
#endif
#ifdef FEAT_INS_EXPAND
"+insert_expand",
#else
"-insert_expand",
#endif
#ifdef FEAT_JOB_CHANNEL
"+job",
#else
"-job",
#endif
#ifdef FEAT_JUMPLIST
"+jumplist",
#else
"-jumplist",
#endif
#ifdef FEAT_KEYMAP
"+keymap",
#else
"-keymap",
#endif
#ifdef FEAT_EVAL
"+lambda",
#else
"-lambda",
#endif
#ifdef FEAT_LANGMAP
"+langmap",
#else
"-langmap",
#endif
#ifdef FEAT_LIBCALL
"+libcall",
#else
"-libcall",
#endif
#ifdef FEAT_LINEBREAK
"+linebreak",
#else
"-linebreak",
#endif
#ifdef FEAT_LISP
"+lispindent",
#else
"-lispindent",
#endif
#ifdef FEAT_LISTCMDS
"+listcmds",
#else
"-listcmds",
#endif
#ifdef FEAT_LOCALMAP
"+localmap",
#else
"-localmap",
#endif
#ifdef FEAT_LUA
# ifdef DYNAMIC_LUA
"+lua/dyn",
# else
"+lua",
# endif
#else
"-lua",
#endif
#ifdef FEAT_MENU
"+menu",
#else
"-menu",
#endif
#ifdef FEAT_SESSION
"+mksession",
#else
"-mksession",
#endif
#ifdef FEAT_MODIFY_FNAME
"+modify_fname",
#else
"-modify_fname",
#endif
#ifdef FEAT_MOUSE
"+mouse",
# ifdef FEAT_MOUSESHAPE
"+mouseshape",
# else
"-mouseshape",
# endif
# else
"-mouse",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_DEC
"+mouse_dec",
# else
"-mouse_dec",
# endif
# ifdef FEAT_MOUSE_GPM
"+mouse_gpm",
# else
"-mouse_gpm",
# endif
# ifdef FEAT_MOUSE_JSB
"+mouse_jsbterm",
# else
"-mouse_jsbterm",
# endif
# ifdef FEAT_MOUSE_NET
"+mouse_netterm",
# else
"-mouse_netterm",
# endif
#endif
#ifdef __QNX__
# ifdef FEAT_MOUSE_PTERM
"+mouse_pterm",
# else
"-mouse_pterm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_SGR
"+mouse_sgr",
# else
"-mouse_sgr",
# endif
# ifdef FEAT_SYSMOUSE
"+mouse_sysmouse",
# else
"-mouse_sysmouse",
# endif
# ifdef FEAT_MOUSE_URXVT
"+mouse_urxvt",
# else
"-mouse_urxvt",
# endif
# ifdef FEAT_MOUSE_XTERM
"+mouse_xterm",
# else
"-mouse_xterm",
# endif
#endif
#ifdef FEAT_MBYTE_IME
# ifdef DYNAMIC_IME
"+multi_byte_ime/dyn",
# else
"+multi_byte_ime",
# endif
#else
# ifdef FEAT_MBYTE
"+multi_byte",
# else
"-multi_byte",
# endif
#endif
#ifdef FEAT_MULTI_LANG
"+multi_lang",
#else
"-multi_lang",
#endif
#ifdef FEAT_MZSCHEME
# ifdef DYNAMIC_MZSCHEME
"+mzscheme/dyn",
# else
"+mzscheme",
# endif
#else
"-mzscheme",
#endif
#ifdef FEAT_NETBEANS_INTG
"+netbeans_intg",
#else
"-netbeans_intg",
#endif
#ifdef FEAT_NUM64
"+num64",
#else
"-num64",
#endif
#ifdef FEAT_GUI_W32
# ifdef FEAT_OLE
"+ole",
# else
"-ole",
# endif
#endif
"+packages",
#ifdef FEAT_PATH_EXTRA
"+path_extra",
#else
"-path_extra",
#endif
#ifdef FEAT_PERL
# ifdef DYNAMIC_PERL
"+perl/dyn",
# else
"+perl",
# endif
#else
"-perl",
#endif
#ifdef FEAT_PERSISTENT_UNDO
"+persistent_undo",
#else
"-persistent_undo",
#endif
#ifdef FEAT_PRINTER
# ifdef FEAT_POSTSCRIPT
"+postscript",
# else
"-postscript",
# endif
"+printer",
#else
"-printer",
#endif
#ifdef FEAT_PROFILE
"+profile",
#else
"-profile",
#endif
#ifdef FEAT_PYTHON
# ifdef DYNAMIC_PYTHON
"+python/dyn",
# else
"+python",
# endif
#else
"-python",
#endif
#ifdef FEAT_PYTHON3
# ifdef DYNAMIC_PYTHON3
"+python3/dyn",
# else
"+python3",
# endif
#else
"-python3",
#endif
#ifdef FEAT_QUICKFIX
"+quickfix",
#else
"-quickfix",
#endif
#ifdef FEAT_RELTIME
"+reltime",
#else
"-reltime",
#endif
#ifdef FEAT_RIGHTLEFT
"+rightleft",
#else
"-rightleft",
#endif
#ifdef FEAT_RUBY
# ifdef DYNAMIC_RUBY
"+ruby/dyn",
# else
"+ruby",
# endif
#else
"-ruby",
#endif
#ifdef FEAT_SCROLLBIND
"+scrollbind",
#else
"-scrollbind",
#endif
#ifdef FEAT_SIGNS
"+signs",
#else
"-signs",
#endif
#ifdef FEAT_SMARTINDENT
"+smartindent",
#else
"-smartindent",
#endif
#ifdef STARTUPTIME
"+startuptime",
#else
"-startuptime",
#endif
#ifdef FEAT_STL_OPT
"+statusline",
#else
"-statusline",
#endif
#ifdef FEAT_SUN_WORKSHOP
"+sun_workshop",
#else
"-sun_workshop",
#endif
#ifdef FEAT_SYN_HL
"+syntax",
#else
"-syntax",
#endif
/* only interesting on Unix systems */
#if defined(USE_SYSTEM) && defined(UNIX)
"+system()",
#endif
#ifdef FEAT_TAG_BINS
"+tag_binary",
#else
"-tag_binary",
#endif
#ifdef FEAT_TAG_OLDSTATIC
"+tag_old_static",
#else
"-tag_old_static",
#endif
#ifdef FEAT_TAG_ANYWHITE
"+tag_any_white",
#else
"-tag_any_white",
#endif
#ifdef FEAT_TCL
# ifdef DYNAMIC_TCL
"+tcl/dyn",
# else
"+tcl",
# endif
#else
"-tcl",
#endif
#ifdef FEAT_TERMGUICOLORS
"+termguicolors",
#else
"-termguicolors",
#endif
#ifdef FEAT_TERMINAL
"+terminal",
#else
"-terminal",
#endif
#if defined(UNIX)
/* only Unix can have terminfo instead of termcap */
# ifdef TERMINFO
"+terminfo",
# else
"-terminfo",
# endif
#else /* unix always includes termcap support */
# ifdef HAVE_TGETENT
"+tgetent",
# else
"-tgetent",
# endif
#endif
#ifdef FEAT_TERMRESPONSE
"+termresponse",
#else
"-termresponse",
#endif
#ifdef FEAT_TEXTOBJ
"+textobjects",
#else
"-textobjects",
#endif
#ifdef FEAT_TIMERS
"+timers",
#else
"-timers",
#endif
#ifdef FEAT_TITLE
"+title",
#else
"-title",
#endif
#ifdef FEAT_TOOLBAR
"+toolbar",
#else
"-toolbar",
#endif
#ifdef FEAT_USR_CMDS
"+user_commands",
#else
"-user_commands",
#endif
"+vertsplit",
#ifdef FEAT_VIRTUALEDIT
"+virtualedit",
#else
"-virtualedit",
#endif
"+visual",
#ifdef FEAT_VISUALEXTRA
"+visualextra",
#else
"-visualextra",
#endif
#ifdef FEAT_VIMINFO
"+viminfo",
#else
"-viminfo",
#endif
#ifdef FEAT_VREPLACE
"+vreplace",
#else
"-vreplace",
#endif
#ifdef FEAT_WILDIGN
"+wildignore",
#else
"-wildignore",
#endif
#ifdef FEAT_WILDMENU
"+wildmenu",
#else
"-wildmenu",
#endif
"+windows",
#ifdef FEAT_WRITEBACKUP
"+writebackup",
#else
"-writebackup",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_X11
"+X11",
# else
"-X11",
# endif
#endif
#ifdef FEAT_XFONTSET
"+xfontset",
#else
"-xfontset",
#endif
#ifdef FEAT_XIM
"+xim",
#else
"-xim",
#endif
#ifdef WIN3264
# ifdef FEAT_XPM_W32
"+xpm_w32",
# else
"-xpm_w32",
# endif
#else
# ifdef HAVE_XPM
"+xpm",
# else
"-xpm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef USE_XSMP_INTERACT
"+xsmp_interact",
# else
# ifdef USE_XSMP
"+xsmp",
# else
"-xsmp",
# endif
# endif
# ifdef FEAT_XCLIPBOARD
"+xterm_clipboard",
# else
"-xterm_clipboard",
# endif
#endif
#ifdef FEAT_XTERM_SAVE
"+xterm_save",
#else
"-xterm_save",
#endif
NULL
};
static int included_patches[] =
{ /* Add new patch number below this line */
/**/
1262,
/**/
1261,
/**/
1260,
/**/
1259,
/**/
1258,
/**/
1257,
/**/
1256,
/**/
1255,
/**/
1254,
/**/
1253,
/**/
1252,
/**/
1251,
/**/
1250,
/**/
1249,
/**/
1248,
/**/
1247,
/**/
1246,
/**/
1245,
/**/
1244,
/**/
1243,
/**/
1242,
/**/
1241,
/**/
1240,
/**/
1239,
/**/
1238,
/**/
1237,
/**/
1236,
/**/
1235,
/**/
1234,
/**/
1233,
/**/
1232,
/**/
1231,
/**/
1230,
/**/
1229,
/**/
1228,
/**/
1227,
/**/
1226,
/**/
1225,
/**/
1224,
/**/
1223,
/**/
1222,
/**/
1221,
/**/
1220,
/**/
1219,
/**/
1218,
/**/
1217,
/**/
1216,
/**/
1215,
/**/
1214,
/**/
1213,
/**/
1212,
/**/
1211,
/**/
1210,
/**/
1209,
/**/
1208,
/**/
1207,
/**/
1206,
/**/
1205,
/**/
1204,
/**/
1203,
/**/
1202,
/**/
1201,
/**/
1200,
/**/
1199,
/**/
1198,
/**/
1197,
/**/
1196,
/**/
1195,
/**/
1194,
/**/
1193,
/**/
1192,
/**/
1191,
/**/
1190,
/**/
1189,
/**/
1188,
/**/
1187,
/**/
1186,
/**/
1185,
/**/
1184,
/**/
1183,
/**/
1182,
/**/
1181,
/**/
1180,
/**/
1179,
/**/
1178,
/**/
1177,
/**/
1176,
/**/
1175,
/**/
1174,
/**/
1173,
/**/
1172,
/**/
1171,
/**/
1170,
/**/
1169,
/**/
1168,
/**/
1167,
/**/
1166,
/**/
1165,
/**/
1164,
/**/
1163,
/**/
1162,
/**/
1161,
/**/
1160,
/**/
1159,
/**/
1158,
/**/
1157,
/**/
1156,
/**/
1155,
/**/
1154,
/**/
1153,
/**/
1152,
/**/
1151,
/**/
1150,
/**/
1149,
/**/
1148,
/**/
1147,
/**/
1146,
/**/
1145,
/**/
1144,
/**/
1143,
/**/
1142,
/**/
1141,
/**/
1140,
/**/
1139,
/**/
1138,
/**/
1137,
/**/
1136,
/**/
1135,
/**/
1134,
/**/
1133,
/**/
1132,
/**/
1131,
/**/
1130,
/**/
1129,
/**/
1128,
/**/
1127,
/**/
1126,
/**/
1125,
/**/
1124,
/**/
1123,
/**/
1122,
/**/
1121,
/**/
1120,
/**/
1119,
/**/
1118,
/**/
1117,
/**/
1116,
/**/
1115,
/**/
1114,
/**/
1113,
/**/
1112,
/**/
1111,
/**/
1110,
/**/
1109,
/**/
1108,
/**/
1107,
/**/
1106,
/**/
1105,
/**/
1104,
/**/
1103,
/**/
1102,
/**/
1101,
/**/
1100,
/**/
1099,
/**/
1098,
/**/
1097,
/**/
1096,
/**/
1095,
/**/
1094,
/**/
1093,
/**/
1092,
/**/
1091,
/**/
1090,
/**/
1089,
/**/
1088,
/**/
1087,
/**/
1086,
/**/
1085,
/**/
1084,
/**/
1083,
/**/
1082,
/**/
1081,
/**/
1080,
/**/
1079,
/**/
1078,
/**/
1077,
/**/
1076,
/**/
1075,
/**/
1074,
/**/
1073,
/**/
1072,
/**/
1071,
/**/
1070,
/**/
1069,
/**/
1068,
/**/
1067,
/**/
1066,
/**/
1065,
/**/
1064,
/**/
1063,
/**/
1062,
/**/
1061,
/**/
1060,
/**/
1059,
/**/
1058,
/**/
1057,
/**/
1056,
/**/
1055,
/**/
1054,
/**/
1053,
/**/
1052,
/**/
1051,
/**/
1050,
/**/
1049,
/**/
1048,
/**/
1047,
/**/
1046,
/**/
1045,
/**/
1044,
/**/
1043,
/**/
1042,
/**/
1041,
/**/
1040,
/**/
1039,
/**/
1038,
/**/
1037,
/**/
1036,
/**/
1035,
/**/
1034,
/**/
1033,
/**/
1032,
/**/
1031,
/**/
1030,
/**/
1029,
/**/
1028,
/**/
1027,
/**/
1026,
/**/
1025,
/**/
1024,
/**/
1023,
/**/
1022,
/**/
1021,
/**/
1020,
/**/
1019,
/**/
1018,
/**/
1017,
/**/
1016,
/**/
1015,
/**/
1014,
/**/
1013,
/**/
1012,
/**/
1011,
/**/
1010,
/**/
1009,
/**/
1008,
/**/
1007,
/**/
1006,
/**/
1005,
/**/
1004,
/**/
1003,
/**/
1002,
/**/
1001,
/**/
1000,
/**/
999,
/**/
998,
/**/
997,
/**/
996,
/**/
995,
/**/
994,
/**/
993,
/**/
992,
/**/
991,
/**/
990,
/**/
989,
/**/
988,
/**/
987,
/**/
986,
/**/
985,
/**/
984,
/**/
983,
/**/
982,
/**/
981,
/**/
980,
/**/
979,
/**/
978,
/**/
977,
/**/
976,
/**/
975,
/**/
974,
/**/
973,
/**/
972,
/**/
971,
/**/
970,
/**/
969,
/**/
968,
/**/
967,
/**/
966,
/**/
965,
/**/
964,
/**/
963,
/**/
962,
/**/
961,
/**/
960,
/**/
959,
/**/
958,
/**/
957,
/**/
956,
/**/
955,
/**/
954,
/**/
953,
/**/
952,
/**/
951,
/**/
950,
/**/
949,
/**/
948,
/**/
947,
/**/
946,
/**/
945,
/**/
944,
/**/
943,
/**/
942,
/**/
941,
/**/
940,
/**/
939,
/**/
938,
/**/
937,
/**/
936,
/**/
935,
/**/
934,
/**/
933,
/**/
932,
/**/
931,
/**/
930,
/**/
929,
/**/
928,
/**/
927,
/**/
926,
/**/
925,
/**/
924,
/**/
923,
/**/
922,
/**/
921,
/**/
920,
/**/
919,
/**/
918,
/**/
917,
/**/
916,
/**/
915,
/**/
914,
/**/
913,
/**/
912,
/**/
911,
/**/
910,
/**/
909,
/**/
908,
/**/
907,
/**/
906,
/**/
905,
/**/
904,
/**/
903,
/**/
902,
/**/
901,
/**/
900,
/**/
899,
/**/
898,
/**/
897,
/**/
896,
/**/
895,
/**/
894,
/**/
893,
/**/
892,
/**/
891,
/**/
890,
/**/
889,
/**/
888,
/**/
887,
/**/
886,
/**/
885,
/**/
884,
/**/
883,
/**/
882,
/**/
881,
/**/
880,
/**/
879,
/**/
878,
/**/
877,
/**/
876,
/**/
875,
/**/
874,
/**/
873,
/**/
872,
/**/
871,
/**/
870,
/**/
869,
/**/
868,
/**/
867,
/**/
866,
/**/
865,
/**/
864,
/**/
863,
/**/
862,
/**/
861,
/**/
860,
/**/
859,
/**/
858,
/**/
857,
/**/
856,
/**/
855,
/**/
854,
/**/
853,
/**/
852,
/**/
851,
/**/
850,
/**/
849,
/**/
848,
/**/
847,
/**/
846,
/**/
845,
/**/
844,
/**/
843,
/**/
842,
/**/
841,
/**/
840,
/**/
839,
/**/
838,
/**/
837,
/**/
836,
/**/
835,
/**/
834,
/**/
833,
/**/
832,
/**/
831,
/**/
830,
/**/
829,
/**/
828,
/**/
827,
/**/
826,
/**/
825,
/**/
824,
/**/
823,
/**/
822,
/**/
821,
/**/
820,
/**/
819,
/**/
818,
/**/
817,
/**/
816,
/**/
815,
/**/
814,
/**/
813,
/**/
812,
/**/
811,
/**/
810,
/**/
809,
/**/
808,
/**/
807,
/**/
806,
/**/
805,
/**/
804,
/**/
803,
/**/
802,
/**/
801,
/**/
800,
/**/
799,
/**/
798,
/**/
797,
/**/
796,
/**/
795,
/**/
794,
/**/
793,
/**/
792,
/**/
791,
/**/
790,
/**/
789,
/**/
788,
/**/
787,
/**/
786,
/**/
785,
/**/
784,
/**/
783,
/**/
782,
/**/
781,
/**/
780,
/**/
779,
/**/
778,
/**/
777,
/**/
776,
/**/
775,
/**/
774,
/**/
773,
/**/
772,
/**/
771,
/**/
770,
/**/
769,
/**/
768,
/**/
767,
/**/
766,
/**/
765,
/**/
764,
/**/
763,
/**/
762,
/**/
761,
/**/
760,
/**/
759,
/**/
758,
/**/
757,
/**/
756,
/**/
755,
/**/
754,
/**/
753,
/**/
752,
/**/
751,
/**/
750,
/**/
749,
/**/
748,
/**/
747,
/**/
746,
/**/
745,
/**/
744,
/**/
743,
/**/
742,
/**/
741,
/**/
740,
/**/
739,
/**/
738,
/**/
737,
/**/
736,
/**/
735,
/**/
734,
/**/
733,
/**/
732,
/**/
731,
/**/
730,
/**/
729,
/**/
728,
/**/
727,
/**/
726,
/**/
725,
/**/
724,
/**/
723,
/**/
722,
/**/
721,
/**/
720,
/**/
719,
/**/
718,
/**/
717,
/**/
716,
/**/
715,
/**/
714,
/**/
713,
/**/
712,
/**/
711,
/**/
710,
/**/
709,
/**/
708,
/**/
707,
/**/
706,
/**/
705,
/**/
704,
/**/
703,
/**/
702,
/**/
701,
/**/
700,
/**/
699,
/**/
698,
/**/
697,
/**/
696,
/**/
695,
/**/
694,
/**/
693,
/**/
692,
/**/
691,
/**/
690,
/**/
689,
/**/
688,
/**/
687,
/**/
686,
/**/
685,
/**/
684,
/**/
683,
/**/
682,
/**/
681,
/**/
680,
/**/
679,
/**/
678,
/**/
677,
/**/
676,
/**/
675,
/**/
674,
/**/
673,
/**/
672,
/**/
671,
/**/
670,
/**/
669,
/**/
668,
/**/
667,
/**/
666,
/**/
665,
/**/
664,
/**/
663,
/**/
662,
/**/
661,
/**/
660,
/**/
659,
/**/
658,
/**/
657,
/**/
656,
/**/
655,
/**/
654,
/**/
653,
/**/
652,
/**/
651,
/**/
650,
/**/
649,
/**/
648,
/**/
647,
/**/
646,
/**/
645,
/**/
644,
/**/
643,
/**/
642,
/**/
641,
/**/
640,
/**/
639,
/**/
638,
/**/
637,
/**/
636,
/**/
635,
/**/
634,
/**/
633,
/**/
632,
/**/
631,
/**/
630,
/**/
629,
/**/
628,
/**/
627,
/**/
626,
/**/
625,
/**/
624,
/**/
623,
/**/
622,
/**/
621,
/**/
620,
/**/
619,
/**/
618,
/**/
617,
/**/
616,
/**/
615,
/**/
614,
/**/
613,
/**/
612,
/**/
611,
/**/
610,
/**/
609,
/**/
608,
/**/
607,
/**/
606,
/**/
605,
/**/
604,
/**/
603,
/**/
602,
/**/
601,
/**/
600,
/**/
599,
/**/
598,
/**/
597,
/**/
596,
/**/
595,
/**/
594,
/**/
593,
/**/
592,
/**/
591,
/**/
590,
/**/
589,
/**/
588,
/**/
587,
/**/
586,
/**/
585,
/**/
584,
/**/
583,
/**/
582,
/**/
581,
/**/
580,
/**/
579,
/**/
578,
/**/
577,
/**/
576,
/**/
575,
/**/
574,
/**/
573,
/**/
572,
/**/
571,
/**/
570,
/**/
569,
/**/
568,
/**/
567,
/**/
566,
/**/
565,
/**/
564,
/**/
563,
/**/
562,
/**/
561,
/**/
560,
/**/
559,
/**/
558,
/**/
557,
/**/
556,
/**/
555,
/**/
554,
/**/
553,
/**/
552,
/**/
551,
/**/
550,
/**/
549,
/**/
548,
/**/
547,
/**/
546,
/**/
545,
/**/
544,
/**/
543,
/**/
542,
/**/
541,
/**/
540,
/**/
539,
/**/
538,
/**/
537,
/**/
536,
/**/
535,
/**/
534,
/**/
533,
/**/
532,
/**/
531,
/**/
530,
/**/
529,
/**/
528,
/**/
527,
/**/
526,
/**/
525,
/**/
524,
/**/
523,
/**/
522,
/**/
521,
/**/
520,
/**/
519,
/**/
518,
/**/
517,
/**/
516,
/**/
515,
/**/
514,
/**/
513,
/**/
512,
/**/
511,
/**/
510,
/**/
509,
/**/
508,
/**/
507,
/**/
506,
/**/
505,
/**/
504,
/**/
503,
/**/
502,
/**/
501,
/**/
500,
/**/
499,
/**/
498,
/**/
497,
/**/
496,
/**/
495,
/**/
494,
/**/
493,
/**/
492,
/**/
491,
/**/
490,
/**/
489,
/**/
488,
/**/
487,
/**/
486,
/**/
485,
/**/
484,
/**/
483,
/**/
482,
/**/
481,
/**/
480,
/**/
479,
/**/
478,
/**/
477,
/**/
476,
/**/
475,
/**/
474,
/**/
473,
/**/
472,
/**/
471,
/**/
470,
/**/
469,
/**/
468,
/**/
467,
/**/
466,
/**/
465,
/**/
464,
/**/
463,
/**/
462,
/**/
461,
/**/
460,
/**/
459,
/**/
458,
/**/
457,
/**/
456,
/**/
455,
/**/
454,
/**/
453,
/**/
452,
/**/
451,
/**/
450,
/**/
449,
/**/
448,
/**/
447,
/**/
446,
/**/
445,
/**/
444,
/**/
443,
/**/
442,
/**/
441,
/**/
440,
/**/
439,
/**/
438,
/**/
437,
/**/
436,
/**/
435,
/**/
434,
/**/
433,
/**/
432,
/**/
431,
/**/
430,
/**/
429,
/**/
428,
/**/
427,
/**/
426,
/**/
425,
/**/
424,
/**/
423,
/**/
422,
/**/
421,
/**/
420,
/**/
419,
/**/
418,
/**/
417,
/**/
416,
/**/
415,
/**/
414,
/**/
413,
/**/
412,
/**/
411,
/**/
410,
/**/
409,
/**/
408,
/**/
407,
/**/
406,
/**/
405,
/**/
404,
/**/
403,
/**/
402,
/**/
401,
/**/
400,
/**/
399,
/**/
398,
/**/
397,
/**/
396,
/**/
395,
/**/
394,
/**/
393,
/**/
392,
/**/
391,
/**/
390,
/**/
389,
/**/
388,
/**/
387,
/**/
386,
/**/
385,
/**/
384,
/**/
383,
/**/
382,
/**/
381,
/**/
380,
/**/
379,
/**/
378,
/**/
377,
/**/
376,
/**/
375,
/**/
374,
/**/
373,
/**/
372,
/**/
371,
/**/
370,
/**/
369,
/**/
368,
/**/
367,
/**/
366,
/**/
365,
/**/
364,
/**/
363,
/**/
362,
/**/
361,
/**/
360,
/**/
359,
/**/
358,
/**/
357,
/**/
356,
/**/
355,
/**/
354,
/**/
353,
/**/
352,
/**/
351,
/**/
350,
/**/
349,
/**/
348,
/**/
347,
/**/
346,
/**/
345,
/**/
344,
/**/
343,
/**/
342,
/**/
341,
/**/
340,
/**/
339,
/**/
338,
/**/
337,
/**/
336,
/**/
335,
/**/
334,
/**/
333,
/**/
332,
/**/
331,
/**/
330,
/**/
329,
/**/
328,
/**/
327,
/**/
326,
/**/
325,
/**/
324,
/**/
323,
/**/
322,
/**/
321,
/**/
320,
/**/
319,
/**/
318,
/**/
317,
/**/
316,
/**/
315,
/**/
314,
/**/
313,
/**/
312,
/**/
311,
/**/
310,
/**/
309,
/**/
308,
/**/
307,
/**/
306,
/**/
305,
/**/
304,
/**/
303,
/**/
302,
/**/
301,
/**/
300,
/**/
299,
/**/
298,
/**/
297,
/**/
296,
/**/
295,
/**/
294,
/**/
293,
/**/
292,
/**/
291,
/**/
290,
/**/
289,
/**/
288,
/**/
287,
/**/
286,
/**/
285,
/**/
284,
/**/
283,
/**/
282,
/**/
281,
/**/
280,
/**/
279,
/**/
278,
/**/
277,
/**/
276,
/**/
275,
/**/
274,
/**/
273,
/**/
272,
/**/
271,
/**/
270,
/**/
269,
/**/
268,
/**/
267,
/**/
266,
/**/
265,
/**/
264,
/**/
263,
/**/
262,
/**/
261,
/**/
260,
/**/
259,
/**/
258,
/**/
257,
/**/
256,
/**/
255,
/**/
254,
/**/
253,
/**/
252,
/**/
251,
/**/
250,
/**/
249,
/**/
248,
/**/
247,
/**/
246,
/**/
245,
/**/
244,
/**/
243,
/**/
242,
/**/
241,
/**/
240,
/**/
239,
/**/
238,
/**/
237,
/**/
236,
/**/
235,
/**/
234,
/**/
233,
/**/
232,
/**/
231,
/**/
230,
/**/
229,
/**/
228,
/**/
227,
/**/
226,
/**/
225,
/**/
224,
/**/
223,
/**/
222,
/**/
221,
/**/
220,
/**/
219,
/**/
218,
/**/
217,
/**/
216,
/**/
215,
/**/
214,
/**/
213,
/**/
212,
/**/
211,
/**/
210,
/**/
209,
/**/
208,
/**/
207,
/**/
206,
/**/
205,
/**/
204,
/**/
203,
/**/
202,
/**/
201,
/**/
200,
/**/
199,
/**/
198,
/**/
197,
/**/
196,
/**/
195,
/**/
194,
/**/
193,
/**/
192,
/**/
191,
/**/
190,
/**/
189,
/**/
188,
/**/
187,
/**/
186,
/**/
185,
/**/
184,
/**/
183,
/**/
182,
/**/
181,
/**/
180,
/**/
179,
/**/
178,
/**/
177,
/**/
176,
/**/
175,
/**/
174,
/**/
173,
/**/
172,
/**/
171,
/**/
170,
/**/
169,
/**/
168,
/**/
167,
/**/
166,
/**/
165,
/**/
164,
/**/
163,
/**/
162,
/**/
161,
/**/
160,
/**/
159,
/**/
158,
/**/
157,
/**/
156,
/**/
155,
/**/
154,
/**/
153,
/**/
152,
/**/
151,
/**/
150,
/**/
149,
/**/
148,
/**/
147,
/**/
146,
/**/
145,
/**/
144,
/**/
143,
/**/
142,
/**/
141,
/**/
140,
/**/
139,
/**/
138,
/**/
137,
/**/
136,
/**/
135,
/**/
134,
/**/
133,
/**/
132,
/**/
131,
/**/
130,
/**/
129,
/**/
128,
/**/
127,
/**/
126,
/**/
125,
/**/
124,
/**/
123,
/**/
122,
/**/
121,
/**/
120,
/**/
119,
/**/
118,
/**/
117,
/**/
116,
/**/
115,
/**/
114,
/**/
113,
/**/
112,
/**/
111,
/**/
110,
/**/
109,
/**/
108,
/**/
107,
/**/
106,
/**/
105,
/**/
104,
/**/
103,
/**/
102,
/**/
101,
/**/
100,
/**/
99,
/**/
98,
/**/
97,
/**/
96,
/**/
95,
/**/
94,
/**/
93,
/**/
92,
/**/
91,
/**/
90,
/**/
89,
/**/
88,
/**/
87,
/**/
86,
/**/
85,
/**/
84,
/**/
83,
/**/
82,
/**/
81,
/**/
80,
/**/
79,
/**/
78,
/**/
77,
/**/
76,
/**/
75,
/**/
74,
/**/
73,
/**/
72,
/**/
71,
/**/
70,
/**/
69,
/**/
68,
/**/
67,
/**/
66,
/**/
65,
/**/
64,
/**/
63,
/**/
62,
/**/
61,
/**/
60,
/**/
59,
/**/
58,
/**/
57,
/**/
56,
/**/
55,
/**/
54,
/**/
53,
/**/
52,
/**/
51,
/**/
50,
/**/
49,
/**/
48,
/**/
47,
/**/
46,
/**/
45,
/**/
44,
/**/
43,
/**/
42,
/**/
41,
/**/
40,
/**/
39,
/**/
38,
/**/
37,
/**/
36,
/**/
35,
/**/
34,
/**/
33,
/**/
32,
/**/
31,
/**/
30,
/**/
29,
/**/
28,
/**/
27,
/**/
26,
/**/
25,
/**/
24,
/**/
23,
/**/
22,
/**/
21,
/**/
20,
/**/
19,
/**/
18,
/**/
17,
/**/
16,
/**/
15,
/**/
14,
/**/
13,
/**/
12,
/**/
11,
/**/
10,
/**/
9,
/**/
8,
/**/
7,
/**/
6,
/**/
5,
/**/
4,
/**/
3,
/**/
2,
/**/
1,
/**/
0
};
/*
* Place to put a short description when adding a feature with a patch.
* Keep it short, e.g.,: "relative numbers", "persistent undo".
* Also add a comment marker to separate the lines.
* See the official Vim patches for the diff format: It must use a context of
* one line only. Create it by hand or use "diff -C2" and edit the patch.
*/
static char *(extra_patches[]) =
{ /* Add your patch description below this line */
/**/
NULL
};
int
highest_patch(void)
{
int i;
int h = 0;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] > h)
h = included_patches[i];
return h;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if patch "n" has been included.
*/
int
has_patch(int n)
{
int i;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] == n)
return TRUE;
return FALSE;
}
#endif
void
ex_version(exarg_T *eap)
{
/*
* Ignore a ":version 9.99" command.
*/
if (*eap->arg == NUL)
{
msg_putchar('\n');
list_version();
}
}
/*
* List all features aligned in columns, dictionary style.
*/
static void
list_features(void)
{
int i;
int ncol;
int nrow;
int nfeat = 0;
int width = 0;
/* Find the length of the longest feature name, use that + 1 as the column
* width */
for (i = 0; features[i] != NULL; ++i)
{
int l = (int)STRLEN(features[i]);
if (l > width)
width = l;
++nfeat;
}
width += 1;
if (Columns < width)
{
/* Not enough screen columns - show one per line */
for (i = 0; features[i] != NULL; ++i)
{
version_msg(features[i]);
if (msg_col > 0)
msg_putchar('\n');
}
return;
}
/* The rightmost column doesn't need a separator.
* Sacrifice it to fit in one more column if possible. */
ncol = (int) (Columns + 1) / width;
nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0);
/* i counts columns then rows. idx counts rows then columns. */
for (i = 0; !got_int && i < nrow * ncol; ++i)
{
int idx = (i / ncol) + (i % ncol) * nrow;
if (idx < nfeat)
{
int last_col = (i + 1) % ncol == 0;
msg_puts((char_u *)features[idx]);
if (last_col)
{
if (msg_col > 0)
msg_putchar('\n');
}
else
{
while (msg_col % width)
msg_putchar(' ');
}
}
else
{
if (msg_col > 0)
msg_putchar('\n');
}
}
}
void
list_version(void)
{
int i;
int first;
char *s = "";
/*
* When adding features here, don't forget to update the list of
* internal variables in eval.c!
*/
MSG(longVersion);
#ifdef WIN3264
# ifdef FEAT_GUI_W32
# ifdef _WIN64
MSG_PUTS(_("\nMS-Windows 64-bit GUI version"));
# else
MSG_PUTS(_("\nMS-Windows 32-bit GUI version"));
# endif
# ifdef FEAT_OLE
MSG_PUTS(_(" with OLE support"));
# endif
# else
# ifdef _WIN64
MSG_PUTS(_("\nMS-Windows 64-bit console version"));
# else
MSG_PUTS(_("\nMS-Windows 32-bit console version"));
# endif
# endif
#endif
#if defined(MACOS_X)
# if defined(MACOS_X_DARWIN)
MSG_PUTS(_("\nmacOS version"));
# else
MSG_PUTS(_("\nmacOS version w/o darwin feat."));
# endif
#endif
#ifdef VMS
MSG_PUTS(_("\nOpenVMS version"));
# ifdef HAVE_PATHDEF
if (*compiled_arch != NUL)
{
MSG_PUTS(" - ");
MSG_PUTS(compiled_arch);
}
# endif
#endif
/* Print the list of patch numbers if there is at least one. */
/* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */
if (included_patches[0] != 0)
{
MSG_PUTS(_("\nIncluded patches: "));
first = -1;
/* find last one */
for (i = 0; included_patches[i] != 0; ++i)
;
while (--i >= 0)
{
if (first < 0)
first = included_patches[i];
if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)
{
MSG_PUTS(s);
s = ", ";
msg_outnum((long)first);
if (first != included_patches[i])
{
MSG_PUTS("-");
msg_outnum((long)included_patches[i]);
}
first = -1;
}
}
}
/* Print the list of extra patch descriptions if there is at least one. */
if (extra_patches[0] != NULL)
{
MSG_PUTS(_("\nExtra patches: "));
s = "";
for (i = 0; extra_patches[i] != NULL; ++i)
{
MSG_PUTS(s);
s = ", ";
MSG_PUTS(extra_patches[i]);
}
}
#ifdef MODIFIED_BY
MSG_PUTS("\n");
MSG_PUTS(_("Modified by "));
MSG_PUTS(MODIFIED_BY);
#endif
#ifdef HAVE_PATHDEF
if (*compiled_user != NUL || *compiled_sys != NUL)
{
MSG_PUTS(_("\nCompiled "));
if (*compiled_user != NUL)
{
MSG_PUTS(_("by "));
MSG_PUTS(compiled_user);
}
if (*compiled_sys != NUL)
{
MSG_PUTS("@");
MSG_PUTS(compiled_sys);
}
}
#endif
#ifdef FEAT_HUGE
MSG_PUTS(_("\nHuge version "));
#else
# ifdef FEAT_BIG
MSG_PUTS(_("\nBig version "));
# else
# ifdef FEAT_NORMAL
MSG_PUTS(_("\nNormal version "));
# else
# ifdef FEAT_SMALL
MSG_PUTS(_("\nSmall version "));
# else
MSG_PUTS(_("\nTiny version "));
# endif
# endif
# endif
#endif
#ifndef FEAT_GUI
MSG_PUTS(_("without GUI."));
#else
# ifdef FEAT_GUI_GTK
# ifdef USE_GTK3
MSG_PUTS(_("with GTK3 GUI."));
# else
# ifdef FEAT_GUI_GNOME
MSG_PUTS(_("with GTK2-GNOME GUI."));
# else
MSG_PUTS(_("with GTK2 GUI."));
# endif
# endif
# else
# ifdef FEAT_GUI_MOTIF
MSG_PUTS(_("with X11-Motif GUI."));
# else
# ifdef FEAT_GUI_ATHENA
# ifdef FEAT_GUI_NEXTAW
MSG_PUTS(_("with X11-neXtaw GUI."));
# else
MSG_PUTS(_("with X11-Athena GUI."));
# endif
# else
# ifdef FEAT_GUI_PHOTON
MSG_PUTS(_("with Photon GUI."));
# else
# if defined(MSWIN)
MSG_PUTS(_("with GUI."));
# else
# if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON
MSG_PUTS(_("with Carbon GUI."));
# else
# if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX
MSG_PUTS(_("with Cocoa GUI."));
# else
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
version_msg(_(" Features included (+) or not (-):\n"));
list_features();
#ifdef SYS_VIMRC_FILE
version_msg(_(" system vimrc file: \""));
version_msg(SYS_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE
version_msg(_(" user vimrc file: \""));
version_msg(USR_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE2
version_msg(_(" 2nd user vimrc file: \""));
version_msg(USR_VIMRC_FILE2);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE3
version_msg(_(" 3rd user vimrc file: \""));
version_msg(USR_VIMRC_FILE3);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE
version_msg(_(" user exrc file: \""));
version_msg(USR_EXRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE2
version_msg(_(" 2nd user exrc file: \""));
version_msg(USR_EXRC_FILE2);
version_msg("\"\n");
#endif
#ifdef FEAT_GUI
# ifdef SYS_GVIMRC_FILE
version_msg(_(" system gvimrc file: \""));
version_msg(SYS_GVIMRC_FILE);
version_msg("\"\n");
# endif
version_msg(_(" user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE);
version_msg("\"\n");
# ifdef USR_GVIMRC_FILE2
version_msg(_("2nd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE2);
version_msg("\"\n");
# endif
# ifdef USR_GVIMRC_FILE3
version_msg(_("3rd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE3);
version_msg("\"\n");
# endif
#endif
version_msg(_(" defaults file: \""));
version_msg(VIM_DEFAULTS_FILE);
version_msg("\"\n");
#ifdef FEAT_GUI
# ifdef SYS_MENU_FILE
version_msg(_(" system menu file: \""));
version_msg(SYS_MENU_FILE);
version_msg("\"\n");
# endif
#endif
#ifdef HAVE_PATHDEF
if (*default_vim_dir != NUL)
{
version_msg(_(" fall-back for $VIM: \""));
version_msg((char *)default_vim_dir);
version_msg("\"\n");
}
if (*default_vimruntime_dir != NUL)
{
version_msg(_(" f-b for $VIMRUNTIME: \""));
version_msg((char *)default_vimruntime_dir);
version_msg("\"\n");
}
version_msg(_("Compilation: "));
version_msg((char *)all_cflags);
version_msg("\n");
#ifdef VMS
if (*compiler_version != NUL)
{
version_msg(_("Compiler: "));
version_msg((char *)compiler_version);
version_msg("\n");
}
#endif
version_msg(_("Linking: "));
version_msg((char *)all_lflags);
#endif
#ifdef DEBUG
version_msg("\n");
version_msg(_(" DEBUG BUILD"));
#endif
}
/*
* Output a string for the version message. If it's going to wrap, output a
* newline, unless the message is too long to fit on the screen anyway.
*/
static void
version_msg(char *s)
{
int len = (int)STRLEN(s);
if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns
&& *s != '\n')
msg_putchar('\n');
if (!got_int)
MSG_PUTS(s);
}
static void do_intro_line(int row, char_u *mesg, int add_version, int attr);
/*
* Show the intro message when not editing a file.
*/
void
maybe_intro_message(void)
{
if (BUFEMPTY()
&& curbuf->b_fname == NULL
&& firstwin->w_next == NULL
&& vim_strchr(p_shm, SHM_INTRO) == NULL)
intro_message(FALSE);
}
/*
* Give an introductory message about Vim.
* Only used when starting Vim on an empty file, without a file name.
* Or with the ":intro" command (for Sven :-).
*/
void
intro_message(
int colon) /* TRUE for ":intro" */
{
int i;
int row;
int blanklines;
int sponsor;
char *p;
static char *(lines[]) =
{
N_("VIM - Vi IMproved"),
"",
N_("version "),
N_("by Bram Moolenaar et al."),
#ifdef MODIFIED_BY
" ",
#endif
N_("Vim is open source and freely distributable"),
"",
N_("Help poor children in Uganda!"),
N_("type :help iccf<Enter> for information "),
"",
N_("type :q<Enter> to exit "),
N_("type :help<Enter> or <F1> for on-line help"),
N_("type :help version8<Enter> for version info"),
NULL,
"",
N_("Running in Vi compatible mode"),
N_("type :set nocp<Enter> for Vim defaults"),
N_("type :help cp-default<Enter> for info on this"),
};
#ifdef FEAT_GUI
static char *(gui_lines[]) =
{
NULL,
NULL,
NULL,
NULL,
#ifdef MODIFIED_BY
NULL,
#endif
NULL,
NULL,
NULL,
N_("menu Help->Orphans for information "),
NULL,
N_("Running modeless, typed text is inserted"),
N_("menu Edit->Global Settings->Toggle Insert Mode "),
N_(" for two modes "),
NULL,
NULL,
NULL,
N_("menu Edit->Global Settings->Toggle Vi Compatible"),
N_(" for Vim defaults "),
};
#endif
/* blanklines = screen height - # message lines */
blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1);
if (!p_cp)
blanklines += 4; /* add 4 for not showing "Vi compatible" message */
/* Don't overwrite a statusline. Depends on 'cmdheight'. */
if (p_ls > 1)
blanklines -= Rows - topframe->fr_height;
if (blanklines < 0)
blanklines = 0;
/* Show the sponsor and register message one out of four times, the Uganda
* message two out of four times. */
sponsor = (int)time(NULL);
sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);
/* start displaying the message lines after half of the blank lines */
row = blanklines / 2;
if ((row >= 2 && Columns >= 50) || colon)
{
for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i)
{
p = lines[i];
#ifdef FEAT_GUI
if (p_im && gui.in_use && gui_lines[i] != NULL)
p = gui_lines[i];
#endif
if (p == NULL)
{
if (!p_cp)
break;
continue;
}
if (sponsor != 0)
{
if (strstr(p, "children") != NULL)
p = sponsor < 0
? N_("Sponsor Vim development!")
: N_("Become a registered Vim user!");
else if (strstr(p, "iccf") != NULL)
p = sponsor < 0
? N_("type :help sponsor<Enter> for information ")
: N_("type :help register<Enter> for information ");
else if (strstr(p, "Orphans") != NULL)
p = N_("menu Help->Sponsor/Register for information ");
}
if (*p != NUL)
do_intro_line(row, (char_u *)_(p), i == 2, 0);
++row;
}
}
/* Make the wait-return message appear just below the text. */
if (colon)
msg_row = row;
}
static void
do_intro_line(
int row,
char_u *mesg,
int add_version,
int attr)
{
char_u vers[20];
int col;
char_u *p;
int l;
int clen;
#ifdef MODIFIED_BY
# define MODBY_LEN 150
char_u modby[MODBY_LEN];
if (*mesg == ' ')
{
vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1);
l = (int)STRLEN(modby);
vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);
mesg = modby;
}
#endif
/* Center the message horizontally. */
col = vim_strsize(mesg);
if (add_version)
{
STRCPY(vers, mediumVersion);
if (highest_patch())
{
/* Check for 9.9x or 9.9xx, alpha/beta version */
if (isalpha((int)vers[3]))
{
int len = (isalpha((int)vers[4])) ? 5 : 4;
sprintf((char *)vers + len, ".%d%s", highest_patch(),
mediumVersion + len);
}
else
sprintf((char *)vers + 3, ".%d", highest_patch());
}
col += (int)STRLEN(vers);
}
col = (Columns - col) / 2;
if (col < 0)
col = 0;
/* Split up in parts to highlight <> items differently. */
for (p = mesg; *p != NUL; p += l)
{
clen = 0;
for (l = 0; p[l] != NUL
&& (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
clen += ptr2cells(p + l);
l += (*mb_ptr2len)(p + l) - 1;
}
else
#endif
clen += byte2cells(p[l]);
}
screen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);
col += clen;
}
/* Add the version number to the version line. */
if (add_version)
screen_puts(vers, row, col, 0);
}
/*
* ":intro": clear screen, display intro screen and wait for return.
*/
void
ex_intro(exarg_T *eap UNUSED)
{
screenclear();
intro_message(TRUE);
wait_return(TRUE);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2958_3 |
crossvul-cpp_data_bad_953_0 | /*
* Copyright (c) Dan Harkins, 2012
*
* Copyright holder grants permission for redistribution and use in source
* and binary forms, with or without modification, provided that the
* following conditions are met:
* 1. Redistribution of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer
* in all source files.
* 2. Redistribution in binary form must retain the above copyright
* notice, this list of conditions, and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* "DISCLAIMER OF LIABILITY
*
* THIS SOFTWARE IS PROVIDED BY DAN HARKINS ``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 INDUSTRIAL LOUNGE BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE."
*
* This license and distribution terms cannot be changed. In other words,
* this code cannot simply be copied and put under a different distribution
* license (including the GNU public license).
*/
RCSID("$Id$")
USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
#include "eap_pwd.h"
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/modules.h>
/* The random function H(x) = HMAC-SHA256(0^32, x) */
static void H_Init(HMAC_CTX *ctx)
{
uint8_t allzero[SHA256_DIGEST_LENGTH];
memset(allzero, 0, SHA256_DIGEST_LENGTH);
HMAC_Init_ex(ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL);
}
static void H_Update(HMAC_CTX *ctx, uint8_t const *data, int len)
{
HMAC_Update(ctx, data, len);
}
static void H_Final(HMAC_CTX *ctx, uint8_t *digest)
{
unsigned int mdlen = SHA256_DIGEST_LENGTH;
HMAC_Final(ctx, digest, &mdlen);
}
/* a counter-based KDF based on NIST SP800-108 */
static int eap_pwd_kdf(uint8_t *key, int keylen, char const *label, int labellen, uint8_t *result, int resultbitlen)
{
HMAC_CTX *hctx = NULL;
uint8_t digest[SHA256_DIGEST_LENGTH];
uint16_t i, ctr, L;
int resultbytelen, len = 0;
unsigned int mdlen = SHA256_DIGEST_LENGTH;
uint8_t mask = 0xff;
hctx = HMAC_CTX_new();
if (hctx == NULL) {
DEBUG("failed allocating HMAC context");
return -1;
}
resultbytelen = (resultbitlen + 7)/8;
ctr = 0;
L = htons(resultbitlen);
while (len < resultbytelen) {
ctr++; i = htons(ctr);
HMAC_Init_ex(hctx, key, keylen, EVP_sha256(), NULL);
if (ctr > 1) {
HMAC_Update(hctx, digest, mdlen);
}
HMAC_Update(hctx, (uint8_t *) &i, sizeof(uint16_t));
HMAC_Update(hctx, (uint8_t const *)label, labellen);
HMAC_Update(hctx, (uint8_t *) &L, sizeof(uint16_t));
HMAC_Final(hctx, digest, &mdlen);
if ((len + (int) mdlen) > resultbytelen) {
memcpy(result + len, digest, resultbytelen - len);
} else {
memcpy(result + len, digest, mdlen);
}
len += mdlen;
}
HMAC_CTX_free(hctx);
/* since we're expanding to a bit length, mask off the excess */
if (resultbitlen % 8) {
mask <<= (8 - (resultbitlen % 8));
result[resultbytelen - 1] &= mask;
}
return 0;
}
int compute_password_element (pwd_session_t *session, uint16_t grp_num,
char const *password, int password_len,
char const *id_server, int id_server_len,
char const *id_peer, int id_peer_len,
uint32_t *token)
{
BIGNUM *x_candidate = NULL, *rnd = NULL, *cofactor = NULL;
HMAC_CTX *ctx = NULL;
uint8_t pwe_digest[SHA256_DIGEST_LENGTH], *prfbuf = NULL, ctr;
int nid, is_odd, primebitlen, primebytelen, ret = 0;
ctx = HMAC_CTX_new();
if (ctx == NULL) {
DEBUG("failed allocating HMAC context");
goto fail;
}
switch (grp_num) { /* from IANA registry for IKE D-H groups */
case 19:
nid = NID_X9_62_prime256v1;
break;
case 20:
nid = NID_secp384r1;
break;
case 21:
nid = NID_secp521r1;
break;
case 25:
nid = NID_X9_62_prime192v1;
break;
case 26:
nid = NID_secp224r1;
break;
default:
DEBUG("unknown group %d", grp_num);
goto fail;
}
session->pwe = NULL;
session->order = NULL;
session->prime = NULL;
if ((session->group = EC_GROUP_new_by_curve_name(nid)) == NULL) {
DEBUG("unable to create EC_GROUP");
goto fail;
}
if (((rnd = BN_new()) == NULL) ||
((cofactor = BN_new()) == NULL) ||
((session->pwe = EC_POINT_new(session->group)) == NULL) ||
((session->order = BN_new()) == NULL) ||
((session->prime = BN_new()) == NULL) ||
((x_candidate = BN_new()) == NULL)) {
DEBUG("unable to create bignums");
goto fail;
}
if (!EC_GROUP_get_curve_GFp(session->group, session->prime, NULL, NULL, NULL)) {
DEBUG("unable to get prime for GFp curve");
goto fail;
}
if (!EC_GROUP_get_order(session->group, session->order, NULL)) {
DEBUG("unable to get order for curve");
goto fail;
}
if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) {
DEBUG("unable to get cofactor for curve");
goto fail;
}
primebitlen = BN_num_bits(session->prime);
primebytelen = BN_num_bytes(session->prime);
if ((prfbuf = talloc_zero_array(session, uint8_t, primebytelen)) == NULL) {
DEBUG("unable to alloc space for prf buffer");
goto fail;
}
ctr = 0;
while (1) {
if (ctr > 10) {
DEBUG("unable to find random point on curve for group %d, something's fishy", grp_num);
goto fail;
}
ctr++;
/*
* compute counter-mode password value and stretch to prime
* pwd-seed = H(token | peer-id | server-id | password |
* counter)
*/
H_Init(ctx);
H_Update(ctx, (uint8_t *)token, sizeof(*token));
H_Update(ctx, (uint8_t const *)id_peer, id_peer_len);
H_Update(ctx, (uint8_t const *)id_server, id_server_len);
H_Update(ctx, (uint8_t const *)password, password_len);
H_Update(ctx, (uint8_t *)&ctr, sizeof(ctr));
H_Final(ctx, pwe_digest);
BN_bin2bn(pwe_digest, SHA256_DIGEST_LENGTH, rnd);
if (eap_pwd_kdf(pwe_digest, SHA256_DIGEST_LENGTH, "EAP-pwd Hunting And Pecking",
strlen("EAP-pwd Hunting And Pecking"), prfbuf, primebitlen) != 0) {
DEBUG("key derivation function failed");
goto fail;
}
BN_bin2bn(prfbuf, primebytelen, x_candidate);
/*
* eap_pwd_kdf() returns a string of bits 0..primebitlen but
* BN_bin2bn will treat that string of bits as a big endian
* number. If the primebitlen is not an even multiple of 8
* then excessive bits-- those _after_ primebitlen-- so now
* we have to shift right the amount we masked off.
*/
if (primebitlen % 8) BN_rshift(x_candidate, x_candidate, (8 - (primebitlen % 8)));
if (BN_ucmp(x_candidate, session->prime) >= 0) continue;
/*
* need to unambiguously identify the solution, if there is
* one...
*/
is_odd = BN_is_odd(rnd) ? 1 : 0;
/*
* solve the quadratic equation, if it's not solvable then we
* don't have a point
*/
if (!EC_POINT_set_compressed_coordinates_GFp(session->group, session->pwe, x_candidate, is_odd, NULL)) {
continue;
}
/*
* If there's a solution to the equation then the point must be
* on the curve so why check again explicitly? OpenSSL code
* says this is required by X9.62. We're not X9.62 but it can't
* hurt just to be sure.
*/
if (!EC_POINT_is_on_curve(session->group, session->pwe, NULL)) {
DEBUG("EAP-pwd: point is not on curve");
continue;
}
if (BN_cmp(cofactor, BN_value_one())) {
/* make sure the point is not in a small sub-group */
if (!EC_POINT_mul(session->group, session->pwe, NULL, session->pwe,
cofactor, NULL)) {
DEBUG("EAP-pwd: cannot multiply generator by order");
continue;
}
if (EC_POINT_is_at_infinity(session->group, session->pwe)) {
DEBUG("EAP-pwd: point is at infinity");
continue;
}
}
/* if we got here then we have a new generator. */
break;
}
session->group_num = grp_num;
if (0) {
fail: /* DON'T free session, it's in handler->opaque */
ret = -1;
}
/* cleanliness and order.... */
BN_clear_free(cofactor);
BN_clear_free(x_candidate);
BN_clear_free(rnd);
talloc_free(prfbuf);
HMAC_CTX_free(ctx);
return ret;
}
int compute_scalar_element (pwd_session_t *session, BN_CTX *bnctx) {
BIGNUM *mask = NULL;
int ret = -1;
if (((session->private_value = BN_new()) == NULL) ||
((session->my_element = EC_POINT_new(session->group)) == NULL) ||
((session->my_scalar = BN_new()) == NULL) ||
((mask = BN_new()) == NULL)) {
DEBUG2("server scalar allocation failed");
goto fail;
}
if (BN_rand_range(session->private_value, session->order) != 1) {
DEBUG2("Unable to get randomness for private_value");
goto fail;
}
if (BN_rand_range(mask, session->order) != 1) {
DEBUG2("Unable to get randomness for mask");
goto fail;
}
BN_add(session->my_scalar, session->private_value, mask);
BN_mod(session->my_scalar, session->my_scalar, session->order, bnctx);
if (!EC_POINT_mul(session->group, session->my_element, NULL, session->pwe, mask, bnctx)) {
DEBUG2("server element allocation failed");
goto fail;
}
if (!EC_POINT_invert(session->group, session->my_element, bnctx)) {
DEBUG2("server element inversion failed");
goto fail;
}
ret = 0;
fail:
BN_clear_free(mask);
return ret;
}
int process_peer_commit (pwd_session_t *session, uint8_t *in, size_t in_len, BN_CTX *bnctx)
{
uint8_t *ptr;
size_t data_len;
BIGNUM *x = NULL, *y = NULL, *cofactor = NULL;
EC_POINT *K = NULL, *point = NULL;
int res = 1;
if (((session->peer_scalar = BN_new()) == NULL) ||
((session->k = BN_new()) == NULL) ||
((cofactor = BN_new()) == NULL) ||
((x = BN_new()) == NULL) ||
((y = BN_new()) == NULL) ||
((point = EC_POINT_new(session->group)) == NULL) ||
((K = EC_POINT_new(session->group)) == NULL) ||
((session->peer_element = EC_POINT_new(session->group)) == NULL)) {
DEBUG2("pwd: failed to allocate room to process peer's commit");
goto finish;
}
if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) {
DEBUG2("pwd: unable to get group co-factor");
goto finish;
}
/* element, x then y, followed by scalar */
ptr = (uint8_t *)in;
data_len = BN_num_bytes(session->prime);
/*
* Did the peer send enough data?
*/
if (in_len < (2 * data_len + BN_num_bytes(session->order))) {
DEBUG("pwd: Invalid commit packet");
goto finish;
}
BN_bin2bn(ptr, data_len, x);
ptr += data_len;
BN_bin2bn(ptr, data_len, y);
ptr += data_len;
data_len = BN_num_bytes(session->order);
BN_bin2bn(ptr, data_len, session->peer_scalar);
/* validate received scalar */
if (BN_is_zero(session->peer_scalar) ||
BN_is_one(session->peer_scalar) ||
BN_cmp(session->peer_scalar, session->order) >= 0) {
ERROR("Peer's scalar is not within the allowed range");
goto finish;
}
if (!EC_POINT_set_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) {
DEBUG2("pwd: unable to get coordinates of peer's element");
goto finish;
}
/* validate received element */
if (!EC_POINT_is_on_curve(session->group, session->peer_element, bnctx) ||
EC_POINT_is_at_infinity(session->group, session->peer_element)) {
ERROR("Peer's element is not a point on the elliptic curve");
goto finish;
}
/* check to ensure peer's element is not in a small sub-group */
if (BN_cmp(cofactor, BN_value_one())) {
if (!EC_POINT_mul(session->group, point, NULL, session->peer_element, cofactor, NULL)) {
DEBUG2("pwd: unable to multiply element by co-factor");
goto finish;
}
if (EC_POINT_is_at_infinity(session->group, point)) {
DEBUG2("pwd: peer's element is in small sub-group");
goto finish;
}
}
/* detect reflection attacks */
if (BN_cmp(session->peer_scalar, session->my_scalar) == 0 ||
EC_POINT_cmp(session->group, session->peer_element, session->my_element, bnctx) == 0) {
ERROR("Reflection attack detected");
goto finish;
}
/* compute the shared key, k */
if ((!EC_POINT_mul(session->group, K, NULL, session->pwe, session->peer_scalar, bnctx)) ||
(!EC_POINT_add(session->group, K, K, session->peer_element, bnctx)) ||
(!EC_POINT_mul(session->group, K, NULL, K, session->private_value, bnctx))) {
DEBUG2("pwd: unable to compute shared key, k");
goto finish;
}
/* ensure that the shared key isn't in a small sub-group */
if (BN_cmp(cofactor, BN_value_one())) {
if (!EC_POINT_mul(session->group, K, NULL, K, cofactor, NULL)) {
DEBUG2("pwd: unable to multiply k by co-factor");
goto finish;
}
}
/*
* This check is strictly speaking just for the case above where
* co-factor > 1 but it was suggested that even though this is probably
* never going to happen it is a simple and safe check "just to be
* sure" so let's be safe.
*/
if (EC_POINT_is_at_infinity(session->group, K)) {
DEBUG2("pwd: k is point-at-infinity!");
goto finish;
}
if (!EC_POINT_get_affine_coordinates_GFp(session->group, K, session->k, NULL, bnctx)) {
DEBUG2("pwd: unable to get shared secret from K");
goto finish;
}
res = 0;
finish:
EC_POINT_clear_free(K);
EC_POINT_clear_free(point);
BN_clear_free(cofactor);
BN_clear_free(x);
BN_clear_free(y);
return res;
}
int compute_server_confirm (pwd_session_t *session, uint8_t *out, BN_CTX *bnctx)
{
BIGNUM *x = NULL, *y = NULL;
HMAC_CTX *ctx = NULL;
uint8_t *cruft = NULL;
int offset, req = -1;
ctx = HMAC_CTX_new();
if (ctx == NULL) {
DEBUG2("pwd: unable to allocate HMAC context!");
goto finish;
}
/*
* Each component of the cruft will be at most as big as the prime
*/
if (((cruft = talloc_zero_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) ||
((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) {
DEBUG2("pwd: unable to allocate space to compute confirm!");
goto finish;
}
/*
* commit is H(k | server_element | server_scalar | peer_element |
* peer_scalar | ciphersuite)
*/
H_Init(ctx);
/*
* Zero the memory each time because this is mod prime math and some
* value may start with a few zeros and the previous one did not.
*
* First is k
*/
offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k);
BN_bn2bin(session->k, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* next is server element: x, y
*/
if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, bnctx)) {
DEBUG2("pwd: unable to get coordinates of server element");
goto finish;
}
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
BN_bn2bin(x, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
BN_bn2bin(y, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* and server scalar
*/
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar);
BN_bn2bin(session->my_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
/*
* next is peer element: x, y
*/
if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) {
DEBUG2("pwd: unable to get coordinates of peer's element");
goto finish;
}
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
BN_bn2bin(x, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
BN_bn2bin(y, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* and peer scalar
*/
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar);
BN_bn2bin(session->peer_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
/*
* finally, ciphersuite
*/
H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite));
H_Final(ctx, out);
req = 0;
finish:
talloc_free(cruft);
BN_free(x);
BN_free(y);
HMAC_CTX_free(ctx);
return req;
}
int compute_peer_confirm (pwd_session_t *session, uint8_t *out, BN_CTX *bnctx)
{
BIGNUM *x = NULL, *y = NULL;
HMAC_CTX *ctx = NULL;
uint8_t *cruft = NULL;
int offset, req = -1;
ctx = HMAC_CTX_new();
if (ctx == NULL) {
DEBUG2("pwd: unable to allocate HMAC context!");
goto finish;
}
/*
* Each component of the cruft will be at most as big as the prime
*/
if (((cruft = talloc_zero_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) ||
((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) {
DEBUG2("pwd: unable to allocate space to compute confirm!");
goto finish;
}
/*
* commit is H(k | server_element | server_scalar | peer_element |
* peer_scalar | ciphersuite)
*/
H_Init(ctx);
/*
* Zero the memory each time because this is mod prime math and some
* value may start with a few zeros and the previous one did not.
*
* First is k
*/
offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k);
BN_bn2bin(session->k, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* then peer element: x, y
*/
if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) {
DEBUG2("pwd: unable to get coordinates of peer's element");
goto finish;
}
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
BN_bn2bin(x, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
BN_bn2bin(y, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* and peer scalar
*/
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar);
BN_bn2bin(session->peer_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
/*
* then server element: x, y
*/
if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, bnctx)) {
DEBUG2("pwd: unable to get coordinates of server element");
goto finish;
}
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
BN_bn2bin(x, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
BN_bn2bin(y, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
/*
* and server scalar
*/
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar);
BN_bn2bin(session->my_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
/*
* finally, ciphersuite
*/
H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite));
H_Final(ctx, out);
req = 0;
finish:
talloc_free(cruft);
BN_free(x);
BN_free(y);
HMAC_CTX_free(ctx);
return req;
}
int compute_keys (pwd_session_t *session, uint8_t *peer_confirm, uint8_t *msk, uint8_t *emsk)
{
HMAC_CTX *ctx = NULL;
uint8_t mk[SHA256_DIGEST_LENGTH], *cruft = NULL;
uint8_t session_id[SHA256_DIGEST_LENGTH + 1];
uint8_t msk_emsk[128]; /* 64 each */
int offset, ret = -1;
ctx = HMAC_CTX_new();
if (ctx == NULL) {
DEBUG2("pwd: unable to allocate HMAC context!");
goto finish;
}
if ((cruft = talloc_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) {
DEBUG2("pwd: unable to allocate space to compute keys");
goto finish;
}
/*
* first compute the session-id = TypeCode | H(ciphersuite | scal_p |
* scal_s)
*/
session_id[0] = PW_EAP_PWD;
H_Init(ctx);
H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar);
memset(cruft, 0, BN_num_bytes(session->prime));
BN_bn2bin(session->peer_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar);
memset(cruft, 0, BN_num_bytes(session->prime));
BN_bn2bin(session->my_scalar, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->order));
H_Final(ctx, (uint8_t *)&session_id[1]);
/* then compute MK = H(k | commit-peer | commit-server) */
H_Init(ctx);
memset(cruft, 0, BN_num_bytes(session->prime));
offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k);
BN_bn2bin(session->k, cruft + offset);
H_Update(ctx, cruft, BN_num_bytes(session->prime));
H_Update(ctx, peer_confirm, SHA256_DIGEST_LENGTH);
H_Update(ctx, session->my_confirm, SHA256_DIGEST_LENGTH);
H_Final(ctx, mk);
/* stretch the mk with the session-id to get MSK | EMSK */
if (eap_pwd_kdf(mk, SHA256_DIGEST_LENGTH, (char const *)session_id,
SHA256_DIGEST_LENGTH + 1, msk_emsk,
/* it's bits, ((64 + 64) * 8) */
1024) != 0) {
DEBUG("key derivation function failed");
goto finish;
}
memcpy(msk, msk_emsk, 64);
memcpy(emsk, msk_emsk + 64, 64);
ret = 0;
finish:
talloc_free(cruft);
HMAC_CTX_free(ctx);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_953_0 |
crossvul-cpp_data_bad_1124_4 | /*
* Elliptic curve DSA
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* References:
*
* SEC1 http://www.secg.org/index.php?action=secg,docs_secg
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_ECDSA_C)
#include "mbedtls/ecdsa.h"
#include "mbedtls/asn1write.h"
#include <string.h>
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
#include "mbedtls/hmac_drbg.h"
#endif
/*
* Derive a suitable integer for group grp from a buffer of length len
* SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3
*/
static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x,
const unsigned char *buf, size_t blen )
{
int ret;
size_t n_size = ( grp->nbits + 7 ) / 8;
size_t use_size = blen > n_size ? n_size : blen;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) );
if( use_size * 8 > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) );
/* While at it, reduce modulo N */
if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) );
cleanup:
return( ret );
}
#if !defined(MBEDTLS_ECDSA_SIGN_ALT)
/*
* Compute ECDSA signature of a hashed message (SEC1 4.1.3)
* Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
*/
int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret, key_tries, sign_tries, blind_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
sign_tries = 0;
do
{
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
key_tries = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );
if( key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
blind_tries = 0;
do
{
size_t n_size = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );
/* See mbedtls_ecp_gen_keypair() */
if( ++blind_tries > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
if( sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
return( ret );
}
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/*
* Deterministic signature wrapper
*/
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg )
{
int ret;
mbedtls_hmac_drbg_context rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
size_t grp_len = ( grp->nbits + 7 ) / 8;
const mbedtls_md_info_t *md_info;
mbedtls_mpi h;
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
mbedtls_mpi_init( &h );
mbedtls_hmac_drbg_init( &rng_ctx );
/* Use private key and message hash (reduced) to initialize HMAC_DRBG */
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );
MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );
mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len );
ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, &rng_ctx );
cleanup:
mbedtls_hmac_drbg_free( &rng_ctx );
mbedtls_mpi_free( &h );
return( ret );
}
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
/*
* Verify ECDSA signature of hashed message (SEC1 4.1.4)
* Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
*/
int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
const unsigned char *buf, size_t blen,
const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s)
{
int ret;
mbedtls_mpi e, s_inv, u1, u2;
mbedtls_ecp_point R;
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 );
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* Step 1: make sure r and s are in range 1..n-1
*/
if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 ||
mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
/*
* Additional precaution: make sure Q is valid
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) );
/*
* Step 3: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Step 4: u1 = e / s mod n, u2 = r / s mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u1, &e, &s_inv ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u1, &u1, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u2, r, &s_inv ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u2, &u2, &grp->N ) );
/*
* Step 5: R = u1 G + u2 Q
*
* Since we're not using any secret data, no need to pass a RNG to
* mbedtls_ecp_mul() for countermesures.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, &R, &u1, &grp->G, &u2, Q ) );
if( mbedtls_ecp_is_zero( &R ) )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
/*
* Step 6: convert xR to an integer (no-op)
* Step 7: reduce xR mod n (gives v)
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) );
/*
* Step 8: check if v (that is, R.X) is equal to r
*/
if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 );
return( ret );
}
#endif /* MBEDTLS_ECDSA_VERIFY_ALT */
/*
* Convert a signature (given by context) to ASN.1
*/
static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
unsigned char *sig, size_t *slen )
{
int ret;
unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];
unsigned char *p = buf + sizeof( buf );
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
memcpy( sig, p, len );
*slen = len;
return( 0 );
}
/*
* Compute and write signature
*/
int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
#if ! defined(MBEDTLS_DEPRECATED_REMOVED) && \
defined(MBEDTLS_ECDSA_DETERMINISTIC)
int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
mbedtls_md_type_t md_alg )
{
return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen,
NULL, NULL ) );
}
#endif
/*
* Read and check signature
*/
int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
const unsigned char *sig, size_t slen )
{
int ret;
unsigned char *p = (unsigned char *) sig;
const unsigned char *end = sig + slen;
size_t len;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
if( p + len != end )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
goto cleanup;
}
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 )
{
ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen,
&ctx->Q, &r, &s ) ) != 0 )
goto cleanup;
/* At this point we know that the buffer starts with a valid signature.
* Return 0 if the buffer just contains the signature, and a specific
* error code if the valid signature is followed by more data. */
if( p != end )
ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
#if !defined(MBEDTLS_ECDSA_GENKEY_ALT)
/*
* Generate key pair
*/
int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = 0;
ret = mbedtls_ecp_group_load( &ctx->grp, gid );
if( ret != 0 )
return( ret );
return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d,
&ctx->Q, f_rng, p_rng ) );
}
#endif /* MBEDTLS_ECDSA_GENKEY_ALT */
/*
* Set context from an mbedtls_ecp_keypair
*/
int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key )
{
int ret;
if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||
( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 ||
( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 )
{
mbedtls_ecdsa_free( ctx );
}
return( ret );
}
/*
* Initialize context
*/
void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx )
{
mbedtls_ecp_keypair_init( ctx );
}
/*
* Free context
*/
void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx )
{
mbedtls_ecp_keypair_free( ctx );
}
#endif /* MBEDTLS_ECDSA_C */
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1124_4 |
crossvul-cpp_data_bad_2864_0 | /*
* FPU register's regset abstraction, for ptrace, core dumps, etc.
*/
#include <asm/fpu/internal.h>
#include <asm/fpu/signal.h>
#include <asm/fpu/regset.h>
#include <asm/fpu/xstate.h>
#include <linux/sched/task_stack.h>
/*
* The xstateregs_active() routine is the same as the regset_fpregs_active() routine,
* as the "regset->n" for the xstate regset will be updated based on the feature
* capabilities supported by the xsave.
*/
int regset_fpregs_active(struct task_struct *target, const struct user_regset *regset)
{
struct fpu *target_fpu = &target->thread.fpu;
return target_fpu->fpstate_active ? regset->n : 0;
}
int regset_xregset_fpregs_active(struct task_struct *target, const struct user_regset *regset)
{
struct fpu *target_fpu = &target->thread.fpu;
if (boot_cpu_has(X86_FEATURE_FXSR) && target_fpu->fpstate_active)
return regset->n;
else
return 0;
}
int xfpregs_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
if (!boot_cpu_has(X86_FEATURE_FXSR))
return -ENODEV;
fpu__activate_fpstate_read(fpu);
fpstate_sanitize_xstate(fpu);
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&fpu->state.fxsave, 0, -1);
}
int xfpregs_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
int ret;
if (!boot_cpu_has(X86_FEATURE_FXSR))
return -ENODEV;
fpu__activate_fpstate_write(fpu);
fpstate_sanitize_xstate(fpu);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&fpu->state.fxsave, 0, -1);
/*
* mxcsr reserved bits must be masked to zero for security reasons.
*/
fpu->state.fxsave.mxcsr &= mxcsr_feature_mask;
/*
* update the header bits in the xsave header, indicating the
* presence of FP and SSE state.
*/
if (boot_cpu_has(X86_FEATURE_XSAVE))
fpu->state.xsave.header.xfeatures |= XFEATURE_MASK_FPSSE;
return ret;
}
int xstateregs_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
struct xregs_state *xsave;
int ret;
if (!boot_cpu_has(X86_FEATURE_XSAVE))
return -ENODEV;
xsave = &fpu->state.xsave;
fpu__activate_fpstate_read(fpu);
if (using_compacted_format()) {
if (kbuf)
ret = copy_xstate_to_kernel(kbuf, xsave, pos, count);
else
ret = copy_xstate_to_user(ubuf, xsave, pos, count);
} else {
fpstate_sanitize_xstate(fpu);
/*
* Copy the 48 bytes defined by the software into the xsave
* area in the thread struct, so that we can copy the whole
* area to user using one user_regset_copyout().
*/
memcpy(&xsave->i387.sw_reserved, xstate_fx_sw_bytes, sizeof(xstate_fx_sw_bytes));
/*
* Copy the xstate memory layout.
*/
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, xsave, 0, -1);
}
return ret;
}
int xstateregs_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
struct xregs_state *xsave;
int ret;
if (!boot_cpu_has(X86_FEATURE_XSAVE))
return -ENODEV;
/*
* A whole standard-format XSAVE buffer is needed:
*/
if ((pos != 0) || (count < fpu_user_xstate_size))
return -EFAULT;
xsave = &fpu->state.xsave;
fpu__activate_fpstate_write(fpu);
if (boot_cpu_has(X86_FEATURE_XSAVES)) {
if (kbuf)
ret = copy_kernel_to_xstate(xsave, kbuf);
else
ret = copy_user_to_xstate(xsave, ubuf);
} else {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, xsave, 0, -1);
}
/*
* In case of failure, mark all states as init:
*/
if (ret)
fpstate_init(&fpu->state);
/*
* mxcsr reserved bits must be masked to zero for security reasons.
*/
xsave->i387.mxcsr &= mxcsr_feature_mask;
xsave->header.xfeatures &= xfeatures_mask;
/*
* These bits must be zero.
*/
memset(&xsave->header.reserved, 0, 48);
return ret;
}
#if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION
/*
* FPU tag word conversions.
*/
static inline unsigned short twd_i387_to_fxsr(unsigned short twd)
{
unsigned int tmp; /* to avoid 16 bit prefixes in the code */
/* Transform each pair of bits into 01 (valid) or 00 (empty) */
tmp = ~twd;
tmp = (tmp | (tmp>>1)) & 0x5555; /* 0V0V0V0V0V0V0V0V */
/* and move the valid bits to the lower byte. */
tmp = (tmp | (tmp >> 1)) & 0x3333; /* 00VV00VV00VV00VV */
tmp = (tmp | (tmp >> 2)) & 0x0f0f; /* 0000VVVV0000VVVV */
tmp = (tmp | (tmp >> 4)) & 0x00ff; /* 00000000VVVVVVVV */
return tmp;
}
#define FPREG_ADDR(f, n) ((void *)&(f)->st_space + (n) * 16)
#define FP_EXP_TAG_VALID 0
#define FP_EXP_TAG_ZERO 1
#define FP_EXP_TAG_SPECIAL 2
#define FP_EXP_TAG_EMPTY 3
static inline u32 twd_fxsr_to_i387(struct fxregs_state *fxsave)
{
struct _fpxreg *st;
u32 tos = (fxsave->swd >> 11) & 7;
u32 twd = (unsigned long) fxsave->twd;
u32 tag;
u32 ret = 0xffff0000u;
int i;
for (i = 0; i < 8; i++, twd >>= 1) {
if (twd & 0x1) {
st = FPREG_ADDR(fxsave, (i - tos) & 7);
switch (st->exponent & 0x7fff) {
case 0x7fff:
tag = FP_EXP_TAG_SPECIAL;
break;
case 0x0000:
if (!st->significand[0] &&
!st->significand[1] &&
!st->significand[2] &&
!st->significand[3])
tag = FP_EXP_TAG_ZERO;
else
tag = FP_EXP_TAG_SPECIAL;
break;
default:
if (st->significand[3] & 0x8000)
tag = FP_EXP_TAG_VALID;
else
tag = FP_EXP_TAG_SPECIAL;
break;
}
} else {
tag = FP_EXP_TAG_EMPTY;
}
ret |= tag << (2 * i);
}
return ret;
}
/*
* FXSR floating point environment conversions.
*/
void
convert_from_fxsr(struct user_i387_ia32_struct *env, struct task_struct *tsk)
{
struct fxregs_state *fxsave = &tsk->thread.fpu.state.fxsave;
struct _fpreg *to = (struct _fpreg *) &env->st_space[0];
struct _fpxreg *from = (struct _fpxreg *) &fxsave->st_space[0];
int i;
env->cwd = fxsave->cwd | 0xffff0000u;
env->swd = fxsave->swd | 0xffff0000u;
env->twd = twd_fxsr_to_i387(fxsave);
#ifdef CONFIG_X86_64
env->fip = fxsave->rip;
env->foo = fxsave->rdp;
/*
* should be actually ds/cs at fpu exception time, but
* that information is not available in 64bit mode.
*/
env->fcs = task_pt_regs(tsk)->cs;
if (tsk == current) {
savesegment(ds, env->fos);
} else {
env->fos = tsk->thread.ds;
}
env->fos |= 0xffff0000;
#else
env->fip = fxsave->fip;
env->fcs = (u16) fxsave->fcs | ((u32) fxsave->fop << 16);
env->foo = fxsave->foo;
env->fos = fxsave->fos;
#endif
for (i = 0; i < 8; ++i)
memcpy(&to[i], &from[i], sizeof(to[0]));
}
void convert_to_fxsr(struct task_struct *tsk,
const struct user_i387_ia32_struct *env)
{
struct fxregs_state *fxsave = &tsk->thread.fpu.state.fxsave;
struct _fpreg *from = (struct _fpreg *) &env->st_space[0];
struct _fpxreg *to = (struct _fpxreg *) &fxsave->st_space[0];
int i;
fxsave->cwd = env->cwd;
fxsave->swd = env->swd;
fxsave->twd = twd_i387_to_fxsr(env->twd);
fxsave->fop = (u16) ((u32) env->fcs >> 16);
#ifdef CONFIG_X86_64
fxsave->rip = env->fip;
fxsave->rdp = env->foo;
/* cs and ds ignored */
#else
fxsave->fip = env->fip;
fxsave->fcs = (env->fcs & 0xffff);
fxsave->foo = env->foo;
fxsave->fos = env->fos;
#endif
for (i = 0; i < 8; ++i)
memcpy(&to[i], &from[i], sizeof(from[0]));
}
int fpregs_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
struct user_i387_ia32_struct env;
fpu__activate_fpstate_read(fpu);
if (!boot_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_get(target, regset, pos, count, kbuf, ubuf);
if (!boot_cpu_has(X86_FEATURE_FXSR))
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&fpu->state.fsave, 0,
-1);
fpstate_sanitize_xstate(fpu);
if (kbuf && pos == 0 && count == sizeof(env)) {
convert_from_fxsr(kbuf, target);
return 0;
}
convert_from_fxsr(&env, target);
return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &env, 0, -1);
}
int fpregs_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
struct user_i387_ia32_struct env;
int ret;
fpu__activate_fpstate_write(fpu);
fpstate_sanitize_xstate(fpu);
if (!boot_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_set(target, regset, pos, count, kbuf, ubuf);
if (!boot_cpu_has(X86_FEATURE_FXSR))
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&fpu->state.fsave, 0,
-1);
if (pos > 0 || count < sizeof(env))
convert_from_fxsr(&env, target);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &env, 0, -1);
if (!ret)
convert_to_fxsr(target, &env);
/*
* update the header bit in the xsave header, indicating the
* presence of FP.
*/
if (boot_cpu_has(X86_FEATURE_XSAVE))
fpu->state.xsave.header.xfeatures |= XFEATURE_MASK_FP;
return ret;
}
/*
* FPU state for core dumps.
* This is only used for a.out dumps now.
* It is declared generically using elf_fpregset_t (which is
* struct user_i387_struct) but is in fact only used for 32-bit
* dumps, so on 64-bit it is really struct user_i387_ia32_struct.
*/
int dump_fpu(struct pt_regs *regs, struct user_i387_struct *ufpu)
{
struct task_struct *tsk = current;
struct fpu *fpu = &tsk->thread.fpu;
int fpvalid;
fpvalid = fpu->fpstate_active;
if (fpvalid)
fpvalid = !fpregs_get(tsk, NULL,
0, sizeof(struct user_i387_ia32_struct),
ufpu, NULL);
return fpvalid;
}
EXPORT_SYMBOL(dump_fpu);
#endif /* CONFIG_X86_32 || CONFIG_IA32_EMULATION */
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2864_0 |
crossvul-cpp_data_bad_3361_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% image file and returns it. It allocates the memory necessary for the new
% Image structure and returns a pointer to the new image.
%
% The format of the ReadRLEImage method is:
%
% Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
ValidateColormapValue(image,*p & mask,&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
ValidateColormapValue(image,(size_t) (x*map_length+
(*p & mask)),&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("RLE","RLE","Utah Run length encoded image");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3361_0 |
crossvul-cpp_data_bad_4240_0 | /*
* random.c -- A strong random number generator
*
* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All
* Rights Reserved.
*
* Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
*
* Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. 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, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* ALTERNATIVELY, this product may be distributed under the terms of
* the GNU General Public License, in which case the provisions of the GPL are
* required INSTEAD OF the above restrictions. (This clause is
* necessary due to a potential bad interaction between the GPL and
* the restrictions contained in a BSD-style copyright.)
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*
* (now, with legal B.S. out of the way.....)
*
* This routine gathers environmental noise from device drivers, etc.,
* and returns good random numbers, suitable for cryptographic use.
* Besides the obvious cryptographic uses, these numbers are also good
* for seeding TCP sequence numbers, and other places where it is
* desirable to have numbers which are not only random, but hard to
* predict by an attacker.
*
* Theory of operation
* ===================
*
* Computers are very predictable devices. Hence it is extremely hard
* to produce truly random numbers on a computer --- as opposed to
* pseudo-random numbers, which can easily generated by using a
* algorithm. Unfortunately, it is very easy for attackers to guess
* the sequence of pseudo-random number generators, and for some
* applications this is not acceptable. So instead, we must try to
* gather "environmental noise" from the computer's environment, which
* must be hard for outside attackers to observe, and use that to
* generate random numbers. In a Unix environment, this is best done
* from inside the kernel.
*
* Sources of randomness from the environment include inter-keyboard
* timings, inter-interrupt timings from some interrupts, and other
* events which are both (a) non-deterministic and (b) hard for an
* outside observer to measure. Randomness from these sources are
* added to an "entropy pool", which is mixed using a CRC-like function.
* This is not cryptographically strong, but it is adequate assuming
* the randomness is not chosen maliciously, and it is fast enough that
* the overhead of doing it on every interrupt is very reasonable.
* As random bytes are mixed into the entropy pool, the routines keep
* an *estimate* of how many bits of randomness have been stored into
* the random number generator's internal state.
*
* When random bytes are desired, they are obtained by taking the SHA
* hash of the contents of the "entropy pool". The SHA hash avoids
* exposing the internal state of the entropy pool. It is believed to
* be computationally infeasible to derive any useful information
* about the input of SHA from its output. Even if it is possible to
* analyze SHA in some clever way, as long as the amount of data
* returned from the generator is less than the inherent entropy in
* the pool, the output data is totally unpredictable. For this
* reason, the routine decreases its internal estimate of how many
* bits of "true randomness" are contained in the entropy pool as it
* outputs random numbers.
*
* If this estimate goes to zero, the routine can still generate
* random numbers; however, an attacker may (at least in theory) be
* able to infer the future output of the generator from prior
* outputs. This requires successful cryptanalysis of SHA, which is
* not believed to be feasible, but there is a remote possibility.
* Nonetheless, these numbers should be useful for the vast majority
* of purposes.
*
* Exported interfaces ---- output
* ===============================
*
* There are four exported interfaces; two for use within the kernel,
* and two or use from userspace.
*
* Exported interfaces ---- userspace output
* -----------------------------------------
*
* The userspace interfaces are two character devices /dev/random and
* /dev/urandom. /dev/random is suitable for use when very high
* quality randomness is desired (for example, for key generation or
* one-time pads), as it will only return a maximum of the number of
* bits of randomness (as estimated by the random number generator)
* contained in the entropy pool.
*
* The /dev/urandom device does not have this limit, and will return
* as many bytes as are requested. As more and more random bytes are
* requested without giving time for the entropy pool to recharge,
* this will result in random numbers that are merely cryptographically
* strong. For many applications, however, this is acceptable.
*
* Exported interfaces ---- kernel output
* --------------------------------------
*
* The primary kernel interface is
*
* void get_random_bytes(void *buf, int nbytes);
*
* This interface will return the requested number of random bytes,
* and place it in the requested buffer. This is equivalent to a
* read from /dev/urandom.
*
* For less critical applications, there are the functions:
*
* u32 get_random_u32()
* u64 get_random_u64()
* unsigned int get_random_int()
* unsigned long get_random_long()
*
* These are produced by a cryptographic RNG seeded from get_random_bytes,
* and so do not deplete the entropy pool as much. These are recommended
* for most in-kernel operations *if the result is going to be stored in
* the kernel*.
*
* Specifically, the get_random_int() family do not attempt to do
* "anti-backtracking". If you capture the state of the kernel (e.g.
* by snapshotting the VM), you can figure out previous get_random_int()
* return values. But if the value is stored in the kernel anyway,
* this is not a problem.
*
* It *is* safe to expose get_random_int() output to attackers (e.g. as
* network cookies); given outputs 1..n, it's not feasible to predict
* outputs 0 or n+1. The only concern is an attacker who breaks into
* the kernel later; the get_random_int() engine is not reseeded as
* often as the get_random_bytes() one.
*
* get_random_bytes() is needed for keys that need to stay secret after
* they are erased from the kernel. For example, any key that will
* be wrapped and stored encrypted. And session encryption keys: we'd
* like to know that after the session is closed and the keys erased,
* the plaintext is unrecoverable to someone who recorded the ciphertext.
*
* But for network ports/cookies, stack canaries, PRNG seeds, address
* space layout randomization, session *authentication* keys, or other
* applications where the sensitive data is stored in the kernel in
* plaintext for as long as it's sensitive, the get_random_int() family
* is just fine.
*
* Consider ASLR. We want to keep the address space secret from an
* outside attacker while the process is running, but once the address
* space is torn down, it's of no use to an attacker any more. And it's
* stored in kernel data structures as long as it's alive, so worrying
* about an attacker's ability to extrapolate it from the get_random_int()
* CRNG is silly.
*
* Even some cryptographic keys are safe to generate with get_random_int().
* In particular, keys for SipHash are generally fine. Here, knowledge
* of the key authorizes you to do something to a kernel object (inject
* packets to a network connection, or flood a hash table), and the
* key is stored with the object being protected. Once it goes away,
* we no longer care if anyone knows the key.
*
* prandom_u32()
* -------------
*
* For even weaker applications, see the pseudorandom generator
* prandom_u32(), prandom_max(), and prandom_bytes(). If the random
* numbers aren't security-critical at all, these are *far* cheaper.
* Useful for self-tests, random error simulation, randomized backoffs,
* and any other application where you trust that nobody is trying to
* maliciously mess with you by guessing the "random" numbers.
*
* Exported interfaces ---- input
* ==============================
*
* The current exported interfaces for gathering environmental noise
* from the devices are:
*
* void add_device_randomness(const void *buf, unsigned int size);
* void add_input_randomness(unsigned int type, unsigned int code,
* unsigned int value);
* void add_interrupt_randomness(int irq, int irq_flags);
* void add_disk_randomness(struct gendisk *disk);
*
* add_device_randomness() is for adding data to the random pool that
* is likely to differ between two devices (or possibly even per boot).
* This would be things like MAC addresses or serial numbers, or the
* read-out of the RTC. This does *not* add any actual entropy to the
* pool, but it initializes the pool to different values for devices
* that might otherwise be identical and have very little entropy
* available to them (particularly common in the embedded world).
*
* add_input_randomness() uses the input layer interrupt timing, as well as
* the event type information from the hardware.
*
* add_interrupt_randomness() uses the interrupt timing as random
* inputs to the entropy pool. Using the cycle counters and the irq source
* as inputs, it feeds the randomness roughly once a second.
*
* add_disk_randomness() uses what amounts to the seek time of block
* layer request events, on a per-disk_devt basis, as input to the
* entropy pool. Note that high-speed solid state drives with very low
* seek times do not make for good sources of entropy, as their seek
* times are usually fairly consistent.
*
* All of these routines try to estimate how many bits of randomness a
* particular randomness source. They do this by keeping track of the
* first and second order deltas of the event timings.
*
* Ensuring unpredictability at system startup
* ============================================
*
* When any operating system starts up, it will go through a sequence
* of actions that are fairly predictable by an adversary, especially
* if the start-up does not involve interaction with a human operator.
* This reduces the actual number of bits of unpredictability in the
* entropy pool below the value in entropy_count. In order to
* counteract this effect, it helps to carry information in the
* entropy pool across shut-downs and start-ups. To do this, put the
* following lines an appropriate script which is run during the boot
* sequence:
*
* echo "Initializing random number generator..."
* random_seed=/var/run/random-seed
* # Carry a random seed from start-up to start-up
* # Load and then save the whole entropy pool
* if [ -f $random_seed ]; then
* cat $random_seed >/dev/urandom
* else
* touch $random_seed
* fi
* chmod 600 $random_seed
* dd if=/dev/urandom of=$random_seed count=1 bs=512
*
* and the following lines in an appropriate script which is run as
* the system is shutdown:
*
* # Carry a random seed from shut-down to start-up
* # Save the whole entropy pool
* echo "Saving random seed..."
* random_seed=/var/run/random-seed
* touch $random_seed
* chmod 600 $random_seed
* dd if=/dev/urandom of=$random_seed count=1 bs=512
*
* For example, on most modern systems using the System V init
* scripts, such code fragments would be found in
* /etc/rc.d/init.d/random. On older Linux systems, the correct script
* location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
*
* Effectively, these commands cause the contents of the entropy pool
* to be saved at shut-down time and reloaded into the entropy pool at
* start-up. (The 'dd' in the addition to the bootup script is to
* make sure that /etc/random-seed is different for every start-up,
* even if the system crashes without executing rc.0.) Even with
* complete knowledge of the start-up activities, predicting the state
* of the entropy pool requires knowledge of the previous history of
* the system.
*
* Configuring the /dev/random driver under Linux
* ==============================================
*
* The /dev/random driver under Linux uses minor numbers 8 and 9 of
* the /dev/mem major number (#1). So if your system does not have
* /dev/random and /dev/urandom created already, they can be created
* by using the commands:
*
* mknod /dev/random c 1 8
* mknod /dev/urandom c 1 9
*
* Acknowledgements:
* =================
*
* Ideas for constructing this random number generator were derived
* from Pretty Good Privacy's random number generator, and from private
* discussions with Phil Karn. Colin Plumb provided a faster random
* number generator, which speed up the mixing function of the entropy
* pool, taken from PGPfone. Dale Worley has also contributed many
* useful ideas and suggestions to improve this driver.
*
* Any flaws in the design are solely my responsibility, and should
* not be attributed to the Phil, Colin, or any of authors of PGP.
*
* Further background information on this topic may be obtained from
* RFC 1750, "Randomness Recommendations for Security", by Donald
* Eastlake, Steve Crocker, and Jeff Schiller.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/utsname.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/fcntl.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/nodemask.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/percpu.h>
#include <linux/fips.h>
#include <linux/ptrace.h>
#include <linux/workqueue.h>
#include <linux/irq.h>
#include <linux/ratelimit.h>
#include <linux/syscalls.h>
#include <linux/completion.h>
#include <linux/uuid.h>
#include <crypto/chacha.h>
#include <crypto/sha.h>
#include <asm/processor.h>
#include <linux/uaccess.h>
#include <asm/irq.h>
#include <asm/irq_regs.h>
#include <asm/io.h>
#define CREATE_TRACE_POINTS
#include <trace/events/random.h>
/* #define ADD_INTERRUPT_BENCH */
/*
* Configuration information
*/
#define INPUT_POOL_SHIFT 12
#define INPUT_POOL_WORDS (1 << (INPUT_POOL_SHIFT-5))
#define OUTPUT_POOL_SHIFT 10
#define OUTPUT_POOL_WORDS (1 << (OUTPUT_POOL_SHIFT-5))
#define EXTRACT_SIZE 10
#define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
/*
* To allow fractional bits to be tracked, the entropy_count field is
* denominated in units of 1/8th bits.
*
* 2*(ENTROPY_SHIFT + poolbitshift) must <= 31, or the multiply in
* credit_entropy_bits() needs to be 64 bits wide.
*/
#define ENTROPY_SHIFT 3
#define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
/*
* If the entropy count falls under this number of bits, then we
* should wake up processes which are selecting or polling on write
* access to /dev/random.
*/
static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
/*
* Originally, we used a primitive polynomial of degree .poolwords
* over GF(2). The taps for various sizes are defined below. They
* were chosen to be evenly spaced except for the last tap, which is 1
* to get the twisting happening as fast as possible.
*
* For the purposes of better mixing, we use the CRC-32 polynomial as
* well to make a (modified) twisted Generalized Feedback Shift
* Register. (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR
* generators. ACM Transactions on Modeling and Computer Simulation
* 2(3):179-194. Also see M. Matsumoto & Y. Kurita, 1994. Twisted
* GFSR generators II. ACM Transactions on Modeling and Computer
* Simulation 4:254-266)
*
* Thanks to Colin Plumb for suggesting this.
*
* The mixing operation is much less sensitive than the output hash,
* where we use SHA-1. All that we want of mixing operation is that
* it be a good non-cryptographic hash; i.e. it not produce collisions
* when fed "random" data of the sort we expect to see. As long as
* the pool state differs for different inputs, we have preserved the
* input entropy and done a good job. The fact that an intelligent
* attacker can construct inputs that will produce controlled
* alterations to the pool's state is not important because we don't
* consider such inputs to contribute any randomness. The only
* property we need with respect to them is that the attacker can't
* increase his/her knowledge of the pool's state. Since all
* additions are reversible (knowing the final state and the input,
* you can reconstruct the initial state), if an attacker has any
* uncertainty about the initial state, he/she can only shuffle that
* uncertainty about, but never cause any collisions (which would
* decrease the uncertainty).
*
* Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
* Videau in their paper, "The Linux Pseudorandom Number Generator
* Revisited" (see: http://eprint.iacr.org/2012/251.pdf). In their
* paper, they point out that we are not using a true Twisted GFSR,
* since Matsumoto & Kurita used a trinomial feedback polynomial (that
* is, with only three taps, instead of the six that we are using).
* As a result, the resulting polynomial is neither primitive nor
* irreducible, and hence does not have a maximal period over
* GF(2**32). They suggest a slight change to the generator
* polynomial which improves the resulting TGFSR polynomial to be
* irreducible, which we have made here.
*/
static const struct poolinfo {
int poolbitshift, poolwords, poolbytes, poolfracbits;
#define S(x) ilog2(x)+5, (x), (x)*4, (x) << (ENTROPY_SHIFT+5)
int tap1, tap2, tap3, tap4, tap5;
} poolinfo_table[] = {
/* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
/* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
{ S(128), 104, 76, 51, 25, 1 },
};
/*
* Static global variables
*/
static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
static struct fasync_struct *fasync;
static DEFINE_SPINLOCK(random_ready_list_lock);
static LIST_HEAD(random_ready_list);
struct crng_state {
__u32 state[16];
unsigned long init_time;
spinlock_t lock;
};
static struct crng_state primary_crng = {
.lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
};
/*
* crng_init = 0 --> Uninitialized
* 1 --> Initialized
* 2 --> Initialized from input_pool
*
* crng_init is protected by primary_crng->lock, and only increases
* its value (from 0->1->2).
*/
static int crng_init = 0;
#define crng_ready() (likely(crng_init > 1))
static int crng_init_cnt = 0;
static unsigned long crng_global_init_time = 0;
#define CRNG_INIT_CNT_THRESH (2*CHACHA_KEY_SIZE)
static void _extract_crng(struct crng_state *crng, __u8 out[CHACHA_BLOCK_SIZE]);
static void _crng_backtrack_protect(struct crng_state *crng,
__u8 tmp[CHACHA_BLOCK_SIZE], int used);
static void process_random_ready_list(void);
static void _get_random_bytes(void *buf, int nbytes);
static struct ratelimit_state unseeded_warning =
RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
static struct ratelimit_state urandom_warning =
RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
static int ratelimit_disable __read_mostly;
module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
/**********************************************************************
*
* OS independent entropy store. Here are the functions which handle
* storing entropy in an entropy pool.
*
**********************************************************************/
struct entropy_store;
struct entropy_store {
/* read-only data: */
const struct poolinfo *poolinfo;
__u32 *pool;
const char *name;
/* read-write data: */
spinlock_t lock;
unsigned short add_ptr;
unsigned short input_rotate;
int entropy_count;
unsigned int initialized:1;
unsigned int last_data_init:1;
__u8 last_data[EXTRACT_SIZE];
};
static ssize_t extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int min, int rsvd);
static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int fips);
static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
static struct entropy_store input_pool = {
.poolinfo = &poolinfo_table[0],
.name = "input",
.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
.pool = input_pool_data
};
static __u32 const twist_table[8] = {
0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
/*
* This function adds bytes into the entropy "pool". It does not
* update the entropy estimate. The caller should call
* credit_entropy_bits if this is appropriate.
*
* The pool is stirred with a primitive polynomial of the appropriate
* degree, and then twisted. We twist by three bits at a time because
* it's cheap to do so and helps slightly in the expected case where
* the entropy is concentrated in the low-order bits.
*/
static void _mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
unsigned long i, tap1, tap2, tap3, tap4, tap5;
int input_rotate;
int wordmask = r->poolinfo->poolwords - 1;
const char *bytes = in;
__u32 w;
tap1 = r->poolinfo->tap1;
tap2 = r->poolinfo->tap2;
tap3 = r->poolinfo->tap3;
tap4 = r->poolinfo->tap4;
tap5 = r->poolinfo->tap5;
input_rotate = r->input_rotate;
i = r->add_ptr;
/* mix one byte at a time to simplify size handling and churn faster */
while (nbytes--) {
w = rol32(*bytes++, input_rotate);
i = (i - 1) & wordmask;
/* XOR in the various taps */
w ^= r->pool[i];
w ^= r->pool[(i + tap1) & wordmask];
w ^= r->pool[(i + tap2) & wordmask];
w ^= r->pool[(i + tap3) & wordmask];
w ^= r->pool[(i + tap4) & wordmask];
w ^= r->pool[(i + tap5) & wordmask];
/* Mix the result back in with a twist */
r->pool[i] = (w >> 3) ^ twist_table[w & 7];
/*
* Normally, we add 7 bits of rotation to the pool.
* At the beginning of the pool, add an extra 7 bits
* rotation, so that successive passes spread the
* input bits across the pool evenly.
*/
input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
}
r->input_rotate = input_rotate;
r->add_ptr = i;
}
static void __mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
_mix_pool_bytes(r, in, nbytes);
}
static void mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
unsigned long flags;
trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
spin_lock_irqsave(&r->lock, flags);
_mix_pool_bytes(r, in, nbytes);
spin_unlock_irqrestore(&r->lock, flags);
}
struct fast_pool {
__u32 pool[4];
unsigned long last;
unsigned short reg_idx;
unsigned char count;
};
/*
* This is a fast mixing routine used by the interrupt randomness
* collector. It's hardcoded for an 128 bit pool and assumes that any
* locks that might be needed are taken by the caller.
*/
static void fast_mix(struct fast_pool *f)
{
__u32 a = f->pool[0], b = f->pool[1];
__u32 c = f->pool[2], d = f->pool[3];
a += b; c += d;
b = rol32(b, 6); d = rol32(d, 27);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 16); d = rol32(d, 14);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 6); d = rol32(d, 27);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 16); d = rol32(d, 14);
d ^= a; b ^= c;
f->pool[0] = a; f->pool[1] = b;
f->pool[2] = c; f->pool[3] = d;
f->count++;
}
static void process_random_ready_list(void)
{
unsigned long flags;
struct random_ready_callback *rdy, *tmp;
spin_lock_irqsave(&random_ready_list_lock, flags);
list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
struct module *owner = rdy->owner;
list_del_init(&rdy->list);
rdy->func(rdy);
module_put(owner);
}
spin_unlock_irqrestore(&random_ready_list_lock, flags);
}
/*
* Credit (or debit) the entropy store with n bits of entropy.
* Use credit_entropy_bits_safe() if the value comes from userspace
* or otherwise should be checked for extreme values.
*/
static void credit_entropy_bits(struct entropy_store *r, int nbits)
{
int entropy_count, orig, has_initialized = 0;
const int pool_size = r->poolinfo->poolfracbits;
int nfrac = nbits << ENTROPY_SHIFT;
if (!nbits)
return;
retry:
entropy_count = orig = READ_ONCE(r->entropy_count);
if (nfrac < 0) {
/* Debit */
entropy_count += nfrac;
} else {
/*
* Credit: we have to account for the possibility of
* overwriting already present entropy. Even in the
* ideal case of pure Shannon entropy, new contributions
* approach the full value asymptotically:
*
* entropy <- entropy + (pool_size - entropy) *
* (1 - exp(-add_entropy/pool_size))
*
* For add_entropy <= pool_size/2 then
* (1 - exp(-add_entropy/pool_size)) >=
* (add_entropy/pool_size)*0.7869...
* so we can approximate the exponential with
* 3/4*add_entropy/pool_size and still be on the
* safe side by adding at most pool_size/2 at a time.
*
* The use of pool_size-2 in the while statement is to
* prevent rounding artifacts from making the loop
* arbitrarily long; this limits the loop to log2(pool_size)*2
* turns no matter how large nbits is.
*/
int pnfrac = nfrac;
const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
/* The +2 corresponds to the /4 in the denominator */
do {
unsigned int anfrac = min(pnfrac, pool_size/2);
unsigned int add =
((pool_size - entropy_count)*anfrac*3) >> s;
entropy_count += add;
pnfrac -= anfrac;
} while (unlikely(entropy_count < pool_size-2 && pnfrac));
}
if (WARN_ON(entropy_count < 0)) {
pr_warn("negative entropy/overflow: pool %s count %d\n",
r->name, entropy_count);
entropy_count = 0;
} else if (entropy_count > pool_size)
entropy_count = pool_size;
if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
goto retry;
if (has_initialized) {
r->initialized = 1;
kill_fasync(&fasync, SIGIO, POLL_IN);
}
trace_credit_entropy_bits(r->name, nbits,
entropy_count >> ENTROPY_SHIFT, _RET_IP_);
if (r == &input_pool) {
int entropy_bits = entropy_count >> ENTROPY_SHIFT;
if (crng_init < 2) {
if (entropy_bits < 128)
return;
crng_reseed(&primary_crng, r);
entropy_bits = ENTROPY_BITS(r);
}
}
}
static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
{
const int nbits_max = r->poolinfo->poolwords * 32;
if (nbits < 0)
return -EINVAL;
/* Cap the value to avoid overflows */
nbits = min(nbits, nbits_max);
credit_entropy_bits(r, nbits);
return 0;
}
/*********************************************************************
*
* CRNG using CHACHA20
*
*********************************************************************/
#define CRNG_RESEED_INTERVAL (300*HZ)
static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
#ifdef CONFIG_NUMA
/*
* Hack to deal with crazy userspace progams when they are all trying
* to access /dev/urandom in parallel. The programs are almost
* certainly doing something terribly wrong, but we'll work around
* their brain damage.
*/
static struct crng_state **crng_node_pool __read_mostly;
#endif
static void invalidate_batched_entropy(void);
static void numa_crng_init(void);
static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
static int __init parse_trust_cpu(char *arg)
{
return kstrtobool(arg, &trust_cpu);
}
early_param("random.trust_cpu", parse_trust_cpu);
static bool crng_init_try_arch(struct crng_state *crng)
{
int i;
bool arch_init = true;
unsigned long rv;
for (i = 4; i < 16; i++) {
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv)) {
rv = random_get_entropy();
arch_init = false;
}
crng->state[i] ^= rv;
}
return arch_init;
}
static bool __init crng_init_try_arch_early(struct crng_state *crng)
{
int i;
bool arch_init = true;
unsigned long rv;
for (i = 4; i < 16; i++) {
if (!arch_get_random_seed_long_early(&rv) &&
!arch_get_random_long_early(&rv)) {
rv = random_get_entropy();
arch_init = false;
}
crng->state[i] ^= rv;
}
return arch_init;
}
static void __maybe_unused crng_initialize_secondary(struct crng_state *crng)
{
memcpy(&crng->state[0], "expand 32-byte k", 16);
_get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
crng_init_try_arch(crng);
crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
}
static void __init crng_initialize_primary(struct crng_state *crng)
{
memcpy(&crng->state[0], "expand 32-byte k", 16);
_extract_entropy(&input_pool, &crng->state[4], sizeof(__u32) * 12, 0);
if (crng_init_try_arch_early(crng) && trust_cpu) {
invalidate_batched_entropy();
numa_crng_init();
crng_init = 2;
pr_notice("crng done (trusting CPU's manufacturer)\n");
}
crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
}
#ifdef CONFIG_NUMA
static void do_numa_crng_init(struct work_struct *work)
{
int i;
struct crng_state *crng;
struct crng_state **pool;
pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
for_each_online_node(i) {
crng = kmalloc_node(sizeof(struct crng_state),
GFP_KERNEL | __GFP_NOFAIL, i);
spin_lock_init(&crng->lock);
crng_initialize_secondary(crng);
pool[i] = crng;
}
mb();
if (cmpxchg(&crng_node_pool, NULL, pool)) {
for_each_node(i)
kfree(pool[i]);
kfree(pool);
}
}
static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init);
static void numa_crng_init(void)
{
schedule_work(&numa_crng_init_work);
}
#else
static void numa_crng_init(void) {}
#endif
/*
* crng_fast_load() can be called by code in the interrupt service
* path. So we can't afford to dilly-dally.
*/
static int crng_fast_load(const char *cp, size_t len)
{
unsigned long flags;
char *p;
if (!spin_trylock_irqsave(&primary_crng.lock, flags))
return 0;
if (crng_init != 0) {
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 0;
}
p = (unsigned char *) &primary_crng.state[4];
while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
p[crng_init_cnt % CHACHA_KEY_SIZE] ^= *cp;
cp++; crng_init_cnt++; len--;
}
spin_unlock_irqrestore(&primary_crng.lock, flags);
if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
invalidate_batched_entropy();
crng_init = 1;
pr_notice("fast init done\n");
}
return 1;
}
/*
* crng_slow_load() is called by add_device_randomness, which has two
* attributes. (1) We can't trust the buffer passed to it is
* guaranteed to be unpredictable (so it might not have any entropy at
* all), and (2) it doesn't have the performance constraints of
* crng_fast_load().
*
* So we do something more comprehensive which is guaranteed to touch
* all of the primary_crng's state, and which uses a LFSR with a
* period of 255 as part of the mixing algorithm. Finally, we do
* *not* advance crng_init_cnt since buffer we may get may be something
* like a fixed DMI table (for example), which might very well be
* unique to the machine, but is otherwise unvarying.
*/
static int crng_slow_load(const char *cp, size_t len)
{
unsigned long flags;
static unsigned char lfsr = 1;
unsigned char tmp;
unsigned i, max = CHACHA_KEY_SIZE;
const char * src_buf = cp;
char * dest_buf = (char *) &primary_crng.state[4];
if (!spin_trylock_irqsave(&primary_crng.lock, flags))
return 0;
if (crng_init != 0) {
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 0;
}
if (len > max)
max = len;
for (i = 0; i < max ; i++) {
tmp = lfsr;
lfsr >>= 1;
if (tmp & 1)
lfsr ^= 0xE1;
tmp = dest_buf[i % CHACHA_KEY_SIZE];
dest_buf[i % CHACHA_KEY_SIZE] ^= src_buf[i % len] ^ lfsr;
lfsr += (tmp << 3) | (tmp >> 5);
}
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 1;
}
static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
{
unsigned long flags;
int i, num;
union {
__u8 block[CHACHA_BLOCK_SIZE];
__u32 key[8];
} buf;
if (r) {
num = extract_entropy(r, &buf, 32, 16, 0);
if (num == 0)
return;
} else {
_extract_crng(&primary_crng, buf.block);
_crng_backtrack_protect(&primary_crng, buf.block,
CHACHA_KEY_SIZE);
}
spin_lock_irqsave(&crng->lock, flags);
for (i = 0; i < 8; i++) {
unsigned long rv;
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv))
rv = random_get_entropy();
crng->state[i+4] ^= buf.key[i] ^ rv;
}
memzero_explicit(&buf, sizeof(buf));
crng->init_time = jiffies;
spin_unlock_irqrestore(&crng->lock, flags);
if (crng == &primary_crng && crng_init < 2) {
invalidate_batched_entropy();
numa_crng_init();
crng_init = 2;
process_random_ready_list();
wake_up_interruptible(&crng_init_wait);
kill_fasync(&fasync, SIGIO, POLL_IN);
pr_notice("crng init done\n");
if (unseeded_warning.missed) {
pr_notice("%d get_random_xx warning(s) missed due to ratelimiting\n",
unseeded_warning.missed);
unseeded_warning.missed = 0;
}
if (urandom_warning.missed) {
pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
urandom_warning.missed);
urandom_warning.missed = 0;
}
}
}
static void _extract_crng(struct crng_state *crng,
__u8 out[CHACHA_BLOCK_SIZE])
{
unsigned long v, flags;
if (crng_ready() &&
(time_after(crng_global_init_time, crng->init_time) ||
time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL)))
crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
spin_lock_irqsave(&crng->lock, flags);
if (arch_get_random_long(&v))
crng->state[14] ^= v;
chacha20_block(&crng->state[0], out);
if (crng->state[12] == 0)
crng->state[13]++;
spin_unlock_irqrestore(&crng->lock, flags);
}
static void extract_crng(__u8 out[CHACHA_BLOCK_SIZE])
{
struct crng_state *crng = NULL;
#ifdef CONFIG_NUMA
if (crng_node_pool)
crng = crng_node_pool[numa_node_id()];
if (crng == NULL)
#endif
crng = &primary_crng;
_extract_crng(crng, out);
}
/*
* Use the leftover bytes from the CRNG block output (if there is
* enough) to mutate the CRNG key to provide backtracking protection.
*/
static void _crng_backtrack_protect(struct crng_state *crng,
__u8 tmp[CHACHA_BLOCK_SIZE], int used)
{
unsigned long flags;
__u32 *s, *d;
int i;
used = round_up(used, sizeof(__u32));
if (used + CHACHA_KEY_SIZE > CHACHA_BLOCK_SIZE) {
extract_crng(tmp);
used = 0;
}
spin_lock_irqsave(&crng->lock, flags);
s = (__u32 *) &tmp[used];
d = &crng->state[4];
for (i=0; i < 8; i++)
*d++ ^= *s++;
spin_unlock_irqrestore(&crng->lock, flags);
}
static void crng_backtrack_protect(__u8 tmp[CHACHA_BLOCK_SIZE], int used)
{
struct crng_state *crng = NULL;
#ifdef CONFIG_NUMA
if (crng_node_pool)
crng = crng_node_pool[numa_node_id()];
if (crng == NULL)
#endif
crng = &primary_crng;
_crng_backtrack_protect(crng, tmp, used);
}
static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
{
ssize_t ret = 0, i = CHACHA_BLOCK_SIZE;
__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
int large_request = (nbytes > 256);
while (nbytes) {
if (large_request && need_resched()) {
if (signal_pending(current)) {
if (ret == 0)
ret = -ERESTARTSYS;
break;
}
schedule();
}
extract_crng(tmp);
i = min_t(int, nbytes, CHACHA_BLOCK_SIZE);
if (copy_to_user(buf, tmp, i)) {
ret = -EFAULT;
break;
}
nbytes -= i;
buf += i;
ret += i;
}
crng_backtrack_protect(tmp, i);
/* Wipe data just written to memory */
memzero_explicit(tmp, sizeof(tmp));
return ret;
}
/*********************************************************************
*
* Entropy input management
*
*********************************************************************/
/* There is one of these per entropy source */
struct timer_rand_state {
cycles_t last_time;
long last_delta, last_delta2;
};
#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
/*
* Add device- or boot-specific data to the input pool to help
* initialize it.
*
* None of this adds any entropy; it is meant to avoid the problem of
* the entropy pool having similar initial state across largely
* identical devices.
*/
void add_device_randomness(const void *buf, unsigned int size)
{
unsigned long time = random_get_entropy() ^ jiffies;
unsigned long flags;
if (!crng_ready() && size)
crng_slow_load(buf, size);
trace_add_device_randomness(size, _RET_IP_);
spin_lock_irqsave(&input_pool.lock, flags);
_mix_pool_bytes(&input_pool, buf, size);
_mix_pool_bytes(&input_pool, &time, sizeof(time));
spin_unlock_irqrestore(&input_pool.lock, flags);
}
EXPORT_SYMBOL(add_device_randomness);
static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
/*
* This function adds entropy to the entropy "pool" by using timing
* delays. It uses the timer_rand_state structure to make an estimate
* of how many bits of entropy this call has added to the pool.
*
* The number "num" is also added to the pool - it should somehow describe
* the type of event which just happened. This is currently 0-255 for
* keyboard scan codes, and 256 upwards for interrupts.
*
*/
static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
{
struct entropy_store *r;
struct {
long jiffies;
unsigned cycles;
unsigned num;
} sample;
long delta, delta2, delta3;
sample.jiffies = jiffies;
sample.cycles = random_get_entropy();
sample.num = num;
r = &input_pool;
mix_pool_bytes(r, &sample, sizeof(sample));
/*
* Calculate number of bits of randomness we probably added.
* We take into account the first, second and third-order deltas
* in order to make our estimate.
*/
delta = sample.jiffies - READ_ONCE(state->last_time);
WRITE_ONCE(state->last_time, sample.jiffies);
delta2 = delta - READ_ONCE(state->last_delta);
WRITE_ONCE(state->last_delta, delta);
delta3 = delta2 - READ_ONCE(state->last_delta2);
WRITE_ONCE(state->last_delta2, delta2);
if (delta < 0)
delta = -delta;
if (delta2 < 0)
delta2 = -delta2;
if (delta3 < 0)
delta3 = -delta3;
if (delta > delta2)
delta = delta2;
if (delta > delta3)
delta = delta3;
/*
* delta is now minimum absolute delta.
* Round down by 1 bit on general principles,
* and limit entropy estimate to 12 bits.
*/
credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
}
void add_input_randomness(unsigned int type, unsigned int code,
unsigned int value)
{
static unsigned char last_value;
/* ignore autorepeat and the like */
if (value == last_value)
return;
last_value = value;
add_timer_randomness(&input_timer_state,
(type << 4) ^ code ^ (code >> 4) ^ value);
trace_add_input_randomness(ENTROPY_BITS(&input_pool));
}
EXPORT_SYMBOL_GPL(add_input_randomness);
static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
#ifdef ADD_INTERRUPT_BENCH
static unsigned long avg_cycles, avg_deviation;
#define AVG_SHIFT 8 /* Exponential average factor k=1/256 */
#define FIXED_1_2 (1 << (AVG_SHIFT-1))
static void add_interrupt_bench(cycles_t start)
{
long delta = random_get_entropy() - start;
/* Use a weighted moving average */
delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
avg_cycles += delta;
/* And average deviation */
delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
avg_deviation += delta;
}
#else
#define add_interrupt_bench(x)
#endif
static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
{
__u32 *ptr = (__u32 *) regs;
unsigned int idx;
if (regs == NULL)
return 0;
idx = READ_ONCE(f->reg_idx);
if (idx >= sizeof(struct pt_regs) / sizeof(__u32))
idx = 0;
ptr += idx++;
WRITE_ONCE(f->reg_idx, idx);
return *ptr;
}
void add_interrupt_randomness(int irq, int irq_flags)
{
struct entropy_store *r;
struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
struct pt_regs *regs = get_irq_regs();
unsigned long now = jiffies;
cycles_t cycles = random_get_entropy();
__u32 c_high, j_high;
__u64 ip;
unsigned long seed;
int credit = 0;
if (cycles == 0)
cycles = get_reg(fast_pool, regs);
c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
fast_pool->pool[1] ^= now ^ c_high;
ip = regs ? instruction_pointer(regs) : _RET_IP_;
fast_pool->pool[2] ^= ip;
fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
get_reg(fast_pool, regs);
fast_mix(fast_pool);
add_interrupt_bench(cycles);
if (unlikely(crng_init == 0)) {
if ((fast_pool->count >= 64) &&
crng_fast_load((char *) fast_pool->pool,
sizeof(fast_pool->pool))) {
fast_pool->count = 0;
fast_pool->last = now;
}
return;
}
if ((fast_pool->count < 64) &&
!time_after(now, fast_pool->last + HZ))
return;
r = &input_pool;
if (!spin_trylock(&r->lock))
return;
fast_pool->last = now;
__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
/*
* If we have architectural seed generator, produce a seed and
* add it to the pool. For the sake of paranoia don't let the
* architectural seed generator dominate the input from the
* interrupt noise.
*/
if (arch_get_random_seed_long(&seed)) {
__mix_pool_bytes(r, &seed, sizeof(seed));
credit = 1;
}
spin_unlock(&r->lock);
fast_pool->count = 0;
/* award one bit for the contents of the fast pool */
credit_entropy_bits(r, credit + 1);
}
EXPORT_SYMBOL_GPL(add_interrupt_randomness);
#ifdef CONFIG_BLOCK
void add_disk_randomness(struct gendisk *disk)
{
if (!disk || !disk->random)
return;
/* first major is 1, so we get >= 0x200 here */
add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
}
EXPORT_SYMBOL_GPL(add_disk_randomness);
#endif
/*********************************************************************
*
* Entropy extraction routines
*
*********************************************************************/
/*
* This function decides how many bytes to actually take from the
* given pool, and also debits the entropy count accordingly.
*/
static size_t account(struct entropy_store *r, size_t nbytes, int min,
int reserved)
{
int entropy_count, orig, have_bytes;
size_t ibytes, nfrac;
BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
/* Can we pull enough? */
retry:
entropy_count = orig = READ_ONCE(r->entropy_count);
ibytes = nbytes;
/* never pull more than available */
have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
if ((have_bytes -= reserved) < 0)
have_bytes = 0;
ibytes = min_t(size_t, ibytes, have_bytes);
if (ibytes < min)
ibytes = 0;
if (WARN_ON(entropy_count < 0)) {
pr_warn("negative entropy count: pool %s count %d\n",
r->name, entropy_count);
entropy_count = 0;
}
nfrac = ibytes << (ENTROPY_SHIFT + 3);
if ((size_t) entropy_count > nfrac)
entropy_count -= nfrac;
else
entropy_count = 0;
if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
goto retry;
trace_debit_entropy(r->name, 8 * ibytes);
if (ibytes && ENTROPY_BITS(r) < random_write_wakeup_bits) {
wake_up_interruptible(&random_write_wait);
kill_fasync(&fasync, SIGIO, POLL_OUT);
}
return ibytes;
}
/*
* This function does the actual extraction for extract_entropy and
* extract_entropy_user.
*
* Note: we assume that .poolwords is a multiple of 16 words.
*/
static void extract_buf(struct entropy_store *r, __u8 *out)
{
int i;
union {
__u32 w[5];
unsigned long l[LONGS(20)];
} hash;
__u32 workspace[SHA1_WORKSPACE_WORDS];
unsigned long flags;
/*
* If we have an architectural hardware random number
* generator, use it for SHA's initial vector
*/
sha1_init(hash.w);
for (i = 0; i < LONGS(20); i++) {
unsigned long v;
if (!arch_get_random_long(&v))
break;
hash.l[i] = v;
}
/* Generate a hash across the pool, 16 words (512 bits) at a time */
spin_lock_irqsave(&r->lock, flags);
for (i = 0; i < r->poolinfo->poolwords; i += 16)
sha1_transform(hash.w, (__u8 *)(r->pool + i), workspace);
/*
* We mix the hash back into the pool to prevent backtracking
* attacks (where the attacker knows the state of the pool
* plus the current outputs, and attempts to find previous
* ouputs), unless the hash function can be inverted. By
* mixing at least a SHA1 worth of hash data back, we make
* brute-forcing the feedback as hard as brute-forcing the
* hash.
*/
__mix_pool_bytes(r, hash.w, sizeof(hash.w));
spin_unlock_irqrestore(&r->lock, flags);
memzero_explicit(workspace, sizeof(workspace));
/*
* In case the hash function has some recognizable output
* pattern, we fold it in half. Thus, we always feed back
* twice as much data as we output.
*/
hash.w[0] ^= hash.w[3];
hash.w[1] ^= hash.w[4];
hash.w[2] ^= rol32(hash.w[2], 16);
memcpy(out, &hash, EXTRACT_SIZE);
memzero_explicit(&hash, sizeof(hash));
}
static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int fips)
{
ssize_t ret = 0, i;
__u8 tmp[EXTRACT_SIZE];
unsigned long flags;
while (nbytes) {
extract_buf(r, tmp);
if (fips) {
spin_lock_irqsave(&r->lock, flags);
if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
panic("Hardware RNG duplicated output!\n");
memcpy(r->last_data, tmp, EXTRACT_SIZE);
spin_unlock_irqrestore(&r->lock, flags);
}
i = min_t(int, nbytes, EXTRACT_SIZE);
memcpy(buf, tmp, i);
nbytes -= i;
buf += i;
ret += i;
}
/* Wipe data just returned from memory */
memzero_explicit(tmp, sizeof(tmp));
return ret;
}
/*
* This function extracts randomness from the "entropy pool", and
* returns it in a buffer.
*
* The min parameter specifies the minimum amount we can pull before
* failing to avoid races that defeat catastrophic reseeding while the
* reserved parameter indicates how much entropy we must leave in the
* pool after each pull to avoid starving other readers.
*/
static ssize_t extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int min, int reserved)
{
__u8 tmp[EXTRACT_SIZE];
unsigned long flags;
/* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
if (fips_enabled) {
spin_lock_irqsave(&r->lock, flags);
if (!r->last_data_init) {
r->last_data_init = 1;
spin_unlock_irqrestore(&r->lock, flags);
trace_extract_entropy(r->name, EXTRACT_SIZE,
ENTROPY_BITS(r), _RET_IP_);
extract_buf(r, tmp);
spin_lock_irqsave(&r->lock, flags);
memcpy(r->last_data, tmp, EXTRACT_SIZE);
}
spin_unlock_irqrestore(&r->lock, flags);
}
trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
nbytes = account(r, nbytes, min, reserved);
return _extract_entropy(r, buf, nbytes, fips_enabled);
}
#define warn_unseeded_randomness(previous) \
_warn_unseeded_randomness(__func__, (void *) _RET_IP_, (previous))
static void _warn_unseeded_randomness(const char *func_name, void *caller,
void **previous)
{
#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
const bool print_once = false;
#else
static bool print_once __read_mostly;
#endif
if (print_once ||
crng_ready() ||
(previous && (caller == READ_ONCE(*previous))))
return;
WRITE_ONCE(*previous, caller);
#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
print_once = true;
#endif
if (__ratelimit(&unseeded_warning))
printk_deferred(KERN_NOTICE "random: %s called from %pS "
"with crng_init=%d\n", func_name, caller,
crng_init);
}
/*
* This function is the exported kernel interface. It returns some
* number of good random numbers, suitable for key generation, seeding
* TCP sequence numbers, etc. It does not rely on the hardware random
* number generator. For random bytes direct from the hardware RNG
* (when available), use get_random_bytes_arch(). In order to ensure
* that the randomness provided by this function is okay, the function
* wait_for_random_bytes() should be called and return 0 at least once
* at any point prior.
*/
static void _get_random_bytes(void *buf, int nbytes)
{
__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
trace_get_random_bytes(nbytes, _RET_IP_);
while (nbytes >= CHACHA_BLOCK_SIZE) {
extract_crng(buf);
buf += CHACHA_BLOCK_SIZE;
nbytes -= CHACHA_BLOCK_SIZE;
}
if (nbytes > 0) {
extract_crng(tmp);
memcpy(buf, tmp, nbytes);
crng_backtrack_protect(tmp, nbytes);
} else
crng_backtrack_protect(tmp, CHACHA_BLOCK_SIZE);
memzero_explicit(tmp, sizeof(tmp));
}
void get_random_bytes(void *buf, int nbytes)
{
static void *previous;
warn_unseeded_randomness(&previous);
_get_random_bytes(buf, nbytes);
}
EXPORT_SYMBOL(get_random_bytes);
/*
* Each time the timer fires, we expect that we got an unpredictable
* jump in the cycle counter. Even if the timer is running on another
* CPU, the timer activity will be touching the stack of the CPU that is
* generating entropy..
*
* Note that we don't re-arm the timer in the timer itself - we are
* happy to be scheduled away, since that just makes the load more
* complex, but we do not want the timer to keep ticking unless the
* entropy loop is running.
*
* So the re-arming always happens in the entropy loop itself.
*/
static void entropy_timer(struct timer_list *t)
{
credit_entropy_bits(&input_pool, 1);
}
/*
* If we have an actual cycle counter, see if we can
* generate enough entropy with timing noise
*/
static void try_to_generate_entropy(void)
{
struct {
unsigned long now;
struct timer_list timer;
} stack;
stack.now = random_get_entropy();
/* Slow counter - or none. Don't even bother */
if (stack.now == random_get_entropy())
return;
timer_setup_on_stack(&stack.timer, entropy_timer, 0);
while (!crng_ready()) {
if (!timer_pending(&stack.timer))
mod_timer(&stack.timer, jiffies+1);
mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
schedule();
stack.now = random_get_entropy();
}
del_timer_sync(&stack.timer);
destroy_timer_on_stack(&stack.timer);
mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
}
/*
* Wait for the urandom pool to be seeded and thus guaranteed to supply
* cryptographically secure random numbers. This applies to: the /dev/urandom
* device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
* family of functions. Using any of these functions without first calling
* this function forfeits the guarantee of security.
*
* Returns: 0 if the urandom pool has been seeded.
* -ERESTARTSYS if the function was interrupted by a signal.
*/
int wait_for_random_bytes(void)
{
if (likely(crng_ready()))
return 0;
do {
int ret;
ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
if (ret)
return ret > 0 ? 0 : ret;
try_to_generate_entropy();
} while (!crng_ready());
return 0;
}
EXPORT_SYMBOL(wait_for_random_bytes);
/*
* Returns whether or not the urandom pool has been seeded and thus guaranteed
* to supply cryptographically secure random numbers. This applies to: the
* /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
* ,u64,int,long} family of functions.
*
* Returns: true if the urandom pool has been seeded.
* false if the urandom pool has not been seeded.
*/
bool rng_is_initialized(void)
{
return crng_ready();
}
EXPORT_SYMBOL(rng_is_initialized);
/*
* Add a callback function that will be invoked when the nonblocking
* pool is initialised.
*
* returns: 0 if callback is successfully added
* -EALREADY if pool is already initialised (callback not called)
* -ENOENT if module for callback is not alive
*/
int add_random_ready_callback(struct random_ready_callback *rdy)
{
struct module *owner;
unsigned long flags;
int err = -EALREADY;
if (crng_ready())
return err;
owner = rdy->owner;
if (!try_module_get(owner))
return -ENOENT;
spin_lock_irqsave(&random_ready_list_lock, flags);
if (crng_ready())
goto out;
owner = NULL;
list_add(&rdy->list, &random_ready_list);
err = 0;
out:
spin_unlock_irqrestore(&random_ready_list_lock, flags);
module_put(owner);
return err;
}
EXPORT_SYMBOL(add_random_ready_callback);
/*
* Delete a previously registered readiness callback function.
*/
void del_random_ready_callback(struct random_ready_callback *rdy)
{
unsigned long flags;
struct module *owner = NULL;
spin_lock_irqsave(&random_ready_list_lock, flags);
if (!list_empty(&rdy->list)) {
list_del_init(&rdy->list);
owner = rdy->owner;
}
spin_unlock_irqrestore(&random_ready_list_lock, flags);
module_put(owner);
}
EXPORT_SYMBOL(del_random_ready_callback);
/*
* This function will use the architecture-specific hardware random
* number generator if it is available. The arch-specific hw RNG will
* almost certainly be faster than what we can do in software, but it
* is impossible to verify that it is implemented securely (as
* opposed, to, say, the AES encryption of a sequence number using a
* key known by the NSA). So it's useful if we need the speed, but
* only if we're willing to trust the hardware manufacturer not to
* have put in a back door.
*
* Return number of bytes filled in.
*/
int __must_check get_random_bytes_arch(void *buf, int nbytes)
{
int left = nbytes;
char *p = buf;
trace_get_random_bytes_arch(left, _RET_IP_);
while (left) {
unsigned long v;
int chunk = min_t(int, left, sizeof(unsigned long));
if (!arch_get_random_long(&v))
break;
memcpy(p, &v, chunk);
p += chunk;
left -= chunk;
}
return nbytes - left;
}
EXPORT_SYMBOL(get_random_bytes_arch);
/*
* init_std_data - initialize pool with system data
*
* @r: pool to initialize
*
* This function clears the pool's entropy count and mixes some system
* data into the pool to prepare it for use. The pool is not cleared
* as that can only decrease the entropy in the pool.
*/
static void __init init_std_data(struct entropy_store *r)
{
int i;
ktime_t now = ktime_get_real();
unsigned long rv;
mix_pool_bytes(r, &now, sizeof(now));
for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv))
rv = random_get_entropy();
mix_pool_bytes(r, &rv, sizeof(rv));
}
mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
}
/*
* Note that setup_arch() may call add_device_randomness()
* long before we get here. This allows seeding of the pools
* with some platform dependent data very early in the boot
* process. But it limits our options here. We must use
* statically allocated structures that already have all
* initializations complete at compile time. We should also
* take care not to overwrite the precious per platform data
* we were given.
*/
int __init rand_initialize(void)
{
init_std_data(&input_pool);
crng_initialize_primary(&primary_crng);
crng_global_init_time = jiffies;
if (ratelimit_disable) {
urandom_warning.interval = 0;
unseeded_warning.interval = 0;
}
return 0;
}
#ifdef CONFIG_BLOCK
void rand_initialize_disk(struct gendisk *disk)
{
struct timer_rand_state *state;
/*
* If kzalloc returns null, we just won't use that entropy
* source.
*/
state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
if (state) {
state->last_time = INITIAL_JIFFIES;
disk->random = state;
}
}
#endif
static ssize_t
urandom_read_nowarn(struct file *file, char __user *buf, size_t nbytes,
loff_t *ppos)
{
int ret;
nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
ret = extract_crng_user(buf, nbytes);
trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
return ret;
}
static ssize_t
urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
unsigned long flags;
static int maxwarn = 10;
if (!crng_ready() && maxwarn > 0) {
maxwarn--;
if (__ratelimit(&urandom_warning))
pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
current->comm, nbytes);
spin_lock_irqsave(&primary_crng.lock, flags);
crng_init_cnt = 0;
spin_unlock_irqrestore(&primary_crng.lock, flags);
}
return urandom_read_nowarn(file, buf, nbytes, ppos);
}
static ssize_t
random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
int ret;
ret = wait_for_random_bytes();
if (ret != 0)
return ret;
return urandom_read_nowarn(file, buf, nbytes, ppos);
}
static __poll_t
random_poll(struct file *file, poll_table * wait)
{
__poll_t mask;
poll_wait(file, &crng_init_wait, wait);
poll_wait(file, &random_write_wait, wait);
mask = 0;
if (crng_ready())
mask |= EPOLLIN | EPOLLRDNORM;
if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
mask |= EPOLLOUT | EPOLLWRNORM;
return mask;
}
static int
write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
{
size_t bytes;
__u32 t, buf[16];
const char __user *p = buffer;
while (count > 0) {
int b, i = 0;
bytes = min(count, sizeof(buf));
if (copy_from_user(&buf, p, bytes))
return -EFAULT;
for (b = bytes ; b > 0 ; b -= sizeof(__u32), i++) {
if (!arch_get_random_int(&t))
break;
buf[i] ^= t;
}
count -= bytes;
p += bytes;
mix_pool_bytes(r, buf, bytes);
cond_resched();
}
return 0;
}
static ssize_t random_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
size_t ret;
ret = write_pool(&input_pool, buffer, count);
if (ret)
return ret;
return (ssize_t)count;
}
static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
int size, ent_count;
int __user *p = (int __user *)arg;
int retval;
switch (cmd) {
case RNDGETENTCNT:
/* inherently racy, no point locking */
ent_count = ENTROPY_BITS(&input_pool);
if (put_user(ent_count, p))
return -EFAULT;
return 0;
case RNDADDTOENTCNT:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ent_count, p))
return -EFAULT;
return credit_entropy_bits_safe(&input_pool, ent_count);
case RNDADDENTROPY:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ent_count, p++))
return -EFAULT;
if (ent_count < 0)
return -EINVAL;
if (get_user(size, p++))
return -EFAULT;
retval = write_pool(&input_pool, (const char __user *)p,
size);
if (retval < 0)
return retval;
return credit_entropy_bits_safe(&input_pool, ent_count);
case RNDZAPENTCNT:
case RNDCLEARPOOL:
/*
* Clear the entropy pool counters. We no longer clear
* the entropy pool, as that's silly.
*/
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
input_pool.entropy_count = 0;
return 0;
case RNDRESEEDCRNG:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (crng_init < 2)
return -ENODATA;
crng_reseed(&primary_crng, NULL);
crng_global_init_time = jiffies - 1;
return 0;
default:
return -EINVAL;
}
}
static int random_fasync(int fd, struct file *filp, int on)
{
return fasync_helper(fd, filp, on, &fasync);
}
const struct file_operations random_fops = {
.read = random_read,
.write = random_write,
.poll = random_poll,
.unlocked_ioctl = random_ioctl,
.compat_ioctl = compat_ptr_ioctl,
.fasync = random_fasync,
.llseek = noop_llseek,
};
const struct file_operations urandom_fops = {
.read = urandom_read,
.write = random_write,
.unlocked_ioctl = random_ioctl,
.compat_ioctl = compat_ptr_ioctl,
.fasync = random_fasync,
.llseek = noop_llseek,
};
SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
unsigned int, flags)
{
int ret;
if (flags & ~(GRND_NONBLOCK|GRND_RANDOM|GRND_INSECURE))
return -EINVAL;
/*
* Requesting insecure and blocking randomness at the same time makes
* no sense.
*/
if ((flags & (GRND_INSECURE|GRND_RANDOM)) == (GRND_INSECURE|GRND_RANDOM))
return -EINVAL;
if (count > INT_MAX)
count = INT_MAX;
if (!(flags & GRND_INSECURE) && !crng_ready()) {
if (flags & GRND_NONBLOCK)
return -EAGAIN;
ret = wait_for_random_bytes();
if (unlikely(ret))
return ret;
}
return urandom_read_nowarn(NULL, buf, count, NULL);
}
/********************************************************************
*
* Sysctl interface
*
********************************************************************/
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
static int min_write_thresh;
static int max_write_thresh = INPUT_POOL_WORDS * 32;
static int random_min_urandom_seed = 60;
static char sysctl_bootid[16];
/*
* This function is used to return both the bootid UUID, and random
* UUID. The difference is in whether table->data is NULL; if it is,
* then a new UUID is generated and returned to the user.
*
* If the user accesses this via the proc interface, the UUID will be
* returned as an ASCII string in the standard UUID format; if via the
* sysctl system call, as 16 bytes of binary data.
*/
static int proc_do_uuid(struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table fake_table;
unsigned char buf[64], tmp_uuid[16], *uuid;
uuid = table->data;
if (!uuid) {
uuid = tmp_uuid;
generate_random_uuid(uuid);
} else {
static DEFINE_SPINLOCK(bootid_spinlock);
spin_lock(&bootid_spinlock);
if (!uuid[8])
generate_random_uuid(uuid);
spin_unlock(&bootid_spinlock);
}
sprintf(buf, "%pU", uuid);
fake_table.data = buf;
fake_table.maxlen = sizeof(buf);
return proc_dostring(&fake_table, write, buffer, lenp, ppos);
}
/*
* Return entropy available scaled to integral bits
*/
static int proc_do_entropy(struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table fake_table;
int entropy_count;
entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
fake_table.data = &entropy_count;
fake_table.maxlen = sizeof(entropy_count);
return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
}
static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
extern struct ctl_table random_table[];
struct ctl_table random_table[] = {
{
.procname = "poolsize",
.data = &sysctl_poolsize,
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_dointvec,
},
{
.procname = "entropy_avail",
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_do_entropy,
.data = &input_pool.entropy_count,
},
{
.procname = "write_wakeup_threshold",
.data = &random_write_wakeup_bits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_write_thresh,
.extra2 = &max_write_thresh,
},
{
.procname = "urandom_min_reseed_secs",
.data = &random_min_urandom_seed,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "boot_id",
.data = &sysctl_bootid,
.maxlen = 16,
.mode = 0444,
.proc_handler = proc_do_uuid,
},
{
.procname = "uuid",
.maxlen = 16,
.mode = 0444,
.proc_handler = proc_do_uuid,
},
#ifdef ADD_INTERRUPT_BENCH
{
.procname = "add_interrupt_avg_cycles",
.data = &avg_cycles,
.maxlen = sizeof(avg_cycles),
.mode = 0444,
.proc_handler = proc_doulongvec_minmax,
},
{
.procname = "add_interrupt_avg_deviation",
.data = &avg_deviation,
.maxlen = sizeof(avg_deviation),
.mode = 0444,
.proc_handler = proc_doulongvec_minmax,
},
#endif
{ }
};
#endif /* CONFIG_SYSCTL */
struct batched_entropy {
union {
u64 entropy_u64[CHACHA_BLOCK_SIZE / sizeof(u64)];
u32 entropy_u32[CHACHA_BLOCK_SIZE / sizeof(u32)];
};
unsigned int position;
spinlock_t batch_lock;
};
/*
* Get a random word for internal kernel use only. The quality of the random
* number is good as /dev/urandom, but there is no backtrack protection, with
* the goal of being quite fast and not depleting entropy. In order to ensure
* that the randomness provided by this function is okay, the function
* wait_for_random_bytes() should be called and return 0 at least once at any
* point prior.
*/
static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
.batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u64.lock),
};
u64 get_random_u64(void)
{
u64 ret;
unsigned long flags;
struct batched_entropy *batch;
static void *previous;
warn_unseeded_randomness(&previous);
batch = raw_cpu_ptr(&batched_entropy_u64);
spin_lock_irqsave(&batch->batch_lock, flags);
if (batch->position % ARRAY_SIZE(batch->entropy_u64) == 0) {
extract_crng((u8 *)batch->entropy_u64);
batch->position = 0;
}
ret = batch->entropy_u64[batch->position++];
spin_unlock_irqrestore(&batch->batch_lock, flags);
return ret;
}
EXPORT_SYMBOL(get_random_u64);
static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
.batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u32.lock),
};
u32 get_random_u32(void)
{
u32 ret;
unsigned long flags;
struct batched_entropy *batch;
static void *previous;
warn_unseeded_randomness(&previous);
batch = raw_cpu_ptr(&batched_entropy_u32);
spin_lock_irqsave(&batch->batch_lock, flags);
if (batch->position % ARRAY_SIZE(batch->entropy_u32) == 0) {
extract_crng((u8 *)batch->entropy_u32);
batch->position = 0;
}
ret = batch->entropy_u32[batch->position++];
spin_unlock_irqrestore(&batch->batch_lock, flags);
return ret;
}
EXPORT_SYMBOL(get_random_u32);
/* It's important to invalidate all potential batched entropy that might
* be stored before the crng is initialized, which we can do lazily by
* simply resetting the counter to zero so that it's re-extracted on the
* next usage. */
static void invalidate_batched_entropy(void)
{
int cpu;
unsigned long flags;
for_each_possible_cpu (cpu) {
struct batched_entropy *batched_entropy;
batched_entropy = per_cpu_ptr(&batched_entropy_u32, cpu);
spin_lock_irqsave(&batched_entropy->batch_lock, flags);
batched_entropy->position = 0;
spin_unlock(&batched_entropy->batch_lock);
batched_entropy = per_cpu_ptr(&batched_entropy_u64, cpu);
spin_lock(&batched_entropy->batch_lock);
batched_entropy->position = 0;
spin_unlock_irqrestore(&batched_entropy->batch_lock, flags);
}
}
/**
* randomize_page - Generate a random, page aligned address
* @start: The smallest acceptable address the caller will take.
* @range: The size of the area, starting at @start, within which the
* random address must fall.
*
* If @start + @range would overflow, @range is capped.
*
* NOTE: Historical use of randomize_range, which this replaces, presumed that
* @start was already page aligned. We now align it regardless.
*
* Return: A page aligned address within [start, start + range). On error,
* @start is returned.
*/
unsigned long
randomize_page(unsigned long start, unsigned long range)
{
if (!PAGE_ALIGNED(start)) {
range -= PAGE_ALIGN(start) - start;
start = PAGE_ALIGN(start);
}
if (start > ULONG_MAX - range)
range = ULONG_MAX - start;
range >>= PAGE_SHIFT;
if (range == 0)
return start;
return start + (get_random_long() % range << PAGE_SHIFT);
}
/* Interface for in-kernel drivers of true hardware RNGs.
* Those devices may produce endless random bits and will be throttled
* when our pool is full.
*/
void add_hwgenerator_randomness(const char *buffer, size_t count,
size_t entropy)
{
struct entropy_store *poolp = &input_pool;
if (unlikely(crng_init == 0)) {
crng_fast_load(buffer, count);
return;
}
/* Suspend writing if we're above the trickle threshold.
* We'll be woken up again once below random_write_wakeup_thresh,
* or when the calling thread is about to terminate.
*/
wait_event_interruptible(random_write_wait, kthread_should_stop() ||
ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
mix_pool_bytes(poolp, buffer, count);
credit_entropy_bits(poolp, entropy);
}
EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
/* Handle random seed passed by bootloader.
* If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
* it would be regarded as device data.
* The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
*/
void add_bootloader_randomness(const void *buf, unsigned int size)
{
if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
add_hwgenerator_randomness(buf, size, size * 8);
else
add_device_randomness(buf, size);
}
EXPORT_SYMBOL_GPL(add_bootloader_randomness);
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_4240_0 |
crossvul-cpp_data_bad_3568_4 | /**
* Copyright 2008-2011 Digital Bazaar, Inc.
*
* This file is part of librdfa.
*
* librdfa is Free Software, and can be licensed under any of the
* following three licenses:
*
* 1. GNU Lesser General Public License (LGPL) V2.1 or any
* newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE-* at the top of this software distribution for more
* information regarding the details of each license.
*
* The librdfa library is the Fastest RDFa Parser in the Universe. It is
* a stream parser, meaning that it takes an XML data as input and spits
* out RDF triples as it comes across them in the stream. Due to this
* processing approach, librdfa has a very, very small memory footprint.
* It is also very fast and can operate on hundreds of gigabytes of XML
* data without breaking a sweat.
*
* Usage:
*
* rdfacontext* context = rdfa_create_context(BASE_URI);
* context->callback_data = your_user_data;
* rdfa_set_default_graph_triple_handler(context, &default_graph_triple);
* rdfa_set_processor_graph_triple_handler(context, &processor_graph_triple);
* rdfa_set_buffer_filler(context, &fill_buffer);
* rdfa_parse(context);
* rdfa_free_context(context);
*
* @author Manu Sporny
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "rdfa_utils.h"
#include "rdfa.h"
#define READ_BUFFER_SIZE 4096
#define RDFA_DOCTYPE_STRING_LENGTH 103
void rdfa_init_context(rdfacontext* context)
{
// the [parent subject] is set to the [base] value;
context->parent_subject = NULL;
if(context->base != NULL)
{
char* cleaned_base = rdfa_iri_get_base(context->base);
context->parent_subject =
rdfa_replace_string(context->parent_subject, cleaned_base);
free(cleaned_base);
}
// the [parent object] is set to null;
context->parent_object = NULL;
#ifndef LIBRDFA_IN_RAPTOR
// the [list of URI mappings] is cleared;
context->uri_mappings = (char**)rdfa_create_mapping(MAX_URI_MAPPINGS);
#endif
// the [list of incomplete triples] is cleared;
context->incomplete_triples = rdfa_create_list(3);
// the [language] is set to null.
context->language = NULL;
// set the [current object resource] to null;
context->current_object_resource = NULL;
// 1. First, the local values are initialized, as follows:
//
// * the [recurse] flag is set to 'true';
context->recurse = 1;
// * the [skip element] flag is set to 'false';
context->skip_element = 0;
// * [new subject] is set to null;
context->new_subject = NULL;
// * [current object resource] is set to null;
context->current_object_resource = NULL;
// * the [local list of URI mappings] is set to the list of URI
// mappings from the [evaluation context];
// NOTE: This step is done in rdfa_create_new_element_context()
// * the [local list of incomplete triples] is set to null;
context->local_incomplete_triples = rdfa_create_list(3);
// * the [current language] value is set to the [language] value
// from the [evaluation context].
// NOTE: This step is done in rdfa_create_new_element_context()
// The next set of variables are initialized to make the C compiler
// and valgrind happy - they are not a part of the RDFa spec.
context->bnode_count = 0;
context->underscore_colon_bnode_name = NULL;
context->xml_literal_namespaces_defined = 0;
context->xml_literal_xml_lang_defined = 0;
context->content = NULL;
context->datatype = NULL;
context->property = NULL;
context->plain_literal = NULL;
context->plain_literal_size = 0;
context->xml_literal = NULL;
context->xml_literal_size = 0;
// FIXME: completing incomplete triples always happens now, change
// all of the code to reflect that.
//context->callback_data = NULL;
}
/**
* Read the head of the XHTML document and determines the base IRI for
* the document.
*
* @param context the current working context.
* @param working_buffer the current working buffer.
* @param wb_allocated the number of bytes that have been allocated to
* the working buffer.
*
* @return the size of the data available in the working buffer.
*/
static size_t rdfa_init_base(
rdfacontext* context, char** working_buffer, size_t* working_buffer_size,
char* temp_buffer, size_t bytes_read)
{
char* head_end = NULL;
size_t offset = context->wb_position;
size_t needed_size = (offset + bytes_read) - *working_buffer_size;
// search for the end of <head>, stop if <head> was found
// extend the working buffer size
if(needed_size > 0)
{
size_t temp_buffer_size = sizeof(char) * READ_BUFFER_SIZE;
if((size_t)needed_size > temp_buffer_size)
temp_buffer_size += needed_size;
*working_buffer_size += temp_buffer_size;
// +1 for NUL at end, to allow strstr() etc. to work
*working_buffer = (char*)realloc(*working_buffer, *working_buffer_size + 1);
}
// append to the working buffer
memmove(*working_buffer + offset, temp_buffer, bytes_read);
// ensure the buffer is a NUL-terminated string
*(*working_buffer + offset + bytes_read) = '\0';
// search for the end of </head> in
head_end = strstr(*working_buffer, "</head>");
if(head_end == NULL)
head_end = strstr(*working_buffer, "</HEAD>");
context->wb_position += bytes_read;
if(head_end == NULL)
return bytes_read;
// if </head> was found, search for <base and extract the base URI
if(head_end != NULL)
{
char* base_start = strstr(*working_buffer, "<base ");
if(base_start == NULL)
base_start = strstr(*working_buffer, "<BASE ");
if(base_start != NULL)
{
char* href_start = strstr(base_start, "href=");
char sep = href_start[5];
char* uri_start = href_start + 6;
char* uri_end = strchr(uri_start, sep);
if((uri_start != NULL) && (uri_end != NULL))
{
if(*uri_start != sep)
{
size_t uri_size = uri_end - uri_start;
char* temp_uri = (char*)malloc(sizeof(char) * uri_size + 1);
char* cleaned_base;
strncpy(temp_uri, uri_start, uri_size);
temp_uri[uri_size] = '\0';
// TODO: This isn't in the processing rules, should it
// be? Setting current_object_resource will make
// sure that the BASE element is inherited by all
// subcontexts.
cleaned_base = rdfa_iri_get_base(temp_uri);
context->current_object_resource =
rdfa_replace_string(
context->current_object_resource, cleaned_base);
// clean up the base context
context->base =
rdfa_replace_string(context->base, cleaned_base);
free(cleaned_base);
free(temp_uri);
}
}
}
}
return bytes_read;
}
/**
* Creates a new context for the current element by cloning certain
* parts of the old context on the top of the given stack.
*
* @param context_stack the context stack that is associated with this
* processing run.
*/
static rdfacontext* rdfa_create_new_element_context(rdfalist* context_stack)
{
rdfacontext* parent_context = (rdfacontext*)
context_stack->items[context_stack->num_items - 1]->data;
rdfacontext* rval = rdfa_create_context(parent_context->base);
// * Otherwise, the values are:
// * the [ base ] is set to the [ base ] value of the current
// [ evaluation context ];
rval->base = rdfa_replace_string(rval->base, parent_context->base);
rdfa_init_context(rval);
// copy the URI mappings
#ifndef LIBRDFA_IN_RAPTOR
rdfa_free_mapping(rval->uri_mappings);
rval->uri_mappings = rdfa_copy_mapping(parent_context->uri_mappings);
#endif
// inherit the parent context's language
if(parent_context->language != NULL)
{
rval->language =
rdfa_replace_string(rval->language, parent_context->language);
}
// set the callbacks callback
rval->default_graph_triple_callback =
parent_context->default_graph_triple_callback;
rval->processor_graph_triple_callback =
parent_context->processor_graph_triple_callback;
rval->buffer_filler_callback = parent_context->buffer_filler_callback;
// inherit the bnode count, _: bnode name, recurse flag, and state
// of the xml_literal_namespace_insertion
rval->bnode_count = parent_context->bnode_count;
rval->underscore_colon_bnode_name =
rdfa_replace_string(rval->underscore_colon_bnode_name,
parent_context->underscore_colon_bnode_name);
rval->recurse = parent_context->recurse;
rval->skip_element = 0;
rval->callback_data = parent_context->callback_data;
rval->xml_literal_namespaces_defined =
parent_context->xml_literal_namespaces_defined;
rval->xml_literal_xml_lang_defined =
parent_context->xml_literal_xml_lang_defined;
// inherit the parent context's new_subject
// TODO: This is not anywhere in the syntax processing document
//if(parent_context->new_subject != NULL)
//{
// rval->new_subject = rdfa_replace_string(
// rval->new_subject, parent_context->new_subject);
//}
if(parent_context->skip_element == 0)
{
// o the [ parent subject ] is set to the value of [ new subject ],
// if non-null, or the value of the [ parent subject ] of the
// current [ evaluation context ];
if(parent_context->new_subject != NULL)
{
rval->parent_subject = rdfa_replace_string(
rval->parent_subject, parent_context->new_subject);
}
else
{
rval->parent_subject = rdfa_replace_string(
rval->parent_subject, parent_context->parent_subject);
}
// o the [ parent object ] is set to value of [ current object
// resource ], if non-null, or the value of [ new subject ], if
// non-null, or the value of the [ parent subject ] of the
// current [ evaluation context ];
if(parent_context->current_object_resource != NULL)
{
rval->parent_object =
rdfa_replace_string(
rval->parent_object, parent_context->current_object_resource);
}
else if(parent_context->new_subject != NULL)
{
rval->parent_object =
rdfa_replace_string(
rval->parent_object, parent_context->new_subject);
}
else
{
rval->parent_object =
rdfa_replace_string(
rval->parent_object, parent_context->parent_subject);
}
// copy the incomplete triples
if(rval->incomplete_triples != NULL)
{
rdfa_free_list(rval->incomplete_triples);
}
// o the [ list of incomplete triples ] is set to the [ local list
// of incomplete triples ];
rval->incomplete_triples =
rdfa_copy_list(parent_context->local_incomplete_triples);
}
else
{
rval->parent_subject = rdfa_replace_string(
rval->parent_subject, parent_context->parent_subject);
rval->parent_object = rdfa_replace_string(
rval->parent_object, parent_context->parent_object);
// copy the incomplete triples
rdfa_free_list(rval->incomplete_triples);
rval->incomplete_triples =
rdfa_copy_list(parent_context->incomplete_triples);
// copy the local list of incomplete triples
rdfa_free_list(rval->local_incomplete_triples);
rval->local_incomplete_triples =
rdfa_copy_list(parent_context->local_incomplete_triples);
}
#ifdef LIBRDFA_IN_RAPTOR
rval->base_uri = parent_context->base_uri;
rval->sax2 = parent_context->sax2;
rval->namespace_handler = parent_context->namespace_handler;
rval->namespace_handler_user_data = parent_context->namespace_handler_user_data;
#endif
return rval;
}
#ifdef LIBRDFA_IN_RAPTOR
static int
raptor_nspace_compare(const void *a, const void *b)
{
raptor_namespace* ns_a=*(raptor_namespace**)a;
raptor_namespace* ns_b=*(raptor_namespace**)b;
if(!ns_a->prefix)
return 1;
else if(!ns_b->prefix)
return -1;
else
return strcmp((const char*)ns_b->prefix, (const char*)ns_a->prefix);
}
#endif
/**
* Handles the start_element call
*/
static void XMLCALL
start_element(void* user_data, const char* name, const char** attributes)
{
rdfalist* context_stack = (rdfalist*) user_data;
rdfacontext* context = rdfa_create_new_element_context(context_stack);
const char** aptr = attributes;
const char* xml_lang = NULL;
const char* about_curie = NULL;
char* about = NULL;
const char* src_curie = NULL;
char* src = NULL;
const char* type_of_curie = NULL;
rdfalist* type_of = NULL;
const char* rel_curie = NULL;
rdfalist* rel = NULL;
const char* rev_curie = NULL;
rdfalist* rev = NULL;
const char* property_curie = NULL;
rdfalist* property = NULL;
const char* resource_curie = NULL;
char* resource = NULL;
const char* href_curie = NULL;
char* href = NULL;
const char* content = NULL;
const char* datatype_curie = NULL;
char* datatype = NULL;
rdfa_push_item(context_stack, context, RDFALIST_FLAG_CONTEXT);
if(DEBUG)
{
printf("DEBUG: ------- START - %s -------\n", name);
}
// start the XML Literal text
if(context->xml_literal == NULL)
{
context->xml_literal = rdfa_replace_string(context->xml_literal, "<");
context->xml_literal_size = 1;
}
else
{
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, "<", 1);
}
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
name, strlen(name));
if(!context->xml_literal_namespaces_defined)
{
// append namespaces to XML Literal
#ifdef LIBRDFA_IN_RAPTOR
raptor_namespace_stack* nstack = &context->sax2->namespaces;
raptor_namespace* ns;
raptor_namespace** ns_list = NULL;
size_t ns_size;
#else
char** umap = context->uri_mappings;
#endif
char* umap_key = NULL;
char* umap_value = NULL;
// if the namespaces are not defined, then neither is the xml:lang
context->xml_literal_xml_lang_defined = 0;
#ifdef LIBRDFA_IN_RAPTOR
ns_size = 0;
ns_list = raptor_namespace_stack_to_array(nstack, &ns_size);
qsort((void*)ns_list, ns_size, sizeof(raptor_namespace*),
raptor_nspace_compare);
while(ns_size > 0)
#else
while(*umap != NULL)
#endif
{
unsigned char insert_xmlns_definition = 1;
const char* attr = NULL;
// get the next mapping to process
#ifdef LIBRDFA_IN_RAPTOR
ns=ns_list[--ns_size];
umap_key = (char*)raptor_namespace_get_prefix(ns);
if(!umap_key)
umap_key=(char*)XMLNS_DEFAULT_MAPPING;
umap_value = (char*)raptor_uri_as_string(raptor_namespace_get_uri(ns));
#else
rdfa_next_mapping(umap++, &umap_key, &umap_value);
umap++;
#endif
// check to make sure that the namespace isn't already
// defined in the current element.
if(attributes != NULL)
{
const char** attrs = attributes;
while((*attrs != NULL) && insert_xmlns_definition)
{
attr = *attrs++;
// if the attribute is a umap_key, skip the definition
// of the attribute.
if((strcmp(attr, umap_key) == 0) ||
(strcmp(umap_key, XMLNS_DEFAULT_MAPPING) == 0))
{
insert_xmlns_definition = 0;
}
}
}
// if the namespace isn't already defined on the element,
// copy it to the XML Literal string.
if(insert_xmlns_definition)
{
// append the namespace attribute to the XML Literal
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
" xmlns", strlen(" xmlns"));
// check to see if we're dumping the standard XHTML namespace or
// a user-defined XML namespace
if(strcmp(umap_key, XMLNS_DEFAULT_MAPPING) != 0)
{
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, ":", 1);
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
umap_key, strlen(umap_key));
}
// append the namespace value
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, "=\"", 2);
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
umap_value, strlen(umap_value));
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, "\"", 1);
}
} /* end while umap not NULL */
context->xml_literal_namespaces_defined = 1;
#ifdef LIBRDFA_IN_RAPTOR
if(ns_list)
raptor_free_memory(ns_list);
#endif
} /* end if namespaces inserted */
// prepare all of the RDFa-specific attributes we are looking for.
// scan all of the attributes for the RDFa-specific attributes
if(aptr != NULL)
{
while(*aptr != NULL)
{
const char* attr;
const char* value;
char* literal_text;
attr = *aptr++;
value = *aptr++;
// append the attribute-value pair to the XML literal
literal_text = (char*)malloc(strlen(attr) + strlen(value) + 5);
sprintf(literal_text, " %s=\"%s\"", attr, value);
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
literal_text, strlen(literal_text));
free(literal_text);
// if xml:lang is defined, ensure that it is not overwritten
if(strcmp(attr, "xml:lang") == 0)
{
context->xml_literal_xml_lang_defined = 1;
}
// process all of the RDFa attributes
if(strcmp(attr, "about") == 0)
{
about_curie = value;
about = rdfa_resolve_curie(
context, about_curie, CURIE_PARSE_ABOUT_RESOURCE);
}
else if(strcmp(attr, "src") == 0)
{
src_curie = value;
src = rdfa_resolve_curie(context, src_curie, CURIE_PARSE_HREF_SRC);
}
else if(strcmp(attr, "typeof") == 0)
{
type_of_curie = value;
type_of = rdfa_resolve_curie_list(
context, type_of_curie,
CURIE_PARSE_INSTANCEOF_DATATYPE);
}
else if(strcmp(attr, "rel") == 0)
{
rel_curie = value;
rel = rdfa_resolve_curie_list(
context, rel_curie, CURIE_PARSE_RELREV);
}
else if(strcmp(attr, "rev") == 0)
{
rev_curie = value;
rev = rdfa_resolve_curie_list(
context, rev_curie, CURIE_PARSE_RELREV);
}
else if(strcmp(attr, "property") == 0)
{
property_curie = value;
property =
rdfa_resolve_curie_list(
context, property_curie, CURIE_PARSE_PROPERTY);
}
else if(strcmp(attr, "resource") == 0)
{
resource_curie = value;
resource = rdfa_resolve_curie(
context, resource_curie, CURIE_PARSE_ABOUT_RESOURCE);
}
else if(strcmp(attr, "href") == 0)
{
href_curie = value;
href =
rdfa_resolve_curie(context, href_curie, CURIE_PARSE_HREF_SRC);
}
else if(strcmp(attr, "content") == 0)
{
content = value;
}
else if(strcmp(attr, "datatype") == 0)
{
datatype_curie = value;
if(strlen(datatype_curie) == 0)
{
datatype = rdfa_replace_string(datatype, "");
}
else
{
datatype = rdfa_resolve_curie(context, datatype_curie,
CURIE_PARSE_INSTANCEOF_DATATYPE);
}
}
#ifndef LIBRDFA_IN_RAPTOR
else if(strcmp(attr, "xml:lang") == 0)
{
xml_lang = value;
}
else if(strstr(attr, "xmlns") != NULL)
{
// 2. Next the [current element] is parsed for
// [URI mapping]s and these are added to the
// [local list of URI mappings]. Note that a
// [URI mapping] will simply overwrite any current
// mapping in the list that has the same name;
rdfa_update_uri_mappings(context, attr, value);
}
#endif
}
}
#ifdef LIBRDFA_IN_RAPTOR
if(context->sax2) {
xml_lang = (const char*)raptor_sax2_inscope_xml_language(context->sax2);
if(!xml_lang)
xml_lang = "";
}
#endif
// check to see if we should append an xml:lang to the XML Literal
// if one is defined in the context and does not exist on the
// element.
if((xml_lang == NULL) && (context->language != NULL) &&
!context->xml_literal_xml_lang_defined)
{
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
" xml:lang=\"", strlen(" xml:lang=\""));
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
context->language, strlen(context->language));
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, "\"", 1);
// ensure that the lang isn't set in a subtree (unless it's overwritten)
context->xml_literal_xml_lang_defined = 1;
}
// close the XML Literal value
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, ">", 1);
// 3. The [current element] is also parsed for any language
// information, and [language] is set in the [current
// evaluation context];
rdfa_update_language(context, xml_lang);
/***************** FOR DEBUGGING PURPOSES ONLY ******************/
if(DEBUG)
{
if(about != NULL)
{
printf("DEBUG: @about = %s\n", about);
}
if(src != NULL)
{
printf("DEBUG: @src = %s\n", src);
}
if(type_of != NULL)
{
printf("DEBUG: @type_of = ");
rdfa_print_list(type_of);
}
if(rel != NULL)
{
printf("DEBUG: @rel = ");
rdfa_print_list(rel);
}
if(rev != NULL)
{
printf("DEBUG: @rev = ");
rdfa_print_list(rev);
}
if(property != NULL)
{
printf("DEBUG: @property = ");
rdfa_print_list(property);
}
if(resource != NULL)
{
printf("DEBUG: @resource = %s\n", resource);
}
if(href != NULL)
{
printf("DEBUG: @href = %s\n", href);
}
if(content != NULL)
{
printf("DEBUG: @content = %s\n", content);
}
if(datatype != NULL)
{
printf("DEBUG: @datatype = %s\n", datatype);
}
}
// TODO: This isn't part of the processing model, it needs to be
// included and is a correction for the last item in step #4.
if((about == NULL) && (src == NULL) && (type_of == NULL) &&
(rel == NULL) && (rev == NULL) && (property == NULL) &&
(resource == NULL) && (href == NULL))
{
context->skip_element = 1;
}
if((rel == NULL) && (rev == NULL))
{
// 4. If the [current element] contains no valid @rel or @rev
// URI, obtained according to the section on CURIE and URI
// Processing, then the next step is to establish a value for
// [new subject]. Any of the attributes that can carry a
// resource can set [new subject];
rdfa_establish_new_subject(
context, name, about, src, resource, href, type_of);
}
else
{
// 5. If the [current element] does contain a valid @rel or @rev
// URI, obtained according to the section on CURIE and URI
// Processing, then the next step is to establish both a value
// for [new subject] and a value for [current object resource]:
rdfa_establish_new_subject_with_relrev(
context, name, about, src, resource, href, type_of);
}
if(context->new_subject != NULL)
{
if(DEBUG)
{
printf("DEBUG: new_subject = %s\n", context->new_subject);
}
// 6. If in any of the previous steps a [new subject] was set to
// a non-null value,
// it is now used to provide a subject for type values;
if(type_of != NULL)
{
rdfa_complete_type_triples(context, type_of);
}
// Note that none of this block is executed if there is no
// [new subject] value, i.e., [new subject] remains null.
}
if(context->current_object_resource != NULL)
{
// 7. If in any of the previous steps a [current object resource]
// was set to a non-null value, it is now used to generate triples
rdfa_complete_relrev_triples(context, rel, rev);
}
else if((rel != NULL) || (rev != NULL))
{
// 8. If however [current object resource] was set to null, but
// there are predicates present, then they must be stored as
// [incomplete triple]s, pending the discovery of a subject that
// can be used as the object. Also, [current object resource]
// should be set to a newly created [bnode]
rdfa_save_incomplete_triples(context, rel, rev);
}
// Ensure to re-insert XML Literal namespace information from this
// point on...
if(property != NULL)
{
context->xml_literal_namespaces_defined = 0;
}
// save these for processing steps #9 and #10
context->property = property;
context->content = rdfa_replace_string(context->datatype, content);
context->datatype = rdfa_replace_string(context->datatype, datatype);
// free the resolved CURIEs
free(about);
free(src);
rdfa_free_list(type_of);
rdfa_free_list(rel);
rdfa_free_list(rev);
free(resource);
free(href);
free(datatype);
}
static void XMLCALL character_data(void *user_data, const char *s, int len)
{
rdfalist* context_stack = (rdfalist*)user_data;
rdfacontext* context = (rdfacontext*)
context_stack->items[context_stack->num_items - 1]->data;
char *buffer = (char*)malloc(len + 1);
memset(buffer, 0, len + 1);
memcpy(buffer, s, len);
// append the text to the current context's plain literal
if(context->plain_literal == NULL)
{
context->plain_literal =
rdfa_replace_string(context->plain_literal, buffer);
context->plain_literal_size = len;
}
else
{
context->plain_literal = rdfa_n_append_string(
context->plain_literal, &context->plain_literal_size, buffer, len);
}
// append the text to the current context's XML literal
if(context->xml_literal == NULL)
{
context->xml_literal =
rdfa_replace_string(context->xml_literal, buffer);
context->xml_literal_size = len;
}
else
{
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size, buffer, len);
}
//printf("plain_literal: %s\n", context->plain_literal);
//printf("xml_literal: %s\n", context->xml_literal);
free(buffer);
}
static void XMLCALL
end_element(void *user_data, const char *name)
{
rdfalist* context_stack = (rdfalist*)user_data;
rdfacontext* context = (rdfacontext*)rdfa_pop_item(context_stack);
rdfacontext* parent_context = (rdfacontext*)
context_stack->items[context_stack->num_items - 1]->data;
// append the text to the current context's XML literal
char* buffer = (char*)malloc(strlen(name) + 4);
if(DEBUG)
{
printf("DEBUG: </%s>\n", name);
}
sprintf(buffer, "</%s>", name);
if(context->xml_literal == NULL)
{
context->xml_literal =
rdfa_replace_string(context->xml_literal, buffer);
context->xml_literal_size = strlen(buffer);
}
else
{
context->xml_literal = rdfa_n_append_string(
context->xml_literal, &context->xml_literal_size,
buffer, strlen(buffer));
}
free(buffer);
// 9. The next step of the iteration is to establish any
// [current object literal];
// generate the complete object literal triples
if(context->property != NULL)
{
// save the current xml literal
char* saved_xml_literal = context->xml_literal;
char* content_start = NULL;
char* content_end = NULL;
// ensure to mark only the inner-content of the XML node for
// processing the object literal.
buffer = NULL;
if(context->xml_literal != NULL)
{
// get the data between the first tag and the last tag
content_start = strchr(context->xml_literal, '>');
content_end = strrchr(context->xml_literal, '<');
if((content_start != NULL) && (content_end != NULL))
{
// set content end to null terminator
context->xml_literal = ++content_start;
*content_end = '\0';
}
}
// update the plain literal if the XML Literal is an empty string
if(strlen(context->xml_literal) == 0)
{
context->plain_literal =
rdfa_replace_string(context->plain_literal, "");
}
// process data between first tag and last tag
// this needs the xml literal to be null terminated
rdfa_complete_object_literal_triples(context);
if(content_end != NULL)
{
// set content end back
*content_end = '<';
}
if(saved_xml_literal != NULL)
{
// restore xml literal
context->xml_literal = saved_xml_literal;
}
}
//printf(context->plain_literal);
// append the XML literal and plain text literals to the parent
// literals
if(context->xml_literal != NULL)
{
if(parent_context->xml_literal == NULL)
{
parent_context->xml_literal =
rdfa_replace_string(
parent_context->xml_literal, context->xml_literal);
parent_context->xml_literal_size = context->xml_literal_size;
}
else
{
parent_context->xml_literal =
rdfa_n_append_string(
parent_context->xml_literal, &parent_context->xml_literal_size,
context->xml_literal, context->xml_literal_size);
}
// if there is an XML literal, there is probably a plain literal
if(context->plain_literal != NULL)
{
if(parent_context->plain_literal == NULL)
{
parent_context->plain_literal =
rdfa_replace_string(
parent_context->plain_literal, context->plain_literal);
parent_context->plain_literal_size = context->plain_literal_size;
}
else
{
parent_context->plain_literal =
rdfa_n_append_string(
parent_context->plain_literal,
&parent_context->plain_literal_size,
context->plain_literal,
context->plain_literal_size);
}
}
}
// preserve the bnode count by copying it to the parent_context
parent_context->bnode_count = context->bnode_count;
parent_context->underscore_colon_bnode_name = \
rdfa_replace_string(parent_context->underscore_colon_bnode_name,
context->underscore_colon_bnode_name);
// 10. If the [ skip element ] flag is 'false', and [ new subject ]
// was set to a non-null value, then any [ incomplete triple ]s
// within the current context should be completed:
if((context->skip_element == 0) && (context->new_subject != NULL))
{
rdfa_complete_incomplete_triples(context);
}
// free the context
rdfa_free_context(context);
}
#ifdef LIBRDFA_IN_RAPTOR
static void raptor_rdfa_start_element(void *user_data,
raptor_xml_element *xml_element)
{
raptor_qname* qname=raptor_xml_element_get_name(xml_element);
int attr_count=raptor_xml_element_get_attributes_count(xml_element);
raptor_qname** attrs=raptor_xml_element_get_attributes(xml_element);
unsigned char* qname_string=raptor_qname_to_counted_name(qname, NULL);
char** attr=NULL;
int i;
if(attr_count > 0) {
attr=(char**)malloc(sizeof(char*) * (1+(attr_count*2)));
for(i=0; i<attr_count; i++) {
attr[2*i]=(char*)raptor_qname_to_counted_name(attrs[i], NULL);
attr[1+(2*i)]=(char*)raptor_qname_get_value(attrs[i]);
}
attr[2*i]=NULL;
}
start_element(user_data, (char*)qname_string, (const char**)attr);
raptor_free_memory(qname_string);
if(attr) {
for(i=0; i<attr_count; i++)
raptor_free_memory(attr[2*i]);
free(attr);
}
}
static void raptor_rdfa_end_element(void *user_data,
raptor_xml_element* xml_element)
{
raptor_qname* qname=raptor_xml_element_get_name(xml_element);
unsigned char* qname_string=raptor_qname_to_counted_name(qname, NULL);
end_element(user_data, (const char*)qname_string);
raptor_free_memory(qname_string);
}
static void raptor_rdfa_character_data(void *user_data,
raptor_xml_element* xml_element,
const unsigned char *s, int len)
{
character_data(user_data, (const char *)s, len);
}
static void raptor_rdfa_namespace_handler(void *user_data,
raptor_namespace* nspace)
{
rdfalist* context_stack = (rdfalist*)user_data;
rdfacontext* context = (rdfacontext*)
context_stack->items[context_stack->num_items - 1]->data;
if(context->namespace_handler)
(*context->namespace_handler)(context->namespace_handler_user_data,
nspace);
}
#endif
rdfacontext* rdfa_create_context(const char* base)
{
rdfacontext* rval = NULL;
size_t base_length = strlen(base);
// if the base isn't specified, don't create a context
if(base_length > 0)
{
char* cleaned_base;
rval = (rdfacontext*)malloc(sizeof(rdfacontext));
rval->base = NULL;
cleaned_base = rdfa_iri_get_base(base);
rval->base = rdfa_replace_string(rval->base, cleaned_base);
free(cleaned_base);
// no callbacks set yet
rval->default_graph_triple_callback = NULL;
rval->buffer_filler_callback = NULL;
rval->processor_graph_triple_callback = NULL;
rval->callback_data = NULL;
/* parse state */
rval->wb_allocated = 0;
rval->working_buffer = NULL;
rval->wb_position = 0;
#ifdef LIBRDFA_IN_RAPTOR
rval->base_uri = NULL;
rval->sax2 = NULL;
rval->namespace_handler = NULL;
rval->namespace_handler_user_data = NULL;
#else
rval->uri_mappings = NULL;
rval->parser = NULL;
#endif
rval->done = 0;
rval->context_stack = NULL;
rval->wb_preread = 0;
rval->preread = 0;
}
else
{
printf("librdfa error: Failed to create a parsing context, "
"base IRI was not specified!\n");
}
return rval;
}
static void rdfa_free_context_stack(rdfacontext* context)
{
// this field is not NULL only on the rdfacontext* at the top of the stack
if(context->context_stack != NULL)
{
void* rval;
// free the stack ensuring that we do not delete this context if
// it is in the list (which it may be, if parsing ended on error)
do
{
rval = rdfa_pop_item(context->context_stack);
if(rval && rval != context)
{
rdfa_free_context((rdfacontext*)rval);
}
}
while(rval);
free(context->context_stack->items);
free(context->context_stack);
context->context_stack = NULL;
}
}
void rdfa_free_context(rdfacontext* context)
{
free(context->base);
free(context->parent_subject);
free(context->parent_object);
#ifndef LIBRDFA_IN_RAPTOR
rdfa_free_mapping(context->uri_mappings);
#endif
rdfa_free_list(context->incomplete_triples);
free(context->language);
free(context->underscore_colon_bnode_name);
free(context->new_subject);
free(context->current_object_resource);
free(context->content);
free(context->datatype);
rdfa_free_list(context->property);
free(context->plain_literal);
free(context->xml_literal);
// TODO: These should be moved into their own data structure
rdfa_free_list(context->local_incomplete_triples);
rdfa_free_context_stack(context);
free(context->working_buffer);
free(context);
}
void rdfa_set_default_graph_triple_handler(
rdfacontext* context, triple_handler_fp th)
{
context->default_graph_triple_callback = th;
}
void rdfa_set_processor_graph_triple_handler(
rdfacontext* context, triple_handler_fp th)
{
context->processor_graph_triple_callback = th;
}
void rdfa_set_buffer_filler(rdfacontext* context, buffer_filler_fp bf)
{
context->buffer_filler_callback = bf;
}
int rdfa_parse_start(rdfacontext* context)
{
// create the buffers and expat parser
int rval = RDFA_PARSE_SUCCESS;
context->wb_allocated = sizeof(char) * READ_BUFFER_SIZE;
// +1 for NUL at end, to allow strstr() etc. to work
// malloc - only the first char needs to be NUL
context->working_buffer = (char*)malloc(context->wb_allocated + 1);
*context->working_buffer = '\0';
#ifndef LIBRDFA_IN_RAPTOR
context->parser = XML_ParserCreate(NULL);
#endif
context->done = 0;
context->context_stack = rdfa_create_list(32);
// initialize the context stack
rdfa_push_item(context->context_stack, context, RDFALIST_FLAG_CONTEXT);
#ifdef LIBRDFA_IN_RAPTOR
context->sax2 = raptor_new_sax2(context->world, context->locator,
context->context_stack);
#else
#endif
// set up the context stack
#ifdef LIBRDFA_IN_RAPTOR
raptor_sax2_set_start_element_handler(context->sax2,
raptor_rdfa_start_element);
raptor_sax2_set_end_element_handler(context->sax2,
raptor_rdfa_end_element);
raptor_sax2_set_characters_handler(context->sax2,
raptor_rdfa_character_data);
raptor_sax2_set_namespace_handler(context->sax2,
raptor_rdfa_namespace_handler);
#else
XML_SetUserData(context->parser, context->context_stack);
XML_SetElementHandler(context->parser, start_element, end_element);
XML_SetCharacterDataHandler(context->parser, character_data);
#endif
rdfa_init_context(context);
#ifdef LIBRDFA_IN_RAPTOR
if(1) {
raptor_parser* rdf_parser = (raptor_parser*)context->callback_data;
/* Optionally forbid internal network and file requests in the
* XML parser
*/
raptor_sax2_set_option(context->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(context->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(context->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
}
context->base_uri=raptor_new_uri(context->sax2->world, (const unsigned char*)context->base);
raptor_sax2_parse_start(context->sax2, context->base_uri);
#endif
return rval;
}
static int rdfa_process_doctype(rdfacontext* context, size_t* bytes)
{
int rval = 0;
char* doctype_position = 0;
char* doctype_buffer;
const char* new_doctype =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML+RDFa 1.0//EN\" "
"\"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd\">";
// Create a working buffer for finding the DOCTYPE
doctype_buffer = (char*)malloc(*bytes + 2);
memcpy(doctype_buffer, context->working_buffer, *bytes);
doctype_buffer[*bytes + 1] = '\0';
doctype_position = strstr(doctype_buffer, "<!DOCTYPE");
// if a doctype declaration was found, attempt to replace it
if(doctype_position != NULL)
{
char* new_doctype_buffer = NULL;
size_t new_doctype_buffer_length = 0;
char* doctype_end = strchr(doctype_position, '>');
// make sure that the end of the doctype declaration can be found
if(doctype_end != NULL)
{
size_t bytes_to_copy = 0;
size_t total_bytes = 0;
// create the new doctype buffer
bytes_to_copy = doctype_position - doctype_buffer;
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, doctype_buffer, bytes_to_copy);
total_bytes += bytes_to_copy;
bytes_to_copy = RDFA_DOCTYPE_STRING_LENGTH;
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, new_doctype, bytes_to_copy);
total_bytes += bytes_to_copy;
bytes_to_copy = *bytes - ((doctype_end + 1) - doctype_buffer);
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, doctype_end + 1, bytes_to_copy);
total_bytes += bytes_to_copy;
// replace the old working buffer with the new doctype buffer
free(context->working_buffer);
context->working_buffer = new_doctype_buffer;
context->wb_position = total_bytes;
context->wb_allocated = total_bytes;
*bytes = context->wb_allocated;
rval = 1;
}
}
else
{
char* new_doctype_buffer = NULL;
size_t new_doctype_buffer_length = 0;
// find where the HTML element begins
char* html_position = strstr(doctype_buffer, "<html");
if(html_position == NULL)
{
html_position = strstr(doctype_buffer, "<HTML");
}
if(html_position != NULL)
{
size_t bytes_to_copy = 0;
size_t total_bytes = 0;
// create the new doctype buffer
bytes_to_copy = html_position - doctype_buffer;
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, doctype_buffer, bytes_to_copy);
total_bytes += bytes_to_copy;
bytes_to_copy = RDFA_DOCTYPE_STRING_LENGTH;
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, new_doctype, bytes_to_copy);
total_bytes += bytes_to_copy;
bytes_to_copy = 1;
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, "\n", bytes_to_copy);
total_bytes += bytes_to_copy;
bytes_to_copy = *bytes - (html_position - doctype_buffer);
new_doctype_buffer = rdfa_n_append_string(new_doctype_buffer,
&new_doctype_buffer_length, html_position, bytes_to_copy);
total_bytes += bytes_to_copy;
// replace the old working buffer with the new doctype buffer
free(context->working_buffer);
context->working_buffer = new_doctype_buffer;
context->wb_position = total_bytes;
context->wb_allocated = total_bytes;
*bytes = context->wb_allocated;
rval = 1;
}
}
free(doctype_buffer);
return rval;
}
#ifndef LIBRDFA_IN_RAPTOR
static void rdfa_report_error(rdfacontext* context, char* data, size_t length)
{
char* buffer = malloc(2<<12);
snprintf(buffer, 2<<12, "XML parsing error: %s at line %d, column %d.",
XML_ErrorString(XML_GetErrorCode(context->parser)),
(int)XML_GetCurrentLineNumber(context->parser),
(int)XML_GetCurrentColumnNumber(context->parser));
if(context->processor_graph_triple_callback != NULL)
{
char* error_subject = rdfa_create_bnode(context);
char* pointer_subject = rdfa_create_bnode(context);
// generate the RDFa Processing Graph error type triple
rdftriple* triple = rdfa_create_triple(
error_subject, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
"http://www.w3.org/ns/rdfa_processing_graph#Error",
RDF_TYPE_IRI, NULL, NULL);
context->processor_graph_triple_callback(triple, context->callback_data);
// generate the error description
triple = rdfa_create_triple(
error_subject, "http://purl.org/dc/terms/description", buffer,
RDF_TYPE_PLAIN_LITERAL, NULL, "en");
context->processor_graph_triple_callback(triple, context->callback_data);
// generate the context triple for the error
triple = rdfa_create_triple(
error_subject, "http://www.w3.org/ns/rdfa_processing_graph#context",
pointer_subject, RDF_TYPE_IRI, NULL, NULL);
context->processor_graph_triple_callback(triple, context->callback_data);
// generate the type for the context triple
triple = rdfa_create_triple(
pointer_subject, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
"http://www.w3.org/2009/pointers#LineCharPointer",
RDF_TYPE_IRI, NULL, NULL);
context->processor_graph_triple_callback(triple, context->callback_data);
// generate the line number
snprintf(buffer, 2<<12, "%d",
(int)XML_GetCurrentLineNumber(context->parser));
triple = rdfa_create_triple(
pointer_subject, "http://www.w3.org/2009/pointers#lineNumber",
buffer, RDF_TYPE_TYPED_LITERAL,
"http://www.w3.org/2001/XMLSchema#positiveInteger", NULL);
context->processor_graph_triple_callback(triple, context->callback_data);
// generate the column number
snprintf(buffer, 2<<12, "%d",
(int)XML_GetCurrentColumnNumber(context->parser));
triple = rdfa_create_triple(
pointer_subject, "http://www.w3.org/2009/pointers#charNumber",
buffer, RDF_TYPE_TYPED_LITERAL,
"http://www.w3.org/2001/XMLSchema#positiveInteger", NULL);
context->processor_graph_triple_callback(triple, context->callback_data);
free(error_subject);
free(pointer_subject);
}
else
{
printf("librdfa processor error: %s\n", buffer);
}
free(buffer);
}
#endif
int rdfa_parse_chunk(rdfacontext* context, char* data, size_t wblen, int done)
{
// it is an error to call this before rdfa_parse_start()
if(context->done)
{
return RDFA_PARSE_FAILED;
}
if(!context->preread)
{
// search for the <base> tag and use the href contained therein to
// set the parsing context.
context->wb_preread = rdfa_init_base(context,
&context->working_buffer, &context->wb_allocated, data, wblen);
// continue looking if in first 131072 bytes of data
if(!context->base && context->wb_preread < (1<<17))
return RDFA_PARSE_SUCCESS;
// process the document's DOCTYPE
rdfa_process_doctype(context, &wblen);
#ifdef LIBRDFA_IN_RAPTOR
if(raptor_sax2_parse_chunk(context->sax2,
(const unsigned char*)context->working_buffer,
context->wb_position, done))
{
return RDFA_PARSE_FAILED;
}
#else
if(XML_Parse(context->parser, context->working_buffer,
context->wb_position, 0) == XML_STATUS_ERROR)
{
rdfa_report_error(context, data, wblen);
return RDFA_PARSE_FAILED;
}
#endif
context->preread = 1;
return RDFA_PARSE_SUCCESS;
}
// otherwise just parse the block passed in
#ifdef LIBRDFA_IN_RAPTOR
if(raptor_sax2_parse_chunk(context->sax2, (const unsigned char*)data, wblen, done))
{
return RDFA_PARSE_FAILED;
}
#else
if(XML_Parse(context->parser, data, wblen, done) == XML_STATUS_ERROR)
{
rdfa_report_error(context, data, wblen);
return RDFA_PARSE_FAILED;
}
#endif
return RDFA_PARSE_SUCCESS;
}
void rdfa_parse_end(rdfacontext* context)
{
// free context stack
rdfa_free_context_stack(context);
// Free the expat parser and the like
#ifdef LIBRDFA_IN_RAPTOR
if(context->base_uri)
raptor_free_uri(context->base_uri);
raptor_free_sax2(context->sax2);
context->sax2=NULL;
#else
// free parser
XML_ParserFree(context->parser);
#endif
}
char* rdfa_get_buffer(rdfacontext* context, size_t* blen)
{
*blen = context->wb_allocated;
return context->working_buffer;
}
int rdfa_parse_buffer(rdfacontext* context, size_t bytes)
{
int rval;
int done;
done = (bytes == 0);
rval = rdfa_parse_chunk(context, context->working_buffer, bytes, done);
context->done = done;
return rval;
}
int rdfa_parse(rdfacontext* context)
{
int rval;
rval = rdfa_parse_start(context);
if(rval != RDFA_PARSE_SUCCESS)
{
context->done = 1;
return rval;
}
do
{
size_t wblen;
int done;
wblen = context->buffer_filler_callback(
context->working_buffer, context->wb_allocated,
context->callback_data);
done = (wblen == 0);
rval = rdfa_parse_chunk(context, context->working_buffer, wblen, done);
context->done=done;
}
while(!context->done && rval == RDFA_PARSE_SUCCESS);
rdfa_parse_end(context);
return rval;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3568_4 |
crossvul-cpp_data_bad_5569_0 | /*
HIDP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2003-2004 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/file.h>
#include <linux/kthread.h>
#include <linux/hidraw.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
#include "hidp.h"
#define VERSION "1.2"
static DECLARE_RWSEM(hidp_session_sem);
static LIST_HEAD(hidp_session_list);
static unsigned char hidp_keycode[256] = {
0, 0, 0, 0, 30, 48, 46, 32, 18, 33, 34, 35, 23, 36,
37, 38, 50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45,
21, 44, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 28, 1,
14, 15, 57, 12, 13, 26, 27, 43, 43, 39, 40, 41, 51, 52,
53, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 87, 88,
99, 70, 119, 110, 102, 104, 111, 107, 109, 106, 105, 108, 103, 69,
98, 55, 74, 78, 96, 79, 80, 81, 75, 76, 77, 71, 72, 73,
82, 83, 86, 127, 116, 117, 183, 184, 185, 186, 187, 188, 189, 190,
191, 192, 193, 194, 134, 138, 130, 132, 128, 129, 131, 137, 133, 135,
136, 113, 115, 114, 0, 0, 0, 121, 0, 89, 93, 124, 92, 94,
95, 0, 0, 0, 122, 123, 90, 91, 85, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
29, 42, 56, 125, 97, 54, 100, 126, 164, 166, 165, 163, 161, 115,
114, 113, 150, 158, 159, 128, 136, 177, 178, 176, 142, 152, 173, 140
};
static unsigned char hidp_mkeyspat[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
static struct hidp_session *__hidp_get_session(bdaddr_t *bdaddr)
{
struct hidp_session *session;
BT_DBG("");
list_for_each_entry(session, &hidp_session_list, list) {
if (!bacmp(bdaddr, &session->bdaddr))
return session;
}
return NULL;
}
static void __hidp_link_session(struct hidp_session *session)
{
list_add(&session->list, &hidp_session_list);
}
static void __hidp_unlink_session(struct hidp_session *session)
{
hci_conn_put_device(session->conn);
list_del(&session->list);
}
static void __hidp_copy_session(struct hidp_session *session, struct hidp_conninfo *ci)
{
memset(ci, 0, sizeof(*ci));
bacpy(&ci->bdaddr, &session->bdaddr);
ci->flags = session->flags;
ci->state = session->state;
ci->vendor = 0x0000;
ci->product = 0x0000;
ci->version = 0x0000;
if (session->input) {
ci->vendor = session->input->id.vendor;
ci->product = session->input->id.product;
ci->version = session->input->id.version;
if (session->input->name)
strncpy(ci->name, session->input->name, 128);
else
strncpy(ci->name, "HID Boot Device", 128);
}
if (session->hid) {
ci->vendor = session->hid->vendor;
ci->product = session->hid->product;
ci->version = session->hid->version;
strncpy(ci->name, session->hid->name, 128);
}
}
static int hidp_queue_event(struct hidp_session *session, struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
unsigned char newleds;
struct sk_buff *skb;
BT_DBG("session %p type %d code %d value %d", session, type, code, value);
if (type != EV_LED)
return -1;
newleds = (!!test_bit(LED_KANA, dev->led) << 3) |
(!!test_bit(LED_COMPOSE, dev->led) << 3) |
(!!test_bit(LED_SCROLLL, dev->led) << 2) |
(!!test_bit(LED_CAPSL, dev->led) << 1) |
(!!test_bit(LED_NUML, dev->led));
if (session->leds == newleds)
return 0;
session->leds = newleds;
skb = alloc_skb(3, GFP_ATOMIC);
if (!skb) {
BT_ERR("Can't allocate memory for new frame");
return -ENOMEM;
}
*skb_put(skb, 1) = HIDP_TRANS_DATA | HIDP_DATA_RTYPE_OUPUT;
*skb_put(skb, 1) = 0x01;
*skb_put(skb, 1) = newleds;
skb_queue_tail(&session->intr_transmit, skb);
hidp_schedule(session);
return 0;
}
static int hidp_hidinput_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
{
struct hid_device *hid = input_get_drvdata(dev);
struct hidp_session *session = hid->driver_data;
return hidp_queue_event(session, dev, type, code, value);
}
static int hidp_input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
{
struct hidp_session *session = input_get_drvdata(dev);
return hidp_queue_event(session, dev, type, code, value);
}
static void hidp_input_report(struct hidp_session *session, struct sk_buff *skb)
{
struct input_dev *dev = session->input;
unsigned char *keys = session->keys;
unsigned char *udata = skb->data + 1;
signed char *sdata = skb->data + 1;
int i, size = skb->len - 1;
switch (skb->data[0]) {
case 0x01: /* Keyboard report */
for (i = 0; i < 8; i++)
input_report_key(dev, hidp_keycode[i + 224], (udata[0] >> i) & 1);
/* If all the key codes have been set to 0x01, it means
* too many keys were pressed at the same time. */
if (!memcmp(udata + 2, hidp_mkeyspat, 6))
break;
for (i = 2; i < 8; i++) {
if (keys[i] > 3 && memscan(udata + 2, keys[i], 6) == udata + 8) {
if (hidp_keycode[keys[i]])
input_report_key(dev, hidp_keycode[keys[i]], 0);
else
BT_ERR("Unknown key (scancode %#x) released.", keys[i]);
}
if (udata[i] > 3 && memscan(keys + 2, udata[i], 6) == keys + 8) {
if (hidp_keycode[udata[i]])
input_report_key(dev, hidp_keycode[udata[i]], 1);
else
BT_ERR("Unknown key (scancode %#x) pressed.", udata[i]);
}
}
memcpy(keys, udata, 8);
break;
case 0x02: /* Mouse report */
input_report_key(dev, BTN_LEFT, sdata[0] & 0x01);
input_report_key(dev, BTN_RIGHT, sdata[0] & 0x02);
input_report_key(dev, BTN_MIDDLE, sdata[0] & 0x04);
input_report_key(dev, BTN_SIDE, sdata[0] & 0x08);
input_report_key(dev, BTN_EXTRA, sdata[0] & 0x10);
input_report_rel(dev, REL_X, sdata[1]);
input_report_rel(dev, REL_Y, sdata[2]);
if (size > 3)
input_report_rel(dev, REL_WHEEL, sdata[3]);
break;
}
input_sync(dev);
}
static int __hidp_send_ctrl_message(struct hidp_session *session,
unsigned char hdr, unsigned char *data,
int size)
{
struct sk_buff *skb;
BT_DBG("session %p data %p size %d", session, data, size);
if (atomic_read(&session->terminate))
return -EIO;
skb = alloc_skb(size + 1, GFP_ATOMIC);
if (!skb) {
BT_ERR("Can't allocate memory for new frame");
return -ENOMEM;
}
*skb_put(skb, 1) = hdr;
if (data && size > 0)
memcpy(skb_put(skb, size), data, size);
skb_queue_tail(&session->ctrl_transmit, skb);
return 0;
}
static int hidp_send_ctrl_message(struct hidp_session *session,
unsigned char hdr, unsigned char *data, int size)
{
int err;
err = __hidp_send_ctrl_message(session, hdr, data, size);
hidp_schedule(session);
return err;
}
static int hidp_queue_report(struct hidp_session *session,
unsigned char *data, int size)
{
struct sk_buff *skb;
BT_DBG("session %p hid %p data %p size %d", session, session->hid, data, size);
skb = alloc_skb(size + 1, GFP_ATOMIC);
if (!skb) {
BT_ERR("Can't allocate memory for new frame");
return -ENOMEM;
}
*skb_put(skb, 1) = 0xa2;
if (size > 0)
memcpy(skb_put(skb, size), data, size);
skb_queue_tail(&session->intr_transmit, skb);
hidp_schedule(session);
return 0;
}
static int hidp_send_report(struct hidp_session *session, struct hid_report *report)
{
unsigned char buf[32];
int rsize;
rsize = ((report->size - 1) >> 3) + 1 + (report->id > 0);
if (rsize > sizeof(buf))
return -EIO;
hid_output_report(report, buf);
return hidp_queue_report(session, buf, rsize);
}
static int hidp_get_raw_report(struct hid_device *hid,
unsigned char report_number,
unsigned char *data, size_t count,
unsigned char report_type)
{
struct hidp_session *session = hid->driver_data;
struct sk_buff *skb;
size_t len;
int numbered_reports = hid->report_enum[report_type].numbered;
int ret;
switch (report_type) {
case HID_FEATURE_REPORT:
report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_FEATURE;
break;
case HID_INPUT_REPORT:
report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_INPUT;
break;
case HID_OUTPUT_REPORT:
report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_OUPUT;
break;
default:
return -EINVAL;
}
if (mutex_lock_interruptible(&session->report_mutex))
return -ERESTARTSYS;
/* Set up our wait, and send the report request to the device. */
session->waiting_report_type = report_type & HIDP_DATA_RTYPE_MASK;
session->waiting_report_number = numbered_reports ? report_number : -1;
set_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
data[0] = report_number;
ret = hidp_send_ctrl_message(hid->driver_data, report_type, data, 1);
if (ret)
goto err;
/* Wait for the return of the report. The returned report
gets put in session->report_return. */
while (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags)) {
int res;
res = wait_event_interruptible_timeout(session->report_queue,
!test_bit(HIDP_WAITING_FOR_RETURN, &session->flags),
5*HZ);
if (res == 0) {
/* timeout */
ret = -EIO;
goto err;
}
if (res < 0) {
/* signal */
ret = -ERESTARTSYS;
goto err;
}
}
skb = session->report_return;
if (skb) {
len = skb->len < count ? skb->len : count;
memcpy(data, skb->data, len);
kfree_skb(skb);
session->report_return = NULL;
} else {
/* Device returned a HANDSHAKE, indicating protocol error. */
len = -EIO;
}
clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
mutex_unlock(&session->report_mutex);
return len;
err:
clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
mutex_unlock(&session->report_mutex);
return ret;
}
static int hidp_output_raw_report(struct hid_device *hid, unsigned char *data, size_t count,
unsigned char report_type)
{
struct hidp_session *session = hid->driver_data;
int ret;
switch (report_type) {
case HID_FEATURE_REPORT:
report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_FEATURE;
break;
case HID_OUTPUT_REPORT:
report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_OUPUT;
break;
default:
return -EINVAL;
}
if (mutex_lock_interruptible(&session->report_mutex))
return -ERESTARTSYS;
/* Set up our wait, and send the report request to the device. */
set_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
ret = hidp_send_ctrl_message(hid->driver_data, report_type, data,
count);
if (ret)
goto err;
/* Wait for the ACK from the device. */
while (test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags)) {
int res;
res = wait_event_interruptible_timeout(session->report_queue,
!test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags),
10*HZ);
if (res == 0) {
/* timeout */
ret = -EIO;
goto err;
}
if (res < 0) {
/* signal */
ret = -ERESTARTSYS;
goto err;
}
}
if (!session->output_report_success) {
ret = -EIO;
goto err;
}
ret = count;
err:
clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
mutex_unlock(&session->report_mutex);
return ret;
}
static void hidp_idle_timeout(unsigned long arg)
{
struct hidp_session *session = (struct hidp_session *) arg;
atomic_inc(&session->terminate);
wake_up_process(session->task);
}
static void hidp_set_timer(struct hidp_session *session)
{
if (session->idle_to > 0)
mod_timer(&session->timer, jiffies + HZ * session->idle_to);
}
static void hidp_del_timer(struct hidp_session *session)
{
if (session->idle_to > 0)
del_timer(&session->timer);
}
static void hidp_process_handshake(struct hidp_session *session,
unsigned char param)
{
BT_DBG("session %p param 0x%02x", session, param);
session->output_report_success = 0; /* default condition */
switch (param) {
case HIDP_HSHK_SUCCESSFUL:
/* FIXME: Call into SET_ GET_ handlers here */
session->output_report_success = 1;
break;
case HIDP_HSHK_NOT_READY:
case HIDP_HSHK_ERR_INVALID_REPORT_ID:
case HIDP_HSHK_ERR_UNSUPPORTED_REQUEST:
case HIDP_HSHK_ERR_INVALID_PARAMETER:
if (test_and_clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags))
wake_up_interruptible(&session->report_queue);
/* FIXME: Call into SET_ GET_ handlers here */
break;
case HIDP_HSHK_ERR_UNKNOWN:
break;
case HIDP_HSHK_ERR_FATAL:
/* Device requests a reboot, as this is the only way this error
* can be recovered. */
__hidp_send_ctrl_message(session,
HIDP_TRANS_HID_CONTROL | HIDP_CTRL_SOFT_RESET, NULL, 0);
break;
default:
__hidp_send_ctrl_message(session,
HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0);
break;
}
/* Wake up the waiting thread. */
if (test_and_clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags))
wake_up_interruptible(&session->report_queue);
}
static void hidp_process_hid_control(struct hidp_session *session,
unsigned char param)
{
BT_DBG("session %p param 0x%02x", session, param);
if (param == HIDP_CTRL_VIRTUAL_CABLE_UNPLUG) {
/* Flush the transmit queues */
skb_queue_purge(&session->ctrl_transmit);
skb_queue_purge(&session->intr_transmit);
atomic_inc(&session->terminate);
wake_up_process(current);
}
}
/* Returns true if the passed-in skb should be freed by the caller. */
static int hidp_process_data(struct hidp_session *session, struct sk_buff *skb,
unsigned char param)
{
int done_with_skb = 1;
BT_DBG("session %p skb %p len %d param 0x%02x", session, skb, skb->len, param);
switch (param) {
case HIDP_DATA_RTYPE_INPUT:
hidp_set_timer(session);
if (session->input)
hidp_input_report(session, skb);
if (session->hid)
hid_input_report(session->hid, HID_INPUT_REPORT, skb->data, skb->len, 0);
break;
case HIDP_DATA_RTYPE_OTHER:
case HIDP_DATA_RTYPE_OUPUT:
case HIDP_DATA_RTYPE_FEATURE:
break;
default:
__hidp_send_ctrl_message(session,
HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0);
}
if (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags) &&
param == session->waiting_report_type) {
if (session->waiting_report_number < 0 ||
session->waiting_report_number == skb->data[0]) {
/* hidp_get_raw_report() is waiting on this report. */
session->report_return = skb;
done_with_skb = 0;
clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
wake_up_interruptible(&session->report_queue);
}
}
return done_with_skb;
}
static void hidp_recv_ctrl_frame(struct hidp_session *session,
struct sk_buff *skb)
{
unsigned char hdr, type, param;
int free_skb = 1;
BT_DBG("session %p skb %p len %d", session, skb, skb->len);
hdr = skb->data[0];
skb_pull(skb, 1);
type = hdr & HIDP_HEADER_TRANS_MASK;
param = hdr & HIDP_HEADER_PARAM_MASK;
switch (type) {
case HIDP_TRANS_HANDSHAKE:
hidp_process_handshake(session, param);
break;
case HIDP_TRANS_HID_CONTROL:
hidp_process_hid_control(session, param);
break;
case HIDP_TRANS_DATA:
free_skb = hidp_process_data(session, skb, param);
break;
default:
__hidp_send_ctrl_message(session,
HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_UNSUPPORTED_REQUEST, NULL, 0);
break;
}
if (free_skb)
kfree_skb(skb);
}
static void hidp_recv_intr_frame(struct hidp_session *session,
struct sk_buff *skb)
{
unsigned char hdr;
BT_DBG("session %p skb %p len %d", session, skb, skb->len);
hdr = skb->data[0];
skb_pull(skb, 1);
if (hdr == (HIDP_TRANS_DATA | HIDP_DATA_RTYPE_INPUT)) {
hidp_set_timer(session);
if (session->input)
hidp_input_report(session, skb);
if (session->hid) {
hid_input_report(session->hid, HID_INPUT_REPORT, skb->data, skb->len, 1);
BT_DBG("report len %d", skb->len);
}
} else {
BT_DBG("Unsupported protocol header 0x%02x", hdr);
}
kfree_skb(skb);
}
static int hidp_send_frame(struct socket *sock, unsigned char *data, int len)
{
struct kvec iv = { data, len };
struct msghdr msg;
BT_DBG("sock %p data %p len %d", sock, data, len);
if (!len)
return 0;
memset(&msg, 0, sizeof(msg));
return kernel_sendmsg(sock, &msg, &iv, 1, len);
}
static void hidp_process_intr_transmit(struct hidp_session *session)
{
struct sk_buff *skb;
BT_DBG("session %p", session);
while ((skb = skb_dequeue(&session->intr_transmit))) {
if (hidp_send_frame(session->intr_sock, skb->data, skb->len) < 0) {
skb_queue_head(&session->intr_transmit, skb);
break;
}
hidp_set_timer(session);
kfree_skb(skb);
}
}
static void hidp_process_ctrl_transmit(struct hidp_session *session)
{
struct sk_buff *skb;
BT_DBG("session %p", session);
while ((skb = skb_dequeue(&session->ctrl_transmit))) {
if (hidp_send_frame(session->ctrl_sock, skb->data, skb->len) < 0) {
skb_queue_head(&session->ctrl_transmit, skb);
break;
}
hidp_set_timer(session);
kfree_skb(skb);
}
}
static int hidp_session(void *arg)
{
struct hidp_session *session = arg;
struct sock *ctrl_sk = session->ctrl_sock->sk;
struct sock *intr_sk = session->intr_sock->sk;
struct sk_buff *skb;
wait_queue_t ctrl_wait, intr_wait;
BT_DBG("session %p", session);
__module_get(THIS_MODULE);
set_user_nice(current, -15);
init_waitqueue_entry(&ctrl_wait, current);
init_waitqueue_entry(&intr_wait, current);
add_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait);
add_wait_queue(sk_sleep(intr_sk), &intr_wait);
session->waiting_for_startup = 0;
wake_up_interruptible(&session->startup_queue);
set_current_state(TASK_INTERRUPTIBLE);
while (!atomic_read(&session->terminate)) {
if (ctrl_sk->sk_state != BT_CONNECTED ||
intr_sk->sk_state != BT_CONNECTED)
break;
while ((skb = skb_dequeue(&intr_sk->sk_receive_queue))) {
skb_orphan(skb);
if (!skb_linearize(skb))
hidp_recv_intr_frame(session, skb);
else
kfree_skb(skb);
}
hidp_process_intr_transmit(session);
while ((skb = skb_dequeue(&ctrl_sk->sk_receive_queue))) {
skb_orphan(skb);
if (!skb_linearize(skb))
hidp_recv_ctrl_frame(session, skb);
else
kfree_skb(skb);
}
hidp_process_ctrl_transmit(session);
schedule();
set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(intr_sk), &intr_wait);
remove_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait);
clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
wake_up_interruptible(&session->report_queue);
down_write(&hidp_session_sem);
hidp_del_timer(session);
if (session->input) {
input_unregister_device(session->input);
session->input = NULL;
}
if (session->hid) {
hid_destroy_device(session->hid);
session->hid = NULL;
}
/* Wakeup user-space polling for socket errors */
session->intr_sock->sk->sk_err = EUNATCH;
session->ctrl_sock->sk->sk_err = EUNATCH;
hidp_schedule(session);
fput(session->intr_sock->file);
wait_event_timeout(*(sk_sleep(ctrl_sk)),
(ctrl_sk->sk_state == BT_CLOSED), msecs_to_jiffies(500));
fput(session->ctrl_sock->file);
__hidp_unlink_session(session);
up_write(&hidp_session_sem);
kfree(session->rd_data);
kfree(session);
module_put_and_exit(0);
return 0;
}
static struct hci_conn *hidp_get_connection(struct hidp_session *session)
{
bdaddr_t *src = &bt_sk(session->ctrl_sock->sk)->src;
bdaddr_t *dst = &bt_sk(session->ctrl_sock->sk)->dst;
struct hci_conn *conn;
struct hci_dev *hdev;
hdev = hci_get_route(dst, src);
if (!hdev)
return NULL;
hci_dev_lock(hdev);
conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst);
if (conn)
hci_conn_hold_device(conn);
hci_dev_unlock(hdev);
hci_dev_put(hdev);
return conn;
}
static int hidp_setup_input(struct hidp_session *session,
struct hidp_connadd_req *req)
{
struct input_dev *input;
int i;
input = input_allocate_device();
if (!input)
return -ENOMEM;
session->input = input;
input_set_drvdata(input, session);
input->name = "Bluetooth HID Boot Protocol Device";
input->id.bustype = BUS_BLUETOOTH;
input->id.vendor = req->vendor;
input->id.product = req->product;
input->id.version = req->version;
if (req->subclass & 0x40) {
set_bit(EV_KEY, input->evbit);
set_bit(EV_LED, input->evbit);
set_bit(EV_REP, input->evbit);
set_bit(LED_NUML, input->ledbit);
set_bit(LED_CAPSL, input->ledbit);
set_bit(LED_SCROLLL, input->ledbit);
set_bit(LED_COMPOSE, input->ledbit);
set_bit(LED_KANA, input->ledbit);
for (i = 0; i < sizeof(hidp_keycode); i++)
set_bit(hidp_keycode[i], input->keybit);
clear_bit(0, input->keybit);
}
if (req->subclass & 0x80) {
input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
input->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
input->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
BIT_MASK(BTN_EXTRA);
input->relbit[0] |= BIT_MASK(REL_WHEEL);
}
input->dev.parent = &session->conn->dev;
input->event = hidp_input_event;
return 0;
}
static int hidp_open(struct hid_device *hid)
{
return 0;
}
static void hidp_close(struct hid_device *hid)
{
}
static int hidp_parse(struct hid_device *hid)
{
struct hidp_session *session = hid->driver_data;
return hid_parse_report(session->hid, session->rd_data,
session->rd_size);
}
static int hidp_start(struct hid_device *hid)
{
struct hidp_session *session = hid->driver_data;
struct hid_report *report;
if (hid->quirks & HID_QUIRK_NO_INIT_REPORTS)
return 0;
list_for_each_entry(report, &hid->report_enum[HID_INPUT_REPORT].
report_list, list)
hidp_send_report(session, report);
list_for_each_entry(report, &hid->report_enum[HID_FEATURE_REPORT].
report_list, list)
hidp_send_report(session, report);
return 0;
}
static void hidp_stop(struct hid_device *hid)
{
struct hidp_session *session = hid->driver_data;
skb_queue_purge(&session->ctrl_transmit);
skb_queue_purge(&session->intr_transmit);
hid->claimed = 0;
}
static struct hid_ll_driver hidp_hid_driver = {
.parse = hidp_parse,
.start = hidp_start,
.stop = hidp_stop,
.open = hidp_open,
.close = hidp_close,
.hidinput_input_event = hidp_hidinput_event,
};
/* This function sets up the hid device. It does not add it
to the HID system. That is done in hidp_add_connection(). */
static int hidp_setup_hid(struct hidp_session *session,
struct hidp_connadd_req *req)
{
struct hid_device *hid;
int err;
session->rd_data = kzalloc(req->rd_size, GFP_KERNEL);
if (!session->rd_data)
return -ENOMEM;
if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) {
err = -EFAULT;
goto fault;
}
session->rd_size = req->rd_size;
hid = hid_allocate_device();
if (IS_ERR(hid)) {
err = PTR_ERR(hid);
goto fault;
}
session->hid = hid;
hid->driver_data = session;
hid->bus = BUS_BLUETOOTH;
hid->vendor = req->vendor;
hid->product = req->product;
hid->version = req->version;
hid->country = req->country;
strncpy(hid->name, req->name, 128);
snprintf(hid->phys, sizeof(hid->phys), "%pMR",
&bt_sk(session->ctrl_sock->sk)->src);
snprintf(hid->uniq, sizeof(hid->uniq), "%pMR",
&bt_sk(session->ctrl_sock->sk)->dst);
hid->dev.parent = &session->conn->dev;
hid->ll_driver = &hidp_hid_driver;
hid->hid_get_raw_report = hidp_get_raw_report;
hid->hid_output_raw_report = hidp_output_raw_report;
/* True if device is blacklisted in drivers/hid/hid-core.c */
if (hid_ignore(hid)) {
hid_destroy_device(session->hid);
session->hid = NULL;
return -ENODEV;
}
return 0;
fault:
kfree(session->rd_data);
session->rd_data = NULL;
return err;
}
int hidp_add_connection(struct hidp_connadd_req *req, struct socket *ctrl_sock, struct socket *intr_sock)
{
struct hidp_session *session, *s;
int vendor, product;
int err;
BT_DBG("");
if (bacmp(&bt_sk(ctrl_sock->sk)->src, &bt_sk(intr_sock->sk)->src) ||
bacmp(&bt_sk(ctrl_sock->sk)->dst, &bt_sk(intr_sock->sk)->dst))
return -ENOTUNIQ;
BT_DBG("rd_data %p rd_size %d", req->rd_data, req->rd_size);
down_write(&hidp_session_sem);
s = __hidp_get_session(&bt_sk(ctrl_sock->sk)->dst);
if (s && s->state == BT_CONNECTED) {
up_write(&hidp_session_sem);
return -EEXIST;
}
session = kzalloc(sizeof(struct hidp_session), GFP_KERNEL);
if (!session) {
up_write(&hidp_session_sem);
return -ENOMEM;
}
bacpy(&session->bdaddr, &bt_sk(ctrl_sock->sk)->dst);
session->ctrl_mtu = min_t(uint, l2cap_pi(ctrl_sock->sk)->chan->omtu,
l2cap_pi(ctrl_sock->sk)->chan->imtu);
session->intr_mtu = min_t(uint, l2cap_pi(intr_sock->sk)->chan->omtu,
l2cap_pi(intr_sock->sk)->chan->imtu);
BT_DBG("ctrl mtu %d intr mtu %d", session->ctrl_mtu, session->intr_mtu);
session->ctrl_sock = ctrl_sock;
session->intr_sock = intr_sock;
session->state = BT_CONNECTED;
session->conn = hidp_get_connection(session);
if (!session->conn) {
err = -ENOTCONN;
goto failed;
}
setup_timer(&session->timer, hidp_idle_timeout, (unsigned long)session);
skb_queue_head_init(&session->ctrl_transmit);
skb_queue_head_init(&session->intr_transmit);
mutex_init(&session->report_mutex);
init_waitqueue_head(&session->report_queue);
init_waitqueue_head(&session->startup_queue);
session->waiting_for_startup = 1;
session->flags = req->flags & (1 << HIDP_BLUETOOTH_VENDOR_ID);
session->idle_to = req->idle_to;
__hidp_link_session(session);
if (req->rd_size > 0) {
err = hidp_setup_hid(session, req);
if (err && err != -ENODEV)
goto purge;
}
if (!session->hid) {
err = hidp_setup_input(session, req);
if (err < 0)
goto purge;
}
hidp_set_timer(session);
if (session->hid) {
vendor = session->hid->vendor;
product = session->hid->product;
} else if (session->input) {
vendor = session->input->id.vendor;
product = session->input->id.product;
} else {
vendor = 0x0000;
product = 0x0000;
}
session->task = kthread_run(hidp_session, session, "khidpd_%04x%04x",
vendor, product);
if (IS_ERR(session->task)) {
err = PTR_ERR(session->task);
goto unlink;
}
while (session->waiting_for_startup) {
wait_event_interruptible(session->startup_queue,
!session->waiting_for_startup);
}
if (session->hid)
err = hid_add_device(session->hid);
else
err = input_register_device(session->input);
if (err < 0) {
atomic_inc(&session->terminate);
wake_up_process(session->task);
up_write(&hidp_session_sem);
return err;
}
if (session->input) {
hidp_send_ctrl_message(session,
HIDP_TRANS_SET_PROTOCOL | HIDP_PROTO_BOOT, NULL, 0);
session->flags |= (1 << HIDP_BOOT_PROTOCOL_MODE);
session->leds = 0xff;
hidp_input_event(session->input, EV_LED, 0, 0);
}
up_write(&hidp_session_sem);
return 0;
unlink:
hidp_del_timer(session);
if (session->input) {
input_unregister_device(session->input);
session->input = NULL;
}
if (session->hid) {
hid_destroy_device(session->hid);
session->hid = NULL;
}
kfree(session->rd_data);
session->rd_data = NULL;
purge:
__hidp_unlink_session(session);
skb_queue_purge(&session->ctrl_transmit);
skb_queue_purge(&session->intr_transmit);
failed:
up_write(&hidp_session_sem);
kfree(session);
return err;
}
int hidp_del_connection(struct hidp_conndel_req *req)
{
struct hidp_session *session;
int err = 0;
BT_DBG("");
down_read(&hidp_session_sem);
session = __hidp_get_session(&req->bdaddr);
if (session) {
if (req->flags & (1 << HIDP_VIRTUAL_CABLE_UNPLUG)) {
hidp_send_ctrl_message(session,
HIDP_TRANS_HID_CONTROL | HIDP_CTRL_VIRTUAL_CABLE_UNPLUG, NULL, 0);
} else {
/* Flush the transmit queues */
skb_queue_purge(&session->ctrl_transmit);
skb_queue_purge(&session->intr_transmit);
atomic_inc(&session->terminate);
wake_up_process(session->task);
}
} else
err = -ENOENT;
up_read(&hidp_session_sem);
return err;
}
int hidp_get_connlist(struct hidp_connlist_req *req)
{
struct hidp_session *session;
int err = 0, n = 0;
BT_DBG("");
down_read(&hidp_session_sem);
list_for_each_entry(session, &hidp_session_list, list) {
struct hidp_conninfo ci;
__hidp_copy_session(session, &ci);
if (copy_to_user(req->ci, &ci, sizeof(ci))) {
err = -EFAULT;
break;
}
if (++n >= req->cnum)
break;
req->ci++;
}
req->cnum = n;
up_read(&hidp_session_sem);
return err;
}
int hidp_get_conninfo(struct hidp_conninfo *ci)
{
struct hidp_session *session;
int err = 0;
down_read(&hidp_session_sem);
session = __hidp_get_session(&ci->bdaddr);
if (session)
__hidp_copy_session(session, ci);
else
err = -ENOENT;
up_read(&hidp_session_sem);
return err;
}
static int __init hidp_init(void)
{
BT_INFO("HIDP (Human Interface Emulation) ver %s", VERSION);
return hidp_init_sockets();
}
static void __exit hidp_exit(void)
{
hidp_cleanup_sockets();
}
module_init(hidp_init);
module_exit(hidp_exit);
MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
MODULE_DESCRIPTION("Bluetooth HIDP ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS("bt-proto-6");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_5569_0 |
crossvul-cpp_data_good_1765_0 | /*
* vivid-osd.c - osd support for testing overlays.
*
* Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/font.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/fb.h>
#include <media/videobuf2-vmalloc.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <media/v4l2-common.h>
#include "vivid-core.h"
#include "vivid-osd.h"
#define MAX_OSD_WIDTH 720
#define MAX_OSD_HEIGHT 576
/*
* Order: white, yellow, cyan, green, magenta, red, blue, black,
* and same again with the alpha bit set (if any)
*/
static const u16 rgb555[16] = {
0x7fff, 0x7fe0, 0x03ff, 0x03e0, 0x7c1f, 0x7c00, 0x001f, 0x0000,
0xffff, 0xffe0, 0x83ff, 0x83e0, 0xfc1f, 0xfc00, 0x801f, 0x8000
};
static const u16 rgb565[16] = {
0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000,
0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000
};
void vivid_clear_fb(struct vivid_dev *dev)
{
void *p = dev->video_vbase;
const u16 *rgb = rgb555;
unsigned x, y;
if (dev->fb_defined.green.length == 6)
rgb = rgb565;
for (y = 0; y < dev->display_height; y++) {
u16 *d = p;
for (x = 0; x < dev->display_width; x++)
d[x] = rgb[(y / 16 + x / 16) % 16];
p += dev->display_byte_stride;
}
}
/* --------------------------------------------------------------------- */
static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg)
{
struct vivid_dev *dev = (struct vivid_dev *)info->par;
switch (cmd) {
case FBIOGET_VBLANK: {
struct fb_vblank vblank;
memset(&vblank, 0, sizeof(vblank));
vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT |
FB_VBLANK_HAVE_VSYNC;
vblank.count = 0;
vblank.vcount = 0;
vblank.hcount = 0;
if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank)))
return -EFAULT;
return 0;
}
default:
dprintk(dev, 1, "Unknown ioctl %08x\n", cmd);
return -EINVAL;
}
return 0;
}
/* Framebuffer device handling */
static int vivid_fb_set_var(struct vivid_dev *dev, struct fb_var_screeninfo *var)
{
dprintk(dev, 1, "vivid_fb_set_var\n");
if (var->bits_per_pixel != 16) {
dprintk(dev, 1, "vivid_fb_set_var - Invalid bpp\n");
return -EINVAL;
}
dev->display_byte_stride = var->xres * dev->bytes_per_pixel;
return 0;
}
static int vivid_fb_get_fix(struct vivid_dev *dev, struct fb_fix_screeninfo *fix)
{
dprintk(dev, 1, "vivid_fb_get_fix\n");
memset(fix, 0, sizeof(struct fb_fix_screeninfo));
strlcpy(fix->id, "vioverlay fb", sizeof(fix->id));
fix->smem_start = dev->video_pbase;
fix->smem_len = dev->video_buffer_size;
fix->type = FB_TYPE_PACKED_PIXELS;
fix->visual = FB_VISUAL_TRUECOLOR;
fix->xpanstep = 1;
fix->ypanstep = 1;
fix->ywrapstep = 0;
fix->line_length = dev->display_byte_stride;
fix->accel = FB_ACCEL_NONE;
return 0;
}
/* Check the requested display mode, returning -EINVAL if we can't
handle it. */
static int _vivid_fb_check_var(struct fb_var_screeninfo *var, struct vivid_dev *dev)
{
dprintk(dev, 1, "vivid_fb_check_var\n");
var->bits_per_pixel = 16;
if (var->green.length == 5) {
var->red.offset = 10;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 5;
var->blue.offset = 0;
var->blue.length = 5;
var->transp.offset = 15;
var->transp.length = 1;
} else {
var->red.offset = 11;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.offset = 0;
var->blue.length = 5;
var->transp.offset = 0;
var->transp.length = 0;
}
var->xoffset = var->yoffset = 0;
var->left_margin = var->upper_margin = 0;
var->nonstd = 0;
var->vmode &= ~FB_VMODE_MASK;
var->vmode = FB_VMODE_NONINTERLACED;
/* Dummy values */
var->hsync_len = 24;
var->vsync_len = 2;
var->pixclock = 84316;
var->right_margin = 776;
var->lower_margin = 591;
return 0;
}
static int vivid_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct vivid_dev *dev = (struct vivid_dev *) info->par;
dprintk(dev, 1, "vivid_fb_check_var\n");
return _vivid_fb_check_var(var, dev);
}
static int vivid_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info)
{
return 0;
}
static int vivid_fb_set_par(struct fb_info *info)
{
int rc = 0;
struct vivid_dev *dev = (struct vivid_dev *) info->par;
dprintk(dev, 1, "vivid_fb_set_par\n");
rc = vivid_fb_set_var(dev, &info->var);
vivid_fb_get_fix(dev, &info->fix);
return rc;
}
static int vivid_fb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
u32 color, *palette;
if (regno >= info->cmap.len)
return -EINVAL;
color = ((transp & 0xFF00) << 16) | ((red & 0xFF00) << 8) |
(green & 0xFF00) | ((blue & 0xFF00) >> 8);
if (regno >= 16)
return -EINVAL;
palette = info->pseudo_palette;
if (info->var.bits_per_pixel == 16) {
switch (info->var.green.length) {
case 6:
color = (red & 0xf800) |
((green & 0xfc00) >> 5) |
((blue & 0xf800) >> 11);
break;
case 5:
color = ((red & 0xf800) >> 1) |
((green & 0xf800) >> 6) |
((blue & 0xf800) >> 11) |
(transp ? 0x8000 : 0);
break;
}
}
palette[regno] = color;
return 0;
}
/* We don't really support blanking. All this does is enable or
disable the OSD. */
static int vivid_fb_blank(int blank_mode, struct fb_info *info)
{
struct vivid_dev *dev = (struct vivid_dev *)info->par;
dprintk(dev, 1, "Set blanking mode : %d\n", blank_mode);
switch (blank_mode) {
case FB_BLANK_UNBLANK:
break;
case FB_BLANK_NORMAL:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_POWERDOWN:
break;
}
return 0;
}
static struct fb_ops vivid_fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = vivid_fb_check_var,
.fb_set_par = vivid_fb_set_par,
.fb_setcolreg = vivid_fb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_cursor = NULL,
.fb_ioctl = vivid_fb_ioctl,
.fb_pan_display = vivid_fb_pan_display,
.fb_blank = vivid_fb_blank,
};
/* Initialization */
/* Setup our initial video mode */
static int vivid_fb_init_vidmode(struct vivid_dev *dev)
{
struct v4l2_rect start_window;
/* Color mode */
dev->bits_per_pixel = 16;
dev->bytes_per_pixel = dev->bits_per_pixel / 8;
start_window.width = MAX_OSD_WIDTH;
start_window.left = 0;
dev->display_byte_stride = start_window.width * dev->bytes_per_pixel;
/* Vertical size & position */
start_window.height = MAX_OSD_HEIGHT;
start_window.top = 0;
dev->display_width = start_window.width;
dev->display_height = start_window.height;
/* Generate a valid fb_var_screeninfo */
dev->fb_defined.xres = dev->display_width;
dev->fb_defined.yres = dev->display_height;
dev->fb_defined.xres_virtual = dev->display_width;
dev->fb_defined.yres_virtual = dev->display_height;
dev->fb_defined.bits_per_pixel = dev->bits_per_pixel;
dev->fb_defined.vmode = FB_VMODE_NONINTERLACED;
dev->fb_defined.left_margin = start_window.left + 1;
dev->fb_defined.upper_margin = start_window.top + 1;
dev->fb_defined.accel_flags = FB_ACCEL_NONE;
dev->fb_defined.nonstd = 0;
/* set default to 1:5:5:5 */
dev->fb_defined.green.length = 5;
/* We've filled in the most data, let the usual mode check
routine fill in the rest. */
_vivid_fb_check_var(&dev->fb_defined, dev);
/* Generate valid fb_fix_screeninfo */
vivid_fb_get_fix(dev, &dev->fb_fix);
/* Generate valid fb_info */
dev->fb_info.node = -1;
dev->fb_info.flags = FBINFO_FLAG_DEFAULT;
dev->fb_info.fbops = &vivid_fb_ops;
dev->fb_info.par = dev;
dev->fb_info.var = dev->fb_defined;
dev->fb_info.fix = dev->fb_fix;
dev->fb_info.screen_base = (u8 __iomem *)dev->video_vbase;
dev->fb_info.fbops = &vivid_fb_ops;
/* Supply some monitor specs. Bogus values will do for now */
dev->fb_info.monspecs.hfmin = 8000;
dev->fb_info.monspecs.hfmax = 70000;
dev->fb_info.monspecs.vfmin = 10;
dev->fb_info.monspecs.vfmax = 100;
/* Allocate color map */
if (fb_alloc_cmap(&dev->fb_info.cmap, 256, 1)) {
pr_err("abort, unable to alloc cmap\n");
return -ENOMEM;
}
/* Allocate the pseudo palette */
dev->fb_info.pseudo_palette = kmalloc_array(16, sizeof(u32), GFP_KERNEL);
return dev->fb_info.pseudo_palette ? 0 : -ENOMEM;
}
/* Release any memory we've grabbed */
void vivid_fb_release_buffers(struct vivid_dev *dev)
{
if (dev->video_vbase == NULL)
return;
/* Release cmap */
if (dev->fb_info.cmap.len)
fb_dealloc_cmap(&dev->fb_info.cmap);
/* Release pseudo palette */
kfree(dev->fb_info.pseudo_palette);
kfree((void *)dev->video_vbase);
}
/* Initialize the specified card */
int vivid_fb_init(struct vivid_dev *dev)
{
int ret;
dev->video_buffer_size = MAX_OSD_HEIGHT * MAX_OSD_WIDTH * 2;
dev->video_vbase = kzalloc(dev->video_buffer_size, GFP_KERNEL | GFP_DMA32);
if (dev->video_vbase == NULL)
return -ENOMEM;
dev->video_pbase = virt_to_phys(dev->video_vbase);
pr_info("Framebuffer at 0x%lx, mapped to 0x%p, size %dk\n",
dev->video_pbase, dev->video_vbase,
dev->video_buffer_size / 1024);
/* Set the startup video mode information */
ret = vivid_fb_init_vidmode(dev);
if (ret) {
vivid_fb_release_buffers(dev);
return ret;
}
vivid_clear_fb(dev);
/* Register the framebuffer */
if (register_framebuffer(&dev->fb_info) < 0) {
vivid_fb_release_buffers(dev);
return -EINVAL;
}
/* Set the card to the requested mode */
vivid_fb_set_par(&dev->fb_info);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1765_0 |
crossvul-cpp_data_bad_2286_1 | /*
* Generic address resultion entity
*
* Authors:
* net_random Alan Cox
* net_ratelimit Andi Kleen
* in{4,6}_pton YOSHIFUJI Hideaki, Copyright (C)2006 USAGI/WIDE Project
*
* Created by Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/ctype.h>
#include <linux/inet.h>
#include <linux/mm.h>
#include <linux/net.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/percpu.h>
#include <linux/init.h>
#include <linux/ratelimit.h>
#include <net/sock.h>
#include <net/net_ratelimit.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
int net_msg_warn __read_mostly = 1;
EXPORT_SYMBOL(net_msg_warn);
DEFINE_RATELIMIT_STATE(net_ratelimit_state, 5 * HZ, 10);
/*
* All net warning printk()s should be guarded by this function.
*/
int net_ratelimit(void)
{
return __ratelimit(&net_ratelimit_state);
}
EXPORT_SYMBOL(net_ratelimit);
/*
* Convert an ASCII string to binary IP.
* This is outside of net/ipv4/ because various code that uses IP addresses
* is otherwise not dependent on the TCP/IP stack.
*/
__be32 in_aton(const char *str)
{
unsigned long l;
unsigned int val;
int i;
l = 0;
for (i = 0; i < 4; i++) {
l <<= 8;
if (*str != '\0') {
val = 0;
while (*str != '\0' && *str != '.' && *str != '\n') {
val *= 10;
val += *str - '0';
str++;
}
l |= val;
if (*str != '\0')
str++;
}
}
return htonl(l);
}
EXPORT_SYMBOL(in_aton);
#define IN6PTON_XDIGIT 0x00010000
#define IN6PTON_DIGIT 0x00020000
#define IN6PTON_COLON_MASK 0x00700000
#define IN6PTON_COLON_1 0x00100000 /* single : requested */
#define IN6PTON_COLON_2 0x00200000 /* second : requested */
#define IN6PTON_COLON_1_2 0x00400000 /* :: requested */
#define IN6PTON_DOT 0x00800000 /* . */
#define IN6PTON_DELIM 0x10000000
#define IN6PTON_NULL 0x20000000 /* first/tail */
#define IN6PTON_UNKNOWN 0x40000000
static inline int xdigit2bin(char c, int delim)
{
int val;
if (c == delim || c == '\0')
return IN6PTON_DELIM;
if (c == ':')
return IN6PTON_COLON_MASK;
if (c == '.')
return IN6PTON_DOT;
val = hex_to_bin(c);
if (val >= 0)
return val | IN6PTON_XDIGIT | (val < 10 ? IN6PTON_DIGIT : 0);
if (delim == -1)
return IN6PTON_DELIM;
return IN6PTON_UNKNOWN;
}
/**
* in4_pton - convert an IPv4 address from literal to binary representation
* @src: the start of the IPv4 address string
* @srclen: the length of the string, -1 means strlen(src)
* @dst: the binary (u8[4] array) representation of the IPv4 address
* @delim: the delimiter of the IPv4 address in @src, -1 means no delimiter
* @end: A pointer to the end of the parsed string will be placed here
*
* Return one on success, return zero when any error occurs
* and @end will point to the end of the parsed string.
*
*/
int in4_pton(const char *src, int srclen,
u8 *dst,
int delim, const char **end)
{
const char *s;
u8 *d;
u8 dbuf[4];
int ret = 0;
int i;
int w = 0;
if (srclen < 0)
srclen = strlen(src);
s = src;
d = dbuf;
i = 0;
while(1) {
int c;
c = xdigit2bin(srclen > 0 ? *s : '\0', delim);
if (!(c & (IN6PTON_DIGIT | IN6PTON_DOT | IN6PTON_DELIM | IN6PTON_COLON_MASK))) {
goto out;
}
if (c & (IN6PTON_DOT | IN6PTON_DELIM | IN6PTON_COLON_MASK)) {
if (w == 0)
goto out;
*d++ = w & 0xff;
w = 0;
i++;
if (c & (IN6PTON_DELIM | IN6PTON_COLON_MASK)) {
if (i != 4)
goto out;
break;
}
goto cont;
}
w = (w * 10) + c;
if ((w & 0xffff) > 255) {
goto out;
}
cont:
if (i >= 4)
goto out;
s++;
srclen--;
}
ret = 1;
memcpy(dst, dbuf, sizeof(dbuf));
out:
if (end)
*end = s;
return ret;
}
EXPORT_SYMBOL(in4_pton);
/**
* in6_pton - convert an IPv6 address from literal to binary representation
* @src: the start of the IPv6 address string
* @srclen: the length of the string, -1 means strlen(src)
* @dst: the binary (u8[16] array) representation of the IPv6 address
* @delim: the delimiter of the IPv6 address in @src, -1 means no delimiter
* @end: A pointer to the end of the parsed string will be placed here
*
* Return one on success, return zero when any error occurs
* and @end will point to the end of the parsed string.
*
*/
int in6_pton(const char *src, int srclen,
u8 *dst,
int delim, const char **end)
{
const char *s, *tok = NULL;
u8 *d, *dc = NULL;
u8 dbuf[16];
int ret = 0;
int i;
int state = IN6PTON_COLON_1_2 | IN6PTON_XDIGIT | IN6PTON_NULL;
int w = 0;
memset(dbuf, 0, sizeof(dbuf));
s = src;
d = dbuf;
if (srclen < 0)
srclen = strlen(src);
while (1) {
int c;
c = xdigit2bin(srclen > 0 ? *s : '\0', delim);
if (!(c & state))
goto out;
if (c & (IN6PTON_DELIM | IN6PTON_COLON_MASK)) {
/* process one 16-bit word */
if (!(state & IN6PTON_NULL)) {
*d++ = (w >> 8) & 0xff;
*d++ = w & 0xff;
}
w = 0;
if (c & IN6PTON_DELIM) {
/* We've processed last word */
break;
}
/*
* COLON_1 => XDIGIT
* COLON_2 => XDIGIT|DELIM
* COLON_1_2 => COLON_2
*/
switch (state & IN6PTON_COLON_MASK) {
case IN6PTON_COLON_2:
dc = d;
state = IN6PTON_XDIGIT | IN6PTON_DELIM;
if (dc - dbuf >= sizeof(dbuf))
state |= IN6PTON_NULL;
break;
case IN6PTON_COLON_1|IN6PTON_COLON_1_2:
state = IN6PTON_XDIGIT | IN6PTON_COLON_2;
break;
case IN6PTON_COLON_1:
state = IN6PTON_XDIGIT;
break;
case IN6PTON_COLON_1_2:
state = IN6PTON_COLON_2;
break;
default:
state = 0;
}
tok = s + 1;
goto cont;
}
if (c & IN6PTON_DOT) {
ret = in4_pton(tok ? tok : s, srclen + (int)(s - tok), d, delim, &s);
if (ret > 0) {
d += 4;
break;
}
goto out;
}
w = (w << 4) | (0xff & c);
state = IN6PTON_COLON_1 | IN6PTON_DELIM;
if (!(w & 0xf000)) {
state |= IN6PTON_XDIGIT;
}
if (!dc && d + 2 < dbuf + sizeof(dbuf)) {
state |= IN6PTON_COLON_1_2;
state &= ~IN6PTON_DELIM;
}
if (d + 2 >= dbuf + sizeof(dbuf)) {
state &= ~(IN6PTON_COLON_1|IN6PTON_COLON_1_2);
}
cont:
if ((dc && d + 4 < dbuf + sizeof(dbuf)) ||
d + 4 == dbuf + sizeof(dbuf)) {
state |= IN6PTON_DOT;
}
if (d >= dbuf + sizeof(dbuf)) {
state &= ~(IN6PTON_XDIGIT|IN6PTON_COLON_MASK);
}
s++;
srclen--;
}
i = 15; d--;
if (dc) {
while(d >= dc)
dst[i--] = *d--;
while(i >= dc - dbuf)
dst[i--] = 0;
while(i >= 0)
dst[i--] = *d--;
} else
memcpy(dst, dbuf, sizeof(dbuf));
ret = 1;
out:
if (end)
*end = s;
return ret;
}
EXPORT_SYMBOL(in6_pton);
void inet_proto_csum_replace4(__sum16 *sum, struct sk_buff *skb,
__be32 from, __be32 to, int pseudohdr)
{
__be32 diff[] = { ~from, to };
if (skb->ip_summed != CHECKSUM_PARTIAL) {
*sum = csum_fold(csum_partial(diff, sizeof(diff),
~csum_unfold(*sum)));
if (skb->ip_summed == CHECKSUM_COMPLETE && pseudohdr)
skb->csum = ~csum_partial(diff, sizeof(diff),
~skb->csum);
} else if (pseudohdr)
*sum = ~csum_fold(csum_partial(diff, sizeof(diff),
csum_unfold(*sum)));
}
EXPORT_SYMBOL(inet_proto_csum_replace4);
void inet_proto_csum_replace16(__sum16 *sum, struct sk_buff *skb,
const __be32 *from, const __be32 *to,
int pseudohdr)
{
__be32 diff[] = {
~from[0], ~from[1], ~from[2], ~from[3],
to[0], to[1], to[2], to[3],
};
if (skb->ip_summed != CHECKSUM_PARTIAL) {
*sum = csum_fold(csum_partial(diff, sizeof(diff),
~csum_unfold(*sum)));
if (skb->ip_summed == CHECKSUM_COMPLETE && pseudohdr)
skb->csum = ~csum_partial(diff, sizeof(diff),
~skb->csum);
} else if (pseudohdr)
*sum = ~csum_fold(csum_partial(diff, sizeof(diff),
csum_unfold(*sum)));
}
EXPORT_SYMBOL(inet_proto_csum_replace16);
struct __net_random_once_work {
struct work_struct work;
struct static_key *key;
};
static void __net_random_once_deferred(struct work_struct *w)
{
struct __net_random_once_work *work =
container_of(w, struct __net_random_once_work, work);
if (!static_key_enabled(work->key))
static_key_slow_inc(work->key);
kfree(work);
}
static void __net_random_once_disable_jump(struct static_key *key)
{
struct __net_random_once_work *w;
w = kmalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return;
INIT_WORK(&w->work, __net_random_once_deferred);
w->key = key;
schedule_work(&w->work);
}
bool __net_get_random_once(void *buf, int nbytes, bool *done,
struct static_key *done_key)
{
static DEFINE_SPINLOCK(lock);
unsigned long flags;
spin_lock_irqsave(&lock, flags);
if (*done) {
spin_unlock_irqrestore(&lock, flags);
return false;
}
get_random_bytes(buf, nbytes);
*done = true;
spin_unlock_irqrestore(&lock, flags);
__net_random_once_disable_jump(done_key);
return true;
}
EXPORT_SYMBOL(__net_get_random_once);
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2286_1 |
crossvul-cpp_data_good_5681_0 | /* net/atm/common.c - ATM sockets (common part for PVC and SVC) */
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/net.h> /* struct socket, struct proto_ops */
#include <linux/atm.h> /* ATM stuff */
#include <linux/atmdev.h>
#include <linux/socket.h> /* SOL_SOCKET */
#include <linux/errno.h> /* error codes */
#include <linux/capability.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/time.h> /* struct timeval */
#include <linux/skbuff.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/sock.h> /* struct sock */
#include <linux/uaccess.h>
#include <linux/poll.h>
#include <linux/atomic.h>
#include "resources.h" /* atm_find_dev */
#include "common.h" /* prototypes */
#include "protocols.h" /* atm_init_<transport> */
#include "addr.h" /* address registry */
#include "signaling.h" /* for WAITING and sigd_attach */
struct hlist_head vcc_hash[VCC_HTABLE_SIZE];
EXPORT_SYMBOL(vcc_hash);
DEFINE_RWLOCK(vcc_sklist_lock);
EXPORT_SYMBOL(vcc_sklist_lock);
static ATOMIC_NOTIFIER_HEAD(atm_dev_notify_chain);
static void __vcc_insert_socket(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
struct hlist_head *head = &vcc_hash[vcc->vci & (VCC_HTABLE_SIZE - 1)];
sk->sk_hash = vcc->vci & (VCC_HTABLE_SIZE - 1);
sk_add_node(sk, head);
}
void vcc_insert_socket(struct sock *sk)
{
write_lock_irq(&vcc_sklist_lock);
__vcc_insert_socket(sk);
write_unlock_irq(&vcc_sklist_lock);
}
EXPORT_SYMBOL(vcc_insert_socket);
static void vcc_remove_socket(struct sock *sk)
{
write_lock_irq(&vcc_sklist_lock);
sk_del_node_init(sk);
write_unlock_irq(&vcc_sklist_lock);
}
static struct sk_buff *alloc_tx(struct atm_vcc *vcc, unsigned int size)
{
struct sk_buff *skb;
struct sock *sk = sk_atm(vcc);
if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) {
pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n",
sk_wmem_alloc_get(sk), size, sk->sk_sndbuf);
return NULL;
}
while (!(skb = alloc_skb(size, GFP_KERNEL)))
schedule();
pr_debug("%d += %d\n", sk_wmem_alloc_get(sk), skb->truesize);
atomic_add(skb->truesize, &sk->sk_wmem_alloc);
return skb;
}
static void vcc_sock_destruct(struct sock *sk)
{
if (atomic_read(&sk->sk_rmem_alloc))
printk(KERN_DEBUG "%s: rmem leakage (%d bytes) detected.\n",
__func__, atomic_read(&sk->sk_rmem_alloc));
if (atomic_read(&sk->sk_wmem_alloc))
printk(KERN_DEBUG "%s: wmem leakage (%d bytes) detected.\n",
__func__, atomic_read(&sk->sk_wmem_alloc));
}
static void vcc_def_wakeup(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up(&wq->wait);
rcu_read_unlock();
}
static inline int vcc_writable(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
return (vcc->qos.txtp.max_sdu +
atomic_read(&sk->sk_wmem_alloc)) <= sk->sk_sndbuf;
}
static void vcc_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (vcc_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible(&wq->wait);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
static void vcc_release_cb(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
if (vcc->release_cb)
vcc->release_cb(vcc);
}
static struct proto vcc_proto = {
.name = "VCC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct atm_vcc),
.release_cb = vcc_release_cb,
};
int vcc_create(struct net *net, struct socket *sock, int protocol, int family)
{
struct sock *sk;
struct atm_vcc *vcc;
sock->sk = NULL;
if (sock->type == SOCK_STREAM)
return -EINVAL;
sk = sk_alloc(net, family, GFP_KERNEL, &vcc_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sk->sk_state_change = vcc_def_wakeup;
sk->sk_write_space = vcc_write_space;
vcc = atm_sk(sk);
vcc->dev = NULL;
memset(&vcc->local, 0, sizeof(struct sockaddr_atmsvc));
memset(&vcc->remote, 0, sizeof(struct sockaddr_atmsvc));
vcc->qos.txtp.max_sdu = 1 << 16; /* for meta VCs */
atomic_set(&sk->sk_wmem_alloc, 1);
atomic_set(&sk->sk_rmem_alloc, 0);
vcc->push = NULL;
vcc->pop = NULL;
vcc->owner = NULL;
vcc->push_oam = NULL;
vcc->release_cb = NULL;
vcc->vpi = vcc->vci = 0; /* no VCI/VPI yet */
vcc->atm_options = vcc->aal_options = 0;
sk->sk_destruct = vcc_sock_destruct;
return 0;
}
static void vcc_destroy_socket(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
struct sk_buff *skb;
set_bit(ATM_VF_CLOSE, &vcc->flags);
clear_bit(ATM_VF_READY, &vcc->flags);
if (vcc->dev) {
if (vcc->dev->ops->close)
vcc->dev->ops->close(vcc);
if (vcc->push)
vcc->push(vcc, NULL); /* atmarpd has no push */
module_put(vcc->owner);
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
atm_return(vcc, skb->truesize);
kfree_skb(skb);
}
module_put(vcc->dev->ops->owner);
atm_dev_put(vcc->dev);
}
vcc_remove_socket(sk);
}
int vcc_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (sk) {
lock_sock(sk);
vcc_destroy_socket(sock->sk);
release_sock(sk);
sock_put(sk);
}
return 0;
}
void vcc_release_async(struct atm_vcc *vcc, int reply)
{
struct sock *sk = sk_atm(vcc);
set_bit(ATM_VF_CLOSE, &vcc->flags);
sk->sk_shutdown |= RCV_SHUTDOWN;
sk->sk_err = -reply;
clear_bit(ATM_VF_WAITING, &vcc->flags);
sk->sk_state_change(sk);
}
EXPORT_SYMBOL(vcc_release_async);
void vcc_process_recv_queue(struct atm_vcc *vcc)
{
struct sk_buff_head queue, *rq;
struct sk_buff *skb, *tmp;
unsigned long flags;
__skb_queue_head_init(&queue);
rq = &sk_atm(vcc)->sk_receive_queue;
spin_lock_irqsave(&rq->lock, flags);
skb_queue_splice_init(rq, &queue);
spin_unlock_irqrestore(&rq->lock, flags);
skb_queue_walk_safe(&queue, skb, tmp) {
__skb_unlink(skb, &queue);
vcc->push(vcc, skb);
}
}
EXPORT_SYMBOL(vcc_process_recv_queue);
void atm_dev_signal_change(struct atm_dev *dev, char signal)
{
pr_debug("%s signal=%d dev=%p number=%d dev->signal=%d\n",
__func__, signal, dev, dev->number, dev->signal);
/* atm driver sending invalid signal */
WARN_ON(signal < ATM_PHY_SIG_LOST || signal > ATM_PHY_SIG_FOUND);
if (dev->signal == signal)
return; /* no change */
dev->signal = signal;
atomic_notifier_call_chain(&atm_dev_notify_chain, signal, dev);
}
EXPORT_SYMBOL(atm_dev_signal_change);
void atm_dev_release_vccs(struct atm_dev *dev)
{
int i;
write_lock_irq(&vcc_sklist_lock);
for (i = 0; i < VCC_HTABLE_SIZE; i++) {
struct hlist_head *head = &vcc_hash[i];
struct hlist_node *tmp;
struct sock *s;
struct atm_vcc *vcc;
sk_for_each_safe(s, tmp, head) {
vcc = atm_sk(s);
if (vcc->dev == dev) {
vcc_release_async(vcc, -EPIPE);
sk_del_node_init(s);
}
}
}
write_unlock_irq(&vcc_sklist_lock);
}
EXPORT_SYMBOL(atm_dev_release_vccs);
static int adjust_tp(struct atm_trafprm *tp, unsigned char aal)
{
int max_sdu;
if (!tp->traffic_class)
return 0;
switch (aal) {
case ATM_AAL0:
max_sdu = ATM_CELL_SIZE-1;
break;
case ATM_AAL34:
max_sdu = ATM_MAX_AAL34_PDU;
break;
default:
pr_warning("AAL problems ... (%d)\n", aal);
/* fall through */
case ATM_AAL5:
max_sdu = ATM_MAX_AAL5_PDU;
}
if (!tp->max_sdu)
tp->max_sdu = max_sdu;
else if (tp->max_sdu > max_sdu)
return -EINVAL;
if (!tp->max_cdv)
tp->max_cdv = ATM_MAX_CDV;
return 0;
}
static int check_ci(const struct atm_vcc *vcc, short vpi, int vci)
{
struct hlist_head *head = &vcc_hash[vci & (VCC_HTABLE_SIZE - 1)];
struct sock *s;
struct atm_vcc *walk;
sk_for_each(s, head) {
walk = atm_sk(s);
if (walk->dev != vcc->dev)
continue;
if (test_bit(ATM_VF_ADDR, &walk->flags) && walk->vpi == vpi &&
walk->vci == vci && ((walk->qos.txtp.traffic_class !=
ATM_NONE && vcc->qos.txtp.traffic_class != ATM_NONE) ||
(walk->qos.rxtp.traffic_class != ATM_NONE &&
vcc->qos.rxtp.traffic_class != ATM_NONE)))
return -EADDRINUSE;
}
/* allow VCCs with same VPI/VCI iff they don't collide on
TX/RX (but we may refuse such sharing for other reasons,
e.g. if protocol requires to have both channels) */
return 0;
}
static int find_ci(const struct atm_vcc *vcc, short *vpi, int *vci)
{
static short p; /* poor man's per-device cache */
static int c;
short old_p;
int old_c;
int err;
if (*vpi != ATM_VPI_ANY && *vci != ATM_VCI_ANY) {
err = check_ci(vcc, *vpi, *vci);
return err;
}
/* last scan may have left values out of bounds for current device */
if (*vpi != ATM_VPI_ANY)
p = *vpi;
else if (p >= 1 << vcc->dev->ci_range.vpi_bits)
p = 0;
if (*vci != ATM_VCI_ANY)
c = *vci;
else if (c < ATM_NOT_RSV_VCI || c >= 1 << vcc->dev->ci_range.vci_bits)
c = ATM_NOT_RSV_VCI;
old_p = p;
old_c = c;
do {
if (!check_ci(vcc, p, c)) {
*vpi = p;
*vci = c;
return 0;
}
if (*vci == ATM_VCI_ANY) {
c++;
if (c >= 1 << vcc->dev->ci_range.vci_bits)
c = ATM_NOT_RSV_VCI;
}
if ((c == ATM_NOT_RSV_VCI || *vci != ATM_VCI_ANY) &&
*vpi == ATM_VPI_ANY) {
p++;
if (p >= 1 << vcc->dev->ci_range.vpi_bits)
p = 0;
}
} while (old_p != p || old_c != c);
return -EADDRINUSE;
}
static int __vcc_connect(struct atm_vcc *vcc, struct atm_dev *dev, short vpi,
int vci)
{
struct sock *sk = sk_atm(vcc);
int error;
if ((vpi != ATM_VPI_UNSPEC && vpi != ATM_VPI_ANY &&
vpi >> dev->ci_range.vpi_bits) || (vci != ATM_VCI_UNSPEC &&
vci != ATM_VCI_ANY && vci >> dev->ci_range.vci_bits))
return -EINVAL;
if (vci > 0 && vci < ATM_NOT_RSV_VCI && !capable(CAP_NET_BIND_SERVICE))
return -EPERM;
error = -ENODEV;
if (!try_module_get(dev->ops->owner))
return error;
vcc->dev = dev;
write_lock_irq(&vcc_sklist_lock);
if (test_bit(ATM_DF_REMOVED, &dev->flags) ||
(error = find_ci(vcc, &vpi, &vci))) {
write_unlock_irq(&vcc_sklist_lock);
goto fail_module_put;
}
vcc->vpi = vpi;
vcc->vci = vci;
__vcc_insert_socket(sk);
write_unlock_irq(&vcc_sklist_lock);
switch (vcc->qos.aal) {
case ATM_AAL0:
error = atm_init_aal0(vcc);
vcc->stats = &dev->stats.aal0;
break;
case ATM_AAL34:
error = atm_init_aal34(vcc);
vcc->stats = &dev->stats.aal34;
break;
case ATM_NO_AAL:
/* ATM_AAL5 is also used in the "0 for default" case */
vcc->qos.aal = ATM_AAL5;
/* fall through */
case ATM_AAL5:
error = atm_init_aal5(vcc);
vcc->stats = &dev->stats.aal5;
break;
default:
error = -EPROTOTYPE;
}
if (!error)
error = adjust_tp(&vcc->qos.txtp, vcc->qos.aal);
if (!error)
error = adjust_tp(&vcc->qos.rxtp, vcc->qos.aal);
if (error)
goto fail;
pr_debug("VCC %d.%d, AAL %d\n", vpi, vci, vcc->qos.aal);
pr_debug(" TX: %d, PCR %d..%d, SDU %d\n",
vcc->qos.txtp.traffic_class,
vcc->qos.txtp.min_pcr,
vcc->qos.txtp.max_pcr,
vcc->qos.txtp.max_sdu);
pr_debug(" RX: %d, PCR %d..%d, SDU %d\n",
vcc->qos.rxtp.traffic_class,
vcc->qos.rxtp.min_pcr,
vcc->qos.rxtp.max_pcr,
vcc->qos.rxtp.max_sdu);
if (dev->ops->open) {
error = dev->ops->open(vcc);
if (error)
goto fail;
}
return 0;
fail:
vcc_remove_socket(sk);
fail_module_put:
module_put(dev->ops->owner);
/* ensure we get dev module ref count correct */
vcc->dev = NULL;
return error;
}
int vcc_connect(struct socket *sock, int itf, short vpi, int vci)
{
struct atm_dev *dev;
struct atm_vcc *vcc = ATM_SD(sock);
int error;
pr_debug("(vpi %d, vci %d)\n", vpi, vci);
if (sock->state == SS_CONNECTED)
return -EISCONN;
if (sock->state != SS_UNCONNECTED)
return -EINVAL;
if (!(vpi || vci))
return -EINVAL;
if (vpi != ATM_VPI_UNSPEC && vci != ATM_VCI_UNSPEC)
clear_bit(ATM_VF_PARTIAL, &vcc->flags);
else
if (test_bit(ATM_VF_PARTIAL, &vcc->flags))
return -EINVAL;
pr_debug("(TX: cl %d,bw %d-%d,sdu %d; "
"RX: cl %d,bw %d-%d,sdu %d,AAL %s%d)\n",
vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr,
vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu,
vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr,
vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu,
vcc->qos.aal == ATM_AAL5 ? "" :
vcc->qos.aal == ATM_AAL0 ? "" : " ??? code ",
vcc->qos.aal == ATM_AAL0 ? 0 : vcc->qos.aal);
if (!test_bit(ATM_VF_HASQOS, &vcc->flags))
return -EBADFD;
if (vcc->qos.txtp.traffic_class == ATM_ANYCLASS ||
vcc->qos.rxtp.traffic_class == ATM_ANYCLASS)
return -EINVAL;
if (likely(itf != ATM_ITF_ANY)) {
dev = try_then_request_module(atm_dev_lookup(itf),
"atm-device-%d", itf);
} else {
dev = NULL;
mutex_lock(&atm_dev_mutex);
if (!list_empty(&atm_devs)) {
dev = list_entry(atm_devs.next,
struct atm_dev, dev_list);
atm_dev_hold(dev);
}
mutex_unlock(&atm_dev_mutex);
}
if (!dev)
return -ENODEV;
error = __vcc_connect(vcc, dev, vpi, vci);
if (error) {
atm_dev_put(dev);
return error;
}
if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC)
set_bit(ATM_VF_PARTIAL, &vcc->flags);
if (test_bit(ATM_VF_READY, &ATM_SD(sock)->flags))
sock->state = SS_CONNECTED;
return 0;
}
int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
msg->msg_namelen = 0;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
int vcc_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t total_len)
{
struct sock *sk = sock->sk;
DEFINE_WAIT(wait);
struct atm_vcc *vcc;
struct sk_buff *skb;
int eff, error;
const void __user *buff;
int size;
lock_sock(sk);
if (sock->state != SS_CONNECTED) {
error = -ENOTCONN;
goto out;
}
if (m->msg_name) {
error = -EISCONN;
goto out;
}
if (m->msg_iovlen != 1) {
error = -ENOSYS; /* fix this later @@@ */
goto out;
}
buff = m->msg_iov->iov_base;
size = m->msg_iov->iov_len;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags)) {
error = -EPIPE;
send_sig(SIGPIPE, current, 0);
goto out;
}
if (!size) {
error = 0;
goto out;
}
if (size < 0 || size > vcc->qos.txtp.max_sdu) {
error = -EMSGSIZE;
goto out;
}
eff = (size+3) & ~3; /* align to word boundary */
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
error = 0;
while (!(skb = alloc_tx(vcc, eff))) {
if (m->msg_flags & MSG_DONTWAIT) {
error = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
error = -ERESTARTSYS;
break;
}
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags)) {
error = -EPIPE;
send_sig(SIGPIPE, current, 0);
break;
}
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
}
finish_wait(sk_sleep(sk), &wait);
if (error)
goto out;
skb->dev = NULL; /* for paths shared with net_device interfaces */
ATM_SKB(skb)->atm_options = vcc->atm_options;
if (copy_from_user(skb_put(skb, size), buff, size)) {
kfree_skb(skb);
error = -EFAULT;
goto out;
}
if (eff != size)
memset(skb->data + size, 0, eff-size);
error = vcc->dev->ops->send(vcc, skb);
error = error ? error : size;
out:
release_sock(sk);
return error;
}
unsigned int vcc_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
vcc = ATM_SD(sock);
/* exceptional events */
if (sk->sk_err)
mask = POLLERR;
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags))
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* writable? */
if (sock->state == SS_CONNECTING &&
test_bit(ATM_VF_WAITING, &vcc->flags))
return mask;
if (vcc->qos.txtp.traffic_class != ATM_NONE &&
vcc_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static int atm_change_qos(struct atm_vcc *vcc, struct atm_qos *qos)
{
int error;
/*
* Don't let the QoS change the already connected AAL type nor the
* traffic class.
*/
if (qos->aal != vcc->qos.aal ||
qos->rxtp.traffic_class != vcc->qos.rxtp.traffic_class ||
qos->txtp.traffic_class != vcc->qos.txtp.traffic_class)
return -EINVAL;
error = adjust_tp(&qos->txtp, qos->aal);
if (!error)
error = adjust_tp(&qos->rxtp, qos->aal);
if (error)
return error;
if (!vcc->dev->ops->change_qos)
return -EOPNOTSUPP;
if (sk_atm(vcc)->sk_family == AF_ATMPVC)
return vcc->dev->ops->change_qos(vcc, qos, ATM_MF_SET);
return svc_change_qos(vcc, qos);
}
static int check_tp(const struct atm_trafprm *tp)
{
/* @@@ Should be merged with adjust_tp */
if (!tp->traffic_class || tp->traffic_class == ATM_ANYCLASS)
return 0;
if (tp->traffic_class != ATM_UBR && !tp->min_pcr && !tp->pcr &&
!tp->max_pcr)
return -EINVAL;
if (tp->min_pcr == ATM_MAX_PCR)
return -EINVAL;
if (tp->min_pcr && tp->max_pcr && tp->max_pcr != ATM_MAX_PCR &&
tp->min_pcr > tp->max_pcr)
return -EINVAL;
/*
* We allow pcr to be outside [min_pcr,max_pcr], because later
* adjustment may still push it in the valid range.
*/
return 0;
}
static int check_qos(const struct atm_qos *qos)
{
int error;
if (!qos->txtp.traffic_class && !qos->rxtp.traffic_class)
return -EINVAL;
if (qos->txtp.traffic_class != qos->rxtp.traffic_class &&
qos->txtp.traffic_class && qos->rxtp.traffic_class &&
qos->txtp.traffic_class != ATM_ANYCLASS &&
qos->rxtp.traffic_class != ATM_ANYCLASS)
return -EINVAL;
error = check_tp(&qos->txtp);
if (error)
return error;
return check_tp(&qos->rxtp);
}
int vcc_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct atm_vcc *vcc;
unsigned long value;
int error;
if (__SO_LEVEL_MATCH(optname, level) && optlen != __SO_SIZE(optname))
return -EINVAL;
vcc = ATM_SD(sock);
switch (optname) {
case SO_ATMQOS:
{
struct atm_qos qos;
if (copy_from_user(&qos, optval, sizeof(qos)))
return -EFAULT;
error = check_qos(&qos);
if (error)
return error;
if (sock->state == SS_CONNECTED)
return atm_change_qos(vcc, &qos);
if (sock->state != SS_UNCONNECTED)
return -EBADFD;
vcc->qos = qos;
set_bit(ATM_VF_HASQOS, &vcc->flags);
return 0;
}
case SO_SETCLP:
if (get_user(value, (unsigned long __user *)optval))
return -EFAULT;
if (value)
vcc->atm_options |= ATM_ATMOPT_CLP;
else
vcc->atm_options &= ~ATM_ATMOPT_CLP;
return 0;
default:
if (level == SOL_SOCKET)
return -EINVAL;
break;
}
if (!vcc->dev || !vcc->dev->ops->setsockopt)
return -EINVAL;
return vcc->dev->ops->setsockopt(vcc, level, optname, optval, optlen);
}
int vcc_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct atm_vcc *vcc;
int len;
if (get_user(len, optlen))
return -EFAULT;
if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname))
return -EINVAL;
vcc = ATM_SD(sock);
switch (optname) {
case SO_ATMQOS:
if (!test_bit(ATM_VF_HASQOS, &vcc->flags))
return -EINVAL;
return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos))
? -EFAULT : 0;
case SO_SETCLP:
return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0,
(unsigned long __user *)optval) ? -EFAULT : 0;
case SO_ATMPVC:
{
struct sockaddr_atmpvc pvc;
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
memset(&pvc, 0, sizeof(pvc));
pvc.sap_family = AF_ATMPVC;
pvc.sap_addr.itf = vcc->dev->number;
pvc.sap_addr.vpi = vcc->vpi;
pvc.sap_addr.vci = vcc->vci;
return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0;
}
default:
if (level == SOL_SOCKET)
return -EINVAL;
break;
}
if (!vcc->dev || !vcc->dev->ops->getsockopt)
return -EINVAL;
return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len);
}
int register_atmdevice_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&atm_dev_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(register_atmdevice_notifier);
void unregister_atmdevice_notifier(struct notifier_block *nb)
{
atomic_notifier_chain_unregister(&atm_dev_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(unregister_atmdevice_notifier);
static int __init atm_init(void)
{
int error;
error = proto_register(&vcc_proto, 0);
if (error < 0)
goto out;
error = atmpvc_init();
if (error < 0) {
pr_err("atmpvc_init() failed with %d\n", error);
goto out_unregister_vcc_proto;
}
error = atmsvc_init();
if (error < 0) {
pr_err("atmsvc_init() failed with %d\n", error);
goto out_atmpvc_exit;
}
error = atm_proc_init();
if (error < 0) {
pr_err("atm_proc_init() failed with %d\n", error);
goto out_atmsvc_exit;
}
error = atm_sysfs_init();
if (error < 0) {
pr_err("atm_sysfs_init() failed with %d\n", error);
goto out_atmproc_exit;
}
out:
return error;
out_atmproc_exit:
atm_proc_exit();
out_atmsvc_exit:
atmsvc_exit();
out_atmpvc_exit:
atmsvc_exit();
out_unregister_vcc_proto:
proto_unregister(&vcc_proto);
goto out;
}
static void __exit atm_exit(void)
{
atm_proc_exit();
atm_sysfs_exit();
atmsvc_exit();
atmpvc_exit();
proto_unregister(&vcc_proto);
}
subsys_initcall(atm_init);
module_exit(atm_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_ATMPVC);
MODULE_ALIAS_NETPROTO(PF_ATMSVC);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5681_0 |
crossvul-cpp_data_good_5058_0 | /*
* Timers abstract layer
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/string.h>
#include <sound/core.h>
#include <sound/timer.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/minors.h>
#include <sound/initval.h>
#include <linux/kmod.h>
#if IS_ENABLED(CONFIG_SND_HRTIMER)
#define DEFAULT_TIMER_LIMIT 4
#else
#define DEFAULT_TIMER_LIMIT 1
#endif
static int timer_limit = DEFAULT_TIMER_LIMIT;
static int timer_tstamp_monotonic = 1;
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("ALSA timer interface");
MODULE_LICENSE("GPL");
module_param(timer_limit, int, 0444);
MODULE_PARM_DESC(timer_limit, "Maximum global timers in system.");
module_param(timer_tstamp_monotonic, int, 0444);
MODULE_PARM_DESC(timer_tstamp_monotonic, "Use posix monotonic clock source for timestamps (default).");
MODULE_ALIAS_CHARDEV(CONFIG_SND_MAJOR, SNDRV_MINOR_TIMER);
MODULE_ALIAS("devname:snd/timer");
struct snd_timer_user {
struct snd_timer_instance *timeri;
int tread; /* enhanced read with timestamps and events */
unsigned long ticks;
unsigned long overrun;
int qhead;
int qtail;
int qused;
int queue_size;
bool disconnected;
struct snd_timer_read *queue;
struct snd_timer_tread *tqueue;
spinlock_t qlock;
unsigned long last_resolution;
unsigned int filter;
struct timespec tstamp; /* trigger tstamp */
wait_queue_head_t qchange_sleep;
struct fasync_struct *fasync;
struct mutex ioctl_lock;
};
/* list of timers */
static LIST_HEAD(snd_timer_list);
/* list of slave instances */
static LIST_HEAD(snd_timer_slave_list);
/* lock for slave active lists */
static DEFINE_SPINLOCK(slave_active_lock);
static DEFINE_MUTEX(register_mutex);
static int snd_timer_free(struct snd_timer *timer);
static int snd_timer_dev_free(struct snd_device *device);
static int snd_timer_dev_register(struct snd_device *device);
static int snd_timer_dev_disconnect(struct snd_device *device);
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left);
/*
* create a timer instance with the given owner string.
* when timer is not NULL, increments the module counter
*/
static struct snd_timer_instance *snd_timer_instance_new(char *owner,
struct snd_timer *timer)
{
struct snd_timer_instance *timeri;
timeri = kzalloc(sizeof(*timeri), GFP_KERNEL);
if (timeri == NULL)
return NULL;
timeri->owner = kstrdup(owner, GFP_KERNEL);
if (! timeri->owner) {
kfree(timeri);
return NULL;
}
INIT_LIST_HEAD(&timeri->open_list);
INIT_LIST_HEAD(&timeri->active_list);
INIT_LIST_HEAD(&timeri->ack_list);
INIT_LIST_HEAD(&timeri->slave_list_head);
INIT_LIST_HEAD(&timeri->slave_active_head);
timeri->timer = timer;
if (timer && !try_module_get(timer->module)) {
kfree(timeri->owner);
kfree(timeri);
return NULL;
}
return timeri;
}
/*
* find a timer instance from the given timer id
*/
static struct snd_timer *snd_timer_find(struct snd_timer_id *tid)
{
struct snd_timer *timer = NULL;
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->tmr_class != tid->dev_class)
continue;
if ((timer->tmr_class == SNDRV_TIMER_CLASS_CARD ||
timer->tmr_class == SNDRV_TIMER_CLASS_PCM) &&
(timer->card == NULL ||
timer->card->number != tid->card))
continue;
if (timer->tmr_device != tid->device)
continue;
if (timer->tmr_subdevice != tid->subdevice)
continue;
return timer;
}
return NULL;
}
#ifdef CONFIG_MODULES
static void snd_timer_request(struct snd_timer_id *tid)
{
switch (tid->dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
if (tid->device < timer_limit)
request_module("snd-timer-%i", tid->device);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (tid->card < snd_ecards_limit)
request_module("snd-card-%i", tid->card);
break;
default:
break;
}
}
#endif
/*
* look for a master instance matching with the slave id of the given slave.
* when found, relink the open_link of the slave.
*
* call this with register_mutex down.
*/
static void snd_timer_check_slave(struct snd_timer_instance *slave)
{
struct snd_timer *timer;
struct snd_timer_instance *master;
/* FIXME: it's really dumb to look up all entries.. */
list_for_each_entry(timer, &snd_timer_list, device_list) {
list_for_each_entry(master, &timer->open_list_head, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list,
&master->slave_list_head);
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
spin_unlock_irq(&slave_active_lock);
return;
}
}
}
}
/*
* look for slave instances matching with the slave id of the given master.
* when found, relink the open_link of slaves.
*
* call this with register_mutex down.
*/
static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
spin_lock(&master->timer->lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock(&master->timer->lock);
spin_unlock_irq(&slave_active_lock);
}
}
}
/*
* open a timer instance
* when opening a master, the slave id must be here given.
*/
int snd_timer_open(struct snd_timer_instance **ti,
char *owner, struct snd_timer_id *tid,
unsigned int slave_id)
{
struct snd_timer *timer;
struct snd_timer_instance *timeri = NULL;
if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {
/* open a slave instance */
if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||
tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {
pr_debug("ALSA: timer: invalid slave class %i\n",
tid->dev_sclass);
return -EINVAL;
}
mutex_lock(®ister_mutex);
timeri = snd_timer_instance_new(owner, NULL);
if (!timeri) {
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = tid->device;
timeri->flags |= SNDRV_TIMER_IFLG_SLAVE;
list_add_tail(&timeri->open_list, &snd_timer_slave_list);
snd_timer_check_slave(timeri);
mutex_unlock(®ister_mutex);
*ti = timeri;
return 0;
}
/* open a master instance */
mutex_lock(®ister_mutex);
timer = snd_timer_find(tid);
#ifdef CONFIG_MODULES
if (!timer) {
mutex_unlock(®ister_mutex);
snd_timer_request(tid);
mutex_lock(®ister_mutex);
timer = snd_timer_find(tid);
}
#endif
if (!timer) {
mutex_unlock(®ister_mutex);
return -ENODEV;
}
if (!list_empty(&timer->open_list_head)) {
timeri = list_entry(timer->open_list_head.next,
struct snd_timer_instance, open_list);
if (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {
mutex_unlock(®ister_mutex);
return -EBUSY;
}
}
timeri = snd_timer_instance_new(owner, timer);
if (!timeri) {
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
/* take a card refcount for safe disconnection */
if (timer->card)
get_device(&timer->card->card_dev);
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = slave_id;
if (list_empty(&timer->open_list_head) && timer->hw.open)
timer->hw.open(timer);
list_add_tail(&timeri->open_list, &timer->open_list_head);
snd_timer_check_master(timeri);
mutex_unlock(®ister_mutex);
*ti = timeri;
return 0;
}
/*
* close a timer instance
*/
int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
/* force to stop the timer */
snd_timer_stop(timeri);
timer = timeri->timer;
if (timer) {
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
/* remove slave links */
spin_lock_irq(&slave_active_lock);
spin_lock(&timer->lock);
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
list_del_init(&slave->ack_list);
list_del_init(&slave->active_list);
}
spin_unlock(&timer->lock);
spin_unlock_irq(&slave_active_lock);
/* slave doesn't need to release timer resources below */
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
timer = NULL;
}
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer) {
if (list_empty(&timer->open_list_head) && timer->hw.close)
timer->hw.close(timer);
/* release a card refcount for safe disconnection */
if (timer->card)
put_device(&timer->card->card_dev);
module_put(timer->module);
}
mutex_unlock(®ister_mutex);
return 0;
}
unsigned long snd_timer_resolution(struct snd_timer_instance *timeri)
{
struct snd_timer * timer;
if (timeri == NULL)
return 0;
if ((timer = timeri->timer) != NULL) {
if (timer->hw.c_resolution)
return timer->hw.c_resolution(timer);
return timer->hw.resolution;
}
return 0;
}
static void snd_timer_notify1(struct snd_timer_instance *ti, int event)
{
struct snd_timer *timer;
unsigned long resolution = 0;
struct snd_timer_instance *ts;
struct timespec tstamp;
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_START ||
event > SNDRV_TIMER_EVENT_PAUSE))
return;
if (event == SNDRV_TIMER_EVENT_START ||
event == SNDRV_TIMER_EVENT_CONTINUE)
resolution = snd_timer_resolution(ti);
if (ti->ccallback)
ti->ccallback(ti, event, &tstamp, resolution);
if (ti->flags & SNDRV_TIMER_IFLG_SLAVE)
return;
timer = ti->timer;
if (timer == NULL)
return;
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
return;
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event + 100, &tstamp, resolution);
}
/* start/continue a master timer */
static int snd_timer_start1(struct snd_timer_instance *timeri,
bool start, unsigned long ticks)
{
struct snd_timer *timer;
int result;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (timer->card && timer->card->shutdown) {
result = -ENODEV;
goto unlock;
}
if (timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START)) {
result = -EBUSY;
goto unlock;
}
if (start)
timeri->ticks = timeri->cticks = ticks;
else if (!timeri->cticks)
timeri->cticks = 1;
timeri->pticks = 0;
list_move_tail(&timeri->active_list, &timer->active_list_head);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
goto __start_now;
timer->flags |= SNDRV_TIMER_FLG_RESCHED;
timeri->flags |= SNDRV_TIMER_IFLG_START;
result = 1; /* delayed start */
} else {
if (start)
timer->sticks = ticks;
timer->hw.start(timer);
__start_now:
timer->running++;
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
result = 0;
}
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* start/continue a slave timer */
static int snd_timer_start_slave(struct snd_timer_instance *timeri,
bool start)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
if (timeri->flags & SNDRV_TIMER_IFLG_RUNNING) {
spin_unlock_irqrestore(&slave_active_lock, flags);
return -EBUSY;
}
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
if (timeri->master && timeri->timer) {
spin_lock(&timeri->timer->lock);
list_add_tail(&timeri->active_list,
&timeri->master->slave_active_head);
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 1; /* delayed start */
}
/* stop/pause a master timer */
static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop)
{
struct snd_timer *timer;
int result = 0;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (!(timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START))) {
result = -EBUSY;
goto unlock;
}
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
if (timer->card && timer->card->shutdown)
goto unlock;
if (stop) {
timeri->cticks = timeri->ticks;
timeri->pticks = 0;
}
if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
!(--timer->running)) {
timer->hw.stop(timer);
if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
snd_timer_reschedule(timer, 0);
if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
}
}
timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_CONTINUE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* stop/pause a slave timer */
static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
if (!(timeri->flags & SNDRV_TIMER_IFLG_RUNNING)) {
spin_unlock_irqrestore(&slave_active_lock, flags);
return -EBUSY;
}
timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
if (timeri->timer) {
spin_lock(&timeri->timer->lock);
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_CONTINUE);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 0;
}
/*
* start the timer instance
*/
int snd_timer_start(struct snd_timer_instance *timeri, unsigned int ticks)
{
if (timeri == NULL || ticks < 1)
return -EINVAL;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, true);
else
return snd_timer_start1(timeri, true, ticks);
}
/*
* stop the timer instance.
*
* do not call this from the timer callback!
*/
int snd_timer_stop(struct snd_timer_instance *timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, true);
else
return snd_timer_stop1(timeri, true);
}
/*
* start again.. the tick is kept.
*/
int snd_timer_continue(struct snd_timer_instance *timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, false);
else
return snd_timer_start1(timeri, false, 0);
}
/*
* pause.. remember the ticks left
*/
int snd_timer_pause(struct snd_timer_instance * timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, false);
else
return snd_timer_stop1(timeri, false);
}
/*
* reschedule the timer
*
* start pending instances and check the scheduling ticks.
* when the scheduling ticks is changed set CHANGE flag to reprogram the timer.
*/
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti;
unsigned long ticks = ~0UL;
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->flags & SNDRV_TIMER_IFLG_START) {
ti->flags &= ~SNDRV_TIMER_IFLG_START;
ti->flags |= SNDRV_TIMER_IFLG_RUNNING;
timer->running++;
}
if (ti->flags & SNDRV_TIMER_IFLG_RUNNING) {
if (ticks > ti->cticks)
ticks = ti->cticks;
}
}
if (ticks == ~0UL) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
return;
}
if (ticks > timer->hw.ticks)
ticks = timer->hw.ticks;
if (ticks_left != ticks)
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
timer->sticks = ticks;
}
/*
* timer tasklet
*
*/
static void snd_timer_tasklet(unsigned long arg)
{
struct snd_timer *timer = (struct snd_timer *) arg;
struct snd_timer_instance *ti;
struct list_head *p;
unsigned long resolution, ticks;
unsigned long flags;
if (timer->card && timer->card->shutdown)
return;
spin_lock_irqsave(&timer->lock, flags);
/* now process all callbacks */
while (!list_empty(&timer->sack_list_head)) {
p = timer->sack_list_head.next; /* get first item */
ti = list_entry(p, struct snd_timer_instance, ack_list);
/* remove from ack_list and make empty */
list_del_init(p);
ticks = ti->pticks;
ti->pticks = 0;
resolution = ti->resolution;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* timer interrupt
*
* ticks_left is usually equal to timer->sticks.
*
*/
void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti, *ts, *tmp;
unsigned long resolution, ticks;
struct list_head *p, *ack_list_head;
unsigned long flags;
int use_tasklet = 0;
if (timer == NULL)
return;
if (timer->card && timer->card->shutdown)
return;
spin_lock_irqsave(&timer->lock, flags);
/* remember the current resolution */
if (timer->hw.c_resolution)
resolution = timer->hw.c_resolution(timer);
else
resolution = timer->hw.resolution;
/* loop for all active instances
* Here we cannot use list_for_each_entry because the active_list of a
* processed instance is relinked to done_list_head before the callback
* is called.
*/
list_for_each_entry_safe(ti, tmp, &timer->active_list_head,
active_list) {
if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING))
continue;
ti->pticks += ticks_left;
ti->resolution = resolution;
if (ti->cticks < ticks_left)
ti->cticks = 0;
else
ti->cticks -= ticks_left;
if (ti->cticks) /* not expired */
continue;
if (ti->flags & SNDRV_TIMER_IFLG_AUTO) {
ti->cticks = ti->ticks;
} else {
ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
--timer->running;
list_del_init(&ti->active_list);
}
if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) ||
(ti->flags & SNDRV_TIMER_IFLG_FAST))
ack_list_head = &timer->ack_list_head;
else
ack_list_head = &timer->sack_list_head;
if (list_empty(&ti->ack_list))
list_add_tail(&ti->ack_list, ack_list_head);
list_for_each_entry(ts, &ti->slave_active_head, active_list) {
ts->pticks = ti->pticks;
ts->resolution = resolution;
if (list_empty(&ts->ack_list))
list_add_tail(&ts->ack_list, ack_list_head);
}
}
if (timer->flags & SNDRV_TIMER_FLG_RESCHED)
snd_timer_reschedule(timer, timer->sticks);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_STOP) {
timer->hw.stop(timer);
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
}
if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) ||
(timer->flags & SNDRV_TIMER_FLG_CHANGE)) {
/* restart timer */
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
} else {
timer->hw.stop(timer);
}
/* now process all fast callbacks */
while (!list_empty(&timer->ack_list_head)) {
p = timer->ack_list_head.next; /* get first item */
ti = list_entry(p, struct snd_timer_instance, ack_list);
/* remove from ack_list and make empty */
list_del_init(p);
ticks = ti->pticks;
ti->pticks = 0;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
/* do we have any slow callbacks? */
use_tasklet = !list_empty(&timer->sack_list_head);
spin_unlock_irqrestore(&timer->lock, flags);
if (use_tasklet)
tasklet_schedule(&timer->task_queue);
}
/*
*/
int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid,
struct snd_timer **rtimer)
{
struct snd_timer *timer;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_timer_dev_free,
.dev_register = snd_timer_dev_register,
.dev_disconnect = snd_timer_dev_disconnect,
};
if (snd_BUG_ON(!tid))
return -EINVAL;
if (rtimer)
*rtimer = NULL;
timer = kzalloc(sizeof(*timer), GFP_KERNEL);
if (!timer)
return -ENOMEM;
timer->tmr_class = tid->dev_class;
timer->card = card;
timer->tmr_device = tid->device;
timer->tmr_subdevice = tid->subdevice;
if (id)
strlcpy(timer->id, id, sizeof(timer->id));
INIT_LIST_HEAD(&timer->device_list);
INIT_LIST_HEAD(&timer->open_list_head);
INIT_LIST_HEAD(&timer->active_list_head);
INIT_LIST_HEAD(&timer->ack_list_head);
INIT_LIST_HEAD(&timer->sack_list_head);
spin_lock_init(&timer->lock);
tasklet_init(&timer->task_queue, snd_timer_tasklet,
(unsigned long)timer);
if (card != NULL) {
timer->module = card->module;
err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops);
if (err < 0) {
snd_timer_free(timer);
return err;
}
}
if (rtimer)
*rtimer = timer;
return 0;
}
static int snd_timer_free(struct snd_timer *timer)
{
if (!timer)
return 0;
mutex_lock(®ister_mutex);
if (! list_empty(&timer->open_list_head)) {
struct list_head *p, *n;
struct snd_timer_instance *ti;
pr_warn("ALSA: timer %p is busy?\n", timer);
list_for_each_safe(p, n, &timer->open_list_head) {
list_del_init(p);
ti = list_entry(p, struct snd_timer_instance, open_list);
ti->timer = NULL;
}
}
list_del(&timer->device_list);
mutex_unlock(®ister_mutex);
if (timer->private_free)
timer->private_free(timer);
kfree(timer);
return 0;
}
static int snd_timer_dev_free(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
return snd_timer_free(timer);
}
static int snd_timer_dev_register(struct snd_device *dev)
{
struct snd_timer *timer = dev->device_data;
struct snd_timer *timer1;
if (snd_BUG_ON(!timer || !timer->hw.start || !timer->hw.stop))
return -ENXIO;
if (!(timer->hw.flags & SNDRV_TIMER_HW_SLAVE) &&
!timer->hw.resolution && timer->hw.c_resolution == NULL)
return -EINVAL;
mutex_lock(®ister_mutex);
list_for_each_entry(timer1, &snd_timer_list, device_list) {
if (timer1->tmr_class > timer->tmr_class)
break;
if (timer1->tmr_class < timer->tmr_class)
continue;
if (timer1->card && timer->card) {
if (timer1->card->number > timer->card->number)
break;
if (timer1->card->number < timer->card->number)
continue;
}
if (timer1->tmr_device > timer->tmr_device)
break;
if (timer1->tmr_device < timer->tmr_device)
continue;
if (timer1->tmr_subdevice > timer->tmr_subdevice)
break;
if (timer1->tmr_subdevice < timer->tmr_subdevice)
continue;
/* conflicts.. */
mutex_unlock(®ister_mutex);
return -EBUSY;
}
list_add_tail(&timer->device_list, &timer1->device_list);
mutex_unlock(®ister_mutex);
return 0;
}
static int snd_timer_dev_disconnect(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_del_init(&timer->device_list);
/* wake up pending sleepers */
list_for_each_entry(ti, &timer->open_list_head, open_list) {
if (ti->disconnect)
ti->disconnect(ti);
}
mutex_unlock(®ister_mutex);
return 0;
}
void snd_timer_notify(struct snd_timer *timer, int event, struct timespec *tstamp)
{
unsigned long flags;
unsigned long resolution = 0;
struct snd_timer_instance *ti, *ts;
if (timer->card && timer->card->shutdown)
return;
if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE))
return;
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART ||
event > SNDRV_TIMER_EVENT_MRESUME))
return;
spin_lock_irqsave(&timer->lock, flags);
if (event == SNDRV_TIMER_EVENT_MSTART ||
event == SNDRV_TIMER_EVENT_MCONTINUE ||
event == SNDRV_TIMER_EVENT_MRESUME) {
if (timer->hw.c_resolution)
resolution = timer->hw.c_resolution(timer);
else
resolution = timer->hw.resolution;
}
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->ccallback)
ti->ccallback(ti, event, tstamp, resolution);
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event, tstamp, resolution);
}
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* exported functions for global timers
*/
int snd_timer_global_new(char *id, int device, struct snd_timer **rtimer)
{
struct snd_timer_id tid;
tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = -1;
tid.device = device;
tid.subdevice = 0;
return snd_timer_new(NULL, id, &tid, rtimer);
}
int snd_timer_global_free(struct snd_timer *timer)
{
return snd_timer_free(timer);
}
int snd_timer_global_register(struct snd_timer *timer)
{
struct snd_device dev;
memset(&dev, 0, sizeof(dev));
dev.device_data = timer;
return snd_timer_dev_register(&dev);
}
/*
* System timer
*/
struct snd_timer_system_private {
struct timer_list tlist;
unsigned long last_expires;
unsigned long last_jiffies;
unsigned long correction;
};
static void snd_timer_s_function(unsigned long data)
{
struct snd_timer *timer = (struct snd_timer *)data;
struct snd_timer_system_private *priv = timer->private_data;
unsigned long jiff = jiffies;
if (time_after(jiff, priv->last_expires))
priv->correction += (long)jiff - (long)priv->last_expires;
snd_timer_interrupt(timer, (long)jiff - (long)priv->last_jiffies);
}
static int snd_timer_s_start(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long njiff;
priv = (struct snd_timer_system_private *) timer->private_data;
njiff = (priv->last_jiffies = jiffies);
if (priv->correction > timer->sticks - 1) {
priv->correction -= timer->sticks - 1;
njiff++;
} else {
njiff += timer->sticks - priv->correction;
priv->correction = 0;
}
priv->last_expires = njiff;
mod_timer(&priv->tlist, njiff);
return 0;
}
static int snd_timer_s_stop(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long jiff;
priv = (struct snd_timer_system_private *) timer->private_data;
del_timer(&priv->tlist);
jiff = jiffies;
if (time_before(jiff, priv->last_expires))
timer->sticks = priv->last_expires - jiff;
else
timer->sticks = 1;
priv->correction = 0;
return 0;
}
static int snd_timer_s_close(struct snd_timer *timer)
{
struct snd_timer_system_private *priv;
priv = (struct snd_timer_system_private *)timer->private_data;
del_timer_sync(&priv->tlist);
return 0;
}
static struct snd_timer_hardware snd_timer_system =
{
.flags = SNDRV_TIMER_HW_FIRST | SNDRV_TIMER_HW_TASKLET,
.resolution = 1000000000L / HZ,
.ticks = 10000000L,
.close = snd_timer_s_close,
.start = snd_timer_s_start,
.stop = snd_timer_s_stop
};
static void snd_timer_free_system(struct snd_timer *timer)
{
kfree(timer->private_data);
}
static int snd_timer_register_system(void)
{
struct snd_timer *timer;
struct snd_timer_system_private *priv;
int err;
err = snd_timer_global_new("system", SNDRV_TIMER_GLOBAL_SYSTEM, &timer);
if (err < 0)
return err;
strcpy(timer->name, "system timer");
timer->hw = snd_timer_system;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
snd_timer_free(timer);
return -ENOMEM;
}
setup_timer(&priv->tlist, snd_timer_s_function, (unsigned long) timer);
timer->private_data = priv;
timer->private_free = snd_timer_free_system;
return snd_timer_global_register(timer);
}
#ifdef CONFIG_SND_PROC_FS
/*
* Info interface
*/
static void snd_timer_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_timer *timer;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->card && timer->card->shutdown)
continue;
switch (timer->tmr_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
snd_iprintf(buffer, "G%i: ", timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_CARD:
snd_iprintf(buffer, "C%i-%i: ",
timer->card->number, timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_PCM:
snd_iprintf(buffer, "P%i-%i-%i: ", timer->card->number,
timer->tmr_device, timer->tmr_subdevice);
break;
default:
snd_iprintf(buffer, "?%i-%i-%i-%i: ", timer->tmr_class,
timer->card ? timer->card->number : -1,
timer->tmr_device, timer->tmr_subdevice);
}
snd_iprintf(buffer, "%s :", timer->name);
if (timer->hw.resolution)
snd_iprintf(buffer, " %lu.%03luus (%lu ticks)",
timer->hw.resolution / 1000,
timer->hw.resolution % 1000,
timer->hw.ticks);
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
snd_iprintf(buffer, " SLAVE");
snd_iprintf(buffer, "\n");
list_for_each_entry(ti, &timer->open_list_head, open_list)
snd_iprintf(buffer, " Client %s : %s\n",
ti->owner ? ti->owner : "unknown",
ti->flags & (SNDRV_TIMER_IFLG_START |
SNDRV_TIMER_IFLG_RUNNING)
? "running" : "stopped");
}
mutex_unlock(®ister_mutex);
}
static struct snd_info_entry *snd_timer_proc_entry;
static void __init snd_timer_proc_init(void)
{
struct snd_info_entry *entry;
entry = snd_info_create_module_entry(THIS_MODULE, "timers", NULL);
if (entry != NULL) {
entry->c.text.read = snd_timer_proc_read;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
snd_timer_proc_entry = entry;
}
static void __exit snd_timer_proc_done(void)
{
snd_info_free_entry(snd_timer_proc_entry);
}
#else /* !CONFIG_SND_PROC_FS */
#define snd_timer_proc_init()
#define snd_timer_proc_done()
#endif
/*
* USER SPACE interface
*/
static void snd_timer_user_interrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_read *r;
int prev;
spin_lock(&tu->qlock);
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->queue[prev];
if (r->resolution == resolution) {
r->ticks += ticks;
goto __wake;
}
}
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
r = &tu->queue[tu->qtail++];
tu->qtail %= tu->queue_size;
r->resolution = resolution;
r->ticks = ticks;
tu->qused++;
}
__wake:
spin_unlock(&tu->qlock);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_append_to_tqueue(struct snd_timer_user *tu,
struct snd_timer_tread *tread)
{
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
memcpy(&tu->tqueue[tu->qtail++], tread, sizeof(*tread));
tu->qtail %= tu->queue_size;
tu->qused++;
}
}
static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,
int event,
struct timespec *tstamp,
unsigned long resolution)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread r1;
unsigned long flags;
if (event >= SNDRV_TIMER_EVENT_START &&
event <= SNDRV_TIMER_EVENT_PAUSE)
tu->tstamp = *tstamp;
if ((tu->filter & (1 << event)) == 0 || !tu->tread)
return;
memset(&r1, 0, sizeof(r1));
r1.event = event;
r1.tstamp = *tstamp;
r1.val = resolution;
spin_lock_irqsave(&tu->qlock, flags);
snd_timer_user_append_to_tqueue(tu, &r1);
spin_unlock_irqrestore(&tu->qlock, flags);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_disconnect(struct snd_timer_instance *timeri)
{
struct snd_timer_user *tu = timeri->callback_data;
tu->disconnected = true;
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread *r, r1;
struct timespec tstamp;
int prev, append = 0;
memset(&tstamp, 0, sizeof(tstamp));
spin_lock(&tu->qlock);
if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) |
(1 << SNDRV_TIMER_EVENT_TICK))) == 0) {
spin_unlock(&tu->qlock);
return;
}
if (tu->last_resolution != resolution || ticks > 0) {
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&
tu->last_resolution != resolution) {
r1.event = SNDRV_TIMER_EVENT_RESOLUTION;
r1.tstamp = tstamp;
r1.val = resolution;
snd_timer_user_append_to_tqueue(tu, &r1);
tu->last_resolution = resolution;
append++;
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0)
goto __wake;
if (ticks == 0)
goto __wake;
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->tqueue[prev];
if (r->event == SNDRV_TIMER_EVENT_TICK) {
r->tstamp = tstamp;
r->val += ticks;
append++;
goto __wake;
}
}
r1.event = SNDRV_TIMER_EVENT_TICK;
r1.tstamp = tstamp;
r1.val = ticks;
snd_timer_user_append_to_tqueue(tu, &r1);
append++;
__wake:
spin_unlock(&tu->qlock);
if (append == 0)
return;
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static int snd_timer_user_open(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
tu = kzalloc(sizeof(*tu), GFP_KERNEL);
if (tu == NULL)
return -ENOMEM;
spin_lock_init(&tu->qlock);
init_waitqueue_head(&tu->qchange_sleep);
mutex_init(&tu->ioctl_lock);
tu->ticks = 1;
tu->queue_size = 128;
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL) {
kfree(tu);
return -ENOMEM;
}
file->private_data = tu;
return 0;
}
static int snd_timer_user_release(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
if (file->private_data) {
tu = file->private_data;
file->private_data = NULL;
mutex_lock(&tu->ioctl_lock);
if (tu->timeri)
snd_timer_close(tu->timeri);
mutex_unlock(&tu->ioctl_lock);
kfree(tu->queue);
kfree(tu->tqueue);
kfree(tu);
}
return 0;
}
static void snd_timer_user_zero_id(struct snd_timer_id *id)
{
id->dev_class = SNDRV_TIMER_CLASS_NONE;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = -1;
id->device = -1;
id->subdevice = -1;
}
static void snd_timer_user_copy_id(struct snd_timer_id *id, struct snd_timer *timer)
{
id->dev_class = timer->tmr_class;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = timer->card ? timer->card->number : -1;
id->device = timer->tmr_device;
id->subdevice = timer->tmr_subdevice;
}
static int snd_timer_user_next_device(struct snd_timer_id __user *_tid)
{
struct snd_timer_id id;
struct snd_timer *timer;
struct list_head *p;
if (copy_from_user(&id, _tid, sizeof(id)))
return -EFAULT;
mutex_lock(®ister_mutex);
if (id.dev_class < 0) { /* first item */
if (list_empty(&snd_timer_list))
snd_timer_user_zero_id(&id);
else {
timer = list_entry(snd_timer_list.next,
struct snd_timer, device_list);
snd_timer_user_copy_id(&id, timer);
}
} else {
switch (id.dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
id.device = id.device < 0 ? 0 : id.device + 1;
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > SNDRV_TIMER_CLASS_GLOBAL) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device >= id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (id.card < 0) {
id.card = 0;
} else {
if (id.card < 0) {
id.card = 0;
} else {
if (id.device < 0) {
id.device = 0;
} else {
if (id.subdevice < 0) {
id.subdevice = 0;
} else {
id.subdevice++;
}
}
}
}
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > id.dev_class) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_class < id.dev_class)
continue;
if (timer->card->number > id.card) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->card->number < id.card)
continue;
if (timer->tmr_device > id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device < id.device)
continue;
if (timer->tmr_subdevice > id.subdevice) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_subdevice < id.subdevice)
continue;
snd_timer_user_copy_id(&id, timer);
break;
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
default:
snd_timer_user_zero_id(&id);
}
}
mutex_unlock(®ister_mutex);
if (copy_to_user(_tid, &id, sizeof(*_tid)))
return -EFAULT;
return 0;
}
static int snd_timer_user_ginfo(struct file *file,
struct snd_timer_ginfo __user *_ginfo)
{
struct snd_timer_ginfo *ginfo;
struct snd_timer_id tid;
struct snd_timer *t;
struct list_head *p;
int err = 0;
ginfo = memdup_user(_ginfo, sizeof(*ginfo));
if (IS_ERR(ginfo))
return PTR_ERR(ginfo);
tid = ginfo->tid;
memset(ginfo, 0, sizeof(*ginfo));
ginfo->tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
ginfo->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
ginfo->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(ginfo->id, t->id, sizeof(ginfo->id));
strlcpy(ginfo->name, t->name, sizeof(ginfo->name));
ginfo->resolution = t->hw.resolution;
if (t->hw.resolution_min > 0) {
ginfo->resolution_min = t->hw.resolution_min;
ginfo->resolution_max = t->hw.resolution_max;
}
list_for_each(p, &t->open_list_head) {
ginfo->clients++;
}
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_ginfo, ginfo, sizeof(*ginfo)))
err = -EFAULT;
kfree(ginfo);
return err;
}
static int timer_set_gparams(struct snd_timer_gparams *gparams)
{
struct snd_timer *t;
int err;
mutex_lock(®ister_mutex);
t = snd_timer_find(&gparams->tid);
if (!t) {
err = -ENODEV;
goto _error;
}
if (!list_empty(&t->open_list_head)) {
err = -EBUSY;
goto _error;
}
if (!t->hw.set_period) {
err = -ENOSYS;
goto _error;
}
err = t->hw.set_period(t, gparams->period_num, gparams->period_den);
_error:
mutex_unlock(®ister_mutex);
return err;
}
static int snd_timer_user_gparams(struct file *file,
struct snd_timer_gparams __user *_gparams)
{
struct snd_timer_gparams gparams;
if (copy_from_user(&gparams, _gparams, sizeof(gparams)))
return -EFAULT;
return timer_set_gparams(&gparams);
}
static int snd_timer_user_gstatus(struct file *file,
struct snd_timer_gstatus __user *_gstatus)
{
struct snd_timer_gstatus gstatus;
struct snd_timer_id tid;
struct snd_timer *t;
int err = 0;
if (copy_from_user(&gstatus, _gstatus, sizeof(gstatus)))
return -EFAULT;
tid = gstatus.tid;
memset(&gstatus, 0, sizeof(gstatus));
gstatus.tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
if (t->hw.c_resolution)
gstatus.resolution = t->hw.c_resolution(t);
else
gstatus.resolution = t->hw.resolution;
if (t->hw.precise_resolution) {
t->hw.precise_resolution(t, &gstatus.resolution_num,
&gstatus.resolution_den);
} else {
gstatus.resolution_num = gstatus.resolution;
gstatus.resolution_den = 1000000000uL;
}
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_gstatus, &gstatus, sizeof(gstatus)))
err = -EFAULT;
return err;
}
static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
tu->timeri->disconnect = snd_timer_user_disconnect;
}
__err:
return err;
}
static int snd_timer_user_info(struct file *file,
struct snd_timer_info __user *_info)
{
struct snd_timer_user *tu;
struct snd_timer_info *info;
struct snd_timer *t;
int err = 0;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (! info)
return -ENOMEM;
info->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
info->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(info->id, t->id, sizeof(info->id));
strlcpy(info->name, t->name, sizeof(info->name));
info->resolution = t->hw.resolution;
if (copy_to_user(_info, info, sizeof(*_info)))
err = -EFAULT;
kfree(info);
return err;
}
static int snd_timer_user_params(struct file *file,
struct snd_timer_params __user *_params)
{
struct snd_timer_user *tu;
struct snd_timer_params params;
struct snd_timer *t;
struct snd_timer_read *tr;
struct snd_timer_tread *ttr;
int err;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
if (copy_from_user(¶ms, _params, sizeof(params)))
return -EFAULT;
if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) {
err = -EINVAL;
goto _end;
}
if (params.queue_size > 0 &&
(params.queue_size < 32 || params.queue_size > 1024)) {
err = -EINVAL;
goto _end;
}
if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)|
(1<<SNDRV_TIMER_EVENT_TICK)|
(1<<SNDRV_TIMER_EVENT_START)|
(1<<SNDRV_TIMER_EVENT_STOP)|
(1<<SNDRV_TIMER_EVENT_CONTINUE)|
(1<<SNDRV_TIMER_EVENT_PAUSE)|
(1<<SNDRV_TIMER_EVENT_SUSPEND)|
(1<<SNDRV_TIMER_EVENT_RESUME)|
(1<<SNDRV_TIMER_EVENT_MSTART)|
(1<<SNDRV_TIMER_EVENT_MSTOP)|
(1<<SNDRV_TIMER_EVENT_MCONTINUE)|
(1<<SNDRV_TIMER_EVENT_MPAUSE)|
(1<<SNDRV_TIMER_EVENT_MSUSPEND)|
(1<<SNDRV_TIMER_EVENT_MRESUME))) {
err = -EINVAL;
goto _end;
}
snd_timer_stop(tu->timeri);
spin_lock_irq(&t->lock);
tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO|
SNDRV_TIMER_IFLG_EXCLUSIVE|
SNDRV_TIMER_IFLG_EARLY_EVENT);
if (params.flags & SNDRV_TIMER_PSFLG_AUTO)
tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO;
if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE;
if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT;
spin_unlock_irq(&t->lock);
if (params.queue_size > 0 &&
(unsigned int)tu->queue_size != params.queue_size) {
if (tu->tread) {
ttr = kmalloc(params.queue_size * sizeof(*ttr),
GFP_KERNEL);
if (ttr) {
kfree(tu->tqueue);
tu->queue_size = params.queue_size;
tu->tqueue = ttr;
}
} else {
tr = kmalloc(params.queue_size * sizeof(*tr),
GFP_KERNEL);
if (tr) {
kfree(tu->queue);
tu->queue_size = params.queue_size;
tu->queue = tr;
}
}
}
tu->qhead = tu->qtail = tu->qused = 0;
if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) {
if (tu->tread) {
struct snd_timer_tread tread;
memset(&tread, 0, sizeof(tread));
tread.event = SNDRV_TIMER_EVENT_EARLY;
tread.tstamp.tv_sec = 0;
tread.tstamp.tv_nsec = 0;
tread.val = 0;
snd_timer_user_append_to_tqueue(tu, &tread);
} else {
struct snd_timer_read *r = &tu->queue[0];
r->resolution = 0;
r->ticks = 0;
tu->qused++;
tu->qtail++;
}
}
tu->filter = params.filter;
tu->ticks = params.ticks;
err = 0;
_end:
if (copy_to_user(_params, ¶ms, sizeof(params)))
return -EFAULT;
return err;
}
static int snd_timer_user_status(struct file *file,
struct snd_timer_status __user *_status)
{
struct snd_timer_user *tu;
struct snd_timer_status status;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
memset(&status, 0, sizeof(status));
status.tstamp = tu->tstamp;
status.resolution = snd_timer_resolution(tu->timeri);
status.lost = tu->timeri->lost;
status.overrun = tu->overrun;
spin_lock_irq(&tu->qlock);
status.queue = tu->qused;
spin_unlock_irq(&tu->qlock);
if (copy_to_user(_status, &status, sizeof(status)))
return -EFAULT;
return 0;
}
static int snd_timer_user_start(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
snd_timer_stop(tu->timeri);
tu->timeri->lost = 0;
tu->last_resolution = 0;
return (err = snd_timer_start(tu->timeri, tu->ticks)) < 0 ? err : 0;
}
static int snd_timer_user_stop(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
return (err = snd_timer_stop(tu->timeri)) < 0 ? err : 0;
}
static int snd_timer_user_continue(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
tu->timeri->lost = 0;
return (err = snd_timer_continue(tu->timeri)) < 0 ? err : 0;
}
static int snd_timer_user_pause(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
return (err = snd_timer_pause(tu->timeri)) < 0 ? err : 0;
}
enum {
SNDRV_TIMER_IOCTL_START_OLD = _IO('T', 0x20),
SNDRV_TIMER_IOCTL_STOP_OLD = _IO('T', 0x21),
SNDRV_TIMER_IOCTL_CONTINUE_OLD = _IO('T', 0x22),
SNDRV_TIMER_IOCTL_PAUSE_OLD = _IO('T', 0x23),
};
static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu;
void __user *argp = (void __user *)arg;
int __user *p = argp;
tu = file->private_data;
switch (cmd) {
case SNDRV_TIMER_IOCTL_PVERSION:
return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0;
case SNDRV_TIMER_IOCTL_NEXT_DEVICE:
return snd_timer_user_next_device(argp);
case SNDRV_TIMER_IOCTL_TREAD:
{
int xarg;
if (tu->timeri) /* too late */
return -EBUSY;
if (get_user(xarg, p))
return -EFAULT;
tu->tread = xarg ? 1 : 0;
return 0;
}
case SNDRV_TIMER_IOCTL_GINFO:
return snd_timer_user_ginfo(file, argp);
case SNDRV_TIMER_IOCTL_GPARAMS:
return snd_timer_user_gparams(file, argp);
case SNDRV_TIMER_IOCTL_GSTATUS:
return snd_timer_user_gstatus(file, argp);
case SNDRV_TIMER_IOCTL_SELECT:
return snd_timer_user_tselect(file, argp);
case SNDRV_TIMER_IOCTL_INFO:
return snd_timer_user_info(file, argp);
case SNDRV_TIMER_IOCTL_PARAMS:
return snd_timer_user_params(file, argp);
case SNDRV_TIMER_IOCTL_STATUS:
return snd_timer_user_status(file, argp);
case SNDRV_TIMER_IOCTL_START:
case SNDRV_TIMER_IOCTL_START_OLD:
return snd_timer_user_start(file);
case SNDRV_TIMER_IOCTL_STOP:
case SNDRV_TIMER_IOCTL_STOP_OLD:
return snd_timer_user_stop(file);
case SNDRV_TIMER_IOCTL_CONTINUE:
case SNDRV_TIMER_IOCTL_CONTINUE_OLD:
return snd_timer_user_continue(file);
case SNDRV_TIMER_IOCTL_PAUSE:
case SNDRV_TIMER_IOCTL_PAUSE_OLD:
return snd_timer_user_pause(file);
}
return -ENOTTY;
}
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu = file->private_data;
long ret;
mutex_lock(&tu->ioctl_lock);
ret = __snd_timer_user_ioctl(file, cmd, arg);
mutex_unlock(&tu->ioctl_lock);
return ret;
}
static int snd_timer_user_fasync(int fd, struct file * file, int on)
{
struct snd_timer_user *tu;
tu = file->private_data;
return fasync_helper(fd, file, on, &tu->fasync);
}
static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
schedule();
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
spin_unlock_irq(&tu->qlock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
spin_lock_irq(&tu->qlock);
tu->qused--;
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
return result > 0 ? result : err;
}
static unsigned int snd_timer_user_poll(struct file *file, poll_table * wait)
{
unsigned int mask;
struct snd_timer_user *tu;
tu = file->private_data;
poll_wait(file, &tu->qchange_sleep, wait);
mask = 0;
if (tu->qused)
mask |= POLLIN | POLLRDNORM;
if (tu->disconnected)
mask |= POLLERR;
return mask;
}
#ifdef CONFIG_COMPAT
#include "timer_compat.c"
#else
#define snd_timer_user_ioctl_compat NULL
#endif
static const struct file_operations snd_timer_f_ops =
{
.owner = THIS_MODULE,
.read = snd_timer_user_read,
.open = snd_timer_user_open,
.release = snd_timer_user_release,
.llseek = no_llseek,
.poll = snd_timer_user_poll,
.unlocked_ioctl = snd_timer_user_ioctl,
.compat_ioctl = snd_timer_user_ioctl_compat,
.fasync = snd_timer_user_fasync,
};
/* unregister the system timer */
static void snd_timer_free_all(void)
{
struct snd_timer *timer, *n;
list_for_each_entry_safe(timer, n, &snd_timer_list, device_list)
snd_timer_free(timer);
}
static struct device timer_dev;
/*
* ENTRY functions
*/
static int __init alsa_timer_init(void)
{
int err;
snd_device_initialize(&timer_dev, NULL);
dev_set_name(&timer_dev, "timer");
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_register(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1,
"system timer");
#endif
err = snd_timer_register_system();
if (err < 0) {
pr_err("ALSA: unable to register system timer (%i)\n", err);
put_device(&timer_dev);
return err;
}
err = snd_register_device(SNDRV_DEVICE_TYPE_TIMER, NULL, 0,
&snd_timer_f_ops, NULL, &timer_dev);
if (err < 0) {
pr_err("ALSA: unable to register timer device (%i)\n", err);
snd_timer_free_all();
put_device(&timer_dev);
return err;
}
snd_timer_proc_init();
return 0;
}
static void __exit alsa_timer_exit(void)
{
snd_unregister_device(&timer_dev);
snd_timer_free_all();
put_device(&timer_dev);
snd_timer_proc_done();
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1);
#endif
}
module_init(alsa_timer_init)
module_exit(alsa_timer_exit)
EXPORT_SYMBOL(snd_timer_open);
EXPORT_SYMBOL(snd_timer_close);
EXPORT_SYMBOL(snd_timer_resolution);
EXPORT_SYMBOL(snd_timer_start);
EXPORT_SYMBOL(snd_timer_stop);
EXPORT_SYMBOL(snd_timer_continue);
EXPORT_SYMBOL(snd_timer_pause);
EXPORT_SYMBOL(snd_timer_new);
EXPORT_SYMBOL(snd_timer_notify);
EXPORT_SYMBOL(snd_timer_global_new);
EXPORT_SYMBOL(snd_timer_global_free);
EXPORT_SYMBOL(snd_timer_global_register);
EXPORT_SYMBOL(snd_timer_interrupt);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5058_0 |
crossvul-cpp_data_good_3823_0 | /* xfrm_user.c: User interface to configure xfrm engine.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
*
*/
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/init.h>
#include <linux/security.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/netlink.h>
#include <net/ah.h>
#include <asm/uaccess.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/in6.h>
#endif
static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
{
struct nlattr *rt = attrs[type];
struct xfrm_algo *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_len(algp))
return -EINVAL;
switch (type) {
case XFRMA_ALG_AUTH:
case XFRMA_ALG_CRYPT:
case XFRMA_ALG_COMP:
break;
default:
return -EINVAL;
}
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_auth_trunc(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
struct xfrm_algo_auth *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_auth_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_aead(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
struct xfrm_algo_aead *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < aead_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
xfrm_address_t **addrp)
{
struct nlattr *rt = attrs[type];
if (rt && addrp)
*addrp = nla_data(rt);
}
static inline int verify_sec_ctx_len(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
return -EINVAL;
return 0;
}
static inline int verify_replay(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
if ((p->flags & XFRM_STATE_ESN) && !rt)
return -EINVAL;
if (!rt)
return 0;
if (p->id.proto != IPPROTO_ESP)
return -EINVAL;
if (p->replay_window != 0)
return -EINVAL;
return 0;
}
static int verify_newsa_info(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
int err;
err = -EINVAL;
switch (p->family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
err = -EAFNOSUPPORT;
goto out;
#endif
default:
goto out;
}
err = -EINVAL;
switch (p->id.proto) {
case IPPROTO_AH:
if ((!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC]) ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
case IPPROTO_ESP:
if (attrs[XFRMA_ALG_COMP])
goto out;
if (!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC] &&
!attrs[XFRMA_ALG_CRYPT] &&
!attrs[XFRMA_ALG_AEAD])
goto out;
if ((attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT]) &&
attrs[XFRMA_ALG_AEAD])
goto out;
if (attrs[XFRMA_TFCPAD] &&
p->mode != XFRM_MODE_TUNNEL)
goto out;
break;
case IPPROTO_COMP:
if (!attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
#if IS_ENABLED(CONFIG_IPV6)
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
if (attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ENCAP] ||
attrs[XFRMA_SEC_CTX] ||
attrs[XFRMA_TFCPAD] ||
!attrs[XFRMA_COADDR])
goto out;
break;
#endif
default:
goto out;
}
if ((err = verify_aead(attrs)))
goto out;
if ((err = verify_auth_trunc(attrs)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
goto out;
if ((err = verify_sec_ctx_len(attrs)))
goto out;
if ((err = verify_replay(p, attrs)))
goto out;
err = -EINVAL;
switch (p->mode) {
case XFRM_MODE_TRANSPORT:
case XFRM_MODE_TUNNEL:
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_BEET:
break;
default:
goto out;
}
err = 0;
out:
return err;
}
static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo *ualg;
struct xfrm_algo_auth *p;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
p->alg_key_len = ualg->alg_key_len;
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
*algpp = p;
return 0;
}
static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_auth *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN ||
ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
return -EINVAL;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
if (!p->alg_trunc_len)
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
*algpp = p;
return 0;
}
static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_aead *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
{
int len = 0;
if (xfrm_ctx) {
len += sizeof(struct xfrm_user_sec_ctx);
len += xfrm_ctx->ctx_len;
}
return len;
}
static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&x->id, &p->id, sizeof(x->id));
memcpy(&x->sel, &p->sel, sizeof(x->sel));
memcpy(&x->lft, &p->lft, sizeof(x->lft));
x->props.mode = p->mode;
x->props.replay_window = p->replay_window;
x->props.reqid = p->reqid;
x->props.family = p->family;
memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
x->props.flags = p->flags;
if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
x->sel.family = p->family;
}
/*
* someday when pfkey also has support, we could have the code
* somehow made shareable and move it to xfrm_state.c - JHS
*
*/
static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs)
{
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
if (re) {
struct xfrm_replay_state_esn *replay_esn;
replay_esn = nla_data(re);
memcpy(x->replay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
memcpy(x->preplay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
}
if (rp) {
struct xfrm_replay_state *replay;
replay = nla_data(rp);
memcpy(&x->replay, replay, sizeof(*replay));
memcpy(&x->preplay, replay, sizeof(*replay));
}
if (lt) {
struct xfrm_lifetime_cur *ltime;
ltime = nla_data(lt);
x->curlft.bytes = ltime->bytes;
x->curlft.packets = ltime->packets;
x->curlft.add_time = ltime->add_time;
x->curlft.use_time = ltime->use_time;
}
if (et)
x->replay_maxage = nla_get_u32(et);
if (rt)
x->replay_maxdiff = nla_get_u32(rt);
}
static struct xfrm_state *xfrm_state_construct(struct net *net,
struct xfrm_usersa_info *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto error_no_put;
copy_from_user_state(x, p);
if ((err = attach_aead(&x->aead, &x->props.ealgo,
attrs[XFRMA_ALG_AEAD])))
goto error;
if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH_TRUNC])))
goto error;
if (!x->props.aalgo) {
if ((err = attach_auth(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH])))
goto error;
}
if ((err = attach_one_algo(&x->ealg, &x->props.ealgo,
xfrm_ealg_get_byname,
attrs[XFRMA_ALG_CRYPT])))
goto error;
if ((err = attach_one_algo(&x->calg, &x->props.calgo,
xfrm_calg_get_byname,
attrs[XFRMA_ALG_COMP])))
goto error;
if (attrs[XFRMA_ENCAP]) {
x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
sizeof(*x->encap), GFP_KERNEL);
if (x->encap == NULL)
goto error;
}
if (attrs[XFRMA_TFCPAD])
x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
if (attrs[XFRMA_COADDR]) {
x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
sizeof(*x->coaddr), GFP_KERNEL);
if (x->coaddr == NULL)
goto error;
}
xfrm_mark_get(attrs, &x->mark);
err = __xfrm_init_state(x, false);
if (err)
goto error;
if (attrs[XFRMA_SEC_CTX] &&
security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])))
goto error;
if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
attrs[XFRMA_REPLAY_ESN_VAL])))
goto error;
x->km.seq = p->seq;
x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
/* sysctl_xfrm_aevent_etime is in 100ms units */
x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
if ((err = xfrm_init_replay(x)))
goto error;
/* override default values from above */
xfrm_update_ae_params(x, attrs);
return x;
error:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
error_no_put:
*errp = err;
return NULL;
}
static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_info *p = nlmsg_data(nlh);
struct xfrm_state *x;
int err;
struct km_event c;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newsa_info(p, attrs);
if (err)
return err;
x = xfrm_state_construct(net, p, attrs, &err);
if (!x)
return err;
xfrm_state_hold(x);
if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
security_task_getsecid(current, &sid);
xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
struct xfrm_usersa_id *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = NULL;
struct xfrm_mark m;
int err;
u32 mark = xfrm_mark_get(attrs, &m);
if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
err = -ESRCH;
x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
} else {
xfrm_address_t *saddr = NULL;
verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
if (!saddr) {
err = -EINVAL;
goto out;
}
err = -ESRCH;
x = xfrm_state_lookup_byaddr(net, mark,
&p->daddr, saddr,
p->proto, p->family);
}
out:
if (!x && errp)
*errp = err;
return x;
}
static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err = -ESRCH;
struct km_event c;
struct xfrm_usersa_id *p = nlmsg_data(nlh);
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
return err;
if ((err = security_xfrm_state_delete(x)) != 0)
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
security_task_getsecid(current, &sid);
xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid);
xfrm_state_put(x);
return err;
}
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memset(p, 0, sizeof(*p));
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
struct xfrm_dump_info {
struct sk_buff *in_skb;
struct sk_buff *out_skb;
u32 nlmsg_seq;
u16 nlmsg_flags;
};
static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
{
struct xfrm_user_sec_ctx *uctx;
struct nlattr *attr;
int ctx_size = sizeof(*uctx) + s->ctx_len;
attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
if (attr == NULL)
return -EMSGSIZE;
uctx = nla_data(attr);
uctx->exttype = XFRMA_SEC_CTX;
uctx->len = ctx_size;
uctx->ctx_doi = s->ctx_doi;
uctx->ctx_alg = s->ctx_alg;
uctx->ctx_len = s->ctx_len;
memcpy(uctx + 1, s->ctx_str, s->ctx_len);
return 0;
}
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
/* Don't change this without updating xfrm_sa_len! */
static int copy_to_user_state_extra(struct xfrm_state *x,
struct xfrm_usersa_info *p,
struct sk_buff *skb)
{
int ret = 0;
copy_to_user_state(x, p);
if (x->coaddr) {
ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
if (ret)
goto out;
}
if (x->lastused) {
ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused);
if (ret)
goto out;
}
if (x->aead) {
ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
if (ret)
goto out;
}
if (x->aalg) {
ret = copy_to_user_auth(x->aalg, skb);
if (!ret)
ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC,
xfrm_alg_auth_len(x->aalg), x->aalg);
if (ret)
goto out;
}
if (x->ealg) {
ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
if (ret)
goto out;
}
if (x->calg) {
ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
if (ret)
goto out;
}
if (x->encap) {
ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
if (ret)
goto out;
}
if (x->tfcpad) {
ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
if (ret)
goto out;
}
ret = xfrm_mark_put(skb, &x->mark);
if (ret)
goto out;
if (x->replay_esn) {
ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
if (ret)
goto out;
}
if (x->security)
ret = copy_sec_ctx(x->security, skb);
out:
return ret;
}
static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct xfrm_usersa_info *p;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
err = copy_to_user_state_extra(x, p, skb);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_sa_done(struct netlink_callback *cb)
{
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
xfrm_state_walk_done(walk);
return 0;
}
static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_state_walk_init(walk, 0);
}
(void) xfrm_state_walk(net, walk, dump_one_state, &info);
return skb->len;
}
static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static inline size_t xfrm_spdinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_spdinfo))
+ nla_total_size(sizeof(struct xfrmu_spdhinfo));
}
static int build_spdinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_spdinfo si;
struct xfrmu_spdinfo spc;
struct xfrmu_spdhinfo sph;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_spd_getinfo(net, &si);
spc.incnt = si.incnt;
spc.outcnt = si.outcnt;
spc.fwdcnt = si.fwdcnt;
spc.inscnt = si.inscnt;
spc.outscnt = si.outscnt;
spc.fwdscnt = si.fwdscnt;
sph.spdhcnt = si.spdhcnt;
sph.spdhmcnt = si.spdhmcnt;
err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
if (!err)
err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static inline size_t xfrm_sadinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_sadhinfo))
+ nla_total_size(4); /* XFRMA_SAD_CNT */
}
static int build_sadinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_sadinfo si;
struct xfrmu_sadhinfo sh;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_sad_getinfo(net, &si);
sh.sadhmcnt = si.sadhmcnt;
sh.sadhcnt = si.sadhcnt;
err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
if (!err)
err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_id *p = nlmsg_data(nlh);
struct xfrm_state *x;
struct sk_buff *resp_skb;
int err = -ESRCH;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
goto out_noput;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
}
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_userspi_info(struct xfrm_userspi_info *p)
{
switch (p->info.id.proto) {
case IPPROTO_AH:
case IPPROTO_ESP:
break;
case IPPROTO_COMP:
/* IPCOMP spi is 16-bits. */
if (p->max >= 0x10000)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (p->min > p->max)
return -EINVAL;
return 0;
}
static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct xfrm_userspi_info *p;
struct sk_buff *resp_skb;
xfrm_address_t *daddr;
int family;
int err;
u32 mark;
struct xfrm_mark m;
p = nlmsg_data(nlh);
err = verify_userspi_info(p);
if (err)
goto out_noput;
family = p->info.family;
daddr = &p->info.id.daddr;
x = NULL;
mark = xfrm_mark_get(attrs, &m);
if (p->info.seq) {
x = xfrm_find_acq_byseq(net, mark, p->info.seq);
if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
p->info.id.proto, daddr,
&p->info.saddr, 1,
family);
err = -ENOENT;
if (x == NULL)
goto out_noput;
err = xfrm_alloc_spi(x, p->min, p->max);
if (err)
goto out;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
goto out;
}
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
out:
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_policy_dir(u8 dir)
{
switch (dir) {
case XFRM_POLICY_IN:
case XFRM_POLICY_OUT:
case XFRM_POLICY_FWD:
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_policy_type(u8 type)
{
switch (type) {
case XFRM_POLICY_TYPE_MAIN:
#ifdef CONFIG_XFRM_SUB_POLICY
case XFRM_POLICY_TYPE_SUB:
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
{
switch (p->share) {
case XFRM_SHARE_ANY:
case XFRM_SHARE_SESSION:
case XFRM_SHARE_USER:
case XFRM_SHARE_UNIQUE:
break;
default:
return -EINVAL;
}
switch (p->action) {
case XFRM_POLICY_ALLOW:
case XFRM_POLICY_BLOCK:
break;
default:
return -EINVAL;
}
switch (p->sel.family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
return -EAFNOSUPPORT;
#endif
default:
return -EINVAL;
}
return verify_policy_dir(p->dir);
}
static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
return security_xfrm_policy_alloc(&pol->security, uctx);
}
static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
int nr)
{
int i;
xp->xfrm_nr = nr;
for (i = 0; i < nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
memcpy(&t->saddr, &ut->saddr,
sizeof(xfrm_address_t));
t->reqid = ut->reqid;
t->mode = ut->mode;
t->share = ut->share;
t->optional = ut->optional;
t->aalgos = ut->aalgos;
t->ealgos = ut->ealgos;
t->calgos = ut->calgos;
/* If all masks are ~0, then we allow all algorithms. */
t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
t->encap_family = ut->family;
}
}
static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
{
int i;
if (nr > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < nr; i++) {
/* We never validated the ut->family value, so many
* applications simply leave it at zero. The check was
* never made and ut->family was ignored because all
* templates could be assumed to have the same family as
* the policy itself. Now that we will have ipv4-in-ipv6
* and ipv6-in-ipv4 tunnels, this is no longer true.
*/
if (!ut[i].family)
ut[i].family = family;
switch (ut[i].family) {
case AF_INET:
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
break;
#endif
default:
return -EINVAL;
}
}
return 0;
}
static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_TMPL];
if (!rt) {
pol->xfrm_nr = 0;
} else {
struct xfrm_user_tmpl *utmpl = nla_data(rt);
int nr = nla_len(rt) / sizeof(*utmpl);
int err;
err = validate_tmpl(nr, utmpl, pol->family);
if (err)
return err;
copy_templates(pol, utmpl, nr);
}
return 0;
}
static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
struct xfrm_userpolicy_type *upt;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
if (rt) {
upt = nla_data(rt);
type = upt->type;
}
err = verify_policy_type(type);
if (err)
return err;
*tp = type;
return 0;
}
static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
{
xp->priority = p->priority;
xp->index = p->index;
memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
xp->action = p->action;
xp->flags = p->flags;
xp->family = p->sel.family;
/* XXX xp->share = p->share; */
}
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memset(p, 0, sizeof(*p));
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
{
struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
int err;
if (!xp) {
*errp = -ENOMEM;
return NULL;
}
copy_from_user_policy(xp, p);
err = copy_from_user_policy_type(&xp->type, attrs);
if (err)
goto error;
if (!(err = copy_from_user_tmpl(xp, attrs)))
err = copy_from_user_sec_ctx(xp, attrs);
if (err)
goto error;
xfrm_mark_get(attrs, &xp->mark);
return xp;
error:
*errp = err;
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
struct xfrm_policy *xp;
struct km_event c;
int err;
int excl;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newpolicy_info(p);
if (err)
return err;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
xp = xfrm_policy_construct(net, p, attrs, &err);
if (!xp)
return err;
/* shouldn't excl be based on nlh flags??
* Aha! this is anti-netlink really i.e more pfkey derived
* in netlink excl is a flag and you wouldnt need
* a type XFRM_MSG_UPDPOLICY - JHS */
excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
err = xfrm_policy_insert(p->dir, xp, excl);
security_task_getsecid(current, &sid);
xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid);
if (err) {
security_xfrm_policy_free(xp->security);
kfree(xp);
return err;
}
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
xfrm_pol_put(xp);
return 0;
}
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
{
struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
int i;
if (xp->xfrm_nr == 0)
return 0;
for (i = 0; i < xp->xfrm_nr; i++) {
struct xfrm_user_tmpl *up = &vec[i];
struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
memset(up, 0, sizeof(*up));
memcpy(&up->id, &kp->id, sizeof(up->id));
up->family = kp->encap_family;
memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
up->reqid = kp->reqid;
up->mode = kp->mode;
up->share = kp->share;
up->optional = kp->optional;
up->aalgos = kp->aalgos;
up->ealgos = kp->ealgos;
up->calgos = kp->calgos;
}
return nla_put(skb, XFRMA_TMPL,
sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
}
static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
{
if (x->security) {
return copy_sec_ctx(x->security, skb);
}
return 0;
}
static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
{
if (xp->security)
return copy_sec_ctx(xp->security, skb);
return 0;
}
static inline size_t userpolicy_type_attrsize(void)
{
#ifdef CONFIG_XFRM_SUB_POLICY
return nla_total_size(sizeof(struct xfrm_userpolicy_type));
#else
return 0;
#endif
}
#ifdef CONFIG_XFRM_SUB_POLICY
static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
struct xfrm_userpolicy_type upt = {
.type = type,
};
return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
}
#else
static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
return 0;
}
#endif
static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct xfrm_userpolicy_info *p;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_policy_done(struct netlink_callback *cb)
{
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
xfrm_policy_walk_done(walk);
return 0;
}
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
struct xfrm_policy *xp,
int dir, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_policy(xp, dir, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_userpolicy_id *p;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct km_event c;
int delete;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
p = nlmsg_data(nlh);
delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel,
ctx, delete, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (!delete) {
struct sk_buff *resp_skb;
resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
NETLINK_CB(skb).pid);
}
} else {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid,
sid);
if (err != 0)
goto out;
c.data.byid = p->index;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
}
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
struct xfrm_usersa_flush *p = nlmsg_data(nlh);
struct xfrm_audit audit_info;
int err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_state_flush(net, p->proto, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.proto = p->proto;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x)
{
size_t replay_size = x->replay_esn ?
xfrm_replay_state_esn_len(x->replay_esn) :
sizeof(struct xfrm_replay_state);
return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
+ nla_total_size(replay_size)
+ nla_total_size(sizeof(struct xfrm_lifetime_cur))
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(4) /* XFRM_AE_RTHR */
+ nla_total_size(4); /* XFRM_AE_ETHR */
}
static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_aevent_id *id;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
if (nlh == NULL)
return -EMSGSIZE;
id = nlmsg_data(nlh);
memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr));
id->sa_id.spi = x->id.spi;
id->sa_id.family = x->props.family;
id->sa_id.proto = x->id.proto;
memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr));
id->reqid = x->props.reqid;
id->flags = c->data.aevent;
if (x->replay_esn) {
err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
} else {
err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
&x->replay);
}
if (err)
goto out_cancel;
err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft);
if (err)
goto out_cancel;
if (id->flags & XFRM_AE_RTHR) {
err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
if (err)
goto out_cancel;
}
if (id->flags & XFRM_AE_ETHR) {
err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
x->replay_maxage * 10 / HZ);
if (err)
goto out_cancel;
}
err = xfrm_mark_put(skb, &x->mark);
if (err)
goto out_cancel;
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct sk_buff *r_skb;
int err;
struct km_event c;
u32 mark;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct xfrm_usersa_id *id = &p->sa_id;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
if (x == NULL)
return -ESRCH;
r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (r_skb == NULL) {
xfrm_state_put(x);
return -ENOMEM;
}
/*
* XXX: is this lock really needed - none of the other
* gets lock (the concern is things getting updated
* while we are still reading) - jhs
*/
spin_lock_bh(&x->lock);
c.data.aevent = p->flags;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
if (build_aevent(r_skb, x, &c) < 0)
BUG();
err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid);
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct km_event c;
int err = - EINVAL;
u32 mark = 0;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
if (!lt && !rp && !re)
return err;
/* pedantic mode - thou shalt sayeth replaceth */
if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
return err;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
if (x == NULL)
return -ESRCH;
if (x->km.state != XFRM_STATE_VALID)
goto out;
err = xfrm_replay_verify_len(x->replay_esn, rp);
if (err)
goto out;
spin_lock_bh(&x->lock);
xfrm_update_ae_params(x, attrs);
spin_unlock_bh(&x->lock);
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.data.aevent = XFRM_AE_CU;
km_state_notify(x, &c);
err = 0;
out:
xfrm_state_put(x);
return err;
}
static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct xfrm_audit audit_info;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_policy_flush(net, type, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.type = type;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_polexpire *up = nlmsg_data(nlh);
struct xfrm_userpolicy_info *p = &up->pol;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err = -ENOENT;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir,
&p->sel, ctx, 0, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (unlikely(xp->walk.dead))
goto out;
err = 0;
if (up->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_policy_delete(xp, p->dir);
xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid);
} else {
// reset the timers here?
WARN(1, "Dont know what to do with soft policy expire\n");
}
km_policy_expired(xp, p->dir, up->hard, current->pid);
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err;
struct xfrm_user_expire *ue = nlmsg_data(nlh);
struct xfrm_usersa_info *p = &ue->state;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
err = -ENOENT;
if (x == NULL)
return err;
spin_lock_bh(&x->lock);
err = -EINVAL;
if (x->km.state != XFRM_STATE_VALID)
goto out;
km_state_expired(x, ue->hard, current->pid);
if (ue->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
__xfrm_state_delete(x);
xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid);
}
err = 0;
out:
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_tmpl *ut;
int i;
struct nlattr *rt = attrs[XFRMA_TMPL];
struct xfrm_mark mark;
struct xfrm_user_acquire *ua = nlmsg_data(nlh);
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto nomem;
xfrm_mark_get(attrs, &mark);
err = verify_newpolicy_info(&ua->policy);
if (err)
goto bad_policy;
/* build an XP */
xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
if (!xp)
goto free_state;
memcpy(&x->id, &ua->id, sizeof(ua->id));
memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
xp->mark.m = x->mark.m = mark.m;
xp->mark.v = x->mark.v = mark.v;
ut = nla_data(rt);
/* extract the templates and for each call km_key */
for (i = 0; i < xp->xfrm_nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&x->id, &t->id, sizeof(x->id));
x->props.mode = t->mode;
x->props.reqid = t->reqid;
x->props.family = ut->family;
t->aalgos = ua->aalgos;
t->ealgos = ua->ealgos;
t->calgos = ua->calgos;
err = km_query(x, t, xp);
}
kfree(x);
kfree(xp);
return 0;
bad_policy:
WARN(1, "BAD policy passed\n");
free_state:
kfree(x);
nomem:
return err;
}
#ifdef CONFIG_XFRM_MIGRATE
static int copy_from_user_migrate(struct xfrm_migrate *ma,
struct xfrm_kmaddress *k,
struct nlattr **attrs, int *num)
{
struct nlattr *rt = attrs[XFRMA_MIGRATE];
struct xfrm_user_migrate *um;
int i, num_migrate;
if (k != NULL) {
struct xfrm_user_kmaddress *uk;
uk = nla_data(attrs[XFRMA_KMADDRESS]);
memcpy(&k->local, &uk->local, sizeof(k->local));
memcpy(&k->remote, &uk->remote, sizeof(k->remote));
k->family = uk->family;
k->reserved = uk->reserved;
}
um = nla_data(rt);
num_migrate = nla_len(rt) / sizeof(*um);
if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++, um++, ma++) {
memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
ma->proto = um->proto;
ma->mode = um->mode;
ma->reqid = um->reqid;
ma->old_family = um->old_family;
ma->new_family = um->new_family;
}
*num = i;
return 0;
}
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress km, *kmp;
u8 type;
int err;
int n = 0;
if (attrs[XFRMA_MIGRATE] == NULL)
return -EINVAL;
kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
if (err)
return err;
if (!n)
return 0;
xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp);
return 0;
}
#else
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
return -ENOPROTOOPT;
}
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
{
struct xfrm_user_migrate um;
memset(&um, 0, sizeof(um));
um.proto = m->proto;
um.mode = m->mode;
um.reqid = m->reqid;
um.old_family = m->old_family;
memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
um.new_family = m->new_family;
memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
}
static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
{
struct xfrm_user_kmaddress uk;
memset(&uk, 0, sizeof(uk));
uk.family = k->family;
uk.reserved = k->reserved;
memcpy(&uk.local, &k->local, sizeof(uk.local));
memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
}
static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma)
{
return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
+ (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
+ nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
+ userpolicy_type_attrsize();
}
static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
int num_migrate, const struct xfrm_kmaddress *k,
const struct xfrm_selector *sel, u8 dir, u8 type)
{
const struct xfrm_migrate *mp;
struct xfrm_userpolicy_id *pol_id;
struct nlmsghdr *nlh;
int i, err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
if (nlh == NULL)
return -EMSGSIZE;
pol_id = nlmsg_data(nlh);
/* copy data from selector, dir, and type to the pol_id */
memset(pol_id, 0, sizeof(*pol_id));
memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
pol_id->dir = dir;
if (k != NULL) {
err = copy_to_user_kmaddress(k, skb);
if (err)
goto out_cancel;
}
err = copy_to_user_policy_type(type, skb);
if (err)
goto out_cancel;
for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
err = copy_to_user_migrate(mp, skb);
if (err)
goto out_cancel;
}
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
struct net *net = &init_net;
struct sk_buff *skb;
skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
/* build migrate */
if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC);
}
#else
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
#define XMSGSIZE(type) sizeof(struct type)
static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32),
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32),
};
#undef XMSGSIZE
static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
[XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)},
[XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)},
[XFRMA_LASTUSED] = { .type = NLA_U64},
[XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)},
[XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) },
[XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) },
[XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) },
[XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) },
[XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) },
[XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) },
[XFRMA_REPLAY_THRESH] = { .type = NLA_U32 },
[XFRMA_ETIMER_THRESH] = { .type = NLA_U32 },
[XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)},
[XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) },
[XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) },
[XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) },
[XFRMA_TFCPAD] = { .type = NLA_U32 },
[XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) },
};
static struct xfrm_link {
int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
int (*dump)(struct sk_buff *, struct netlink_callback *);
int (*done)(struct netlink_callback *);
} xfrm_dispatch[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa },
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
.dump = xfrm_dump_sa,
.done = xfrm_dump_sa_done },
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy },
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
.dump = xfrm_dump_policy,
.done = xfrm_dump_policy_done },
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire },
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa },
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy },
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae },
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae },
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate },
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo },
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo },
};
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
struct xfrm_link *link;
int type, err;
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,
xfrma_policy);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
static void xfrm_netlink_rcv(struct sk_buff *skb)
{
mutex_lock(&xfrm_cfg_mutex);
netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
mutex_unlock(&xfrm_cfg_mutex);
}
static inline size_t xfrm_expire_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
+ nla_total_size(sizeof(struct xfrm_mark));
}
static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
err = xfrm_mark_put(skb, &x->mark);
if (err)
return err;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_expire(skb, x, c) < 0) {
kfree_skb(skb);
return -EMSGSIZE;
}
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
static int xfrm_notify_sa_flush(const struct km_event *c)
{
struct net *net = c->net;
struct xfrm_usersa_flush *p;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
if (nlh == NULL) {
kfree_skb(skb);
return -EMSGSIZE;
}
p = nlmsg_data(nlh);
p->proto = c->data.proto;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
}
static inline size_t xfrm_sa_len(struct xfrm_state *x)
{
size_t l = 0;
if (x->aead)
l += nla_total_size(aead_len(x->aead));
if (x->aalg) {
l += nla_total_size(sizeof(struct xfrm_algo) +
(x->aalg->alg_key_len + 7) / 8);
l += nla_total_size(xfrm_alg_auth_len(x->aalg));
}
if (x->ealg)
l += nla_total_size(xfrm_alg_len(x->ealg));
if (x->calg)
l += nla_total_size(sizeof(*x->calg));
if (x->encap)
l += nla_total_size(sizeof(*x->encap));
if (x->tfcpad)
l += nla_total_size(sizeof(x->tfcpad));
if (x->replay_esn)
l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
if (x->security)
l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
x->security->ctx_len);
if (x->coaddr)
l += nla_total_size(sizeof(*x->coaddr));
/* Must count x->lastused as it may become non-zero behind our back. */
l += nla_total_size(sizeof(u64));
return l;
}
static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct xfrm_usersa_info *p;
struct xfrm_usersa_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = xfrm_sa_len(x);
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELSA) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
len += nla_total_size(sizeof(struct xfrm_mark));
}
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELSA) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
id->spi = x->id.spi;
id->family = x->props.family;
id->proto = x->id.proto;
attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
err = copy_to_user_state_extra(x, p, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_EXPIRE:
return xfrm_exp_state_notify(x, c);
case XFRM_MSG_NEWAE:
return xfrm_aevent_state_notify(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_UPDSA:
case XFRM_MSG_NEWSA:
return xfrm_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return xfrm_notify_sa_flush(c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
c->event);
break;
}
return 0;
}
static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x,
struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(xfrm_user_sec_ctx_size(x->security))
+ userpolicy_type_attrsize();
}
static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
struct xfrm_tmpl *xt, struct xfrm_policy *xp,
int dir)
{
__u32 seq = xfrm_get_acqseq();
struct xfrm_user_acquire *ua;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
if (nlh == NULL)
return -EMSGSIZE;
ua = nlmsg_data(nlh);
memcpy(&ua->id, &x->id, sizeof(ua->id));
memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
copy_to_user_policy(xp, &ua->policy, dir);
ua->aalgos = xt->aalgos;
ua->ealgos = xt->ealgos;
ua->calgos = xt->calgos;
ua->seq = x->km.seq = seq;
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_state_sec_ctx(x, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
struct xfrm_policy *xp, int dir)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_acquire(skb, x, xt, xp, dir) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC);
}
/* User gives us xfrm_user_policy_info followed by an array of 0
* or more templates.
*/
static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
struct xfrm_policy *xp;
int nr;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
if (opt != IPV6_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(*p) ||
verify_newpolicy_info(p))
return NULL;
nr = ((len - sizeof(*p)) / sizeof(*ut));
if (validate_tmpl(nr, ut, p->sel.family))
return NULL;
if (p->dir > XFRM_POLICY_OUT)
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
copy_from_user_policy(xp, p);
xp->type = XFRM_POLICY_TYPE_MAIN;
copy_templates(xp, ut, nr);
*dir = p->dir;
return xp;
}
static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(xfrm_user_sec_ctx_size(xp->security))
+ nla_total_size(sizeof(struct xfrm_mark))
+ userpolicy_type_attrsize();
}
static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
int dir, const struct km_event *c)
{
struct xfrm_user_polexpire *upe;
int hard = c->data.hard;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
if (nlh == NULL)
return -EMSGSIZE;
upe = nlmsg_data(nlh);
copy_to_user_policy(xp, &upe->pol, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
upe->hard = !!hard;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_polexpire(skb, xp, dir, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
struct net *net = xp_net(xp);
struct xfrm_userpolicy_info *p;
struct xfrm_userpolicy_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELPOLICY) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
}
len += userpolicy_type_attrsize();
len += nla_total_size(sizeof(struct xfrm_mark));
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELPOLICY) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memset(id, 0, sizeof(*id));
id->dir = dir;
if (c->data.byid)
id->index = xp->index;
else
memcpy(&id->sel, &xp->selector, sizeof(id->sel));
attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_notify_policy_flush(const struct km_event *c)
{
struct net *net = c->net;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int err;
skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
err = copy_to_user_policy_type(c->data.type, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
case XFRM_MSG_DELPOLICY:
return xfrm_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
return xfrm_notify_policy_flush(c);
case XFRM_MSG_POLEXPIRE:
return xfrm_exp_policy_notify(xp, dir, c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
c->event);
}
return 0;
}
static inline size_t xfrm_report_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
}
static int build_report(struct sk_buff *skb, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct xfrm_user_report *ur;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
if (nlh == NULL)
return -EMSGSIZE;
ur = nlmsg_data(nlh);
ur->proto = proto;
memcpy(&ur->sel, sel, sizeof(ur->sel));
if (addr) {
int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_report(struct net *net, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct sk_buff *skb;
skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_report(skb, proto, sel, addr) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC);
}
static inline size_t xfrm_mapping_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
}
static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
xfrm_address_t *new_saddr, __be16 new_sport)
{
struct xfrm_user_mapping *um;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
if (nlh == NULL)
return -EMSGSIZE;
um = nlmsg_data(nlh);
memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
um->id.spi = x->id.spi;
um->id.family = x->props.family;
um->id.proto = x->id.proto;
memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
um->new_sport = new_sport;
um->old_sport = x->encap->encap_sport;
um->reqid = x->props.reqid;
return nlmsg_end(skb, nlh);
}
static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
__be16 sport)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
if (x->id.proto != IPPROTO_ESP)
return -EINVAL;
if (!x->encap)
return -EINVAL;
skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_mapping(skb, x, ipaddr, sport) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC);
}
static struct xfrm_mgr netlink_mgr = {
.id = "netlink",
.notify = xfrm_send_state_notify,
.acquire = xfrm_send_acquire,
.compile_policy = xfrm_compile_policy,
.notify_policy = xfrm_send_policy_notify,
.report = xfrm_send_report,
.migrate = xfrm_send_migrate,
.new_mapping = xfrm_send_mapping,
};
static int __net_init xfrm_user_net_init(struct net *net)
{
struct sock *nlsk;
struct netlink_kernel_cfg cfg = {
.groups = XFRMNLGRP_MAX,
.input = xfrm_netlink_rcv,
};
nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg);
if (nlsk == NULL)
return -ENOMEM;
net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
rcu_assign_pointer(net->xfrm.nlsk, nlsk);
return 0;
}
static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->xfrm.nlsk_stash);
}
static struct pernet_operations xfrm_user_net_ops = {
.init = xfrm_user_net_init,
.exit_batch = xfrm_user_net_exit,
};
static int __init xfrm_user_init(void)
{
int rv;
printk(KERN_INFO "Initializing XFRM netlink socket\n");
rv = register_pernet_subsys(&xfrm_user_net_ops);
if (rv < 0)
return rv;
rv = xfrm_register_km(&netlink_mgr);
if (rv < 0)
unregister_pernet_subsys(&xfrm_user_net_ops);
return rv;
}
static void __exit xfrm_user_exit(void)
{
xfrm_unregister_km(&netlink_mgr);
unregister_pernet_subsys(&xfrm_user_net_ops);
}
module_init(xfrm_user_init);
module_exit(xfrm_user_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3823_0 |
crossvul-cpp_data_bad_3485_0 | /*
comedi/comedi_fops.c
comedi kernel module
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#undef DEBUG
#define __NO_VERSION__
#include "comedi_fops.h"
#include "comedi_compat32.h"
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fcntl.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include "comedidev.h"
#include <linux/cdev.h>
#include <linux/stat.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include "internal.h"
MODULE_AUTHOR("http://www.comedi.org");
MODULE_DESCRIPTION("Comedi core module");
MODULE_LICENSE("GPL");
#ifdef CONFIG_COMEDI_DEBUG
int comedi_debug;
EXPORT_SYMBOL(comedi_debug);
module_param(comedi_debug, int, 0644);
#endif
int comedi_autoconfig = 1;
module_param(comedi_autoconfig, bool, 0444);
static int comedi_num_legacy_minors;
module_param(comedi_num_legacy_minors, int, 0444);
static DEFINE_SPINLOCK(comedi_file_info_table_lock);
static struct comedi_device_file_info
*comedi_file_info_table[COMEDI_NUM_MINORS];
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg);
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg);
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file);
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file);
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg);
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file);
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file);
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file);
static int do_poll_ioctl(struct comedi_device *dev, unsigned int subd,
void *file);
extern void do_become_nonbusy(struct comedi_device *dev,
struct comedi_subdevice *s);
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static int comedi_fasync(int fd, struct file *file, int on);
static int is_device_busy(struct comedi_device *dev);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size);
/* declarations for sysfs attribute files */
static struct device_attribute dev_attr_max_read_buffer_kb;
static struct device_attribute dev_attr_read_buffer_kb;
static struct device_attribute dev_attr_max_write_buffer_kb;
static struct device_attribute dev_attr_write_buffer_kb;
static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev;
int rc;
if (dev_file_info == NULL || dev_file_info->device == NULL)
return -ENODEV;
dev = dev_file_info->device;
mutex_lock(&dev->mutex);
/* Device config is special, because it must work on
* an unconfigured device. */
if (cmd == COMEDI_DEVCONFIG) {
rc = do_devconfig_ioctl(dev,
(struct comedi_devconfig __user *)arg);
goto done;
}
if (!dev->attached) {
DPRINTK("no driver configured on /dev/comedi%i\n", dev->minor);
rc = -ENODEV;
goto done;
}
switch (cmd) {
case COMEDI_BUFCONFIG:
rc = do_bufconfig_ioctl(dev,
(struct comedi_bufconfig __user *)arg);
break;
case COMEDI_DEVINFO:
rc = do_devinfo_ioctl(dev, (struct comedi_devinfo __user *)arg,
file);
break;
case COMEDI_SUBDINFO:
rc = do_subdinfo_ioctl(dev,
(struct comedi_subdinfo __user *)arg,
file);
break;
case COMEDI_CHANINFO:
rc = do_chaninfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_RANGEINFO:
rc = do_rangeinfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_BUFINFO:
rc = do_bufinfo_ioctl(dev,
(struct comedi_bufinfo __user *)arg,
file);
break;
case COMEDI_LOCK:
rc = do_lock_ioctl(dev, arg, file);
break;
case COMEDI_UNLOCK:
rc = do_unlock_ioctl(dev, arg, file);
break;
case COMEDI_CANCEL:
rc = do_cancel_ioctl(dev, arg, file);
break;
case COMEDI_CMD:
rc = do_cmd_ioctl(dev, (struct comedi_cmd __user *)arg, file);
break;
case COMEDI_CMDTEST:
rc = do_cmdtest_ioctl(dev, (struct comedi_cmd __user *)arg,
file);
break;
case COMEDI_INSNLIST:
rc = do_insnlist_ioctl(dev,
(struct comedi_insnlist __user *)arg,
file);
break;
case COMEDI_INSN:
rc = do_insn_ioctl(dev, (struct comedi_insn __user *)arg,
file);
break;
case COMEDI_POLL:
rc = do_poll_ioctl(dev, arg, file);
break;
default:
rc = -ENOTTY;
break;
}
done:
mutex_unlock(&dev->mutex);
return rc;
}
/*
COMEDI_DEVCONFIG
device config ioctl
arg:
pointer to devconfig structure
reads:
devconfig structure at arg
writes:
none
*/
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg)
{
struct comedi_devconfig it;
int ret;
unsigned char *aux_data = NULL;
int aux_len;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (arg == NULL) {
if (is_device_busy(dev))
return -EBUSY;
if (dev->attached) {
struct module *driver_module = dev->driver->module;
comedi_device_detach(dev);
module_put(driver_module);
}
return 0;
}
if (copy_from_user(&it, arg, sizeof(struct comedi_devconfig)))
return -EFAULT;
it.board_name[COMEDI_NAMELEN - 1] = 0;
if (comedi_aux_data(it.options, 0) &&
it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
int bit_shift;
aux_len = it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH];
if (aux_len < 0)
return -EFAULT;
aux_data = vmalloc(aux_len);
if (!aux_data)
return -ENOMEM;
if (copy_from_user(aux_data,
comedi_aux_data(it.options, 0), aux_len)) {
vfree(aux_data);
return -EFAULT;
}
it.options[COMEDI_DEVCONF_AUX_DATA_LO] =
(unsigned long)aux_data;
if (sizeof(void *) > sizeof(int)) {
bit_shift = sizeof(int) * 8;
it.options[COMEDI_DEVCONF_AUX_DATA_HI] =
((unsigned long)aux_data) >> bit_shift;
} else
it.options[COMEDI_DEVCONF_AUX_DATA_HI] = 0;
}
ret = comedi_device_attach(dev, &it);
if (ret == 0) {
if (!try_module_get(dev->driver->module)) {
comedi_device_detach(dev);
return -ENOSYS;
}
}
if (aux_data)
vfree(aux_data);
return ret;
}
/*
COMEDI_BUFCONFIG
buffer configuration ioctl
arg:
pointer to bufconfig structure
reads:
bufconfig at arg
writes:
modified bufconfig at arg
*/
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg)
{
struct comedi_bufconfig bc;
struct comedi_async *async;
struct comedi_subdevice *s;
int retval = 0;
if (copy_from_user(&bc, arg, sizeof(struct comedi_bufconfig)))
return -EFAULT;
if (bc.subdevice >= dev->n_subdevices || bc.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bc.subdevice;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bc.size = 0;
bc.maximum_size = 0;
goto copyback;
}
if (bc.maximum_size) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
async->max_bufsize = bc.maximum_size;
}
if (bc.size) {
retval = resize_async_buffer(dev, s, async, bc.size);
if (retval < 0)
return retval;
}
bc.size = async->prealloc_bufsz;
bc.maximum_size = async->max_bufsize;
copyback:
if (copy_to_user(arg, &bc, sizeof(struct comedi_bufconfig)))
return -EFAULT;
return 0;
}
/*
COMEDI_DEVINFO
device info ioctl
arg:
pointer to devinfo structure
reads:
none
writes:
devinfo structure
*/
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file)
{
struct comedi_devinfo devinfo;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_subdevice *read_subdev =
comedi_get_read_subdevice(dev_file_info);
struct comedi_subdevice *write_subdev =
comedi_get_write_subdevice(dev_file_info);
memset(&devinfo, 0, sizeof(devinfo));
/* fill devinfo structure */
devinfo.version_code = COMEDI_VERSION_CODE;
devinfo.n_subdevs = dev->n_subdevices;
memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
if (read_subdev)
devinfo.read_subdevice = read_subdev - dev->subdevices;
else
devinfo.read_subdevice = -1;
if (write_subdev)
devinfo.write_subdevice = write_subdev - dev->subdevices;
else
devinfo.write_subdevice = -1;
if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo)))
return -EFAULT;
return 0;
}
/*
COMEDI_SUBDINFO
subdevice info ioctl
arg:
pointer to array of subdevice info structures
reads:
none
writes:
array of subdevice info structures at arg
*/
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file)
{
int ret, i;
struct comedi_subdinfo *tmp, *us;
struct comedi_subdevice *s;
tmp =
kcalloc(dev->n_subdevices, sizeof(struct comedi_subdinfo),
GFP_KERNEL);
if (!tmp)
return -ENOMEM;
/* fill subdinfo structs */
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
us = tmp + i;
us->type = s->type;
us->n_chan = s->n_chan;
us->subd_flags = s->subdev_flags;
if (comedi_get_subdevice_runflags(s) & SRF_RUNNING)
us->subd_flags |= SDF_RUNNING;
#define TIMER_nanosec 5 /* backwards compatibility */
us->timer_type = TIMER_nanosec;
us->len_chanlist = s->len_chanlist;
us->maxdata = s->maxdata;
if (s->range_table) {
us->range_type =
(i << 24) | (0 << 16) | (s->range_table->length);
} else {
us->range_type = 0; /* XXX */
}
us->flags = s->flags;
if (s->busy)
us->subd_flags |= SDF_BUSY;
if (s->busy == file)
us->subd_flags |= SDF_BUSY_OWNER;
if (s->lock)
us->subd_flags |= SDF_LOCKED;
if (s->lock == file)
us->subd_flags |= SDF_LOCK_OWNER;
if (!s->maxdata && s->maxdata_list)
us->subd_flags |= SDF_MAXDATA;
if (s->flaglist)
us->subd_flags |= SDF_FLAGS;
if (s->range_table_list)
us->subd_flags |= SDF_RANGETYPE;
if (s->do_cmd)
us->subd_flags |= SDF_CMD;
if (s->insn_bits != &insn_inval)
us->insn_bits_support = COMEDI_SUPPORTED;
else
us->insn_bits_support = COMEDI_UNSUPPORTED;
us->settling_time_0 = s->settling_time_0;
}
ret = copy_to_user(arg, tmp,
dev->n_subdevices * sizeof(struct comedi_subdinfo));
kfree(tmp);
return ret ? -EFAULT : 0;
}
/*
COMEDI_CHANINFO
subdevice info ioctl
arg:
pointer to chaninfo structure
reads:
chaninfo structure at arg
writes:
arrays at elements of chaninfo structure
*/
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg)
{
struct comedi_subdevice *s;
struct comedi_chaninfo it;
if (copy_from_user(&it, arg, sizeof(struct comedi_chaninfo)))
return -EFAULT;
if (it.subdev >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + it.subdev;
if (it.maxdata_list) {
if (s->maxdata || !s->maxdata_list)
return -EINVAL;
if (copy_to_user(it.maxdata_list, s->maxdata_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.flaglist) {
if (!s->flaglist)
return -EINVAL;
if (copy_to_user(it.flaglist, s->flaglist,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.rangelist) {
int i;
if (!s->range_table_list)
return -EINVAL;
for (i = 0; i < s->n_chan; i++) {
int x;
x = (dev->minor << 28) | (it.subdev << 24) | (i << 16) |
(s->range_table_list[i]->length);
if (put_user(x, it.rangelist + i))
return -EFAULT;
}
#if 0
if (copy_to_user(it.rangelist, s->range_type_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
#endif
}
return 0;
}
/*
COMEDI_BUFINFO
buffer information ioctl
arg:
pointer to bufinfo structure
reads:
bufinfo at arg
writes:
modified bufinfo at arg
*/
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file)
{
struct comedi_bufinfo bi;
struct comedi_subdevice *s;
struct comedi_async *async;
if (copy_from_user(&bi, arg, sizeof(struct comedi_bufinfo)))
return -EFAULT;
if (bi.subdevice >= dev->n_subdevices || bi.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bi.subdevice;
if (s->lock && s->lock != file)
return -EACCES;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bi.buf_write_ptr = 0;
bi.buf_read_ptr = 0;
bi.buf_write_count = 0;
bi.buf_read_count = 0;
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback;
}
if (!s->busy) {
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback_position;
}
if (s->busy != file)
return -EACCES;
if (bi.bytes_read && (s->subdev_flags & SDF_CMD_READ)) {
bi.bytes_read = comedi_buf_read_alloc(async, bi.bytes_read);
comedi_buf_read_free(async, bi.bytes_read);
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR |
SRF_RUNNING))
&& async->buf_write_count == async->buf_read_count) {
do_become_nonbusy(dev, s);
}
}
if (bi.bytes_written && (s->subdev_flags & SDF_CMD_WRITE)) {
bi.bytes_written =
comedi_buf_write_alloc(async, bi.bytes_written);
comedi_buf_write_free(async, bi.bytes_written);
}
copyback_position:
bi.buf_write_count = async->buf_write_count;
bi.buf_write_ptr = async->buf_write_ptr;
bi.buf_read_count = async->buf_read_count;
bi.buf_read_ptr = async->buf_read_ptr;
copyback:
if (copy_to_user(arg, &bi, sizeof(struct comedi_bufinfo)))
return -EFAULT;
return 0;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file);
/*
* COMEDI_INSNLIST
* synchronous instructions
*
* arg:
* pointer to sync cmd structure
*
* reads:
* sync cmd struct at arg
* instruction list
* data (for writes)
*
* writes:
* data (for reads)
*/
/* arbitrary limits */
#define MAX_SAMPLES 256
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file)
{
struct comedi_insnlist insnlist;
struct comedi_insn *insns = NULL;
unsigned int *data = NULL;
int i = 0;
int ret = 0;
if (copy_from_user(&insnlist, arg, sizeof(struct comedi_insnlist)))
return -EFAULT;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
insns =
kmalloc(sizeof(struct comedi_insn) * insnlist.n_insns, GFP_KERNEL);
if (!insns) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
if (copy_from_user(insns, insnlist.insns,
sizeof(struct comedi_insn) * insnlist.n_insns)) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
for (i = 0; i < insnlist.n_insns; i++) {
if (insns[i].n > MAX_SAMPLES) {
DPRINTK("number of samples too large\n");
ret = -EINVAL;
goto error;
}
if (insns[i].insn & INSN_MASK_WRITE) {
if (copy_from_user(data, insns[i].data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, insns + i, data, file);
if (ret < 0)
goto error;
if (insns[i].insn & INSN_MASK_READ) {
if (copy_to_user(insns[i].data, data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_to_user failed\n");
ret = -EFAULT;
goto error;
}
}
if (need_resched())
schedule();
}
error:
kfree(insns);
kfree(data);
if (ret < 0)
return ret;
return i;
}
static int check_insn_config_length(struct comedi_insn *insn,
unsigned int *data)
{
if (insn->n < 1)
return -EINVAL;
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
case INSN_CONFIG_DIO_INPUT:
case INSN_CONFIG_DISARM:
case INSN_CONFIG_RESET:
if (insn->n == 1)
return 0;
break;
case INSN_CONFIG_ARM:
case INSN_CONFIG_DIO_QUERY:
case INSN_CONFIG_BLOCK_SIZE:
case INSN_CONFIG_FILTER:
case INSN_CONFIG_SERIAL_CLOCK:
case INSN_CONFIG_BIDIRECTIONAL_DATA:
case INSN_CONFIG_ALT_SOURCE:
case INSN_CONFIG_SET_COUNTER_MODE:
case INSN_CONFIG_8254_READ_STATUS:
case INSN_CONFIG_SET_ROUTING:
case INSN_CONFIG_GET_ROUTING:
case INSN_CONFIG_GET_PWM_STATUS:
case INSN_CONFIG_PWM_SET_PERIOD:
case INSN_CONFIG_PWM_GET_PERIOD:
if (insn->n == 2)
return 0;
break;
case INSN_CONFIG_SET_GATE_SRC:
case INSN_CONFIG_GET_GATE_SRC:
case INSN_CONFIG_SET_CLOCK_SRC:
case INSN_CONFIG_GET_CLOCK_SRC:
case INSN_CONFIG_SET_OTHER_SRC:
case INSN_CONFIG_GET_COUNTER_STATUS:
case INSN_CONFIG_PWM_SET_H_BRIDGE:
case INSN_CONFIG_PWM_GET_H_BRIDGE:
case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
if (insn->n == 3)
return 0;
break;
case INSN_CONFIG_PWM_OUTPUT:
case INSN_CONFIG_ANALOG_TRIG:
if (insn->n == 5)
return 0;
break;
/* by default we allow the insn since we don't have checks for
* all possible cases yet */
default:
printk(KERN_WARNING
"comedi: no check for data length of config insn id "
"%i is implemented.\n"
" Add a check to %s in %s.\n"
" Assuming n=%i is correct.\n", data[0], __func__,
__FILE__, insn->n);
return 0;
break;
}
return -EINVAL;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file)
{
struct comedi_subdevice *s;
int ret = 0;
int i;
if (insn->insn & INSN_MASK_SPECIAL) {
/* a non-subdevice instruction */
switch (insn->insn) {
case INSN_GTOD:
{
struct timeval tv;
if (insn->n != 2) {
ret = -EINVAL;
break;
}
do_gettimeofday(&tv);
data[0] = tv.tv_sec;
data[1] = tv.tv_usec;
ret = 2;
break;
}
case INSN_WAIT:
if (insn->n != 1 || data[0] >= 100000) {
ret = -EINVAL;
break;
}
udelay(data[0] / 1000);
ret = 1;
break;
case INSN_INTTRIG:
if (insn->n != 1) {
ret = -EINVAL;
break;
}
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("%d not usable subdevice\n",
insn->subdev);
ret = -EINVAL;
break;
}
s = dev->subdevices + insn->subdev;
if (!s->async) {
DPRINTK("no async\n");
ret = -EINVAL;
break;
}
if (!s->async->inttrig) {
DPRINTK("no inttrig\n");
ret = -EAGAIN;
break;
}
ret = s->async->inttrig(dev, s, insn->data[0]);
if (ret >= 0)
ret = 1;
break;
default:
DPRINTK("invalid insn\n");
ret = -EINVAL;
break;
}
} else {
/* a subdevice instruction */
unsigned int maxdata;
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("subdevice %d out of range\n", insn->subdev);
ret = -EINVAL;
goto out;
}
s = dev->subdevices + insn->subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not usable subdevice\n", insn->subdev);
ret = -EIO;
goto out;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("device locked\n");
ret = -EACCES;
goto out;
}
ret = comedi_check_chanlist(s, 1, &insn->chanspec);
if (ret < 0) {
ret = -EINVAL;
DPRINTK("bad chanspec\n");
goto out;
}
if (s->busy) {
ret = -EBUSY;
goto out;
}
/* This looks arbitrary. It is. */
s->busy = &parse_insn;
switch (insn->insn) {
case INSN_READ:
ret = s->insn_read(dev, s, insn, data);
break;
case INSN_WRITE:
maxdata = s->maxdata_list
? s->maxdata_list[CR_CHAN(insn->chanspec)]
: s->maxdata;
for (i = 0; i < insn->n; ++i) {
if (data[i] > maxdata) {
ret = -EINVAL;
DPRINTK("bad data value(s)\n");
break;
}
}
if (ret == 0)
ret = s->insn_write(dev, s, insn, data);
break;
case INSN_BITS:
if (insn->n != 2) {
ret = -EINVAL;
} else {
/* Most drivers ignore the base channel in
* insn->chanspec. Fix this here if
* the subdevice has <= 32 channels. */
unsigned int shift;
unsigned int orig_mask;
orig_mask = data[0];
if (s->n_chan <= 32) {
shift = CR_CHAN(insn->chanspec);
if (shift > 0) {
insn->chanspec = 0;
data[0] <<= shift;
data[1] <<= shift;
}
} else
shift = 0;
ret = s->insn_bits(dev, s, insn, data);
data[0] = orig_mask;
if (shift > 0)
data[1] >>= shift;
}
break;
case INSN_CONFIG:
ret = check_insn_config_length(insn, data);
if (ret)
break;
ret = s->insn_config(dev, s, insn, data);
break;
default:
ret = -EINVAL;
break;
}
s->busy = NULL;
}
out:
return ret;
}
/*
* COMEDI_INSN
* synchronous instructions
*
* arg:
* pointer to insn
*
* reads:
* struct comedi_insn struct at arg
* data (for writes)
*
* writes:
* data (for reads)
*/
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file)
{
struct comedi_insn insn;
unsigned int *data = NULL;
int ret = 0;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
ret = -ENOMEM;
goto error;
}
if (copy_from_user(&insn, arg, sizeof(struct comedi_insn))) {
ret = -EFAULT;
goto error;
}
/* This is where the behavior of insn and insnlist deviate. */
if (insn.n > MAX_SAMPLES)
insn.n = MAX_SAMPLES;
if (insn.insn & INSN_MASK_WRITE) {
if (copy_from_user(data,
insn.data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, &insn, data, file);
if (ret < 0)
goto error;
if (insn.insn & INSN_MASK_READ) {
if (copy_to_user(insn.data,
data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = insn.n;
error:
kfree(data);
return ret;
}
static void comedi_set_subdevice_runflags(struct comedi_subdevice *s,
unsigned mask, unsigned bits)
{
unsigned long flags;
spin_lock_irqsave(&s->spin_lock, flags);
s->runflags &= ~mask;
s->runflags |= (bits & mask);
spin_unlock_irqrestore(&s->spin_lock, flags);
}
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *cmd, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
struct comedi_async *async;
int ret = 0;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
async = s->async;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest || !s->async) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("subdevice locked\n");
return -EACCES;
}
/* are we busy? */
if (s->busy) {
DPRINTK("subdevice busy\n");
return -EBUSY;
}
s->busy = file;
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %u > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* make sure channel/gain list isn't too short */
if (user_cmd.chanlist_len < 1) {
DPRINTK("channel/gain list too short %u < 1\n",
user_cmd.chanlist_len);
ret = -EINVAL;
goto cleanup;
}
kfree(async->cmd.chanlist);
async->cmd = user_cmd;
async->cmd.data = NULL;
/* load channel/gain list */
async->cmd.chanlist =
kmalloc(async->cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!async->cmd.chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(async->cmd.chanlist, user_cmd.chanlist,
async->cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s,
async->cmd.chanlist_len,
async->cmd.chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
ret = s->do_cmdtest(dev, s, &async->cmd);
if (async->cmd.flags & TRIG_BOGUS || ret) {
DPRINTK("test returned %d\n", ret);
user_cmd = async->cmd;
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
user_cmd.data = NULL;
if (copy_to_user(cmd, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("fault writing cmd\n");
ret = -EFAULT;
goto cleanup;
}
ret = -EAGAIN;
goto cleanup;
}
if (!async->prealloc_bufsz) {
ret = -ENOMEM;
DPRINTK("no buffer (?)\n");
goto cleanup;
}
comedi_reset_async_buf(async);
async->cb_mask =
COMEDI_CB_EOA | COMEDI_CB_BLOCK | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW;
if (async->cmd.flags & TRIG_WAKE_EOS)
async->cb_mask |= COMEDI_CB_EOS;
comedi_set_subdevice_runflags(s, ~0, SRF_USER | SRF_RUNNING);
ret = s->do_cmd(dev, s);
if (ret == 0)
return 0;
cleanup:
do_become_nonbusy(dev, s);
return ret;
}
/*
COMEDI_CMDTEST
command testing ioctl
arg:
pointer to cmd structure
reads:
cmd structure at arg
channel/range list
writes:
modified cmd structure at arg
*/
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
int ret = 0;
unsigned int *chanlist = NULL;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, arg, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %d > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* load channel/gain list */
if (user_cmd.chanlist) {
chanlist =
kmalloc(user_cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(chanlist, user_cmd.chanlist,
user_cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s, user_cmd.chanlist_len, chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
user_cmd.chanlist = chanlist;
}
ret = s->do_cmdtest(dev, s, &user_cmd);
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
if (copy_to_user(arg, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
ret = -EFAULT;
goto cleanup;
}
cleanup:
kfree(chanlist);
return ret;
}
/*
COMEDI_LOCK
lock subdevice
arg:
subdevice number
reads:
none
writes:
none
*/
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
int ret = 0;
unsigned long flags;
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
spin_lock_irqsave(&s->spin_lock, flags);
if (s->busy || s->lock)
ret = -EBUSY;
else
s->lock = file;
spin_unlock_irqrestore(&s->spin_lock, flags);
#if 0
if (ret < 0)
return ret;
if (s->lock_f)
ret = s->lock_f(dev, s);
#endif
return ret;
}
/*
COMEDI_UNLOCK
unlock subdevice
arg:
subdevice number
reads:
none
writes:
none
This function isn't protected by the semaphore, since
we already own the lock.
*/
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->busy)
return -EBUSY;
if (s->lock && s->lock != file)
return -EACCES;
if (s->lock == file) {
#if 0
if (s->unlock)
s->unlock(dev, s);
#endif
s->lock = NULL;
}
return 0;
}
/*
COMEDI_CANCEL
cancel acquisition ioctl
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->async == NULL)
return -EINVAL;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
return do_cancel(dev, s);
}
/*
COMEDI_POLL ioctl
instructs driver to synchronize buffers
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_poll_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
if (s->poll)
return s->poll(dev, s);
return -EINVAL;
}
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
int ret = 0;
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) && s->cancel)
ret = s->cancel(dev, s);
do_become_nonbusy(dev, s);
return ret;
}
static void comedi_unmap(struct vm_area_struct *area)
{
struct comedi_async *async;
struct comedi_device *dev;
async = area->vm_private_data;
dev = async->subdevice->device;
mutex_lock(&dev->mutex);
async->mmap_count--;
mutex_unlock(&dev->mutex);
}
static struct vm_operations_struct comedi_vm_ops = {
.close = comedi_unmap,
};
static int comedi_mmap(struct file *file, struct vm_area_struct *vma)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
struct comedi_async *async = NULL;
unsigned long start = vma->vm_start;
unsigned long size;
int n_pages;
int i;
int retval;
struct comedi_subdevice *s;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
if (vma->vm_flags & VM_WRITE)
s = comedi_get_write_subdevice(dev_file_info);
else
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EINVAL;
goto done;
}
async = s->async;
if (async == NULL) {
retval = -EINVAL;
goto done;
}
if (vma->vm_pgoff != 0) {
DPRINTK("comedi: mmap() offset must be 0.\n");
retval = -EINVAL;
goto done;
}
size = vma->vm_end - vma->vm_start;
if (size > async->prealloc_bufsz) {
retval = -EFAULT;
goto done;
}
if (size & (~PAGE_MASK)) {
retval = -EFAULT;
goto done;
}
n_pages = size >> PAGE_SHIFT;
for (i = 0; i < n_pages; ++i) {
if (remap_pfn_range(vma, start,
page_to_pfn(virt_to_page
(async->buf_page_list
[i].virt_addr)), PAGE_SIZE,
PAGE_SHARED)) {
retval = -EAGAIN;
goto done;
}
start += PAGE_SIZE;
}
vma->vm_ops = &comedi_vm_ops;
vma->vm_private_data = async;
async->mmap_count++;
retval = 0;
done:
mutex_unlock(&dev->mutex);
return retval;
}
static unsigned int comedi_poll(struct file *file, poll_table * wait)
{
unsigned int mask = 0;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
struct comedi_subdevice *read_subdev;
struct comedi_subdevice *write_subdev;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
mutex_unlock(&dev->mutex);
return 0;
}
mask = 0;
read_subdev = comedi_get_read_subdevice(dev_file_info);
if (read_subdev) {
poll_wait(file, &read_subdev->async->wait_head, wait);
if (!read_subdev->busy
|| comedi_buf_read_n_available(read_subdev->async) > 0
|| !(comedi_get_subdevice_runflags(read_subdev) &
SRF_RUNNING)) {
mask |= POLLIN | POLLRDNORM;
}
}
write_subdev = comedi_get_write_subdevice(dev_file_info);
if (write_subdev) {
poll_wait(file, &write_subdev->async->wait_head, wait);
comedi_buf_write_alloc(write_subdev->async,
write_subdev->async->prealloc_bufsz);
if (!write_subdev->busy
|| !(comedi_get_subdevice_runflags(write_subdev) &
SRF_RUNNING)
|| comedi_buf_write_n_allocated(write_subdev->async) >=
bytes_per_sample(write_subdev->async->subdevice)) {
mask |= POLLOUT | POLLWRNORM;
}
}
mutex_unlock(&dev->mutex);
return mask;
}
static ssize_t comedi_write(struct file *file, const char __user *buf,
size_t nbytes, loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_write_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
if (count == 0) {
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
do_become_nonbusy(dev, s);
}
break;
}
n = nbytes;
m = n;
if (async->buf_write_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_write_ptr;
comedi_buf_write_alloc(async, async->prealloc_bufsz);
if (m > comedi_buf_write_n_allocated(async))
m = comedi_buf_write_n_allocated(async);
if (m < n)
n = m;
if (n == 0) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
schedule();
if (!s->busy)
break;
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_from_user(async->prealloc_buf + async->buf_write_ptr,
buf, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_write_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
static ssize_t comedi_read(struct file *file, char __user *buf, size_t nbytes,
loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
n = nbytes;
m = comedi_buf_read_n_available(async);
/* printk("%d available\n",m); */
if (async->buf_read_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_read_ptr;
/* printk("%d contiguous\n",m); */
if (m < n)
n = m;
if (n == 0) {
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
do_become_nonbusy(dev, s);
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
break;
}
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
schedule();
if (!s->busy) {
retval = 0;
break;
}
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_to_user(buf, async->prealloc_buf +
async->buf_read_ptr, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_read_alloc(async, n);
comedi_buf_read_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR | SRF_RUNNING)) &&
async->buf_read_count - async->buf_write_count == 0) {
do_become_nonbusy(dev, s);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
/*
This function restores a subdevice to an idle state.
*/
void do_become_nonbusy(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
comedi_set_subdevice_runflags(s, SRF_RUNNING, 0);
if (async) {
comedi_reset_async_buf(async);
async->inttrig = NULL;
} else {
printk(KERN_ERR
"BUG: (?) do_become_nonbusy called with async=0\n");
}
s->busy = NULL;
}
static int comedi_open(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev =
dev_file_info ? dev_file_info->device : NULL;
if (dev == NULL) {
DPRINTK("invalid minor number\n");
return -ENODEV;
}
/* This is slightly hacky, but we want module autoloading
* to work for root.
* case: user opens device, attached -> ok
* case: user opens device, unattached, in_request_module=0 -> autoload
* case: user opens device, unattached, in_request_module=1 -> fail
* case: root opens device, attached -> ok
* case: root opens device, unattached, in_request_module=1 -> ok
* (typically called from modprobe)
* case: root opens device, unattached, in_request_module=0 -> autoload
*
* The last could be changed to "-> ok", which would deny root
* autoloading.
*/
mutex_lock(&dev->mutex);
if (dev->attached)
goto ok;
if (!capable(CAP_NET_ADMIN) && dev->in_request_module) {
DPRINTK("in request module\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
if (capable(CAP_NET_ADMIN) && dev->in_request_module)
goto ok;
dev->in_request_module = 1;
#ifdef CONFIG_KMOD
mutex_unlock(&dev->mutex);
request_module("char-major-%i-%i", COMEDI_MAJOR, dev->minor);
mutex_lock(&dev->mutex);
#endif
dev->in_request_module = 0;
if (!dev->attached && !capable(CAP_NET_ADMIN)) {
DPRINTK("not attached and not CAP_NET_ADMIN\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
ok:
__module_get(THIS_MODULE);
if (dev->attached) {
if (!try_module_get(dev->driver->module)) {
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return -ENOSYS;
}
}
if (dev->attached && dev->use_count == 0 && dev->open) {
int rc = dev->open(dev);
if (rc < 0) {
module_put(dev->driver->module);
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return rc;
}
}
dev->use_count++;
mutex_unlock(&dev->mutex);
return 0;
}
static int comedi_close(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
struct comedi_subdevice *s = NULL;
int i;
mutex_lock(&dev->mutex);
if (dev->subdevices) {
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy == file)
do_cancel(dev, s);
if (s->lock == file)
s->lock = NULL;
}
}
if (dev->attached && dev->use_count == 1 && dev->close)
dev->close(dev);
module_put(THIS_MODULE);
if (dev->attached)
module_put(dev->driver->module);
dev->use_count--;
mutex_unlock(&dev->mutex);
if (file->f_flags & FASYNC)
comedi_fasync(-1, file, 0);
return 0;
}
static int comedi_fasync(int fd, struct file *file, int on)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev = dev_file_info->device;
return fasync_helper(fd, file, on, &dev->async_queue);
}
const struct file_operations comedi_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = comedi_unlocked_ioctl,
.compat_ioctl = comedi_compat_ioctl,
.open = comedi_open,
.release = comedi_close,
.read = comedi_read,
.write = comedi_write,
.mmap = comedi_mmap,
.poll = comedi_poll,
.fasync = comedi_fasync,
.llseek = noop_llseek,
};
struct class *comedi_class;
static struct cdev comedi_cdev;
static void comedi_cleanup_legacy_minors(void)
{
unsigned i;
for (i = 0; i < comedi_num_legacy_minors; i++)
comedi_free_board_minor(i);
}
static int __init comedi_init(void)
{
int i;
int retval;
printk(KERN_INFO "comedi: version " COMEDI_RELEASE
" - http://www.comedi.org\n");
if (comedi_num_legacy_minors < 0 ||
comedi_num_legacy_minors > COMEDI_NUM_BOARD_MINORS) {
printk(KERN_ERR "comedi: error: invalid value for module "
"parameter \"comedi_num_legacy_minors\". Valid values "
"are 0 through %i.\n", COMEDI_NUM_BOARD_MINORS);
return -EINVAL;
}
/*
* comedi is unusable if both comedi_autoconfig and
* comedi_num_legacy_minors are zero, so we might as well adjust the
* defaults in that case
*/
if (comedi_autoconfig == 0 && comedi_num_legacy_minors == 0)
comedi_num_legacy_minors = 16;
memset(comedi_file_info_table, 0,
sizeof(struct comedi_device_file_info *) * COMEDI_NUM_MINORS);
retval = register_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS, "comedi");
if (retval)
return -EIO;
cdev_init(&comedi_cdev, &comedi_fops);
comedi_cdev.owner = THIS_MODULE;
kobject_set_name(&comedi_cdev.kobj, "comedi");
if (cdev_add(&comedi_cdev, MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS)) {
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return -EIO;
}
comedi_class = class_create(THIS_MODULE, "comedi");
if (IS_ERR(comedi_class)) {
printk(KERN_ERR "comedi: failed to create class");
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return PTR_ERR(comedi_class);
}
/* XXX requires /proc interface */
comedi_proc_init();
/* create devices files for legacy/manual use */
for (i = 0; i < comedi_num_legacy_minors; i++) {
int minor;
minor = comedi_alloc_board_minor(NULL);
if (minor < 0) {
comedi_cleanup_legacy_minors();
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return minor;
}
}
return 0;
}
static void __exit comedi_cleanup(void)
{
int i;
comedi_cleanup_legacy_minors();
for (i = 0; i < COMEDI_NUM_MINORS; ++i)
BUG_ON(comedi_file_info_table[i]);
class_destroy(comedi_class);
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS);
comedi_proc_cleanup();
}
module_init(comedi_init);
module_exit(comedi_cleanup);
void comedi_error(const struct comedi_device *dev, const char *s)
{
printk(KERN_ERR "comedi%d: %s: %s\n", dev->minor,
dev->driver->driver_name, s);
}
EXPORT_SYMBOL(comedi_error);
void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
unsigned runflags = 0;
unsigned runflags_mask = 0;
/* DPRINTK("comedi_event 0x%x\n",mask); */
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) == 0)
return;
if (s->
async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_RUNNING;
}
/* remember if an error event has occurred, so an error
* can be returned the next time the user does a read() */
if (s->async->events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_ERROR;
runflags |= SRF_ERROR;
}
if (runflags_mask) {
/*sets SRF_ERROR and SRF_RUNNING together atomically */
comedi_set_subdevice_runflags(s, runflags_mask, runflags);
}
if (async->cb_mask & s->async->events) {
if (comedi_get_subdevice_runflags(s) & SRF_USER) {
wake_up_interruptible(&async->wait_head);
if (s->subdev_flags & SDF_CMD_READ)
kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
if (s->subdev_flags & SDF_CMD_WRITE)
kill_fasync(&dev->async_queue, SIGIO, POLL_OUT);
} else {
if (async->cb_func)
async->cb_func(s->async->events, async->cb_arg);
}
}
s->async->events = 0;
}
EXPORT_SYMBOL(comedi_event);
unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s)
{
unsigned long flags;
unsigned runflags;
spin_lock_irqsave(&s->spin_lock, flags);
runflags = s->runflags;
spin_unlock_irqrestore(&s->spin_lock, flags);
return runflags;
}
EXPORT_SYMBOL(comedi_get_subdevice_runflags);
static int is_device_busy(struct comedi_device *dev)
{
struct comedi_subdevice *s;
int i;
if (!dev->attached)
return 0;
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy)
return 1;
if (s->async && s->async->mmap_count)
return 1;
}
return 0;
}
static void comedi_device_init(struct comedi_device *dev)
{
memset(dev, 0, sizeof(struct comedi_device));
spin_lock_init(&dev->spinlock);
mutex_init(&dev->mutex);
dev->minor = -1;
}
static void comedi_device_cleanup(struct comedi_device *dev)
{
if (dev == NULL)
return;
mutex_lock(&dev->mutex);
comedi_device_detach(dev);
mutex_unlock(&dev->mutex);
mutex_destroy(&dev->mutex);
}
int comedi_alloc_board_minor(struct device *hardware_device)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kzalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = kzalloc(sizeof(struct comedi_device), GFP_KERNEL);
if (info->device == NULL) {
kfree(info);
return -ENOMEM;
}
comedi_device_init(info->device);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_BOARD_MINORS) {
comedi_device_cleanup(info->device);
kfree(info->device);
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
info->device->minor = i;
csdev = COMEDI_DEVICE_CREATE(comedi_class, NULL,
MKDEV(COMEDI_MAJOR, i), NULL,
hardware_device, "comedi%i", i);
if (!IS_ERR(csdev))
info->device->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
return i;
}
void comedi_free_board_minor(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
comedi_file_info_table[minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (info) {
struct comedi_device *dev = info->device;
if (dev) {
if (dev->class_dev) {
device_destroy(comedi_class,
MKDEV(COMEDI_MAJOR, dev->minor));
}
comedi_device_cleanup(dev);
kfree(dev);
}
kfree(info);
}
}
int comedi_alloc_subdevice_minor(struct comedi_device *dev,
struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kmalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = dev;
info->read_subdevice = s;
info->write_subdevice = s;
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = COMEDI_FIRST_SUBDEVICE_MINOR; i < COMEDI_NUM_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_MINORS) {
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
s->minor = i;
csdev = COMEDI_DEVICE_CREATE(comedi_class, dev->class_dev,
MKDEV(COMEDI_MAJOR, i), NULL, NULL,
"comedi%i_subd%i", dev->minor,
(int)(s - dev->subdevices));
if (!IS_ERR(csdev))
s->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
return i;
}
void comedi_free_subdevice_minor(struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
if (s == NULL)
return;
if (s->minor < 0)
return;
BUG_ON(s->minor >= COMEDI_NUM_MINORS);
BUG_ON(s->minor < COMEDI_FIRST_SUBDEVICE_MINOR);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[s->minor];
comedi_file_info_table[s->minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (s->class_dev) {
device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor));
s->class_dev = NULL;
}
kfree(info);
}
struct comedi_device_file_info *comedi_get_device_file_info(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
return info;
}
EXPORT_SYMBOL_GPL(comedi_get_device_file_info);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size)
{
int retval;
if (new_size > async->max_bufsize)
return -EPERM;
if (s->busy) {
DPRINTK("subdevice is busy, cannot resize buffer\n");
return -EBUSY;
}
if (async->mmap_count) {
DPRINTK("subdevice is mmapped, cannot resize buffer\n");
return -EBUSY;
}
if (!async->prealloc_buf)
return -EINVAL;
/* make sure buffer is an integral number of pages
* (we round up) */
new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK;
retval = comedi_buf_alloc(dev, s, new_size);
if (retval < 0)
return retval;
if (s->buf_change) {
retval = s->buf_change(dev, s, new_size);
if (retval < 0)
return retval;
}
DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
dev->minor, (int)(s - dev->subdevices), async->prealloc_bufsz);
return 0;
}
/* sysfs attribute files */
static const unsigned bytes_per_kibi = 1024;
static ssize_t show_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
max_buffer_size_kb = read_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned long new_max_size_kb;
uint64_t new_max_size;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
if (strict_strtoul(buf, 10, &new_max_size_kb))
return -EINVAL;
if (new_max_size_kb != (uint32_t) new_max_size_kb)
return -EINVAL;
new_max_size = ((uint64_t) new_max_size_kb) * bytes_per_kibi;
if (new_max_size != (uint32_t) new_max_size)
return -EINVAL;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
read_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_read_buffer_kb = {
.attr = {
.name = "max_read_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_read_buffer_kb,
.store = &store_max_read_buffer_kb
};
static ssize_t show_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
buffer_size_kb = read_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned long new_size_kb;
uint64_t new_size;
int retval;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
if (strict_strtoul(buf, 10, &new_size_kb))
return -EINVAL;
if (new_size_kb != (uint32_t) new_size_kb)
return -EINVAL;
new_size = ((uint64_t) new_size_kb) * bytes_per_kibi;
if (new_size != (uint32_t) new_size)
return -EINVAL;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, read_subdevice,
read_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_read_buffer_kb = {
.attr = {
.name = "read_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_read_buffer_kb,
.store = &store_read_buffer_kb
};
static ssize_t show_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
max_buffer_size_kb = write_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned long new_max_size_kb;
uint64_t new_max_size;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
if (strict_strtoul(buf, 10, &new_max_size_kb))
return -EINVAL;
if (new_max_size_kb != (uint32_t) new_max_size_kb)
return -EINVAL;
new_max_size = ((uint64_t) new_max_size_kb) * bytes_per_kibi;
if (new_max_size != (uint32_t) new_max_size)
return -EINVAL;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
write_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_write_buffer_kb = {
.attr = {
.name = "max_write_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_write_buffer_kb,
.store = &store_max_write_buffer_kb
};
static ssize_t show_write_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
buffer_size_kb = write_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned long new_size_kb;
uint64_t new_size;
int retval;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
if (strict_strtoul(buf, 10, &new_size_kb))
return -EINVAL;
if (new_size_kb != (uint32_t) new_size_kb)
return -EINVAL;
new_size = ((uint64_t) new_size_kb) * bytes_per_kibi;
if (new_size != (uint32_t) new_size)
return -EINVAL;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, write_subdevice,
write_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_write_buffer_kb = {
.attr = {
.name = "write_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_write_buffer_kb,
.store = &store_write_buffer_kb
};
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3485_0 |
crossvul-cpp_data_bad_2526_0 | /*
* Timers abstract layer
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/sched/signal.h>
#include <sound/core.h>
#include <sound/timer.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/minors.h>
#include <sound/initval.h>
#include <linux/kmod.h>
/* internal flags */
#define SNDRV_TIMER_IFLG_PAUSED 0x00010000
#if IS_ENABLED(CONFIG_SND_HRTIMER)
#define DEFAULT_TIMER_LIMIT 4
#else
#define DEFAULT_TIMER_LIMIT 1
#endif
static int timer_limit = DEFAULT_TIMER_LIMIT;
static int timer_tstamp_monotonic = 1;
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("ALSA timer interface");
MODULE_LICENSE("GPL");
module_param(timer_limit, int, 0444);
MODULE_PARM_DESC(timer_limit, "Maximum global timers in system.");
module_param(timer_tstamp_monotonic, int, 0444);
MODULE_PARM_DESC(timer_tstamp_monotonic, "Use posix monotonic clock source for timestamps (default).");
MODULE_ALIAS_CHARDEV(CONFIG_SND_MAJOR, SNDRV_MINOR_TIMER);
MODULE_ALIAS("devname:snd/timer");
struct snd_timer_user {
struct snd_timer_instance *timeri;
int tread; /* enhanced read with timestamps and events */
unsigned long ticks;
unsigned long overrun;
int qhead;
int qtail;
int qused;
int queue_size;
bool disconnected;
struct snd_timer_read *queue;
struct snd_timer_tread *tqueue;
spinlock_t qlock;
unsigned long last_resolution;
unsigned int filter;
struct timespec tstamp; /* trigger tstamp */
wait_queue_head_t qchange_sleep;
struct fasync_struct *fasync;
struct mutex ioctl_lock;
};
/* list of timers */
static LIST_HEAD(snd_timer_list);
/* list of slave instances */
static LIST_HEAD(snd_timer_slave_list);
/* lock for slave active lists */
static DEFINE_SPINLOCK(slave_active_lock);
static DEFINE_MUTEX(register_mutex);
static int snd_timer_free(struct snd_timer *timer);
static int snd_timer_dev_free(struct snd_device *device);
static int snd_timer_dev_register(struct snd_device *device);
static int snd_timer_dev_disconnect(struct snd_device *device);
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left);
/*
* create a timer instance with the given owner string.
* when timer is not NULL, increments the module counter
*/
static struct snd_timer_instance *snd_timer_instance_new(char *owner,
struct snd_timer *timer)
{
struct snd_timer_instance *timeri;
timeri = kzalloc(sizeof(*timeri), GFP_KERNEL);
if (timeri == NULL)
return NULL;
timeri->owner = kstrdup(owner, GFP_KERNEL);
if (! timeri->owner) {
kfree(timeri);
return NULL;
}
INIT_LIST_HEAD(&timeri->open_list);
INIT_LIST_HEAD(&timeri->active_list);
INIT_LIST_HEAD(&timeri->ack_list);
INIT_LIST_HEAD(&timeri->slave_list_head);
INIT_LIST_HEAD(&timeri->slave_active_head);
timeri->timer = timer;
if (timer && !try_module_get(timer->module)) {
kfree(timeri->owner);
kfree(timeri);
return NULL;
}
return timeri;
}
/*
* find a timer instance from the given timer id
*/
static struct snd_timer *snd_timer_find(struct snd_timer_id *tid)
{
struct snd_timer *timer = NULL;
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->tmr_class != tid->dev_class)
continue;
if ((timer->tmr_class == SNDRV_TIMER_CLASS_CARD ||
timer->tmr_class == SNDRV_TIMER_CLASS_PCM) &&
(timer->card == NULL ||
timer->card->number != tid->card))
continue;
if (timer->tmr_device != tid->device)
continue;
if (timer->tmr_subdevice != tid->subdevice)
continue;
return timer;
}
return NULL;
}
#ifdef CONFIG_MODULES
static void snd_timer_request(struct snd_timer_id *tid)
{
switch (tid->dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
if (tid->device < timer_limit)
request_module("snd-timer-%i", tid->device);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (tid->card < snd_ecards_limit)
request_module("snd-card-%i", tid->card);
break;
default:
break;
}
}
#endif
/*
* look for a master instance matching with the slave id of the given slave.
* when found, relink the open_link of the slave.
*
* call this with register_mutex down.
*/
static void snd_timer_check_slave(struct snd_timer_instance *slave)
{
struct snd_timer *timer;
struct snd_timer_instance *master;
/* FIXME: it's really dumb to look up all entries.. */
list_for_each_entry(timer, &snd_timer_list, device_list) {
list_for_each_entry(master, &timer->open_list_head, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list,
&master->slave_list_head);
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
spin_unlock_irq(&slave_active_lock);
return;
}
}
}
}
/*
* look for slave instances matching with the slave id of the given master.
* when found, relink the open_link of slaves.
*
* call this with register_mutex down.
*/
static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
spin_lock(&master->timer->lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock(&master->timer->lock);
spin_unlock_irq(&slave_active_lock);
}
}
}
/*
* open a timer instance
* when opening a master, the slave id must be here given.
*/
int snd_timer_open(struct snd_timer_instance **ti,
char *owner, struct snd_timer_id *tid,
unsigned int slave_id)
{
struct snd_timer *timer;
struct snd_timer_instance *timeri = NULL;
if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {
/* open a slave instance */
if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||
tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {
pr_debug("ALSA: timer: invalid slave class %i\n",
tid->dev_sclass);
return -EINVAL;
}
mutex_lock(®ister_mutex);
timeri = snd_timer_instance_new(owner, NULL);
if (!timeri) {
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = tid->device;
timeri->flags |= SNDRV_TIMER_IFLG_SLAVE;
list_add_tail(&timeri->open_list, &snd_timer_slave_list);
snd_timer_check_slave(timeri);
mutex_unlock(®ister_mutex);
*ti = timeri;
return 0;
}
/* open a master instance */
mutex_lock(®ister_mutex);
timer = snd_timer_find(tid);
#ifdef CONFIG_MODULES
if (!timer) {
mutex_unlock(®ister_mutex);
snd_timer_request(tid);
mutex_lock(®ister_mutex);
timer = snd_timer_find(tid);
}
#endif
if (!timer) {
mutex_unlock(®ister_mutex);
return -ENODEV;
}
if (!list_empty(&timer->open_list_head)) {
timeri = list_entry(timer->open_list_head.next,
struct snd_timer_instance, open_list);
if (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {
mutex_unlock(®ister_mutex);
return -EBUSY;
}
}
timeri = snd_timer_instance_new(owner, timer);
if (!timeri) {
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
/* take a card refcount for safe disconnection */
if (timer->card)
get_device(&timer->card->card_dev);
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = slave_id;
if (list_empty(&timer->open_list_head) && timer->hw.open) {
int err = timer->hw.open(timer);
if (err) {
kfree(timeri->owner);
kfree(timeri);
if (timer->card)
put_device(&timer->card->card_dev);
module_put(timer->module);
mutex_unlock(®ister_mutex);
return err;
}
}
list_add_tail(&timeri->open_list, &timer->open_list_head);
snd_timer_check_master(timeri);
mutex_unlock(®ister_mutex);
*ti = timeri;
return 0;
}
/*
* close a timer instance
*/
int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
/* force to stop the timer */
snd_timer_stop(timeri);
timer = timeri->timer;
if (timer) {
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
/* remove slave links */
spin_lock_irq(&slave_active_lock);
spin_lock(&timer->lock);
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
list_del_init(&slave->ack_list);
list_del_init(&slave->active_list);
}
spin_unlock(&timer->lock);
spin_unlock_irq(&slave_active_lock);
/* slave doesn't need to release timer resources below */
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
timer = NULL;
}
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer) {
if (list_empty(&timer->open_list_head) && timer->hw.close)
timer->hw.close(timer);
/* release a card refcount for safe disconnection */
if (timer->card)
put_device(&timer->card->card_dev);
module_put(timer->module);
}
mutex_unlock(®ister_mutex);
return 0;
}
unsigned long snd_timer_resolution(struct snd_timer_instance *timeri)
{
struct snd_timer * timer;
if (timeri == NULL)
return 0;
if ((timer = timeri->timer) != NULL) {
if (timer->hw.c_resolution)
return timer->hw.c_resolution(timer);
return timer->hw.resolution;
}
return 0;
}
static void snd_timer_notify1(struct snd_timer_instance *ti, int event)
{
struct snd_timer *timer;
unsigned long resolution = 0;
struct snd_timer_instance *ts;
struct timespec tstamp;
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_START ||
event > SNDRV_TIMER_EVENT_PAUSE))
return;
if (event == SNDRV_TIMER_EVENT_START ||
event == SNDRV_TIMER_EVENT_CONTINUE)
resolution = snd_timer_resolution(ti);
if (ti->ccallback)
ti->ccallback(ti, event, &tstamp, resolution);
if (ti->flags & SNDRV_TIMER_IFLG_SLAVE)
return;
timer = ti->timer;
if (timer == NULL)
return;
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
return;
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event + 100, &tstamp, resolution);
}
/* start/continue a master timer */
static int snd_timer_start1(struct snd_timer_instance *timeri,
bool start, unsigned long ticks)
{
struct snd_timer *timer;
int result;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (timer->card && timer->card->shutdown) {
result = -ENODEV;
goto unlock;
}
if (timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START)) {
result = -EBUSY;
goto unlock;
}
if (start)
timeri->ticks = timeri->cticks = ticks;
else if (!timeri->cticks)
timeri->cticks = 1;
timeri->pticks = 0;
list_move_tail(&timeri->active_list, &timer->active_list_head);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
goto __start_now;
timer->flags |= SNDRV_TIMER_FLG_RESCHED;
timeri->flags |= SNDRV_TIMER_IFLG_START;
result = 1; /* delayed start */
} else {
if (start)
timer->sticks = ticks;
timer->hw.start(timer);
__start_now:
timer->running++;
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
result = 0;
}
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* start/continue a slave timer */
static int snd_timer_start_slave(struct snd_timer_instance *timeri,
bool start)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
if (timeri->flags & SNDRV_TIMER_IFLG_RUNNING) {
spin_unlock_irqrestore(&slave_active_lock, flags);
return -EBUSY;
}
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
if (timeri->master && timeri->timer) {
spin_lock(&timeri->timer->lock);
list_add_tail(&timeri->active_list,
&timeri->master->slave_active_head);
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 1; /* delayed start */
}
/* stop/pause a master timer */
static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop)
{
struct snd_timer *timer;
int result = 0;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (!(timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START))) {
result = -EBUSY;
goto unlock;
}
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
if (timer->card && timer->card->shutdown)
goto unlock;
if (stop) {
timeri->cticks = timeri->ticks;
timeri->pticks = 0;
}
if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
!(--timer->running)) {
timer->hw.stop(timer);
if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
snd_timer_reschedule(timer, 0);
if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
}
}
timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
if (stop)
timeri->flags &= ~SNDRV_TIMER_IFLG_PAUSED;
else
timeri->flags |= SNDRV_TIMER_IFLG_PAUSED;
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_CONTINUE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* stop/pause a slave timer */
static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
if (!(timeri->flags & SNDRV_TIMER_IFLG_RUNNING)) {
spin_unlock_irqrestore(&slave_active_lock, flags);
return -EBUSY;
}
timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
if (timeri->timer) {
spin_lock(&timeri->timer->lock);
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_CONTINUE);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 0;
}
/*
* start the timer instance
*/
int snd_timer_start(struct snd_timer_instance *timeri, unsigned int ticks)
{
if (timeri == NULL || ticks < 1)
return -EINVAL;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, true);
else
return snd_timer_start1(timeri, true, ticks);
}
/*
* stop the timer instance.
*
* do not call this from the timer callback!
*/
int snd_timer_stop(struct snd_timer_instance *timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, true);
else
return snd_timer_stop1(timeri, true);
}
/*
* start again.. the tick is kept.
*/
int snd_timer_continue(struct snd_timer_instance *timeri)
{
/* timer can continue only after pause */
if (!(timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
return -EINVAL;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, false);
else
return snd_timer_start1(timeri, false, 0);
}
/*
* pause.. remember the ticks left
*/
int snd_timer_pause(struct snd_timer_instance * timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, false);
else
return snd_timer_stop1(timeri, false);
}
/*
* reschedule the timer
*
* start pending instances and check the scheduling ticks.
* when the scheduling ticks is changed set CHANGE flag to reprogram the timer.
*/
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti;
unsigned long ticks = ~0UL;
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->flags & SNDRV_TIMER_IFLG_START) {
ti->flags &= ~SNDRV_TIMER_IFLG_START;
ti->flags |= SNDRV_TIMER_IFLG_RUNNING;
timer->running++;
}
if (ti->flags & SNDRV_TIMER_IFLG_RUNNING) {
if (ticks > ti->cticks)
ticks = ti->cticks;
}
}
if (ticks == ~0UL) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
return;
}
if (ticks > timer->hw.ticks)
ticks = timer->hw.ticks;
if (ticks_left != ticks)
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
timer->sticks = ticks;
}
/*
* timer tasklet
*
*/
static void snd_timer_tasklet(unsigned long arg)
{
struct snd_timer *timer = (struct snd_timer *) arg;
struct snd_timer_instance *ti;
struct list_head *p;
unsigned long resolution, ticks;
unsigned long flags;
if (timer->card && timer->card->shutdown)
return;
spin_lock_irqsave(&timer->lock, flags);
/* now process all callbacks */
while (!list_empty(&timer->sack_list_head)) {
p = timer->sack_list_head.next; /* get first item */
ti = list_entry(p, struct snd_timer_instance, ack_list);
/* remove from ack_list and make empty */
list_del_init(p);
ticks = ti->pticks;
ti->pticks = 0;
resolution = ti->resolution;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* timer interrupt
*
* ticks_left is usually equal to timer->sticks.
*
*/
void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti, *ts, *tmp;
unsigned long resolution, ticks;
struct list_head *p, *ack_list_head;
unsigned long flags;
int use_tasklet = 0;
if (timer == NULL)
return;
if (timer->card && timer->card->shutdown)
return;
spin_lock_irqsave(&timer->lock, flags);
/* remember the current resolution */
if (timer->hw.c_resolution)
resolution = timer->hw.c_resolution(timer);
else
resolution = timer->hw.resolution;
/* loop for all active instances
* Here we cannot use list_for_each_entry because the active_list of a
* processed instance is relinked to done_list_head before the callback
* is called.
*/
list_for_each_entry_safe(ti, tmp, &timer->active_list_head,
active_list) {
if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING))
continue;
ti->pticks += ticks_left;
ti->resolution = resolution;
if (ti->cticks < ticks_left)
ti->cticks = 0;
else
ti->cticks -= ticks_left;
if (ti->cticks) /* not expired */
continue;
if (ti->flags & SNDRV_TIMER_IFLG_AUTO) {
ti->cticks = ti->ticks;
} else {
ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
--timer->running;
list_del_init(&ti->active_list);
}
if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) ||
(ti->flags & SNDRV_TIMER_IFLG_FAST))
ack_list_head = &timer->ack_list_head;
else
ack_list_head = &timer->sack_list_head;
if (list_empty(&ti->ack_list))
list_add_tail(&ti->ack_list, ack_list_head);
list_for_each_entry(ts, &ti->slave_active_head, active_list) {
ts->pticks = ti->pticks;
ts->resolution = resolution;
if (list_empty(&ts->ack_list))
list_add_tail(&ts->ack_list, ack_list_head);
}
}
if (timer->flags & SNDRV_TIMER_FLG_RESCHED)
snd_timer_reschedule(timer, timer->sticks);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_STOP) {
timer->hw.stop(timer);
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
}
if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) ||
(timer->flags & SNDRV_TIMER_FLG_CHANGE)) {
/* restart timer */
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
} else {
timer->hw.stop(timer);
}
/* now process all fast callbacks */
while (!list_empty(&timer->ack_list_head)) {
p = timer->ack_list_head.next; /* get first item */
ti = list_entry(p, struct snd_timer_instance, ack_list);
/* remove from ack_list and make empty */
list_del_init(p);
ticks = ti->pticks;
ti->pticks = 0;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
/* do we have any slow callbacks? */
use_tasklet = !list_empty(&timer->sack_list_head);
spin_unlock_irqrestore(&timer->lock, flags);
if (use_tasklet)
tasklet_schedule(&timer->task_queue);
}
/*
*/
int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid,
struct snd_timer **rtimer)
{
struct snd_timer *timer;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_timer_dev_free,
.dev_register = snd_timer_dev_register,
.dev_disconnect = snd_timer_dev_disconnect,
};
if (snd_BUG_ON(!tid))
return -EINVAL;
if (rtimer)
*rtimer = NULL;
timer = kzalloc(sizeof(*timer), GFP_KERNEL);
if (!timer)
return -ENOMEM;
timer->tmr_class = tid->dev_class;
timer->card = card;
timer->tmr_device = tid->device;
timer->tmr_subdevice = tid->subdevice;
if (id)
strlcpy(timer->id, id, sizeof(timer->id));
timer->sticks = 1;
INIT_LIST_HEAD(&timer->device_list);
INIT_LIST_HEAD(&timer->open_list_head);
INIT_LIST_HEAD(&timer->active_list_head);
INIT_LIST_HEAD(&timer->ack_list_head);
INIT_LIST_HEAD(&timer->sack_list_head);
spin_lock_init(&timer->lock);
tasklet_init(&timer->task_queue, snd_timer_tasklet,
(unsigned long)timer);
if (card != NULL) {
timer->module = card->module;
err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops);
if (err < 0) {
snd_timer_free(timer);
return err;
}
}
if (rtimer)
*rtimer = timer;
return 0;
}
static int snd_timer_free(struct snd_timer *timer)
{
if (!timer)
return 0;
mutex_lock(®ister_mutex);
if (! list_empty(&timer->open_list_head)) {
struct list_head *p, *n;
struct snd_timer_instance *ti;
pr_warn("ALSA: timer %p is busy?\n", timer);
list_for_each_safe(p, n, &timer->open_list_head) {
list_del_init(p);
ti = list_entry(p, struct snd_timer_instance, open_list);
ti->timer = NULL;
}
}
list_del(&timer->device_list);
mutex_unlock(®ister_mutex);
if (timer->private_free)
timer->private_free(timer);
kfree(timer);
return 0;
}
static int snd_timer_dev_free(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
return snd_timer_free(timer);
}
static int snd_timer_dev_register(struct snd_device *dev)
{
struct snd_timer *timer = dev->device_data;
struct snd_timer *timer1;
if (snd_BUG_ON(!timer || !timer->hw.start || !timer->hw.stop))
return -ENXIO;
if (!(timer->hw.flags & SNDRV_TIMER_HW_SLAVE) &&
!timer->hw.resolution && timer->hw.c_resolution == NULL)
return -EINVAL;
mutex_lock(®ister_mutex);
list_for_each_entry(timer1, &snd_timer_list, device_list) {
if (timer1->tmr_class > timer->tmr_class)
break;
if (timer1->tmr_class < timer->tmr_class)
continue;
if (timer1->card && timer->card) {
if (timer1->card->number > timer->card->number)
break;
if (timer1->card->number < timer->card->number)
continue;
}
if (timer1->tmr_device > timer->tmr_device)
break;
if (timer1->tmr_device < timer->tmr_device)
continue;
if (timer1->tmr_subdevice > timer->tmr_subdevice)
break;
if (timer1->tmr_subdevice < timer->tmr_subdevice)
continue;
/* conflicts.. */
mutex_unlock(®ister_mutex);
return -EBUSY;
}
list_add_tail(&timer->device_list, &timer1->device_list);
mutex_unlock(®ister_mutex);
return 0;
}
static int snd_timer_dev_disconnect(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_del_init(&timer->device_list);
/* wake up pending sleepers */
list_for_each_entry(ti, &timer->open_list_head, open_list) {
if (ti->disconnect)
ti->disconnect(ti);
}
mutex_unlock(®ister_mutex);
return 0;
}
void snd_timer_notify(struct snd_timer *timer, int event, struct timespec *tstamp)
{
unsigned long flags;
unsigned long resolution = 0;
struct snd_timer_instance *ti, *ts;
if (timer->card && timer->card->shutdown)
return;
if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE))
return;
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART ||
event > SNDRV_TIMER_EVENT_MRESUME))
return;
spin_lock_irqsave(&timer->lock, flags);
if (event == SNDRV_TIMER_EVENT_MSTART ||
event == SNDRV_TIMER_EVENT_MCONTINUE ||
event == SNDRV_TIMER_EVENT_MRESUME) {
if (timer->hw.c_resolution)
resolution = timer->hw.c_resolution(timer);
else
resolution = timer->hw.resolution;
}
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->ccallback)
ti->ccallback(ti, event, tstamp, resolution);
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event, tstamp, resolution);
}
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* exported functions for global timers
*/
int snd_timer_global_new(char *id, int device, struct snd_timer **rtimer)
{
struct snd_timer_id tid;
tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = -1;
tid.device = device;
tid.subdevice = 0;
return snd_timer_new(NULL, id, &tid, rtimer);
}
int snd_timer_global_free(struct snd_timer *timer)
{
return snd_timer_free(timer);
}
int snd_timer_global_register(struct snd_timer *timer)
{
struct snd_device dev;
memset(&dev, 0, sizeof(dev));
dev.device_data = timer;
return snd_timer_dev_register(&dev);
}
/*
* System timer
*/
struct snd_timer_system_private {
struct timer_list tlist;
unsigned long last_expires;
unsigned long last_jiffies;
unsigned long correction;
};
static void snd_timer_s_function(unsigned long data)
{
struct snd_timer *timer = (struct snd_timer *)data;
struct snd_timer_system_private *priv = timer->private_data;
unsigned long jiff = jiffies;
if (time_after(jiff, priv->last_expires))
priv->correction += (long)jiff - (long)priv->last_expires;
snd_timer_interrupt(timer, (long)jiff - (long)priv->last_jiffies);
}
static int snd_timer_s_start(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long njiff;
priv = (struct snd_timer_system_private *) timer->private_data;
njiff = (priv->last_jiffies = jiffies);
if (priv->correction > timer->sticks - 1) {
priv->correction -= timer->sticks - 1;
njiff++;
} else {
njiff += timer->sticks - priv->correction;
priv->correction = 0;
}
priv->last_expires = njiff;
mod_timer(&priv->tlist, njiff);
return 0;
}
static int snd_timer_s_stop(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long jiff;
priv = (struct snd_timer_system_private *) timer->private_data;
del_timer(&priv->tlist);
jiff = jiffies;
if (time_before(jiff, priv->last_expires))
timer->sticks = priv->last_expires - jiff;
else
timer->sticks = 1;
priv->correction = 0;
return 0;
}
static int snd_timer_s_close(struct snd_timer *timer)
{
struct snd_timer_system_private *priv;
priv = (struct snd_timer_system_private *)timer->private_data;
del_timer_sync(&priv->tlist);
return 0;
}
static struct snd_timer_hardware snd_timer_system =
{
.flags = SNDRV_TIMER_HW_FIRST | SNDRV_TIMER_HW_TASKLET,
.resolution = 1000000000L / HZ,
.ticks = 10000000L,
.close = snd_timer_s_close,
.start = snd_timer_s_start,
.stop = snd_timer_s_stop
};
static void snd_timer_free_system(struct snd_timer *timer)
{
kfree(timer->private_data);
}
static int snd_timer_register_system(void)
{
struct snd_timer *timer;
struct snd_timer_system_private *priv;
int err;
err = snd_timer_global_new("system", SNDRV_TIMER_GLOBAL_SYSTEM, &timer);
if (err < 0)
return err;
strcpy(timer->name, "system timer");
timer->hw = snd_timer_system;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
snd_timer_free(timer);
return -ENOMEM;
}
setup_timer(&priv->tlist, snd_timer_s_function, (unsigned long) timer);
timer->private_data = priv;
timer->private_free = snd_timer_free_system;
return snd_timer_global_register(timer);
}
#ifdef CONFIG_SND_PROC_FS
/*
* Info interface
*/
static void snd_timer_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_timer *timer;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->card && timer->card->shutdown)
continue;
switch (timer->tmr_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
snd_iprintf(buffer, "G%i: ", timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_CARD:
snd_iprintf(buffer, "C%i-%i: ",
timer->card->number, timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_PCM:
snd_iprintf(buffer, "P%i-%i-%i: ", timer->card->number,
timer->tmr_device, timer->tmr_subdevice);
break;
default:
snd_iprintf(buffer, "?%i-%i-%i-%i: ", timer->tmr_class,
timer->card ? timer->card->number : -1,
timer->tmr_device, timer->tmr_subdevice);
}
snd_iprintf(buffer, "%s :", timer->name);
if (timer->hw.resolution)
snd_iprintf(buffer, " %lu.%03luus (%lu ticks)",
timer->hw.resolution / 1000,
timer->hw.resolution % 1000,
timer->hw.ticks);
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
snd_iprintf(buffer, " SLAVE");
snd_iprintf(buffer, "\n");
list_for_each_entry(ti, &timer->open_list_head, open_list)
snd_iprintf(buffer, " Client %s : %s\n",
ti->owner ? ti->owner : "unknown",
ti->flags & (SNDRV_TIMER_IFLG_START |
SNDRV_TIMER_IFLG_RUNNING)
? "running" : "stopped");
}
mutex_unlock(®ister_mutex);
}
static struct snd_info_entry *snd_timer_proc_entry;
static void __init snd_timer_proc_init(void)
{
struct snd_info_entry *entry;
entry = snd_info_create_module_entry(THIS_MODULE, "timers", NULL);
if (entry != NULL) {
entry->c.text.read = snd_timer_proc_read;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
snd_timer_proc_entry = entry;
}
static void __exit snd_timer_proc_done(void)
{
snd_info_free_entry(snd_timer_proc_entry);
}
#else /* !CONFIG_SND_PROC_FS */
#define snd_timer_proc_init()
#define snd_timer_proc_done()
#endif
/*
* USER SPACE interface
*/
static void snd_timer_user_interrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_read *r;
int prev;
spin_lock(&tu->qlock);
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->queue[prev];
if (r->resolution == resolution) {
r->ticks += ticks;
goto __wake;
}
}
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
r = &tu->queue[tu->qtail++];
tu->qtail %= tu->queue_size;
r->resolution = resolution;
r->ticks = ticks;
tu->qused++;
}
__wake:
spin_unlock(&tu->qlock);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_append_to_tqueue(struct snd_timer_user *tu,
struct snd_timer_tread *tread)
{
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
memcpy(&tu->tqueue[tu->qtail++], tread, sizeof(*tread));
tu->qtail %= tu->queue_size;
tu->qused++;
}
}
static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,
int event,
struct timespec *tstamp,
unsigned long resolution)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread r1;
unsigned long flags;
if (event >= SNDRV_TIMER_EVENT_START &&
event <= SNDRV_TIMER_EVENT_PAUSE)
tu->tstamp = *tstamp;
if ((tu->filter & (1 << event)) == 0 || !tu->tread)
return;
memset(&r1, 0, sizeof(r1));
r1.event = event;
r1.tstamp = *tstamp;
r1.val = resolution;
spin_lock_irqsave(&tu->qlock, flags);
snd_timer_user_append_to_tqueue(tu, &r1);
spin_unlock_irqrestore(&tu->qlock, flags);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_disconnect(struct snd_timer_instance *timeri)
{
struct snd_timer_user *tu = timeri->callback_data;
tu->disconnected = true;
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread *r, r1;
struct timespec tstamp;
int prev, append = 0;
memset(&r1, 0, sizeof(r1));
memset(&tstamp, 0, sizeof(tstamp));
spin_lock(&tu->qlock);
if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) |
(1 << SNDRV_TIMER_EVENT_TICK))) == 0) {
spin_unlock(&tu->qlock);
return;
}
if (tu->last_resolution != resolution || ticks > 0) {
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&
tu->last_resolution != resolution) {
r1.event = SNDRV_TIMER_EVENT_RESOLUTION;
r1.tstamp = tstamp;
r1.val = resolution;
snd_timer_user_append_to_tqueue(tu, &r1);
tu->last_resolution = resolution;
append++;
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0)
goto __wake;
if (ticks == 0)
goto __wake;
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->tqueue[prev];
if (r->event == SNDRV_TIMER_EVENT_TICK) {
r->tstamp = tstamp;
r->val += ticks;
append++;
goto __wake;
}
}
r1.event = SNDRV_TIMER_EVENT_TICK;
r1.tstamp = tstamp;
r1.val = ticks;
snd_timer_user_append_to_tqueue(tu, &r1);
append++;
__wake:
spin_unlock(&tu->qlock);
if (append == 0)
return;
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static int snd_timer_user_open(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
tu = kzalloc(sizeof(*tu), GFP_KERNEL);
if (tu == NULL)
return -ENOMEM;
spin_lock_init(&tu->qlock);
init_waitqueue_head(&tu->qchange_sleep);
mutex_init(&tu->ioctl_lock);
tu->ticks = 1;
tu->queue_size = 128;
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL) {
kfree(tu);
return -ENOMEM;
}
file->private_data = tu;
return 0;
}
static int snd_timer_user_release(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
if (file->private_data) {
tu = file->private_data;
file->private_data = NULL;
mutex_lock(&tu->ioctl_lock);
if (tu->timeri)
snd_timer_close(tu->timeri);
mutex_unlock(&tu->ioctl_lock);
kfree(tu->queue);
kfree(tu->tqueue);
kfree(tu);
}
return 0;
}
static void snd_timer_user_zero_id(struct snd_timer_id *id)
{
id->dev_class = SNDRV_TIMER_CLASS_NONE;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = -1;
id->device = -1;
id->subdevice = -1;
}
static void snd_timer_user_copy_id(struct snd_timer_id *id, struct snd_timer *timer)
{
id->dev_class = timer->tmr_class;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = timer->card ? timer->card->number : -1;
id->device = timer->tmr_device;
id->subdevice = timer->tmr_subdevice;
}
static int snd_timer_user_next_device(struct snd_timer_id __user *_tid)
{
struct snd_timer_id id;
struct snd_timer *timer;
struct list_head *p;
if (copy_from_user(&id, _tid, sizeof(id)))
return -EFAULT;
mutex_lock(®ister_mutex);
if (id.dev_class < 0) { /* first item */
if (list_empty(&snd_timer_list))
snd_timer_user_zero_id(&id);
else {
timer = list_entry(snd_timer_list.next,
struct snd_timer, device_list);
snd_timer_user_copy_id(&id, timer);
}
} else {
switch (id.dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
id.device = id.device < 0 ? 0 : id.device + 1;
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > SNDRV_TIMER_CLASS_GLOBAL) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device >= id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (id.card < 0) {
id.card = 0;
} else {
if (id.device < 0) {
id.device = 0;
} else {
if (id.subdevice < 0)
id.subdevice = 0;
else
id.subdevice++;
}
}
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > id.dev_class) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_class < id.dev_class)
continue;
if (timer->card->number > id.card) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->card->number < id.card)
continue;
if (timer->tmr_device > id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device < id.device)
continue;
if (timer->tmr_subdevice > id.subdevice) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_subdevice < id.subdevice)
continue;
snd_timer_user_copy_id(&id, timer);
break;
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
default:
snd_timer_user_zero_id(&id);
}
}
mutex_unlock(®ister_mutex);
if (copy_to_user(_tid, &id, sizeof(*_tid)))
return -EFAULT;
return 0;
}
static int snd_timer_user_ginfo(struct file *file,
struct snd_timer_ginfo __user *_ginfo)
{
struct snd_timer_ginfo *ginfo;
struct snd_timer_id tid;
struct snd_timer *t;
struct list_head *p;
int err = 0;
ginfo = memdup_user(_ginfo, sizeof(*ginfo));
if (IS_ERR(ginfo))
return PTR_ERR(ginfo);
tid = ginfo->tid;
memset(ginfo, 0, sizeof(*ginfo));
ginfo->tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
ginfo->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
ginfo->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(ginfo->id, t->id, sizeof(ginfo->id));
strlcpy(ginfo->name, t->name, sizeof(ginfo->name));
ginfo->resolution = t->hw.resolution;
if (t->hw.resolution_min > 0) {
ginfo->resolution_min = t->hw.resolution_min;
ginfo->resolution_max = t->hw.resolution_max;
}
list_for_each(p, &t->open_list_head) {
ginfo->clients++;
}
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_ginfo, ginfo, sizeof(*ginfo)))
err = -EFAULT;
kfree(ginfo);
return err;
}
static int timer_set_gparams(struct snd_timer_gparams *gparams)
{
struct snd_timer *t;
int err;
mutex_lock(®ister_mutex);
t = snd_timer_find(&gparams->tid);
if (!t) {
err = -ENODEV;
goto _error;
}
if (!list_empty(&t->open_list_head)) {
err = -EBUSY;
goto _error;
}
if (!t->hw.set_period) {
err = -ENOSYS;
goto _error;
}
err = t->hw.set_period(t, gparams->period_num, gparams->period_den);
_error:
mutex_unlock(®ister_mutex);
return err;
}
static int snd_timer_user_gparams(struct file *file,
struct snd_timer_gparams __user *_gparams)
{
struct snd_timer_gparams gparams;
if (copy_from_user(&gparams, _gparams, sizeof(gparams)))
return -EFAULT;
return timer_set_gparams(&gparams);
}
static int snd_timer_user_gstatus(struct file *file,
struct snd_timer_gstatus __user *_gstatus)
{
struct snd_timer_gstatus gstatus;
struct snd_timer_id tid;
struct snd_timer *t;
int err = 0;
if (copy_from_user(&gstatus, _gstatus, sizeof(gstatus)))
return -EFAULT;
tid = gstatus.tid;
memset(&gstatus, 0, sizeof(gstatus));
gstatus.tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
if (t->hw.c_resolution)
gstatus.resolution = t->hw.c_resolution(t);
else
gstatus.resolution = t->hw.resolution;
if (t->hw.precise_resolution) {
t->hw.precise_resolution(t, &gstatus.resolution_num,
&gstatus.resolution_den);
} else {
gstatus.resolution_num = gstatus.resolution;
gstatus.resolution_den = 1000000000uL;
}
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_gstatus, &gstatus, sizeof(gstatus)))
err = -EFAULT;
return err;
}
static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
tu->timeri->disconnect = snd_timer_user_disconnect;
}
__err:
return err;
}
static int snd_timer_user_info(struct file *file,
struct snd_timer_info __user *_info)
{
struct snd_timer_user *tu;
struct snd_timer_info *info;
struct snd_timer *t;
int err = 0;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (! info)
return -ENOMEM;
info->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
info->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(info->id, t->id, sizeof(info->id));
strlcpy(info->name, t->name, sizeof(info->name));
info->resolution = t->hw.resolution;
if (copy_to_user(_info, info, sizeof(*_info)))
err = -EFAULT;
kfree(info);
return err;
}
static int snd_timer_user_params(struct file *file,
struct snd_timer_params __user *_params)
{
struct snd_timer_user *tu;
struct snd_timer_params params;
struct snd_timer *t;
struct snd_timer_read *tr;
struct snd_timer_tread *ttr;
int err;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
if (copy_from_user(¶ms, _params, sizeof(params)))
return -EFAULT;
if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE)) {
u64 resolution;
if (params.ticks < 1) {
err = -EINVAL;
goto _end;
}
/* Don't allow resolution less than 1ms */
resolution = snd_timer_resolution(tu->timeri);
resolution *= params.ticks;
if (resolution < 1000000) {
err = -EINVAL;
goto _end;
}
}
if (params.queue_size > 0 &&
(params.queue_size < 32 || params.queue_size > 1024)) {
err = -EINVAL;
goto _end;
}
if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)|
(1<<SNDRV_TIMER_EVENT_TICK)|
(1<<SNDRV_TIMER_EVENT_START)|
(1<<SNDRV_TIMER_EVENT_STOP)|
(1<<SNDRV_TIMER_EVENT_CONTINUE)|
(1<<SNDRV_TIMER_EVENT_PAUSE)|
(1<<SNDRV_TIMER_EVENT_SUSPEND)|
(1<<SNDRV_TIMER_EVENT_RESUME)|
(1<<SNDRV_TIMER_EVENT_MSTART)|
(1<<SNDRV_TIMER_EVENT_MSTOP)|
(1<<SNDRV_TIMER_EVENT_MCONTINUE)|
(1<<SNDRV_TIMER_EVENT_MPAUSE)|
(1<<SNDRV_TIMER_EVENT_MSUSPEND)|
(1<<SNDRV_TIMER_EVENT_MRESUME))) {
err = -EINVAL;
goto _end;
}
snd_timer_stop(tu->timeri);
spin_lock_irq(&t->lock);
tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO|
SNDRV_TIMER_IFLG_EXCLUSIVE|
SNDRV_TIMER_IFLG_EARLY_EVENT);
if (params.flags & SNDRV_TIMER_PSFLG_AUTO)
tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO;
if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE;
if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT;
spin_unlock_irq(&t->lock);
if (params.queue_size > 0 &&
(unsigned int)tu->queue_size != params.queue_size) {
if (tu->tread) {
ttr = kmalloc(params.queue_size * sizeof(*ttr),
GFP_KERNEL);
if (ttr) {
kfree(tu->tqueue);
tu->queue_size = params.queue_size;
tu->tqueue = ttr;
}
} else {
tr = kmalloc(params.queue_size * sizeof(*tr),
GFP_KERNEL);
if (tr) {
kfree(tu->queue);
tu->queue_size = params.queue_size;
tu->queue = tr;
}
}
}
tu->qhead = tu->qtail = tu->qused = 0;
if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) {
if (tu->tread) {
struct snd_timer_tread tread;
memset(&tread, 0, sizeof(tread));
tread.event = SNDRV_TIMER_EVENT_EARLY;
tread.tstamp.tv_sec = 0;
tread.tstamp.tv_nsec = 0;
tread.val = 0;
snd_timer_user_append_to_tqueue(tu, &tread);
} else {
struct snd_timer_read *r = &tu->queue[0];
r->resolution = 0;
r->ticks = 0;
tu->qused++;
tu->qtail++;
}
}
tu->filter = params.filter;
tu->ticks = params.ticks;
err = 0;
_end:
if (copy_to_user(_params, ¶ms, sizeof(params)))
return -EFAULT;
return err;
}
static int snd_timer_user_status(struct file *file,
struct snd_timer_status __user *_status)
{
struct snd_timer_user *tu;
struct snd_timer_status status;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
memset(&status, 0, sizeof(status));
status.tstamp = tu->tstamp;
status.resolution = snd_timer_resolution(tu->timeri);
status.lost = tu->timeri->lost;
status.overrun = tu->overrun;
spin_lock_irq(&tu->qlock);
status.queue = tu->qused;
spin_unlock_irq(&tu->qlock);
if (copy_to_user(_status, &status, sizeof(status)))
return -EFAULT;
return 0;
}
static int snd_timer_user_start(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
snd_timer_stop(tu->timeri);
tu->timeri->lost = 0;
tu->last_resolution = 0;
return (err = snd_timer_start(tu->timeri, tu->ticks)) < 0 ? err : 0;
}
static int snd_timer_user_stop(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
return (err = snd_timer_stop(tu->timeri)) < 0 ? err : 0;
}
static int snd_timer_user_continue(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
/* start timer instead of continue if it's not used before */
if (!(tu->timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
return snd_timer_user_start(file);
tu->timeri->lost = 0;
return (err = snd_timer_continue(tu->timeri)) < 0 ? err : 0;
}
static int snd_timer_user_pause(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
return (err = snd_timer_pause(tu->timeri)) < 0 ? err : 0;
}
enum {
SNDRV_TIMER_IOCTL_START_OLD = _IO('T', 0x20),
SNDRV_TIMER_IOCTL_STOP_OLD = _IO('T', 0x21),
SNDRV_TIMER_IOCTL_CONTINUE_OLD = _IO('T', 0x22),
SNDRV_TIMER_IOCTL_PAUSE_OLD = _IO('T', 0x23),
};
static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu;
void __user *argp = (void __user *)arg;
int __user *p = argp;
tu = file->private_data;
switch (cmd) {
case SNDRV_TIMER_IOCTL_PVERSION:
return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0;
case SNDRV_TIMER_IOCTL_NEXT_DEVICE:
return snd_timer_user_next_device(argp);
case SNDRV_TIMER_IOCTL_TREAD:
{
int xarg;
if (tu->timeri) /* too late */
return -EBUSY;
if (get_user(xarg, p))
return -EFAULT;
tu->tread = xarg ? 1 : 0;
return 0;
}
case SNDRV_TIMER_IOCTL_GINFO:
return snd_timer_user_ginfo(file, argp);
case SNDRV_TIMER_IOCTL_GPARAMS:
return snd_timer_user_gparams(file, argp);
case SNDRV_TIMER_IOCTL_GSTATUS:
return snd_timer_user_gstatus(file, argp);
case SNDRV_TIMER_IOCTL_SELECT:
return snd_timer_user_tselect(file, argp);
case SNDRV_TIMER_IOCTL_INFO:
return snd_timer_user_info(file, argp);
case SNDRV_TIMER_IOCTL_PARAMS:
return snd_timer_user_params(file, argp);
case SNDRV_TIMER_IOCTL_STATUS:
return snd_timer_user_status(file, argp);
case SNDRV_TIMER_IOCTL_START:
case SNDRV_TIMER_IOCTL_START_OLD:
return snd_timer_user_start(file);
case SNDRV_TIMER_IOCTL_STOP:
case SNDRV_TIMER_IOCTL_STOP_OLD:
return snd_timer_user_stop(file);
case SNDRV_TIMER_IOCTL_CONTINUE:
case SNDRV_TIMER_IOCTL_CONTINUE_OLD:
return snd_timer_user_continue(file);
case SNDRV_TIMER_IOCTL_PAUSE:
case SNDRV_TIMER_IOCTL_PAUSE_OLD:
return snd_timer_user_pause(file);
}
return -ENOTTY;
}
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu = file->private_data;
long ret;
mutex_lock(&tu->ioctl_lock);
ret = __snd_timer_user_ioctl(file, cmd, arg);
mutex_unlock(&tu->ioctl_lock);
return ret;
}
static int snd_timer_user_fasync(int fd, struct file * file, int on)
{
struct snd_timer_user *tu;
tu = file->private_data;
return fasync_helper(fd, file, on, &tu->fasync);
}
static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
schedule();
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
return result > 0 ? result : err;
}
static unsigned int snd_timer_user_poll(struct file *file, poll_table * wait)
{
unsigned int mask;
struct snd_timer_user *tu;
tu = file->private_data;
poll_wait(file, &tu->qchange_sleep, wait);
mask = 0;
if (tu->qused)
mask |= POLLIN | POLLRDNORM;
if (tu->disconnected)
mask |= POLLERR;
return mask;
}
#ifdef CONFIG_COMPAT
#include "timer_compat.c"
#else
#define snd_timer_user_ioctl_compat NULL
#endif
static const struct file_operations snd_timer_f_ops =
{
.owner = THIS_MODULE,
.read = snd_timer_user_read,
.open = snd_timer_user_open,
.release = snd_timer_user_release,
.llseek = no_llseek,
.poll = snd_timer_user_poll,
.unlocked_ioctl = snd_timer_user_ioctl,
.compat_ioctl = snd_timer_user_ioctl_compat,
.fasync = snd_timer_user_fasync,
};
/* unregister the system timer */
static void snd_timer_free_all(void)
{
struct snd_timer *timer, *n;
list_for_each_entry_safe(timer, n, &snd_timer_list, device_list)
snd_timer_free(timer);
}
static struct device timer_dev;
/*
* ENTRY functions
*/
static int __init alsa_timer_init(void)
{
int err;
snd_device_initialize(&timer_dev, NULL);
dev_set_name(&timer_dev, "timer");
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_register(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1,
"system timer");
#endif
err = snd_timer_register_system();
if (err < 0) {
pr_err("ALSA: unable to register system timer (%i)\n", err);
put_device(&timer_dev);
return err;
}
err = snd_register_device(SNDRV_DEVICE_TYPE_TIMER, NULL, 0,
&snd_timer_f_ops, NULL, &timer_dev);
if (err < 0) {
pr_err("ALSA: unable to register timer device (%i)\n", err);
snd_timer_free_all();
put_device(&timer_dev);
return err;
}
snd_timer_proc_init();
return 0;
}
static void __exit alsa_timer_exit(void)
{
snd_unregister_device(&timer_dev);
snd_timer_free_all();
put_device(&timer_dev);
snd_timer_proc_done();
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1);
#endif
}
module_init(alsa_timer_init)
module_exit(alsa_timer_exit)
EXPORT_SYMBOL(snd_timer_open);
EXPORT_SYMBOL(snd_timer_close);
EXPORT_SYMBOL(snd_timer_resolution);
EXPORT_SYMBOL(snd_timer_start);
EXPORT_SYMBOL(snd_timer_stop);
EXPORT_SYMBOL(snd_timer_continue);
EXPORT_SYMBOL(snd_timer_pause);
EXPORT_SYMBOL(snd_timer_new);
EXPORT_SYMBOL(snd_timer_notify);
EXPORT_SYMBOL(snd_timer_global_new);
EXPORT_SYMBOL(snd_timer_global_free);
EXPORT_SYMBOL(snd_timer_global_register);
EXPORT_SYMBOL(snd_timer_interrupt);
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2526_0 |
crossvul-cpp_data_bad_293_0 | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2017 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Pierre A. Joye <pierre@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef PHP_WIN32
#include "php.h"
#include "php_filestat.h"
#include "php_globals.h"
#include <WinBase.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_PWD_H
#include "win32/pwd.h"
#endif
#if HAVE_GRP_H
#include "win32/grp.h"
#endif
#include <errno.h>
#include <ctype.h>
#include "php_link.h"
#include "php_string.h"
/*
TODO:
- Create php_readlink (done), php_link and php_symlink in win32/link.c
- Expose them (PHPAPI) so extensions developers can use them
- define link/readlink/symlink to their php_ equivalent and use them in ext/standart/link.c
- this file is then useless and we have a portable link API
*/
#ifndef VOLUME_NAME_NT
#define VOLUME_NAME_NT 0x2
#endif
#ifndef VOLUME_NAME_DOS
#define VOLUME_NAME_DOS 0x0
#endif
/* {{{ proto string readlink(string filename)
Return the target of a symbolic link */
PHP_FUNCTION(readlink)
{
char *link;
size_t link_len;
char target[MAXPATHLEN];
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) {
return;
}
if (OPENBASEDIR_CHECKPATH(link)) {
RETURN_FALSE;
}
if (php_sys_readlink(link, target, MAXPATHLEN) == -1) {
php_error_docref(NULL, E_WARNING, "readlink failed to read the symbolic link (%s), error %d)", link, GetLastError());
RETURN_FALSE;
}
RETURN_STRING(target);
}
/* }}} */
/* {{{ proto int linkinfo(string filename)
Returns the st_dev field of the UNIX C stat structure describing the link */
PHP_FUNCTION(linkinfo)
{
char *link;
size_t link_len;
zend_stat_t sb;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) {
return;
}
ret = VCWD_STAT(link, &sb);
if (ret == -1) {
php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
RETURN_LONG(Z_L(-1));
}
RETURN_LONG((zend_long) sb.st_dev);
}
/* }}} */
/* {{{ proto int symlink(string target, string link)
Create a symbolic link */
PHP_FUNCTION(symlink)
{
char *topath, *frompath;
size_t topath_len, frompath_len;
BOOLEAN ret;
char source_p[MAXPATHLEN];
char dest_p[MAXPATHLEN];
char dirname[MAXPATHLEN];
size_t len;
DWORD attr;
HINSTANCE kernel32;
typedef BOOLEAN (WINAPI *csla_func)(LPCSTR, LPCSTR, DWORD);
csla_func pCreateSymbolicLinkA;
kernel32 = LoadLibrary("kernel32.dll");
if (kernel32) {
pCreateSymbolicLinkA = (csla_func)GetProcAddress(kernel32, "CreateSymbolicLinkA");
if (pCreateSymbolicLinkA == NULL) {
php_error_docref(NULL, E_WARNING, "Can't call CreateSymbolicLinkA");
RETURN_FALSE;
}
} else {
php_error_docref(NULL, E_WARNING, "Can't call get a handle on kernel32.dll");
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &topath, &topath_len, &frompath, &frompath_len) == FAILURE) {
return;
}
if (!expand_filepath(frompath, source_p)) {
php_error_docref(NULL, E_WARNING, "No such file or directory");
RETURN_FALSE;
}
memcpy(dirname, source_p, sizeof(source_p));
len = php_dirname(dirname, strlen(dirname));
if (!expand_filepath_ex(topath, dest_p, dirname, len)) {
php_error_docref(NULL, E_WARNING, "No such file or directory");
RETURN_FALSE;
}
if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ||
php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) )
{
php_error_docref(NULL, E_WARNING, "Unable to symlink to a URL");
RETURN_FALSE;
}
if (OPENBASEDIR_CHECKPATH(dest_p)) {
RETURN_FALSE;
}
if (OPENBASEDIR_CHECKPATH(source_p)) {
RETURN_FALSE;
}
if ((attr = GetFileAttributes(topath)) == INVALID_FILE_ATTRIBUTES) {
php_error_docref(NULL, E_WARNING, "Could not fetch file information(error %d)", GetLastError());
RETURN_FALSE;
}
/* For the source, an expanded path must be used (in ZTS an other thread could have changed the CWD).
* For the target the exact string given by the user must be used, relative or not, existing or not.
* The target is relative to the link itself, not to the CWD. */
ret = pCreateSymbolicLinkA(source_p, topath, (attr & FILE_ATTRIBUTE_DIRECTORY ? 1 : 0));
if (!ret) {
php_error_docref(NULL, E_WARNING, "Cannot create symlink, error code(%d)", GetLastError());
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int link(string target, string link)
Create a hard link */
PHP_FUNCTION(link)
{
char *topath, *frompath;
size_t topath_len, frompath_len;
int ret;
char source_p[MAXPATHLEN];
char dest_p[MAXPATHLEN];
/*First argument to link function is the target and hence should go to frompath
Second argument to link function is the link itself and hence should go to topath */
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &frompath, &frompath_len, &topath, &topath_len) == FAILURE) {
return;
}
if (!expand_filepath(frompath, source_p) || !expand_filepath(topath, dest_p)) {
php_error_docref(NULL, E_WARNING, "No such file or directory");
RETURN_FALSE;
}
if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ||
php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) )
{
php_error_docref(NULL, E_WARNING, "Unable to link to a URL");
RETURN_FALSE;
}
if (OPENBASEDIR_CHECKPATH(source_p)) {
RETURN_FALSE;
}
if (OPENBASEDIR_CHECKPATH(dest_p)) {
RETURN_FALSE;
}
#ifndef ZTS
ret = CreateHardLinkA(topath, frompath, NULL);
#else
ret = CreateHardLinkA(dest_p, source_p, NULL);
#endif
if (ret == 0) {
php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_293_0 |
crossvul-cpp_data_good_1626_0 | /*
* linux/fs/namespace.c
*
* (C) Copyright Al Viro 2000, 2001
* Released under GPL v2.
*
* Based on code from fs/super.c, copyright Linus Torvalds and others.
* Heavily rewritten.
*/
#include <linux/syscalls.h>
#include <linux/export.h>
#include <linux/capability.h>
#include <linux/mnt_namespace.h>
#include <linux/user_namespace.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/idr.h>
#include <linux/init.h> /* init_rootfs */
#include <linux/fs_struct.h> /* get_fs_root et.al. */
#include <linux/fsnotify.h> /* fsnotify_vfsmount_delete */
#include <linux/uaccess.h>
#include <linux/proc_ns.h>
#include <linux/magic.h>
#include <linux/bootmem.h>
#include <linux/task_work.h>
#include "pnode.h"
#include "internal.h"
static unsigned int m_hash_mask __read_mostly;
static unsigned int m_hash_shift __read_mostly;
static unsigned int mp_hash_mask __read_mostly;
static unsigned int mp_hash_shift __read_mostly;
static __initdata unsigned long mhash_entries;
static int __init set_mhash_entries(char *str)
{
if (!str)
return 0;
mhash_entries = simple_strtoul(str, &str, 0);
return 1;
}
__setup("mhash_entries=", set_mhash_entries);
static __initdata unsigned long mphash_entries;
static int __init set_mphash_entries(char *str)
{
if (!str)
return 0;
mphash_entries = simple_strtoul(str, &str, 0);
return 1;
}
__setup("mphash_entries=", set_mphash_entries);
static u64 event;
static DEFINE_IDA(mnt_id_ida);
static DEFINE_IDA(mnt_group_ida);
static DEFINE_SPINLOCK(mnt_id_lock);
static int mnt_id_start = 0;
static int mnt_group_start = 1;
static struct hlist_head *mount_hashtable __read_mostly;
static struct hlist_head *mountpoint_hashtable __read_mostly;
static struct kmem_cache *mnt_cache __read_mostly;
static DECLARE_RWSEM(namespace_sem);
/* /sys/fs */
struct kobject *fs_kobj;
EXPORT_SYMBOL_GPL(fs_kobj);
/*
* vfsmount lock may be taken for read to prevent changes to the
* vfsmount hash, ie. during mountpoint lookups or walking back
* up the tree.
*
* It should be taken for write in all cases where the vfsmount
* tree or hash is modified or when a vfsmount structure is modified.
*/
__cacheline_aligned_in_smp DEFINE_SEQLOCK(mount_lock);
static inline struct hlist_head *m_hash(struct vfsmount *mnt, struct dentry *dentry)
{
unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES);
tmp += ((unsigned long)dentry / L1_CACHE_BYTES);
tmp = tmp + (tmp >> m_hash_shift);
return &mount_hashtable[tmp & m_hash_mask];
}
static inline struct hlist_head *mp_hash(struct dentry *dentry)
{
unsigned long tmp = ((unsigned long)dentry / L1_CACHE_BYTES);
tmp = tmp + (tmp >> mp_hash_shift);
return &mountpoint_hashtable[tmp & mp_hash_mask];
}
/*
* allocation is serialized by namespace_sem, but we need the spinlock to
* serialize with freeing.
*/
static int mnt_alloc_id(struct mount *mnt)
{
int res;
retry:
ida_pre_get(&mnt_id_ida, GFP_KERNEL);
spin_lock(&mnt_id_lock);
res = ida_get_new_above(&mnt_id_ida, mnt_id_start, &mnt->mnt_id);
if (!res)
mnt_id_start = mnt->mnt_id + 1;
spin_unlock(&mnt_id_lock);
if (res == -EAGAIN)
goto retry;
return res;
}
static void mnt_free_id(struct mount *mnt)
{
int id = mnt->mnt_id;
spin_lock(&mnt_id_lock);
ida_remove(&mnt_id_ida, id);
if (mnt_id_start > id)
mnt_id_start = id;
spin_unlock(&mnt_id_lock);
}
/*
* Allocate a new peer group ID
*
* mnt_group_ida is protected by namespace_sem
*/
static int mnt_alloc_group_id(struct mount *mnt)
{
int res;
if (!ida_pre_get(&mnt_group_ida, GFP_KERNEL))
return -ENOMEM;
res = ida_get_new_above(&mnt_group_ida,
mnt_group_start,
&mnt->mnt_group_id);
if (!res)
mnt_group_start = mnt->mnt_group_id + 1;
return res;
}
/*
* Release a peer group ID
*/
void mnt_release_group_id(struct mount *mnt)
{
int id = mnt->mnt_group_id;
ida_remove(&mnt_group_ida, id);
if (mnt_group_start > id)
mnt_group_start = id;
mnt->mnt_group_id = 0;
}
/*
* vfsmount lock must be held for read
*/
static inline void mnt_add_count(struct mount *mnt, int n)
{
#ifdef CONFIG_SMP
this_cpu_add(mnt->mnt_pcp->mnt_count, n);
#else
preempt_disable();
mnt->mnt_count += n;
preempt_enable();
#endif
}
/*
* vfsmount lock must be held for write
*/
unsigned int mnt_get_count(struct mount *mnt)
{
#ifdef CONFIG_SMP
unsigned int count = 0;
int cpu;
for_each_possible_cpu(cpu) {
count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count;
}
return count;
#else
return mnt->mnt_count;
#endif
}
static void drop_mountpoint(struct fs_pin *p)
{
struct mount *m = container_of(p, struct mount, mnt_umount);
dput(m->mnt_ex_mountpoint);
pin_remove(p);
mntput(&m->mnt);
}
static struct mount *alloc_vfsmnt(const char *name)
{
struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL);
if (mnt) {
int err;
err = mnt_alloc_id(mnt);
if (err)
goto out_free_cache;
if (name) {
mnt->mnt_devname = kstrdup_const(name, GFP_KERNEL);
if (!mnt->mnt_devname)
goto out_free_id;
}
#ifdef CONFIG_SMP
mnt->mnt_pcp = alloc_percpu(struct mnt_pcp);
if (!mnt->mnt_pcp)
goto out_free_devname;
this_cpu_add(mnt->mnt_pcp->mnt_count, 1);
#else
mnt->mnt_count = 1;
mnt->mnt_writers = 0;
#endif
INIT_HLIST_NODE(&mnt->mnt_hash);
INIT_LIST_HEAD(&mnt->mnt_child);
INIT_LIST_HEAD(&mnt->mnt_mounts);
INIT_LIST_HEAD(&mnt->mnt_list);
INIT_LIST_HEAD(&mnt->mnt_expire);
INIT_LIST_HEAD(&mnt->mnt_share);
INIT_LIST_HEAD(&mnt->mnt_slave_list);
INIT_LIST_HEAD(&mnt->mnt_slave);
INIT_HLIST_NODE(&mnt->mnt_mp_list);
#ifdef CONFIG_FSNOTIFY
INIT_HLIST_HEAD(&mnt->mnt_fsnotify_marks);
#endif
init_fs_pin(&mnt->mnt_umount, drop_mountpoint);
}
return mnt;
#ifdef CONFIG_SMP
out_free_devname:
kfree_const(mnt->mnt_devname);
#endif
out_free_id:
mnt_free_id(mnt);
out_free_cache:
kmem_cache_free(mnt_cache, mnt);
return NULL;
}
/*
* Most r/o checks on a fs are for operations that take
* discrete amounts of time, like a write() or unlink().
* We must keep track of when those operations start
* (for permission checks) and when they end, so that
* we can determine when writes are able to occur to
* a filesystem.
*/
/*
* __mnt_is_readonly: check whether a mount is read-only
* @mnt: the mount to check for its write status
*
* This shouldn't be used directly ouside of the VFS.
* It does not guarantee that the filesystem will stay
* r/w, just that it is right *now*. This can not and
* should not be used in place of IS_RDONLY(inode).
* mnt_want/drop_write() will _keep_ the filesystem
* r/w.
*/
int __mnt_is_readonly(struct vfsmount *mnt)
{
if (mnt->mnt_flags & MNT_READONLY)
return 1;
if (mnt->mnt_sb->s_flags & MS_RDONLY)
return 1;
return 0;
}
EXPORT_SYMBOL_GPL(__mnt_is_readonly);
static inline void mnt_inc_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
this_cpu_inc(mnt->mnt_pcp->mnt_writers);
#else
mnt->mnt_writers++;
#endif
}
static inline void mnt_dec_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
this_cpu_dec(mnt->mnt_pcp->mnt_writers);
#else
mnt->mnt_writers--;
#endif
}
static unsigned int mnt_get_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
unsigned int count = 0;
int cpu;
for_each_possible_cpu(cpu) {
count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers;
}
return count;
#else
return mnt->mnt_writers;
#endif
}
static int mnt_is_readonly(struct vfsmount *mnt)
{
if (mnt->mnt_sb->s_readonly_remount)
return 1;
/* Order wrt setting s_flags/s_readonly_remount in do_remount() */
smp_rmb();
return __mnt_is_readonly(mnt);
}
/*
* Most r/o & frozen checks on a fs are for operations that take discrete
* amounts of time, like a write() or unlink(). We must keep track of when
* those operations start (for permission checks) and when they end, so that we
* can determine when writes are able to occur to a filesystem.
*/
/**
* __mnt_want_write - get write access to a mount without freeze protection
* @m: the mount on which to take a write
*
* This tells the low-level filesystem that a write is about to be performed to
* it, and makes sure that writes are allowed (mnt it read-write) before
* returning success. This operation does not protect against filesystem being
* frozen. When the write operation is finished, __mnt_drop_write() must be
* called. This is effectively a refcount.
*/
int __mnt_want_write(struct vfsmount *m)
{
struct mount *mnt = real_mount(m);
int ret = 0;
preempt_disable();
mnt_inc_writers(mnt);
/*
* The store to mnt_inc_writers must be visible before we pass
* MNT_WRITE_HOLD loop below, so that the slowpath can see our
* incremented count after it has set MNT_WRITE_HOLD.
*/
smp_mb();
while (ACCESS_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD)
cpu_relax();
/*
* After the slowpath clears MNT_WRITE_HOLD, mnt_is_readonly will
* be set to match its requirements. So we must not load that until
* MNT_WRITE_HOLD is cleared.
*/
smp_rmb();
if (mnt_is_readonly(m)) {
mnt_dec_writers(mnt);
ret = -EROFS;
}
preempt_enable();
return ret;
}
/**
* mnt_want_write - get write access to a mount
* @m: the mount on which to take a write
*
* This tells the low-level filesystem that a write is about to be performed to
* it, and makes sure that writes are allowed (mount is read-write, filesystem
* is not frozen) before returning success. When the write operation is
* finished, mnt_drop_write() must be called. This is effectively a refcount.
*/
int mnt_want_write(struct vfsmount *m)
{
int ret;
sb_start_write(m->mnt_sb);
ret = __mnt_want_write(m);
if (ret)
sb_end_write(m->mnt_sb);
return ret;
}
EXPORT_SYMBOL_GPL(mnt_want_write);
/**
* mnt_clone_write - get write access to a mount
* @mnt: the mount on which to take a write
*
* This is effectively like mnt_want_write, except
* it must only be used to take an extra write reference
* on a mountpoint that we already know has a write reference
* on it. This allows some optimisation.
*
* After finished, mnt_drop_write must be called as usual to
* drop the reference.
*/
int mnt_clone_write(struct vfsmount *mnt)
{
/* superblock may be r/o */
if (__mnt_is_readonly(mnt))
return -EROFS;
preempt_disable();
mnt_inc_writers(real_mount(mnt));
preempt_enable();
return 0;
}
EXPORT_SYMBOL_GPL(mnt_clone_write);
/**
* __mnt_want_write_file - get write access to a file's mount
* @file: the file who's mount on which to take a write
*
* This is like __mnt_want_write, but it takes a file and can
* do some optimisations if the file is open for write already
*/
int __mnt_want_write_file(struct file *file)
{
if (!(file->f_mode & FMODE_WRITER))
return __mnt_want_write(file->f_path.mnt);
else
return mnt_clone_write(file->f_path.mnt);
}
/**
* mnt_want_write_file - get write access to a file's mount
* @file: the file who's mount on which to take a write
*
* This is like mnt_want_write, but it takes a file and can
* do some optimisations if the file is open for write already
*/
int mnt_want_write_file(struct file *file)
{
int ret;
sb_start_write(file->f_path.mnt->mnt_sb);
ret = __mnt_want_write_file(file);
if (ret)
sb_end_write(file->f_path.mnt->mnt_sb);
return ret;
}
EXPORT_SYMBOL_GPL(mnt_want_write_file);
/**
* __mnt_drop_write - give up write access to a mount
* @mnt: the mount on which to give up write access
*
* Tells the low-level filesystem that we are done
* performing writes to it. Must be matched with
* __mnt_want_write() call above.
*/
void __mnt_drop_write(struct vfsmount *mnt)
{
preempt_disable();
mnt_dec_writers(real_mount(mnt));
preempt_enable();
}
/**
* mnt_drop_write - give up write access to a mount
* @mnt: the mount on which to give up write access
*
* Tells the low-level filesystem that we are done performing writes to it and
* also allows filesystem to be frozen again. Must be matched with
* mnt_want_write() call above.
*/
void mnt_drop_write(struct vfsmount *mnt)
{
__mnt_drop_write(mnt);
sb_end_write(mnt->mnt_sb);
}
EXPORT_SYMBOL_GPL(mnt_drop_write);
void __mnt_drop_write_file(struct file *file)
{
__mnt_drop_write(file->f_path.mnt);
}
void mnt_drop_write_file(struct file *file)
{
mnt_drop_write(file->f_path.mnt);
}
EXPORT_SYMBOL(mnt_drop_write_file);
static int mnt_make_readonly(struct mount *mnt)
{
int ret = 0;
lock_mount_hash();
mnt->mnt.mnt_flags |= MNT_WRITE_HOLD;
/*
* After storing MNT_WRITE_HOLD, we'll read the counters. This store
* should be visible before we do.
*/
smp_mb();
/*
* With writers on hold, if this value is zero, then there are
* definitely no active writers (although held writers may subsequently
* increment the count, they'll have to wait, and decrement it after
* seeing MNT_READONLY).
*
* It is OK to have counter incremented on one CPU and decremented on
* another: the sum will add up correctly. The danger would be when we
* sum up each counter, if we read a counter before it is incremented,
* but then read another CPU's count which it has been subsequently
* decremented from -- we would see more decrements than we should.
* MNT_WRITE_HOLD protects against this scenario, because
* mnt_want_write first increments count, then smp_mb, then spins on
* MNT_WRITE_HOLD, so it can't be decremented by another CPU while
* we're counting up here.
*/
if (mnt_get_writers(mnt) > 0)
ret = -EBUSY;
else
mnt->mnt.mnt_flags |= MNT_READONLY;
/*
* MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers
* that become unheld will see MNT_READONLY.
*/
smp_wmb();
mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
unlock_mount_hash();
return ret;
}
static void __mnt_unmake_readonly(struct mount *mnt)
{
lock_mount_hash();
mnt->mnt.mnt_flags &= ~MNT_READONLY;
unlock_mount_hash();
}
int sb_prepare_remount_readonly(struct super_block *sb)
{
struct mount *mnt;
int err = 0;
/* Racy optimization. Recheck the counter under MNT_WRITE_HOLD */
if (atomic_long_read(&sb->s_remove_count))
return -EBUSY;
lock_mount_hash();
list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
if (!(mnt->mnt.mnt_flags & MNT_READONLY)) {
mnt->mnt.mnt_flags |= MNT_WRITE_HOLD;
smp_mb();
if (mnt_get_writers(mnt) > 0) {
err = -EBUSY;
break;
}
}
}
if (!err && atomic_long_read(&sb->s_remove_count))
err = -EBUSY;
if (!err) {
sb->s_readonly_remount = 1;
smp_wmb();
}
list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD)
mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
}
unlock_mount_hash();
return err;
}
static void free_vfsmnt(struct mount *mnt)
{
kfree_const(mnt->mnt_devname);
#ifdef CONFIG_SMP
free_percpu(mnt->mnt_pcp);
#endif
kmem_cache_free(mnt_cache, mnt);
}
static void delayed_free_vfsmnt(struct rcu_head *head)
{
free_vfsmnt(container_of(head, struct mount, mnt_rcu));
}
/* call under rcu_read_lock */
bool legitimize_mnt(struct vfsmount *bastard, unsigned seq)
{
struct mount *mnt;
if (read_seqretry(&mount_lock, seq))
return false;
if (bastard == NULL)
return true;
mnt = real_mount(bastard);
mnt_add_count(mnt, 1);
if (likely(!read_seqretry(&mount_lock, seq)))
return true;
if (bastard->mnt_flags & MNT_SYNC_UMOUNT) {
mnt_add_count(mnt, -1);
return false;
}
rcu_read_unlock();
mntput(bastard);
rcu_read_lock();
return false;
}
/*
* find the first mount at @dentry on vfsmount @mnt.
* call under rcu_read_lock()
*/
struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry)
{
struct hlist_head *head = m_hash(mnt, dentry);
struct mount *p;
hlist_for_each_entry_rcu(p, head, mnt_hash)
if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry)
return p;
return NULL;
}
/*
* find the last mount at @dentry on vfsmount @mnt.
* mount_lock must be held.
*/
struct mount *__lookup_mnt_last(struct vfsmount *mnt, struct dentry *dentry)
{
struct mount *p, *res = NULL;
p = __lookup_mnt(mnt, dentry);
if (!p)
goto out;
if (!(p->mnt.mnt_flags & MNT_UMOUNT))
res = p;
hlist_for_each_entry_continue(p, mnt_hash) {
if (&p->mnt_parent->mnt != mnt || p->mnt_mountpoint != dentry)
break;
if (!(p->mnt.mnt_flags & MNT_UMOUNT))
res = p;
}
out:
return res;
}
/*
* lookup_mnt - Return the first child mount mounted at path
*
* "First" means first mounted chronologically. If you create the
* following mounts:
*
* mount /dev/sda1 /mnt
* mount /dev/sda2 /mnt
* mount /dev/sda3 /mnt
*
* Then lookup_mnt() on the base /mnt dentry in the root mount will
* return successively the root dentry and vfsmount of /dev/sda1, then
* /dev/sda2, then /dev/sda3, then NULL.
*
* lookup_mnt takes a reference to the found vfsmount.
*/
struct vfsmount *lookup_mnt(struct path *path)
{
struct mount *child_mnt;
struct vfsmount *m;
unsigned seq;
rcu_read_lock();
do {
seq = read_seqbegin(&mount_lock);
child_mnt = __lookup_mnt(path->mnt, path->dentry);
m = child_mnt ? &child_mnt->mnt : NULL;
} while (!legitimize_mnt(m, seq));
rcu_read_unlock();
return m;
}
/*
* __is_local_mountpoint - Test to see if dentry is a mountpoint in the
* current mount namespace.
*
* The common case is dentries are not mountpoints at all and that
* test is handled inline. For the slow case when we are actually
* dealing with a mountpoint of some kind, walk through all of the
* mounts in the current mount namespace and test to see if the dentry
* is a mountpoint.
*
* The mount_hashtable is not usable in the context because we
* need to identify all mounts that may be in the current mount
* namespace not just a mount that happens to have some specified
* parent mount.
*/
bool __is_local_mountpoint(struct dentry *dentry)
{
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;
bool is_covered = false;
if (!d_mountpoint(dentry))
goto out;
down_read(&namespace_sem);
list_for_each_entry(mnt, &ns->list, mnt_list) {
is_covered = (mnt->mnt_mountpoint == dentry);
if (is_covered)
break;
}
up_read(&namespace_sem);
out:
return is_covered;
}
static struct mountpoint *lookup_mountpoint(struct dentry *dentry)
{
struct hlist_head *chain = mp_hash(dentry);
struct mountpoint *mp;
hlist_for_each_entry(mp, chain, m_hash) {
if (mp->m_dentry == dentry) {
/* might be worth a WARN_ON() */
if (d_unlinked(dentry))
return ERR_PTR(-ENOENT);
mp->m_count++;
return mp;
}
}
return NULL;
}
static struct mountpoint *new_mountpoint(struct dentry *dentry)
{
struct hlist_head *chain = mp_hash(dentry);
struct mountpoint *mp;
int ret;
mp = kmalloc(sizeof(struct mountpoint), GFP_KERNEL);
if (!mp)
return ERR_PTR(-ENOMEM);
ret = d_set_mounted(dentry);
if (ret) {
kfree(mp);
return ERR_PTR(ret);
}
mp->m_dentry = dentry;
mp->m_count = 1;
hlist_add_head(&mp->m_hash, chain);
INIT_HLIST_HEAD(&mp->m_list);
return mp;
}
static void put_mountpoint(struct mountpoint *mp)
{
if (!--mp->m_count) {
struct dentry *dentry = mp->m_dentry;
BUG_ON(!hlist_empty(&mp->m_list));
spin_lock(&dentry->d_lock);
dentry->d_flags &= ~DCACHE_MOUNTED;
spin_unlock(&dentry->d_lock);
hlist_del(&mp->m_hash);
kfree(mp);
}
}
static inline int check_mnt(struct mount *mnt)
{
return mnt->mnt_ns == current->nsproxy->mnt_ns;
}
/*
* vfsmount lock must be held for write
*/
static void touch_mnt_namespace(struct mnt_namespace *ns)
{
if (ns) {
ns->event = ++event;
wake_up_interruptible(&ns->poll);
}
}
/*
* vfsmount lock must be held for write
*/
static void __touch_mnt_namespace(struct mnt_namespace *ns)
{
if (ns && ns->event != event) {
ns->event = event;
wake_up_interruptible(&ns->poll);
}
}
/*
* vfsmount lock must be held for write
*/
static void unhash_mnt(struct mount *mnt)
{
mnt->mnt_parent = mnt;
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
list_del_init(&mnt->mnt_child);
hlist_del_init_rcu(&mnt->mnt_hash);
hlist_del_init(&mnt->mnt_mp_list);
put_mountpoint(mnt->mnt_mp);
mnt->mnt_mp = NULL;
}
/*
* vfsmount lock must be held for write
*/
static void detach_mnt(struct mount *mnt, struct path *old_path)
{
old_path->dentry = mnt->mnt_mountpoint;
old_path->mnt = &mnt->mnt_parent->mnt;
unhash_mnt(mnt);
}
/*
* vfsmount lock must be held for write
*/
static void umount_mnt(struct mount *mnt)
{
/* old mountpoint will be dropped when we can do that */
mnt->mnt_ex_mountpoint = mnt->mnt_mountpoint;
unhash_mnt(mnt);
}
/*
* vfsmount lock must be held for write
*/
void mnt_set_mountpoint(struct mount *mnt,
struct mountpoint *mp,
struct mount *child_mnt)
{
mp->m_count++;
mnt_add_count(mnt, 1); /* essentially, that's mntget */
child_mnt->mnt_mountpoint = dget(mp->m_dentry);
child_mnt->mnt_parent = mnt;
child_mnt->mnt_mp = mp;
hlist_add_head(&child_mnt->mnt_mp_list, &mp->m_list);
}
/*
* vfsmount lock must be held for write
*/
static void attach_mnt(struct mount *mnt,
struct mount *parent,
struct mountpoint *mp)
{
mnt_set_mountpoint(parent, mp, mnt);
hlist_add_head_rcu(&mnt->mnt_hash, m_hash(&parent->mnt, mp->m_dentry));
list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
}
static void attach_shadowed(struct mount *mnt,
struct mount *parent,
struct mount *shadows)
{
if (shadows) {
hlist_add_behind_rcu(&mnt->mnt_hash, &shadows->mnt_hash);
list_add(&mnt->mnt_child, &shadows->mnt_child);
} else {
hlist_add_head_rcu(&mnt->mnt_hash,
m_hash(&parent->mnt, mnt->mnt_mountpoint));
list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
}
}
/*
* vfsmount lock must be held for write
*/
static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
static struct mount *next_mnt(struct mount *p, struct mount *root)
{
struct list_head *next = p->mnt_mounts.next;
if (next == &p->mnt_mounts) {
while (1) {
if (p == root)
return NULL;
next = p->mnt_child.next;
if (next != &p->mnt_parent->mnt_mounts)
break;
p = p->mnt_parent;
}
}
return list_entry(next, struct mount, mnt_child);
}
static struct mount *skip_mnt_tree(struct mount *p)
{
struct list_head *prev = p->mnt_mounts.prev;
while (prev != &p->mnt_mounts) {
p = list_entry(prev, struct mount, mnt_child);
prev = p->mnt_mounts.prev;
}
return p;
}
struct vfsmount *
vfs_kern_mount(struct file_system_type *type, int flags, const char *name, void *data)
{
struct mount *mnt;
struct dentry *root;
if (!type)
return ERR_PTR(-ENODEV);
mnt = alloc_vfsmnt(name);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flags & MS_KERNMOUNT)
mnt->mnt.mnt_flags = MNT_INTERNAL;
root = mount_fs(type, flags, name, data);
if (IS_ERR(root)) {
mnt_free_id(mnt);
free_vfsmnt(mnt);
return ERR_CAST(root);
}
mnt->mnt.mnt_root = root;
mnt->mnt.mnt_sb = root->d_sb;
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
lock_mount_hash();
list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts);
unlock_mount_hash();
return &mnt->mnt;
}
EXPORT_SYMBOL_GPL(vfs_kern_mount);
static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED);
/* Don't allow unprivileged users to change mount flags */
if (flag & CL_UNPRIVILEGED) {
mnt->mnt.mnt_flags |= MNT_LOCK_ATIME;
if (mnt->mnt.mnt_flags & MNT_READONLY)
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
if (mnt->mnt.mnt_flags & MNT_NODEV)
mnt->mnt.mnt_flags |= MNT_LOCK_NODEV;
if (mnt->mnt.mnt_flags & MNT_NOSUID)
mnt->mnt.mnt_flags |= MNT_LOCK_NOSUID;
if (mnt->mnt.mnt_flags & MNT_NOEXEC)
mnt->mnt.mnt_flags |= MNT_LOCK_NOEXEC;
}
/* Don't allow unprivileged users to reveal what is under a mount */
if ((flag & CL_UNPRIVILEGED) &&
(!(flag & CL_EXPIRE) || list_empty(&old->mnt_expire)))
mnt->mnt.mnt_flags |= MNT_LOCKED;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
lock_mount_hash();
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
unlock_mount_hash();
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
mnt_free_id(mnt);
free_vfsmnt(mnt);
return ERR_PTR(err);
}
static void cleanup_mnt(struct mount *mnt)
{
/*
* This probably indicates that somebody messed
* up a mnt_want/drop_write() pair. If this
* happens, the filesystem was probably unable
* to make r/w->r/o transitions.
*/
/*
* The locking used to deal with mnt_count decrement provides barriers,
* so mnt_get_writers() below is safe.
*/
WARN_ON(mnt_get_writers(mnt));
if (unlikely(mnt->mnt_pins.first))
mnt_pin_kill(mnt);
fsnotify_vfsmount_delete(&mnt->mnt);
dput(mnt->mnt.mnt_root);
deactivate_super(mnt->mnt.mnt_sb);
mnt_free_id(mnt);
call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt);
}
static void __cleanup_mnt(struct rcu_head *head)
{
cleanup_mnt(container_of(head, struct mount, mnt_rcu));
}
static LLIST_HEAD(delayed_mntput_list);
static void delayed_mntput(struct work_struct *unused)
{
struct llist_node *node = llist_del_all(&delayed_mntput_list);
struct llist_node *next;
for (; node; node = next) {
next = llist_next(node);
cleanup_mnt(llist_entry(node, struct mount, mnt_llist));
}
}
static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
static void mntput_no_expire(struct mount *mnt)
{
rcu_read_lock();
mnt_add_count(mnt, -1);
if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */
rcu_read_unlock();
return;
}
lock_mount_hash();
if (mnt_get_count(mnt)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
mnt->mnt.mnt_flags |= MNT_DOOMED;
rcu_read_unlock();
list_del(&mnt->mnt_instance);
if (unlikely(!list_empty(&mnt->mnt_mounts))) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
umount_mnt(p);
}
}
unlock_mount_hash();
if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) {
struct task_struct *task = current;
if (likely(!(task->flags & PF_KTHREAD))) {
init_task_work(&mnt->mnt_rcu, __cleanup_mnt);
if (!task_work_add(task, &mnt->mnt_rcu, true))
return;
}
if (llist_add(&mnt->mnt_llist, &delayed_mntput_list))
schedule_delayed_work(&delayed_mntput_work, 1);
return;
}
cleanup_mnt(mnt);
}
void mntput(struct vfsmount *mnt)
{
if (mnt) {
struct mount *m = real_mount(mnt);
/* avoid cacheline pingpong, hope gcc doesn't get "smart" */
if (unlikely(m->mnt_expiry_mark))
m->mnt_expiry_mark = 0;
mntput_no_expire(m);
}
}
EXPORT_SYMBOL(mntput);
struct vfsmount *mntget(struct vfsmount *mnt)
{
if (mnt)
mnt_add_count(real_mount(mnt), 1);
return mnt;
}
EXPORT_SYMBOL(mntget);
struct vfsmount *mnt_clone_internal(struct path *path)
{
struct mount *p;
p = clone_mnt(real_mount(path->mnt), path->dentry, CL_PRIVATE);
if (IS_ERR(p))
return ERR_CAST(p);
p->mnt.mnt_flags |= MNT_INTERNAL;
return &p->mnt;
}
static inline void mangle(struct seq_file *m, const char *s)
{
seq_escape(m, s, " \t\n\\");
}
/*
* Simple .show_options callback for filesystems which don't want to
* implement more complex mount option showing.
*
* See also save_mount_options().
*/
int generic_show_options(struct seq_file *m, struct dentry *root)
{
const char *options;
rcu_read_lock();
options = rcu_dereference(root->d_sb->s_options);
if (options != NULL && options[0]) {
seq_putc(m, ',');
mangle(m, options);
}
rcu_read_unlock();
return 0;
}
EXPORT_SYMBOL(generic_show_options);
/*
* If filesystem uses generic_show_options(), this function should be
* called from the fill_super() callback.
*
* The .remount_fs callback usually needs to be handled in a special
* way, to make sure, that previous options are not overwritten if the
* remount fails.
*
* Also note, that if the filesystem's .remount_fs function doesn't
* reset all options to their default value, but changes only newly
* given options, then the displayed options will not reflect reality
* any more.
*/
void save_mount_options(struct super_block *sb, char *options)
{
BUG_ON(sb->s_options);
rcu_assign_pointer(sb->s_options, kstrdup(options, GFP_KERNEL));
}
EXPORT_SYMBOL(save_mount_options);
void replace_mount_options(struct super_block *sb, char *options)
{
char *old = sb->s_options;
rcu_assign_pointer(sb->s_options, options);
if (old) {
synchronize_rcu();
kfree(old);
}
}
EXPORT_SYMBOL(replace_mount_options);
#ifdef CONFIG_PROC_FS
/* iterator; we want it to have access to namespace_sem, thus here... */
static void *m_start(struct seq_file *m, loff_t *pos)
{
struct proc_mounts *p = proc_mounts(m);
down_read(&namespace_sem);
if (p->cached_event == p->ns->event) {
void *v = p->cached_mount;
if (*pos == p->cached_index)
return v;
if (*pos == p->cached_index + 1) {
v = seq_list_next(v, &p->ns->list, &p->cached_index);
return p->cached_mount = v;
}
}
p->cached_event = p->ns->event;
p->cached_mount = seq_list_start(&p->ns->list, *pos);
p->cached_index = *pos;
return p->cached_mount;
}
static void *m_next(struct seq_file *m, void *v, loff_t *pos)
{
struct proc_mounts *p = proc_mounts(m);
p->cached_mount = seq_list_next(v, &p->ns->list, pos);
p->cached_index = *pos;
return p->cached_mount;
}
static void m_stop(struct seq_file *m, void *v)
{
up_read(&namespace_sem);
}
static int m_show(struct seq_file *m, void *v)
{
struct proc_mounts *p = proc_mounts(m);
struct mount *r = list_entry(v, struct mount, mnt_list);
return p->show(m, &r->mnt);
}
const struct seq_operations mounts_op = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = m_show,
};
#endif /* CONFIG_PROC_FS */
/**
* may_umount_tree - check if a mount tree is busy
* @mnt: root of mount tree
*
* This is called to check if a tree of mounts has any
* open files, pwds, chroots or sub mounts that are
* busy.
*/
int may_umount_tree(struct vfsmount *m)
{
struct mount *mnt = real_mount(m);
int actual_refs = 0;
int minimum_refs = 0;
struct mount *p;
BUG_ON(!m);
/* write lock needed for mnt_get_count */
lock_mount_hash();
for (p = mnt; p; p = next_mnt(p, mnt)) {
actual_refs += mnt_get_count(p);
minimum_refs += 2;
}
unlock_mount_hash();
if (actual_refs > minimum_refs)
return 0;
return 1;
}
EXPORT_SYMBOL(may_umount_tree);
/**
* may_umount - check if a mount point is busy
* @mnt: root of mount
*
* This is called to check if a mount point has any
* open files, pwds, chroots or sub mounts. If the
* mount has sub mounts this will return busy
* regardless of whether the sub mounts are busy.
*
* Doesn't take quota and stuff into account. IOW, in some cases it will
* give false negatives. The main reason why it's here is that we need
* a non-destructive way to look for easily umountable filesystems.
*/
int may_umount(struct vfsmount *mnt)
{
int ret = 1;
down_read(&namespace_sem);
lock_mount_hash();
if (propagate_mount_busy(real_mount(mnt), 2))
ret = 0;
unlock_mount_hash();
up_read(&namespace_sem);
return ret;
}
EXPORT_SYMBOL(may_umount);
static HLIST_HEAD(unmounted); /* protected by namespace_sem */
static void namespace_unlock(void)
{
struct hlist_head head;
hlist_move_list(&unmounted, &head);
up_write(&namespace_sem);
if (likely(hlist_empty(&head)))
return;
synchronize_rcu();
group_pin_kill(&head);
}
static inline void namespace_lock(void)
{
down_write(&namespace_sem);
}
enum umount_tree_flags {
UMOUNT_SYNC = 1,
UMOUNT_PROPAGATE = 2,
UMOUNT_CONNECTED = 4,
};
/*
* mount_lock must be held
* namespace_sem must be held for write
*/
static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = !(((how & UMOUNT_CONNECTED) &&
mnt_has_parent(p) &&
(p->mnt_parent->mnt.mnt_flags & MNT_UMOUNT)) ||
IS_MNT_LOCKED_AND_LAZY(p));
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
static void shrink_submounts(struct mount *mnt);
static int do_umount(struct mount *mnt, int flags)
{
struct super_block *sb = mnt->mnt.mnt_sb;
int retval;
retval = security_sb_umount(&mnt->mnt, flags);
if (retval)
return retval;
/*
* Allow userspace to request a mountpoint be expired rather than
* unmounting unconditionally. Unmount only happens if:
* (1) the mark is already set (the mark is cleared by mntput())
* (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount]
*/
if (flags & MNT_EXPIRE) {
if (&mnt->mnt == current->fs->root.mnt ||
flags & (MNT_FORCE | MNT_DETACH))
return -EINVAL;
/*
* probably don't strictly need the lock here if we examined
* all race cases, but it's a slowpath.
*/
lock_mount_hash();
if (mnt_get_count(mnt) != 2) {
unlock_mount_hash();
return -EBUSY;
}
unlock_mount_hash();
if (!xchg(&mnt->mnt_expiry_mark, 1))
return -EAGAIN;
}
/*
* If we may have to abort operations to get out of this
* mount, and they will themselves hold resources we must
* allow the fs to do things. In the Unix tradition of
* 'Gee thats tricky lets do it in userspace' the umount_begin
* might fail to complete on the first run through as other tasks
* must return, and the like. Thats for the mount program to worry
* about for the moment.
*/
if (flags & MNT_FORCE && sb->s_op->umount_begin) {
sb->s_op->umount_begin(sb);
}
/*
* No sense to grab the lock for this test, but test itself looks
* somewhat bogus. Suggestions for better replacement?
* Ho-hum... In principle, we might treat that as umount + switch
* to rootfs. GC would eventually take care of the old vfsmount.
* Actually it makes sense, especially if rootfs would contain a
* /reboot - static binary that would close all descriptors and
* call reboot(9). Then init(8) could umount root and exec /reboot.
*/
if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) {
/*
* Special case for "unmounting" root ...
* we just try to remount it readonly.
*/
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
down_write(&sb->s_umount);
if (!(sb->s_flags & MS_RDONLY))
retval = do_remount_sb(sb, MS_RDONLY, NULL, 0);
up_write(&sb->s_umount);
return retval;
}
namespace_lock();
lock_mount_hash();
event++;
if (flags & MNT_DETACH) {
if (!list_empty(&mnt->mnt_list))
umount_tree(mnt, UMOUNT_PROPAGATE);
retval = 0;
} else {
shrink_submounts(mnt);
retval = -EBUSY;
if (!propagate_mount_busy(mnt, 2)) {
if (!list_empty(&mnt->mnt_list))
umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
retval = 0;
}
}
unlock_mount_hash();
namespace_unlock();
return retval;
}
/*
* __detach_mounts - lazily unmount all mounts on the specified dentry
*
* During unlink, rmdir, and d_drop it is possible to loose the path
* to an existing mountpoint, and wind up leaking the mount.
* detach_mounts allows lazily unmounting those mounts instead of
* leaking them.
*
* The caller may hold dentry->d_inode->i_mutex.
*/
void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (IS_ERR_OR_NULL(mp))
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
hlist_add_head(&p->mnt_umount.s_list, &unmounted);
umount_mnt(p);
}
}
else umount_tree(mnt, UMOUNT_CONNECTED);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
/*
* Is the caller allowed to modify his namespace?
*/
static inline bool may_mount(void)
{
return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN);
}
/*
* Now umount can handle mount points as well as block devices.
* This is important for filesystems which use unnamed block devices.
*
* We now support a flag for forced unmount like the other 'big iron'
* unixes. Our API is identical to OSF/1 to avoid making a mess of AMD
*/
SYSCALL_DEFINE2(umount, char __user *, name, int, flags)
{
struct path path;
struct mount *mnt;
int retval;
int lookup_flags = 0;
if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW))
return -EINVAL;
if (!may_mount())
return -EPERM;
if (!(flags & UMOUNT_NOFOLLOW))
lookup_flags |= LOOKUP_FOLLOW;
retval = user_path_mountpoint_at(AT_FDCWD, name, lookup_flags, &path);
if (retval)
goto out;
mnt = real_mount(path.mnt);
retval = -EINVAL;
if (path.dentry != path.mnt->mnt_root)
goto dput_and_out;
if (!check_mnt(mnt))
goto dput_and_out;
if (mnt->mnt.mnt_flags & MNT_LOCKED)
goto dput_and_out;
retval = -EPERM;
if (flags & MNT_FORCE && !capable(CAP_SYS_ADMIN))
goto dput_and_out;
retval = do_umount(mnt, flags);
dput_and_out:
/* we mustn't call path_put() as that would clear mnt_expiry_mark */
dput(path.dentry);
mntput_no_expire(mnt);
out:
return retval;
}
#ifdef __ARCH_WANT_SYS_OLDUMOUNT
/*
* The 2.0 compatible umount. No flags.
*/
SYSCALL_DEFINE1(oldumount, char __user *, name)
{
return sys_umount(name, 0);
}
#endif
static bool is_mnt_ns_file(struct dentry *dentry)
{
/* Is this a proxy for a mount namespace? */
return dentry->d_op == &ns_dentry_operations &&
dentry->d_fsdata == &mntns_operations;
}
struct mnt_namespace *to_mnt_ns(struct ns_common *ns)
{
return container_of(ns, struct mnt_namespace, ns);
}
static bool mnt_ns_loop(struct dentry *dentry)
{
/* Could bind mounting the mount namespace inode cause a
* mount namespace loop?
*/
struct mnt_namespace *mnt_ns;
if (!is_mnt_ns_file(dentry))
return false;
mnt_ns = to_mnt_ns(get_proc_ns(dentry->d_inode));
return current->nsproxy->mnt_ns->seq >= mnt_ns->seq;
}
struct mount *copy_tree(struct mount *mnt, struct dentry *dentry,
int flag)
{
struct mount *res, *p, *q, *r, *parent;
if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(mnt))
return ERR_PTR(-EINVAL);
if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(dentry))
return ERR_PTR(-EINVAL);
res = q = clone_mnt(mnt, dentry, flag);
if (IS_ERR(q))
return q;
q->mnt_mountpoint = mnt->mnt_mountpoint;
p = mnt;
list_for_each_entry(r, &mnt->mnt_mounts, mnt_child) {
struct mount *s;
if (!is_subdir(r->mnt_mountpoint, dentry))
continue;
for (s = r; s; s = next_mnt(s, r)) {
struct mount *t = NULL;
if (!(flag & CL_COPY_UNBINDABLE) &&
IS_MNT_UNBINDABLE(s)) {
s = skip_mnt_tree(s);
continue;
}
if (!(flag & CL_COPY_MNT_NS_FILE) &&
is_mnt_ns_file(s->mnt.mnt_root)) {
s = skip_mnt_tree(s);
continue;
}
while (p != s->mnt_parent) {
p = p->mnt_parent;
q = q->mnt_parent;
}
p = s;
parent = q;
q = clone_mnt(p, p->mnt.mnt_root, flag);
if (IS_ERR(q))
goto out;
lock_mount_hash();
list_add_tail(&q->mnt_list, &res->mnt_list);
mnt_set_mountpoint(parent, p->mnt_mp, q);
if (!list_empty(&parent->mnt_mounts)) {
t = list_last_entry(&parent->mnt_mounts,
struct mount, mnt_child);
if (t->mnt_mp != p->mnt_mp)
t = NULL;
}
attach_shadowed(q, parent, t);
unlock_mount_hash();
}
}
return res;
out:
if (res) {
lock_mount_hash();
umount_tree(res, UMOUNT_SYNC);
unlock_mount_hash();
}
return q;
}
/* Caller should check returned pointer for errors */
struct vfsmount *collect_mounts(struct path *path)
{
struct mount *tree;
namespace_lock();
if (!check_mnt(real_mount(path->mnt)))
tree = ERR_PTR(-EINVAL);
else
tree = copy_tree(real_mount(path->mnt), path->dentry,
CL_COPY_ALL | CL_PRIVATE);
namespace_unlock();
if (IS_ERR(tree))
return ERR_CAST(tree);
return &tree->mnt;
}
void drop_collected_mounts(struct vfsmount *mnt)
{
namespace_lock();
lock_mount_hash();
umount_tree(real_mount(mnt), UMOUNT_SYNC);
unlock_mount_hash();
namespace_unlock();
}
/**
* clone_private_mount - create a private clone of a path
*
* This creates a new vfsmount, which will be the clone of @path. The new will
* not be attached anywhere in the namespace and will be private (i.e. changes
* to the originating mount won't be propagated into this).
*
* Release with mntput().
*/
struct vfsmount *clone_private_mount(struct path *path)
{
struct mount *old_mnt = real_mount(path->mnt);
struct mount *new_mnt;
if (IS_MNT_UNBINDABLE(old_mnt))
return ERR_PTR(-EINVAL);
down_read(&namespace_sem);
new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
up_read(&namespace_sem);
if (IS_ERR(new_mnt))
return ERR_CAST(new_mnt);
return &new_mnt->mnt;
}
EXPORT_SYMBOL_GPL(clone_private_mount);
int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg,
struct vfsmount *root)
{
struct mount *mnt;
int res = f(root, arg);
if (res)
return res;
list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) {
res = f(&mnt->mnt, arg);
if (res)
return res;
}
return 0;
}
static void cleanup_group_ids(struct mount *mnt, struct mount *end)
{
struct mount *p;
for (p = mnt; p != end; p = next_mnt(p, mnt)) {
if (p->mnt_group_id && !IS_MNT_SHARED(p))
mnt_release_group_id(p);
}
}
static int invent_group_ids(struct mount *mnt, bool recurse)
{
struct mount *p;
for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) {
if (!p->mnt_group_id && !IS_MNT_SHARED(p)) {
int err = mnt_alloc_group_id(p);
if (err) {
cleanup_group_ids(mnt, p);
return err;
}
}
}
return 0;
}
/*
* @source_mnt : mount tree to be attached
* @nd : place the mount tree @source_mnt is attached
* @parent_nd : if non-null, detach the source_mnt from its parent and
* store the parent mount and mountpoint dentry.
* (done when source_mnt is moved)
*
* NOTE: in the table below explains the semantics when a source mount
* of a given type is attached to a destination mount of a given type.
* ---------------------------------------------------------------------------
* | BIND MOUNT OPERATION |
* |**************************************************************************
* | source-->| shared | private | slave | unbindable |
* | dest | | | | |
* | | | | | | |
* | v | | | | |
* |**************************************************************************
* | shared | shared (++) | shared (+) | shared(+++)| invalid |
* | | | | | |
* |non-shared| shared (+) | private | slave (*) | invalid |
* ***************************************************************************
* A bind operation clones the source mount and mounts the clone on the
* destination mount.
*
* (++) the cloned mount is propagated to all the mounts in the propagation
* tree of the destination mount and the cloned mount is added to
* the peer group of the source mount.
* (+) the cloned mount is created under the destination mount and is marked
* as shared. The cloned mount is added to the peer group of the source
* mount.
* (+++) the mount is propagated to all the mounts in the propagation tree
* of the destination mount and the cloned mount is made slave
* of the same master as that of the source mount. The cloned mount
* is marked as 'shared and slave'.
* (*) the cloned mount is made a slave of the same master as that of the
* source mount.
*
* ---------------------------------------------------------------------------
* | MOVE MOUNT OPERATION |
* |**************************************************************************
* | source-->| shared | private | slave | unbindable |
* | dest | | | | |
* | | | | | | |
* | v | | | | |
* |**************************************************************************
* | shared | shared (+) | shared (+) | shared(+++) | invalid |
* | | | | | |
* |non-shared| shared (+*) | private | slave (*) | unbindable |
* ***************************************************************************
*
* (+) the mount is moved to the destination. And is then propagated to
* all the mounts in the propagation tree of the destination mount.
* (+*) the mount is moved to the destination.
* (+++) the mount is moved to the destination and is then propagated to
* all the mounts belonging to the destination mount's propagation tree.
* the mount is marked as 'shared and slave'.
* (*) the mount continues to be a slave at the new location.
*
* if the source mount is a tree, the operations explained above is
* applied to each mount in the tree.
* Must be called without spinlocks held, since this function can sleep
* in allocations.
*/
static int attach_recursive_mnt(struct mount *source_mnt,
struct mount *dest_mnt,
struct mountpoint *dest_mp,
struct path *parent_path)
{
HLIST_HEAD(tree_list);
struct mount *child, *p;
struct hlist_node *n;
int err;
if (IS_MNT_SHARED(dest_mnt)) {
err = invent_group_ids(source_mnt, true);
if (err)
goto out;
err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
lock_mount_hash();
if (err)
goto out_cleanup_ids;
for (p = source_mnt; p; p = next_mnt(p, source_mnt))
set_mnt_shared(p);
} else {
lock_mount_hash();
}
if (parent_path) {
detach_mnt(source_mnt, parent_path);
attach_mnt(source_mnt, dest_mnt, dest_mp);
touch_mnt_namespace(source_mnt->mnt_ns);
} else {
mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
commit_tree(source_mnt, NULL);
}
hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
struct mount *q;
hlist_del_init(&child->mnt_hash);
q = __lookup_mnt_last(&child->mnt_parent->mnt,
child->mnt_mountpoint);
commit_tree(child, q);
}
unlock_mount_hash();
return 0;
out_cleanup_ids:
while (!hlist_empty(&tree_list)) {
child = hlist_entry(tree_list.first, struct mount, mnt_hash);
umount_tree(child, UMOUNT_SYNC);
}
unlock_mount_hash();
cleanup_group_ids(source_mnt, NULL);
out:
return err;
}
static struct mountpoint *lock_mount(struct path *path)
{
struct vfsmount *mnt;
struct dentry *dentry = path->dentry;
retry:
mutex_lock(&dentry->d_inode->i_mutex);
if (unlikely(cant_mount(dentry))) {
mutex_unlock(&dentry->d_inode->i_mutex);
return ERR_PTR(-ENOENT);
}
namespace_lock();
mnt = lookup_mnt(path);
if (likely(!mnt)) {
struct mountpoint *mp = lookup_mountpoint(dentry);
if (!mp)
mp = new_mountpoint(dentry);
if (IS_ERR(mp)) {
namespace_unlock();
mutex_unlock(&dentry->d_inode->i_mutex);
return mp;
}
return mp;
}
namespace_unlock();
mutex_unlock(&path->dentry->d_inode->i_mutex);
path_put(path);
path->mnt = mnt;
dentry = path->dentry = dget(mnt->mnt_root);
goto retry;
}
static void unlock_mount(struct mountpoint *where)
{
struct dentry *dentry = where->m_dentry;
put_mountpoint(where);
namespace_unlock();
mutex_unlock(&dentry->d_inode->i_mutex);
}
static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp)
{
if (mnt->mnt.mnt_sb->s_flags & MS_NOUSER)
return -EINVAL;
if (d_is_dir(mp->m_dentry) !=
d_is_dir(mnt->mnt.mnt_root))
return -ENOTDIR;
return attach_recursive_mnt(mnt, p, mp, NULL);
}
/*
* Sanity check the flags to change_mnt_propagation.
*/
static int flags_to_propagation_type(int flags)
{
int type = flags & ~(MS_REC | MS_SILENT);
/* Fail if any non-propagation flags are set */
if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
return 0;
/* Only one propagation flag should be set */
if (!is_power_of_2(type))
return 0;
return type;
}
/*
* recursively change the type of the mountpoint.
*/
static int do_change_type(struct path *path, int flag)
{
struct mount *m;
struct mount *mnt = real_mount(path->mnt);
int recurse = flag & MS_REC;
int type;
int err = 0;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
type = flags_to_propagation_type(flag);
if (!type)
return -EINVAL;
namespace_lock();
if (type == MS_SHARED) {
err = invent_group_ids(mnt, recurse);
if (err)
goto out_unlock;
}
lock_mount_hash();
for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL))
change_mnt_propagation(m, type);
unlock_mount_hash();
out_unlock:
namespace_unlock();
return err;
}
static bool has_locked_children(struct mount *mnt, struct dentry *dentry)
{
struct mount *child;
list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
if (!is_subdir(child->mnt_mountpoint, dentry))
continue;
if (child->mnt.mnt_flags & MNT_LOCKED)
return true;
}
return false;
}
/*
* do loopback mount.
*/
static int do_loopback(struct path *path, const char *old_name,
int recurse)
{
struct path old_path;
struct mount *mnt = NULL, *old, *parent;
struct mountpoint *mp;
int err;
if (!old_name || !*old_name)
return -EINVAL;
err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
if (err)
return err;
err = -EINVAL;
if (mnt_ns_loop(old_path.dentry))
goto out;
mp = lock_mount(path);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto out;
old = real_mount(old_path.mnt);
parent = real_mount(path->mnt);
err = -EINVAL;
if (IS_MNT_UNBINDABLE(old))
goto out2;
if (!check_mnt(parent))
goto out2;
if (!check_mnt(old) && old_path.dentry->d_op != &ns_dentry_operations)
goto out2;
if (!recurse && has_locked_children(old, old_path.dentry))
goto out2;
if (recurse)
mnt = copy_tree(old, old_path.dentry, CL_COPY_MNT_NS_FILE);
else
mnt = clone_mnt(old, old_path.dentry, 0);
if (IS_ERR(mnt)) {
err = PTR_ERR(mnt);
goto out2;
}
mnt->mnt.mnt_flags &= ~MNT_LOCKED;
err = graft_tree(mnt, parent, mp);
if (err) {
lock_mount_hash();
umount_tree(mnt, UMOUNT_SYNC);
unlock_mount_hash();
}
out2:
unlock_mount(mp);
out:
path_put(&old_path);
return err;
}
static int change_mount_flags(struct vfsmount *mnt, int ms_flags)
{
int error = 0;
int readonly_request = 0;
if (ms_flags & MS_RDONLY)
readonly_request = 1;
if (readonly_request == __mnt_is_readonly(mnt))
return 0;
if (readonly_request)
error = mnt_make_readonly(real_mount(mnt));
else
__mnt_unmake_readonly(real_mount(mnt));
return error;
}
/*
* change filesystem flags. dir should be a physical root of filesystem.
* If you've mounted a non-root directory somewhere and want to do remount
* on it - tough luck.
*/
static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
/* Don't allow changing of locked mnt flags.
*
* No locks need to be held here while testing the various
* MNT_LOCK flags because those flags can never be cleared
* once they are set.
*/
if ((mnt->mnt.mnt_flags & MNT_LOCK_READONLY) &&
!(mnt_flags & MNT_READONLY)) {
return -EPERM;
}
if ((mnt->mnt.mnt_flags & MNT_LOCK_NODEV) &&
!(mnt_flags & MNT_NODEV)) {
/* Was the nodev implicitly added in mount? */
if ((mnt->mnt_ns->user_ns != &init_user_ns) &&
!(sb->s_type->fs_flags & FS_USERNS_DEV_MOUNT)) {
mnt_flags |= MNT_NODEV;
} else {
return -EPERM;
}
}
if ((mnt->mnt.mnt_flags & MNT_LOCK_NOSUID) &&
!(mnt_flags & MNT_NOSUID)) {
return -EPERM;
}
if ((mnt->mnt.mnt_flags & MNT_LOCK_NOEXEC) &&
!(mnt_flags & MNT_NOEXEC)) {
return -EPERM;
}
if ((mnt->mnt.mnt_flags & MNT_LOCK_ATIME) &&
((mnt->mnt.mnt_flags & MNT_ATIME_MASK) != (mnt_flags & MNT_ATIME_MASK))) {
return -EPERM;
}
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
lock_mount_hash();
mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK;
mnt->mnt.mnt_flags = mnt_flags;
touch_mnt_namespace(mnt->mnt_ns);
unlock_mount_hash();
}
up_write(&sb->s_umount);
return err;
}
static inline int tree_contains_unbindable(struct mount *mnt)
{
struct mount *p;
for (p = mnt; p; p = next_mnt(p, mnt)) {
if (IS_MNT_UNBINDABLE(p))
return 1;
}
return 0;
}
static int do_move_mount(struct path *path, const char *old_name)
{
struct path old_path, parent_path;
struct mount *p;
struct mount *old;
struct mountpoint *mp;
int err;
if (!old_name || !*old_name)
return -EINVAL;
err = kern_path(old_name, LOOKUP_FOLLOW, &old_path);
if (err)
return err;
mp = lock_mount(path);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto out;
old = real_mount(old_path.mnt);
p = real_mount(path->mnt);
err = -EINVAL;
if (!check_mnt(p) || !check_mnt(old))
goto out1;
if (old->mnt.mnt_flags & MNT_LOCKED)
goto out1;
err = -EINVAL;
if (old_path.dentry != old_path.mnt->mnt_root)
goto out1;
if (!mnt_has_parent(old))
goto out1;
if (d_is_dir(path->dentry) !=
d_is_dir(old_path.dentry))
goto out1;
/*
* Don't move a mount residing in a shared parent.
*/
if (IS_MNT_SHARED(old->mnt_parent))
goto out1;
/*
* Don't move a mount tree containing unbindable mounts to a destination
* mount which is shared.
*/
if (IS_MNT_SHARED(p) && tree_contains_unbindable(old))
goto out1;
err = -ELOOP;
for (; mnt_has_parent(p); p = p->mnt_parent)
if (p == old)
goto out1;
err = attach_recursive_mnt(old, real_mount(path->mnt), mp, &parent_path);
if (err)
goto out1;
/* if the mount is moved, it should no longer be expire
* automatically */
list_del_init(&old->mnt_expire);
out1:
unlock_mount(mp);
out:
if (!err)
path_put(&parent_path);
path_put(&old_path);
return err;
}
static struct vfsmount *fs_set_subtype(struct vfsmount *mnt, const char *fstype)
{
int err;
const char *subtype = strchr(fstype, '.');
if (subtype) {
subtype++;
err = -EINVAL;
if (!subtype[0])
goto err;
} else
subtype = "";
mnt->mnt_sb->s_subtype = kstrdup(subtype, GFP_KERNEL);
err = -ENOMEM;
if (!mnt->mnt_sb->s_subtype)
goto err;
return mnt;
err:
mntput(mnt);
return ERR_PTR(err);
}
/*
* add a mount into a namespace's mount tree
*/
static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags)
{
struct mountpoint *mp;
struct mount *parent;
int err;
mnt_flags &= ~MNT_INTERNAL_FLAGS;
mp = lock_mount(path);
if (IS_ERR(mp))
return PTR_ERR(mp);
parent = real_mount(path->mnt);
err = -EINVAL;
if (unlikely(!check_mnt(parent))) {
/* that's acceptable only for automounts done in private ns */
if (!(mnt_flags & MNT_SHRINKABLE))
goto unlock;
/* ... and for those we'd better have mountpoint still alive */
if (!parent->mnt_ns)
goto unlock;
}
/* Refuse the same filesystem on the same mount point */
err = -EBUSY;
if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb &&
path->mnt->mnt_root == path->dentry)
goto unlock;
err = -EINVAL;
if (d_is_symlink(newmnt->mnt.mnt_root))
goto unlock;
newmnt->mnt.mnt_flags = mnt_flags;
err = graft_tree(newmnt, parent, mp);
unlock:
unlock_mount(mp);
return err;
}
/*
* create a new mount for userspace and request it to be added into the
* namespace's tree
*/
static int do_new_mount(struct path *path, const char *fstype, int flags,
int mnt_flags, const char *name, void *data)
{
struct file_system_type *type;
struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
struct vfsmount *mnt;
int err;
if (!fstype)
return -EINVAL;
type = get_fs_type(fstype);
if (!type)
return -ENODEV;
if (user_ns != &init_user_ns) {
if (!(type->fs_flags & FS_USERNS_MOUNT)) {
put_filesystem(type);
return -EPERM;
}
/* Only in special cases allow devices from mounts
* created outside the initial user namespace.
*/
if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) {
flags |= MS_NODEV;
mnt_flags |= MNT_NODEV | MNT_LOCK_NODEV;
}
}
mnt = vfs_kern_mount(type, flags, name, data);
if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) &&
!mnt->mnt_sb->s_subtype)
mnt = fs_set_subtype(mnt, fstype);
put_filesystem(type);
if (IS_ERR(mnt))
return PTR_ERR(mnt);
err = do_add_mount(real_mount(mnt), path, mnt_flags);
if (err)
mntput(mnt);
return err;
}
int finish_automount(struct vfsmount *m, struct path *path)
{
struct mount *mnt = real_mount(m);
int err;
/* The new mount record should have at least 2 refs to prevent it being
* expired before we get a chance to add it
*/
BUG_ON(mnt_get_count(mnt) < 2);
if (m->mnt_sb == path->mnt->mnt_sb &&
m->mnt_root == path->dentry) {
err = -ELOOP;
goto fail;
}
err = do_add_mount(mnt, path, path->mnt->mnt_flags | MNT_SHRINKABLE);
if (!err)
return 0;
fail:
/* remove m from any expiration list it may be on */
if (!list_empty(&mnt->mnt_expire)) {
namespace_lock();
list_del_init(&mnt->mnt_expire);
namespace_unlock();
}
mntput(m);
mntput(m);
return err;
}
/**
* mnt_set_expiry - Put a mount on an expiration list
* @mnt: The mount to list.
* @expiry_list: The list to add the mount to.
*/
void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list)
{
namespace_lock();
list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list);
namespace_unlock();
}
EXPORT_SYMBOL(mnt_set_expiry);
/*
* process a list of expirable mountpoints with the intent of discarding any
* mountpoints that aren't in use and haven't been touched since last we came
* here
*/
void mark_mounts_for_expiry(struct list_head *mounts)
{
struct mount *mnt, *next;
LIST_HEAD(graveyard);
if (list_empty(mounts))
return;
namespace_lock();
lock_mount_hash();
/* extract from the expiration list every vfsmount that matches the
* following criteria:
* - only referenced by its parent vfsmount
* - still marked for expiry (marked on the last call here; marks are
* cleared by mntput())
*/
list_for_each_entry_safe(mnt, next, mounts, mnt_expire) {
if (!xchg(&mnt->mnt_expiry_mark, 1) ||
propagate_mount_busy(mnt, 1))
continue;
list_move(&mnt->mnt_expire, &graveyard);
}
while (!list_empty(&graveyard)) {
mnt = list_first_entry(&graveyard, struct mount, mnt_expire);
touch_mnt_namespace(mnt->mnt_ns);
umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
}
unlock_mount_hash();
namespace_unlock();
}
EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);
/*
* Ripoff of 'select_parent()'
*
* search the list of submounts for a given mountpoint, and move any
* shrinkable submounts to the 'graveyard' list.
*/
static int select_submounts(struct mount *parent, struct list_head *graveyard)
{
struct mount *this_parent = parent;
struct list_head *next;
int found = 0;
repeat:
next = this_parent->mnt_mounts.next;
resume:
while (next != &this_parent->mnt_mounts) {
struct list_head *tmp = next;
struct mount *mnt = list_entry(tmp, struct mount, mnt_child);
next = tmp->next;
if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE))
continue;
/*
* Descend a level if the d_mounts list is non-empty.
*/
if (!list_empty(&mnt->mnt_mounts)) {
this_parent = mnt;
goto repeat;
}
if (!propagate_mount_busy(mnt, 1)) {
list_move_tail(&mnt->mnt_expire, graveyard);
found++;
}
}
/*
* All done at this level ... ascend and resume the search
*/
if (this_parent != parent) {
next = this_parent->mnt_child.next;
this_parent = this_parent->mnt_parent;
goto resume;
}
return found;
}
/*
* process a list of expirable mountpoints with the intent of discarding any
* submounts of a specific parent mountpoint
*
* mount_lock must be held for write
*/
static void shrink_submounts(struct mount *mnt)
{
LIST_HEAD(graveyard);
struct mount *m;
/* extract submounts of 'mountpoint' from the expiration list */
while (select_submounts(mnt, &graveyard)) {
while (!list_empty(&graveyard)) {
m = list_first_entry(&graveyard, struct mount,
mnt_expire);
touch_mnt_namespace(m->mnt_ns);
umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC);
}
}
}
/*
* Some copy_from_user() implementations do not return the exact number of
* bytes remaining to copy on a fault. But copy_mount_options() requires that.
* Note that this function differs from copy_from_user() in that it will oops
* on bad values of `to', rather than returning a short copy.
*/
static long exact_copy_from_user(void *to, const void __user * from,
unsigned long n)
{
char *t = to;
const char __user *f = from;
char c;
if (!access_ok(VERIFY_READ, from, n))
return n;
while (n) {
if (__get_user(c, f)) {
memset(t, 0, n);
break;
}
*t++ = c;
f++;
n--;
}
return n;
}
int copy_mount_options(const void __user * data, unsigned long *where)
{
int i;
unsigned long page;
unsigned long size;
*where = 0;
if (!data)
return 0;
if (!(page = __get_free_page(GFP_KERNEL)))
return -ENOMEM;
/* We only care that *some* data at the address the user
* gave us is valid. Just in case, we'll zero
* the remainder of the page.
*/
/* copy_from_user cannot cross TASK_SIZE ! */
size = TASK_SIZE - (unsigned long)data;
if (size > PAGE_SIZE)
size = PAGE_SIZE;
i = size - exact_copy_from_user((void *)page, data, size);
if (!i) {
free_page(page);
return -EFAULT;
}
if (i != PAGE_SIZE)
memset((char *)page + i, 0, PAGE_SIZE - i);
*where = page;
return 0;
}
char *copy_mount_string(const void __user *data)
{
return data ? strndup_user(data, PAGE_SIZE) : NULL;
}
/*
* Flags is a 32-bit value that allows up to 31 non-fs dependent flags to
* be given to the mount() call (ie: read-only, no-dev, no-suid etc).
*
* data is a (void *) that can point to any structure up to
* PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent
* information (or be NULL).
*
* Pre-0.97 versions of mount() didn't have a flags word.
* When the flags word was introduced its top half was required
* to have the magic value 0xC0ED, and this remained so until 2.4.0-test9.
* Therefore, if this magic number is present, it carries no information
* and must be discarded.
*/
long do_mount(const char *dev_name, const char __user *dir_name,
const char *type_page, unsigned long flags, void *data_page)
{
struct path path;
int retval = 0;
int mnt_flags = 0;
/* Discard magic */
if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
flags &= ~MS_MGC_MSK;
/* Basic sanity checks */
if (data_page)
((char *)data_page)[PAGE_SIZE - 1] = 0;
/* ... and get the mountpoint */
retval = user_path(dir_name, &path);
if (retval)
return retval;
retval = security_sb_mount(dev_name, &path,
type_page, flags, data_page);
if (!retval && !may_mount())
retval = -EPERM;
if (retval)
goto dput_out;
/* Default to relatime unless overriden */
if (!(flags & MS_NOATIME))
mnt_flags |= MNT_RELATIME;
/* Separate the per-mountpoint flags */
if (flags & MS_NOSUID)
mnt_flags |= MNT_NOSUID;
if (flags & MS_NODEV)
mnt_flags |= MNT_NODEV;
if (flags & MS_NOEXEC)
mnt_flags |= MNT_NOEXEC;
if (flags & MS_NOATIME)
mnt_flags |= MNT_NOATIME;
if (flags & MS_NODIRATIME)
mnt_flags |= MNT_NODIRATIME;
if (flags & MS_STRICTATIME)
mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME);
if (flags & MS_RDONLY)
mnt_flags |= MNT_READONLY;
/* The default atime for remount is preservation */
if ((flags & MS_REMOUNT) &&
((flags & (MS_NOATIME | MS_NODIRATIME | MS_RELATIME |
MS_STRICTATIME)) == 0)) {
mnt_flags &= ~MNT_ATIME_MASK;
mnt_flags |= path.mnt->mnt_flags & MNT_ATIME_MASK;
}
flags &= ~(MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_ACTIVE | MS_BORN |
MS_NOATIME | MS_NODIRATIME | MS_RELATIME| MS_KERNMOUNT |
MS_STRICTATIME);
if (flags & MS_REMOUNT)
retval = do_remount(&path, flags & ~MS_REMOUNT, mnt_flags,
data_page);
else if (flags & MS_BIND)
retval = do_loopback(&path, dev_name, flags & MS_REC);
else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
retval = do_change_type(&path, flags);
else if (flags & MS_MOVE)
retval = do_move_mount(&path, dev_name);
else
retval = do_new_mount(&path, type_page, flags, mnt_flags,
dev_name, data_page);
dput_out:
path_put(&path);
return retval;
}
static void free_mnt_ns(struct mnt_namespace *ns)
{
ns_free_inum(&ns->ns);
put_user_ns(ns->user_ns);
kfree(ns);
}
/*
* Assign a sequence number so we can detect when we attempt to bind
* mount a reference to an older mount namespace into the current
* mount namespace, preventing reference counting loops. A 64bit
* number incrementing at 10Ghz will take 12,427 years to wrap which
* is effectively never, so we can ignore the possibility.
*/
static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1);
static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns)
{
struct mnt_namespace *new_ns;
int ret;
new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL);
if (!new_ns)
return ERR_PTR(-ENOMEM);
ret = ns_alloc_inum(&new_ns->ns);
if (ret) {
kfree(new_ns);
return ERR_PTR(ret);
}
new_ns->ns.ops = &mntns_operations;
new_ns->seq = atomic64_add_return(1, &mnt_ns_seq);
atomic_set(&new_ns->count, 1);
new_ns->root = NULL;
INIT_LIST_HEAD(&new_ns->list);
init_waitqueue_head(&new_ns->poll);
new_ns->event = 0;
new_ns->user_ns = get_user_ns(user_ns);
return new_ns;
}
struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns,
struct user_namespace *user_ns, struct fs_struct *new_fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old;
struct mount *new;
int copy_flags;
BUG_ON(!ns);
if (likely(!(flags & CLONE_NEWNS))) {
get_mnt_ns(ns);
return ns;
}
old = ns->root;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
namespace_lock();
/* First pass: copy the tree topology */
copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE;
if (user_ns != ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
namespace_unlock();
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
list_add_tail(&new_ns->list, &new->mnt_list);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (new_fs) {
if (&p->mnt == new_fs->root.mnt) {
new_fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == new_fs->pwd.mnt) {
new_fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
if (!q)
break;
while (p->mnt.mnt_root != q->mnt.mnt_root)
p = next_mnt(p, old);
}
namespace_unlock();
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
/**
* create_mnt_ns - creates a private namespace and adds a root filesystem
* @mnt: pointer to the new root filesystem mountpoint
*/
static struct mnt_namespace *create_mnt_ns(struct vfsmount *m)
{
struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns);
if (!IS_ERR(new_ns)) {
struct mount *mnt = real_mount(m);
mnt->mnt_ns = new_ns;
new_ns->root = mnt;
list_add(&mnt->mnt_list, &new_ns->list);
} else {
mntput(m);
}
return new_ns;
}
struct dentry *mount_subtree(struct vfsmount *mnt, const char *name)
{
struct mnt_namespace *ns;
struct super_block *s;
struct path path;
int err;
ns = create_mnt_ns(mnt);
if (IS_ERR(ns))
return ERR_CAST(ns);
err = vfs_path_lookup(mnt->mnt_root, mnt,
name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
put_mnt_ns(ns);
if (err)
return ERR_PTR(err);
/* trade a vfsmount reference for active sb one */
s = path.mnt->mnt_sb;
atomic_inc(&s->s_active);
mntput(path.mnt);
/* lock the sucker */
down_write(&s->s_umount);
/* ... and return the root of (sub)tree on it */
return path.dentry;
}
EXPORT_SYMBOL(mount_subtree);
SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name,
char __user *, type, unsigned long, flags, void __user *, data)
{
int ret;
char *kernel_type;
char *kernel_dev;
unsigned long data_page;
kernel_type = copy_mount_string(type);
ret = PTR_ERR(kernel_type);
if (IS_ERR(kernel_type))
goto out_type;
kernel_dev = copy_mount_string(dev_name);
ret = PTR_ERR(kernel_dev);
if (IS_ERR(kernel_dev))
goto out_dev;
ret = copy_mount_options(data, &data_page);
if (ret < 0)
goto out_data;
ret = do_mount(kernel_dev, dir_name, kernel_type, flags,
(void *) data_page);
free_page(data_page);
out_data:
kfree(kernel_dev);
out_dev:
kfree(kernel_type);
out_type:
return ret;
}
/*
* Return true if path is reachable from root
*
* namespace_sem or mount_lock is held
*/
bool is_path_reachable(struct mount *mnt, struct dentry *dentry,
const struct path *root)
{
while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) {
dentry = mnt->mnt_mountpoint;
mnt = mnt->mnt_parent;
}
return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry);
}
int path_is_under(struct path *path1, struct path *path2)
{
int res;
read_seqlock_excl(&mount_lock);
res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2);
read_sequnlock_excl(&mount_lock);
return res;
}
EXPORT_SYMBOL(path_is_under);
/*
* pivot_root Semantics:
* Moves the root file system of the current process to the directory put_old,
* makes new_root as the new root file system of the current process, and sets
* root/cwd of all processes which had them on the current root to new_root.
*
* Restrictions:
* The new_root and put_old must be directories, and must not be on the
* same file system as the current process root. The put_old must be
* underneath new_root, i.e. adding a non-zero number of /.. to the string
* pointed to by put_old must yield the same directory as new_root. No other
* file system may be mounted on put_old. After all, new_root is a mountpoint.
*
* Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
* See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
* in this situation.
*
* Notes:
* - we don't move root/cwd if they are not at the root (reason: if something
* cared enough to change them, it's probably wrong to force them elsewhere)
* - it's okay to pick a root that isn't the root of a file system, e.g.
* /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
* though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
* first.
*/
SYSCALL_DEFINE2(pivot_root, const char __user *, new_root,
const char __user *, put_old)
{
struct path new, old, parent_path, root_parent, root;
struct mount *new_mnt, *root_mnt, *old_mnt;
struct mountpoint *old_mp, *root_mp;
int error;
if (!may_mount())
return -EPERM;
error = user_path_dir(new_root, &new);
if (error)
goto out0;
error = user_path_dir(put_old, &old);
if (error)
goto out1;
error = security_sb_pivotroot(&old, &new);
if (error)
goto out2;
get_fs_root(current->fs, &root);
old_mp = lock_mount(&old);
error = PTR_ERR(old_mp);
if (IS_ERR(old_mp))
goto out3;
error = -EINVAL;
new_mnt = real_mount(new.mnt);
root_mnt = real_mount(root.mnt);
old_mnt = real_mount(old.mnt);
if (IS_MNT_SHARED(old_mnt) ||
IS_MNT_SHARED(new_mnt->mnt_parent) ||
IS_MNT_SHARED(root_mnt->mnt_parent))
goto out4;
if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
goto out4;
if (new_mnt->mnt.mnt_flags & MNT_LOCKED)
goto out4;
error = -ENOENT;
if (d_unlinked(new.dentry))
goto out4;
error = -EBUSY;
if (new_mnt == root_mnt || old_mnt == root_mnt)
goto out4; /* loop, on the same file system */
error = -EINVAL;
if (root.mnt->mnt_root != root.dentry)
goto out4; /* not a mountpoint */
if (!mnt_has_parent(root_mnt))
goto out4; /* not attached */
root_mp = root_mnt->mnt_mp;
if (new.mnt->mnt_root != new.dentry)
goto out4; /* not a mountpoint */
if (!mnt_has_parent(new_mnt))
goto out4; /* not attached */
/* make sure we can reach put_old from new_root */
if (!is_path_reachable(old_mnt, old.dentry, &new))
goto out4;
/* make certain new is below the root */
if (!is_path_reachable(new_mnt, new.dentry, &root))
goto out4;
root_mp->m_count++; /* pin it so it won't go away */
lock_mount_hash();
detach_mnt(new_mnt, &parent_path);
detach_mnt(root_mnt, &root_parent);
if (root_mnt->mnt.mnt_flags & MNT_LOCKED) {
new_mnt->mnt.mnt_flags |= MNT_LOCKED;
root_mnt->mnt.mnt_flags &= ~MNT_LOCKED;
}
/* mount old root on put_old */
attach_mnt(root_mnt, old_mnt, old_mp);
/* mount new_root on / */
attach_mnt(new_mnt, real_mount(root_parent.mnt), root_mp);
touch_mnt_namespace(current->nsproxy->mnt_ns);
/* A moved mount should not expire automatically */
list_del_init(&new_mnt->mnt_expire);
unlock_mount_hash();
chroot_fs_refs(&root, &new);
put_mountpoint(root_mp);
error = 0;
out4:
unlock_mount(old_mp);
if (!error) {
path_put(&root_parent);
path_put(&parent_path);
}
out3:
path_put(&root);
out2:
path_put(&old);
out1:
path_put(&new);
out0:
return error;
}
static void __init init_mount_tree(void)
{
struct vfsmount *mnt;
struct mnt_namespace *ns;
struct path root;
struct file_system_type *type;
type = get_fs_type("rootfs");
if (!type)
panic("Can't find rootfs type");
mnt = vfs_kern_mount(type, 0, "rootfs", NULL);
put_filesystem(type);
if (IS_ERR(mnt))
panic("Can't create rootfs");
ns = create_mnt_ns(mnt);
if (IS_ERR(ns))
panic("Can't allocate initial namespace");
init_task.nsproxy->mnt_ns = ns;
get_mnt_ns(ns);
root.mnt = mnt;
root.dentry = mnt->mnt_root;
mnt->mnt_flags |= MNT_LOCKED;
set_fs_pwd(current->fs, &root);
set_fs_root(current->fs, &root);
}
void __init mnt_init(void)
{
unsigned u;
int err;
mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount),
0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
mount_hashtable = alloc_large_system_hash("Mount-cache",
sizeof(struct hlist_head),
mhash_entries, 19,
0,
&m_hash_shift, &m_hash_mask, 0, 0);
mountpoint_hashtable = alloc_large_system_hash("Mountpoint-cache",
sizeof(struct hlist_head),
mphash_entries, 19,
0,
&mp_hash_shift, &mp_hash_mask, 0, 0);
if (!mount_hashtable || !mountpoint_hashtable)
panic("Failed to allocate mount hash table\n");
for (u = 0; u <= m_hash_mask; u++)
INIT_HLIST_HEAD(&mount_hashtable[u]);
for (u = 0; u <= mp_hash_mask; u++)
INIT_HLIST_HEAD(&mountpoint_hashtable[u]);
kernfs_init();
err = sysfs_init();
if (err)
printk(KERN_WARNING "%s: sysfs_init error: %d\n",
__func__, err);
fs_kobj = kobject_create_and_add("fs", NULL);
if (!fs_kobj)
printk(KERN_WARNING "%s: kobj create error\n", __func__);
init_rootfs();
init_mount_tree();
}
void put_mnt_ns(struct mnt_namespace *ns)
{
if (!atomic_dec_and_test(&ns->count))
return;
drop_collected_mounts(&ns->root->mnt);
free_mnt_ns(ns);
}
struct vfsmount *kern_mount_data(struct file_system_type *type, void *data)
{
struct vfsmount *mnt;
mnt = vfs_kern_mount(type, MS_KERNMOUNT, type->name, data);
if (!IS_ERR(mnt)) {
/*
* it is a longterm mount, don't release mnt until
* we unmount before file sys is unregistered
*/
real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL;
}
return mnt;
}
EXPORT_SYMBOL_GPL(kern_mount_data);
void kern_unmount(struct vfsmount *mnt)
{
/* release long term mount so mount point can be released */
if (!IS_ERR_OR_NULL(mnt)) {
real_mount(mnt)->mnt_ns = NULL;
synchronize_rcu(); /* yecchhh... */
mntput(mnt);
}
}
EXPORT_SYMBOL(kern_unmount);
bool our_mnt(struct vfsmount *mnt)
{
return check_mnt(real_mount(mnt));
}
bool current_chrooted(void)
{
/* Does the current process have a non-standard root */
struct path ns_root;
struct path fs_root;
bool chrooted;
/* Find the namespace root */
ns_root.mnt = ¤t->nsproxy->mnt_ns->root->mnt;
ns_root.dentry = ns_root.mnt->mnt_root;
path_get(&ns_root);
while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root))
;
get_fs_root(current->fs, &fs_root);
chrooted = !path_equal(&fs_root, &ns_root);
path_put(&fs_root);
path_put(&ns_root);
return chrooted;
}
bool fs_fully_visible(struct file_system_type *type)
{
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;
bool visible = false;
if (unlikely(!ns))
return false;
down_read(&namespace_sem);
list_for_each_entry(mnt, &ns->list, mnt_list) {
struct mount *child;
if (mnt->mnt.mnt_sb->s_type != type)
continue;
/* This mount is not fully visible if there are any child mounts
* that cover anything except for empty directories.
*/
list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
struct inode *inode = child->mnt_mountpoint->d_inode;
if (!S_ISDIR(inode->i_mode))
goto next;
if (inode->i_nlink > 2)
goto next;
}
visible = true;
goto found;
next: ;
}
found:
up_read(&namespace_sem);
return visible;
}
static struct ns_common *mntns_get(struct task_struct *task)
{
struct ns_common *ns = NULL;
struct nsproxy *nsproxy;
task_lock(task);
nsproxy = task->nsproxy;
if (nsproxy) {
ns = &nsproxy->mnt_ns->ns;
get_mnt_ns(to_mnt_ns(ns));
}
task_unlock(task);
return ns;
}
static void mntns_put(struct ns_common *ns)
{
put_mnt_ns(to_mnt_ns(ns));
}
static int mntns_install(struct nsproxy *nsproxy, struct ns_common *ns)
{
struct fs_struct *fs = current->fs;
struct mnt_namespace *mnt_ns = to_mnt_ns(ns);
struct path root;
if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) ||
!ns_capable(current_user_ns(), CAP_SYS_CHROOT) ||
!ns_capable(current_user_ns(), CAP_SYS_ADMIN))
return -EPERM;
if (fs->users != 1)
return -EINVAL;
get_mnt_ns(mnt_ns);
put_mnt_ns(nsproxy->mnt_ns);
nsproxy->mnt_ns = mnt_ns;
/* Find the root */
root.mnt = &mnt_ns->root->mnt;
root.dentry = mnt_ns->root->mnt.mnt_root;
path_get(&root);
while(d_mountpoint(root.dentry) && follow_down_one(&root))
;
/* Update the pwd and root */
set_fs_pwd(fs, &root);
set_fs_root(fs, &root);
path_put(&root);
return 0;
}
const struct proc_ns_operations mntns_operations = {
.name = "mnt",
.type = CLONE_NEWNS,
.get = mntns_get,
.put = mntns_put,
.install = mntns_install,
};
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1626_0 |
crossvul-cpp_data_good_1102_0 | /*
* Copyright (c) 2006, 2019 Oracle and/or its affiliates. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/in.h>
#include <linux/export.h>
#include <linux/time.h>
#include <linux/rds.h>
#include "rds.h"
void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn,
struct in6_addr *saddr)
{
refcount_set(&inc->i_refcount, 1);
INIT_LIST_HEAD(&inc->i_item);
inc->i_conn = conn;
inc->i_saddr = *saddr;
inc->i_rdma_cookie = 0;
inc->i_rx_tstamp = ktime_set(0, 0);
memset(inc->i_rx_lat_trace, 0, sizeof(inc->i_rx_lat_trace));
}
EXPORT_SYMBOL_GPL(rds_inc_init);
void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp,
struct in6_addr *saddr)
{
refcount_set(&inc->i_refcount, 1);
INIT_LIST_HEAD(&inc->i_item);
inc->i_conn = cp->cp_conn;
inc->i_conn_path = cp;
inc->i_saddr = *saddr;
inc->i_rdma_cookie = 0;
inc->i_rx_tstamp = ktime_set(0, 0);
}
EXPORT_SYMBOL_GPL(rds_inc_path_init);
static void rds_inc_addref(struct rds_incoming *inc)
{
rdsdebug("addref inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
refcount_inc(&inc->i_refcount);
}
void rds_inc_put(struct rds_incoming *inc)
{
rdsdebug("put inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
if (refcount_dec_and_test(&inc->i_refcount)) {
BUG_ON(!list_empty(&inc->i_item));
inc->i_conn->c_trans->inc_free(inc);
}
}
EXPORT_SYMBOL_GPL(rds_inc_put);
static void rds_recv_rcvbuf_delta(struct rds_sock *rs, struct sock *sk,
struct rds_cong_map *map,
int delta, __be16 port)
{
int now_congested;
if (delta == 0)
return;
rs->rs_rcv_bytes += delta;
if (delta > 0)
rds_stats_add(s_recv_bytes_added_to_socket, delta);
else
rds_stats_add(s_recv_bytes_removed_from_socket, -delta);
/* loop transport doesn't send/recv congestion updates */
if (rs->rs_transport->t_type == RDS_TRANS_LOOP)
return;
now_congested = rs->rs_rcv_bytes > rds_sk_rcvbuf(rs);
rdsdebug("rs %p (%pI6c:%u) recv bytes %d buf %d "
"now_cong %d delta %d\n",
rs, &rs->rs_bound_addr,
ntohs(rs->rs_bound_port), rs->rs_rcv_bytes,
rds_sk_rcvbuf(rs), now_congested, delta);
/* wasn't -> am congested */
if (!rs->rs_congested && now_congested) {
rs->rs_congested = 1;
rds_cong_set_bit(map, port);
rds_cong_queue_updates(map);
}
/* was -> aren't congested */
/* Require more free space before reporting uncongested to prevent
bouncing cong/uncong state too often */
else if (rs->rs_congested && (rs->rs_rcv_bytes < (rds_sk_rcvbuf(rs)/2))) {
rs->rs_congested = 0;
rds_cong_clear_bit(map, port);
rds_cong_queue_updates(map);
}
/* do nothing if no change in cong state */
}
static void rds_conn_peer_gen_update(struct rds_connection *conn,
u32 peer_gen_num)
{
int i;
struct rds_message *rm, *tmp;
unsigned long flags;
WARN_ON(conn->c_trans->t_type != RDS_TRANS_TCP);
if (peer_gen_num != 0) {
if (conn->c_peer_gen_num != 0 &&
peer_gen_num != conn->c_peer_gen_num) {
for (i = 0; i < RDS_MPATH_WORKERS; i++) {
struct rds_conn_path *cp;
cp = &conn->c_path[i];
spin_lock_irqsave(&cp->cp_lock, flags);
cp->cp_next_tx_seq = 1;
cp->cp_next_rx_seq = 0;
list_for_each_entry_safe(rm, tmp,
&cp->cp_retrans,
m_conn_item) {
set_bit(RDS_MSG_FLUSH, &rm->m_flags);
}
spin_unlock_irqrestore(&cp->cp_lock, flags);
}
}
conn->c_peer_gen_num = peer_gen_num;
}
}
/*
* Process all extension headers that come with this message.
*/
static void rds_recv_incoming_exthdrs(struct rds_incoming *inc, struct rds_sock *rs)
{
struct rds_header *hdr = &inc->i_hdr;
unsigned int pos = 0, type, len;
union {
struct rds_ext_header_version version;
struct rds_ext_header_rdma rdma;
struct rds_ext_header_rdma_dest rdma_dest;
} buffer;
while (1) {
len = sizeof(buffer);
type = rds_message_next_extension(hdr, &pos, &buffer, &len);
if (type == RDS_EXTHDR_NONE)
break;
/* Process extension header here */
switch (type) {
case RDS_EXTHDR_RDMA:
rds_rdma_unuse(rs, be32_to_cpu(buffer.rdma.h_rdma_rkey), 0);
break;
case RDS_EXTHDR_RDMA_DEST:
/* We ignore the size for now. We could stash it
* somewhere and use it for error checking. */
inc->i_rdma_cookie = rds_rdma_make_cookie(
be32_to_cpu(buffer.rdma_dest.h_rdma_rkey),
be32_to_cpu(buffer.rdma_dest.h_rdma_offset));
break;
}
}
}
static void rds_recv_hs_exthdrs(struct rds_header *hdr,
struct rds_connection *conn)
{
unsigned int pos = 0, type, len;
union {
struct rds_ext_header_version version;
u16 rds_npaths;
u32 rds_gen_num;
} buffer;
u32 new_peer_gen_num = 0;
while (1) {
len = sizeof(buffer);
type = rds_message_next_extension(hdr, &pos, &buffer, &len);
if (type == RDS_EXTHDR_NONE)
break;
/* Process extension header here */
switch (type) {
case RDS_EXTHDR_NPATHS:
conn->c_npaths = min_t(int, RDS_MPATH_WORKERS,
be16_to_cpu(buffer.rds_npaths));
break;
case RDS_EXTHDR_GEN_NUM:
new_peer_gen_num = be32_to_cpu(buffer.rds_gen_num);
break;
default:
pr_warn_ratelimited("ignoring unknown exthdr type "
"0x%x\n", type);
}
}
/* if RDS_EXTHDR_NPATHS was not found, default to a single-path */
conn->c_npaths = max_t(int, conn->c_npaths, 1);
conn->c_ping_triggered = 0;
rds_conn_peer_gen_update(conn, new_peer_gen_num);
}
/* rds_start_mprds() will synchronously start multiple paths when appropriate.
* The scheme is based on the following rules:
*
* 1. rds_sendmsg on first connect attempt sends the probe ping, with the
* sender's npaths (s_npaths)
* 2. rcvr of probe-ping knows the mprds_paths = min(s_npaths, r_npaths). It
* sends back a probe-pong with r_npaths. After that, if rcvr is the
* smaller ip addr, it starts rds_conn_path_connect_if_down on all
* mprds_paths.
* 3. sender gets woken up, and can move to rds_conn_path_connect_if_down.
* If it is the smaller ipaddr, rds_conn_path_connect_if_down can be
* called after reception of the probe-pong on all mprds_paths.
* Otherwise (sender of probe-ping is not the smaller ip addr): just call
* rds_conn_path_connect_if_down on the hashed path. (see rule 4)
* 4. rds_connect_worker must only trigger a connection if laddr < faddr.
* 5. sender may end up queuing the packet on the cp. will get sent out later.
* when connection is completed.
*/
static void rds_start_mprds(struct rds_connection *conn)
{
int i;
struct rds_conn_path *cp;
if (conn->c_npaths > 1 &&
rds_addr_cmp(&conn->c_laddr, &conn->c_faddr) < 0) {
for (i = 0; i < conn->c_npaths; i++) {
cp = &conn->c_path[i];
rds_conn_path_connect_if_down(cp);
}
}
}
/*
* The transport must make sure that this is serialized against other
* rx and conn reset on this specific conn.
*
* We currently assert that only one fragmented message will be sent
* down a connection at a time. This lets us reassemble in the conn
* instead of per-flow which means that we don't have to go digging through
* flows to tear down partial reassembly progress on conn failure and
* we save flow lookup and locking for each frag arrival. It does mean
* that small messages will wait behind large ones. Fragmenting at all
* is only to reduce the memory consumption of pre-posted buffers.
*
* The caller passes in saddr and daddr instead of us getting it from the
* conn. This lets loopback, who only has one conn for both directions,
* tell us which roles the addrs in the conn are playing for this message.
*/
void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
struct in6_addr *daddr,
struct rds_incoming *inc, gfp_t gfp)
{
struct rds_sock *rs = NULL;
struct sock *sk;
unsigned long flags;
struct rds_conn_path *cp;
inc->i_conn = conn;
inc->i_rx_jiffies = jiffies;
if (conn->c_trans->t_mp_capable)
cp = inc->i_conn_path;
else
cp = &conn->c_path[0];
rdsdebug("conn %p next %llu inc %p seq %llu len %u sport %u dport %u "
"flags 0x%x rx_jiffies %lu\n", conn,
(unsigned long long)cp->cp_next_rx_seq,
inc,
(unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence),
be32_to_cpu(inc->i_hdr.h_len),
be16_to_cpu(inc->i_hdr.h_sport),
be16_to_cpu(inc->i_hdr.h_dport),
inc->i_hdr.h_flags,
inc->i_rx_jiffies);
/*
* Sequence numbers should only increase. Messages get their
* sequence number as they're queued in a sending conn. They
* can be dropped, though, if the sending socket is closed before
* they hit the wire. So sequence numbers can skip forward
* under normal operation. They can also drop back in the conn
* failover case as previously sent messages are resent down the
* new instance of a conn. We drop those, otherwise we have
* to assume that the next valid seq does not come after a
* hole in the fragment stream.
*
* The headers don't give us a way to realize if fragments of
* a message have been dropped. We assume that frags that arrive
* to a flow are part of the current message on the flow that is
* being reassembled. This means that senders can't drop messages
* from the sending conn until all their frags are sent.
*
* XXX we could spend more on the wire to get more robust failure
* detection, arguably worth it to avoid data corruption.
*/
if (be64_to_cpu(inc->i_hdr.h_sequence) < cp->cp_next_rx_seq &&
(inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) {
rds_stats_inc(s_recv_drop_old_seq);
goto out;
}
cp->cp_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1;
if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) {
if (inc->i_hdr.h_sport == 0) {
rdsdebug("ignore ping with 0 sport from %pI6c\n",
saddr);
goto out;
}
rds_stats_inc(s_recv_ping);
rds_send_pong(cp, inc->i_hdr.h_sport);
/* if this is a handshake ping, start multipath if necessary */
if (RDS_HS_PROBE(be16_to_cpu(inc->i_hdr.h_sport),
be16_to_cpu(inc->i_hdr.h_dport))) {
rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
rds_start_mprds(cp->cp_conn);
}
goto out;
}
if (be16_to_cpu(inc->i_hdr.h_dport) == RDS_FLAG_PROBE_PORT &&
inc->i_hdr.h_sport == 0) {
rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
/* if this is a handshake pong, start multipath if necessary */
rds_start_mprds(cp->cp_conn);
wake_up(&cp->cp_conn->c_hs_waitq);
goto out;
}
rs = rds_find_bound(daddr, inc->i_hdr.h_dport, conn->c_bound_if);
if (!rs) {
rds_stats_inc(s_recv_drop_no_sock);
goto out;
}
/* Process extension headers */
rds_recv_incoming_exthdrs(inc, rs);
/* We can be racing with rds_release() which marks the socket dead. */
sk = rds_rs_to_sk(rs);
/* serialize with rds_release -> sock_orphan */
write_lock_irqsave(&rs->rs_recv_lock, flags);
if (!sock_flag(sk, SOCK_DEAD)) {
rdsdebug("adding inc %p to rs %p's recv queue\n", inc, rs);
rds_stats_inc(s_recv_queued);
rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
be32_to_cpu(inc->i_hdr.h_len),
inc->i_hdr.h_dport);
if (sock_flag(sk, SOCK_RCVTSTAMP))
inc->i_rx_tstamp = ktime_get_real();
rds_inc_addref(inc);
inc->i_rx_lat_trace[RDS_MSG_RX_END] = local_clock();
list_add_tail(&inc->i_item, &rs->rs_recv_queue);
__rds_wake_sk_sleep(sk);
} else {
rds_stats_inc(s_recv_drop_dead_sock);
}
write_unlock_irqrestore(&rs->rs_recv_lock, flags);
out:
if (rs)
rds_sock_put(rs);
}
EXPORT_SYMBOL_GPL(rds_recv_incoming);
/*
* be very careful here. This is being called as the condition in
* wait_event_*() needs to cope with being called many times.
*/
static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc)
{
unsigned long flags;
if (!*inc) {
read_lock_irqsave(&rs->rs_recv_lock, flags);
if (!list_empty(&rs->rs_recv_queue)) {
*inc = list_entry(rs->rs_recv_queue.next,
struct rds_incoming,
i_item);
rds_inc_addref(*inc);
}
read_unlock_irqrestore(&rs->rs_recv_lock, flags);
}
return *inc != NULL;
}
static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,
int drop)
{
struct sock *sk = rds_rs_to_sk(rs);
int ret = 0;
unsigned long flags;
write_lock_irqsave(&rs->rs_recv_lock, flags);
if (!list_empty(&inc->i_item)) {
ret = 1;
if (drop) {
/* XXX make sure this i_conn is reliable */
rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
-be32_to_cpu(inc->i_hdr.h_len),
inc->i_hdr.h_dport);
list_del_init(&inc->i_item);
rds_inc_put(inc);
}
}
write_unlock_irqrestore(&rs->rs_recv_lock, flags);
rdsdebug("inc %p rs %p still %d dropped %d\n", inc, rs, ret, drop);
return ret;
}
/*
* Pull errors off the error queue.
* If msghdr is NULL, we will just purge the error queue.
*/
int rds_notify_queue_get(struct rds_sock *rs, struct msghdr *msghdr)
{
struct rds_notifier *notifier;
struct rds_rdma_notify cmsg = { 0 }; /* fill holes with zero */
unsigned int count = 0, max_messages = ~0U;
unsigned long flags;
LIST_HEAD(copy);
int err = 0;
/* put_cmsg copies to user space and thus may sleep. We can't do this
* with rs_lock held, so first grab as many notifications as we can stuff
* in the user provided cmsg buffer. We don't try to copy more, to avoid
* losing notifications - except when the buffer is so small that it wouldn't
* even hold a single notification. Then we give him as much of this single
* msg as we can squeeze in, and set MSG_CTRUNC.
*/
if (msghdr) {
max_messages = msghdr->msg_controllen / CMSG_SPACE(sizeof(cmsg));
if (!max_messages)
max_messages = 1;
}
spin_lock_irqsave(&rs->rs_lock, flags);
while (!list_empty(&rs->rs_notify_queue) && count < max_messages) {
notifier = list_entry(rs->rs_notify_queue.next,
struct rds_notifier, n_list);
list_move(¬ifier->n_list, ©);
count++;
}
spin_unlock_irqrestore(&rs->rs_lock, flags);
if (!count)
return 0;
while (!list_empty(©)) {
notifier = list_entry(copy.next, struct rds_notifier, n_list);
if (msghdr) {
cmsg.user_token = notifier->n_user_token;
cmsg.status = notifier->n_status;
err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_RDMA_STATUS,
sizeof(cmsg), &cmsg);
if (err)
break;
}
list_del_init(¬ifier->n_list);
kfree(notifier);
}
/* If we bailed out because of an error in put_cmsg,
* we may be left with one or more notifications that we
* didn't process. Return them to the head of the list. */
if (!list_empty(©)) {
spin_lock_irqsave(&rs->rs_lock, flags);
list_splice(©, &rs->rs_notify_queue);
spin_unlock_irqrestore(&rs->rs_lock, flags);
}
return err;
}
/*
* Queue a congestion notification
*/
static int rds_notify_cong(struct rds_sock *rs, struct msghdr *msghdr)
{
uint64_t notify = rs->rs_cong_notify;
unsigned long flags;
int err;
err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_CONG_UPDATE,
sizeof(notify), ¬ify);
if (err)
return err;
spin_lock_irqsave(&rs->rs_lock, flags);
rs->rs_cong_notify &= ~notify;
spin_unlock_irqrestore(&rs->rs_lock, flags);
return 0;
}
/*
* Receive any control messages.
*/
static int rds_cmsg_recv(struct rds_incoming *inc, struct msghdr *msg,
struct rds_sock *rs)
{
int ret = 0;
if (inc->i_rdma_cookie) {
ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RDMA_DEST,
sizeof(inc->i_rdma_cookie), &inc->i_rdma_cookie);
if (ret)
goto out;
}
if ((inc->i_rx_tstamp != 0) &&
sock_flag(rds_rs_to_sk(rs), SOCK_RCVTSTAMP)) {
struct __kernel_old_timeval tv = ns_to_kernel_old_timeval(inc->i_rx_tstamp);
if (!sock_flag(rds_rs_to_sk(rs), SOCK_TSTAMP_NEW)) {
ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
sizeof(tv), &tv);
} else {
struct __kernel_sock_timeval sk_tv;
sk_tv.tv_sec = tv.tv_sec;
sk_tv.tv_usec = tv.tv_usec;
ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
sizeof(sk_tv), &sk_tv);
}
if (ret)
goto out;
}
if (rs->rs_rx_traces) {
struct rds_cmsg_rx_trace t;
int i, j;
memset(&t, 0, sizeof(t));
inc->i_rx_lat_trace[RDS_MSG_RX_CMSG] = local_clock();
t.rx_traces = rs->rs_rx_traces;
for (i = 0; i < rs->rs_rx_traces; i++) {
j = rs->rs_rx_trace[i];
t.rx_trace_pos[i] = j;
t.rx_trace[i] = inc->i_rx_lat_trace[j + 1] -
inc->i_rx_lat_trace[j];
}
ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RXPATH_LATENCY,
sizeof(t), &t);
if (ret)
goto out;
}
out:
return ret;
}
static bool rds_recvmsg_zcookie(struct rds_sock *rs, struct msghdr *msg)
{
struct rds_msg_zcopy_queue *q = &rs->rs_zcookie_queue;
struct rds_msg_zcopy_info *info = NULL;
struct rds_zcopy_cookies *done;
unsigned long flags;
if (!msg->msg_control)
return false;
if (!sock_flag(rds_rs_to_sk(rs), SOCK_ZEROCOPY) ||
msg->msg_controllen < CMSG_SPACE(sizeof(*done)))
return false;
spin_lock_irqsave(&q->lock, flags);
if (!list_empty(&q->zcookie_head)) {
info = list_entry(q->zcookie_head.next,
struct rds_msg_zcopy_info, rs_zcookie_next);
list_del(&info->rs_zcookie_next);
}
spin_unlock_irqrestore(&q->lock, flags);
if (!info)
return false;
done = &info->zcookies;
if (put_cmsg(msg, SOL_RDS, RDS_CMSG_ZCOPY_COMPLETION, sizeof(*done),
done)) {
spin_lock_irqsave(&q->lock, flags);
list_add(&info->rs_zcookie_next, &q->zcookie_head);
spin_unlock_irqrestore(&q->lock, flags);
return false;
}
kfree(info);
return true;
}
int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
int msg_flags)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
long timeo;
int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct rds_incoming *inc = NULL;
/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
timeo = sock_rcvtimeo(sk, nonblock);
rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
if (msg_flags & MSG_OOB)
goto out;
if (msg_flags & MSG_ERRQUEUE)
return sock_recv_errqueue(sk, msg, size, SOL_IP, IP_RECVERR);
while (1) {
/* If there are pending notifications, do those - and nothing else */
if (!list_empty(&rs->rs_notify_queue)) {
ret = rds_notify_queue_get(rs, msg);
break;
}
if (rs->rs_cong_notify) {
ret = rds_notify_cong(rs, msg);
break;
}
if (!rds_next_incoming(rs, &inc)) {
if (nonblock) {
bool reaped = rds_recvmsg_zcookie(rs, msg);
ret = reaped ? 0 : -EAGAIN;
break;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
(!list_empty(&rs->rs_notify_queue) ||
rs->rs_cong_notify ||
rds_next_incoming(rs, &inc)), timeo);
rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
break;
}
rdsdebug("copying inc %p from %pI6c:%u to user\n", inc,
&inc->i_conn->c_faddr,
ntohs(inc->i_hdr.h_sport));
ret = inc->i_conn->c_trans->inc_copy_to_user(inc, &msg->msg_iter);
if (ret < 0)
break;
/*
* if the message we just copied isn't at the head of the
* recv queue then someone else raced us to return it, try
* to get the next message.
*/
if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
rds_inc_put(inc);
inc = NULL;
rds_stats_inc(s_recv_deliver_raced);
iov_iter_revert(&msg->msg_iter, ret);
continue;
}
if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
if (msg_flags & MSG_TRUNC)
ret = be32_to_cpu(inc->i_hdr.h_len);
msg->msg_flags |= MSG_TRUNC;
}
if (rds_cmsg_recv(inc, msg, rs)) {
ret = -EFAULT;
goto out;
}
rds_recvmsg_zcookie(rs, msg);
rds_stats_inc(s_recv_delivered);
if (msg->msg_name) {
if (ipv6_addr_v4mapped(&inc->i_saddr)) {
sin = (struct sockaddr_in *)msg->msg_name;
sin->sin_family = AF_INET;
sin->sin_port = inc->i_hdr.h_sport;
sin->sin_addr.s_addr =
inc->i_saddr.s6_addr32[3];
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
msg->msg_namelen = sizeof(*sin);
} else {
sin6 = (struct sockaddr_in6 *)msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = inc->i_hdr.h_sport;
sin6->sin6_addr = inc->i_saddr;
sin6->sin6_flowinfo = 0;
sin6->sin6_scope_id = rs->rs_bound_scope_id;
msg->msg_namelen = sizeof(*sin6);
}
}
break;
}
if (inc)
rds_inc_put(inc);
out:
return ret;
}
/*
* The socket is being shut down and we're asked to drop messages that were
* queued for recvmsg. The caller has unbound the socket so the receive path
* won't queue any more incoming fragments or messages on the socket.
*/
void rds_clear_recv_queue(struct rds_sock *rs)
{
struct sock *sk = rds_rs_to_sk(rs);
struct rds_incoming *inc, *tmp;
unsigned long flags;
write_lock_irqsave(&rs->rs_recv_lock, flags);
list_for_each_entry_safe(inc, tmp, &rs->rs_recv_queue, i_item) {
rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
-be32_to_cpu(inc->i_hdr.h_len),
inc->i_hdr.h_dport);
list_del_init(&inc->i_item);
rds_inc_put(inc);
}
write_unlock_irqrestore(&rs->rs_recv_lock, flags);
}
/*
* inc->i_saddr isn't used here because it is only set in the receive
* path.
*/
void rds_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
__be32 saddr, __be32 daddr, int flip)
{
struct rds_info_message minfo;
minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo.len = be32_to_cpu(inc->i_hdr.h_len);
minfo.tos = inc->i_conn->c_tos;
if (flip) {
minfo.laddr = daddr;
minfo.faddr = saddr;
minfo.lport = inc->i_hdr.h_dport;
minfo.fport = inc->i_hdr.h_sport;
} else {
minfo.laddr = saddr;
minfo.faddr = daddr;
minfo.lport = inc->i_hdr.h_sport;
minfo.fport = inc->i_hdr.h_dport;
}
minfo.flags = 0;
rds_info_copy(iter, &minfo, sizeof(minfo));
}
#if IS_ENABLED(CONFIG_IPV6)
void rds6_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
struct in6_addr *saddr, struct in6_addr *daddr,
int flip)
{
struct rds6_info_message minfo6;
minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
minfo6.tos = inc->i_conn->c_tos;
if (flip) {
minfo6.laddr = *daddr;
minfo6.faddr = *saddr;
minfo6.lport = inc->i_hdr.h_dport;
minfo6.fport = inc->i_hdr.h_sport;
} else {
minfo6.laddr = *saddr;
minfo6.faddr = *daddr;
minfo6.lport = inc->i_hdr.h_sport;
minfo6.fport = inc->i_hdr.h_dport;
}
minfo6.flags = 0;
rds_info_copy(iter, &minfo6, sizeof(minfo6));
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1102_0 |
crossvul-cpp_data_good_308_0 | /* Paravirtualization interfaces
Copyright (C) 2006 Rusty Russell IBM Corporation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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
2007 - x86_64 support added by Glauber de Oliveira Costa, Red Hat Inc
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/export.h>
#include <linux/efi.h>
#include <linux/bcd.h>
#include <linux/highmem.h>
#include <linux/kprobes.h>
#include <asm/bug.h>
#include <asm/paravirt.h>
#include <asm/debugreg.h>
#include <asm/desc.h>
#include <asm/setup.h>
#include <asm/pgtable.h>
#include <asm/time.h>
#include <asm/pgalloc.h>
#include <asm/irq.h>
#include <asm/delay.h>
#include <asm/fixmap.h>
#include <asm/apic.h>
#include <asm/tlbflush.h>
#include <asm/timer.h>
#include <asm/special_insns.h>
/*
* nop stub, which must not clobber anything *including the stack* to
* avoid confusing the entry prologues.
*/
extern void _paravirt_nop(void);
asm (".pushsection .entry.text, \"ax\"\n"
".global _paravirt_nop\n"
"_paravirt_nop:\n\t"
"ret\n\t"
".size _paravirt_nop, . - _paravirt_nop\n\t"
".type _paravirt_nop, @function\n\t"
".popsection");
/* identity function, which can be inlined */
u32 notrace _paravirt_ident_32(u32 x)
{
return x;
}
u64 notrace _paravirt_ident_64(u64 x)
{
return x;
}
void __init default_banner(void)
{
printk(KERN_INFO "Booting paravirtualized kernel on %s\n",
pv_info.name);
}
/* Undefined instruction for dealing with missing ops pointers. */
static const unsigned char ud2a[] = { 0x0f, 0x0b };
struct branch {
unsigned char opcode;
u32 delta;
} __attribute__((packed));
unsigned paravirt_patch_call(void *insnbuf,
const void *target, u16 tgt_clobbers,
unsigned long addr, u16 site_clobbers,
unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (len < 5) {
#ifdef CONFIG_RETPOLINE
WARN_ONCE("Failing to patch indirect CALL in %ps\n", (void *)addr);
#endif
return len; /* call too long for patch site */
}
b->opcode = 0xe8; /* call */
b->delta = delta;
BUILD_BUG_ON(sizeof(*b) != 5);
return 5;
}
unsigned paravirt_patch_jmp(void *insnbuf, const void *target,
unsigned long addr, unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (len < 5) {
#ifdef CONFIG_RETPOLINE
WARN_ONCE("Failing to patch indirect JMP in %ps\n", (void *)addr);
#endif
return len; /* call too long for patch site */
}
b->opcode = 0xe9; /* jmp */
b->delta = delta;
return 5;
}
DEFINE_STATIC_KEY_TRUE(virt_spin_lock_key);
void __init native_pv_lock_init(void)
{
if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
static_branch_disable(&virt_spin_lock_key);
}
/*
* Neat trick to map patch type back to the call within the
* corresponding structure.
*/
static void *get_call_destination(u8 type)
{
struct paravirt_patch_template tmpl = {
.pv_init_ops = pv_init_ops,
.pv_time_ops = pv_time_ops,
.pv_cpu_ops = pv_cpu_ops,
.pv_irq_ops = pv_irq_ops,
.pv_mmu_ops = pv_mmu_ops,
#ifdef CONFIG_PARAVIRT_SPINLOCKS
.pv_lock_ops = pv_lock_ops,
#endif
};
return *((void **)&tmpl + type);
}
unsigned paravirt_patch_default(u8 type, u16 clobbers, void *insnbuf,
unsigned long addr, unsigned len)
{
void *opfunc = get_call_destination(type);
unsigned ret;
if (opfunc == NULL)
/* If there's no function, patch it with a ud2a (BUG) */
ret = paravirt_patch_insns(insnbuf, len, ud2a, ud2a+sizeof(ud2a));
else if (opfunc == _paravirt_nop)
ret = 0;
/* identity functions just return their single argument */
else if (opfunc == _paravirt_ident_32)
ret = paravirt_patch_ident_32(insnbuf, len);
else if (opfunc == _paravirt_ident_64)
ret = paravirt_patch_ident_64(insnbuf, len);
else if (type == PARAVIRT_PATCH(pv_cpu_ops.iret) ||
type == PARAVIRT_PATCH(pv_cpu_ops.usergs_sysret64))
/* If operation requires a jmp, then jmp */
ret = paravirt_patch_jmp(insnbuf, opfunc, addr, len);
else
/* Otherwise call the function; assume target could
clobber any caller-save reg */
ret = paravirt_patch_call(insnbuf, opfunc, CLBR_ANY,
addr, clobbers, len);
return ret;
}
unsigned paravirt_patch_insns(void *insnbuf, unsigned len,
const char *start, const char *end)
{
unsigned insn_len = end - start;
if (insn_len > len || start == NULL)
insn_len = len;
else
memcpy(insnbuf, start, insn_len);
return insn_len;
}
static void native_flush_tlb(void)
{
__native_flush_tlb();
}
/*
* Global pages have to be flushed a bit differently. Not a real
* performance problem because this does not happen often.
*/
static void native_flush_tlb_global(void)
{
__native_flush_tlb_global();
}
static void native_flush_tlb_one_user(unsigned long addr)
{
__native_flush_tlb_one_user(addr);
}
struct static_key paravirt_steal_enabled;
struct static_key paravirt_steal_rq_enabled;
static u64 native_steal_clock(int cpu)
{
return 0;
}
/* These are in entry.S */
extern void native_iret(void);
extern void native_usergs_sysret64(void);
static struct resource reserve_ioports = {
.start = 0,
.end = IO_SPACE_LIMIT,
.name = "paravirt-ioport",
.flags = IORESOURCE_IO | IORESOURCE_BUSY,
};
/*
* Reserve the whole legacy IO space to prevent any legacy drivers
* from wasting time probing for their hardware. This is a fairly
* brute-force approach to disabling all non-virtual drivers.
*
* Note that this must be called very early to have any effect.
*/
int paravirt_disable_iospace(void)
{
return request_resource(&ioport_resource, &reserve_ioports);
}
static DEFINE_PER_CPU(enum paravirt_lazy_mode, paravirt_lazy_mode) = PARAVIRT_LAZY_NONE;
static inline void enter_lazy(enum paravirt_lazy_mode mode)
{
BUG_ON(this_cpu_read(paravirt_lazy_mode) != PARAVIRT_LAZY_NONE);
this_cpu_write(paravirt_lazy_mode, mode);
}
static void leave_lazy(enum paravirt_lazy_mode mode)
{
BUG_ON(this_cpu_read(paravirt_lazy_mode) != mode);
this_cpu_write(paravirt_lazy_mode, PARAVIRT_LAZY_NONE);
}
void paravirt_enter_lazy_mmu(void)
{
enter_lazy(PARAVIRT_LAZY_MMU);
}
void paravirt_leave_lazy_mmu(void)
{
leave_lazy(PARAVIRT_LAZY_MMU);
}
void paravirt_flush_lazy_mmu(void)
{
preempt_disable();
if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU) {
arch_leave_lazy_mmu_mode();
arch_enter_lazy_mmu_mode();
}
preempt_enable();
}
void paravirt_start_context_switch(struct task_struct *prev)
{
BUG_ON(preemptible());
if (this_cpu_read(paravirt_lazy_mode) == PARAVIRT_LAZY_MMU) {
arch_leave_lazy_mmu_mode();
set_ti_thread_flag(task_thread_info(prev), TIF_LAZY_MMU_UPDATES);
}
enter_lazy(PARAVIRT_LAZY_CPU);
}
void paravirt_end_context_switch(struct task_struct *next)
{
BUG_ON(preemptible());
leave_lazy(PARAVIRT_LAZY_CPU);
if (test_and_clear_ti_thread_flag(task_thread_info(next), TIF_LAZY_MMU_UPDATES))
arch_enter_lazy_mmu_mode();
}
enum paravirt_lazy_mode paravirt_get_lazy_mode(void)
{
if (in_interrupt())
return PARAVIRT_LAZY_NONE;
return this_cpu_read(paravirt_lazy_mode);
}
struct pv_info pv_info = {
.name = "bare hardware",
.kernel_rpl = 0,
.shared_kernel_pmd = 1, /* Only used when CONFIG_X86_PAE is set */
#ifdef CONFIG_X86_64
.extra_user_64bit_cs = __USER_CS,
#endif
};
struct pv_init_ops pv_init_ops = {
.patch = native_patch,
};
struct pv_time_ops pv_time_ops = {
.sched_clock = native_sched_clock,
.steal_clock = native_steal_clock,
};
__visible struct pv_irq_ops pv_irq_ops = {
.save_fl = __PV_IS_CALLEE_SAVE(native_save_fl),
.restore_fl = __PV_IS_CALLEE_SAVE(native_restore_fl),
.irq_disable = __PV_IS_CALLEE_SAVE(native_irq_disable),
.irq_enable = __PV_IS_CALLEE_SAVE(native_irq_enable),
.safe_halt = native_safe_halt,
.halt = native_halt,
};
__visible struct pv_cpu_ops pv_cpu_ops = {
.cpuid = native_cpuid,
.get_debugreg = native_get_debugreg,
.set_debugreg = native_set_debugreg,
.read_cr0 = native_read_cr0,
.write_cr0 = native_write_cr0,
.write_cr4 = native_write_cr4,
#ifdef CONFIG_X86_64
.read_cr8 = native_read_cr8,
.write_cr8 = native_write_cr8,
#endif
.wbinvd = native_wbinvd,
.read_msr = native_read_msr,
.write_msr = native_write_msr,
.read_msr_safe = native_read_msr_safe,
.write_msr_safe = native_write_msr_safe,
.read_pmc = native_read_pmc,
.load_tr_desc = native_load_tr_desc,
.set_ldt = native_set_ldt,
.load_gdt = native_load_gdt,
.load_idt = native_load_idt,
.store_tr = native_store_tr,
.load_tls = native_load_tls,
#ifdef CONFIG_X86_64
.load_gs_index = native_load_gs_index,
#endif
.write_ldt_entry = native_write_ldt_entry,
.write_gdt_entry = native_write_gdt_entry,
.write_idt_entry = native_write_idt_entry,
.alloc_ldt = paravirt_nop,
.free_ldt = paravirt_nop,
.load_sp0 = native_load_sp0,
#ifdef CONFIG_X86_64
.usergs_sysret64 = native_usergs_sysret64,
#endif
.iret = native_iret,
.swapgs = native_swapgs,
.set_iopl_mask = native_set_iopl_mask,
.io_delay = native_io_delay,
.start_context_switch = paravirt_nop,
.end_context_switch = paravirt_nop,
};
/* At this point, native_get/set_debugreg has real function entries */
NOKPROBE_SYMBOL(native_get_debugreg);
NOKPROBE_SYMBOL(native_set_debugreg);
NOKPROBE_SYMBOL(native_load_idt);
#if defined(CONFIG_X86_32) && !defined(CONFIG_X86_PAE)
/* 32-bit pagetable entries */
#define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_32)
#else
/* 64-bit pagetable entries */
#define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_64)
#endif
struct pv_mmu_ops pv_mmu_ops __ro_after_init = {
.read_cr2 = native_read_cr2,
.write_cr2 = native_write_cr2,
.read_cr3 = __native_read_cr3,
.write_cr3 = native_write_cr3,
.flush_tlb_user = native_flush_tlb,
.flush_tlb_kernel = native_flush_tlb_global,
.flush_tlb_one_user = native_flush_tlb_one_user,
.flush_tlb_others = native_flush_tlb_others,
.pgd_alloc = __paravirt_pgd_alloc,
.pgd_free = paravirt_nop,
.alloc_pte = paravirt_nop,
.alloc_pmd = paravirt_nop,
.alloc_pud = paravirt_nop,
.alloc_p4d = paravirt_nop,
.release_pte = paravirt_nop,
.release_pmd = paravirt_nop,
.release_pud = paravirt_nop,
.release_p4d = paravirt_nop,
.set_pte = native_set_pte,
.set_pte_at = native_set_pte_at,
.set_pmd = native_set_pmd,
.ptep_modify_prot_start = __ptep_modify_prot_start,
.ptep_modify_prot_commit = __ptep_modify_prot_commit,
#if CONFIG_PGTABLE_LEVELS >= 3
#ifdef CONFIG_X86_PAE
.set_pte_atomic = native_set_pte_atomic,
.pte_clear = native_pte_clear,
.pmd_clear = native_pmd_clear,
#endif
.set_pud = native_set_pud,
.pmd_val = PTE_IDENT,
.make_pmd = PTE_IDENT,
#if CONFIG_PGTABLE_LEVELS >= 4
.pud_val = PTE_IDENT,
.make_pud = PTE_IDENT,
.set_p4d = native_set_p4d,
#if CONFIG_PGTABLE_LEVELS >= 5
.p4d_val = PTE_IDENT,
.make_p4d = PTE_IDENT,
.set_pgd = native_set_pgd,
#endif /* CONFIG_PGTABLE_LEVELS >= 5 */
#endif /* CONFIG_PGTABLE_LEVELS >= 4 */
#endif /* CONFIG_PGTABLE_LEVELS >= 3 */
.pte_val = PTE_IDENT,
.pgd_val = PTE_IDENT,
.make_pte = PTE_IDENT,
.make_pgd = PTE_IDENT,
.dup_mmap = paravirt_nop,
.exit_mmap = paravirt_nop,
.activate_mm = paravirt_nop,
.lazy_mode = {
.enter = paravirt_nop,
.leave = paravirt_nop,
.flush = paravirt_nop,
},
.set_fixmap = native_set_fixmap,
};
EXPORT_SYMBOL_GPL(pv_time_ops);
EXPORT_SYMBOL (pv_cpu_ops);
EXPORT_SYMBOL (pv_mmu_ops);
EXPORT_SYMBOL_GPL(pv_info);
EXPORT_SYMBOL (pv_irq_ops);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_308_0 |
crossvul-cpp_data_bad_1331_0 | // SPDX-License-Identifier: GPL-2.0
/* Parts of this driver are based on the following:
* - Kvaser linux leaf driver (version 4.78)
* - CAN driver for esd CAN-USB/2
* - Kvaser linux usbcanII driver (version 5.3)
*
* Copyright (C) 2002-2018 KVASER AB, Sweden. All rights reserved.
* Copyright (C) 2010 Matthias Fuchs <matthias.fuchs@esd.eu>, esd gmbh
* Copyright (C) 2012 Olivier Sobrie <olivier@sobrie.be>
* Copyright (C) 2015 Valeo S.A.
*/
#include <linux/completion.h>
#include <linux/device.h>
#include <linux/gfp.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/usb.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include <linux/can/netlink.h>
#include "kvaser_usb.h"
/* Forward declaration */
static const struct kvaser_usb_dev_cfg kvaser_usb_leaf_dev_cfg;
#define CAN_USB_CLOCK 8000000
#define MAX_USBCAN_NET_DEVICES 2
/* Command header size */
#define CMD_HEADER_LEN 2
/* Kvaser CAN message flags */
#define MSG_FLAG_ERROR_FRAME BIT(0)
#define MSG_FLAG_OVERRUN BIT(1)
#define MSG_FLAG_NERR BIT(2)
#define MSG_FLAG_WAKEUP BIT(3)
#define MSG_FLAG_REMOTE_FRAME BIT(4)
#define MSG_FLAG_RESERVED BIT(5)
#define MSG_FLAG_TX_ACK BIT(6)
#define MSG_FLAG_TX_REQUEST BIT(7)
/* CAN states (M16C CxSTRH register) */
#define M16C_STATE_BUS_RESET BIT(0)
#define M16C_STATE_BUS_ERROR BIT(4)
#define M16C_STATE_BUS_PASSIVE BIT(5)
#define M16C_STATE_BUS_OFF BIT(6)
/* Leaf/usbcan command ids */
#define CMD_RX_STD_MESSAGE 12
#define CMD_TX_STD_MESSAGE 13
#define CMD_RX_EXT_MESSAGE 14
#define CMD_TX_EXT_MESSAGE 15
#define CMD_SET_BUS_PARAMS 16
#define CMD_CHIP_STATE_EVENT 20
#define CMD_SET_CTRL_MODE 21
#define CMD_RESET_CHIP 24
#define CMD_START_CHIP 26
#define CMD_START_CHIP_REPLY 27
#define CMD_STOP_CHIP 28
#define CMD_STOP_CHIP_REPLY 29
#define CMD_USBCAN_CLOCK_OVERFLOW_EVENT 33
#define CMD_GET_CARD_INFO 34
#define CMD_GET_CARD_INFO_REPLY 35
#define CMD_GET_SOFTWARE_INFO 38
#define CMD_GET_SOFTWARE_INFO_REPLY 39
#define CMD_FLUSH_QUEUE 48
#define CMD_TX_ACKNOWLEDGE 50
#define CMD_CAN_ERROR_EVENT 51
#define CMD_FLUSH_QUEUE_REPLY 68
#define CMD_LEAF_LOG_MESSAGE 106
/* error factors */
#define M16C_EF_ACKE BIT(0)
#define M16C_EF_CRCE BIT(1)
#define M16C_EF_FORME BIT(2)
#define M16C_EF_STFE BIT(3)
#define M16C_EF_BITE0 BIT(4)
#define M16C_EF_BITE1 BIT(5)
#define M16C_EF_RCVE BIT(6)
#define M16C_EF_TRE BIT(7)
/* Only Leaf-based devices can report M16C error factors,
* thus define our own error status flags for USBCANII
*/
#define USBCAN_ERROR_STATE_NONE 0
#define USBCAN_ERROR_STATE_TX_ERROR BIT(0)
#define USBCAN_ERROR_STATE_RX_ERROR BIT(1)
#define USBCAN_ERROR_STATE_BUSERROR BIT(2)
/* bittiming parameters */
#define KVASER_USB_TSEG1_MIN 1
#define KVASER_USB_TSEG1_MAX 16
#define KVASER_USB_TSEG2_MIN 1
#define KVASER_USB_TSEG2_MAX 8
#define KVASER_USB_SJW_MAX 4
#define KVASER_USB_BRP_MIN 1
#define KVASER_USB_BRP_MAX 64
#define KVASER_USB_BRP_INC 1
/* ctrl modes */
#define KVASER_CTRL_MODE_NORMAL 1
#define KVASER_CTRL_MODE_SILENT 2
#define KVASER_CTRL_MODE_SELFRECEPTION 3
#define KVASER_CTRL_MODE_OFF 4
/* Extended CAN identifier flag */
#define KVASER_EXTENDED_FRAME BIT(31)
struct kvaser_cmd_simple {
u8 tid;
u8 channel;
} __packed;
struct kvaser_cmd_cardinfo {
u8 tid;
u8 nchannels;
__le32 serial_number;
__le32 padding0;
__le32 clock_resolution;
__le32 mfgdate;
u8 ean[8];
u8 hw_revision;
union {
struct {
u8 usb_hs_mode;
} __packed leaf1;
struct {
u8 padding;
} __packed usbcan1;
} __packed;
__le16 padding1;
} __packed;
struct leaf_cmd_softinfo {
u8 tid;
u8 padding0;
__le32 sw_options;
__le32 fw_version;
__le16 max_outstanding_tx;
__le16 padding1[9];
} __packed;
struct usbcan_cmd_softinfo {
u8 tid;
u8 fw_name[5];
__le16 max_outstanding_tx;
u8 padding[6];
__le32 fw_version;
__le16 checksum;
__le16 sw_options;
} __packed;
struct kvaser_cmd_busparams {
u8 tid;
u8 channel;
__le32 bitrate;
u8 tseg1;
u8 tseg2;
u8 sjw;
u8 no_samp;
} __packed;
struct kvaser_cmd_tx_can {
u8 channel;
u8 tid;
u8 data[14];
union {
struct {
u8 padding;
u8 flags;
} __packed leaf;
struct {
u8 flags;
u8 padding;
} __packed usbcan;
} __packed;
} __packed;
struct kvaser_cmd_rx_can_header {
u8 channel;
u8 flag;
} __packed;
struct leaf_cmd_rx_can {
u8 channel;
u8 flag;
__le16 time[3];
u8 data[14];
} __packed;
struct usbcan_cmd_rx_can {
u8 channel;
u8 flag;
u8 data[14];
__le16 time;
} __packed;
struct leaf_cmd_chip_state_event {
u8 tid;
u8 channel;
__le16 time[3];
u8 tx_errors_count;
u8 rx_errors_count;
u8 status;
u8 padding[3];
} __packed;
struct usbcan_cmd_chip_state_event {
u8 tid;
u8 channel;
u8 tx_errors_count;
u8 rx_errors_count;
__le16 time;
u8 status;
u8 padding[3];
} __packed;
struct kvaser_cmd_tx_acknowledge_header {
u8 channel;
u8 tid;
} __packed;
struct leaf_cmd_error_event {
u8 tid;
u8 flags;
__le16 time[3];
u8 channel;
u8 padding;
u8 tx_errors_count;
u8 rx_errors_count;
u8 status;
u8 error_factor;
} __packed;
struct usbcan_cmd_error_event {
u8 tid;
u8 padding;
u8 tx_errors_count_ch0;
u8 rx_errors_count_ch0;
u8 tx_errors_count_ch1;
u8 rx_errors_count_ch1;
u8 status_ch0;
u8 status_ch1;
__le16 time;
} __packed;
struct kvaser_cmd_ctrl_mode {
u8 tid;
u8 channel;
u8 ctrl_mode;
u8 padding[3];
} __packed;
struct kvaser_cmd_flush_queue {
u8 tid;
u8 channel;
u8 flags;
u8 padding[3];
} __packed;
struct leaf_cmd_log_message {
u8 channel;
u8 flags;
__le16 time[3];
u8 dlc;
u8 time_offset;
__le32 id;
u8 data[8];
} __packed;
struct kvaser_cmd {
u8 len;
u8 id;
union {
struct kvaser_cmd_simple simple;
struct kvaser_cmd_cardinfo cardinfo;
struct kvaser_cmd_busparams busparams;
struct kvaser_cmd_rx_can_header rx_can_header;
struct kvaser_cmd_tx_acknowledge_header tx_acknowledge_header;
union {
struct leaf_cmd_softinfo softinfo;
struct leaf_cmd_rx_can rx_can;
struct leaf_cmd_chip_state_event chip_state_event;
struct leaf_cmd_error_event error_event;
struct leaf_cmd_log_message log_message;
} __packed leaf;
union {
struct usbcan_cmd_softinfo softinfo;
struct usbcan_cmd_rx_can rx_can;
struct usbcan_cmd_chip_state_event chip_state_event;
struct usbcan_cmd_error_event error_event;
} __packed usbcan;
struct kvaser_cmd_tx_can tx_can;
struct kvaser_cmd_ctrl_mode ctrl_mode;
struct kvaser_cmd_flush_queue flush_queue;
} u;
} __packed;
/* Summary of a kvaser error event, for a unified Leaf/Usbcan error
* handling. Some discrepancies between the two families exist:
*
* - USBCAN firmware does not report M16C "error factors"
* - USBCAN controllers has difficulties reporting if the raised error
* event is for ch0 or ch1. They leave such arbitration to the OS
* driver by letting it compare error counters with previous values
* and decide the error event's channel. Thus for USBCAN, the channel
* field is only advisory.
*/
struct kvaser_usb_err_summary {
u8 channel, status, txerr, rxerr;
union {
struct {
u8 error_factor;
} leaf;
struct {
u8 other_ch_status;
u8 error_state;
} usbcan;
};
};
static void *
kvaser_usb_leaf_frame_to_cmd(const struct kvaser_usb_net_priv *priv,
const struct sk_buff *skb, int *frame_len,
int *cmd_len, u16 transid)
{
struct kvaser_usb *dev = priv->dev;
struct kvaser_cmd *cmd;
u8 *cmd_tx_can_flags = NULL; /* GCC */
struct can_frame *cf = (struct can_frame *)skb->data;
*frame_len = cf->can_dlc;
cmd = kmalloc(sizeof(*cmd), GFP_ATOMIC);
if (cmd) {
cmd->u.tx_can.tid = transid & 0xff;
cmd->len = *cmd_len = CMD_HEADER_LEN +
sizeof(struct kvaser_cmd_tx_can);
cmd->u.tx_can.channel = priv->channel;
switch (dev->card_data.leaf.family) {
case KVASER_LEAF:
cmd_tx_can_flags = &cmd->u.tx_can.leaf.flags;
break;
case KVASER_USBCAN:
cmd_tx_can_flags = &cmd->u.tx_can.usbcan.flags;
break;
}
*cmd_tx_can_flags = 0;
if (cf->can_id & CAN_EFF_FLAG) {
cmd->id = CMD_TX_EXT_MESSAGE;
cmd->u.tx_can.data[0] = (cf->can_id >> 24) & 0x1f;
cmd->u.tx_can.data[1] = (cf->can_id >> 18) & 0x3f;
cmd->u.tx_can.data[2] = (cf->can_id >> 14) & 0x0f;
cmd->u.tx_can.data[3] = (cf->can_id >> 6) & 0xff;
cmd->u.tx_can.data[4] = cf->can_id & 0x3f;
} else {
cmd->id = CMD_TX_STD_MESSAGE;
cmd->u.tx_can.data[0] = (cf->can_id >> 6) & 0x1f;
cmd->u.tx_can.data[1] = cf->can_id & 0x3f;
}
cmd->u.tx_can.data[5] = cf->can_dlc;
memcpy(&cmd->u.tx_can.data[6], cf->data, cf->can_dlc);
if (cf->can_id & CAN_RTR_FLAG)
*cmd_tx_can_flags |= MSG_FLAG_REMOTE_FRAME;
}
return cmd;
}
static int kvaser_usb_leaf_wait_cmd(const struct kvaser_usb *dev, u8 id,
struct kvaser_cmd *cmd)
{
struct kvaser_cmd *tmp;
void *buf;
int actual_len;
int err;
int pos;
unsigned long to = jiffies + msecs_to_jiffies(KVASER_USB_TIMEOUT);
buf = kzalloc(KVASER_USB_RX_BUFFER_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
do {
err = kvaser_usb_recv_cmd(dev, buf, KVASER_USB_RX_BUFFER_SIZE,
&actual_len);
if (err < 0)
goto end;
pos = 0;
while (pos <= actual_len - CMD_HEADER_LEN) {
tmp = buf + pos;
/* Handle commands crossing the USB endpoint max packet
* size boundary. Check kvaser_usb_read_bulk_callback()
* for further details.
*/
if (tmp->len == 0) {
pos = round_up(pos,
le16_to_cpu
(dev->bulk_in->wMaxPacketSize));
continue;
}
if (pos + tmp->len > actual_len) {
dev_err_ratelimited(&dev->intf->dev,
"Format error\n");
break;
}
if (tmp->id == id) {
memcpy(cmd, tmp, tmp->len);
goto end;
}
pos += tmp->len;
}
} while (time_before(jiffies, to));
err = -EINVAL;
end:
kfree(buf);
return err;
}
static int kvaser_usb_leaf_send_simple_cmd(const struct kvaser_usb *dev,
u8 cmd_id, int channel)
{
struct kvaser_cmd *cmd;
int rc;
cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd)
return -ENOMEM;
cmd->id = cmd_id;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_simple);
cmd->u.simple.channel = channel;
cmd->u.simple.tid = 0xff;
rc = kvaser_usb_send_cmd(dev, cmd, cmd->len);
kfree(cmd);
return rc;
}
static int kvaser_usb_leaf_get_software_info_inner(struct kvaser_usb *dev)
{
struct kvaser_cmd cmd;
int err;
err = kvaser_usb_leaf_send_simple_cmd(dev, CMD_GET_SOFTWARE_INFO, 0);
if (err)
return err;
err = kvaser_usb_leaf_wait_cmd(dev, CMD_GET_SOFTWARE_INFO_REPLY, &cmd);
if (err)
return err;
switch (dev->card_data.leaf.family) {
case KVASER_LEAF:
dev->fw_version = le32_to_cpu(cmd.u.leaf.softinfo.fw_version);
dev->max_tx_urbs =
le16_to_cpu(cmd.u.leaf.softinfo.max_outstanding_tx);
break;
case KVASER_USBCAN:
dev->fw_version = le32_to_cpu(cmd.u.usbcan.softinfo.fw_version);
dev->max_tx_urbs =
le16_to_cpu(cmd.u.usbcan.softinfo.max_outstanding_tx);
break;
}
return 0;
}
static int kvaser_usb_leaf_get_software_info(struct kvaser_usb *dev)
{
int err;
int retry = 3;
/* On some x86 laptops, plugging a Kvaser device again after
* an unplug makes the firmware always ignore the very first
* command. For such a case, provide some room for retries
* instead of completely exiting the driver.
*/
do {
err = kvaser_usb_leaf_get_software_info_inner(dev);
} while (--retry && err == -ETIMEDOUT);
return err;
}
static int kvaser_usb_leaf_get_card_info(struct kvaser_usb *dev)
{
struct kvaser_cmd cmd;
int err;
err = kvaser_usb_leaf_send_simple_cmd(dev, CMD_GET_CARD_INFO, 0);
if (err)
return err;
err = kvaser_usb_leaf_wait_cmd(dev, CMD_GET_CARD_INFO_REPLY, &cmd);
if (err)
return err;
dev->nchannels = cmd.u.cardinfo.nchannels;
if (dev->nchannels > KVASER_USB_MAX_NET_DEVICES ||
(dev->card_data.leaf.family == KVASER_USBCAN &&
dev->nchannels > MAX_USBCAN_NET_DEVICES))
return -EINVAL;
return 0;
}
static void kvaser_usb_leaf_tx_acknowledge(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct net_device_stats *stats;
struct kvaser_usb_tx_urb_context *context;
struct kvaser_usb_net_priv *priv;
unsigned long flags;
u8 channel, tid;
channel = cmd->u.tx_acknowledge_header.channel;
tid = cmd->u.tx_acknowledge_header.tid;
if (channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", channel);
return;
}
priv = dev->nets[channel];
if (!netif_device_present(priv->netdev))
return;
stats = &priv->netdev->stats;
context = &priv->tx_contexts[tid % dev->max_tx_urbs];
/* Sometimes the state change doesn't come after a bus-off event */
if (priv->can.restart_ms && priv->can.state >= CAN_STATE_BUS_OFF) {
struct sk_buff *skb;
struct can_frame *cf;
skb = alloc_can_err_skb(priv->netdev, &cf);
if (skb) {
cf->can_id |= CAN_ERR_RESTARTED;
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_rx(skb);
} else {
netdev_err(priv->netdev,
"No memory left for err_skb\n");
}
priv->can.can_stats.restarts++;
netif_carrier_on(priv->netdev);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
}
stats->tx_packets++;
stats->tx_bytes += context->dlc;
spin_lock_irqsave(&priv->tx_contexts_lock, flags);
can_get_echo_skb(priv->netdev, context->echo_index);
context->echo_index = dev->max_tx_urbs;
--priv->active_tx_contexts;
netif_wake_queue(priv->netdev);
spin_unlock_irqrestore(&priv->tx_contexts_lock, flags);
}
static int kvaser_usb_leaf_simple_cmd_async(struct kvaser_usb_net_priv *priv,
u8 cmd_id)
{
struct kvaser_cmd *cmd;
int err;
cmd = kmalloc(sizeof(*cmd), GFP_ATOMIC);
if (!cmd)
return -ENOMEM;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_simple);
cmd->id = cmd_id;
cmd->u.simple.channel = priv->channel;
err = kvaser_usb_send_cmd_async(priv, cmd, cmd->len);
if (err)
kfree(cmd);
return err;
}
static void
kvaser_usb_leaf_rx_error_update_can_state(struct kvaser_usb_net_priv *priv,
const struct kvaser_usb_err_summary *es,
struct can_frame *cf)
{
struct kvaser_usb *dev = priv->dev;
struct net_device_stats *stats = &priv->netdev->stats;
enum can_state cur_state, new_state, tx_state, rx_state;
netdev_dbg(priv->netdev, "Error status: 0x%02x\n", es->status);
new_state = priv->can.state;
cur_state = priv->can.state;
if (es->status & (M16C_STATE_BUS_OFF | M16C_STATE_BUS_RESET)) {
new_state = CAN_STATE_BUS_OFF;
} else if (es->status & M16C_STATE_BUS_PASSIVE) {
new_state = CAN_STATE_ERROR_PASSIVE;
} else if (es->status & M16C_STATE_BUS_ERROR) {
/* Guard against spurious error events after a busoff */
if (cur_state < CAN_STATE_BUS_OFF) {
if (es->txerr >= 128 || es->rxerr >= 128)
new_state = CAN_STATE_ERROR_PASSIVE;
else if (es->txerr >= 96 || es->rxerr >= 96)
new_state = CAN_STATE_ERROR_WARNING;
else if (cur_state > CAN_STATE_ERROR_ACTIVE)
new_state = CAN_STATE_ERROR_ACTIVE;
}
}
if (!es->status)
new_state = CAN_STATE_ERROR_ACTIVE;
if (new_state != cur_state) {
tx_state = (es->txerr >= es->rxerr) ? new_state : 0;
rx_state = (es->txerr <= es->rxerr) ? new_state : 0;
can_change_state(priv->netdev, cf, tx_state, rx_state);
}
if (priv->can.restart_ms &&
cur_state >= CAN_STATE_BUS_OFF &&
new_state < CAN_STATE_BUS_OFF)
priv->can.can_stats.restarts++;
switch (dev->card_data.leaf.family) {
case KVASER_LEAF:
if (es->leaf.error_factor) {
priv->can.can_stats.bus_error++;
stats->rx_errors++;
}
break;
case KVASER_USBCAN:
if (es->usbcan.error_state & USBCAN_ERROR_STATE_TX_ERROR)
stats->tx_errors++;
if (es->usbcan.error_state & USBCAN_ERROR_STATE_RX_ERROR)
stats->rx_errors++;
if (es->usbcan.error_state & USBCAN_ERROR_STATE_BUSERROR)
priv->can.can_stats.bus_error++;
break;
}
priv->bec.txerr = es->txerr;
priv->bec.rxerr = es->rxerr;
}
static void kvaser_usb_leaf_rx_error(const struct kvaser_usb *dev,
const struct kvaser_usb_err_summary *es)
{
struct can_frame *cf;
struct can_frame tmp_cf = { .can_id = CAN_ERR_FLAG,
.can_dlc = CAN_ERR_DLC };
struct sk_buff *skb;
struct net_device_stats *stats;
struct kvaser_usb_net_priv *priv;
enum can_state old_state, new_state;
if (es->channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", es->channel);
return;
}
priv = dev->nets[es->channel];
stats = &priv->netdev->stats;
/* Update all of the CAN interface's state and error counters before
* trying any memory allocation that can actually fail with -ENOMEM.
*
* We send a temporary stack-allocated error CAN frame to
* can_change_state() for the very same reason.
*
* TODO: Split can_change_state() responsibility between updating the
* CAN interface's state and counters, and the setting up of CAN error
* frame ID and data to userspace. Remove stack allocation afterwards.
*/
old_state = priv->can.state;
kvaser_usb_leaf_rx_error_update_can_state(priv, es, &tmp_cf);
new_state = priv->can.state;
skb = alloc_can_err_skb(priv->netdev, &cf);
if (!skb) {
stats->rx_dropped++;
return;
}
memcpy(cf, &tmp_cf, sizeof(*cf));
if (new_state != old_state) {
if (es->status &
(M16C_STATE_BUS_OFF | M16C_STATE_BUS_RESET)) {
if (!priv->can.restart_ms)
kvaser_usb_leaf_simple_cmd_async(priv,
CMD_STOP_CHIP);
netif_carrier_off(priv->netdev);
}
if (priv->can.restart_ms &&
old_state >= CAN_STATE_BUS_OFF &&
new_state < CAN_STATE_BUS_OFF) {
cf->can_id |= CAN_ERR_RESTARTED;
netif_carrier_on(priv->netdev);
}
}
switch (dev->card_data.leaf.family) {
case KVASER_LEAF:
if (es->leaf.error_factor) {
cf->can_id |= CAN_ERR_BUSERROR | CAN_ERR_PROT;
if (es->leaf.error_factor & M16C_EF_ACKE)
cf->data[3] = CAN_ERR_PROT_LOC_ACK;
if (es->leaf.error_factor & M16C_EF_CRCE)
cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;
if (es->leaf.error_factor & M16C_EF_FORME)
cf->data[2] |= CAN_ERR_PROT_FORM;
if (es->leaf.error_factor & M16C_EF_STFE)
cf->data[2] |= CAN_ERR_PROT_STUFF;
if (es->leaf.error_factor & M16C_EF_BITE0)
cf->data[2] |= CAN_ERR_PROT_BIT0;
if (es->leaf.error_factor & M16C_EF_BITE1)
cf->data[2] |= CAN_ERR_PROT_BIT1;
if (es->leaf.error_factor & M16C_EF_TRE)
cf->data[2] |= CAN_ERR_PROT_TX;
}
break;
case KVASER_USBCAN:
if (es->usbcan.error_state & USBCAN_ERROR_STATE_BUSERROR)
cf->can_id |= CAN_ERR_BUSERROR;
break;
}
cf->data[6] = es->txerr;
cf->data[7] = es->rxerr;
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_rx(skb);
}
/* For USBCAN, report error to userspace if the channels's errors counter
* has changed, or we're the only channel seeing a bus error state.
*/
static void
kvaser_usb_leaf_usbcan_conditionally_rx_error(const struct kvaser_usb *dev,
struct kvaser_usb_err_summary *es)
{
struct kvaser_usb_net_priv *priv;
unsigned int channel;
bool report_error;
channel = es->channel;
if (channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", channel);
return;
}
priv = dev->nets[channel];
report_error = false;
if (es->txerr != priv->bec.txerr) {
es->usbcan.error_state |= USBCAN_ERROR_STATE_TX_ERROR;
report_error = true;
}
if (es->rxerr != priv->bec.rxerr) {
es->usbcan.error_state |= USBCAN_ERROR_STATE_RX_ERROR;
report_error = true;
}
if ((es->status & M16C_STATE_BUS_ERROR) &&
!(es->usbcan.other_ch_status & M16C_STATE_BUS_ERROR)) {
es->usbcan.error_state |= USBCAN_ERROR_STATE_BUSERROR;
report_error = true;
}
if (report_error)
kvaser_usb_leaf_rx_error(dev, es);
}
static void kvaser_usb_leaf_usbcan_rx_error(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct kvaser_usb_err_summary es = { };
switch (cmd->id) {
/* Sometimes errors are sent as unsolicited chip state events */
case CMD_CHIP_STATE_EVENT:
es.channel = cmd->u.usbcan.chip_state_event.channel;
es.status = cmd->u.usbcan.chip_state_event.status;
es.txerr = cmd->u.usbcan.chip_state_event.tx_errors_count;
es.rxerr = cmd->u.usbcan.chip_state_event.rx_errors_count;
kvaser_usb_leaf_usbcan_conditionally_rx_error(dev, &es);
break;
case CMD_CAN_ERROR_EVENT:
es.channel = 0;
es.status = cmd->u.usbcan.error_event.status_ch0;
es.txerr = cmd->u.usbcan.error_event.tx_errors_count_ch0;
es.rxerr = cmd->u.usbcan.error_event.rx_errors_count_ch0;
es.usbcan.other_ch_status =
cmd->u.usbcan.error_event.status_ch1;
kvaser_usb_leaf_usbcan_conditionally_rx_error(dev, &es);
/* The USBCAN firmware supports up to 2 channels.
* Now that ch0 was checked, check if ch1 has any errors.
*/
if (dev->nchannels == MAX_USBCAN_NET_DEVICES) {
es.channel = 1;
es.status = cmd->u.usbcan.error_event.status_ch1;
es.txerr =
cmd->u.usbcan.error_event.tx_errors_count_ch1;
es.rxerr =
cmd->u.usbcan.error_event.rx_errors_count_ch1;
es.usbcan.other_ch_status =
cmd->u.usbcan.error_event.status_ch0;
kvaser_usb_leaf_usbcan_conditionally_rx_error(dev, &es);
}
break;
default:
dev_err(&dev->intf->dev, "Invalid cmd id (%d)\n", cmd->id);
}
}
static void kvaser_usb_leaf_leaf_rx_error(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct kvaser_usb_err_summary es = { };
switch (cmd->id) {
case CMD_CAN_ERROR_EVENT:
es.channel = cmd->u.leaf.error_event.channel;
es.status = cmd->u.leaf.error_event.status;
es.txerr = cmd->u.leaf.error_event.tx_errors_count;
es.rxerr = cmd->u.leaf.error_event.rx_errors_count;
es.leaf.error_factor = cmd->u.leaf.error_event.error_factor;
break;
case CMD_LEAF_LOG_MESSAGE:
es.channel = cmd->u.leaf.log_message.channel;
es.status = cmd->u.leaf.log_message.data[0];
es.txerr = cmd->u.leaf.log_message.data[2];
es.rxerr = cmd->u.leaf.log_message.data[3];
es.leaf.error_factor = cmd->u.leaf.log_message.data[1];
break;
case CMD_CHIP_STATE_EVENT:
es.channel = cmd->u.leaf.chip_state_event.channel;
es.status = cmd->u.leaf.chip_state_event.status;
es.txerr = cmd->u.leaf.chip_state_event.tx_errors_count;
es.rxerr = cmd->u.leaf.chip_state_event.rx_errors_count;
es.leaf.error_factor = 0;
break;
default:
dev_err(&dev->intf->dev, "Invalid cmd id (%d)\n", cmd->id);
return;
}
kvaser_usb_leaf_rx_error(dev, &es);
}
static void kvaser_usb_leaf_rx_can_err(const struct kvaser_usb_net_priv *priv,
const struct kvaser_cmd *cmd)
{
if (cmd->u.rx_can_header.flag & (MSG_FLAG_ERROR_FRAME |
MSG_FLAG_NERR)) {
struct net_device_stats *stats = &priv->netdev->stats;
netdev_err(priv->netdev, "Unknown error (flags: 0x%02x)\n",
cmd->u.rx_can_header.flag);
stats->rx_errors++;
return;
}
if (cmd->u.rx_can_header.flag & MSG_FLAG_OVERRUN)
kvaser_usb_can_rx_over_error(priv->netdev);
}
static void kvaser_usb_leaf_rx_can_msg(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct kvaser_usb_net_priv *priv;
struct can_frame *cf;
struct sk_buff *skb;
struct net_device_stats *stats;
u8 channel = cmd->u.rx_can_header.channel;
const u8 *rx_data = NULL; /* GCC */
if (channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", channel);
return;
}
priv = dev->nets[channel];
stats = &priv->netdev->stats;
if ((cmd->u.rx_can_header.flag & MSG_FLAG_ERROR_FRAME) &&
(dev->card_data.leaf.family == KVASER_LEAF &&
cmd->id == CMD_LEAF_LOG_MESSAGE)) {
kvaser_usb_leaf_leaf_rx_error(dev, cmd);
return;
} else if (cmd->u.rx_can_header.flag & (MSG_FLAG_ERROR_FRAME |
MSG_FLAG_NERR |
MSG_FLAG_OVERRUN)) {
kvaser_usb_leaf_rx_can_err(priv, cmd);
return;
} else if (cmd->u.rx_can_header.flag & ~MSG_FLAG_REMOTE_FRAME) {
netdev_warn(priv->netdev,
"Unhandled frame (flags: 0x%02x)\n",
cmd->u.rx_can_header.flag);
return;
}
switch (dev->card_data.leaf.family) {
case KVASER_LEAF:
rx_data = cmd->u.leaf.rx_can.data;
break;
case KVASER_USBCAN:
rx_data = cmd->u.usbcan.rx_can.data;
break;
}
skb = alloc_can_skb(priv->netdev, &cf);
if (!skb) {
stats->rx_dropped++;
return;
}
if (dev->card_data.leaf.family == KVASER_LEAF && cmd->id ==
CMD_LEAF_LOG_MESSAGE) {
cf->can_id = le32_to_cpu(cmd->u.leaf.log_message.id);
if (cf->can_id & KVASER_EXTENDED_FRAME)
cf->can_id &= CAN_EFF_MASK | CAN_EFF_FLAG;
else
cf->can_id &= CAN_SFF_MASK;
cf->can_dlc = get_can_dlc(cmd->u.leaf.log_message.dlc);
if (cmd->u.leaf.log_message.flags & MSG_FLAG_REMOTE_FRAME)
cf->can_id |= CAN_RTR_FLAG;
else
memcpy(cf->data, &cmd->u.leaf.log_message.data,
cf->can_dlc);
} else {
cf->can_id = ((rx_data[0] & 0x1f) << 6) | (rx_data[1] & 0x3f);
if (cmd->id == CMD_RX_EXT_MESSAGE) {
cf->can_id <<= 18;
cf->can_id |= ((rx_data[2] & 0x0f) << 14) |
((rx_data[3] & 0xff) << 6) |
(rx_data[4] & 0x3f);
cf->can_id |= CAN_EFF_FLAG;
}
cf->can_dlc = get_can_dlc(rx_data[5]);
if (cmd->u.rx_can_header.flag & MSG_FLAG_REMOTE_FRAME)
cf->can_id |= CAN_RTR_FLAG;
else
memcpy(cf->data, &rx_data[6], cf->can_dlc);
}
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_rx(skb);
}
static void kvaser_usb_leaf_start_chip_reply(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct kvaser_usb_net_priv *priv;
u8 channel = cmd->u.simple.channel;
if (channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", channel);
return;
}
priv = dev->nets[channel];
if (completion_done(&priv->start_comp) &&
netif_queue_stopped(priv->netdev)) {
netif_wake_queue(priv->netdev);
} else {
netif_start_queue(priv->netdev);
complete(&priv->start_comp);
}
}
static void kvaser_usb_leaf_stop_chip_reply(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
struct kvaser_usb_net_priv *priv;
u8 channel = cmd->u.simple.channel;
if (channel >= dev->nchannels) {
dev_err(&dev->intf->dev,
"Invalid channel number (%d)\n", channel);
return;
}
priv = dev->nets[channel];
complete(&priv->stop_comp);
}
static void kvaser_usb_leaf_handle_command(const struct kvaser_usb *dev,
const struct kvaser_cmd *cmd)
{
switch (cmd->id) {
case CMD_START_CHIP_REPLY:
kvaser_usb_leaf_start_chip_reply(dev, cmd);
break;
case CMD_STOP_CHIP_REPLY:
kvaser_usb_leaf_stop_chip_reply(dev, cmd);
break;
case CMD_RX_STD_MESSAGE:
case CMD_RX_EXT_MESSAGE:
kvaser_usb_leaf_rx_can_msg(dev, cmd);
break;
case CMD_LEAF_LOG_MESSAGE:
if (dev->card_data.leaf.family != KVASER_LEAF)
goto warn;
kvaser_usb_leaf_rx_can_msg(dev, cmd);
break;
case CMD_CHIP_STATE_EVENT:
case CMD_CAN_ERROR_EVENT:
if (dev->card_data.leaf.family == KVASER_LEAF)
kvaser_usb_leaf_leaf_rx_error(dev, cmd);
else
kvaser_usb_leaf_usbcan_rx_error(dev, cmd);
break;
case CMD_TX_ACKNOWLEDGE:
kvaser_usb_leaf_tx_acknowledge(dev, cmd);
break;
/* Ignored commands */
case CMD_USBCAN_CLOCK_OVERFLOW_EVENT:
if (dev->card_data.leaf.family != KVASER_USBCAN)
goto warn;
break;
case CMD_FLUSH_QUEUE_REPLY:
if (dev->card_data.leaf.family != KVASER_LEAF)
goto warn;
break;
default:
warn: dev_warn(&dev->intf->dev, "Unhandled command (%d)\n", cmd->id);
break;
}
}
static void kvaser_usb_leaf_read_bulk_callback(struct kvaser_usb *dev,
void *buf, int len)
{
struct kvaser_cmd *cmd;
int pos = 0;
while (pos <= len - CMD_HEADER_LEN) {
cmd = buf + pos;
/* The Kvaser firmware can only read and write commands that
* does not cross the USB's endpoint wMaxPacketSize boundary.
* If a follow-up command crosses such boundary, firmware puts
* a placeholder zero-length command in its place then aligns
* the real command to the next max packet size.
*
* Handle such cases or we're going to miss a significant
* number of events in case of a heavy rx load on the bus.
*/
if (cmd->len == 0) {
pos = round_up(pos, le16_to_cpu
(dev->bulk_in->wMaxPacketSize));
continue;
}
if (pos + cmd->len > len) {
dev_err_ratelimited(&dev->intf->dev, "Format error\n");
break;
}
kvaser_usb_leaf_handle_command(dev, cmd);
pos += cmd->len;
}
}
static int kvaser_usb_leaf_set_opt_mode(const struct kvaser_usb_net_priv *priv)
{
struct kvaser_cmd *cmd;
int rc;
cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd)
return -ENOMEM;
cmd->id = CMD_SET_CTRL_MODE;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_ctrl_mode);
cmd->u.ctrl_mode.tid = 0xff;
cmd->u.ctrl_mode.channel = priv->channel;
if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
cmd->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_SILENT;
else
cmd->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_NORMAL;
rc = kvaser_usb_send_cmd(priv->dev, cmd, cmd->len);
kfree(cmd);
return rc;
}
static int kvaser_usb_leaf_start_chip(struct kvaser_usb_net_priv *priv)
{
int err;
init_completion(&priv->start_comp);
err = kvaser_usb_leaf_send_simple_cmd(priv->dev, CMD_START_CHIP,
priv->channel);
if (err)
return err;
if (!wait_for_completion_timeout(&priv->start_comp,
msecs_to_jiffies(KVASER_USB_TIMEOUT)))
return -ETIMEDOUT;
return 0;
}
static int kvaser_usb_leaf_stop_chip(struct kvaser_usb_net_priv *priv)
{
int err;
init_completion(&priv->stop_comp);
err = kvaser_usb_leaf_send_simple_cmd(priv->dev, CMD_STOP_CHIP,
priv->channel);
if (err)
return err;
if (!wait_for_completion_timeout(&priv->stop_comp,
msecs_to_jiffies(KVASER_USB_TIMEOUT)))
return -ETIMEDOUT;
return 0;
}
static int kvaser_usb_leaf_reset_chip(struct kvaser_usb *dev, int channel)
{
return kvaser_usb_leaf_send_simple_cmd(dev, CMD_RESET_CHIP, channel);
}
static int kvaser_usb_leaf_flush_queue(struct kvaser_usb_net_priv *priv)
{
struct kvaser_cmd *cmd;
int rc;
cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd)
return -ENOMEM;
cmd->id = CMD_FLUSH_QUEUE;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_flush_queue);
cmd->u.flush_queue.channel = priv->channel;
cmd->u.flush_queue.flags = 0x00;
rc = kvaser_usb_send_cmd(priv->dev, cmd, cmd->len);
kfree(cmd);
return rc;
}
static int kvaser_usb_leaf_init_card(struct kvaser_usb *dev)
{
struct kvaser_usb_dev_card_data *card_data = &dev->card_data;
dev->cfg = &kvaser_usb_leaf_dev_cfg;
card_data->ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
return 0;
}
static const struct can_bittiming_const kvaser_usb_leaf_bittiming_const = {
.name = "kvaser_usb",
.tseg1_min = KVASER_USB_TSEG1_MIN,
.tseg1_max = KVASER_USB_TSEG1_MAX,
.tseg2_min = KVASER_USB_TSEG2_MIN,
.tseg2_max = KVASER_USB_TSEG2_MAX,
.sjw_max = KVASER_USB_SJW_MAX,
.brp_min = KVASER_USB_BRP_MIN,
.brp_max = KVASER_USB_BRP_MAX,
.brp_inc = KVASER_USB_BRP_INC,
};
static int kvaser_usb_leaf_set_bittiming(struct net_device *netdev)
{
struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
struct can_bittiming *bt = &priv->can.bittiming;
struct kvaser_usb *dev = priv->dev;
struct kvaser_cmd *cmd;
int rc;
cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd)
return -ENOMEM;
cmd->id = CMD_SET_BUS_PARAMS;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_busparams);
cmd->u.busparams.channel = priv->channel;
cmd->u.busparams.tid = 0xff;
cmd->u.busparams.bitrate = cpu_to_le32(bt->bitrate);
cmd->u.busparams.sjw = bt->sjw;
cmd->u.busparams.tseg1 = bt->prop_seg + bt->phase_seg1;
cmd->u.busparams.tseg2 = bt->phase_seg2;
if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
cmd->u.busparams.no_samp = 3;
else
cmd->u.busparams.no_samp = 1;
rc = kvaser_usb_send_cmd(dev, cmd, cmd->len);
kfree(cmd);
return rc;
}
static int kvaser_usb_leaf_set_mode(struct net_device *netdev,
enum can_mode mode)
{
struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
int err;
switch (mode) {
case CAN_MODE_START:
err = kvaser_usb_leaf_simple_cmd_async(priv, CMD_START_CHIP);
if (err)
return err;
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int kvaser_usb_leaf_get_berr_counter(const struct net_device *netdev,
struct can_berr_counter *bec)
{
struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
*bec = priv->bec;
return 0;
}
static int kvaser_usb_leaf_setup_endpoints(struct kvaser_usb *dev)
{
const struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
iface_desc = &dev->intf->altsetting[0];
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (!dev->bulk_in && usb_endpoint_is_bulk_in(endpoint))
dev->bulk_in = endpoint;
if (!dev->bulk_out && usb_endpoint_is_bulk_out(endpoint))
dev->bulk_out = endpoint;
/* use first bulk endpoint for in and out */
if (dev->bulk_in && dev->bulk_out)
return 0;
}
return -ENODEV;
}
const struct kvaser_usb_dev_ops kvaser_usb_leaf_dev_ops = {
.dev_set_mode = kvaser_usb_leaf_set_mode,
.dev_set_bittiming = kvaser_usb_leaf_set_bittiming,
.dev_set_data_bittiming = NULL,
.dev_get_berr_counter = kvaser_usb_leaf_get_berr_counter,
.dev_setup_endpoints = kvaser_usb_leaf_setup_endpoints,
.dev_init_card = kvaser_usb_leaf_init_card,
.dev_get_software_info = kvaser_usb_leaf_get_software_info,
.dev_get_software_details = NULL,
.dev_get_card_info = kvaser_usb_leaf_get_card_info,
.dev_get_capabilities = NULL,
.dev_set_opt_mode = kvaser_usb_leaf_set_opt_mode,
.dev_start_chip = kvaser_usb_leaf_start_chip,
.dev_stop_chip = kvaser_usb_leaf_stop_chip,
.dev_reset_chip = kvaser_usb_leaf_reset_chip,
.dev_flush_queue = kvaser_usb_leaf_flush_queue,
.dev_read_bulk_callback = kvaser_usb_leaf_read_bulk_callback,
.dev_frame_to_cmd = kvaser_usb_leaf_frame_to_cmd,
};
static const struct kvaser_usb_dev_cfg kvaser_usb_leaf_dev_cfg = {
.clock = {
.freq = CAN_USB_CLOCK,
},
.timestamp_freq = 1,
.bittiming_const = &kvaser_usb_leaf_bittiming_const,
};
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_1331_0 |
crossvul-cpp_data_good_5759_0 | #include <linux/fs.h>
#include "headers.h"
/***************************************************************
* Function - bcm_char_open()
*
* Description - This is the "open" entry point for the character
* driver.
*
* Parameters - inode: Pointer to the Inode structure of char device
* filp : File pointer of the char device
*
* Returns - Zero(Success)
****************************************************************/
static int bcm_char_open(struct inode *inode, struct file *filp)
{
struct bcm_mini_adapter *Adapter = NULL;
struct bcm_tarang_data *pTarang = NULL;
Adapter = GET_BCM_ADAPTER(gblpnetdev);
pTarang = kzalloc(sizeof(struct bcm_tarang_data), GFP_KERNEL);
if (!pTarang)
return -ENOMEM;
pTarang->Adapter = Adapter;
pTarang->RxCntrlMsgBitMask = 0xFFFFFFFF & ~(1 << 0xB);
down(&Adapter->RxAppControlQueuelock);
pTarang->next = Adapter->pTarangs;
Adapter->pTarangs = pTarang;
up(&Adapter->RxAppControlQueuelock);
/* Store the Adapter structure */
filp->private_data = pTarang;
/* Start Queuing the control response Packets */
atomic_inc(&Adapter->ApplicationRunning);
nonseekable_open(inode, filp);
return 0;
}
static int bcm_char_release(struct inode *inode, struct file *filp)
{
struct bcm_tarang_data *pTarang, *tmp, *ptmp;
struct bcm_mini_adapter *Adapter = NULL;
struct sk_buff *pkt, *npkt;
pTarang = (struct bcm_tarang_data *)filp->private_data;
if (pTarang == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"ptarang is null\n");
return 0;
}
Adapter = pTarang->Adapter;
down(&Adapter->RxAppControlQueuelock);
tmp = Adapter->pTarangs;
for (ptmp = NULL; tmp; ptmp = tmp, tmp = tmp->next) {
if (tmp == pTarang)
break;
}
if (tmp) {
if (!ptmp)
Adapter->pTarangs = tmp->next;
else
ptmp->next = tmp->next;
} else {
up(&Adapter->RxAppControlQueuelock);
return 0;
}
pkt = pTarang->RxAppControlHead;
while (pkt) {
npkt = pkt->next;
kfree_skb(pkt);
pkt = npkt;
}
up(&Adapter->RxAppControlQueuelock);
/* Stop Queuing the control response Packets */
atomic_dec(&Adapter->ApplicationRunning);
kfree(pTarang);
/* remove this filp from the asynchronously notified filp's */
filp->private_data = NULL;
return 0;
}
static ssize_t bcm_char_read(struct file *filp, char __user *buf, size_t size,
loff_t *f_pos)
{
struct bcm_tarang_data *pTarang = filp->private_data;
struct bcm_mini_adapter *Adapter = pTarang->Adapter;
struct sk_buff *Packet = NULL;
ssize_t PktLen = 0;
int wait_ret_val = 0;
unsigned long ret = 0;
wait_ret_val = wait_event_interruptible(Adapter->process_read_wait_queue,
(pTarang->RxAppControlHead ||
Adapter->device_removed));
if ((wait_ret_val == -ERESTARTSYS)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Exiting as i've been asked to exit!!!\n");
return wait_ret_val;
}
if (Adapter->device_removed) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Device Removed... Killing the Apps...\n");
return -ENODEV;
}
if (FALSE == Adapter->fw_download_done)
return -EACCES;
down(&Adapter->RxAppControlQueuelock);
if (pTarang->RxAppControlHead) {
Packet = pTarang->RxAppControlHead;
DEQUEUEPACKET(pTarang->RxAppControlHead,
pTarang->RxAppControlTail);
pTarang->AppCtrlQueueLen--;
}
up(&Adapter->RxAppControlQueuelock);
if (Packet) {
PktLen = Packet->len;
ret = copy_to_user(buf, Packet->data,
min_t(size_t, PktLen, size));
if (ret) {
dev_kfree_skb(Packet);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Returning from copy to user failure\n");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Read %zd Bytes From Adapter packet = %p by process %d!\n",
PktLen, Packet, current->pid);
dev_kfree_skb(Packet);
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "<\n");
return PktLen;
}
static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg)
{
struct bcm_tarang_data *pTarang = filp->private_data;
void __user *argp = (void __user *)arg;
struct bcm_mini_adapter *Adapter = pTarang->Adapter;
INT Status = STATUS_FAILURE;
int timeout = 0;
struct bcm_ioctl_buffer IoBuffer;
int bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX", cmd, arg);
if (_IOC_TYPE(cmd) != BCM_IOCTL)
return -EFAULT;
if (_IOC_DIR(cmd) & _IOC_READ)
Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd));
else if (_IOC_DIR(cmd) & _IOC_WRITE)
Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd));
else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE))
Status = STATUS_SUCCESS;
if (Status)
return -EFAULT;
if (Adapter->device_removed)
return -EFAULT;
if (FALSE == Adapter->fw_download_done) {
switch (cmd) {
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ:
case IOCTL_BCM_GPIO_SET_REQUEST:
case IOCTL_BCM_GPIO_STATUS_REQUEST:
return -EACCES;
default:
break;
}
}
Status = vendorextnIoctl(Adapter, cmd, arg);
if (Status != CONTINUE_COMMON_PATH)
return Status;
switch (cmd) {
/* Rdms for Swin Idle... */
case IOCTL_BCM_REGISTER_READ_PRIVATE: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff;
UINT Bufflen;
u16 temp_value;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
Bufflen = IoBuffer.OutputLength;
temp_value = 4 - (Bufflen % 4);
Bufflen += temp_value % 4;
temp_buff = kmalloc(Bufflen, GFP_KERNEL);
if (!temp_buff)
return -ENOMEM;
bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register,
(PUINT)temp_buff, Bufflen);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE_PRIVATE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_REGISTER_READ:
case IOCTL_BCM_EEPROM_REGISTER_READ: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff = NULL;
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Rdms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sRdmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Done On invalid Address : %x Access Denied.\n",
(int)sRdmBuffer.Register);
kfree(temp_buff);
return -EINVAL;
}
uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK;
bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE:
case IOCTL_BCM_EEPROM_REGISTER_WRITE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Wrms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sWrmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)sWrmBuffer.Register);
return -EINVAL;
}
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sWrmBuffer.Length);
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_GPIO_SET_REQUEST: {
UCHAR ucResetValue[4];
UINT value = 0;
UINT uiBit = 0;
UINT uiOperation = 0;
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
return -EACCES;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
uiOperation = gpio_info.uiGpioValue;
value = (1<<uiBit);
if (IsReqGpioIsLedInNVM(Adapter, value) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to LED !!!", value);
Status = -EINVAL;
break;
}
/* Set - setting 1 */
if (uiOperation) {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to set the %dth GPIO\n", uiBit);
break;
}
} else {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to clear the %dth GPIO\n", uiBit);
break;
}
}
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"GPIO_MODE_REGISTER read failed");
break;
} else {
Status = STATUS_SUCCESS;
}
/* Set the gpio mode register to output */
*(UINT *)ucResetValue |= (1<<uiBit);
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER,
(PUINT)ucResetValue, sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO to output Mode\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to put GPIO in Output Mode\n");
break;
}
}
break;
case BCM_LED_THREAD_STATE_CHANGE_REQ: {
struct bcm_user_thread_req threadReq = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "User made LED thread InActive");
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
Status = -EACCES;
break;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(threadReq))
return -EINVAL;
if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
/* if LED thread is running(Actively or Inactively) set it state to make inactive */
if (Adapter->LEDInfo.led_thread_running) {
if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Activating thread req");
Adapter->DriverState = LED_THREAD_ACTIVE;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DeActivating Thread req.....");
Adapter->DriverState = LED_THREAD_INACTIVE;
}
/* signal thread. */
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
break;
case IOCTL_BCM_GPIO_STATUS_REQUEST: {
ULONG uiBit = 0;
UCHAR ucRead[4];
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EACCES;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
/* Set the gpio output register */
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER,
(PUINT)ucRead, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Failed\n");
return Status;
} else {
Status = STATUS_SUCCESS;
}
}
break;
case IOCTL_BCM_GPIO_MULTI_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX];
struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info;
memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info));
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_info))
return -EINVAL;
if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
/* Set the gpio output register */
if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) &
(pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) {
/* Set 1's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
pgpio_multi_info[WIMAX_IDX].uiGPIOValue;
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG,
(PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_SET_REG Failed.");
return Status;
}
/* Clear to 0's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
(~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue)));
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.");
return Status;
}
}
if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) {
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM to GPIO_PIN_STATE_REGISTER Failed.");
return Status;
} else {
Status = STATUS_SUCCESS;
}
pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue &
pgpio_multi_info[WIMAX_IDX].uiGPIOMask);
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_BCM_GPIO_MODE_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX];
struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_mode))
return -EINVAL;
if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Read of GPIO_MODE_REGISTER failed");
return Status;
} else {
Status = STATUS_SUCCESS;
}
/* Validating the request */
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) {
/* write all OUT's (1's) */
*(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* write all IN's (0's) */
*(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* Currently implemented return the modes of all GPIO's
* else needs to bit AND with mask
*/
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"WRM to GPIO_MODE_REGISTER Done");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"WRM to GPIO_MODE_REGISTER Failed");
Status = -EFAULT;
break;
}
} else {
/* if uiGPIOMask is 0 then return mode register configuration */
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ: {
PVOID pvBuffer = NULL;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(struct bcm_link_request))
return -EINVAL;
if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
down(&Adapter->LowPowerModeSync);
Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue,
!Adapter->bPreparingForLowPowerMode,
(1 * HZ));
if (Status == -ERESTARTSYS)
goto cntrlEnd;
if (Adapter->bPreparingForLowPowerMode) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Preparing Idle Mode is still True - Hence Rejecting control message\n");
Status = STATUS_FAILURE;
goto cntrlEnd;
}
Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer);
cntrlEnd:
up(&Adapter->LowPowerModeSync);
kfree(pvBuffer);
break;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_START: {
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (down_trylock(&Adapter->fw_download_sema))
return -EBUSY;
Adapter->bBinDownloaded = FALSE;
Adapter->fw_download_process_pid = current->pid;
Adapter->bCfgDownloaded = FALSE;
Adapter->fw_download_done = FALSE;
netif_carrier_off(Adapter->dev);
netif_stop_queue(Adapter->dev);
Status = reset_card_proc(Adapter);
if (Status) {
pr_err(PFX "%s: reset_card_proc Failed!\n", Adapter->dev->name);
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
mdelay(10);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD: {
struct bcm_firmware_info *psFwInfo = NULL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (!down_trylock(&Adapter->fw_download_sema)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Invalid way to download buffer. Use Start and then call this!!!\n");
up(&Adapter->fw_download_sema);
Status = -EINVAL;
return Status;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
up(&Adapter->fw_download_sema);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length for FW DLD is : %lx\n", IoBuffer.InputLength);
if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL);
if (!psFwInfo) {
up(&Adapter->fw_download_sema);
return -ENOMEM;
}
if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) {
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
return -EFAULT;
}
if (!psFwInfo->pvMappedFirmwareAddress ||
(psFwInfo->u32FirmwareLength == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Something else is wrong %lu\n",
psFwInfo->u32FirmwareLength);
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
Status = -EINVAL;
return Status;
}
Status = bcm_ioctl_fw_download(Adapter, psFwInfo);
if (Status != STATUS_SUCCESS) {
if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Configuration File Upload Failed\n");
else
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Firmware File Upload Failed\n");
/* up(&Adapter->fw_download_sema); */
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = DRIVER_INIT;
Adapter->LEDInfo.bLedInitDone = FALSE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
if (Status != STATUS_SUCCESS)
up(&Adapter->fw_download_sema);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "IOCTL: Firmware File Uploaded\n");
kfree(psFwInfo);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: {
if (!down_trylock(&Adapter->fw_download_sema)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"FW download blocked as EEPROM Read/Write is in progress\n");
up(&Adapter->fw_download_sema);
return -EACCES;
}
Adapter->bBinDownloaded = TRUE;
Adapter->bCfgDownloaded = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->downloadDDR = 0;
/* setting the Mips to Run */
Status = run_card_proc(Adapter);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Firm Download Failed\n");
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG,
DBG_LVL_ALL, "Firm Download Over...\n");
}
mdelay(10);
/* Wait for MailBox Interrupt */
if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter))
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Unable to send interrupt...\n");
timeout = 5*HZ;
Adapter->waiting_to_fw_download_done = FALSE;
wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue,
Adapter->waiting_to_fw_download_done, timeout);
Adapter->fw_download_process_pid = INVALID_PID;
Adapter->fw_download_done = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->PrevNumRecvDescs = 0;
atomic_set(&Adapter->cntrlpktCnt, 0);
Adapter->LinkUpStatus = 0;
Adapter->LinkStatus = 0;
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = FW_DOWNLOAD_DONE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
if (!timeout)
Status = -ENODEV;
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BE_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_RTPS_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_CHIP_RESET: {
INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock);
if (NVMAccess) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, " IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
down(&Adapter->RxAppControlQueuelock);
Status = reset_card_proc(Adapter);
flushAllAppQ();
up(&Adapter->RxAppControlQueuelock);
up(&Adapter->NVMRdmWrmLock);
ResetCounters(Adapter);
break;
}
case IOCTL_QOS_THRESHOLD: {
USHORT uiLoopIndex;
Status = 0;
for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) {
if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold,
(unsigned long __user *)arg)) {
Status = -EFAULT;
break;
}
}
break;
}
case IOCTL_DUMP_PACKET_INFO:
DumpPackInfo(Adapter);
DumpPhsRules(&Adapter->stBCMPhsContext);
Status = STATUS_SUCCESS;
break;
case IOCTL_GET_PACK_INFO:
if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_SWITCH_TRANSFER_MODE: {
UINT uiData = 0;
if (copy_from_user(&uiData, argp, sizeof(UINT)))
return -EFAULT;
if (uiData) {
/* Allow All Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\n");
Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE;
} else {
/* Allow IP only Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\n");
Adapter->TransferMode = IP_PACKET_ONLY_MODE;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_DRIVER_VERSION: {
ulong len;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1);
if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_CURRENT_STATUS: {
struct bcm_link_state link_state;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user failed..\n");
return -EFAULT;
}
if (IoBuffer.OutputLength != sizeof(link_state)) {
Status = -EINVAL;
break;
}
memset(&link_state, 0, sizeof(link_state));
link_state.bIdleMode = Adapter->IdleMode;
link_state.bShutdownMode = Adapter->bShutStatus;
link_state.ucLinkStatus = Adapter->LinkStatus;
if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy_to_user Failed..\n");
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_SET_MAC_TRACING: {
UINT tracing_flag;
/* copy ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if (tracing_flag)
Adapter->pTarangs->MacTracingEnabled = TRUE;
else
Adapter->pTarangs->MacTracingEnabled = FALSE;
break;
}
case IOCTL_BCM_GET_DSX_INDICATION: {
ULONG ulSFId = 0;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Mismatch req: %lx needed is =0x%zx!!!",
IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt));
return -EINVAL;
}
if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Get DSX Data SF ID is =%lx\n", ulSFId);
get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer);
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_GET_HOST_MIBS: {
PVOID temp_buff;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length Check failed %lu %zd\n",
IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs));
return -EINVAL;
}
/* FIXME: HOST_STATS are too big for kmalloc (122048)! */
temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
Status = ProcessGetHostMibs(Adapter, temp_buff);
GetDroppedAppCntrlPktMibs(temp_buff, pTarang);
if (Status != STATUS_FAILURE)
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) {
kfree(temp_buff);
return -EFAULT;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE:
if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) {
Adapter->usIdleModePattern = ABORT_IDLE_MODE;
Adapter->bWakeUpDevice = TRUE;
wake_up(&Adapter->process_rx_cntrlpkt);
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_BULK_WRM: {
struct bcm_bulk_wrm_buffer *pBulkBuffer;
UINT uiTempVar = 0;
PCHAR pvBuffer = NULL;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle/Shutdown Mode, Blocking Wrms\n");
Status = -EACCES;
break;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(ULONG) * 2)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer;
if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 ||
((ULONG)pBulkBuffer->Register & 0x3)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)pBulkBuffer->Register);
kfree(pvBuffer);
Status = -EINVAL;
break;
}
uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
kfree(pvBuffer);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
Status = -EFAULT;
break;
}
if (pBulkBuffer->SwapEndian == FALSE)
Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
else
Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
if (Status != STATUS_SUCCESS)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Failed\n");
kfree(pvBuffer);
break;
}
case IOCTL_BCM_GET_NVM_SIZE:
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT)))
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_CAL_INIT: {
UINT uiSectorSize = 0 ;
if (Adapter->eNVMType == NVM_FLASH) {
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize,
sizeof(UINT)))
return -EFAULT;
} else {
if (IsFlash2x(Adapter)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT)))
return -EFAULT;
} else {
if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is in Idle/Shutdown Mode\n");
return -EACCES;
}
Adapter->uiSectorSize = uiSectorSize;
BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize);
}
}
Status = STATUS_SUCCESS;
} else {
Status = STATUS_FAILURE;
}
}
break;
case IOCTL_BCM_SET_DEBUG:
#ifdef DEBUG
{
struct bcm_user_debug_state sUserDebugState;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "In SET_DEBUG ioctl\n");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state)))
return -EFAULT;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x ",
sUserDebugState.OnOff, sUserDebugState.Type);
/* sUserDebugState.Subtype <<= 1; */
sUserDebugState.Subtype = 1 << sUserDebugState.Subtype;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "actual Subtype=0x%x\n", sUserDebugState.Subtype);
/* Update new 'DebugState' in the Adapter */
Adapter->stDebugState.type |= sUserDebugState.Type;
/* Subtype: A bitmap of 32 bits for Subtype per Type.
* Valid indexes in 'subtype' array: 1,2,4,8
* corresponding to valid Type values. Hence we can use the 'Type' field
* as the index value, ignoring the array entries 0,3,5,6,7 !
*/
if (sUserDebugState.OnOff)
Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype;
else
Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype;
BCM_SHOW_DEBUG_BITMAP(Adapter);
}
#endif
break;
case IOCTL_BCM_NVM_READ:
case IOCTL_BCM_NVM_WRITE: {
struct bcm_nvm_readwrite stNVMReadWrite;
PUCHAR pReadData = NULL;
ULONG ulDSDMagicNumInUsrBuff = 0;
struct timeval tv0, tv1;
memset(&tv0, 0, sizeof(struct timeval));
memset(&tv1, 0, sizeof(struct timeval));
if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\n");
return -EFAULT;
}
if (IsFlash2x(Adapter)) {
if ((Adapter->eActiveDSD != DSD0) &&
(Adapter->eActiveDSD != DSD1) &&
(Adapter->eActiveDSD != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "No DSD is active..hence NVM Command is blocked");
return STATUS_FAILURE;
}
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&stNVMReadWrite,
(IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer,
sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
/*
* Deny the access if the offset crosses the cal area limit.
*/
if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize)
return STATUS_FAILURE;
if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) {
/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allow access beyond NVM Size: 0x%x 0x%x\n", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */
return STATUS_FAILURE;
}
pReadData = memdup_user(stNVMReadWrite.pBuffer,
stNVMReadWrite.uiNumBytes);
if (IS_ERR(pReadData))
return PTR_ERR(pReadData);
do_gettimeofday(&tv0);
if (IOCTL_BCM_NVM_READ == cmd) {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes);
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) {
kfree(pReadData);
return -EFAULT;
}
} else {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Adapter->bHeaderChangeAllowed = TRUE;
if (IsFlash2x(Adapter)) {
/*
* New Requirement:-
* DSD section updation will be allowed in two case:-
* 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull
* 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is
* corrupted then user space program first modify the DSD header with valid DSD sig so
* that this as well as further write may be worthwhile.
*
* This restriction has been put assuming that if DSD sig is corrupted, DSD
* data won't be considered valid.
*/
Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD);
if (Status != STATUS_SUCCESS) {
if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) ||
(stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE));
if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
}
}
Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify);
if (IsFlash2x(Adapter))
BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD);
Adapter->bHeaderChangeAllowed = FALSE;
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
}
do_gettimeofday(&tv1);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " timetaken by Write/read :%ld msec\n", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000);
kfree(pReadData);
return STATUS_SUCCESS;
}
case IOCTL_BCM_FLASH2X_SECTION_READ: {
struct bcm_flash2x_readwrite sFlash2xRead = {0};
PUCHAR pReadBuff = NULL ;
UINT NOB = 0;
UINT BuffSize = 0;
UINT ReadBytes = 0;
UINT ReadOffset = 0;
void __user *OutPutBuff;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_READ Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xRead.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%x", sFlash2xRead.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xRead.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xRead.bVerify);
/* This was internal to driver for raw read. now it has ben exposed to user space app. */
if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE)
return STATUS_FAILURE;
NOB = sFlash2xRead.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB;
ReadOffset = sFlash2xRead.offset ;
OutPutBuff = IoBuffer.OutputBuffer;
pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
return -ENOMEM;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EACCES;
}
while (NOB) {
if (NOB > Adapter->uiSectorSize)
ReadBytes = Adapter->uiSectorSize;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes ;
}
}
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
}
break;
case IOCTL_BCM_FLASH2X_SECTION_WRITE: {
struct bcm_flash2x_readwrite sFlash2xWrite = {0};
PUCHAR pWriteBuff;
void __user *InputAddr;
UINT NOB = 0;
UINT BuffSize = 0;
UINT WriteOffset = 0;
UINT WriteBytes = 0;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_WRITE Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xWrite.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%d", sFlash2xWrite.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xWrite.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xWrite.bVerify);
if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Only VSA write is allowed");
return -EINVAL;
}
if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE)
return STATUS_FAILURE;
InputAddr = sFlash2xWrite.pDataBuff;
WriteOffset = sFlash2xWrite.offset;
NOB = sFlash2xWrite.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB ;
pWriteBuff = kmalloc(BuffSize, GFP_KERNEL);
if (pWriteBuff == NULL)
return -ENOMEM;
/* extracting the remainder of the given offset. */
WriteBytes = Adapter->uiSectorSize;
if (WriteOffset % Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize);
if (NOB < WriteBytes)
WriteBytes = NOB;
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EACCES;
}
BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section);
do {
Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to user failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EFAULT;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes);
/* Writing the data from Flash 2.x */
Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
NOB = NOB - WriteBytes;
if (NOB) {
WriteOffset = WriteOffset + WriteBytes;
InputAddr = InputAddr + WriteBytes;
if (NOB > Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize;
else
WriteBytes = NOB;
}
} while (NOB > 0);
BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
}
break;
case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: {
struct bcm_flash2x_bitmap *psFlash2xBitMap;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap))
return -EINVAL;
psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL);
if (psFlash2xBitMap == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory is not available");
return -ENOMEM;
}
/* Reading the Flash Sectio Bit map */
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(psFlash2xBitMap);
return -EACCES;
}
BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap);
up(&Adapter->NVMRdmWrmLock);
if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) {
kfree(psFlash2xBitMap);
return -EFAULT;
}
kfree(psFlash2xBitMap);
}
break;
case IOCTL_BCM_SET_ACTIVE_SECTION: {
enum bcm_flash2x_section_val eFlash2xSectionVal = 0;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SET_ACTIVE_SECTION Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal);
if (Status)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed to make it's priority Highest. Status %d", Status);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: {
/* Right Now we are taking care of only DSD */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called");
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_COPY_SECTION: {
struct bcm_flash2x_copy_section sCopySectStrut = {0};
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_COPY_SECTION Called");
Adapter->bAllDSDWriteAllow = FALSE;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed Status :%d", Status);
return -EFAULT;
}
Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of Copy_Section_Struct failed with Status :%d", Status);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source SEction :%x", sCopySectStrut.SrcSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Destination SEction :%x", sCopySectStrut.DstSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "offset :%x", sCopySectStrut.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "NOB :%x", sCopySectStrut.numOfBytes);
if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Source Section<%x> does not exixt in Flash ", sCopySectStrut.SrcSection);
return -EINVAL;
}
if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Destinatio Section<%x> does not exixt in Flash ", sCopySectStrut.DstSection);
return -EINVAL;
}
if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source and Destination section should be different");
return -EINVAL;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) {
if (IsNonCDLessDevice(Adapter)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is Non-CDLess hence won't have ISO !!");
Status = -EINVAL;
} else if (sCopySectStrut.numOfBytes == 0) {
Status = BcmCopyISO(Adapter, sCopySectStrut);
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Partial Copy of ISO section is not Allowed..");
Status = STATUS_FAILURE;
}
up(&Adapter->NVMRdmWrmLock);
return Status;
}
Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection,
sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_GET_FLASH_CS_INFO: {
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " IOCTL_BCM_GET_FLASH_CS_INFO Called");
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Connected device does not have flash");
Status = -EINVAL;
break;
}
if (IsFlash2x(Adapter) == TRUE) {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info)))
return -EFAULT;
} else {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info)))
return -EFAULT;
}
}
break;
case IOCTL_BCM_SELECT_DSD: {
UINT SectOfset = 0;
enum bcm_flash2x_section_val eFlash2xSectionVal;
eFlash2xSectionVal = NO_SECTION_VAL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SELECT_DSD Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read Section :%d", eFlash2xSectionVal);
if ((eFlash2xSectionVal != DSD0) &&
(eFlash2xSectionVal != DSD1) &&
(eFlash2xSectionVal != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Passed section<%x> is not DSD section", eFlash2xSectionVal);
return STATUS_FAILURE;
}
SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal);
if (SectOfset == INVALID_OFFSET) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Provided Section val <%d> does not exixt in Flash 2.x", eFlash2xSectionVal);
return -EINVAL;
}
Adapter->bAllDSDWriteAllow = TRUE;
Adapter->ulFlashCalStart = SectOfset;
Adapter->eActiveDSD = eFlash2xSectionVal;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_NVM_RAW_READ: {
struct bcm_nvm_readwrite stNVMRead;
INT NOB ;
INT BuffSize ;
INT ReadOffset = 0;
UINT ReadBytes = 0 ;
PUCHAR pReadBuff;
void __user *OutPutBuff;
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "NVM TYPE is not Flash");
return -EINVAL;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user 1 failed\n");
return -EFAULT;
}
if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
NOB = stNVMRead.uiNumBytes;
/* In Raw-Read max Buff size : 64MB */
if (NOB > DEFAULT_BUFF_SIZE)
BuffSize = DEFAULT_BUFF_SIZE;
else
BuffSize = NOB;
ReadOffset = stNVMRead.uiOffset;
OutPutBuff = stNVMRead.pBuffer;
pReadBuff = kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
Status = -ENOMEM;
break;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
kfree(pReadBuff);
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Adapter->bFlashRawRead = TRUE;
while (NOB) {
if (NOB > DEFAULT_BUFF_SIZE)
ReadBytes = DEFAULT_BUFF_SIZE;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes;
}
}
Adapter->bFlashRawRead = FALSE;
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
break;
}
case IOCTL_BCM_CNTRLMSG_MASK: {
ULONG RxCntrlMsgBitMask = 0;
/* Copy Ioctl Buffer structure */
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of Ioctl buffer is failed from user space");
return -EFAULT;
}
if (IoBuffer.InputLength != sizeof(unsigned long)) {
Status = -EINVAL;
break;
}
Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of control bit mask failed from user space");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\n Got user defined cntrl msg bit mask :%lx", RxCntrlMsgBitMask);
pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask;
}
break;
case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: {
struct bcm_driver_info DevInfo;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\n");
memset(&DevInfo, 0, sizeof(DevInfo));
DevInfo.MaxRDMBufferSize = BUFFER_4K;
DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START;
DevInfo.u32RxAlignmentCorrection = 0;
DevInfo.u32NVMType = Adapter->eNVMType;
DevInfo.u32InterfaceType = BCM_USB;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(DevInfo))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo)))
return -EFAULT;
}
break;
case IOCTL_BCM_TIME_SINCE_NET_ENTRY: {
struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_TIME_SINCE_NET_ENTRY called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed))
return -EINVAL;
stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry;
if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed)))
return -EFAULT;
}
break;
case IOCTL_CLOSE_NOTIFICATION:
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_CLOSE_NOTIFICATION");
break;
default:
pr_info(DRV_NAME ": unknown ioctl cmd=%#x\n", cmd);
Status = STATUS_FAILURE;
break;
}
return Status;
}
static const struct file_operations bcm_fops = {
.owner = THIS_MODULE,
.open = bcm_char_open,
.release = bcm_char_release,
.read = bcm_char_read,
.unlocked_ioctl = bcm_char_ioctl,
.llseek = no_llseek,
};
int register_control_device_interface(struct bcm_mini_adapter *Adapter)
{
if (Adapter->major > 0)
return Adapter->major;
Adapter->major = register_chrdev(0, DEV_NAME, &bcm_fops);
if (Adapter->major < 0) {
pr_err(DRV_NAME ": could not created character device\n");
return Adapter->major;
}
Adapter->pstCreatedClassDevice = device_create(bcm_class, NULL,
MKDEV(Adapter->major, 0),
Adapter, DEV_NAME);
if (IS_ERR(Adapter->pstCreatedClassDevice)) {
pr_err(DRV_NAME ": class device create failed\n");
unregister_chrdev(Adapter->major, DEV_NAME);
return PTR_ERR(Adapter->pstCreatedClassDevice);
}
return 0;
}
void unregister_control_device_interface(struct bcm_mini_adapter *Adapter)
{
if (Adapter->major > 0) {
device_destroy(bcm_class, MKDEV(Adapter->major, 0));
unregister_chrdev(Adapter->major, DEV_NAME);
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5759_0 |
crossvul-cpp_data_good_5340_0 | /* Netfilter messages via netlink socket. Allows for user space
* protocol helpers and general trouble making from userspace.
*
* (C) 2001 by Jay Schulist <jschlst@samba.org>,
* (C) 2002-2005 by Harald Welte <laforge@gnumonks.org>
* (C) 2005,2007 by Pablo Neira Ayuso <pablo@netfilter.org>
*
* Initial netfilter messages via netlink development funded and
* generally made possible by Network Robots, Inc. (www.networkrobots.com)
*
* Further development of this code funded by Astaro AG (http://www.astaro.com)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <asm/uaccess.h>
#include <net/sock.h>
#include <linux/init.h>
#include <net/netlink.h>
#include <linux/netfilter/nfnetlink.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_NETFILTER);
#define nfnl_dereference_protected(id) \
rcu_dereference_protected(table[(id)].subsys, \
lockdep_nfnl_is_held((id)))
static char __initdata nfversion[] = "0.30";
static struct {
struct mutex mutex;
const struct nfnetlink_subsystem __rcu *subsys;
} table[NFNL_SUBSYS_COUNT];
static const int nfnl_group2type[NFNLGRP_MAX+1] = {
[NFNLGRP_CONNTRACK_NEW] = NFNL_SUBSYS_CTNETLINK,
[NFNLGRP_CONNTRACK_UPDATE] = NFNL_SUBSYS_CTNETLINK,
[NFNLGRP_CONNTRACK_DESTROY] = NFNL_SUBSYS_CTNETLINK,
[NFNLGRP_CONNTRACK_EXP_NEW] = NFNL_SUBSYS_CTNETLINK_EXP,
[NFNLGRP_CONNTRACK_EXP_UPDATE] = NFNL_SUBSYS_CTNETLINK_EXP,
[NFNLGRP_CONNTRACK_EXP_DESTROY] = NFNL_SUBSYS_CTNETLINK_EXP,
[NFNLGRP_NFTABLES] = NFNL_SUBSYS_NFTABLES,
[NFNLGRP_ACCT_QUOTA] = NFNL_SUBSYS_ACCT,
[NFNLGRP_NFTRACE] = NFNL_SUBSYS_NFTABLES,
};
void nfnl_lock(__u8 subsys_id)
{
mutex_lock(&table[subsys_id].mutex);
}
EXPORT_SYMBOL_GPL(nfnl_lock);
void nfnl_unlock(__u8 subsys_id)
{
mutex_unlock(&table[subsys_id].mutex);
}
EXPORT_SYMBOL_GPL(nfnl_unlock);
#ifdef CONFIG_PROVE_LOCKING
bool lockdep_nfnl_is_held(u8 subsys_id)
{
return lockdep_is_held(&table[subsys_id].mutex);
}
EXPORT_SYMBOL_GPL(lockdep_nfnl_is_held);
#endif
int nfnetlink_subsys_register(const struct nfnetlink_subsystem *n)
{
nfnl_lock(n->subsys_id);
if (table[n->subsys_id].subsys) {
nfnl_unlock(n->subsys_id);
return -EBUSY;
}
rcu_assign_pointer(table[n->subsys_id].subsys, n);
nfnl_unlock(n->subsys_id);
return 0;
}
EXPORT_SYMBOL_GPL(nfnetlink_subsys_register);
int nfnetlink_subsys_unregister(const struct nfnetlink_subsystem *n)
{
nfnl_lock(n->subsys_id);
table[n->subsys_id].subsys = NULL;
nfnl_unlock(n->subsys_id);
synchronize_rcu();
return 0;
}
EXPORT_SYMBOL_GPL(nfnetlink_subsys_unregister);
static inline const struct nfnetlink_subsystem *nfnetlink_get_subsys(u_int16_t type)
{
u_int8_t subsys_id = NFNL_SUBSYS_ID(type);
if (subsys_id >= NFNL_SUBSYS_COUNT)
return NULL;
return rcu_dereference(table[subsys_id].subsys);
}
static inline const struct nfnl_callback *
nfnetlink_find_client(u_int16_t type, const struct nfnetlink_subsystem *ss)
{
u_int8_t cb_id = NFNL_MSG_TYPE(type);
if (cb_id >= ss->cb_count)
return NULL;
return &ss->cb[cb_id];
}
int nfnetlink_has_listeners(struct net *net, unsigned int group)
{
return netlink_has_listeners(net->nfnl, group);
}
EXPORT_SYMBOL_GPL(nfnetlink_has_listeners);
struct sk_buff *nfnetlink_alloc_skb(struct net *net, unsigned int size,
u32 dst_portid, gfp_t gfp_mask)
{
return netlink_alloc_skb(net->nfnl, size, dst_portid, gfp_mask);
}
EXPORT_SYMBOL_GPL(nfnetlink_alloc_skb);
int nfnetlink_send(struct sk_buff *skb, struct net *net, u32 portid,
unsigned int group, int echo, gfp_t flags)
{
return nlmsg_notify(net->nfnl, skb, portid, group, echo, flags);
}
EXPORT_SYMBOL_GPL(nfnetlink_send);
int nfnetlink_set_err(struct net *net, u32 portid, u32 group, int error)
{
return netlink_set_err(net->nfnl, portid, group, error);
}
EXPORT_SYMBOL_GPL(nfnetlink_set_err);
int nfnetlink_unicast(struct sk_buff *skb, struct net *net, u32 portid,
int flags)
{
return netlink_unicast(net->nfnl, skb, portid, flags);
}
EXPORT_SYMBOL_GPL(nfnetlink_unicast);
/* Process one complete nfnetlink message. */
static int nfnetlink_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
const struct nfnl_callback *nc;
const struct nfnetlink_subsystem *ss;
int type, err;
/* All the messages must at least contain nfgenmsg */
if (nlmsg_len(nlh) < sizeof(struct nfgenmsg))
return 0;
type = nlh->nlmsg_type;
replay:
rcu_read_lock();
ss = nfnetlink_get_subsys(type);
if (!ss) {
#ifdef CONFIG_MODULES
rcu_read_unlock();
request_module("nfnetlink-subsys-%d", NFNL_SUBSYS_ID(type));
rcu_read_lock();
ss = nfnetlink_get_subsys(type);
if (!ss)
#endif
{
rcu_read_unlock();
return -EINVAL;
}
}
nc = nfnetlink_find_client(type, ss);
if (!nc) {
rcu_read_unlock();
return -EINVAL;
}
{
int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type);
struct nlattr *cda[ss->cb[cb_id].attr_count + 1];
struct nlattr *attr = (void *)nlh + min_len;
int attrlen = nlh->nlmsg_len - min_len;
__u8 subsys_id = NFNL_SUBSYS_ID(type);
err = nla_parse(cda, ss->cb[cb_id].attr_count,
attr, attrlen, ss->cb[cb_id].policy);
if (err < 0) {
rcu_read_unlock();
return err;
}
if (nc->call_rcu) {
err = nc->call_rcu(net, net->nfnl, skb, nlh,
(const struct nlattr **)cda);
rcu_read_unlock();
} else {
rcu_read_unlock();
nfnl_lock(subsys_id);
if (nfnl_dereference_protected(subsys_id) != ss ||
nfnetlink_find_client(type, ss) != nc)
err = -EAGAIN;
else if (nc->call)
err = nc->call(net, net->nfnl, skb, nlh,
(const struct nlattr **)cda);
else
err = -EINVAL;
nfnl_unlock(subsys_id);
}
if (err == -EAGAIN)
goto replay;
return err;
}
}
struct nfnl_err {
struct list_head head;
struct nlmsghdr *nlh;
int err;
};
static int nfnl_err_add(struct list_head *list, struct nlmsghdr *nlh, int err)
{
struct nfnl_err *nfnl_err;
nfnl_err = kmalloc(sizeof(struct nfnl_err), GFP_KERNEL);
if (nfnl_err == NULL)
return -ENOMEM;
nfnl_err->nlh = nlh;
nfnl_err->err = err;
list_add_tail(&nfnl_err->head, list);
return 0;
}
static void nfnl_err_del(struct nfnl_err *nfnl_err)
{
list_del(&nfnl_err->head);
kfree(nfnl_err);
}
static void nfnl_err_reset(struct list_head *err_list)
{
struct nfnl_err *nfnl_err, *next;
list_for_each_entry_safe(nfnl_err, next, err_list, head)
nfnl_err_del(nfnl_err);
}
static void nfnl_err_deliver(struct list_head *err_list, struct sk_buff *skb)
{
struct nfnl_err *nfnl_err, *next;
list_for_each_entry_safe(nfnl_err, next, err_list, head) {
netlink_ack(skb, nfnl_err->nlh, nfnl_err->err);
nfnl_err_del(nfnl_err);
}
}
enum {
NFNL_BATCH_FAILURE = (1 << 0),
NFNL_BATCH_DONE = (1 << 1),
NFNL_BATCH_REPLAY = (1 << 2),
};
static void nfnetlink_rcv_batch(struct sk_buff *skb, struct nlmsghdr *nlh,
u_int16_t subsys_id)
{
struct sk_buff *oskb = skb;
struct net *net = sock_net(skb->sk);
const struct nfnetlink_subsystem *ss;
const struct nfnl_callback *nc;
static LIST_HEAD(err_list);
u32 status;
int err;
if (subsys_id >= NFNL_SUBSYS_COUNT)
return netlink_ack(skb, nlh, -EINVAL);
replay:
status = 0;
skb = netlink_skb_clone(oskb, GFP_KERNEL);
if (!skb)
return netlink_ack(oskb, nlh, -ENOMEM);
nfnl_lock(subsys_id);
ss = nfnl_dereference_protected(subsys_id);
if (!ss) {
#ifdef CONFIG_MODULES
nfnl_unlock(subsys_id);
request_module("nfnetlink-subsys-%d", subsys_id);
nfnl_lock(subsys_id);
ss = nfnl_dereference_protected(subsys_id);
if (!ss)
#endif
{
nfnl_unlock(subsys_id);
netlink_ack(oskb, nlh, -EOPNOTSUPP);
return kfree_skb(skb);
}
}
if (!ss->commit || !ss->abort) {
nfnl_unlock(subsys_id);
netlink_ack(oskb, nlh, -EOPNOTSUPP);
return kfree_skb(skb);
}
while (skb->len >= nlmsg_total_size(0)) {
int msglen, type;
nlh = nlmsg_hdr(skb);
err = 0;
if (nlh->nlmsg_len < NLMSG_HDRLEN ||
skb->len < nlh->nlmsg_len ||
nlmsg_len(nlh) < sizeof(struct nfgenmsg)) {
nfnl_err_reset(&err_list);
status |= NFNL_BATCH_FAILURE;
goto done;
}
/* Only requests are handled by the kernel */
if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) {
err = -EINVAL;
goto ack;
}
type = nlh->nlmsg_type;
if (type == NFNL_MSG_BATCH_BEGIN) {
/* Malformed: Batch begin twice */
nfnl_err_reset(&err_list);
status |= NFNL_BATCH_FAILURE;
goto done;
} else if (type == NFNL_MSG_BATCH_END) {
status |= NFNL_BATCH_DONE;
goto done;
} else if (type < NLMSG_MIN_TYPE) {
err = -EINVAL;
goto ack;
}
/* We only accept a batch with messages for the same
* subsystem.
*/
if (NFNL_SUBSYS_ID(type) != subsys_id) {
err = -EINVAL;
goto ack;
}
nc = nfnetlink_find_client(type, ss);
if (!nc) {
err = -EINVAL;
goto ack;
}
{
int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type);
struct nlattr *cda[ss->cb[cb_id].attr_count + 1];
struct nlattr *attr = (void *)nlh + min_len;
int attrlen = nlh->nlmsg_len - min_len;
err = nla_parse(cda, ss->cb[cb_id].attr_count,
attr, attrlen, ss->cb[cb_id].policy);
if (err < 0)
goto ack;
if (nc->call_batch) {
err = nc->call_batch(net, net->nfnl, skb, nlh,
(const struct nlattr **)cda);
}
/* The lock was released to autoload some module, we
* have to abort and start from scratch using the
* original skb.
*/
if (err == -EAGAIN) {
status |= NFNL_BATCH_REPLAY;
goto next;
}
}
ack:
if (nlh->nlmsg_flags & NLM_F_ACK || err) {
/* Errors are delivered once the full batch has been
* processed, this avoids that the same error is
* reported several times when replaying the batch.
*/
if (nfnl_err_add(&err_list, nlh, err) < 0) {
/* We failed to enqueue an error, reset the
* list of errors and send OOM to userspace
* pointing to the batch header.
*/
nfnl_err_reset(&err_list);
netlink_ack(oskb, nlmsg_hdr(oskb), -ENOMEM);
status |= NFNL_BATCH_FAILURE;
goto done;
}
/* We don't stop processing the batch on errors, thus,
* userspace gets all the errors that the batch
* triggers.
*/
if (err)
status |= NFNL_BATCH_FAILURE;
}
next:
msglen = NLMSG_ALIGN(nlh->nlmsg_len);
if (msglen > skb->len)
msglen = skb->len;
skb_pull(skb, msglen);
}
done:
if (status & NFNL_BATCH_REPLAY) {
ss->abort(net, oskb);
nfnl_err_reset(&err_list);
nfnl_unlock(subsys_id);
kfree_skb(skb);
goto replay;
} else if (status == NFNL_BATCH_DONE) {
ss->commit(net, oskb);
} else {
ss->abort(net, oskb);
}
nfnl_err_deliver(&err_list, oskb);
nfnl_unlock(subsys_id);
kfree_skb(skb);
}
static void nfnetlink_rcv(struct sk_buff *skb)
{
struct nlmsghdr *nlh = nlmsg_hdr(skb);
u_int16_t res_id;
int msglen;
if (nlh->nlmsg_len < NLMSG_HDRLEN ||
skb->len < nlh->nlmsg_len)
return;
if (!netlink_net_capable(skb, CAP_NET_ADMIN)) {
netlink_ack(skb, nlh, -EPERM);
return;
}
if (nlh->nlmsg_type == NFNL_MSG_BATCH_BEGIN) {
struct nfgenmsg *nfgenmsg;
msglen = NLMSG_ALIGN(nlh->nlmsg_len);
if (msglen > skb->len)
msglen = skb->len;
if (nlh->nlmsg_len < NLMSG_HDRLEN ||
skb->len < NLMSG_HDRLEN + sizeof(struct nfgenmsg))
return;
nfgenmsg = nlmsg_data(nlh);
skb_pull(skb, msglen);
/* Work around old nft using host byte order */
if (nfgenmsg->res_id == NFNL_SUBSYS_NFTABLES)
res_id = NFNL_SUBSYS_NFTABLES;
else
res_id = ntohs(nfgenmsg->res_id);
nfnetlink_rcv_batch(skb, nlh, res_id);
} else {
netlink_rcv_skb(skb, &nfnetlink_rcv_msg);
}
}
#ifdef CONFIG_MODULES
static int nfnetlink_bind(struct net *net, int group)
{
const struct nfnetlink_subsystem *ss;
int type;
if (group <= NFNLGRP_NONE || group > NFNLGRP_MAX)
return 0;
type = nfnl_group2type[group];
rcu_read_lock();
ss = nfnetlink_get_subsys(type << 8);
rcu_read_unlock();
if (!ss)
request_module("nfnetlink-subsys-%d", type);
return 0;
}
#endif
static int __net_init nfnetlink_net_init(struct net *net)
{
struct sock *nfnl;
struct netlink_kernel_cfg cfg = {
.groups = NFNLGRP_MAX,
.input = nfnetlink_rcv,
#ifdef CONFIG_MODULES
.bind = nfnetlink_bind,
#endif
};
nfnl = netlink_kernel_create(net, NETLINK_NETFILTER, &cfg);
if (!nfnl)
return -ENOMEM;
net->nfnl_stash = nfnl;
rcu_assign_pointer(net->nfnl, nfnl);
return 0;
}
static void __net_exit nfnetlink_net_exit_batch(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
RCU_INIT_POINTER(net->nfnl, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->nfnl_stash);
}
static struct pernet_operations nfnetlink_net_ops = {
.init = nfnetlink_net_init,
.exit_batch = nfnetlink_net_exit_batch,
};
static int __init nfnetlink_init(void)
{
int i;
for (i = NFNLGRP_NONE + 1; i <= NFNLGRP_MAX; i++)
BUG_ON(nfnl_group2type[i] == NFNL_SUBSYS_NONE);
for (i=0; i<NFNL_SUBSYS_COUNT; i++)
mutex_init(&table[i].mutex);
pr_info("Netfilter messages via NETLINK v%s.\n", nfversion);
return register_pernet_subsys(&nfnetlink_net_ops);
}
static void __exit nfnetlink_exit(void)
{
pr_info("Removing netfilter NETLINK layer.\n");
unregister_pernet_subsys(&nfnetlink_net_ops);
}
module_init(nfnetlink_init);
module_exit(nfnetlink_exit);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5340_0 |
crossvul-cpp_data_good_3361_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% image file and returns it. It allocates the memory necessary for the new
% Image structure and returns a pointer to the new image.
%
% The format of the ReadRLEImage method is:
%
% Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,pixel_info_length);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
ValidateColormapValue(image,*p & mask,&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
ValidateColormapValue(image,(size_t) (x*map_length+
(*p & mask)),&index,exception);
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("RLE","RLE","Utah Run length encoded image");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3361_0 |
crossvul-cpp_data_good_1860_0 | #include <linux/types.h>
#include <linux/errno.h>
#include <linux/kmod.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/ratelimit.h>
#undef LDISC_DEBUG_HANGUP
#ifdef LDISC_DEBUG_HANGUP
#define tty_ldisc_debug(tty, f, args...) tty_debug(tty, f, ##args)
#else
#define tty_ldisc_debug(tty, f, args...)
#endif
/* lockdep nested classes for tty->ldisc_sem */
enum {
LDISC_SEM_NORMAL,
LDISC_SEM_OTHER,
};
/*
* This guards the refcounted line discipline lists. The lock
* must be taken with irqs off because there are hangup path
* callers who will do ldisc lookups and cannot sleep.
*/
static DEFINE_RAW_SPINLOCK(tty_ldiscs_lock);
/* Line disc dispatch table */
static struct tty_ldisc_ops *tty_ldiscs[NR_LDISCS];
/**
* tty_register_ldisc - install a line discipline
* @disc: ldisc number
* @new_ldisc: pointer to the ldisc object
*
* Installs a new line discipline into the kernel. The discipline
* is set up as unreferenced and then made available to the kernel
* from this point onwards.
*
* Locking:
* takes tty_ldiscs_lock to guard against ldisc races
*/
int tty_register_ldisc(int disc, struct tty_ldisc_ops *new_ldisc)
{
unsigned long flags;
int ret = 0;
if (disc < N_TTY || disc >= NR_LDISCS)
return -EINVAL;
raw_spin_lock_irqsave(&tty_ldiscs_lock, flags);
tty_ldiscs[disc] = new_ldisc;
new_ldisc->num = disc;
new_ldisc->refcount = 0;
raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_register_ldisc);
/**
* tty_unregister_ldisc - unload a line discipline
* @disc: ldisc number
* @new_ldisc: pointer to the ldisc object
*
* Remove a line discipline from the kernel providing it is not
* currently in use.
*
* Locking:
* takes tty_ldiscs_lock to guard against ldisc races
*/
int tty_unregister_ldisc(int disc)
{
unsigned long flags;
int ret = 0;
if (disc < N_TTY || disc >= NR_LDISCS)
return -EINVAL;
raw_spin_lock_irqsave(&tty_ldiscs_lock, flags);
if (tty_ldiscs[disc]->refcount)
ret = -EBUSY;
else
tty_ldiscs[disc] = NULL;
raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_unregister_ldisc);
static struct tty_ldisc_ops *get_ldops(int disc)
{
unsigned long flags;
struct tty_ldisc_ops *ldops, *ret;
raw_spin_lock_irqsave(&tty_ldiscs_lock, flags);
ret = ERR_PTR(-EINVAL);
ldops = tty_ldiscs[disc];
if (ldops) {
ret = ERR_PTR(-EAGAIN);
if (try_module_get(ldops->owner)) {
ldops->refcount++;
ret = ldops;
}
}
raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags);
return ret;
}
static void put_ldops(struct tty_ldisc_ops *ldops)
{
unsigned long flags;
raw_spin_lock_irqsave(&tty_ldiscs_lock, flags);
ldops->refcount--;
module_put(ldops->owner);
raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags);
}
/**
* tty_ldisc_get - take a reference to an ldisc
* @disc: ldisc number
*
* Takes a reference to a line discipline. Deals with refcounts and
* module locking counts. Returns NULL if the discipline is not available.
* Returns a pointer to the discipline and bumps the ref count if it is
* available
*
* Locking:
* takes tty_ldiscs_lock to guard against ldisc races
*/
static struct tty_ldisc *tty_ldisc_get(struct tty_struct *tty, int disc)
{
struct tty_ldisc *ld;
struct tty_ldisc_ops *ldops;
if (disc < N_TTY || disc >= NR_LDISCS)
return ERR_PTR(-EINVAL);
/*
* Get the ldisc ops - we may need to request them to be loaded
* dynamically and try again.
*/
ldops = get_ldops(disc);
if (IS_ERR(ldops)) {
request_module("tty-ldisc-%d", disc);
ldops = get_ldops(disc);
if (IS_ERR(ldops))
return ERR_CAST(ldops);
}
ld = kmalloc(sizeof(struct tty_ldisc), GFP_KERNEL);
if (ld == NULL) {
put_ldops(ldops);
return ERR_PTR(-ENOMEM);
}
ld->ops = ldops;
ld->tty = tty;
return ld;
}
/**
* tty_ldisc_put - release the ldisc
*
* Complement of tty_ldisc_get().
*/
static void tty_ldisc_put(struct tty_ldisc *ld)
{
if (WARN_ON_ONCE(!ld))
return;
put_ldops(ld->ops);
kfree(ld);
}
static void *tty_ldiscs_seq_start(struct seq_file *m, loff_t *pos)
{
return (*pos < NR_LDISCS) ? pos : NULL;
}
static void *tty_ldiscs_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return (*pos < NR_LDISCS) ? pos : NULL;
}
static void tty_ldiscs_seq_stop(struct seq_file *m, void *v)
{
}
static int tty_ldiscs_seq_show(struct seq_file *m, void *v)
{
int i = *(loff_t *)v;
struct tty_ldisc_ops *ldops;
ldops = get_ldops(i);
if (IS_ERR(ldops))
return 0;
seq_printf(m, "%-10s %2d\n", ldops->name ? ldops->name : "???", i);
put_ldops(ldops);
return 0;
}
static const struct seq_operations tty_ldiscs_seq_ops = {
.start = tty_ldiscs_seq_start,
.next = tty_ldiscs_seq_next,
.stop = tty_ldiscs_seq_stop,
.show = tty_ldiscs_seq_show,
};
static int proc_tty_ldiscs_open(struct inode *inode, struct file *file)
{
return seq_open(file, &tty_ldiscs_seq_ops);
}
const struct file_operations tty_ldiscs_proc_fops = {
.owner = THIS_MODULE,
.open = proc_tty_ldiscs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/**
* tty_ldisc_ref_wait - wait for the tty ldisc
* @tty: tty device
*
* Dereference the line discipline for the terminal and take a
* reference to it. If the line discipline is in flux then
* wait patiently until it changes.
*
* Note: Must not be called from an IRQ/timer context. The caller
* must also be careful not to hold other locks that will deadlock
* against a discipline change, such as an existing ldisc reference
* (which we check for)
*
* Note: only callable from a file_operations routine (which
* guarantees tty->ldisc != NULL when the lock is acquired).
*/
struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty)
{
ldsem_down_read(&tty->ldisc_sem, MAX_SCHEDULE_TIMEOUT);
WARN_ON(!tty->ldisc);
return tty->ldisc;
}
EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait);
/**
* tty_ldisc_ref - get the tty ldisc
* @tty: tty device
*
* Dereference the line discipline for the terminal and take a
* reference to it. If the line discipline is in flux then
* return NULL. Can be called from IRQ and timer functions.
*/
struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty)
{
struct tty_ldisc *ld = NULL;
if (ldsem_down_read_trylock(&tty->ldisc_sem)) {
ld = tty->ldisc;
if (!ld)
ldsem_up_read(&tty->ldisc_sem);
}
return ld;
}
EXPORT_SYMBOL_GPL(tty_ldisc_ref);
/**
* tty_ldisc_deref - free a tty ldisc reference
* @ld: reference to free up
*
* Undoes the effect of tty_ldisc_ref or tty_ldisc_ref_wait. May
* be called in IRQ context.
*/
void tty_ldisc_deref(struct tty_ldisc *ld)
{
ldsem_up_read(&ld->tty->ldisc_sem);
}
EXPORT_SYMBOL_GPL(tty_ldisc_deref);
static inline int __lockfunc
__tty_ldisc_lock(struct tty_struct *tty, unsigned long timeout)
{
return ldsem_down_write(&tty->ldisc_sem, timeout);
}
static inline int __lockfunc
__tty_ldisc_lock_nested(struct tty_struct *tty, unsigned long timeout)
{
return ldsem_down_write_nested(&tty->ldisc_sem,
LDISC_SEM_OTHER, timeout);
}
static inline void __tty_ldisc_unlock(struct tty_struct *tty)
{
ldsem_up_write(&tty->ldisc_sem);
}
static int __lockfunc
tty_ldisc_lock(struct tty_struct *tty, unsigned long timeout)
{
int ret;
ret = __tty_ldisc_lock(tty, timeout);
if (!ret)
return -EBUSY;
set_bit(TTY_LDISC_HALTED, &tty->flags);
return 0;
}
static void tty_ldisc_unlock(struct tty_struct *tty)
{
clear_bit(TTY_LDISC_HALTED, &tty->flags);
__tty_ldisc_unlock(tty);
}
static int __lockfunc
tty_ldisc_lock_pair_timeout(struct tty_struct *tty, struct tty_struct *tty2,
unsigned long timeout)
{
int ret;
if (tty < tty2) {
ret = __tty_ldisc_lock(tty, timeout);
if (ret) {
ret = __tty_ldisc_lock_nested(tty2, timeout);
if (!ret)
__tty_ldisc_unlock(tty);
}
} else {
/* if this is possible, it has lots of implications */
WARN_ON_ONCE(tty == tty2);
if (tty2 && tty != tty2) {
ret = __tty_ldisc_lock(tty2, timeout);
if (ret) {
ret = __tty_ldisc_lock_nested(tty, timeout);
if (!ret)
__tty_ldisc_unlock(tty2);
}
} else
ret = __tty_ldisc_lock(tty, timeout);
}
if (!ret)
return -EBUSY;
set_bit(TTY_LDISC_HALTED, &tty->flags);
if (tty2)
set_bit(TTY_LDISC_HALTED, &tty2->flags);
return 0;
}
static void __lockfunc
tty_ldisc_lock_pair(struct tty_struct *tty, struct tty_struct *tty2)
{
tty_ldisc_lock_pair_timeout(tty, tty2, MAX_SCHEDULE_TIMEOUT);
}
static void __lockfunc tty_ldisc_unlock_pair(struct tty_struct *tty,
struct tty_struct *tty2)
{
__tty_ldisc_unlock(tty);
if (tty2)
__tty_ldisc_unlock(tty2);
}
/**
* tty_ldisc_flush - flush line discipline queue
* @tty: tty
*
* Flush the line discipline queue (if any) and the tty flip buffers
* for this tty.
*/
void tty_ldisc_flush(struct tty_struct *tty)
{
struct tty_ldisc *ld = tty_ldisc_ref(tty);
tty_buffer_flush(tty, ld);
if (ld)
tty_ldisc_deref(ld);
}
EXPORT_SYMBOL_GPL(tty_ldisc_flush);
/**
* tty_set_termios_ldisc - set ldisc field
* @tty: tty structure
* @num: line discipline number
*
* This is probably overkill for real world processors but
* they are not on hot paths so a little discipline won't do
* any harm.
*
* The line discipline-related tty_struct fields are reset to
* prevent the ldisc driver from re-using stale information for
* the new ldisc instance.
*
* Locking: takes termios_rwsem
*/
static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
{
down_write(&tty->termios_rwsem);
tty->termios.c_line = num;
up_write(&tty->termios_rwsem);
tty->disc_data = NULL;
tty->receive_room = 0;
}
/**
* tty_ldisc_open - open a line discipline
* @tty: tty we are opening the ldisc on
* @ld: discipline to open
*
* A helper opening method. Also a convenient debugging and check
* point.
*
* Locking: always called with BTM already held.
*/
static int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
{
WARN_ON(test_and_set_bit(TTY_LDISC_OPEN, &tty->flags));
if (ld->ops->open) {
int ret;
/* BTM here locks versus a hangup event */
ret = ld->ops->open(tty);
if (ret)
clear_bit(TTY_LDISC_OPEN, &tty->flags);
tty_ldisc_debug(tty, "%p: opened\n", tty->ldisc);
return ret;
}
return 0;
}
/**
* tty_ldisc_close - close a line discipline
* @tty: tty we are opening the ldisc on
* @ld: discipline to close
*
* A helper close method. Also a convenient debugging and check
* point.
*/
static void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld)
{
WARN_ON(!test_bit(TTY_LDISC_OPEN, &tty->flags));
clear_bit(TTY_LDISC_OPEN, &tty->flags);
if (ld->ops->close)
ld->ops->close(tty);
tty_ldisc_debug(tty, "%p: closed\n", tty->ldisc);
}
/**
* tty_ldisc_restore - helper for tty ldisc change
* @tty: tty to recover
* @old: previous ldisc
*
* Restore the previous line discipline or N_TTY when a line discipline
* change fails due to an open error
*/
static void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old)
{
struct tty_ldisc *new_ldisc;
int r;
/* There is an outstanding reference here so this is safe */
old = tty_ldisc_get(tty, old->ops->num);
WARN_ON(IS_ERR(old));
tty->ldisc = old;
tty_set_termios_ldisc(tty, old->ops->num);
if (tty_ldisc_open(tty, old) < 0) {
tty_ldisc_put(old);
/* This driver is always present */
new_ldisc = tty_ldisc_get(tty, N_TTY);
if (IS_ERR(new_ldisc))
panic("n_tty: get");
tty->ldisc = new_ldisc;
tty_set_termios_ldisc(tty, N_TTY);
r = tty_ldisc_open(tty, new_ldisc);
if (r < 0)
panic("Couldn't open N_TTY ldisc for "
"%s --- error %d.",
tty_name(tty), r);
}
}
/**
* tty_set_ldisc - set line discipline
* @tty: the terminal to set
* @ldisc: the line discipline
*
* Set the discipline of a tty line. Must be called from a process
* context. The ldisc change logic has to protect itself against any
* overlapping ldisc change (including on the other end of pty pairs),
* the close of one side of a tty/pty pair, and eventually hangup.
*/
int tty_set_ldisc(struct tty_struct *tty, int ldisc)
{
int retval;
struct tty_ldisc *old_ldisc, *new_ldisc;
new_ldisc = tty_ldisc_get(tty, ldisc);
if (IS_ERR(new_ldisc))
return PTR_ERR(new_ldisc);
tty_lock(tty);
retval = tty_ldisc_lock(tty, 5 * HZ);
if (retval)
goto err;
/* Check the no-op case */
if (tty->ldisc->ops->num == ldisc)
goto out;
if (test_bit(TTY_HUPPED, &tty->flags)) {
/* We were raced by hangup */
retval = -EIO;
goto out;
}
old_ldisc = tty->ldisc;
/* Shutdown the old discipline. */
tty_ldisc_close(tty, old_ldisc);
/* Now set up the new line discipline. */
tty->ldisc = new_ldisc;
tty_set_termios_ldisc(tty, ldisc);
retval = tty_ldisc_open(tty, new_ldisc);
if (retval < 0) {
/* Back to the old one or N_TTY if we can't */
tty_ldisc_put(new_ldisc);
tty_ldisc_restore(tty, old_ldisc);
}
if (tty->ldisc->ops->num != old_ldisc->ops->num && tty->ops->set_ldisc) {
down_read(&tty->termios_rwsem);
tty->ops->set_ldisc(tty);
up_read(&tty->termios_rwsem);
}
/* At this point we hold a reference to the new ldisc and a
reference to the old ldisc, or we hold two references to
the old ldisc (if it was restored as part of error cleanup
above). In either case, releasing a single reference from
the old ldisc is correct. */
new_ldisc = old_ldisc;
out:
tty_ldisc_unlock(tty);
/* Restart the work queue in case no characters kick it off. Safe if
already running */
tty_buffer_restart_work(tty->port);
err:
tty_ldisc_put(new_ldisc); /* drop the extra reference */
tty_unlock(tty);
return retval;
}
/**
* tty_reset_termios - reset terminal state
* @tty: tty to reset
*
* Restore a terminal to the driver default state.
*/
static void tty_reset_termios(struct tty_struct *tty)
{
down_write(&tty->termios_rwsem);
tty->termios = tty->driver->init_termios;
tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
up_write(&tty->termios_rwsem);
}
/**
* tty_ldisc_reinit - reinitialise the tty ldisc
* @tty: tty to reinit
* @ldisc: line discipline to reinitialize
*
* Switch the tty to a line discipline and leave the ldisc
* state closed
*/
static int tty_ldisc_reinit(struct tty_struct *tty, int ldisc)
{
struct tty_ldisc *ld = tty_ldisc_get(tty, ldisc);
if (IS_ERR(ld))
return -1;
tty_ldisc_close(tty, tty->ldisc);
tty_ldisc_put(tty->ldisc);
/*
* Switch the line discipline back
*/
tty->ldisc = ld;
tty_set_termios_ldisc(tty, ldisc);
return 0;
}
/**
* tty_ldisc_hangup - hangup ldisc reset
* @tty: tty being hung up
*
* Some tty devices reset their termios when they receive a hangup
* event. In that situation we must also switch back to N_TTY properly
* before we reset the termios data.
*
* Locking: We can take the ldisc mutex as the rest of the code is
* careful to allow for this.
*
* In the pty pair case this occurs in the close() path of the
* tty itself so we must be careful about locking rules.
*/
void tty_ldisc_hangup(struct tty_struct *tty)
{
struct tty_ldisc *ld;
int reset = tty->driver->flags & TTY_DRIVER_RESET_TERMIOS;
int err = 0;
tty_ldisc_debug(tty, "%p: closing\n", tty->ldisc);
ld = tty_ldisc_ref(tty);
if (ld != NULL) {
if (ld->ops->flush_buffer)
ld->ops->flush_buffer(tty);
tty_driver_flush_buffer(tty);
if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
ld->ops->write_wakeup)
ld->ops->write_wakeup(tty);
if (ld->ops->hangup)
ld->ops->hangup(tty);
tty_ldisc_deref(ld);
}
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
wake_up_interruptible_poll(&tty->read_wait, POLLIN);
/*
* Shutdown the current line discipline, and reset it to
* N_TTY if need be.
*
* Avoid racing set_ldisc or tty_ldisc_release
*/
tty_ldisc_lock(tty, MAX_SCHEDULE_TIMEOUT);
if (tty->ldisc) {
/* At this point we have a halted ldisc; we want to close it and
reopen a new ldisc. We could defer the reopen to the next
open but it means auditing a lot of other paths so this is
a FIXME */
if (reset == 0) {
if (!tty_ldisc_reinit(tty, tty->termios.c_line))
err = tty_ldisc_open(tty, tty->ldisc);
else
err = 1;
}
/* If the re-open fails or we reset then go to N_TTY. The
N_TTY open cannot fail */
if (reset || err) {
BUG_ON(tty_ldisc_reinit(tty, N_TTY));
WARN_ON(tty_ldisc_open(tty, tty->ldisc));
}
}
tty_ldisc_unlock(tty);
if (reset)
tty_reset_termios(tty);
tty_ldisc_debug(tty, "%p: re-opened\n", tty->ldisc);
}
/**
* tty_ldisc_setup - open line discipline
* @tty: tty being shut down
* @o_tty: pair tty for pty/tty pairs
*
* Called during the initial open of a tty/pty pair in order to set up the
* line disciplines and bind them to the tty. This has no locking issues
* as the device isn't yet active.
*/
int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty)
{
struct tty_ldisc *ld = tty->ldisc;
int retval;
retval = tty_ldisc_open(tty, ld);
if (retval)
return retval;
if (o_tty) {
retval = tty_ldisc_open(o_tty, o_tty->ldisc);
if (retval) {
tty_ldisc_close(tty, ld);
return retval;
}
}
return 0;
}
static void tty_ldisc_kill(struct tty_struct *tty)
{
/*
* Now kill off the ldisc
*/
tty_ldisc_close(tty, tty->ldisc);
tty_ldisc_put(tty->ldisc);
/* Force an oops if we mess this up */
tty->ldisc = NULL;
/* Ensure the next open requests the N_TTY ldisc */
tty_set_termios_ldisc(tty, N_TTY);
}
/**
* tty_ldisc_release - release line discipline
* @tty: tty being shut down (or one end of pty pair)
*
* Called during the final close of a tty or a pty pair in order to shut
* down the line discpline layer. On exit, each ldisc assigned is N_TTY and
* each ldisc has not been opened.
*/
void tty_ldisc_release(struct tty_struct *tty)
{
struct tty_struct *o_tty = tty->link;
/*
* Shutdown this line discipline. As this is the final close,
* it does not race with the set_ldisc code path.
*/
tty_ldisc_lock_pair(tty, o_tty);
tty_ldisc_kill(tty);
if (o_tty)
tty_ldisc_kill(o_tty);
tty_ldisc_unlock_pair(tty, o_tty);
/* And the memory resources remaining (buffers, termios) will be
disposed of when the kref hits zero */
tty_ldisc_debug(tty, "released\n");
}
/**
* tty_ldisc_init - ldisc setup for new tty
* @tty: tty being allocated
*
* Set up the line discipline objects for a newly allocated tty. Note that
* the tty structure is not completely set up when this call is made.
*/
void tty_ldisc_init(struct tty_struct *tty)
{
struct tty_ldisc *ld = tty_ldisc_get(tty, N_TTY);
if (IS_ERR(ld))
panic("n_tty: init_tty");
tty->ldisc = ld;
}
/**
* tty_ldisc_init - ldisc cleanup for new tty
* @tty: tty that was allocated recently
*
* The tty structure must not becompletely set up (tty_ldisc_setup) when
* this call is made.
*/
void tty_ldisc_deinit(struct tty_struct *tty)
{
tty_ldisc_put(tty->ldisc);
tty->ldisc = NULL;
}
void tty_ldisc_begin(void)
{
/* Setup the default TTY line discipline. */
(void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1860_0 |
crossvul-cpp_data_bad_3829_0 | /*
* Copyright (c) 2007 The University of Aberdeen, Scotland, UK
* Copyright (c) 2005-7 The University of Waikato, Hamilton, New Zealand.
* Copyright (c) 2005-7 Ian McDonald <ian.mcdonald@jandi.co.nz>
*
* An implementation of the DCCP protocol
*
* This code has been developed by the University of Waikato WAND
* research group. For further information please see http://www.wand.net.nz/
*
* This code also uses code from Lulea University, rereleased as GPL by its
* authors:
* Copyright (c) 2003 Nils-Erik Mattsson, Joacim Haggmark, Magnus Erixzon
*
* Changes to meet Linux coding standards, to make it meet latest ccid3 draft
* and to make it work as a loadable module in the DCCP stack written by
* Arnaldo Carvalho de Melo <acme@conectiva.com.br>.
*
* Copyright (c) 2005 Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "../dccp.h"
#include "ccid3.h"
#include <asm/unaligned.h>
#ifdef CONFIG_IP_DCCP_CCID3_DEBUG
static bool ccid3_debug;
#define ccid3_pr_debug(format, a...) DCCP_PR_DEBUG(ccid3_debug, format, ##a)
#else
#define ccid3_pr_debug(format, a...)
#endif
/*
* Transmitter Half-Connection Routines
*/
#ifdef CONFIG_IP_DCCP_CCID3_DEBUG
static const char *ccid3_tx_state_name(enum ccid3_hc_tx_states state)
{
static const char *const ccid3_state_names[] = {
[TFRC_SSTATE_NO_SENT] = "NO_SENT",
[TFRC_SSTATE_NO_FBACK] = "NO_FBACK",
[TFRC_SSTATE_FBACK] = "FBACK",
};
return ccid3_state_names[state];
}
#endif
static void ccid3_hc_tx_set_state(struct sock *sk,
enum ccid3_hc_tx_states state)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
enum ccid3_hc_tx_states oldstate = hc->tx_state;
ccid3_pr_debug("%s(%p) %-8.8s -> %s\n",
dccp_role(sk), sk, ccid3_tx_state_name(oldstate),
ccid3_tx_state_name(state));
WARN_ON(state == oldstate);
hc->tx_state = state;
}
/*
* Compute the initial sending rate X_init in the manner of RFC 3390:
*
* X_init = min(4 * s, max(2 * s, 4380 bytes)) / RTT
*
* Note that RFC 3390 uses MSS, RFC 4342 refers to RFC 3390, and rfc3448bis
* (rev-02) clarifies the use of RFC 3390 with regard to the above formula.
* For consistency with other parts of the code, X_init is scaled by 2^6.
*/
static inline u64 rfc3390_initial_rate(struct sock *sk)
{
const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
const __u32 w_init = clamp_t(__u32, 4380U, 2 * hc->tx_s, 4 * hc->tx_s);
return scaled_div(w_init << 6, hc->tx_rtt);
}
/**
* ccid3_update_send_interval - Calculate new t_ipi = s / X_inst
* This respects the granularity of X_inst (64 * bytes/second).
*/
static void ccid3_update_send_interval(struct ccid3_hc_tx_sock *hc)
{
hc->tx_t_ipi = scaled_div32(((u64)hc->tx_s) << 6, hc->tx_x);
DCCP_BUG_ON(hc->tx_t_ipi == 0);
ccid3_pr_debug("t_ipi=%u, s=%u, X=%u\n", hc->tx_t_ipi,
hc->tx_s, (unsigned int)(hc->tx_x >> 6));
}
static u32 ccid3_hc_tx_idle_rtt(struct ccid3_hc_tx_sock *hc, ktime_t now)
{
u32 delta = ktime_us_delta(now, hc->tx_t_last_win_count);
return delta / hc->tx_rtt;
}
/**
* ccid3_hc_tx_update_x - Update allowed sending rate X
* @stamp: most recent time if available - can be left NULL.
*
* This function tracks draft rfc3448bis, check there for latest details.
*
* Note: X and X_recv are both stored in units of 64 * bytes/second, to support
* fine-grained resolution of sending rates. This requires scaling by 2^6
* throughout the code. Only X_calc is unscaled (in bytes/second).
*
*/
static void ccid3_hc_tx_update_x(struct sock *sk, ktime_t *stamp)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
__u64 min_rate = 2 * hc->tx_x_recv;
const __u64 old_x = hc->tx_x;
ktime_t now = stamp ? *stamp : ktime_get_real();
/*
* Handle IDLE periods: do not reduce below RFC3390 initial sending rate
* when idling [RFC 4342, 5.1]. Definition of idling is from rfc3448bis:
* a sender is idle if it has not sent anything over a 2-RTT-period.
* For consistency with X and X_recv, min_rate is also scaled by 2^6.
*/
if (ccid3_hc_tx_idle_rtt(hc, now) >= 2) {
min_rate = rfc3390_initial_rate(sk);
min_rate = max(min_rate, 2 * hc->tx_x_recv);
}
if (hc->tx_p > 0) {
hc->tx_x = min(((__u64)hc->tx_x_calc) << 6, min_rate);
hc->tx_x = max(hc->tx_x, (((__u64)hc->tx_s) << 6) / TFRC_T_MBI);
} else if (ktime_us_delta(now, hc->tx_t_ld) - (s64)hc->tx_rtt >= 0) {
hc->tx_x = min(2 * hc->tx_x, min_rate);
hc->tx_x = max(hc->tx_x,
scaled_div(((__u64)hc->tx_s) << 6, hc->tx_rtt));
hc->tx_t_ld = now;
}
if (hc->tx_x != old_x) {
ccid3_pr_debug("X_prev=%u, X_now=%u, X_calc=%u, "
"X_recv=%u\n", (unsigned int)(old_x >> 6),
(unsigned int)(hc->tx_x >> 6), hc->tx_x_calc,
(unsigned int)(hc->tx_x_recv >> 6));
ccid3_update_send_interval(hc);
}
}
/**
* ccid3_hc_tx_update_s - Track the mean packet size `s'
* @len: DCCP packet payload size in bytes
*
* cf. RFC 4342, 5.3 and RFC 3448, 4.1
*/
static inline void ccid3_hc_tx_update_s(struct ccid3_hc_tx_sock *hc, int len)
{
const u16 old_s = hc->tx_s;
hc->tx_s = tfrc_ewma(hc->tx_s, len, 9);
if (hc->tx_s != old_s)
ccid3_update_send_interval(hc);
}
/*
* Update Window Counter using the algorithm from [RFC 4342, 8.1].
* As elsewhere, RTT > 0 is assumed by using dccp_sample_rtt().
*/
static inline void ccid3_hc_tx_update_win_count(struct ccid3_hc_tx_sock *hc,
ktime_t now)
{
u32 delta = ktime_us_delta(now, hc->tx_t_last_win_count),
quarter_rtts = (4 * delta) / hc->tx_rtt;
if (quarter_rtts > 0) {
hc->tx_t_last_win_count = now;
hc->tx_last_win_count += min(quarter_rtts, 5U);
hc->tx_last_win_count &= 0xF; /* mod 16 */
}
}
static void ccid3_hc_tx_no_feedback_timer(unsigned long data)
{
struct sock *sk = (struct sock *)data;
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
unsigned long t_nfb = USEC_PER_SEC / 5;
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
/* Try again later. */
/* XXX: set some sensible MIB */
goto restart_timer;
}
ccid3_pr_debug("%s(%p, state=%s) - entry\n", dccp_role(sk), sk,
ccid3_tx_state_name(hc->tx_state));
/* Ignore and do not restart after leaving the established state */
if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN))
goto out;
/* Reset feedback state to "no feedback received" */
if (hc->tx_state == TFRC_SSTATE_FBACK)
ccid3_hc_tx_set_state(sk, TFRC_SSTATE_NO_FBACK);
/*
* Determine new allowed sending rate X as per draft rfc3448bis-00, 4.4
* RTO is 0 if and only if no feedback has been received yet.
*/
if (hc->tx_t_rto == 0 || hc->tx_p == 0) {
/* halve send rate directly */
hc->tx_x = max(hc->tx_x / 2,
(((__u64)hc->tx_s) << 6) / TFRC_T_MBI);
ccid3_update_send_interval(hc);
} else {
/*
* Modify the cached value of X_recv
*
* If (X_calc > 2 * X_recv)
* X_recv = max(X_recv / 2, s / (2 * t_mbi));
* Else
* X_recv = X_calc / 4;
*
* Note that X_recv is scaled by 2^6 while X_calc is not
*/
if (hc->tx_x_calc > (hc->tx_x_recv >> 5))
hc->tx_x_recv =
max(hc->tx_x_recv / 2,
(((__u64)hc->tx_s) << 6) / (2*TFRC_T_MBI));
else {
hc->tx_x_recv = hc->tx_x_calc;
hc->tx_x_recv <<= 4;
}
ccid3_hc_tx_update_x(sk, NULL);
}
ccid3_pr_debug("Reduced X to %llu/64 bytes/sec\n",
(unsigned long long)hc->tx_x);
/*
* Set new timeout for the nofeedback timer.
* See comments in packet_recv() regarding the value of t_RTO.
*/
if (unlikely(hc->tx_t_rto == 0)) /* no feedback received yet */
t_nfb = TFRC_INITIAL_TIMEOUT;
else
t_nfb = max(hc->tx_t_rto, 2 * hc->tx_t_ipi);
restart_timer:
sk_reset_timer(sk, &hc->tx_no_feedback_timer,
jiffies + usecs_to_jiffies(t_nfb));
out:
bh_unlock_sock(sk);
sock_put(sk);
}
/**
* ccid3_hc_tx_send_packet - Delay-based dequeueing of TX packets
* @skb: next packet candidate to send on @sk
*
* This function uses the convention of ccid_packet_dequeue_eval() and
* returns a millisecond-delay value between 0 and t_mbi = 64000 msec.
*/
static int ccid3_hc_tx_send_packet(struct sock *sk, struct sk_buff *skb)
{
struct dccp_sock *dp = dccp_sk(sk);
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
ktime_t now = ktime_get_real();
s64 delay;
/*
* This function is called only for Data and DataAck packets. Sending
* zero-sized Data(Ack)s is theoretically possible, but for congestion
* control this case is pathological - ignore it.
*/
if (unlikely(skb->len == 0))
return -EBADMSG;
if (hc->tx_state == TFRC_SSTATE_NO_SENT) {
sk_reset_timer(sk, &hc->tx_no_feedback_timer, (jiffies +
usecs_to_jiffies(TFRC_INITIAL_TIMEOUT)));
hc->tx_last_win_count = 0;
hc->tx_t_last_win_count = now;
/* Set t_0 for initial packet */
hc->tx_t_nom = now;
hc->tx_s = skb->len;
/*
* Use initial RTT sample when available: recommended by erratum
* to RFC 4342. This implements the initialisation procedure of
* draft rfc3448bis, section 4.2. Remember, X is scaled by 2^6.
*/
if (dp->dccps_syn_rtt) {
ccid3_pr_debug("SYN RTT = %uus\n", dp->dccps_syn_rtt);
hc->tx_rtt = dp->dccps_syn_rtt;
hc->tx_x = rfc3390_initial_rate(sk);
hc->tx_t_ld = now;
} else {
/*
* Sender does not have RTT sample:
* - set fallback RTT (RFC 4340, 3.4) since a RTT value
* is needed in several parts (e.g. window counter);
* - set sending rate X_pps = 1pps as per RFC 3448, 4.2.
*/
hc->tx_rtt = DCCP_FALLBACK_RTT;
hc->tx_x = hc->tx_s;
hc->tx_x <<= 6;
}
ccid3_update_send_interval(hc);
ccid3_hc_tx_set_state(sk, TFRC_SSTATE_NO_FBACK);
} else {
delay = ktime_us_delta(hc->tx_t_nom, now);
ccid3_pr_debug("delay=%ld\n", (long)delay);
/*
* Scheduling of packet transmissions (RFC 5348, 8.3)
*
* if (t_now > t_nom - delta)
* // send the packet now
* else
* // send the packet in (t_nom - t_now) milliseconds.
*/
if (delay >= TFRC_T_DELTA)
return (u32)delay / USEC_PER_MSEC;
ccid3_hc_tx_update_win_count(hc, now);
}
/* prepare to send now (add options etc.) */
dp->dccps_hc_tx_insert_options = 1;
DCCP_SKB_CB(skb)->dccpd_ccval = hc->tx_last_win_count;
/* set the nominal send time for the next following packet */
hc->tx_t_nom = ktime_add_us(hc->tx_t_nom, hc->tx_t_ipi);
return CCID_PACKET_SEND_AT_ONCE;
}
static void ccid3_hc_tx_packet_sent(struct sock *sk, unsigned int len)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
ccid3_hc_tx_update_s(hc, len);
if (tfrc_tx_hist_add(&hc->tx_hist, dccp_sk(sk)->dccps_gss))
DCCP_CRIT("packet history - out of memory!");
}
static void ccid3_hc_tx_packet_recv(struct sock *sk, struct sk_buff *skb)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
struct tfrc_tx_hist_entry *acked;
ktime_t now;
unsigned long t_nfb;
u32 r_sample;
/* we are only interested in ACKs */
if (!(DCCP_SKB_CB(skb)->dccpd_type == DCCP_PKT_ACK ||
DCCP_SKB_CB(skb)->dccpd_type == DCCP_PKT_DATAACK))
return;
/*
* Locate the acknowledged packet in the TX history.
*
* Returning "entry not found" here can for instance happen when
* - the host has not sent out anything (e.g. a passive server),
* - the Ack is outdated (packet with higher Ack number was received),
* - it is a bogus Ack (for a packet not sent on this connection).
*/
acked = tfrc_tx_hist_find_entry(hc->tx_hist, dccp_hdr_ack_seq(skb));
if (acked == NULL)
return;
/* For the sake of RTT sampling, ignore/remove all older entries */
tfrc_tx_hist_purge(&acked->next);
/* Update the moving average for the RTT estimate (RFC 3448, 4.3) */
now = ktime_get_real();
r_sample = dccp_sample_rtt(sk, ktime_us_delta(now, acked->stamp));
hc->tx_rtt = tfrc_ewma(hc->tx_rtt, r_sample, 9);
/*
* Update allowed sending rate X as per draft rfc3448bis-00, 4.2/3
*/
if (hc->tx_state == TFRC_SSTATE_NO_FBACK) {
ccid3_hc_tx_set_state(sk, TFRC_SSTATE_FBACK);
if (hc->tx_t_rto == 0) {
/*
* Initial feedback packet: Larger Initial Windows (4.2)
*/
hc->tx_x = rfc3390_initial_rate(sk);
hc->tx_t_ld = now;
ccid3_update_send_interval(hc);
goto done_computing_x;
} else if (hc->tx_p == 0) {
/*
* First feedback after nofeedback timer expiry (4.3)
*/
goto done_computing_x;
}
}
/* Update sending rate (step 4 of [RFC 3448, 4.3]) */
if (hc->tx_p > 0)
hc->tx_x_calc = tfrc_calc_x(hc->tx_s, hc->tx_rtt, hc->tx_p);
ccid3_hc_tx_update_x(sk, &now);
done_computing_x:
ccid3_pr_debug("%s(%p), RTT=%uus (sample=%uus), s=%u, "
"p=%u, X_calc=%u, X_recv=%u, X=%u\n",
dccp_role(sk), sk, hc->tx_rtt, r_sample,
hc->tx_s, hc->tx_p, hc->tx_x_calc,
(unsigned int)(hc->tx_x_recv >> 6),
(unsigned int)(hc->tx_x >> 6));
/* unschedule no feedback timer */
sk_stop_timer(sk, &hc->tx_no_feedback_timer);
/*
* As we have calculated new ipi, delta, t_nom it is possible
* that we now can send a packet, so wake up dccp_wait_for_ccid
*/
sk->sk_write_space(sk);
/*
* Update timeout interval for the nofeedback timer. In order to control
* rate halving on networks with very low RTTs (<= 1 ms), use per-route
* tunable RTAX_RTO_MIN value as the lower bound.
*/
hc->tx_t_rto = max_t(u32, 4 * hc->tx_rtt,
USEC_PER_SEC/HZ * tcp_rto_min(sk));
/*
* Schedule no feedback timer to expire in
* max(t_RTO, 2 * s/X) = max(t_RTO, 2 * t_ipi)
*/
t_nfb = max(hc->tx_t_rto, 2 * hc->tx_t_ipi);
ccid3_pr_debug("%s(%p), Scheduled no feedback timer to "
"expire in %lu jiffies (%luus)\n",
dccp_role(sk), sk, usecs_to_jiffies(t_nfb), t_nfb);
sk_reset_timer(sk, &hc->tx_no_feedback_timer,
jiffies + usecs_to_jiffies(t_nfb));
}
static int ccid3_hc_tx_parse_options(struct sock *sk, u8 packet_type,
u8 option, u8 *optval, u8 optlen)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
__be32 opt_val;
switch (option) {
case TFRC_OPT_RECEIVE_RATE:
case TFRC_OPT_LOSS_EVENT_RATE:
/* Must be ignored on Data packets, cf. RFC 4342 8.3 and 8.5 */
if (packet_type == DCCP_PKT_DATA)
break;
if (unlikely(optlen != 4)) {
DCCP_WARN("%s(%p), invalid len %d for %u\n",
dccp_role(sk), sk, optlen, option);
return -EINVAL;
}
opt_val = ntohl(get_unaligned((__be32 *)optval));
if (option == TFRC_OPT_RECEIVE_RATE) {
/* Receive Rate is kept in units of 64 bytes/second */
hc->tx_x_recv = opt_val;
hc->tx_x_recv <<= 6;
ccid3_pr_debug("%s(%p), RECEIVE_RATE=%u\n",
dccp_role(sk), sk, opt_val);
} else {
/* Update the fixpoint Loss Event Rate fraction */
hc->tx_p = tfrc_invert_loss_event_rate(opt_val);
ccid3_pr_debug("%s(%p), LOSS_EVENT_RATE=%u\n",
dccp_role(sk), sk, opt_val);
}
}
return 0;
}
static int ccid3_hc_tx_init(struct ccid *ccid, struct sock *sk)
{
struct ccid3_hc_tx_sock *hc = ccid_priv(ccid);
hc->tx_state = TFRC_SSTATE_NO_SENT;
hc->tx_hist = NULL;
setup_timer(&hc->tx_no_feedback_timer,
ccid3_hc_tx_no_feedback_timer, (unsigned long)sk);
return 0;
}
static void ccid3_hc_tx_exit(struct sock *sk)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
sk_stop_timer(sk, &hc->tx_no_feedback_timer);
tfrc_tx_hist_purge(&hc->tx_hist);
}
static void ccid3_hc_tx_get_info(struct sock *sk, struct tcp_info *info)
{
info->tcpi_rto = ccid3_hc_tx_sk(sk)->tx_t_rto;
info->tcpi_rtt = ccid3_hc_tx_sk(sk)->tx_rtt;
}
static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
struct tfrc_tx_info tfrc;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_TX_INFO:
if (len < sizeof(tfrc))
return -EINVAL;
tfrc.tfrctx_x = hc->tx_x;
tfrc.tfrctx_x_recv = hc->tx_x_recv;
tfrc.tfrctx_x_calc = hc->tx_x_calc;
tfrc.tfrctx_rtt = hc->tx_rtt;
tfrc.tfrctx_p = hc->tx_p;
tfrc.tfrctx_rto = hc->tx_t_rto;
tfrc.tfrctx_ipi = hc->tx_t_ipi;
len = sizeof(tfrc);
val = &tfrc;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
/*
* Receiver Half-Connection Routines
*/
/* CCID3 feedback types */
enum ccid3_fback_type {
CCID3_FBACK_NONE = 0,
CCID3_FBACK_INITIAL,
CCID3_FBACK_PERIODIC,
CCID3_FBACK_PARAM_CHANGE
};
#ifdef CONFIG_IP_DCCP_CCID3_DEBUG
static const char *ccid3_rx_state_name(enum ccid3_hc_rx_states state)
{
static const char *const ccid3_rx_state_names[] = {
[TFRC_RSTATE_NO_DATA] = "NO_DATA",
[TFRC_RSTATE_DATA] = "DATA",
};
return ccid3_rx_state_names[state];
}
#endif
static void ccid3_hc_rx_set_state(struct sock *sk,
enum ccid3_hc_rx_states state)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
enum ccid3_hc_rx_states oldstate = hc->rx_state;
ccid3_pr_debug("%s(%p) %-8.8s -> %s\n",
dccp_role(sk), sk, ccid3_rx_state_name(oldstate),
ccid3_rx_state_name(state));
WARN_ON(state == oldstate);
hc->rx_state = state;
}
static void ccid3_hc_rx_send_feedback(struct sock *sk,
const struct sk_buff *skb,
enum ccid3_fback_type fbtype)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
ktime_t now = ktime_get_real();
s64 delta = 0;
switch (fbtype) {
case CCID3_FBACK_INITIAL:
hc->rx_x_recv = 0;
hc->rx_pinv = ~0U; /* see RFC 4342, 8.5 */
break;
case CCID3_FBACK_PARAM_CHANGE:
/*
* When parameters change (new loss or p > p_prev), we do not
* have a reliable estimate for R_m of [RFC 3448, 6.2] and so
* need to reuse the previous value of X_recv. However, when
* X_recv was 0 (due to early loss), this would kill X down to
* s/t_mbi (i.e. one packet in 64 seconds).
* To avoid such drastic reduction, we approximate X_recv as
* the number of bytes since last feedback.
* This is a safe fallback, since X is bounded above by X_calc.
*/
if (hc->rx_x_recv > 0)
break;
/* fall through */
case CCID3_FBACK_PERIODIC:
delta = ktime_us_delta(now, hc->rx_tstamp_last_feedback);
if (delta <= 0)
DCCP_BUG("delta (%ld) <= 0", (long)delta);
else
hc->rx_x_recv = scaled_div32(hc->rx_bytes_recv, delta);
break;
default:
return;
}
ccid3_pr_debug("Interval %ldusec, X_recv=%u, 1/p=%u\n", (long)delta,
hc->rx_x_recv, hc->rx_pinv);
hc->rx_tstamp_last_feedback = now;
hc->rx_last_counter = dccp_hdr(skb)->dccph_ccval;
hc->rx_bytes_recv = 0;
dp->dccps_hc_rx_insert_options = 1;
dccp_send_ack(sk);
}
static int ccid3_hc_rx_insert_options(struct sock *sk, struct sk_buff *skb)
{
const struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
__be32 x_recv, pinv;
if (!(sk->sk_state == DCCP_OPEN || sk->sk_state == DCCP_PARTOPEN))
return 0;
if (dccp_packet_without_ack(skb))
return 0;
x_recv = htonl(hc->rx_x_recv);
pinv = htonl(hc->rx_pinv);
if (dccp_insert_option(skb, TFRC_OPT_LOSS_EVENT_RATE,
&pinv, sizeof(pinv)) ||
dccp_insert_option(skb, TFRC_OPT_RECEIVE_RATE,
&x_recv, sizeof(x_recv)))
return -1;
return 0;
}
/**
* ccid3_first_li - Implements [RFC 5348, 6.3.1]
*
* Determine the length of the first loss interval via inverse lookup.
* Assume that X_recv can be computed by the throughput equation
* s
* X_recv = --------
* R * fval
* Find some p such that f(p) = fval; return 1/p (scaled).
*/
static u32 ccid3_first_li(struct sock *sk)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
u32 x_recv, p, delta;
u64 fval;
if (hc->rx_rtt == 0) {
DCCP_WARN("No RTT estimate available, using fallback RTT\n");
hc->rx_rtt = DCCP_FALLBACK_RTT;
}
delta = ktime_to_us(net_timedelta(hc->rx_tstamp_last_feedback));
x_recv = scaled_div32(hc->rx_bytes_recv, delta);
if (x_recv == 0) { /* would also trigger divide-by-zero */
DCCP_WARN("X_recv==0\n");
if (hc->rx_x_recv == 0) {
DCCP_BUG("stored value of X_recv is zero");
return ~0U;
}
x_recv = hc->rx_x_recv;
}
fval = scaled_div(hc->rx_s, hc->rx_rtt);
fval = scaled_div32(fval, x_recv);
p = tfrc_calc_x_reverse_lookup(fval);
ccid3_pr_debug("%s(%p), receive rate=%u bytes/s, implied "
"loss rate=%u\n", dccp_role(sk), sk, x_recv, p);
return p == 0 ? ~0U : scaled_div(1, p);
}
static void ccid3_hc_rx_packet_recv(struct sock *sk, struct sk_buff *skb)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
enum ccid3_fback_type do_feedback = CCID3_FBACK_NONE;
const u64 ndp = dccp_sk(sk)->dccps_options_received.dccpor_ndp;
const bool is_data_packet = dccp_data_packet(skb);
if (unlikely(hc->rx_state == TFRC_RSTATE_NO_DATA)) {
if (is_data_packet) {
const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4;
do_feedback = CCID3_FBACK_INITIAL;
ccid3_hc_rx_set_state(sk, TFRC_RSTATE_DATA);
hc->rx_s = payload;
/*
* Not necessary to update rx_bytes_recv here,
* since X_recv = 0 for the first feedback packet (cf.
* RFC 3448, 6.3) -- gerrit
*/
}
goto update_records;
}
if (tfrc_rx_hist_duplicate(&hc->rx_hist, skb))
return; /* done receiving */
if (is_data_packet) {
const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4;
/*
* Update moving-average of s and the sum of received payload bytes
*/
hc->rx_s = tfrc_ewma(hc->rx_s, payload, 9);
hc->rx_bytes_recv += payload;
}
/*
* Perform loss detection and handle pending losses
*/
if (tfrc_rx_handle_loss(&hc->rx_hist, &hc->rx_li_hist,
skb, ndp, ccid3_first_li, sk)) {
do_feedback = CCID3_FBACK_PARAM_CHANGE;
goto done_receiving;
}
if (tfrc_rx_hist_loss_pending(&hc->rx_hist))
return; /* done receiving */
/*
* Handle data packets: RTT sampling and monitoring p
*/
if (unlikely(!is_data_packet))
goto update_records;
if (!tfrc_lh_is_initialised(&hc->rx_li_hist)) {
const u32 sample = tfrc_rx_hist_sample_rtt(&hc->rx_hist, skb);
/*
* Empty loss history: no loss so far, hence p stays 0.
* Sample RTT values, since an RTT estimate is required for the
* computation of p when the first loss occurs; RFC 3448, 6.3.1.
*/
if (sample != 0)
hc->rx_rtt = tfrc_ewma(hc->rx_rtt, sample, 9);
} else if (tfrc_lh_update_i_mean(&hc->rx_li_hist, skb)) {
/*
* Step (3) of [RFC 3448, 6.1]: Recompute I_mean and, if I_mean
* has decreased (resp. p has increased), send feedback now.
*/
do_feedback = CCID3_FBACK_PARAM_CHANGE;
}
/*
* Check if the periodic once-per-RTT feedback is due; RFC 4342, 10.3
*/
if (SUB16(dccp_hdr(skb)->dccph_ccval, hc->rx_last_counter) > 3)
do_feedback = CCID3_FBACK_PERIODIC;
update_records:
tfrc_rx_hist_add_packet(&hc->rx_hist, skb, ndp);
done_receiving:
if (do_feedback)
ccid3_hc_rx_send_feedback(sk, skb, do_feedback);
}
static int ccid3_hc_rx_init(struct ccid *ccid, struct sock *sk)
{
struct ccid3_hc_rx_sock *hc = ccid_priv(ccid);
hc->rx_state = TFRC_RSTATE_NO_DATA;
tfrc_lh_init(&hc->rx_li_hist);
return tfrc_rx_hist_alloc(&hc->rx_hist);
}
static void ccid3_hc_rx_exit(struct sock *sk)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
tfrc_rx_hist_purge(&hc->rx_hist);
tfrc_lh_cleanup(&hc->rx_li_hist);
}
static void ccid3_hc_rx_get_info(struct sock *sk, struct tcp_info *info)
{
info->tcpi_ca_state = ccid3_hc_rx_sk(sk)->rx_state;
info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
info->tcpi_rcv_rtt = ccid3_hc_rx_sk(sk)->rx_rtt;
}
static int ccid3_hc_rx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
struct tfrc_rx_info rx_info;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_RX_INFO:
if (len < sizeof(rx_info))
return -EINVAL;
rx_info.tfrcrx_x_recv = hc->rx_x_recv;
rx_info.tfrcrx_rtt = hc->rx_rtt;
rx_info.tfrcrx_p = tfrc_invert_loss_event_rate(hc->rx_pinv);
len = sizeof(rx_info);
val = &rx_info;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
struct ccid_operations ccid3_ops = {
.ccid_id = DCCPC_CCID3,
.ccid_name = "TCP-Friendly Rate Control",
.ccid_hc_tx_obj_size = sizeof(struct ccid3_hc_tx_sock),
.ccid_hc_tx_init = ccid3_hc_tx_init,
.ccid_hc_tx_exit = ccid3_hc_tx_exit,
.ccid_hc_tx_send_packet = ccid3_hc_tx_send_packet,
.ccid_hc_tx_packet_sent = ccid3_hc_tx_packet_sent,
.ccid_hc_tx_packet_recv = ccid3_hc_tx_packet_recv,
.ccid_hc_tx_parse_options = ccid3_hc_tx_parse_options,
.ccid_hc_rx_obj_size = sizeof(struct ccid3_hc_rx_sock),
.ccid_hc_rx_init = ccid3_hc_rx_init,
.ccid_hc_rx_exit = ccid3_hc_rx_exit,
.ccid_hc_rx_insert_options = ccid3_hc_rx_insert_options,
.ccid_hc_rx_packet_recv = ccid3_hc_rx_packet_recv,
.ccid_hc_rx_get_info = ccid3_hc_rx_get_info,
.ccid_hc_tx_get_info = ccid3_hc_tx_get_info,
.ccid_hc_rx_getsockopt = ccid3_hc_rx_getsockopt,
.ccid_hc_tx_getsockopt = ccid3_hc_tx_getsockopt,
};
#ifdef CONFIG_IP_DCCP_CCID3_DEBUG
module_param(ccid3_debug, bool, 0644);
MODULE_PARM_DESC(ccid3_debug, "Enable CCID-3 debug messages");
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3829_0 |
crossvul-cpp_data_bad_368_0 | /* linux/drivers/cdrom/cdrom.c
Copyright (c) 1996, 1997 David A. van Leeuwen.
Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org>
Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk>
May be copied or modified under the terms of the GNU General Public
License. See linux/COPYING for more information.
Uniform CD-ROM driver for Linux.
See Documentation/cdrom/cdrom-standard.tex for usage information.
The routines in the file provide a uniform interface between the
software that uses CD-ROMs and the various low-level drivers that
actually talk to the hardware. Suggestions are welcome.
Patches that work are more welcome though. ;-)
To Do List:
----------------------------------
-- Modify sysctl/proc interface. I plan on having one directory per
drive, with entries for outputing general drive information, and sysctl
based tunable parameters such as whether the tray should auto-close for
that drive. Suggestions (or patches) for this welcome!
Revision History
----------------------------------
1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl>
-- Initial version by David A. van Leeuwen. I don't have a detailed
changelog for the 1.x series, David?
2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org>
-- New maintainer! As David A. van Leeuwen has been too busy to actively
maintain and improve this driver, I am now carrying on the torch. If
you have a problem with this driver, please feel free to contact me.
-- Added (rudimentary) sysctl interface. I realize this is really weak
right now, and is _very_ badly implemented. It will be improved...
-- Modified CDROM_DISC_STATUS so that it is now incorporated into
the Uniform CD-ROM driver via the cdrom_count_tracks function.
The cdrom_count_tracks function helps resolve some of the false
assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check
for the correct media type when mounting or playing audio from a CD.
-- Remove the calls to verify_area and only use the copy_from_user and
copy_to_user stuff, since these calls now provide their own memory
checking with the 2.1.x kernels.
-- Major update to return codes so that errors from low-level drivers
are passed on through (thanks to Gerd Knorr for pointing out this
problem).
-- Made it so if a function isn't implemented in a low-level driver,
ENOSYS is now returned instead of EINVAL.
-- Simplified some complex logic so that the source code is easier to read.
-- Other stuff I probably forgot to mention (lots of changes).
2.01 to 2.11 Dec 1997-Jan 1998
-- TO-DO! Write changelogs for 2.01 to 2.12.
2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that
copy_*_user does not return EFAULT on error, but instead returns the number
of bytes not copied. I was returning whatever non-zero stuff came back from
the copy_*_user functions directly, which would result in strange errors.
2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed
of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing
this out and providing a simple fix.
-- Fixed the procfs-unload-module bug with the fill_inode procfs callback.
thanks to Andrea Arcangeli
-- Fixed it so that the /proc entry now also shows up when cdrom is
compiled into the kernel. Before it only worked when loaded as a module.
2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org>
-- Fixed a bug in cdrom_media_changed and handling of reporting that
the media had changed for devices that _don't_ implement media_changed.
Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug.
-- Made a few things more pedanticly correct.
2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk>
-- New maintainers! Erik was too busy to continue the work on the driver,
so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk>
will do their best to follow in his footsteps
2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk>
-- Check if drive is capable of doing what we ask before blindly changing
cdi->options in various ioctl.
-- Added version to proc entry.
2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed an error in open_for_data where we would sometimes not return
the correct error value. Thanks Huba Gaspar <huba@softcell.hu>.
-- Fixed module usage count - usage was based on /proc/sys/dev
instead of /proc/sys/dev/cdrom. This could lead to an oops when other
modules had entries in dev. Feb 02 - real bug was in sysctl.c where
dev would be removed even though it was used. cdrom.c just illuminated
that bug.
2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk>
-- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has
been "rewritten" because capabilities and options aren't in sync. They
should be...
-- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way.
-- Added CDROM_RESET ioctl.
-- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly.
-- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs
from parsing /proc/sys/dev/cdrom/info.
2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk>
-- Check capability mask from low level driver when counting tracks as
per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>.
2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk>
-- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of
CDC_CLOSE_TRAY.
-- proc info didn't mask against capabilities mask.
3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk>
-- Unified audio ioctl handling across CD-ROM drivers. A lot of the
code was duplicated before. Drives that support the generic packet
interface are now being fed packets from here instead.
-- First attempt at adding support for MMC2 commands - for DVD and
CD-R(W) drives. Only the DVD parts are in now - the interface used is
the same as for the audio ioctls.
-- ioctl cleanups. if a drive couldn't play audio, it didn't get
a change to perform device specific ioctls as well.
-- Defined CDROM_CAN(CDC_XXX) for checking the capabilities.
-- Put in sysctl files for autoclose, autoeject, check_media, debug,
and lock.
-- /proc/sys/dev/cdrom/info has been updated to also contain info about
CD-Rx and DVD capabilities.
-- Now default to checking media type.
-- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for
doing this anyway, with the generic_packet addition.
3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk>
-- Fix up the sysctl handling so that the option flags get set
correctly.
-- Fix up ioctl handling so the device specific ones actually get
called :).
3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed volume control on SCSI drives (or others with longer audio
page).
-- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath
<andrewtv@usa.net> for telling me and for having defined the various
DVD structures and ioctls in the first place! He designed the original
DVD patches for ide-cd and while I rearranged and unified them, the
interface is still the same.
3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk>
-- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only
CDROMREADTOCENTRY and CDROMREADTOCHDR are left.
-- Moved the CDROMREADxxx ioctls in here.
-- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls
and exported functions.
-- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands
to now read GPCMD_ for the new generic packet interface. All low level
drivers are updated as well.
-- Various other cleanups.
3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk>
-- Fixed a couple of possible memory leaks (if an operation failed and
we didn't free the buffer before returning the error).
-- Integrated Uniform CD Changer handling from Richard Sharman
<rsharman@pobox.com>.
-- Defined CD_DVD and CD_CHANGER log levels.
-- Fixed the CDROMREADxxx ioctls.
-- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few
drives supported it. We lose the index part, however.
-- Small modifications to accommodate opens of /dev/hdc1, required
for ide-cd to handle multisession discs.
-- Export cdrom_mode_sense and cdrom_mode_select.
-- init_cdrom_command() for setting up a cgc command.
3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk>
-- Changed the interface for CDROM_SEND_PACKET. Before it was virtually
impossible to send the drive data in a sensible way.
-- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and
dvd_read_manufact.
-- Added setup of write mode for packet writing.
-- Fixed CDDA ripping with cdda2wav - accept much larger requests of
number of frames and split the reads in blocks of 8.
3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk>
-- Added support for changing the region of DVD drives.
-- Added sense data to generic command.
3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de>
-- Do same "read header length" trick in cdrom_get_disc_info() as
we do in cdrom_get_track_info() -- some drive don't obey specs and
fail if they can't supply the full Mt Fuji size table.
-- Deleted stuff related to setting up write modes. It has a different
home now.
-- Clear header length in mode_select unconditionally.
-- Removed the register_disk() that was added, not needed here.
3.08 May 1, 2000 - Jens Axboe <axboe@suse.de>
-- Fix direction flag in setup_send_key and setup_report_key. This
gave some SCSI adapters problems.
-- Always return -EROFS for write opens
-- Convert to module_init/module_exit style init and remove some
of the #ifdef MODULE stuff
-- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid,
DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and
dvd_do_auth passed uninitialized data to drive because init_cdrom_command
did not clear a 0 sized buffer.
3.09 May 12, 2000 - Jens Axboe <axboe@suse.de>
-- Fix Video-CD on SCSI drives that don't support READ_CD command. In
that case switch block size and issue plain READ_10 again, then switch
back.
3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de>
-- Fix volume control on CD's - old SCSI-II drives now use their own
code, as doing MODE6 stuff in here is really not my intention.
-- Use READ_DISC_INFO for more reliable end-of-disc.
3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de>
-- Fix bug in getting rpc phase 2 region info.
-- Reinstate "correct" CDROMPLAYTRKIND
3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de>
-- Use quiet bit on packet commands not known to work
3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de>
-- Various fixes and lots of cleanups not listed :-)
-- Locking fixes
-- Mt Rainier support
-- DVD-RAM write open fixes
Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov
<appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units.
Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW
2.4.x patch by Andy Polyakov <appro@fy.chalmers.se>
-------------------------------------------------------------------------*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define REVISION "Revision: 3.20"
#define VERSION "Id: cdrom.c 3.20 2003/12/17"
/* I use an error-log mask to give fine grain control over the type of
messages dumped to the system logs. The available masks include: */
#define CD_NOTHING 0x0
#define CD_WARNING 0x1
#define CD_REG_UNREG 0x2
#define CD_DO_IOCTL 0x4
#define CD_OPEN 0x8
#define CD_CLOSE 0x10
#define CD_COUNT_TRACKS 0x20
#define CD_CHANGER 0x40
#define CD_DVD 0x80
/* Define this to remove _all_ the debugging messages */
/* #define ERRLOGMASK CD_NOTHING */
#define ERRLOGMASK CD_WARNING
/* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */
/* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/major.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/cdrom.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/blkpg.h>
#include <linux/init.h>
#include <linux/fcntl.h>
#include <linux/blkdev.h>
#include <linux/times.h>
#include <linux/uaccess.h>
#include <scsi/scsi_common.h>
#include <scsi/scsi_request.h>
/* used to tell the module to turn on full debugging messages */
static bool debug;
/* default compatibility mode */
static bool autoclose=1;
static bool autoeject;
static bool lockdoor = 1;
/* will we ever get to use this... sigh. */
static bool check_media_type;
/* automatically restart mrw format */
static bool mrw_format_restart = 1;
module_param(debug, bool, 0);
module_param(autoclose, bool, 0);
module_param(autoeject, bool, 0);
module_param(lockdoor, bool, 0);
module_param(check_media_type, bool, 0);
module_param(mrw_format_restart, bool, 0);
static DEFINE_MUTEX(cdrom_mutex);
static const char *mrw_format_status[] = {
"not mrw",
"bgformat inactive",
"bgformat active",
"mrw complete",
};
static const char *mrw_address_space[] = { "DMA", "GAA" };
#if (ERRLOGMASK != CD_NOTHING)
#define cd_dbg(type, fmt, ...) \
do { \
if ((ERRLOGMASK & type) || debug == 1) \
pr_debug(fmt, ##__VA_ARGS__); \
} while (0)
#else
#define cd_dbg(type, fmt, ...) \
do { \
if (0 && (ERRLOGMASK & type) || debug == 1) \
pr_debug(fmt, ##__VA_ARGS__); \
} while (0)
#endif
/* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in
a lot of places. This macro makes the code more clear. */
#define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type))
/*
* Another popular OS uses 7 seconds as the hard timeout for default
* commands, so it is a good choice for us as well.
*/
#define CDROM_DEF_TIMEOUT (7 * HZ)
/* Not-exported routines. */
static void cdrom_sysctl_register(void);
static LIST_HEAD(cdrom_list);
int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
if (cgc->sshdr) {
cgc->sshdr->sense_key = 0x05;
cgc->sshdr->asc = 0x20;
cgc->sshdr->ascq = 0x00;
}
cgc->stat = -EIO;
return -EIO;
}
EXPORT_SYMBOL(cdrom_dummy_generic_packet);
static int cdrom_flush_cache(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_FLUSH_CACHE;
cgc.timeout = 5 * 60 * HZ;
return cdi->ops->generic_packet(cdi, &cgc);
}
/* requires CD R/RW */
static int cdrom_get_disc_info(struct cdrom_device_info *cdi,
disc_information *di)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
int ret, buflen;
/* set up command and get the disc info */
init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_DISC_INFO;
cgc.cmd[8] = cgc.buflen = 2;
cgc.quiet = 1;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* not all drives have the same disc_info length, so requeue
* packet with the length the drive tells us it can supply
*/
buflen = be16_to_cpu(di->disc_information_length) +
sizeof(di->disc_information_length);
if (buflen > sizeof(disc_information))
buflen = sizeof(disc_information);
cgc.cmd[8] = cgc.buflen = buflen;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* return actual fill size */
return buflen;
}
/* This macro makes sure we don't have to check on cdrom_device_ops
* existence in the run-time routines below. Change_capability is a
* hack to have the capability flags defined const, while we can still
* change it here without gcc complaining at every line.
*/
#define ENSURE(call, bits) \
do { \
if (cdo->call == NULL) \
*change_capability &= ~(bits); \
} while (0)
/*
* the first prototypes used 0x2c as the page code for the mrw mode page,
* subsequently this was changed to 0x03. probe the one used by this drive
*/
static int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[16];
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.timeout = HZ;
cgc.quiet = 1;
if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) {
cdi->mrw_mode_page = MRW_MODE_PC;
return 0;
} else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) {
cdi->mrw_mode_page = MRW_MODE_PC_PRE1;
return 0;
}
return 1;
}
static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write)
{
struct packet_command cgc;
struct mrw_feature_desc *mfd;
unsigned char buffer[16];
int ret;
*write = 0;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[3] = CDF_MRW;
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
mfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)];
if (be16_to_cpu(mfd->feature_code) != CDF_MRW)
return 1;
*write = mfd->write;
if ((ret = cdrom_mrw_probe_pc(cdi))) {
*write = 0;
return ret;
}
return 0;
}
static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont)
{
struct packet_command cgc;
unsigned char buffer[12];
int ret;
pr_info("%sstarting format\n", cont ? "Re" : "");
/*
* FmtData bit set (bit 4), format type is 1
*/
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE);
cgc.cmd[0] = GPCMD_FORMAT_UNIT;
cgc.cmd[1] = (1 << 4) | 1;
cgc.timeout = 5 * 60 * HZ;
/*
* 4 byte format list header, 8 byte format list descriptor
*/
buffer[1] = 1 << 1;
buffer[3] = 8;
/*
* nr_blocks field
*/
buffer[4] = 0xff;
buffer[5] = 0xff;
buffer[6] = 0xff;
buffer[7] = 0xff;
buffer[8] = 0x24 << 2;
buffer[11] = cont;
ret = cdi->ops->generic_packet(cdi, &cgc);
if (ret)
pr_info("bgformat failed\n");
return ret;
}
static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed)
{
struct packet_command cgc;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
/*
* Session = 1, Track = 0
*/
cgc.cmd[1] = !!immed;
cgc.cmd[2] = 1 << 1;
cgc.timeout = 5 * 60 * HZ;
return cdi->ops->generic_packet(cdi, &cgc);
}
static int cdrom_mrw_exit(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type))
return 1;
ret = 0;
if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) {
pr_info("issuing MRW background format suspend\n");
ret = cdrom_mrw_bgformat_susp(cdi, 0);
}
if (!ret && cdi->media_written)
ret = cdrom_flush_cache(cdi);
return ret;
}
static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
{
struct packet_command cgc;
struct mode_page_header *mph;
char buffer[16];
int ret, offset, size;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.buffer = buffer;
cgc.buflen = sizeof(buffer);
ret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0);
if (ret)
return ret;
mph = (struct mode_page_header *)buffer;
offset = be16_to_cpu(mph->desc_length);
size = be16_to_cpu(mph->mode_data_length) + 2;
buffer[offset + 3] = space;
cgc.buflen = size;
ret = cdrom_mode_select(cdi, &cgc);
if (ret)
return ret;
pr_info("%s: mrw address space %s selected\n",
cdi->name, mrw_address_space[space]);
return 0;
}
int register_cdrom(struct cdrom_device_info *cdi)
{
static char banner_printed;
const struct cdrom_device_ops *cdo = cdi->ops;
int *change_capability = (int *)&cdo->capability; /* hack */
cd_dbg(CD_OPEN, "entering register_cdrom\n");
if (cdo->open == NULL || cdo->release == NULL)
return -EINVAL;
if (!banner_printed) {
pr_info("Uniform CD-ROM driver " REVISION "\n");
banner_printed = 1;
cdrom_sysctl_register();
}
ENSURE(drive_status, CDC_DRIVE_STATUS);
if (cdo->check_events == NULL && cdo->media_changed == NULL)
*change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC);
ENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY);
ENSURE(lock_door, CDC_LOCK);
ENSURE(select_speed, CDC_SELECT_SPEED);
ENSURE(get_last_session, CDC_MULTI_SESSION);
ENSURE(get_mcn, CDC_MCN);
ENSURE(reset, CDC_RESET);
ENSURE(generic_packet, CDC_GENERIC_PACKET);
cdi->mc_flags = 0;
cdi->options = CDO_USE_FFLAGS;
if (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY))
cdi->options |= (int) CDO_AUTO_CLOSE;
if (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY))
cdi->options |= (int) CDO_AUTO_EJECT;
if (lockdoor == 1)
cdi->options |= (int) CDO_LOCK;
if (check_media_type == 1)
cdi->options |= (int) CDO_CHECK_TYPE;
if (CDROM_CAN(CDC_MRW_W))
cdi->exit = cdrom_mrw_exit;
if (cdi->disk)
cdi->cdda_method = CDDA_BPC_FULL;
else
cdi->cdda_method = CDDA_OLD;
WARN_ON(!cdo->generic_packet);
cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" registered\n", cdi->name);
mutex_lock(&cdrom_mutex);
list_add(&cdi->list, &cdrom_list);
mutex_unlock(&cdrom_mutex);
return 0;
}
#undef ENSURE
void unregister_cdrom(struct cdrom_device_info *cdi)
{
cd_dbg(CD_OPEN, "entering unregister_cdrom\n");
mutex_lock(&cdrom_mutex);
list_del(&cdi->list);
mutex_unlock(&cdrom_mutex);
if (cdi->exit)
cdi->exit(cdi);
cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" unregistered\n", cdi->name);
}
int cdrom_get_media_event(struct cdrom_device_info *cdi,
struct media_event_desc *med)
{
struct packet_command cgc;
unsigned char buffer[8];
struct event_header *eh = (struct event_header *)buffer;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION;
cgc.cmd[1] = 1; /* IMMED */
cgc.cmd[4] = 1 << 4; /* media event */
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if (cdi->ops->generic_packet(cdi, &cgc))
return 1;
if (be16_to_cpu(eh->data_len) < sizeof(*med))
return 1;
if (eh->nea || eh->notification_class != 0x4)
return 1;
memcpy(med, &buffer[sizeof(*eh)], sizeof(*med));
return 0;
}
static int cdrom_get_random_writable(struct cdrom_device_info *cdi,
struct rwrt_feature_desc *rfd)
{
struct packet_command cgc;
char buffer[24];
int ret;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION; /* often 0x46 */
cgc.cmd[3] = CDF_RWRT; /* often 0x0020 */
cgc.cmd[8] = sizeof(buffer); /* often 0x18 */
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));
return 0;
}
static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[16];
__be16 *feature_code;
int ret;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[3] = CDF_HWDM;
cgc.cmd[8] = sizeof(buffer);
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
feature_code = (__be16 *) &buffer[sizeof(struct feature_header)];
if (be16_to_cpu(*feature_code) == CDF_HWDM)
return 0;
return 1;
}
static int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write)
{
struct rwrt_feature_desc rfd;
int ret;
*write = 0;
if ((ret = cdrom_get_random_writable(cdi, &rfd)))
return ret;
if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
*write = 1;
return 0;
}
static int cdrom_media_erasable(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di), n_first_track))
return -1;
return di.erasable;
}
/*
* FIXME: check RO bit
*/
static int cdrom_dvdram_open_write(struct cdrom_device_info *cdi)
{
int ret = cdrom_media_erasable(cdi);
/*
* allow writable open if media info read worked and media is
* erasable, _or_ if it fails since not all drives support it
*/
if (!ret)
return 1;
return 0;
}
static int cdrom_mrw_open_write(struct cdrom_device_info *cdi)
{
disc_information di;
int ret;
/*
* always reset to DMA lba space on open
*/
if (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) {
pr_err("failed setting lba address space\n");
return 1;
}
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di),disc_type))
return 1;
if (!di.erasable)
return 1;
/*
* mrw_status
* 0 - not MRW formatted
* 1 - MRW bgformat started, but not running or complete
* 2 - MRW bgformat in progress
* 3 - MRW formatting complete
*/
ret = 0;
pr_info("open: mrw_status '%s'\n", mrw_format_status[di.mrw_status]);
if (!di.mrw_status)
ret = 1;
else if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE &&
mrw_format_restart)
ret = cdrom_mrw_bgformat(cdi, 1);
return ret;
}
static int mo_open_write(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[255];
int ret;
init_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ);
cgc.quiet = 1;
/*
* obtain write protect information as per
* drivers/scsi/sd.c:sd_read_write_protect_flag
*/
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
if (ret)
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0);
if (ret) {
cgc.buflen = 255;
ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
}
/* drive gave us no info, let the user go ahead */
if (ret)
return 0;
return buffer[3] & 0x80;
}
static int cdrom_ram_open_write(struct cdrom_device_info *cdi)
{
struct rwrt_feature_desc rfd;
int ret;
if ((ret = cdrom_has_defect_mgt(cdi)))
return ret;
if ((ret = cdrom_get_random_writable(cdi, &rfd)))
return ret;
else if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
ret = !rfd.curr;
cd_dbg(CD_OPEN, "can open for random write\n");
return ret;
}
static void cdrom_mmc3_profile(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
char buffer[32];
int ret, mmc3_profile;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
cgc.cmd[1] = 0;
cgc.cmd[2] = cgc.cmd[3] = 0; /* Starting Feature Number */
cgc.cmd[8] = sizeof(buffer); /* Allocation Length */
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
mmc3_profile = 0xffff;
else
mmc3_profile = (buffer[6] << 8) | buffer[7];
cdi->mmc3_profile = mmc3_profile;
}
static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi)
{
switch (cdi->mmc3_profile) {
case 0x12: /* DVD-RAM */
case 0x1A: /* DVD+RW */
case 0x43: /* BD-RE */
return 0;
default:
return 1;
}
}
/*
* returns 0 for ok to open write, non-0 to disallow
*/
static int cdrom_open_write(struct cdrom_device_info *cdi)
{
int mrw, mrw_write, ram_write;
int ret = 1;
mrw = 0;
if (!cdrom_is_mrw(cdi, &mrw_write))
mrw = 1;
if (CDROM_CAN(CDC_MO_DRIVE))
ram_write = 1;
else
(void) cdrom_is_random_writable(cdi, &ram_write);
if (mrw)
cdi->mask &= ~CDC_MRW;
else
cdi->mask |= CDC_MRW;
if (mrw_write)
cdi->mask &= ~CDC_MRW_W;
else
cdi->mask |= CDC_MRW_W;
if (ram_write)
cdi->mask &= ~CDC_RAM;
else
cdi->mask |= CDC_RAM;
if (CDROM_CAN(CDC_MRW_W))
ret = cdrom_mrw_open_write(cdi);
else if (CDROM_CAN(CDC_DVD_RAM))
ret = cdrom_dvdram_open_write(cdi);
else if (CDROM_CAN(CDC_RAM) &&
!CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE))
ret = cdrom_ram_open_write(cdi);
else if (CDROM_CAN(CDC_MO_DRIVE))
ret = mo_open_write(cdi);
else if (!cdrom_is_dvd_rw(cdi))
ret = 0;
return ret;
}
static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi)
{
struct packet_command cgc;
if (cdi->mmc3_profile != 0x1a) {
cd_dbg(CD_CLOSE, "%s: No DVD+RW\n", cdi->name);
return;
}
if (!cdi->media_written) {
cd_dbg(CD_CLOSE, "%s: DVD+RW media clean\n", cdi->name);
return;
}
pr_info("%s: dirty DVD+RW media, \"finalizing\"\n", cdi->name);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_FLUSH_CACHE;
cgc.timeout = 30*HZ;
cdi->ops->generic_packet(cdi, &cgc);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
cgc.timeout = 3000*HZ;
cgc.quiet = 1;
cdi->ops->generic_packet(cdi, &cgc);
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_CLOSE_TRACK;
cgc.cmd[2] = 2; /* Close session */
cgc.quiet = 1;
cgc.timeout = 3000*HZ;
cdi->ops->generic_packet(cdi, &cgc);
cdi->media_written = 0;
}
static int cdrom_close_write(struct cdrom_device_info *cdi)
{
#if 0
return cdrom_flush_cache(cdi);
#else
return 0;
#endif
}
/* badly broken, I know. Is due for a fixup anytime. */
static void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks)
{
struct cdrom_tochdr header;
struct cdrom_tocentry entry;
int ret, i;
tracks->data = 0;
tracks->audio = 0;
tracks->cdi = 0;
tracks->xa = 0;
tracks->error = 0;
cd_dbg(CD_COUNT_TRACKS, "entering cdrom_count_tracks\n");
/* Grab the TOC header so we can see how many tracks there are */
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);
if (ret) {
if (ret == -ENOMEDIUM)
tracks->error = CDS_NO_DISC;
else
tracks->error = CDS_NO_INFO;
return;
}
/* check what type of tracks are on this disc */
entry.cdte_format = CDROM_MSF;
for (i = header.cdth_trk0; i <= header.cdth_trk1; i++) {
entry.cdte_track = i;
if (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) {
tracks->error = CDS_NO_INFO;
return;
}
if (entry.cdte_ctrl & CDROM_DATA_TRACK) {
if (entry.cdte_format == 0x10)
tracks->cdi++;
else if (entry.cdte_format == 0x20)
tracks->xa++;
else
tracks->data++;
} else {
tracks->audio++;
}
cd_dbg(CD_COUNT_TRACKS, "track %d: format=%d, ctrl=%d\n",
i, entry.cdte_format, entry.cdte_ctrl);
}
cd_dbg(CD_COUNT_TRACKS, "disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\n",
header.cdth_trk1, tracks->audio, tracks->data,
tracks->cdi, tracks->xa);
}
static
int open_for_data(struct cdrom_device_info *cdi)
{
int ret;
const struct cdrom_device_ops *cdo = cdi->ops;
tracktype tracks;
cd_dbg(CD_OPEN, "entering open_for_data\n");
/* Check if the driver can report drive status. If it can, we
can do clever things. If it can't, well, we at least tried! */
if (cdo->drive_status != NULL) {
ret = cdo->drive_status(cdi, CDSL_CURRENT);
cd_dbg(CD_OPEN, "drive_status=%d\n", ret);
if (ret == CDS_TRAY_OPEN) {
cd_dbg(CD_OPEN, "the tray is open...\n");
/* can/may i close it? */
if (CDROM_CAN(CDC_CLOSE_TRAY) &&
cdi->options & CDO_AUTO_CLOSE) {
cd_dbg(CD_OPEN, "trying to close the tray\n");
ret=cdo->tray_move(cdi,0);
if (ret) {
cd_dbg(CD_OPEN, "bummer. tried to close the tray but failed.\n");
/* Ignore the error from the low
level driver. We don't care why it
couldn't close the tray. We only care
that there is no disc in the drive,
since that is the _REAL_ problem here.*/
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
} else {
cd_dbg(CD_OPEN, "bummer. this drive can't close the tray.\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
/* Ok, the door should be closed now.. Check again */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n");
cd_dbg(CD_OPEN, "tray might not contain a medium\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
cd_dbg(CD_OPEN, "the tray is now closed\n");
}
/* the door should be closed now, check for the disc */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if (ret!=CDS_DISC_OK) {
ret = -ENOMEDIUM;
goto clean_up_and_return;
}
}
cdrom_count_tracks(cdi, &tracks);
if (tracks.error == CDS_NO_DISC) {
cd_dbg(CD_OPEN, "bummer. no disc.\n");
ret=-ENOMEDIUM;
goto clean_up_and_return;
}
/* CD-Players which don't use O_NONBLOCK, workman
* for example, need bit CDO_CHECK_TYPE cleared! */
if (tracks.data==0) {
if (cdi->options & CDO_CHECK_TYPE) {
/* give people a warning shot, now that CDO_CHECK_TYPE
is the default case! */
cd_dbg(CD_OPEN, "bummer. wrong media type.\n");
cd_dbg(CD_WARNING, "pid %d must open device O_NONBLOCK!\n",
(unsigned int)task_pid_nr(current));
ret=-EMEDIUMTYPE;
goto clean_up_and_return;
}
else {
cd_dbg(CD_OPEN, "wrong media type, but CDO_CHECK_TYPE not set\n");
}
}
cd_dbg(CD_OPEN, "all seems well, opening the devicen");
/* all seems well, we can open the device */
ret = cdo->open(cdi, 0); /* open for data */
cd_dbg(CD_OPEN, "opening the device gave me %d\n", ret);
/* After all this careful checking, we shouldn't have problems
opening the device, but we don't want the device locked if
this somehow fails... */
if (ret) {
cd_dbg(CD_OPEN, "open device failed\n");
goto clean_up_and_return;
}
if (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) {
cdo->lock_door(cdi, 1);
cd_dbg(CD_OPEN, "door locked\n");
}
cd_dbg(CD_OPEN, "device opened successfully\n");
return ret;
/* Something failed. Try to unlock the drive, because some drivers
(notably ide-cd) lock the drive after every command. This produced
a nasty bug where after mount failed, the drive would remain locked!
This ensures that the drive gets unlocked after a mount fails. This
is a goto to avoid bloating the driver with redundant code. */
clean_up_and_return:
cd_dbg(CD_OPEN, "open failed\n");
if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {
cdo->lock_door(cdi, 0);
cd_dbg(CD_OPEN, "door unlocked\n");
}
return ret;
}
/* We use the open-option O_NONBLOCK to indicate that the
* purpose of opening is only for subsequent ioctl() calls; no device
* integrity checks are performed.
*
* We hope that all cd-player programs will adopt this convention. It
* is in their own interest: device control becomes a lot easier
* this way.
*/
int cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev,
fmode_t mode)
{
int ret;
cd_dbg(CD_OPEN, "entering cdrom_open\n");
/* if this was a O_NONBLOCK open and we should honor the flags,
* do a quick open without drive/disc integrity checks. */
cdi->use_count++;
if ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) {
ret = cdi->ops->open(cdi, 1);
} else {
ret = open_for_data(cdi);
if (ret)
goto err;
cdrom_mmc3_profile(cdi);
if (mode & FMODE_WRITE) {
ret = -EROFS;
if (cdrom_open_write(cdi))
goto err_release;
if (!CDROM_CAN(CDC_RAM))
goto err_release;
ret = 0;
cdi->media_written = 0;
}
}
if (ret)
goto err;
cd_dbg(CD_OPEN, "Use count for \"/dev/%s\" now %d\n",
cdi->name, cdi->use_count);
return 0;
err_release:
if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {
cdi->ops->lock_door(cdi, 0);
cd_dbg(CD_OPEN, "door unlocked\n");
}
cdi->ops->release(cdi);
err:
cdi->use_count--;
return ret;
}
/* This code is similar to that in open_for_data. The routine is called
whenever an audio play operation is requested.
*/
static int check_for_audio_disc(struct cdrom_device_info *cdi,
const struct cdrom_device_ops *cdo)
{
int ret;
tracktype tracks;
cd_dbg(CD_OPEN, "entering check_for_audio_disc\n");
if (!(cdi->options & CDO_CHECK_TYPE))
return 0;
if (cdo->drive_status != NULL) {
ret = cdo->drive_status(cdi, CDSL_CURRENT);
cd_dbg(CD_OPEN, "drive_status=%d\n", ret);
if (ret == CDS_TRAY_OPEN) {
cd_dbg(CD_OPEN, "the tray is open...\n");
/* can/may i close it? */
if (CDROM_CAN(CDC_CLOSE_TRAY) &&
cdi->options & CDO_AUTO_CLOSE) {
cd_dbg(CD_OPEN, "trying to close the tray\n");
ret=cdo->tray_move(cdi,0);
if (ret) {
cd_dbg(CD_OPEN, "bummer. tried to close tray but failed.\n");
/* Ignore the error from the low
level driver. We don't care why it
couldn't close the tray. We only care
that there is no disc in the drive,
since that is the _REAL_ problem here.*/
return -ENOMEDIUM;
}
} else {
cd_dbg(CD_OPEN, "bummer. this driver can't close the tray.\n");
return -ENOMEDIUM;
}
/* Ok, the door should be closed now.. Check again */
ret = cdo->drive_status(cdi, CDSL_CURRENT);
if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n");
return -ENOMEDIUM;
}
if (ret!=CDS_DISC_OK) {
cd_dbg(CD_OPEN, "bummer. disc isn't ready.\n");
return -EIO;
}
cd_dbg(CD_OPEN, "the tray is now closed\n");
}
}
cdrom_count_tracks(cdi, &tracks);
if (tracks.error)
return(tracks.error);
if (tracks.audio==0)
return -EMEDIUMTYPE;
return 0;
}
void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode)
{
const struct cdrom_device_ops *cdo = cdi->ops;
int opened_for_data;
cd_dbg(CD_CLOSE, "entering cdrom_release\n");
if (cdi->use_count > 0)
cdi->use_count--;
if (cdi->use_count == 0) {
cd_dbg(CD_CLOSE, "Use count for \"/dev/%s\" now zero\n",
cdi->name);
cdrom_dvd_rw_close_write(cdi);
if ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) {
cd_dbg(CD_CLOSE, "Unlocking door!\n");
cdo->lock_door(cdi, 0);
}
}
opened_for_data = !(cdi->options & CDO_USE_FFLAGS) ||
!(mode & FMODE_NDELAY);
/*
* flush cache on last write release
*/
if (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data)
cdrom_close_write(cdi);
cdo->release(cdi);
if (cdi->use_count == 0) { /* last process that closes dev*/
if (opened_for_data &&
cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY))
cdo->tray_move(cdi, 1);
}
}
static int cdrom_read_mech_status(struct cdrom_device_info *cdi,
struct cdrom_changer_info *buf)
{
struct packet_command cgc;
const struct cdrom_device_ops *cdo = cdi->ops;
int length;
/*
* Sanyo changer isn't spec compliant (doesn't use regular change
* LOAD_UNLOAD command, and it doesn't implement the mech status
* command below
*/
if (cdi->sanyo_slot) {
buf->hdr.nslots = 3;
buf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot;
for (length = 0; length < 3; length++) {
buf->slots[length].disc_present = 1;
buf->slots[length].change = 0;
}
return 0;
}
length = sizeof(struct cdrom_mechstat_header) +
cdi->capacity * sizeof(struct cdrom_slot);
init_cdrom_command(&cgc, buf, length, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_MECHANISM_STATUS;
cgc.cmd[8] = (length >> 8) & 0xff;
cgc.cmd[9] = length & 0xff;
return cdo->generic_packet(cdi, &cgc);
}
static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_CHANGER, "entering cdrom_slot_status()\n");
if (cdi->sanyo_slot)
return CDS_NO_INFO;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((ret = cdrom_read_mech_status(cdi, info)))
goto out_free;
if (info->slots[slot].disc_present)
ret = CDS_DISC_OK;
else
ret = CDS_NO_DISC;
out_free:
kfree(info);
return ret;
}
/* Return the number of slots for an ATAPI/SCSI cdrom,
* return 1 if not a changer.
*/
int cdrom_number_of_slots(struct cdrom_device_info *cdi)
{
int status;
int nslots = 1;
struct cdrom_changer_info *info;
cd_dbg(CD_CHANGER, "entering cdrom_number_of_slots()\n");
/* cdrom_read_mech_status requires a valid value for capacity: */
cdi->capacity = 0;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((status = cdrom_read_mech_status(cdi, info)) == 0)
nslots = info->hdr.nslots;
kfree(info);
return nslots;
}
/* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */
static int cdrom_load_unload(struct cdrom_device_info *cdi, int slot)
{
struct packet_command cgc;
cd_dbg(CD_CHANGER, "entering cdrom_load_unload()\n");
if (cdi->sanyo_slot && slot < 0)
return 0;
init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
cgc.cmd[0] = GPCMD_LOAD_UNLOAD;
cgc.cmd[4] = 2 + (slot >= 0);
cgc.cmd[8] = slot;
cgc.timeout = 60 * HZ;
/* The Sanyo 3 CD changer uses byte 7 of the
GPCMD_TEST_UNIT_READY to command to switch CDs instead of
using the GPCMD_LOAD_UNLOAD opcode. */
if (cdi->sanyo_slot && -1 < slot) {
cgc.cmd[0] = GPCMD_TEST_UNIT_READY;
cgc.cmd[7] = slot;
cgc.cmd[4] = cgc.cmd[8] = 0;
cdi->sanyo_slot = slot ? slot : 3;
}
return cdi->ops->generic_packet(cdi, &cgc);
}
static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot)
{
struct cdrom_changer_info *info;
int curslot;
int ret;
cd_dbg(CD_CHANGER, "entering cdrom_select_disc()\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -EDRIVE_CANT_DO_THIS;
if (cdi->ops->check_events)
cdi->ops->check_events(cdi, 0, slot);
else
cdi->ops->media_changed(cdi, slot);
if (slot == CDSL_NONE) {
/* set media changed bits, on both queues */
cdi->mc_flags = 0x3;
return cdrom_load_unload(cdi, -1);
}
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
if ((ret = cdrom_read_mech_status(cdi, info))) {
kfree(info);
return ret;
}
curslot = info->hdr.curslot;
kfree(info);
if (cdi->use_count > 1 || cdi->keeplocked) {
if (slot == CDSL_CURRENT) {
return curslot;
} else {
return -EBUSY;
}
}
/* Specifying CDSL_CURRENT will attempt to load the currnet slot,
which is useful if it had been previously unloaded.
Whether it can or not, it returns the current slot.
Similarly, if slot happens to be the current one, we still
try and load it. */
if (slot == CDSL_CURRENT)
slot = curslot;
/* set media changed bits on both queues */
cdi->mc_flags = 0x3;
if ((ret = cdrom_load_unload(cdi, slot)))
return ret;
return slot;
}
/*
* As cdrom implements an extra ioctl consumer for media changed
* event, it needs to buffer ->check_events() output, such that event
* is not lost for both the usual VFS and ioctl paths.
* cdi->{vfs|ioctl}_events are used to buffer pending events for each
* path.
*
* XXX: Locking is non-existent. cdi->ops->check_events() can be
* called in parallel and buffering fields are accessed without any
* exclusion. The original media_changed code had the same problem.
* It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl
* and remove this cruft altogether. It doesn't have much usefulness
* at this point.
*/
static void cdrom_update_events(struct cdrom_device_info *cdi,
unsigned int clearing)
{
unsigned int events;
events = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT);
cdi->vfs_events |= events;
cdi->ioctl_events |= events;
}
unsigned int cdrom_check_events(struct cdrom_device_info *cdi,
unsigned int clearing)
{
unsigned int events;
cdrom_update_events(cdi, clearing);
events = cdi->vfs_events;
cdi->vfs_events = 0;
return events;
}
EXPORT_SYMBOL(cdrom_check_events);
/* We want to make media_changed accessible to the user through an
* ioctl. The main problem now is that we must double-buffer the
* low-level implementation, to assure that the VFS and the user both
* see a medium change once.
*/
static
int media_changed(struct cdrom_device_info *cdi, int queue)
{
unsigned int mask = (1 << (queue & 1));
int ret = !!(cdi->mc_flags & mask);
bool changed;
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return ret;
/* changed since last call? */
if (cdi->ops->check_events) {
BUG_ON(!queue); /* shouldn't be called from VFS path */
cdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE);
changed = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE;
cdi->ioctl_events = 0;
} else
changed = cdi->ops->media_changed(cdi, CDSL_CURRENT);
if (changed) {
cdi->mc_flags = 0x3; /* set bit on both queues */
ret |= 1;
cdi->media_written = 0;
}
cdi->mc_flags &= ~mask; /* clear bit */
return ret;
}
int cdrom_media_changed(struct cdrom_device_info *cdi)
{
/* This talks to the VFS, which doesn't like errors - just 1 or 0.
* Returning "0" is always safe (media hasn't been changed). Do that
* if the low-level cdrom driver dosn't support media changed. */
if (cdi == NULL || cdi->ops->media_changed == NULL)
return 0;
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return 0;
return media_changed(cdi, 0);
}
/* Requests to the low-level drivers will /always/ be done in the
following format convention:
CDROM_LBA: all data-related requests.
CDROM_MSF: all audio-related requests.
However, a low-level implementation is allowed to refuse this
request, and return information in its own favorite format.
It doesn't make sense /at all/ to ask for a play_audio in LBA
format, or ask for multi-session info in MSF format. However, for
backward compatibility these format requests will be satisfied, but
the requests to the low-level drivers will be sanitized in the more
meaningful format indicated above.
*/
static
void sanitize_format(union cdrom_addr *addr,
u_char * curr, u_char requested)
{
if (*curr == requested)
return; /* nothing to be done! */
if (requested == CDROM_LBA) {
addr->lba = (int) addr->msf.frame +
75 * (addr->msf.second - 2 + 60 * addr->msf.minute);
} else { /* CDROM_MSF */
int lba = addr->lba;
addr->msf.frame = lba % 75;
lba /= 75;
lba += 2;
addr->msf.second = lba % 60;
addr->msf.minute = lba / 60;
}
*curr = requested;
}
void init_cdrom_command(struct packet_command *cgc, void *buf, int len,
int type)
{
memset(cgc, 0, sizeof(struct packet_command));
if (buf)
memset(buf, 0, len);
cgc->buffer = (char *) buf;
cgc->buflen = len;
cgc->data_direction = type;
cgc->timeout = CDROM_DEF_TIMEOUT;
}
/* DVD handling */
#define copy_key(dest,src) memcpy((dest), (src), sizeof(dvd_key))
#define copy_chal(dest,src) memcpy((dest), (src), sizeof(dvd_challenge))
static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type)
{
cgc->cmd[0] = GPCMD_REPORT_KEY;
cgc->cmd[10] = type | (agid << 6);
switch (type) {
case 0: case 8: case 5: {
cgc->buflen = 8;
break;
}
case 1: {
cgc->buflen = 16;
break;
}
case 2: case 4: {
cgc->buflen = 12;
break;
}
}
cgc->cmd[9] = cgc->buflen;
cgc->data_direction = CGC_DATA_READ;
}
static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type)
{
cgc->cmd[0] = GPCMD_SEND_KEY;
cgc->cmd[10] = type | (agid << 6);
switch (type) {
case 1: {
cgc->buflen = 16;
break;
}
case 3: {
cgc->buflen = 12;
break;
}
case 6: {
cgc->buflen = 8;
break;
}
}
cgc->cmd[9] = cgc->buflen;
cgc->data_direction = CGC_DATA_WRITE;
}
static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai)
{
int ret;
u_char buf[20];
struct packet_command cgc;
const struct cdrom_device_ops *cdo = cdi->ops;
rpc_state_t rpc_state;
memset(buf, 0, sizeof(buf));
init_cdrom_command(&cgc, buf, 0, CGC_DATA_READ);
switch (ai->type) {
/* LU data send */
case DVD_LU_SEND_AGID:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_AGID\n");
cgc.quiet = 1;
setup_report_key(&cgc, ai->lsa.agid, 0);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lsa.agid = buf[7] >> 6;
/* Returning data, let host change state */
break;
case DVD_LU_SEND_KEY1:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_KEY1\n");
setup_report_key(&cgc, ai->lsk.agid, 2);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
copy_key(ai->lsk.key, &buf[4]);
/* Returning data, let host change state */
break;
case DVD_LU_SEND_CHALLENGE:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_CHALLENGE\n");
setup_report_key(&cgc, ai->lsc.agid, 1);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
copy_chal(ai->lsc.chal, &buf[4]);
/* Returning data, let host change state */
break;
/* Post-auth key */
case DVD_LU_SEND_TITLE_KEY:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_TITLE_KEY\n");
cgc.quiet = 1;
setup_report_key(&cgc, ai->lstk.agid, 4);
cgc.cmd[5] = ai->lstk.lba;
cgc.cmd[4] = ai->lstk.lba >> 8;
cgc.cmd[3] = ai->lstk.lba >> 16;
cgc.cmd[2] = ai->lstk.lba >> 24;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lstk.cpm = (buf[4] >> 7) & 1;
ai->lstk.cp_sec = (buf[4] >> 6) & 1;
ai->lstk.cgms = (buf[4] >> 4) & 3;
copy_key(ai->lstk.title_key, &buf[5]);
/* Returning data, let host change state */
break;
case DVD_LU_SEND_ASF:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_ASF\n");
setup_report_key(&cgc, ai->lsasf.agid, 5);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lsasf.asf = buf[7] & 1;
break;
/* LU data receive (LU changes state) */
case DVD_HOST_SEND_CHALLENGE:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_CHALLENGE\n");
setup_send_key(&cgc, ai->hsc.agid, 1);
buf[1] = 0xe;
copy_chal(&buf[4], ai->hsc.chal);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->type = DVD_LU_SEND_KEY1;
break;
case DVD_HOST_SEND_KEY2:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_KEY2\n");
setup_send_key(&cgc, ai->hsk.agid, 3);
buf[1] = 0xa;
copy_key(&buf[4], ai->hsk.key);
if ((ret = cdo->generic_packet(cdi, &cgc))) {
ai->type = DVD_AUTH_FAILURE;
return ret;
}
ai->type = DVD_AUTH_ESTABLISHED;
break;
/* Misc */
case DVD_INVALIDATE_AGID:
cgc.quiet = 1;
cd_dbg(CD_DVD, "entering DVD_INVALIDATE_AGID\n");
setup_report_key(&cgc, ai->lsa.agid, 0x3f);
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
break;
/* Get region settings */
case DVD_LU_SEND_RPC_STATE:
cd_dbg(CD_DVD, "entering DVD_LU_SEND_RPC_STATE\n");
setup_report_key(&cgc, 0, 8);
memset(&rpc_state, 0, sizeof(rpc_state_t));
cgc.buffer = (char *) &rpc_state;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
ai->lrpcs.type = rpc_state.type_code;
ai->lrpcs.vra = rpc_state.vra;
ai->lrpcs.ucca = rpc_state.ucca;
ai->lrpcs.region_mask = rpc_state.region_mask;
ai->lrpcs.rpc_scheme = rpc_state.rpc_scheme;
break;
/* Set region settings */
case DVD_HOST_SEND_RPC_STATE:
cd_dbg(CD_DVD, "entering DVD_HOST_SEND_RPC_STATE\n");
setup_send_key(&cgc, 0, 6);
buf[1] = 6;
buf[4] = ai->hrpcs.pdrc;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
break;
default:
cd_dbg(CD_WARNING, "Invalid DVD key ioctl (%d)\n", ai->type);
return -ENOTTY;
}
return 0;
}
static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
unsigned char buf[21], *base;
struct dvd_layer *layer;
const struct cdrom_device_ops *cdo = cdi->ops;
int ret, layer_num = s->physical.layer_num;
if (layer_num >= DVD_LAYERS)
return -EINVAL;
init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[6] = layer_num;
cgc->cmd[7] = s->type;
cgc->cmd[9] = cgc->buflen & 0xff;
/*
* refrain from reporting errors on non-existing layers (mainly)
*/
cgc->quiet = 1;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
return ret;
base = &buf[4];
layer = &s->physical.layer[layer_num];
/*
* place the data... really ugly, but at least we won't have to
* worry about endianess in userspace.
*/
memset(layer, 0, sizeof(*layer));
layer->book_version = base[0] & 0xf;
layer->book_type = base[0] >> 4;
layer->min_rate = base[1] & 0xf;
layer->disc_size = base[1] >> 4;
layer->layer_type = base[2] & 0xf;
layer->track_path = (base[2] >> 4) & 1;
layer->nlayers = (base[2] >> 5) & 3;
layer->track_density = base[3] & 0xf;
layer->linear_density = base[3] >> 4;
layer->start_sector = base[5] << 16 | base[6] << 8 | base[7];
layer->end_sector = base[9] << 16 | base[10] << 8 | base[11];
layer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15];
layer->bca = base[16] >> 7;
return 0;
}
static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret;
u_char buf[8];
const struct cdrom_device_ops *cdo = cdi->ops;
init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[6] = s->copyright.layer_num;
cgc->cmd[7] = s->type;
cgc->cmd[8] = cgc->buflen >> 8;
cgc->cmd[9] = cgc->buflen & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
return ret;
s->copyright.cpst = buf[4];
s->copyright.rmi = buf[5];
return 0;
}
static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret, size;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
size = sizeof(s->disckey.value) + 4;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[8] = size >> 8;
cgc->cmd[9] = size & 0xff;
cgc->cmd[10] = s->disckey.agid << 6;
ret = cdo->generic_packet(cdi, cgc);
if (!ret)
memcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value));
kfree(buf);
return ret;
}
static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret, size = 4 + 188;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[9] = cgc->buflen & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
goto out;
s->bca.len = buf[0] << 8 | buf[1];
if (s->bca.len < 12 || s->bca.len > 188) {
cd_dbg(CD_WARNING, "Received invalid BCA length (%d)\n",
s->bca.len);
ret = -EIO;
goto out;
}
memcpy(s->bca.value, &buf[4], s->bca.len);
ret = 0;
out:
kfree(buf);
return ret;
}
static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
int ret = 0, size;
u_char *buf;
const struct cdrom_device_ops *cdo = cdi->ops;
size = sizeof(s->manufact.value) + 4;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
init_cdrom_command(cgc, buf, size, CGC_DATA_READ);
cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;
cgc->cmd[7] = s->type;
cgc->cmd[8] = size >> 8;
cgc->cmd[9] = size & 0xff;
ret = cdo->generic_packet(cdi, cgc);
if (ret)
goto out;
s->manufact.len = buf[0] << 8 | buf[1];
if (s->manufact.len < 0) {
cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d)\n",
s->manufact.len);
ret = -EIO;
} else {
if (s->manufact.len > 2048) {
cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d): truncating to 2048\n",
s->manufact.len);
s->manufact.len = 2048;
}
memcpy(s->manufact.value, &buf[4], s->manufact.len);
}
out:
kfree(buf);
return ret;
}
static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s,
struct packet_command *cgc)
{
switch (s->type) {
case DVD_STRUCT_PHYSICAL:
return dvd_read_physical(cdi, s, cgc);
case DVD_STRUCT_COPYRIGHT:
return dvd_read_copyright(cdi, s, cgc);
case DVD_STRUCT_DISCKEY:
return dvd_read_disckey(cdi, s, cgc);
case DVD_STRUCT_BCA:
return dvd_read_bca(cdi, s, cgc);
case DVD_STRUCT_MANUFACT:
return dvd_read_manufact(cdi, s, cgc);
default:
cd_dbg(CD_WARNING, ": Invalid DVD structure read requested (%d)\n",
s->type);
return -EINVAL;
}
}
int cdrom_mode_sense(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int page_code, int page_control)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_MODE_SENSE_10;
cgc->cmd[2] = page_code | (page_control << 6);
cgc->cmd[7] = cgc->buflen >> 8;
cgc->cmd[8] = cgc->buflen & 0xff;
cgc->data_direction = CGC_DATA_READ;
return cdo->generic_packet(cdi, cgc);
}
int cdrom_mode_select(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(cgc->cmd, 0, sizeof(cgc->cmd));
memset(cgc->buffer, 0, 2);
cgc->cmd[0] = GPCMD_MODE_SELECT_10;
cgc->cmd[1] = 0x10; /* PF */
cgc->cmd[7] = cgc->buflen >> 8;
cgc->cmd[8] = cgc->buflen & 0xff;
cgc->data_direction = CGC_DATA_WRITE;
return cdo->generic_packet(cdi, cgc);
}
static int cdrom_read_subchannel(struct cdrom_device_info *cdi,
struct cdrom_subchnl *subchnl, int mcn)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
char buffer[32];
int ret;
init_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_SUBCHANNEL;
cgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */
cgc.cmd[2] = 0x40; /* request subQ data */
cgc.cmd[3] = mcn ? 2 : 1;
cgc.cmd[8] = 16;
if ((ret = cdo->generic_packet(cdi, &cgc)))
return ret;
subchnl->cdsc_audiostatus = cgc.buffer[1];
subchnl->cdsc_ctrl = cgc.buffer[5] & 0xf;
subchnl->cdsc_trk = cgc.buffer[6];
subchnl->cdsc_ind = cgc.buffer[7];
if (subchnl->cdsc_format == CDROM_LBA) {
subchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) |
(cgc.buffer[9] << 16) |
(cgc.buffer[10] << 8) |
(cgc.buffer[11]));
subchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) |
(cgc.buffer[13] << 16) |
(cgc.buffer[14] << 8) |
(cgc.buffer[15]));
} else {
subchnl->cdsc_reladdr.msf.minute = cgc.buffer[13];
subchnl->cdsc_reladdr.msf.second = cgc.buffer[14];
subchnl->cdsc_reladdr.msf.frame = cgc.buffer[15];
subchnl->cdsc_absaddr.msf.minute = cgc.buffer[9];
subchnl->cdsc_absaddr.msf.second = cgc.buffer[10];
subchnl->cdsc_absaddr.msf.frame = cgc.buffer[11];
}
return 0;
}
/*
* Specific READ_10 interface
*/
static int cdrom_read_cd(struct cdrom_device_info *cdi,
struct packet_command *cgc, int lba,
int blocksize, int nblocks)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(&cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_READ_10;
cgc->cmd[2] = (lba >> 24) & 0xff;
cgc->cmd[3] = (lba >> 16) & 0xff;
cgc->cmd[4] = (lba >> 8) & 0xff;
cgc->cmd[5] = lba & 0xff;
cgc->cmd[6] = (nblocks >> 16) & 0xff;
cgc->cmd[7] = (nblocks >> 8) & 0xff;
cgc->cmd[8] = nblocks & 0xff;
cgc->buflen = blocksize * nblocks;
return cdo->generic_packet(cdi, cgc);
}
/* very generic interface for reading the various types of blocks */
static int cdrom_read_block(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int lba, int nblocks, int format, int blksize)
{
const struct cdrom_device_ops *cdo = cdi->ops;
memset(&cgc->cmd, 0, sizeof(cgc->cmd));
cgc->cmd[0] = GPCMD_READ_CD;
/* expected sector size - cdda,mode1,etc. */
cgc->cmd[1] = format << 2;
/* starting address */
cgc->cmd[2] = (lba >> 24) & 0xff;
cgc->cmd[3] = (lba >> 16) & 0xff;
cgc->cmd[4] = (lba >> 8) & 0xff;
cgc->cmd[5] = lba & 0xff;
/* number of blocks */
cgc->cmd[6] = (nblocks >> 16) & 0xff;
cgc->cmd[7] = (nblocks >> 8) & 0xff;
cgc->cmd[8] = nblocks & 0xff;
cgc->buflen = blksize * nblocks;
/* set the header info returned */
switch (blksize) {
case CD_FRAMESIZE_RAW0 : cgc->cmd[9] = 0x58; break;
case CD_FRAMESIZE_RAW1 : cgc->cmd[9] = 0x78; break;
case CD_FRAMESIZE_RAW : cgc->cmd[9] = 0xf8; break;
default : cgc->cmd[9] = 0x10;
}
return cdo->generic_packet(cdi, cgc);
}
static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
struct packet_command cgc;
int ret = 0;
int nr;
cdi->last_sense = 0;
memset(&cgc, 0, sizeof(cgc));
/*
* start with will ra.nframes size, back down if alloc fails
*/
nr = nframes;
do {
cgc.buffer = kmalloc_array(nr, CD_FRAMESIZE_RAW, GFP_KERNEL);
if (cgc.buffer)
break;
nr >>= 1;
} while (nr);
if (!nr)
return -ENOMEM;
cgc.data_direction = CGC_DATA_READ;
while (nframes > 0) {
if (nr > nframes)
nr = nframes;
ret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW);
if (ret)
break;
if (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) {
ret = -EFAULT;
break;
}
ubuf += CD_FRAMESIZE_RAW * nr;
nframes -= nr;
lba += nr;
}
kfree(cgc.buffer);
return ret;
}
static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
struct request_queue *q = cdi->disk->queue;
struct request *rq;
struct scsi_request *req;
struct bio *bio;
unsigned int len;
int nr, ret = 0;
if (!q)
return -ENXIO;
if (!blk_queue_scsi_passthrough(q)) {
WARN_ONCE(true,
"Attempt read CDDA info through a non-SCSI queue\n");
return -EINVAL;
}
cdi->last_sense = 0;
while (nframes) {
nr = nframes;
if (cdi->cdda_method == CDDA_BPC_SINGLE)
nr = 1;
if (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9))
nr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW;
len = nr * CD_FRAMESIZE_RAW;
rq = blk_get_request(q, REQ_OP_SCSI_IN, 0);
if (IS_ERR(rq)) {
ret = PTR_ERR(rq);
break;
}
req = scsi_req(rq);
ret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL);
if (ret) {
blk_put_request(rq);
break;
}
req->cmd[0] = GPCMD_READ_CD;
req->cmd[1] = 1 << 2;
req->cmd[2] = (lba >> 24) & 0xff;
req->cmd[3] = (lba >> 16) & 0xff;
req->cmd[4] = (lba >> 8) & 0xff;
req->cmd[5] = lba & 0xff;
req->cmd[6] = (nr >> 16) & 0xff;
req->cmd[7] = (nr >> 8) & 0xff;
req->cmd[8] = nr & 0xff;
req->cmd[9] = 0xf8;
req->cmd_len = 12;
rq->timeout = 60 * HZ;
bio = rq->bio;
blk_execute_rq(q, cdi->disk, rq, 0);
if (scsi_req(rq)->result) {
struct scsi_sense_hdr sshdr;
ret = -EIO;
scsi_normalize_sense(req->sense, req->sense_len,
&sshdr);
cdi->last_sense = sshdr.sense_key;
}
if (blk_rq_unmap_user(bio))
ret = -EFAULT;
blk_put_request(rq);
if (ret)
break;
nframes -= nr;
lba += nr;
ubuf += len;
}
return ret;
}
static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf,
int lba, int nframes)
{
int ret;
if (cdi->cdda_method == CDDA_OLD)
return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);
retry:
/*
* for anything else than success and io error, we need to retry
*/
ret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes);
if (!ret || ret != -EIO)
return ret;
/*
* I've seen drives get sense 4/8/3 udma crc errors on multi
* frame dma, so drop to single frame dma if we need to
*/
if (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) {
pr_info("dropping to single frame dma\n");
cdi->cdda_method = CDDA_BPC_SINGLE;
goto retry;
}
/*
* so we have an io error of some sort with multi frame dma. if the
* condition wasn't a hardware error
* problems, not for any error
*/
if (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b)
return ret;
pr_info("dropping to old style cdda (sense=%x)\n", cdi->last_sense);
cdi->cdda_method = CDDA_OLD;
return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);
}
static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_multisession ms_info;
u8 requested_format;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMMULTISESSION\n");
if (!(cdi->ops->capability & CDC_MULTI_SESSION))
return -ENOSYS;
if (copy_from_user(&ms_info, argp, sizeof(ms_info)))
return -EFAULT;
requested_format = ms_info.addr_format;
if (requested_format != CDROM_MSF && requested_format != CDROM_LBA)
return -EINVAL;
ms_info.addr_format = CDROM_LBA;
ret = cdi->ops->get_last_session(cdi, &ms_info);
if (ret)
return ret;
sanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format);
if (copy_to_user(argp, &ms_info, sizeof(ms_info)))
return -EFAULT;
cd_dbg(CD_DO_IOCTL, "CDROMMULTISESSION successful\n");
return 0;
}
static int cdrom_ioctl_eject(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT\n");
if (!CDROM_CAN(CDC_OPEN_TRAY))
return -ENOSYS;
if (cdi->use_count != 1 || cdi->keeplocked)
return -EBUSY;
if (CDROM_CAN(CDC_LOCK)) {
int ret = cdi->ops->lock_door(cdi, 0);
if (ret)
return ret;
}
return cdi->ops->tray_move(cdi, 1);
}
static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n");
if (!CDROM_CAN(CDC_CLOSE_TRAY))
return -ENOSYS;
return cdi->ops->tray_move(cdi, 0);
}
static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT_SW\n");
if (!CDROM_CAN(CDC_OPEN_TRAY))
return -ENOSYS;
if (cdi->keeplocked)
return -EBUSY;
cdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT);
if (arg)
cdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT;
return 0;
}
static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,
unsigned long arg)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n");
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return -ENOSYS;
/* cannot select disc or select current disc */
if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)
return media_changed(cdi, 1);
if (arg >= cdi->capacity)
return -EINVAL;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
ret = cdrom_read_mech_status(cdi, info);
if (!ret)
ret = info->slots[arg].change;
kfree(info);
return ret;
}
static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SET_OPTIONS\n");
/*
* Options need to be in sync with capability.
* Too late for that, so we have to check each one separately.
*/
switch (arg) {
case CDO_USE_FFLAGS:
case CDO_CHECK_TYPE:
break;
case CDO_LOCK:
if (!CDROM_CAN(CDC_LOCK))
return -ENOSYS;
break;
case 0:
return cdi->options;
/* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */
default:
if (!CDROM_CAN(arg))
return -ENOSYS;
}
cdi->options |= (int) arg;
return cdi->options;
}
static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_CLEAR_OPTIONS\n");
cdi->options &= ~(int) arg;
return cdi->options;
}
static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_SPEED\n");
if (!CDROM_CAN(CDC_SELECT_SPEED))
return -ENOSYS;
return cdi->ops->select_speed(cdi, arg);
}
static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -ENOSYS;
if (arg != CDSL_CURRENT && arg != CDSL_NONE) {
if ((int)arg >= cdi->capacity)
return -EINVAL;
}
/*
* ->select_disc is a hook to allow a driver-specific way of
* seleting disc. However, since there is no equivalent hook for
* cdrom_slot_status this may not actually be useful...
*/
if (cdi->ops->select_disc)
return cdi->ops->select_disc(cdi, arg);
cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n");
return cdrom_select_disc(cdi, arg);
}
static int cdrom_ioctl_reset(struct cdrom_device_info *cdi,
struct block_device *bdev)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_RESET\n");
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (!CDROM_CAN(CDC_RESET))
return -ENOSYS;
invalidate_bdev(bdev);
return cdi->ops->reset(cdi);
}
static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "%socking door\n", arg ? "L" : "Unl");
if (!CDROM_CAN(CDC_LOCK))
return -EDRIVE_CANT_DO_THIS;
cdi->keeplocked = arg ? 1 : 0;
/*
* Don't unlock the door on multiple opens by default, but allow
* root to do so.
*/
if (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN))
return -EBUSY;
return cdi->ops->lock_door(cdi, arg);
}
static int cdrom_ioctl_debug(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "%sabling debug\n", arg ? "En" : "Dis");
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
debug = arg ? 1 : 0;
return debug;
}
static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_CAPABILITY\n");
return (cdi->ops->capability & ~cdi->mask);
}
/*
* The following function is implemented, although very few audio
* discs give Universal Product Code information, which should just be
* the Medium Catalog Number on the box. Note, that the way the code
* is written on the CD is /not/ uniform across all discs!
*/
static int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_mcn mcn;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_MCN\n");
if (!(cdi->ops->capability & CDC_MCN))
return -ENOSYS;
ret = cdi->ops->get_mcn(cdi, &mcn);
if (ret)
return ret;
if (copy_to_user(argp, &mcn, sizeof(mcn)))
return -EFAULT;
cd_dbg(CD_DO_IOCTL, "CDROM_GET_MCN successful\n");
return 0;
}
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n");
if (!(cdi->ops->capability & CDC_DRIVE_STATUS))
return -ENOSYS;
if (!CDROM_CAN(CDC_SELECT_DISC) ||
(arg == CDSL_CURRENT || arg == CDSL_NONE))
return cdi->ops->drive_status(cdi, CDSL_CURRENT);
if (((int)arg >= cdi->capacity))
return -EINVAL;
return cdrom_slot_status(cdi, arg);
}
/*
* Ok, this is where problems start. The current interface for the
* CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that
* CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this
* is often the case, it is also very common for CDs to have some tracks
* with data, and some tracks with audio. Just because I feel like it,
* I declare the following to be the best way to cope. If the CD has ANY
* data tracks on it, it will be returned as a data CD. If it has any XA
* tracks, I will return it as that. Now I could simplify this interface
* by combining these returns with the above, but this more clearly
* demonstrates the problem with the current interface. Too bad this
* wasn't designed to use bitmasks... -Erik
*
* Well, now we have the option CDS_MIXED: a mixed-type CD.
* User level programmers might feel the ioctl is not very useful.
* ---david
*/
static int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi)
{
tracktype tracks;
cd_dbg(CD_DO_IOCTL, "entering CDROM_DISC_STATUS\n");
cdrom_count_tracks(cdi, &tracks);
if (tracks.error)
return tracks.error;
/* Policy mode on */
if (tracks.audio > 0) {
if (!tracks.data && !tracks.cdi && !tracks.xa)
return CDS_AUDIO;
else
return CDS_MIXED;
}
if (tracks.cdi > 0)
return CDS_XA_2_2;
if (tracks.xa > 0)
return CDS_XA_2_1;
if (tracks.data > 0)
return CDS_DATA_1;
/* Policy mode off */
cd_dbg(CD_WARNING, "This disc doesn't have any tracks I recognize!\n");
return CDS_NO_INFO;
}
static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n");
return cdi->capacity;
}
static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_subchnl q;
u8 requested, back;
int ret;
/* cd_dbg(CD_DO_IOCTL,"entering CDROMSUBCHNL\n");*/
if (copy_from_user(&q, argp, sizeof(q)))
return -EFAULT;
requested = q.cdsc_format;
if (requested != CDROM_MSF && requested != CDROM_LBA)
return -EINVAL;
q.cdsc_format = CDROM_MSF;
ret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q);
if (ret)
return ret;
back = q.cdsc_format; /* local copy */
sanitize_format(&q.cdsc_absaddr, &back, requested);
sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
if (copy_to_user(argp, &q, sizeof(q)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */
return 0;
}
static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_tochdr header;
int ret;
/* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCHDR\n"); */
if (copy_from_user(&header, argp, sizeof(header)))
return -EFAULT;
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);
if (ret)
return ret;
if (copy_to_user(argp, &header, sizeof(header)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCHDR successful\n"); */
return 0;
}
static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_tocentry entry;
u8 requested_format;
int ret;
/* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCENTRY\n"); */
if (copy_from_user(&entry, argp, sizeof(entry)))
return -EFAULT;
requested_format = entry.cdte_format;
if (requested_format != CDROM_MSF && requested_format != CDROM_LBA)
return -EINVAL;
/* make interface to low-level uniform */
entry.cdte_format = CDROM_MSF;
ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry);
if (ret)
return ret;
sanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format);
if (copy_to_user(argp, &entry, sizeof(entry)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCENTRY successful\n"); */
return 0;
}
static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_msf msf;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&msf, argp, sizeof(msf)))
return -EFAULT;
return cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf);
}
static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_ti ti;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYTRKIND\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&ti, argp, sizeof(ti)))
return -EFAULT;
ret = check_for_audio_disc(cdi, cdi->ops);
if (ret)
return ret;
return cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti);
}
static int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_volctrl volume;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLCTRL\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
if (copy_from_user(&volume, argp, sizeof(volume)))
return -EFAULT;
return cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume);
}
static int cdrom_ioctl_volread(struct cdrom_device_info *cdi,
void __user *argp)
{
struct cdrom_volctrl volume;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLREAD\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
ret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume);
if (ret)
return ret;
if (copy_to_user(argp, &volume, sizeof(volume)))
return -EFAULT;
return 0;
}
static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi,
unsigned int cmd)
{
int ret;
cd_dbg(CD_DO_IOCTL, "doing audio ioctl (start/stop/pause/resume)\n");
if (!CDROM_CAN(CDC_PLAY_AUDIO))
return -ENOSYS;
ret = check_for_audio_disc(cdi, cdi->ops);
if (ret)
return ret;
return cdi->ops->audio_ioctl(cdi, cmd, NULL);
}
/*
* Required when we need to use READ_10 to issue other than 2048 block
* reads
*/
static int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
struct modesel_head mh;
memset(&mh, 0, sizeof(mh));
mh.block_desc_length = 0x08;
mh.block_length_med = (size >> 8) & 0xff;
mh.block_length_lo = size & 0xff;
memset(&cgc, 0, sizeof(cgc));
cgc.cmd[0] = 0x15;
cgc.cmd[1] = 1 << 4;
cgc.cmd[4] = 12;
cgc.buflen = sizeof(mh);
cgc.buffer = (char *) &mh;
cgc.data_direction = CGC_DATA_WRITE;
mh.block_desc_length = 0x08;
mh.block_length_med = (size >> 8) & 0xff;
mh.block_length_lo = size & 0xff;
return cdo->generic_packet(cdi, &cgc);
}
static int cdrom_get_track_info(struct cdrom_device_info *cdi,
__u16 track, __u8 type, track_information *ti)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct packet_command cgc;
int ret, buflen;
init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
cgc.cmd[1] = type & 3;
cgc.cmd[4] = (track & 0xff00) >> 8;
cgc.cmd[5] = track & 0xff;
cgc.cmd[8] = 8;
cgc.quiet = 1;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
buflen = be16_to_cpu(ti->track_information_length) +
sizeof(ti->track_information_length);
if (buflen > sizeof(track_information))
buflen = sizeof(track_information);
cgc.cmd[8] = cgc.buflen = buflen;
ret = cdo->generic_packet(cdi, &cgc);
if (ret)
return ret;
/* return actual fill size */
return buflen;
}
/* return the last written block on the CD-R media. this is for the udf
file system. */
int cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written)
{
struct cdrom_tocentry toc;
disc_information di;
track_information ti;
__u32 last_track;
int ret = -1, ti_size;
if (!CDROM_CAN(CDC_GENERIC_PACKET))
goto use_toc;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < (int)(offsetof(typeof(di), last_track_lsb)
+ sizeof(di.last_track_lsb)))
goto use_toc;
/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
last_track = (di.last_track_msb << 8) | di.last_track_lsb;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < (int)offsetof(typeof(ti), track_start))
goto use_toc;
/* if this track is blank, try the previous. */
if (ti.blank) {
if (last_track == 1)
goto use_toc;
last_track--;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
}
if (ti_size < (int)(offsetof(typeof(ti), track_size)
+ sizeof(ti.track_size)))
goto use_toc;
/* if last recorded field is valid, return it. */
if (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address)
+ sizeof(ti.last_rec_address))) {
*last_written = be32_to_cpu(ti.last_rec_address);
} else {
/* make it up instead */
*last_written = be32_to_cpu(ti.track_start) +
be32_to_cpu(ti.track_size);
if (ti.free_blocks)
*last_written -= (be32_to_cpu(ti.free_blocks) + 7);
}
return 0;
/* this is where we end up if the drive either can't do a
GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if
it doesn't give enough information or fails. then we return
the toc contents. */
use_toc:
toc.cdte_format = CDROM_MSF;
toc.cdte_track = CDROM_LEADOUT;
if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc)))
return ret;
sanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA);
*last_written = toc.cdte_addr.lba;
return 0;
}
/* return the next writable block. also for udf file system. */
static int cdrom_get_next_writable(struct cdrom_device_info *cdi,
long *next_writable)
{
disc_information di;
track_information ti;
__u16 last_track;
int ret, ti_size;
if (!CDROM_CAN(CDC_GENERIC_PACKET))
goto use_last_written;
ret = cdrom_get_disc_info(cdi, &di);
if (ret < 0 || ret < offsetof(typeof(di), last_track_lsb)
+ sizeof(di.last_track_lsb))
goto use_last_written;
/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
last_track = (di.last_track_msb << 8) | di.last_track_lsb;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start))
goto use_last_written;
/* if this track is blank, try the previous. */
if (ti.blank) {
if (last_track == 1)
goto use_last_written;
last_track--;
ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
if (ti_size < 0)
goto use_last_written;
}
/* if next recordable address field is valid, use it. */
if (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable)
+ sizeof(ti.next_writable)) {
*next_writable = be32_to_cpu(ti.next_writable);
return 0;
}
use_last_written:
ret = cdrom_get_last_written(cdi, next_writable);
if (ret) {
*next_writable = 0;
return ret;
} else {
*next_writable += 7;
return 0;
}
}
static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc,
int cmd)
{
struct scsi_sense_hdr sshdr;
struct cdrom_msf msf;
int blocksize = 0, format = 0, lba;
int ret;
switch (cmd) {
case CDROMREADRAW:
blocksize = CD_FRAMESIZE_RAW;
break;
case CDROMREADMODE1:
blocksize = CD_FRAMESIZE;
format = 2;
break;
case CDROMREADMODE2:
blocksize = CD_FRAMESIZE_RAW0;
break;
}
if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))
return -EFAULT;
lba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0);
/* FIXME: we need upper bound checking, too!! */
if (lba < 0)
return -EINVAL;
cgc->buffer = kzalloc(blocksize, GFP_KERNEL);
if (cgc->buffer == NULL)
return -ENOMEM;
memset(&sshdr, 0, sizeof(sshdr));
cgc->sshdr = &sshdr;
cgc->data_direction = CGC_DATA_READ;
ret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize);
if (ret && sshdr.sense_key == 0x05 &&
sshdr.asc == 0x20 &&
sshdr.ascq == 0x00) {
/*
* SCSI-II devices are not required to support
* READ_CD, so let's try switching block size
*/
/* FIXME: switch back again... */
ret = cdrom_switch_blocksize(cdi, blocksize);
if (ret)
goto out;
cgc->sshdr = NULL;
ret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1);
ret |= cdrom_switch_blocksize(cdi, blocksize);
}
if (!ret && copy_to_user(arg, cgc->buffer, blocksize))
ret = -EFAULT;
out:
kfree(cgc->buffer);
return ret;
}
static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi,
void __user *arg)
{
struct cdrom_read_audio ra;
int lba;
if (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg,
sizeof(ra)))
return -EFAULT;
if (ra.addr_format == CDROM_MSF)
lba = msf_to_lba(ra.addr.msf.minute,
ra.addr.msf.second,
ra.addr.msf.frame);
else if (ra.addr_format == CDROM_LBA)
lba = ra.addr.lba;
else
return -EINVAL;
/* FIXME: we need upper bound checking, too!! */
if (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES)
return -EINVAL;
return cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes);
}
static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
struct cdrom_subchnl q;
u_char requested, back;
if (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q)))
return -EFAULT;
requested = q.cdsc_format;
if (!((requested == CDROM_MSF) ||
(requested == CDROM_LBA)))
return -EINVAL;
ret = cdrom_read_subchannel(cdi, &q, 0);
if (ret)
return ret;
back = q.cdsc_format; /* local copy */
sanitize_format(&q.cdsc_absaddr, &back, requested);
sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
if (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q)))
return -EFAULT;
/* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */
return 0;
}
static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct cdrom_msf msf;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))
return -EFAULT;
cgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF;
cgc->cmd[3] = msf.cdmsf_min0;
cgc->cmd[4] = msf.cdmsf_sec0;
cgc->cmd[5] = msf.cdmsf_frame0;
cgc->cmd[6] = msf.cdmsf_min1;
cgc->cmd[7] = msf.cdmsf_sec1;
cgc->cmd[8] = msf.cdmsf_frame1;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct cdrom_blk blk;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYBLK\n");
if (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk)))
return -EFAULT;
cgc->cmd[0] = GPCMD_PLAY_AUDIO_10;
cgc->cmd[2] = (blk.from >> 24) & 0xff;
cgc->cmd[3] = (blk.from >> 16) & 0xff;
cgc->cmd[4] = (blk.from >> 8) & 0xff;
cgc->cmd[5] = blk.from & 0xff;
cgc->cmd[7] = (blk.len >> 8) & 0xff;
cgc->cmd[8] = blk.len & 0xff;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc,
unsigned int cmd)
{
struct cdrom_volctrl volctrl;
unsigned char buffer[32];
char mask[sizeof(buffer)];
unsigned short offset;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROMVOLUME\n");
if (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg,
sizeof(volctrl)))
return -EFAULT;
cgc->buffer = buffer;
cgc->buflen = 24;
ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0);
if (ret)
return ret;
/* originally the code depended on buffer[1] to determine
how much data is available for transfer. buffer[1] is
unfortunately ambigious and the only reliable way seem
to be to simply skip over the block descriptor... */
offset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6));
if (offset + 16 > sizeof(buffer))
return -E2BIG;
if (offset + 16 > cgc->buflen) {
cgc->buflen = offset + 16;
ret = cdrom_mode_sense(cdi, cgc,
GPMODE_AUDIO_CTL_PAGE, 0);
if (ret)
return ret;
}
/* sanity check */
if ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE ||
buffer[offset + 1] < 14)
return -EINVAL;
/* now we have the current volume settings. if it was only
a CDROMVOLREAD, return these values */
if (cmd == CDROMVOLREAD) {
volctrl.channel0 = buffer[offset+9];
volctrl.channel1 = buffer[offset+11];
volctrl.channel2 = buffer[offset+13];
volctrl.channel3 = buffer[offset+15];
if (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl,
sizeof(volctrl)))
return -EFAULT;
return 0;
}
/* get the volume mask */
cgc->buffer = mask;
ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1);
if (ret)
return ret;
buffer[offset + 9] = volctrl.channel0 & mask[offset + 9];
buffer[offset + 11] = volctrl.channel1 & mask[offset + 11];
buffer[offset + 13] = volctrl.channel2 & mask[offset + 13];
buffer[offset + 15] = volctrl.channel3 & mask[offset + 15];
/* set volume */
cgc->buffer = buffer + offset - 8;
memset(cgc->buffer, 0, 8);
return cdrom_mode_select(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int cmd)
{
const struct cdrom_device_ops *cdo = cdi->ops;
cd_dbg(CD_DO_IOCTL, "entering CDROMSTART/CDROMSTOP\n");
cgc->cmd[0] = GPCMD_START_STOP_UNIT;
cgc->cmd[1] = 1;
cgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi,
struct packet_command *cgc,
int cmd)
{
const struct cdrom_device_ops *cdo = cdi->ops;
cd_dbg(CD_DO_IOCTL, "entering CDROMPAUSE/CDROMRESUME\n");
cgc->cmd[0] = GPCMD_PAUSE_RESUME;
cgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
int ret;
dvd_struct *s;
int size = sizeof(dvd_struct);
if (!CDROM_CAN(CDC_DVD))
return -ENOSYS;
s = memdup_user(arg, size);
if (IS_ERR(s))
return PTR_ERR(s);
cd_dbg(CD_DO_IOCTL, "entering DVD_READ_STRUCT\n");
ret = dvd_read_struct(cdi, s, cgc);
if (ret)
goto out;
if (copy_to_user(arg, s, size))
ret = -EFAULT;
out:
kfree(s);
return ret;
}
static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
dvd_authinfo ai;
if (!CDROM_CAN(CDC_DVD))
return -ENOSYS;
cd_dbg(CD_DO_IOCTL, "entering DVD_AUTH\n");
if (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai)))
return -EFAULT;
ret = dvd_do_auth(cdi, &ai);
if (ret)
return ret;
if (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai)))
return -EFAULT;
return 0;
}
static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
long next = 0;
cd_dbg(CD_DO_IOCTL, "entering CDROM_NEXT_WRITABLE\n");
ret = cdrom_get_next_writable(cdi, &next);
if (ret)
return ret;
if (copy_to_user((long __user *)arg, &next, sizeof(next)))
return -EFAULT;
return 0;
}
static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi,
void __user *arg)
{
int ret;
long last = 0;
cd_dbg(CD_DO_IOCTL, "entering CDROM_LAST_WRITTEN\n");
ret = cdrom_get_last_written(cdi, &last);
if (ret)
return ret;
if (copy_to_user((long __user *)arg, &last, sizeof(last)))
return -EFAULT;
return 0;
}
static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,
unsigned long arg)
{
struct packet_command cgc;
void __user *userptr = (void __user *)arg;
memset(&cgc, 0, sizeof(cgc));
/* build a unified command and queue it through
cdo->generic_packet() */
switch (cmd) {
case CDROMREADRAW:
case CDROMREADMODE1:
case CDROMREADMODE2:
return mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd);
case CDROMREADAUDIO:
return mmc_ioctl_cdrom_read_audio(cdi, userptr);
case CDROMSUBCHNL:
return mmc_ioctl_cdrom_subchannel(cdi, userptr);
case CDROMPLAYMSF:
return mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc);
case CDROMPLAYBLK:
return mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc);
case CDROMVOLCTRL:
case CDROMVOLREAD:
return mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd);
case CDROMSTART:
case CDROMSTOP:
return mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd);
case CDROMPAUSE:
case CDROMRESUME:
return mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd);
case DVD_READ_STRUCT:
return mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc);
case DVD_AUTH:
return mmc_ioctl_dvd_auth(cdi, userptr);
case CDROM_NEXT_WRITABLE:
return mmc_ioctl_cdrom_next_writable(cdi, userptr);
case CDROM_LAST_WRITTEN:
return mmc_ioctl_cdrom_last_written(cdi, userptr);
}
return -ENOTTY;
}
/*
* Just about every imaginable ioctl is supported in the Uniform layer
* these days.
* ATAPI / SCSI specific code now mainly resides in mmc_ioctl().
*/
int cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev,
fmode_t mode, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int ret;
/*
* Try the generic SCSI command ioctl's first.
*/
ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp);
if (ret != -ENOTTY)
return ret;
switch (cmd) {
case CDROMMULTISESSION:
return cdrom_ioctl_multisession(cdi, argp);
case CDROMEJECT:
return cdrom_ioctl_eject(cdi);
case CDROMCLOSETRAY:
return cdrom_ioctl_closetray(cdi);
case CDROMEJECT_SW:
return cdrom_ioctl_eject_sw(cdi, arg);
case CDROM_MEDIA_CHANGED:
return cdrom_ioctl_media_changed(cdi, arg);
case CDROM_SET_OPTIONS:
return cdrom_ioctl_set_options(cdi, arg);
case CDROM_CLEAR_OPTIONS:
return cdrom_ioctl_clear_options(cdi, arg);
case CDROM_SELECT_SPEED:
return cdrom_ioctl_select_speed(cdi, arg);
case CDROM_SELECT_DISC:
return cdrom_ioctl_select_disc(cdi, arg);
case CDROMRESET:
return cdrom_ioctl_reset(cdi, bdev);
case CDROM_LOCKDOOR:
return cdrom_ioctl_lock_door(cdi, arg);
case CDROM_DEBUG:
return cdrom_ioctl_debug(cdi, arg);
case CDROM_GET_CAPABILITY:
return cdrom_ioctl_get_capability(cdi);
case CDROM_GET_MCN:
return cdrom_ioctl_get_mcn(cdi, argp);
case CDROM_DRIVE_STATUS:
return cdrom_ioctl_drive_status(cdi, arg);
case CDROM_DISC_STATUS:
return cdrom_ioctl_disc_status(cdi);
case CDROM_CHANGER_NSLOTS:
return cdrom_ioctl_changer_nslots(cdi);
}
/*
* Use the ioctls that are implemented through the generic_packet()
* interface. this may look at bit funny, but if -ENOTTY is
* returned that particular ioctl is not implemented and we
* let it go through the device specific ones.
*/
if (CDROM_CAN(CDC_GENERIC_PACKET)) {
ret = mmc_ioctl(cdi, cmd, arg);
if (ret != -ENOTTY)
return ret;
}
/*
* Note: most of the cd_dbg() calls are commented out here,
* because they fill up the sys log when CD players poll
* the drive.
*/
switch (cmd) {
case CDROMSUBCHNL:
return cdrom_ioctl_get_subchnl(cdi, argp);
case CDROMREADTOCHDR:
return cdrom_ioctl_read_tochdr(cdi, argp);
case CDROMREADTOCENTRY:
return cdrom_ioctl_read_tocentry(cdi, argp);
case CDROMPLAYMSF:
return cdrom_ioctl_play_msf(cdi, argp);
case CDROMPLAYTRKIND:
return cdrom_ioctl_play_trkind(cdi, argp);
case CDROMVOLCTRL:
return cdrom_ioctl_volctrl(cdi, argp);
case CDROMVOLREAD:
return cdrom_ioctl_volread(cdi, argp);
case CDROMSTART:
case CDROMSTOP:
case CDROMPAUSE:
case CDROMRESUME:
return cdrom_ioctl_audioctl(cdi, cmd);
}
return -ENOSYS;
}
EXPORT_SYMBOL(cdrom_get_last_written);
EXPORT_SYMBOL(register_cdrom);
EXPORT_SYMBOL(unregister_cdrom);
EXPORT_SYMBOL(cdrom_open);
EXPORT_SYMBOL(cdrom_release);
EXPORT_SYMBOL(cdrom_ioctl);
EXPORT_SYMBOL(cdrom_media_changed);
EXPORT_SYMBOL(cdrom_number_of_slots);
EXPORT_SYMBOL(cdrom_mode_select);
EXPORT_SYMBOL(cdrom_mode_sense);
EXPORT_SYMBOL(init_cdrom_command);
EXPORT_SYMBOL(cdrom_get_media_event);
#ifdef CONFIG_SYSCTL
#define CDROM_STR_SIZE 1000
static struct cdrom_sysctl_settings {
char info[CDROM_STR_SIZE]; /* general info */
int autoclose; /* close tray upon mount, etc */
int autoeject; /* eject on umount */
int debug; /* turn on debugging messages */
int lock; /* lock the door on device open */
int check; /* check media type */
} cdrom_sysctl_settings;
enum cdrom_print_option {
CTL_NAME,
CTL_SPEED,
CTL_SLOTS,
CTL_CAPABILITY
};
static int cdrom_print_info(const char *header, int val, char *info,
int *pos, enum cdrom_print_option option)
{
const int max_size = sizeof(cdrom_sysctl_settings.info);
struct cdrom_device_info *cdi;
int ret;
ret = scnprintf(info + *pos, max_size - *pos, header);
if (!ret)
return 1;
*pos += ret;
list_for_each_entry(cdi, &cdrom_list, list) {
switch (option) {
case CTL_NAME:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%s", cdi->name);
break;
case CTL_SPEED:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", cdi->speed);
break;
case CTL_SLOTS:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", cdi->capacity);
break;
case CTL_CAPABILITY:
ret = scnprintf(info + *pos, max_size - *pos,
"\t%d", CDROM_CAN(val) != 0);
break;
default:
pr_info("invalid option%d\n", option);
return 1;
}
if (!ret)
return 1;
*pos += ret;
}
return 0;
}
static int cdrom_sysctl_info(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int pos;
char *info = cdrom_sysctl_settings.info;
const int max_size = sizeof(cdrom_sysctl_settings.info);
if (!*lenp || (*ppos && !write)) {
*lenp = 0;
return 0;
}
mutex_lock(&cdrom_mutex);
pos = sprintf(info, "CD-ROM information, " VERSION "\n");
if (cdrom_print_info("\ndrive name:\t", 0, info, &pos, CTL_NAME))
goto done;
if (cdrom_print_info("\ndrive speed:\t", 0, info, &pos, CTL_SPEED))
goto done;
if (cdrom_print_info("\ndrive # of slots:", 0, info, &pos, CTL_SLOTS))
goto done;
if (cdrom_print_info("\nCan close tray:\t",
CDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan open tray:\t",
CDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan lock tray:\t",
CDC_LOCK, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan change speed:",
CDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan select disk:",
CDC_SELECT_DISC, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read multisession:",
CDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read MCN:\t",
CDC_MCN, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nReports media changed:",
CDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan play audio:\t",
CDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write CD-R:\t",
CDC_CD_R, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write CD-RW:",
CDC_CD_RW, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read DVD:\t",
CDC_DVD, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write DVD-R:",
CDC_DVD_R, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write DVD-RAM:",
CDC_DVD_RAM, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan read MRW:\t",
CDC_MRW, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write MRW:\t",
CDC_MRW_W, info, &pos, CTL_CAPABILITY))
goto done;
if (cdrom_print_info("\nCan write RAM:\t",
CDC_RAM, info, &pos, CTL_CAPABILITY))
goto done;
if (!scnprintf(info + pos, max_size - pos, "\n\n"))
goto done;
doit:
mutex_unlock(&cdrom_mutex);
return proc_dostring(ctl, write, buffer, lenp, ppos);
done:
pr_info("info buffer too small\n");
goto doit;
}
/* Unfortunately, per device settings are not implemented through
procfs/sysctl yet. When they are, this will naturally disappear. For now
just update all drives. Later this will become the template on which
new registered drives will be based. */
static void cdrom_update_settings(void)
{
struct cdrom_device_info *cdi;
mutex_lock(&cdrom_mutex);
list_for_each_entry(cdi, &cdrom_list, list) {
if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY))
cdi->options |= CDO_AUTO_CLOSE;
else if (!autoclose)
cdi->options &= ~CDO_AUTO_CLOSE;
if (autoeject && CDROM_CAN(CDC_OPEN_TRAY))
cdi->options |= CDO_AUTO_EJECT;
else if (!autoeject)
cdi->options &= ~CDO_AUTO_EJECT;
if (lockdoor && CDROM_CAN(CDC_LOCK))
cdi->options |= CDO_LOCK;
else if (!lockdoor)
cdi->options &= ~CDO_LOCK;
if (check_media_type)
cdi->options |= CDO_CHECK_TYPE;
else
cdi->options &= ~CDO_CHECK_TYPE;
}
mutex_unlock(&cdrom_mutex);
}
static int cdrom_sysctl_handler(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int ret;
ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
if (write) {
/* we only care for 1 or 0. */
autoclose = !!cdrom_sysctl_settings.autoclose;
autoeject = !!cdrom_sysctl_settings.autoeject;
debug = !!cdrom_sysctl_settings.debug;
lockdoor = !!cdrom_sysctl_settings.lock;
check_media_type = !!cdrom_sysctl_settings.check;
/* update the option flags according to the changes. we
don't have per device options through sysctl yet,
but we will have and then this will disappear. */
cdrom_update_settings();
}
return ret;
}
/* Place files in /proc/sys/dev/cdrom */
static struct ctl_table cdrom_table[] = {
{
.procname = "info",
.data = &cdrom_sysctl_settings.info,
.maxlen = CDROM_STR_SIZE,
.mode = 0444,
.proc_handler = cdrom_sysctl_info,
},
{
.procname = "autoclose",
.data = &cdrom_sysctl_settings.autoclose,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "autoeject",
.data = &cdrom_sysctl_settings.autoeject,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "debug",
.data = &cdrom_sysctl_settings.debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "lock",
.data = &cdrom_sysctl_settings.lock,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler,
},
{
.procname = "check_media",
.data = &cdrom_sysctl_settings.check,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = cdrom_sysctl_handler
},
{ }
};
static struct ctl_table cdrom_cdrom_table[] = {
{
.procname = "cdrom",
.maxlen = 0,
.mode = 0555,
.child = cdrom_table,
},
{ }
};
/* Make sure that /proc/sys/dev is there */
static struct ctl_table cdrom_root_table[] = {
{
.procname = "dev",
.maxlen = 0,
.mode = 0555,
.child = cdrom_cdrom_table,
},
{ }
};
static struct ctl_table_header *cdrom_sysctl_header;
static void cdrom_sysctl_register(void)
{
static int initialized;
if (initialized == 1)
return;
cdrom_sysctl_header = register_sysctl_table(cdrom_root_table);
/* set the defaults */
cdrom_sysctl_settings.autoclose = autoclose;
cdrom_sysctl_settings.autoeject = autoeject;
cdrom_sysctl_settings.debug = debug;
cdrom_sysctl_settings.lock = lockdoor;
cdrom_sysctl_settings.check = check_media_type;
initialized = 1;
}
static void cdrom_sysctl_unregister(void)
{
if (cdrom_sysctl_header)
unregister_sysctl_table(cdrom_sysctl_header);
}
#else /* CONFIG_SYSCTL */
static void cdrom_sysctl_register(void)
{
}
static void cdrom_sysctl_unregister(void)
{
}
#endif /* CONFIG_SYSCTL */
static int __init cdrom_init(void)
{
cdrom_sysctl_register();
return 0;
}
static void __exit cdrom_exit(void)
{
pr_info("Uniform CD-ROM driver unloaded\n");
cdrom_sysctl_unregister();
}
module_init(cdrom_init);
module_exit(cdrom_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_368_0 |
crossvul-cpp_data_good_1405_1 | /* tracked memory
*
* 2/11/99 JC
* - from im_open.c and callback.c
* - malloc tracking stuff added
* 11/3/01 JC
* - im_strncpy() added
* 20/4/01 JC
* - im_(v)snprintf() added
* 6/7/05
* - more tracking for DEBUGM
* 20/10/06
* - return NULL for size <= 0
* 11/5/06
* - abort() on malloc() failure with DEBUG
* 20/10/09
* - gtkdoc comment
* 6/11/09
* - im_malloc()/im_free() now call g_try_malloc()/g_free() ... removes
* confusion over whether to use im_free() or g_free() for things like
* im_header_string()
* 21/9/11
* - rename as vips_tracked_malloc() to emphasise difference from
* g_malloc()/g_free()
*/
/*
This file is part of VIPS.
VIPS is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_IO_H
#include <io.h>
#endif /*HAVE_IO_H*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <vips/vips.h>
#include <vips/thread.h>
/**
* SECTION: memory
* @short_description: memory utilities
* @stability: Stable
* @include: vips/vips.h
*
* These functions cover two main areas.
*
* First, some simple utility functions over the underlying
* g_malloc()/g_free() functions. Memory allocated and freeded using these
* functions is interchangeable with any other glib library.
*
* Second, a pair of functions, vips_tracked_malloc() and vips_tracked_free(),
* which are NOT compatible. If you g_free() memory that has been allocated
* with vips_tracked_malloc() you will see crashes.
*
* The tracked functions are
* only suitable for large allocations internal to the library, for example
* pixel buffers. libvips watches the total amount of live tracked memory and
* uses this information to decide when to trim caches.
*/
/* g_assert_not_reached() on memory errors.
#define DEBUG
*/
/* Track malloc/free and open/close.
#define DEBUG_VERBOSE
*/
#ifdef DEBUG
# warning DEBUG on in libsrc/iofuncs/memory.c
#endif /*DEBUG*/
static int vips_tracked_allocs = 0;
static size_t vips_tracked_mem = 0;
static int vips_tracked_files = 0;
static size_t vips_tracked_mem_highwater = 0;
static GMutex *vips_tracked_mutex = NULL;
/**
* VIPS_NEW:
* @OBJ: allocate memory local to @OBJ, or %NULL for no auto-free
* @T: type of thing to allocate
*
* Allocate memory for a thing of type @T. The memory is not
* cleared.
*
* This macro cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_malloc().
*
* Returns: A pointer of type @T *.
*/
/**
* VIPS_ARRAY:
* @OBJ: allocate memory local to @OBJ, or %NULL for no auto-free
* @N: number of @T 's to allocate
* @T: type of thing to allocate
*
* Allocate memory for an array of objects of type @T. The memory is not
* cleared.
*
* This macro cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_malloc().
*
* Returns: A pointer of type @T *.
*/
static void
vips_malloc_cb( VipsObject *object, char *buf )
{
g_free( buf );
}
/**
* vips_malloc:
* @object: (nullable): allocate memory local to this #VipsObject, or %NULL
* @size: number of bytes to allocate
*
* g_malloc() local to @object, that is, the memory will be automatically
* freed for you when the object is closed. If @object is %NULL, you need to
* free the memory explicitly with g_free().
*
* This function cannot fail. See vips_tracked_malloc() if you are
* allocating large amounts of memory.
*
* See also: vips_tracked_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory.
*/
void *
vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc0( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
/**
* vips_strdup:
* @object: (nullable): allocate memory local to this #VipsObject, or %NULL
* @str: string to copy
*
* g_strdup() a string. When @object is freed, the string will be freed for
* you. If @object is %NULL, you need to
* free the memory yourself with g_free().
*
* This function cannot fail.
*
* See also: vips_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory
*/
char *
vips_strdup( VipsObject *object, const char *str )
{
char *str_dup;
str_dup = g_strdup( str );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), str_dup );
object->local_memory += strlen( str );
}
return( str_dup );
}
/**
* vips_free:
* @buf: memory to free
*
* Frees memory with g_free() and returns 0. Handy for callbacks.
*
* See also: vips_malloc().
*
* Returns: 0
*/
int
vips_free( void *buf )
{
g_free( buf );
return( 0 );
}
/**
* vips_tracked_free:
* @s: (transfer full): memory to free
*
* Only use it to free
* memory that was previously allocated with vips_tracked_malloc() with a
* %NULL first argument.
*
* See also: vips_tracked_malloc().
*/
void
vips_tracked_free( void *s )
{
/* Keep the size of the alloc in the previous 16 bytes. Ensures
* alignment rules are kept.
*/
void *start = (void *) ((char *) s - 16);
size_t size = *((size_t *) start);
g_mutex_lock( vips_tracked_mutex );
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_free: %p, %zd bytes\n", s, size );
#endif /*DEBUG_VERBOSE*/
if( vips_tracked_allocs <= 0 )
g_warning( "%s", _( "vips_free: too many frees" ) );
if( vips_tracked_mem < size )
g_warning( "%s", _( "vips_free: too much free" ) );
vips_tracked_mem -= size;
vips_tracked_allocs -= 1;
g_mutex_unlock( vips_tracked_mutex );
g_free( start );
VIPS_GATE_FREE( size );
}
static void
vips_tracked_init_mutex( void )
{
vips_tracked_mutex = vips_g_mutex_new();
}
static void
vips_tracked_init( void )
{
static GOnce vips_tracked_once = G_ONCE_INIT;
VIPS_ONCE( &vips_tracked_once,
(GThreadFunc) vips_tracked_init_mutex, NULL );
}
/**
* vips_tracked_malloc:
* @size: number of bytes to allocate
*
* Allocate an area of memory that will be tracked by vips_tracked_get_mem()
* and friends.
*
* If allocation fails, vips_malloc() returns %NULL and
* sets an error message.
*
* You must only free the memory returned with vips_tracked_free().
*
* See also: vips_tracked_free(), vips_malloc().
*
* Returns: (transfer full): a pointer to the allocated memory, or %NULL on error.
*/
void *
vips_tracked_malloc( size_t size )
{
void *buf;
vips_tracked_init();
/* Need an extra sizeof(size_t) bytes to track
* size of this block. Ask for an extra 16 to make sure we don't break
* alignment rules.
*/
size += 16;
if( !(buf = g_try_malloc0( size )) ) {
#ifdef DEBUG
g_assert_not_reached();
#endif /*DEBUG*/
vips_error( "vips_tracked",
_( "out of memory --- size == %dMB" ),
(int) (size / (1024.0 * 1024.0)) );
g_warning( _( "out of memory --- size == %dMB" ),
(int) (size / (1024.0 * 1024.0)) );
return( NULL );
}
g_mutex_lock( vips_tracked_mutex );
*((size_t *)buf) = size;
buf = (void *) ((char *)buf + 16);
vips_tracked_mem += size;
if( vips_tracked_mem > vips_tracked_mem_highwater )
vips_tracked_mem_highwater = vips_tracked_mem;
vips_tracked_allocs += 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_malloc: %p, %zd bytes\n", buf, size );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
VIPS_GATE_MALLOC( size );
return( buf );
}
/**
* vips_tracked_open:
* @pathname: name of file to open
* @flags: flags for open()
* @...: open mode
*
* Exactly as open(2), but the number of files current open via
* vips_tracked_open() is available via vips_tracked_get_files(). This is used
* by the vips operation cache to drop cache when the number of files
* available is low.
*
* You must only close the file descriptor with vips_tracked_close().
*
* See also: vips_tracked_close(), vips_tracked_get_files().
*
* Returns: a file descriptor, or -1 on error.
*/
int
vips_tracked_open( const char *pathname, int flags, ... )
{
int fd;
mode_t mode;
va_list ap;
/* mode_t is promoted to int in ..., so we have to pull it out as an
* int.
*/
va_start( ap, flags );
mode = va_arg( ap, int );
va_end( ap );
if( (fd = vips__open( pathname, flags, mode )) == -1 )
return( -1 );
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
vips_tracked_files += 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_open: %s = %d (%d)\n",
pathname, fd, vips_tracked_files );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
return( fd );
}
/**
* vips_tracked_close:
* @fd: file to close()
*
* Exactly as close(2), but update the number of files currently open via
* vips_tracked_get_files(). This is used
* by the vips operation cache to drop cache when the number of files
* available is low.
*
* You must only close file descriptors opened with vips_tracked_open().
*
* See also: vips_tracked_open(), vips_tracked_get_files().
*
* Returns: a file descriptor, or -1 on error.
*/
int
vips_tracked_close( int fd )
{
int result;
g_mutex_lock( vips_tracked_mutex );
g_assert( vips_tracked_files > 0 );
vips_tracked_files -= 1;
#ifdef DEBUG_VERBOSE
printf( "vips_tracked_close: %d (%d)\n", fd, vips_tracked_files );
#endif /*DEBUG_VERBOSE*/
g_mutex_unlock( vips_tracked_mutex );
result = close( fd );
return( result );
}
/**
* vips_tracked_get_mem:
*
* Returns the number of bytes currently allocated via vips_malloc() and
* friends. vips uses this figure to decide when to start dropping cache, see
* #VipsOperation.
*
* Returns: the number of currently allocated bytes
*/
size_t
vips_tracked_get_mem( void )
{
size_t mem;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
mem = vips_tracked_mem;
g_mutex_unlock( vips_tracked_mutex );
return( mem );
}
/**
* vips_tracked_get_mem_highwater:
*
* Returns the largest number of bytes simultaneously allocated via
* vips_tracked_malloc(). Handy for estimating max memory requirements for a
* program.
*
* Returns: the largest number of currently allocated bytes
*/
size_t
vips_tracked_get_mem_highwater( void )
{
size_t mx;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
mx = vips_tracked_mem_highwater;
g_mutex_unlock( vips_tracked_mutex );
return( mx );
}
/**
* vips_tracked_get_allocs:
*
* Returns the number of active allocations.
*
* Returns: the number of active allocations
*/
int
vips_tracked_get_allocs( void )
{
int n;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
n = vips_tracked_allocs;
g_mutex_unlock( vips_tracked_mutex );
return( n );
}
/**
* vips_tracked_get_files:
*
* Returns the number of open files.
*
* Returns: the number of open files
*/
int
vips_tracked_get_files( void )
{
int n;
vips_tracked_init();
g_mutex_lock( vips_tracked_mutex );
n = vips_tracked_files;
g_mutex_unlock( vips_tracked_mutex );
return( n );
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1405_1 |
crossvul-cpp_data_good_4240_0 | /*
* random.c -- A strong random number generator
*
* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All
* Rights Reserved.
*
* Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
*
* Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. 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, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* ALTERNATIVELY, this product may be distributed under the terms of
* the GNU General Public License, in which case the provisions of the GPL are
* required INSTEAD OF the above restrictions. (This clause is
* necessary due to a potential bad interaction between the GPL and
* the restrictions contained in a BSD-style copyright.)
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*
* (now, with legal B.S. out of the way.....)
*
* This routine gathers environmental noise from device drivers, etc.,
* and returns good random numbers, suitable for cryptographic use.
* Besides the obvious cryptographic uses, these numbers are also good
* for seeding TCP sequence numbers, and other places where it is
* desirable to have numbers which are not only random, but hard to
* predict by an attacker.
*
* Theory of operation
* ===================
*
* Computers are very predictable devices. Hence it is extremely hard
* to produce truly random numbers on a computer --- as opposed to
* pseudo-random numbers, which can easily generated by using a
* algorithm. Unfortunately, it is very easy for attackers to guess
* the sequence of pseudo-random number generators, and for some
* applications this is not acceptable. So instead, we must try to
* gather "environmental noise" from the computer's environment, which
* must be hard for outside attackers to observe, and use that to
* generate random numbers. In a Unix environment, this is best done
* from inside the kernel.
*
* Sources of randomness from the environment include inter-keyboard
* timings, inter-interrupt timings from some interrupts, and other
* events which are both (a) non-deterministic and (b) hard for an
* outside observer to measure. Randomness from these sources are
* added to an "entropy pool", which is mixed using a CRC-like function.
* This is not cryptographically strong, but it is adequate assuming
* the randomness is not chosen maliciously, and it is fast enough that
* the overhead of doing it on every interrupt is very reasonable.
* As random bytes are mixed into the entropy pool, the routines keep
* an *estimate* of how many bits of randomness have been stored into
* the random number generator's internal state.
*
* When random bytes are desired, they are obtained by taking the SHA
* hash of the contents of the "entropy pool". The SHA hash avoids
* exposing the internal state of the entropy pool. It is believed to
* be computationally infeasible to derive any useful information
* about the input of SHA from its output. Even if it is possible to
* analyze SHA in some clever way, as long as the amount of data
* returned from the generator is less than the inherent entropy in
* the pool, the output data is totally unpredictable. For this
* reason, the routine decreases its internal estimate of how many
* bits of "true randomness" are contained in the entropy pool as it
* outputs random numbers.
*
* If this estimate goes to zero, the routine can still generate
* random numbers; however, an attacker may (at least in theory) be
* able to infer the future output of the generator from prior
* outputs. This requires successful cryptanalysis of SHA, which is
* not believed to be feasible, but there is a remote possibility.
* Nonetheless, these numbers should be useful for the vast majority
* of purposes.
*
* Exported interfaces ---- output
* ===============================
*
* There are four exported interfaces; two for use within the kernel,
* and two or use from userspace.
*
* Exported interfaces ---- userspace output
* -----------------------------------------
*
* The userspace interfaces are two character devices /dev/random and
* /dev/urandom. /dev/random is suitable for use when very high
* quality randomness is desired (for example, for key generation or
* one-time pads), as it will only return a maximum of the number of
* bits of randomness (as estimated by the random number generator)
* contained in the entropy pool.
*
* The /dev/urandom device does not have this limit, and will return
* as many bytes as are requested. As more and more random bytes are
* requested without giving time for the entropy pool to recharge,
* this will result in random numbers that are merely cryptographically
* strong. For many applications, however, this is acceptable.
*
* Exported interfaces ---- kernel output
* --------------------------------------
*
* The primary kernel interface is
*
* void get_random_bytes(void *buf, int nbytes);
*
* This interface will return the requested number of random bytes,
* and place it in the requested buffer. This is equivalent to a
* read from /dev/urandom.
*
* For less critical applications, there are the functions:
*
* u32 get_random_u32()
* u64 get_random_u64()
* unsigned int get_random_int()
* unsigned long get_random_long()
*
* These are produced by a cryptographic RNG seeded from get_random_bytes,
* and so do not deplete the entropy pool as much. These are recommended
* for most in-kernel operations *if the result is going to be stored in
* the kernel*.
*
* Specifically, the get_random_int() family do not attempt to do
* "anti-backtracking". If you capture the state of the kernel (e.g.
* by snapshotting the VM), you can figure out previous get_random_int()
* return values. But if the value is stored in the kernel anyway,
* this is not a problem.
*
* It *is* safe to expose get_random_int() output to attackers (e.g. as
* network cookies); given outputs 1..n, it's not feasible to predict
* outputs 0 or n+1. The only concern is an attacker who breaks into
* the kernel later; the get_random_int() engine is not reseeded as
* often as the get_random_bytes() one.
*
* get_random_bytes() is needed for keys that need to stay secret after
* they are erased from the kernel. For example, any key that will
* be wrapped and stored encrypted. And session encryption keys: we'd
* like to know that after the session is closed and the keys erased,
* the plaintext is unrecoverable to someone who recorded the ciphertext.
*
* But for network ports/cookies, stack canaries, PRNG seeds, address
* space layout randomization, session *authentication* keys, or other
* applications where the sensitive data is stored in the kernel in
* plaintext for as long as it's sensitive, the get_random_int() family
* is just fine.
*
* Consider ASLR. We want to keep the address space secret from an
* outside attacker while the process is running, but once the address
* space is torn down, it's of no use to an attacker any more. And it's
* stored in kernel data structures as long as it's alive, so worrying
* about an attacker's ability to extrapolate it from the get_random_int()
* CRNG is silly.
*
* Even some cryptographic keys are safe to generate with get_random_int().
* In particular, keys for SipHash are generally fine. Here, knowledge
* of the key authorizes you to do something to a kernel object (inject
* packets to a network connection, or flood a hash table), and the
* key is stored with the object being protected. Once it goes away,
* we no longer care if anyone knows the key.
*
* prandom_u32()
* -------------
*
* For even weaker applications, see the pseudorandom generator
* prandom_u32(), prandom_max(), and prandom_bytes(). If the random
* numbers aren't security-critical at all, these are *far* cheaper.
* Useful for self-tests, random error simulation, randomized backoffs,
* and any other application where you trust that nobody is trying to
* maliciously mess with you by guessing the "random" numbers.
*
* Exported interfaces ---- input
* ==============================
*
* The current exported interfaces for gathering environmental noise
* from the devices are:
*
* void add_device_randomness(const void *buf, unsigned int size);
* void add_input_randomness(unsigned int type, unsigned int code,
* unsigned int value);
* void add_interrupt_randomness(int irq, int irq_flags);
* void add_disk_randomness(struct gendisk *disk);
*
* add_device_randomness() is for adding data to the random pool that
* is likely to differ between two devices (or possibly even per boot).
* This would be things like MAC addresses or serial numbers, or the
* read-out of the RTC. This does *not* add any actual entropy to the
* pool, but it initializes the pool to different values for devices
* that might otherwise be identical and have very little entropy
* available to them (particularly common in the embedded world).
*
* add_input_randomness() uses the input layer interrupt timing, as well as
* the event type information from the hardware.
*
* add_interrupt_randomness() uses the interrupt timing as random
* inputs to the entropy pool. Using the cycle counters and the irq source
* as inputs, it feeds the randomness roughly once a second.
*
* add_disk_randomness() uses what amounts to the seek time of block
* layer request events, on a per-disk_devt basis, as input to the
* entropy pool. Note that high-speed solid state drives with very low
* seek times do not make for good sources of entropy, as their seek
* times are usually fairly consistent.
*
* All of these routines try to estimate how many bits of randomness a
* particular randomness source. They do this by keeping track of the
* first and second order deltas of the event timings.
*
* Ensuring unpredictability at system startup
* ============================================
*
* When any operating system starts up, it will go through a sequence
* of actions that are fairly predictable by an adversary, especially
* if the start-up does not involve interaction with a human operator.
* This reduces the actual number of bits of unpredictability in the
* entropy pool below the value in entropy_count. In order to
* counteract this effect, it helps to carry information in the
* entropy pool across shut-downs and start-ups. To do this, put the
* following lines an appropriate script which is run during the boot
* sequence:
*
* echo "Initializing random number generator..."
* random_seed=/var/run/random-seed
* # Carry a random seed from start-up to start-up
* # Load and then save the whole entropy pool
* if [ -f $random_seed ]; then
* cat $random_seed >/dev/urandom
* else
* touch $random_seed
* fi
* chmod 600 $random_seed
* dd if=/dev/urandom of=$random_seed count=1 bs=512
*
* and the following lines in an appropriate script which is run as
* the system is shutdown:
*
* # Carry a random seed from shut-down to start-up
* # Save the whole entropy pool
* echo "Saving random seed..."
* random_seed=/var/run/random-seed
* touch $random_seed
* chmod 600 $random_seed
* dd if=/dev/urandom of=$random_seed count=1 bs=512
*
* For example, on most modern systems using the System V init
* scripts, such code fragments would be found in
* /etc/rc.d/init.d/random. On older Linux systems, the correct script
* location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
*
* Effectively, these commands cause the contents of the entropy pool
* to be saved at shut-down time and reloaded into the entropy pool at
* start-up. (The 'dd' in the addition to the bootup script is to
* make sure that /etc/random-seed is different for every start-up,
* even if the system crashes without executing rc.0.) Even with
* complete knowledge of the start-up activities, predicting the state
* of the entropy pool requires knowledge of the previous history of
* the system.
*
* Configuring the /dev/random driver under Linux
* ==============================================
*
* The /dev/random driver under Linux uses minor numbers 8 and 9 of
* the /dev/mem major number (#1). So if your system does not have
* /dev/random and /dev/urandom created already, they can be created
* by using the commands:
*
* mknod /dev/random c 1 8
* mknod /dev/urandom c 1 9
*
* Acknowledgements:
* =================
*
* Ideas for constructing this random number generator were derived
* from Pretty Good Privacy's random number generator, and from private
* discussions with Phil Karn. Colin Plumb provided a faster random
* number generator, which speed up the mixing function of the entropy
* pool, taken from PGPfone. Dale Worley has also contributed many
* useful ideas and suggestions to improve this driver.
*
* Any flaws in the design are solely my responsibility, and should
* not be attributed to the Phil, Colin, or any of authors of PGP.
*
* Further background information on this topic may be obtained from
* RFC 1750, "Randomness Recommendations for Security", by Donald
* Eastlake, Steve Crocker, and Jeff Schiller.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/utsname.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/fcntl.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/nodemask.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/percpu.h>
#include <linux/fips.h>
#include <linux/ptrace.h>
#include <linux/workqueue.h>
#include <linux/irq.h>
#include <linux/ratelimit.h>
#include <linux/syscalls.h>
#include <linux/completion.h>
#include <linux/uuid.h>
#include <crypto/chacha.h>
#include <crypto/sha.h>
#include <asm/processor.h>
#include <linux/uaccess.h>
#include <asm/irq.h>
#include <asm/irq_regs.h>
#include <asm/io.h>
#define CREATE_TRACE_POINTS
#include <trace/events/random.h>
/* #define ADD_INTERRUPT_BENCH */
/*
* Configuration information
*/
#define INPUT_POOL_SHIFT 12
#define INPUT_POOL_WORDS (1 << (INPUT_POOL_SHIFT-5))
#define OUTPUT_POOL_SHIFT 10
#define OUTPUT_POOL_WORDS (1 << (OUTPUT_POOL_SHIFT-5))
#define EXTRACT_SIZE 10
#define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
/*
* To allow fractional bits to be tracked, the entropy_count field is
* denominated in units of 1/8th bits.
*
* 2*(ENTROPY_SHIFT + poolbitshift) must <= 31, or the multiply in
* credit_entropy_bits() needs to be 64 bits wide.
*/
#define ENTROPY_SHIFT 3
#define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
/*
* If the entropy count falls under this number of bits, then we
* should wake up processes which are selecting or polling on write
* access to /dev/random.
*/
static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
/*
* Originally, we used a primitive polynomial of degree .poolwords
* over GF(2). The taps for various sizes are defined below. They
* were chosen to be evenly spaced except for the last tap, which is 1
* to get the twisting happening as fast as possible.
*
* For the purposes of better mixing, we use the CRC-32 polynomial as
* well to make a (modified) twisted Generalized Feedback Shift
* Register. (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR
* generators. ACM Transactions on Modeling and Computer Simulation
* 2(3):179-194. Also see M. Matsumoto & Y. Kurita, 1994. Twisted
* GFSR generators II. ACM Transactions on Modeling and Computer
* Simulation 4:254-266)
*
* Thanks to Colin Plumb for suggesting this.
*
* The mixing operation is much less sensitive than the output hash,
* where we use SHA-1. All that we want of mixing operation is that
* it be a good non-cryptographic hash; i.e. it not produce collisions
* when fed "random" data of the sort we expect to see. As long as
* the pool state differs for different inputs, we have preserved the
* input entropy and done a good job. The fact that an intelligent
* attacker can construct inputs that will produce controlled
* alterations to the pool's state is not important because we don't
* consider such inputs to contribute any randomness. The only
* property we need with respect to them is that the attacker can't
* increase his/her knowledge of the pool's state. Since all
* additions are reversible (knowing the final state and the input,
* you can reconstruct the initial state), if an attacker has any
* uncertainty about the initial state, he/she can only shuffle that
* uncertainty about, but never cause any collisions (which would
* decrease the uncertainty).
*
* Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
* Videau in their paper, "The Linux Pseudorandom Number Generator
* Revisited" (see: http://eprint.iacr.org/2012/251.pdf). In their
* paper, they point out that we are not using a true Twisted GFSR,
* since Matsumoto & Kurita used a trinomial feedback polynomial (that
* is, with only three taps, instead of the six that we are using).
* As a result, the resulting polynomial is neither primitive nor
* irreducible, and hence does not have a maximal period over
* GF(2**32). They suggest a slight change to the generator
* polynomial which improves the resulting TGFSR polynomial to be
* irreducible, which we have made here.
*/
static const struct poolinfo {
int poolbitshift, poolwords, poolbytes, poolfracbits;
#define S(x) ilog2(x)+5, (x), (x)*4, (x) << (ENTROPY_SHIFT+5)
int tap1, tap2, tap3, tap4, tap5;
} poolinfo_table[] = {
/* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
/* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
{ S(128), 104, 76, 51, 25, 1 },
};
/*
* Static global variables
*/
static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
static struct fasync_struct *fasync;
static DEFINE_SPINLOCK(random_ready_list_lock);
static LIST_HEAD(random_ready_list);
struct crng_state {
__u32 state[16];
unsigned long init_time;
spinlock_t lock;
};
static struct crng_state primary_crng = {
.lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
};
/*
* crng_init = 0 --> Uninitialized
* 1 --> Initialized
* 2 --> Initialized from input_pool
*
* crng_init is protected by primary_crng->lock, and only increases
* its value (from 0->1->2).
*/
static int crng_init = 0;
#define crng_ready() (likely(crng_init > 1))
static int crng_init_cnt = 0;
static unsigned long crng_global_init_time = 0;
#define CRNG_INIT_CNT_THRESH (2*CHACHA_KEY_SIZE)
static void _extract_crng(struct crng_state *crng, __u8 out[CHACHA_BLOCK_SIZE]);
static void _crng_backtrack_protect(struct crng_state *crng,
__u8 tmp[CHACHA_BLOCK_SIZE], int used);
static void process_random_ready_list(void);
static void _get_random_bytes(void *buf, int nbytes);
static struct ratelimit_state unseeded_warning =
RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
static struct ratelimit_state urandom_warning =
RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
static int ratelimit_disable __read_mostly;
module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
/**********************************************************************
*
* OS independent entropy store. Here are the functions which handle
* storing entropy in an entropy pool.
*
**********************************************************************/
struct entropy_store;
struct entropy_store {
/* read-only data: */
const struct poolinfo *poolinfo;
__u32 *pool;
const char *name;
/* read-write data: */
spinlock_t lock;
unsigned short add_ptr;
unsigned short input_rotate;
int entropy_count;
unsigned int initialized:1;
unsigned int last_data_init:1;
__u8 last_data[EXTRACT_SIZE];
};
static ssize_t extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int min, int rsvd);
static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int fips);
static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
static struct entropy_store input_pool = {
.poolinfo = &poolinfo_table[0],
.name = "input",
.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
.pool = input_pool_data
};
static __u32 const twist_table[8] = {
0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
/*
* This function adds bytes into the entropy "pool". It does not
* update the entropy estimate. The caller should call
* credit_entropy_bits if this is appropriate.
*
* The pool is stirred with a primitive polynomial of the appropriate
* degree, and then twisted. We twist by three bits at a time because
* it's cheap to do so and helps slightly in the expected case where
* the entropy is concentrated in the low-order bits.
*/
static void _mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
unsigned long i, tap1, tap2, tap3, tap4, tap5;
int input_rotate;
int wordmask = r->poolinfo->poolwords - 1;
const char *bytes = in;
__u32 w;
tap1 = r->poolinfo->tap1;
tap2 = r->poolinfo->tap2;
tap3 = r->poolinfo->tap3;
tap4 = r->poolinfo->tap4;
tap5 = r->poolinfo->tap5;
input_rotate = r->input_rotate;
i = r->add_ptr;
/* mix one byte at a time to simplify size handling and churn faster */
while (nbytes--) {
w = rol32(*bytes++, input_rotate);
i = (i - 1) & wordmask;
/* XOR in the various taps */
w ^= r->pool[i];
w ^= r->pool[(i + tap1) & wordmask];
w ^= r->pool[(i + tap2) & wordmask];
w ^= r->pool[(i + tap3) & wordmask];
w ^= r->pool[(i + tap4) & wordmask];
w ^= r->pool[(i + tap5) & wordmask];
/* Mix the result back in with a twist */
r->pool[i] = (w >> 3) ^ twist_table[w & 7];
/*
* Normally, we add 7 bits of rotation to the pool.
* At the beginning of the pool, add an extra 7 bits
* rotation, so that successive passes spread the
* input bits across the pool evenly.
*/
input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
}
r->input_rotate = input_rotate;
r->add_ptr = i;
}
static void __mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
_mix_pool_bytes(r, in, nbytes);
}
static void mix_pool_bytes(struct entropy_store *r, const void *in,
int nbytes)
{
unsigned long flags;
trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
spin_lock_irqsave(&r->lock, flags);
_mix_pool_bytes(r, in, nbytes);
spin_unlock_irqrestore(&r->lock, flags);
}
struct fast_pool {
__u32 pool[4];
unsigned long last;
unsigned short reg_idx;
unsigned char count;
};
/*
* This is a fast mixing routine used by the interrupt randomness
* collector. It's hardcoded for an 128 bit pool and assumes that any
* locks that might be needed are taken by the caller.
*/
static void fast_mix(struct fast_pool *f)
{
__u32 a = f->pool[0], b = f->pool[1];
__u32 c = f->pool[2], d = f->pool[3];
a += b; c += d;
b = rol32(b, 6); d = rol32(d, 27);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 16); d = rol32(d, 14);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 6); d = rol32(d, 27);
d ^= a; b ^= c;
a += b; c += d;
b = rol32(b, 16); d = rol32(d, 14);
d ^= a; b ^= c;
f->pool[0] = a; f->pool[1] = b;
f->pool[2] = c; f->pool[3] = d;
f->count++;
}
static void process_random_ready_list(void)
{
unsigned long flags;
struct random_ready_callback *rdy, *tmp;
spin_lock_irqsave(&random_ready_list_lock, flags);
list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
struct module *owner = rdy->owner;
list_del_init(&rdy->list);
rdy->func(rdy);
module_put(owner);
}
spin_unlock_irqrestore(&random_ready_list_lock, flags);
}
/*
* Credit (or debit) the entropy store with n bits of entropy.
* Use credit_entropy_bits_safe() if the value comes from userspace
* or otherwise should be checked for extreme values.
*/
static void credit_entropy_bits(struct entropy_store *r, int nbits)
{
int entropy_count, orig, has_initialized = 0;
const int pool_size = r->poolinfo->poolfracbits;
int nfrac = nbits << ENTROPY_SHIFT;
if (!nbits)
return;
retry:
entropy_count = orig = READ_ONCE(r->entropy_count);
if (nfrac < 0) {
/* Debit */
entropy_count += nfrac;
} else {
/*
* Credit: we have to account for the possibility of
* overwriting already present entropy. Even in the
* ideal case of pure Shannon entropy, new contributions
* approach the full value asymptotically:
*
* entropy <- entropy + (pool_size - entropy) *
* (1 - exp(-add_entropy/pool_size))
*
* For add_entropy <= pool_size/2 then
* (1 - exp(-add_entropy/pool_size)) >=
* (add_entropy/pool_size)*0.7869...
* so we can approximate the exponential with
* 3/4*add_entropy/pool_size and still be on the
* safe side by adding at most pool_size/2 at a time.
*
* The use of pool_size-2 in the while statement is to
* prevent rounding artifacts from making the loop
* arbitrarily long; this limits the loop to log2(pool_size)*2
* turns no matter how large nbits is.
*/
int pnfrac = nfrac;
const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
/* The +2 corresponds to the /4 in the denominator */
do {
unsigned int anfrac = min(pnfrac, pool_size/2);
unsigned int add =
((pool_size - entropy_count)*anfrac*3) >> s;
entropy_count += add;
pnfrac -= anfrac;
} while (unlikely(entropy_count < pool_size-2 && pnfrac));
}
if (WARN_ON(entropy_count < 0)) {
pr_warn("negative entropy/overflow: pool %s count %d\n",
r->name, entropy_count);
entropy_count = 0;
} else if (entropy_count > pool_size)
entropy_count = pool_size;
if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
goto retry;
if (has_initialized) {
r->initialized = 1;
kill_fasync(&fasync, SIGIO, POLL_IN);
}
trace_credit_entropy_bits(r->name, nbits,
entropy_count >> ENTROPY_SHIFT, _RET_IP_);
if (r == &input_pool) {
int entropy_bits = entropy_count >> ENTROPY_SHIFT;
if (crng_init < 2) {
if (entropy_bits < 128)
return;
crng_reseed(&primary_crng, r);
entropy_bits = ENTROPY_BITS(r);
}
}
}
static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
{
const int nbits_max = r->poolinfo->poolwords * 32;
if (nbits < 0)
return -EINVAL;
/* Cap the value to avoid overflows */
nbits = min(nbits, nbits_max);
credit_entropy_bits(r, nbits);
return 0;
}
/*********************************************************************
*
* CRNG using CHACHA20
*
*********************************************************************/
#define CRNG_RESEED_INTERVAL (300*HZ)
static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
#ifdef CONFIG_NUMA
/*
* Hack to deal with crazy userspace progams when they are all trying
* to access /dev/urandom in parallel. The programs are almost
* certainly doing something terribly wrong, but we'll work around
* their brain damage.
*/
static struct crng_state **crng_node_pool __read_mostly;
#endif
static void invalidate_batched_entropy(void);
static void numa_crng_init(void);
static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
static int __init parse_trust_cpu(char *arg)
{
return kstrtobool(arg, &trust_cpu);
}
early_param("random.trust_cpu", parse_trust_cpu);
static bool crng_init_try_arch(struct crng_state *crng)
{
int i;
bool arch_init = true;
unsigned long rv;
for (i = 4; i < 16; i++) {
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv)) {
rv = random_get_entropy();
arch_init = false;
}
crng->state[i] ^= rv;
}
return arch_init;
}
static bool __init crng_init_try_arch_early(struct crng_state *crng)
{
int i;
bool arch_init = true;
unsigned long rv;
for (i = 4; i < 16; i++) {
if (!arch_get_random_seed_long_early(&rv) &&
!arch_get_random_long_early(&rv)) {
rv = random_get_entropy();
arch_init = false;
}
crng->state[i] ^= rv;
}
return arch_init;
}
static void __maybe_unused crng_initialize_secondary(struct crng_state *crng)
{
memcpy(&crng->state[0], "expand 32-byte k", 16);
_get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
crng_init_try_arch(crng);
crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
}
static void __init crng_initialize_primary(struct crng_state *crng)
{
memcpy(&crng->state[0], "expand 32-byte k", 16);
_extract_entropy(&input_pool, &crng->state[4], sizeof(__u32) * 12, 0);
if (crng_init_try_arch_early(crng) && trust_cpu) {
invalidate_batched_entropy();
numa_crng_init();
crng_init = 2;
pr_notice("crng done (trusting CPU's manufacturer)\n");
}
crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
}
#ifdef CONFIG_NUMA
static void do_numa_crng_init(struct work_struct *work)
{
int i;
struct crng_state *crng;
struct crng_state **pool;
pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
for_each_online_node(i) {
crng = kmalloc_node(sizeof(struct crng_state),
GFP_KERNEL | __GFP_NOFAIL, i);
spin_lock_init(&crng->lock);
crng_initialize_secondary(crng);
pool[i] = crng;
}
mb();
if (cmpxchg(&crng_node_pool, NULL, pool)) {
for_each_node(i)
kfree(pool[i]);
kfree(pool);
}
}
static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init);
static void numa_crng_init(void)
{
schedule_work(&numa_crng_init_work);
}
#else
static void numa_crng_init(void) {}
#endif
/*
* crng_fast_load() can be called by code in the interrupt service
* path. So we can't afford to dilly-dally.
*/
static int crng_fast_load(const char *cp, size_t len)
{
unsigned long flags;
char *p;
if (!spin_trylock_irqsave(&primary_crng.lock, flags))
return 0;
if (crng_init != 0) {
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 0;
}
p = (unsigned char *) &primary_crng.state[4];
while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
p[crng_init_cnt % CHACHA_KEY_SIZE] ^= *cp;
cp++; crng_init_cnt++; len--;
}
spin_unlock_irqrestore(&primary_crng.lock, flags);
if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
invalidate_batched_entropy();
crng_init = 1;
pr_notice("fast init done\n");
}
return 1;
}
/*
* crng_slow_load() is called by add_device_randomness, which has two
* attributes. (1) We can't trust the buffer passed to it is
* guaranteed to be unpredictable (so it might not have any entropy at
* all), and (2) it doesn't have the performance constraints of
* crng_fast_load().
*
* So we do something more comprehensive which is guaranteed to touch
* all of the primary_crng's state, and which uses a LFSR with a
* period of 255 as part of the mixing algorithm. Finally, we do
* *not* advance crng_init_cnt since buffer we may get may be something
* like a fixed DMI table (for example), which might very well be
* unique to the machine, but is otherwise unvarying.
*/
static int crng_slow_load(const char *cp, size_t len)
{
unsigned long flags;
static unsigned char lfsr = 1;
unsigned char tmp;
unsigned i, max = CHACHA_KEY_SIZE;
const char * src_buf = cp;
char * dest_buf = (char *) &primary_crng.state[4];
if (!spin_trylock_irqsave(&primary_crng.lock, flags))
return 0;
if (crng_init != 0) {
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 0;
}
if (len > max)
max = len;
for (i = 0; i < max ; i++) {
tmp = lfsr;
lfsr >>= 1;
if (tmp & 1)
lfsr ^= 0xE1;
tmp = dest_buf[i % CHACHA_KEY_SIZE];
dest_buf[i % CHACHA_KEY_SIZE] ^= src_buf[i % len] ^ lfsr;
lfsr += (tmp << 3) | (tmp >> 5);
}
spin_unlock_irqrestore(&primary_crng.lock, flags);
return 1;
}
static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
{
unsigned long flags;
int i, num;
union {
__u8 block[CHACHA_BLOCK_SIZE];
__u32 key[8];
} buf;
if (r) {
num = extract_entropy(r, &buf, 32, 16, 0);
if (num == 0)
return;
} else {
_extract_crng(&primary_crng, buf.block);
_crng_backtrack_protect(&primary_crng, buf.block,
CHACHA_KEY_SIZE);
}
spin_lock_irqsave(&crng->lock, flags);
for (i = 0; i < 8; i++) {
unsigned long rv;
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv))
rv = random_get_entropy();
crng->state[i+4] ^= buf.key[i] ^ rv;
}
memzero_explicit(&buf, sizeof(buf));
crng->init_time = jiffies;
spin_unlock_irqrestore(&crng->lock, flags);
if (crng == &primary_crng && crng_init < 2) {
invalidate_batched_entropy();
numa_crng_init();
crng_init = 2;
process_random_ready_list();
wake_up_interruptible(&crng_init_wait);
kill_fasync(&fasync, SIGIO, POLL_IN);
pr_notice("crng init done\n");
if (unseeded_warning.missed) {
pr_notice("%d get_random_xx warning(s) missed due to ratelimiting\n",
unseeded_warning.missed);
unseeded_warning.missed = 0;
}
if (urandom_warning.missed) {
pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
urandom_warning.missed);
urandom_warning.missed = 0;
}
}
}
static void _extract_crng(struct crng_state *crng,
__u8 out[CHACHA_BLOCK_SIZE])
{
unsigned long v, flags;
if (crng_ready() &&
(time_after(crng_global_init_time, crng->init_time) ||
time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL)))
crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
spin_lock_irqsave(&crng->lock, flags);
if (arch_get_random_long(&v))
crng->state[14] ^= v;
chacha20_block(&crng->state[0], out);
if (crng->state[12] == 0)
crng->state[13]++;
spin_unlock_irqrestore(&crng->lock, flags);
}
static void extract_crng(__u8 out[CHACHA_BLOCK_SIZE])
{
struct crng_state *crng = NULL;
#ifdef CONFIG_NUMA
if (crng_node_pool)
crng = crng_node_pool[numa_node_id()];
if (crng == NULL)
#endif
crng = &primary_crng;
_extract_crng(crng, out);
}
/*
* Use the leftover bytes from the CRNG block output (if there is
* enough) to mutate the CRNG key to provide backtracking protection.
*/
static void _crng_backtrack_protect(struct crng_state *crng,
__u8 tmp[CHACHA_BLOCK_SIZE], int used)
{
unsigned long flags;
__u32 *s, *d;
int i;
used = round_up(used, sizeof(__u32));
if (used + CHACHA_KEY_SIZE > CHACHA_BLOCK_SIZE) {
extract_crng(tmp);
used = 0;
}
spin_lock_irqsave(&crng->lock, flags);
s = (__u32 *) &tmp[used];
d = &crng->state[4];
for (i=0; i < 8; i++)
*d++ ^= *s++;
spin_unlock_irqrestore(&crng->lock, flags);
}
static void crng_backtrack_protect(__u8 tmp[CHACHA_BLOCK_SIZE], int used)
{
struct crng_state *crng = NULL;
#ifdef CONFIG_NUMA
if (crng_node_pool)
crng = crng_node_pool[numa_node_id()];
if (crng == NULL)
#endif
crng = &primary_crng;
_crng_backtrack_protect(crng, tmp, used);
}
static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
{
ssize_t ret = 0, i = CHACHA_BLOCK_SIZE;
__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
int large_request = (nbytes > 256);
while (nbytes) {
if (large_request && need_resched()) {
if (signal_pending(current)) {
if (ret == 0)
ret = -ERESTARTSYS;
break;
}
schedule();
}
extract_crng(tmp);
i = min_t(int, nbytes, CHACHA_BLOCK_SIZE);
if (copy_to_user(buf, tmp, i)) {
ret = -EFAULT;
break;
}
nbytes -= i;
buf += i;
ret += i;
}
crng_backtrack_protect(tmp, i);
/* Wipe data just written to memory */
memzero_explicit(tmp, sizeof(tmp));
return ret;
}
/*********************************************************************
*
* Entropy input management
*
*********************************************************************/
/* There is one of these per entropy source */
struct timer_rand_state {
cycles_t last_time;
long last_delta, last_delta2;
};
#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
/*
* Add device- or boot-specific data to the input pool to help
* initialize it.
*
* None of this adds any entropy; it is meant to avoid the problem of
* the entropy pool having similar initial state across largely
* identical devices.
*/
void add_device_randomness(const void *buf, unsigned int size)
{
unsigned long time = random_get_entropy() ^ jiffies;
unsigned long flags;
if (!crng_ready() && size)
crng_slow_load(buf, size);
trace_add_device_randomness(size, _RET_IP_);
spin_lock_irqsave(&input_pool.lock, flags);
_mix_pool_bytes(&input_pool, buf, size);
_mix_pool_bytes(&input_pool, &time, sizeof(time));
spin_unlock_irqrestore(&input_pool.lock, flags);
}
EXPORT_SYMBOL(add_device_randomness);
static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
/*
* This function adds entropy to the entropy "pool" by using timing
* delays. It uses the timer_rand_state structure to make an estimate
* of how many bits of entropy this call has added to the pool.
*
* The number "num" is also added to the pool - it should somehow describe
* the type of event which just happened. This is currently 0-255 for
* keyboard scan codes, and 256 upwards for interrupts.
*
*/
static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
{
struct entropy_store *r;
struct {
long jiffies;
unsigned cycles;
unsigned num;
} sample;
long delta, delta2, delta3;
sample.jiffies = jiffies;
sample.cycles = random_get_entropy();
sample.num = num;
r = &input_pool;
mix_pool_bytes(r, &sample, sizeof(sample));
/*
* Calculate number of bits of randomness we probably added.
* We take into account the first, second and third-order deltas
* in order to make our estimate.
*/
delta = sample.jiffies - READ_ONCE(state->last_time);
WRITE_ONCE(state->last_time, sample.jiffies);
delta2 = delta - READ_ONCE(state->last_delta);
WRITE_ONCE(state->last_delta, delta);
delta3 = delta2 - READ_ONCE(state->last_delta2);
WRITE_ONCE(state->last_delta2, delta2);
if (delta < 0)
delta = -delta;
if (delta2 < 0)
delta2 = -delta2;
if (delta3 < 0)
delta3 = -delta3;
if (delta > delta2)
delta = delta2;
if (delta > delta3)
delta = delta3;
/*
* delta is now minimum absolute delta.
* Round down by 1 bit on general principles,
* and limit entropy estimate to 12 bits.
*/
credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
}
void add_input_randomness(unsigned int type, unsigned int code,
unsigned int value)
{
static unsigned char last_value;
/* ignore autorepeat and the like */
if (value == last_value)
return;
last_value = value;
add_timer_randomness(&input_timer_state,
(type << 4) ^ code ^ (code >> 4) ^ value);
trace_add_input_randomness(ENTROPY_BITS(&input_pool));
}
EXPORT_SYMBOL_GPL(add_input_randomness);
static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
#ifdef ADD_INTERRUPT_BENCH
static unsigned long avg_cycles, avg_deviation;
#define AVG_SHIFT 8 /* Exponential average factor k=1/256 */
#define FIXED_1_2 (1 << (AVG_SHIFT-1))
static void add_interrupt_bench(cycles_t start)
{
long delta = random_get_entropy() - start;
/* Use a weighted moving average */
delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
avg_cycles += delta;
/* And average deviation */
delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
avg_deviation += delta;
}
#else
#define add_interrupt_bench(x)
#endif
static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
{
__u32 *ptr = (__u32 *) regs;
unsigned int idx;
if (regs == NULL)
return 0;
idx = READ_ONCE(f->reg_idx);
if (idx >= sizeof(struct pt_regs) / sizeof(__u32))
idx = 0;
ptr += idx++;
WRITE_ONCE(f->reg_idx, idx);
return *ptr;
}
void add_interrupt_randomness(int irq, int irq_flags)
{
struct entropy_store *r;
struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
struct pt_regs *regs = get_irq_regs();
unsigned long now = jiffies;
cycles_t cycles = random_get_entropy();
__u32 c_high, j_high;
__u64 ip;
unsigned long seed;
int credit = 0;
if (cycles == 0)
cycles = get_reg(fast_pool, regs);
c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
fast_pool->pool[1] ^= now ^ c_high;
ip = regs ? instruction_pointer(regs) : _RET_IP_;
fast_pool->pool[2] ^= ip;
fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
get_reg(fast_pool, regs);
fast_mix(fast_pool);
add_interrupt_bench(cycles);
this_cpu_add(net_rand_state.s1, fast_pool->pool[cycles & 3]);
if (unlikely(crng_init == 0)) {
if ((fast_pool->count >= 64) &&
crng_fast_load((char *) fast_pool->pool,
sizeof(fast_pool->pool))) {
fast_pool->count = 0;
fast_pool->last = now;
}
return;
}
if ((fast_pool->count < 64) &&
!time_after(now, fast_pool->last + HZ))
return;
r = &input_pool;
if (!spin_trylock(&r->lock))
return;
fast_pool->last = now;
__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
/*
* If we have architectural seed generator, produce a seed and
* add it to the pool. For the sake of paranoia don't let the
* architectural seed generator dominate the input from the
* interrupt noise.
*/
if (arch_get_random_seed_long(&seed)) {
__mix_pool_bytes(r, &seed, sizeof(seed));
credit = 1;
}
spin_unlock(&r->lock);
fast_pool->count = 0;
/* award one bit for the contents of the fast pool */
credit_entropy_bits(r, credit + 1);
}
EXPORT_SYMBOL_GPL(add_interrupt_randomness);
#ifdef CONFIG_BLOCK
void add_disk_randomness(struct gendisk *disk)
{
if (!disk || !disk->random)
return;
/* first major is 1, so we get >= 0x200 here */
add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
}
EXPORT_SYMBOL_GPL(add_disk_randomness);
#endif
/*********************************************************************
*
* Entropy extraction routines
*
*********************************************************************/
/*
* This function decides how many bytes to actually take from the
* given pool, and also debits the entropy count accordingly.
*/
static size_t account(struct entropy_store *r, size_t nbytes, int min,
int reserved)
{
int entropy_count, orig, have_bytes;
size_t ibytes, nfrac;
BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
/* Can we pull enough? */
retry:
entropy_count = orig = READ_ONCE(r->entropy_count);
ibytes = nbytes;
/* never pull more than available */
have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
if ((have_bytes -= reserved) < 0)
have_bytes = 0;
ibytes = min_t(size_t, ibytes, have_bytes);
if (ibytes < min)
ibytes = 0;
if (WARN_ON(entropy_count < 0)) {
pr_warn("negative entropy count: pool %s count %d\n",
r->name, entropy_count);
entropy_count = 0;
}
nfrac = ibytes << (ENTROPY_SHIFT + 3);
if ((size_t) entropy_count > nfrac)
entropy_count -= nfrac;
else
entropy_count = 0;
if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
goto retry;
trace_debit_entropy(r->name, 8 * ibytes);
if (ibytes && ENTROPY_BITS(r) < random_write_wakeup_bits) {
wake_up_interruptible(&random_write_wait);
kill_fasync(&fasync, SIGIO, POLL_OUT);
}
return ibytes;
}
/*
* This function does the actual extraction for extract_entropy and
* extract_entropy_user.
*
* Note: we assume that .poolwords is a multiple of 16 words.
*/
static void extract_buf(struct entropy_store *r, __u8 *out)
{
int i;
union {
__u32 w[5];
unsigned long l[LONGS(20)];
} hash;
__u32 workspace[SHA1_WORKSPACE_WORDS];
unsigned long flags;
/*
* If we have an architectural hardware random number
* generator, use it for SHA's initial vector
*/
sha1_init(hash.w);
for (i = 0; i < LONGS(20); i++) {
unsigned long v;
if (!arch_get_random_long(&v))
break;
hash.l[i] = v;
}
/* Generate a hash across the pool, 16 words (512 bits) at a time */
spin_lock_irqsave(&r->lock, flags);
for (i = 0; i < r->poolinfo->poolwords; i += 16)
sha1_transform(hash.w, (__u8 *)(r->pool + i), workspace);
/*
* We mix the hash back into the pool to prevent backtracking
* attacks (where the attacker knows the state of the pool
* plus the current outputs, and attempts to find previous
* ouputs), unless the hash function can be inverted. By
* mixing at least a SHA1 worth of hash data back, we make
* brute-forcing the feedback as hard as brute-forcing the
* hash.
*/
__mix_pool_bytes(r, hash.w, sizeof(hash.w));
spin_unlock_irqrestore(&r->lock, flags);
memzero_explicit(workspace, sizeof(workspace));
/*
* In case the hash function has some recognizable output
* pattern, we fold it in half. Thus, we always feed back
* twice as much data as we output.
*/
hash.w[0] ^= hash.w[3];
hash.w[1] ^= hash.w[4];
hash.w[2] ^= rol32(hash.w[2], 16);
memcpy(out, &hash, EXTRACT_SIZE);
memzero_explicit(&hash, sizeof(hash));
}
static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int fips)
{
ssize_t ret = 0, i;
__u8 tmp[EXTRACT_SIZE];
unsigned long flags;
while (nbytes) {
extract_buf(r, tmp);
if (fips) {
spin_lock_irqsave(&r->lock, flags);
if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
panic("Hardware RNG duplicated output!\n");
memcpy(r->last_data, tmp, EXTRACT_SIZE);
spin_unlock_irqrestore(&r->lock, flags);
}
i = min_t(int, nbytes, EXTRACT_SIZE);
memcpy(buf, tmp, i);
nbytes -= i;
buf += i;
ret += i;
}
/* Wipe data just returned from memory */
memzero_explicit(tmp, sizeof(tmp));
return ret;
}
/*
* This function extracts randomness from the "entropy pool", and
* returns it in a buffer.
*
* The min parameter specifies the minimum amount we can pull before
* failing to avoid races that defeat catastrophic reseeding while the
* reserved parameter indicates how much entropy we must leave in the
* pool after each pull to avoid starving other readers.
*/
static ssize_t extract_entropy(struct entropy_store *r, void *buf,
size_t nbytes, int min, int reserved)
{
__u8 tmp[EXTRACT_SIZE];
unsigned long flags;
/* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
if (fips_enabled) {
spin_lock_irqsave(&r->lock, flags);
if (!r->last_data_init) {
r->last_data_init = 1;
spin_unlock_irqrestore(&r->lock, flags);
trace_extract_entropy(r->name, EXTRACT_SIZE,
ENTROPY_BITS(r), _RET_IP_);
extract_buf(r, tmp);
spin_lock_irqsave(&r->lock, flags);
memcpy(r->last_data, tmp, EXTRACT_SIZE);
}
spin_unlock_irqrestore(&r->lock, flags);
}
trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
nbytes = account(r, nbytes, min, reserved);
return _extract_entropy(r, buf, nbytes, fips_enabled);
}
#define warn_unseeded_randomness(previous) \
_warn_unseeded_randomness(__func__, (void *) _RET_IP_, (previous))
static void _warn_unseeded_randomness(const char *func_name, void *caller,
void **previous)
{
#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
const bool print_once = false;
#else
static bool print_once __read_mostly;
#endif
if (print_once ||
crng_ready() ||
(previous && (caller == READ_ONCE(*previous))))
return;
WRITE_ONCE(*previous, caller);
#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
print_once = true;
#endif
if (__ratelimit(&unseeded_warning))
printk_deferred(KERN_NOTICE "random: %s called from %pS "
"with crng_init=%d\n", func_name, caller,
crng_init);
}
/*
* This function is the exported kernel interface. It returns some
* number of good random numbers, suitable for key generation, seeding
* TCP sequence numbers, etc. It does not rely on the hardware random
* number generator. For random bytes direct from the hardware RNG
* (when available), use get_random_bytes_arch(). In order to ensure
* that the randomness provided by this function is okay, the function
* wait_for_random_bytes() should be called and return 0 at least once
* at any point prior.
*/
static void _get_random_bytes(void *buf, int nbytes)
{
__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
trace_get_random_bytes(nbytes, _RET_IP_);
while (nbytes >= CHACHA_BLOCK_SIZE) {
extract_crng(buf);
buf += CHACHA_BLOCK_SIZE;
nbytes -= CHACHA_BLOCK_SIZE;
}
if (nbytes > 0) {
extract_crng(tmp);
memcpy(buf, tmp, nbytes);
crng_backtrack_protect(tmp, nbytes);
} else
crng_backtrack_protect(tmp, CHACHA_BLOCK_SIZE);
memzero_explicit(tmp, sizeof(tmp));
}
void get_random_bytes(void *buf, int nbytes)
{
static void *previous;
warn_unseeded_randomness(&previous);
_get_random_bytes(buf, nbytes);
}
EXPORT_SYMBOL(get_random_bytes);
/*
* Each time the timer fires, we expect that we got an unpredictable
* jump in the cycle counter. Even if the timer is running on another
* CPU, the timer activity will be touching the stack of the CPU that is
* generating entropy..
*
* Note that we don't re-arm the timer in the timer itself - we are
* happy to be scheduled away, since that just makes the load more
* complex, but we do not want the timer to keep ticking unless the
* entropy loop is running.
*
* So the re-arming always happens in the entropy loop itself.
*/
static void entropy_timer(struct timer_list *t)
{
credit_entropy_bits(&input_pool, 1);
}
/*
* If we have an actual cycle counter, see if we can
* generate enough entropy with timing noise
*/
static void try_to_generate_entropy(void)
{
struct {
unsigned long now;
struct timer_list timer;
} stack;
stack.now = random_get_entropy();
/* Slow counter - or none. Don't even bother */
if (stack.now == random_get_entropy())
return;
timer_setup_on_stack(&stack.timer, entropy_timer, 0);
while (!crng_ready()) {
if (!timer_pending(&stack.timer))
mod_timer(&stack.timer, jiffies+1);
mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
schedule();
stack.now = random_get_entropy();
}
del_timer_sync(&stack.timer);
destroy_timer_on_stack(&stack.timer);
mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
}
/*
* Wait for the urandom pool to be seeded and thus guaranteed to supply
* cryptographically secure random numbers. This applies to: the /dev/urandom
* device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
* family of functions. Using any of these functions without first calling
* this function forfeits the guarantee of security.
*
* Returns: 0 if the urandom pool has been seeded.
* -ERESTARTSYS if the function was interrupted by a signal.
*/
int wait_for_random_bytes(void)
{
if (likely(crng_ready()))
return 0;
do {
int ret;
ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
if (ret)
return ret > 0 ? 0 : ret;
try_to_generate_entropy();
} while (!crng_ready());
return 0;
}
EXPORT_SYMBOL(wait_for_random_bytes);
/*
* Returns whether or not the urandom pool has been seeded and thus guaranteed
* to supply cryptographically secure random numbers. This applies to: the
* /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
* ,u64,int,long} family of functions.
*
* Returns: true if the urandom pool has been seeded.
* false if the urandom pool has not been seeded.
*/
bool rng_is_initialized(void)
{
return crng_ready();
}
EXPORT_SYMBOL(rng_is_initialized);
/*
* Add a callback function that will be invoked when the nonblocking
* pool is initialised.
*
* returns: 0 if callback is successfully added
* -EALREADY if pool is already initialised (callback not called)
* -ENOENT if module for callback is not alive
*/
int add_random_ready_callback(struct random_ready_callback *rdy)
{
struct module *owner;
unsigned long flags;
int err = -EALREADY;
if (crng_ready())
return err;
owner = rdy->owner;
if (!try_module_get(owner))
return -ENOENT;
spin_lock_irqsave(&random_ready_list_lock, flags);
if (crng_ready())
goto out;
owner = NULL;
list_add(&rdy->list, &random_ready_list);
err = 0;
out:
spin_unlock_irqrestore(&random_ready_list_lock, flags);
module_put(owner);
return err;
}
EXPORT_SYMBOL(add_random_ready_callback);
/*
* Delete a previously registered readiness callback function.
*/
void del_random_ready_callback(struct random_ready_callback *rdy)
{
unsigned long flags;
struct module *owner = NULL;
spin_lock_irqsave(&random_ready_list_lock, flags);
if (!list_empty(&rdy->list)) {
list_del_init(&rdy->list);
owner = rdy->owner;
}
spin_unlock_irqrestore(&random_ready_list_lock, flags);
module_put(owner);
}
EXPORT_SYMBOL(del_random_ready_callback);
/*
* This function will use the architecture-specific hardware random
* number generator if it is available. The arch-specific hw RNG will
* almost certainly be faster than what we can do in software, but it
* is impossible to verify that it is implemented securely (as
* opposed, to, say, the AES encryption of a sequence number using a
* key known by the NSA). So it's useful if we need the speed, but
* only if we're willing to trust the hardware manufacturer not to
* have put in a back door.
*
* Return number of bytes filled in.
*/
int __must_check get_random_bytes_arch(void *buf, int nbytes)
{
int left = nbytes;
char *p = buf;
trace_get_random_bytes_arch(left, _RET_IP_);
while (left) {
unsigned long v;
int chunk = min_t(int, left, sizeof(unsigned long));
if (!arch_get_random_long(&v))
break;
memcpy(p, &v, chunk);
p += chunk;
left -= chunk;
}
return nbytes - left;
}
EXPORT_SYMBOL(get_random_bytes_arch);
/*
* init_std_data - initialize pool with system data
*
* @r: pool to initialize
*
* This function clears the pool's entropy count and mixes some system
* data into the pool to prepare it for use. The pool is not cleared
* as that can only decrease the entropy in the pool.
*/
static void __init init_std_data(struct entropy_store *r)
{
int i;
ktime_t now = ktime_get_real();
unsigned long rv;
mix_pool_bytes(r, &now, sizeof(now));
for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
if (!arch_get_random_seed_long(&rv) &&
!arch_get_random_long(&rv))
rv = random_get_entropy();
mix_pool_bytes(r, &rv, sizeof(rv));
}
mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
}
/*
* Note that setup_arch() may call add_device_randomness()
* long before we get here. This allows seeding of the pools
* with some platform dependent data very early in the boot
* process. But it limits our options here. We must use
* statically allocated structures that already have all
* initializations complete at compile time. We should also
* take care not to overwrite the precious per platform data
* we were given.
*/
int __init rand_initialize(void)
{
init_std_data(&input_pool);
crng_initialize_primary(&primary_crng);
crng_global_init_time = jiffies;
if (ratelimit_disable) {
urandom_warning.interval = 0;
unseeded_warning.interval = 0;
}
return 0;
}
#ifdef CONFIG_BLOCK
void rand_initialize_disk(struct gendisk *disk)
{
struct timer_rand_state *state;
/*
* If kzalloc returns null, we just won't use that entropy
* source.
*/
state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
if (state) {
state->last_time = INITIAL_JIFFIES;
disk->random = state;
}
}
#endif
static ssize_t
urandom_read_nowarn(struct file *file, char __user *buf, size_t nbytes,
loff_t *ppos)
{
int ret;
nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
ret = extract_crng_user(buf, nbytes);
trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
return ret;
}
static ssize_t
urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
unsigned long flags;
static int maxwarn = 10;
if (!crng_ready() && maxwarn > 0) {
maxwarn--;
if (__ratelimit(&urandom_warning))
pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
current->comm, nbytes);
spin_lock_irqsave(&primary_crng.lock, flags);
crng_init_cnt = 0;
spin_unlock_irqrestore(&primary_crng.lock, flags);
}
return urandom_read_nowarn(file, buf, nbytes, ppos);
}
static ssize_t
random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
int ret;
ret = wait_for_random_bytes();
if (ret != 0)
return ret;
return urandom_read_nowarn(file, buf, nbytes, ppos);
}
static __poll_t
random_poll(struct file *file, poll_table * wait)
{
__poll_t mask;
poll_wait(file, &crng_init_wait, wait);
poll_wait(file, &random_write_wait, wait);
mask = 0;
if (crng_ready())
mask |= EPOLLIN | EPOLLRDNORM;
if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
mask |= EPOLLOUT | EPOLLWRNORM;
return mask;
}
static int
write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
{
size_t bytes;
__u32 t, buf[16];
const char __user *p = buffer;
while (count > 0) {
int b, i = 0;
bytes = min(count, sizeof(buf));
if (copy_from_user(&buf, p, bytes))
return -EFAULT;
for (b = bytes ; b > 0 ; b -= sizeof(__u32), i++) {
if (!arch_get_random_int(&t))
break;
buf[i] ^= t;
}
count -= bytes;
p += bytes;
mix_pool_bytes(r, buf, bytes);
cond_resched();
}
return 0;
}
static ssize_t random_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
size_t ret;
ret = write_pool(&input_pool, buffer, count);
if (ret)
return ret;
return (ssize_t)count;
}
static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
int size, ent_count;
int __user *p = (int __user *)arg;
int retval;
switch (cmd) {
case RNDGETENTCNT:
/* inherently racy, no point locking */
ent_count = ENTROPY_BITS(&input_pool);
if (put_user(ent_count, p))
return -EFAULT;
return 0;
case RNDADDTOENTCNT:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ent_count, p))
return -EFAULT;
return credit_entropy_bits_safe(&input_pool, ent_count);
case RNDADDENTROPY:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ent_count, p++))
return -EFAULT;
if (ent_count < 0)
return -EINVAL;
if (get_user(size, p++))
return -EFAULT;
retval = write_pool(&input_pool, (const char __user *)p,
size);
if (retval < 0)
return retval;
return credit_entropy_bits_safe(&input_pool, ent_count);
case RNDZAPENTCNT:
case RNDCLEARPOOL:
/*
* Clear the entropy pool counters. We no longer clear
* the entropy pool, as that's silly.
*/
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
input_pool.entropy_count = 0;
return 0;
case RNDRESEEDCRNG:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (crng_init < 2)
return -ENODATA;
crng_reseed(&primary_crng, NULL);
crng_global_init_time = jiffies - 1;
return 0;
default:
return -EINVAL;
}
}
static int random_fasync(int fd, struct file *filp, int on)
{
return fasync_helper(fd, filp, on, &fasync);
}
const struct file_operations random_fops = {
.read = random_read,
.write = random_write,
.poll = random_poll,
.unlocked_ioctl = random_ioctl,
.compat_ioctl = compat_ptr_ioctl,
.fasync = random_fasync,
.llseek = noop_llseek,
};
const struct file_operations urandom_fops = {
.read = urandom_read,
.write = random_write,
.unlocked_ioctl = random_ioctl,
.compat_ioctl = compat_ptr_ioctl,
.fasync = random_fasync,
.llseek = noop_llseek,
};
SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
unsigned int, flags)
{
int ret;
if (flags & ~(GRND_NONBLOCK|GRND_RANDOM|GRND_INSECURE))
return -EINVAL;
/*
* Requesting insecure and blocking randomness at the same time makes
* no sense.
*/
if ((flags & (GRND_INSECURE|GRND_RANDOM)) == (GRND_INSECURE|GRND_RANDOM))
return -EINVAL;
if (count > INT_MAX)
count = INT_MAX;
if (!(flags & GRND_INSECURE) && !crng_ready()) {
if (flags & GRND_NONBLOCK)
return -EAGAIN;
ret = wait_for_random_bytes();
if (unlikely(ret))
return ret;
}
return urandom_read_nowarn(NULL, buf, count, NULL);
}
/********************************************************************
*
* Sysctl interface
*
********************************************************************/
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
static int min_write_thresh;
static int max_write_thresh = INPUT_POOL_WORDS * 32;
static int random_min_urandom_seed = 60;
static char sysctl_bootid[16];
/*
* This function is used to return both the bootid UUID, and random
* UUID. The difference is in whether table->data is NULL; if it is,
* then a new UUID is generated and returned to the user.
*
* If the user accesses this via the proc interface, the UUID will be
* returned as an ASCII string in the standard UUID format; if via the
* sysctl system call, as 16 bytes of binary data.
*/
static int proc_do_uuid(struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table fake_table;
unsigned char buf[64], tmp_uuid[16], *uuid;
uuid = table->data;
if (!uuid) {
uuid = tmp_uuid;
generate_random_uuid(uuid);
} else {
static DEFINE_SPINLOCK(bootid_spinlock);
spin_lock(&bootid_spinlock);
if (!uuid[8])
generate_random_uuid(uuid);
spin_unlock(&bootid_spinlock);
}
sprintf(buf, "%pU", uuid);
fake_table.data = buf;
fake_table.maxlen = sizeof(buf);
return proc_dostring(&fake_table, write, buffer, lenp, ppos);
}
/*
* Return entropy available scaled to integral bits
*/
static int proc_do_entropy(struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table fake_table;
int entropy_count;
entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
fake_table.data = &entropy_count;
fake_table.maxlen = sizeof(entropy_count);
return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
}
static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
extern struct ctl_table random_table[];
struct ctl_table random_table[] = {
{
.procname = "poolsize",
.data = &sysctl_poolsize,
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_dointvec,
},
{
.procname = "entropy_avail",
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_do_entropy,
.data = &input_pool.entropy_count,
},
{
.procname = "write_wakeup_threshold",
.data = &random_write_wakeup_bits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_write_thresh,
.extra2 = &max_write_thresh,
},
{
.procname = "urandom_min_reseed_secs",
.data = &random_min_urandom_seed,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "boot_id",
.data = &sysctl_bootid,
.maxlen = 16,
.mode = 0444,
.proc_handler = proc_do_uuid,
},
{
.procname = "uuid",
.maxlen = 16,
.mode = 0444,
.proc_handler = proc_do_uuid,
},
#ifdef ADD_INTERRUPT_BENCH
{
.procname = "add_interrupt_avg_cycles",
.data = &avg_cycles,
.maxlen = sizeof(avg_cycles),
.mode = 0444,
.proc_handler = proc_doulongvec_minmax,
},
{
.procname = "add_interrupt_avg_deviation",
.data = &avg_deviation,
.maxlen = sizeof(avg_deviation),
.mode = 0444,
.proc_handler = proc_doulongvec_minmax,
},
#endif
{ }
};
#endif /* CONFIG_SYSCTL */
struct batched_entropy {
union {
u64 entropy_u64[CHACHA_BLOCK_SIZE / sizeof(u64)];
u32 entropy_u32[CHACHA_BLOCK_SIZE / sizeof(u32)];
};
unsigned int position;
spinlock_t batch_lock;
};
/*
* Get a random word for internal kernel use only. The quality of the random
* number is good as /dev/urandom, but there is no backtrack protection, with
* the goal of being quite fast and not depleting entropy. In order to ensure
* that the randomness provided by this function is okay, the function
* wait_for_random_bytes() should be called and return 0 at least once at any
* point prior.
*/
static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
.batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u64.lock),
};
u64 get_random_u64(void)
{
u64 ret;
unsigned long flags;
struct batched_entropy *batch;
static void *previous;
warn_unseeded_randomness(&previous);
batch = raw_cpu_ptr(&batched_entropy_u64);
spin_lock_irqsave(&batch->batch_lock, flags);
if (batch->position % ARRAY_SIZE(batch->entropy_u64) == 0) {
extract_crng((u8 *)batch->entropy_u64);
batch->position = 0;
}
ret = batch->entropy_u64[batch->position++];
spin_unlock_irqrestore(&batch->batch_lock, flags);
return ret;
}
EXPORT_SYMBOL(get_random_u64);
static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
.batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u32.lock),
};
u32 get_random_u32(void)
{
u32 ret;
unsigned long flags;
struct batched_entropy *batch;
static void *previous;
warn_unseeded_randomness(&previous);
batch = raw_cpu_ptr(&batched_entropy_u32);
spin_lock_irqsave(&batch->batch_lock, flags);
if (batch->position % ARRAY_SIZE(batch->entropy_u32) == 0) {
extract_crng((u8 *)batch->entropy_u32);
batch->position = 0;
}
ret = batch->entropy_u32[batch->position++];
spin_unlock_irqrestore(&batch->batch_lock, flags);
return ret;
}
EXPORT_SYMBOL(get_random_u32);
/* It's important to invalidate all potential batched entropy that might
* be stored before the crng is initialized, which we can do lazily by
* simply resetting the counter to zero so that it's re-extracted on the
* next usage. */
static void invalidate_batched_entropy(void)
{
int cpu;
unsigned long flags;
for_each_possible_cpu (cpu) {
struct batched_entropy *batched_entropy;
batched_entropy = per_cpu_ptr(&batched_entropy_u32, cpu);
spin_lock_irqsave(&batched_entropy->batch_lock, flags);
batched_entropy->position = 0;
spin_unlock(&batched_entropy->batch_lock);
batched_entropy = per_cpu_ptr(&batched_entropy_u64, cpu);
spin_lock(&batched_entropy->batch_lock);
batched_entropy->position = 0;
spin_unlock_irqrestore(&batched_entropy->batch_lock, flags);
}
}
/**
* randomize_page - Generate a random, page aligned address
* @start: The smallest acceptable address the caller will take.
* @range: The size of the area, starting at @start, within which the
* random address must fall.
*
* If @start + @range would overflow, @range is capped.
*
* NOTE: Historical use of randomize_range, which this replaces, presumed that
* @start was already page aligned. We now align it regardless.
*
* Return: A page aligned address within [start, start + range). On error,
* @start is returned.
*/
unsigned long
randomize_page(unsigned long start, unsigned long range)
{
if (!PAGE_ALIGNED(start)) {
range -= PAGE_ALIGN(start) - start;
start = PAGE_ALIGN(start);
}
if (start > ULONG_MAX - range)
range = ULONG_MAX - start;
range >>= PAGE_SHIFT;
if (range == 0)
return start;
return start + (get_random_long() % range << PAGE_SHIFT);
}
/* Interface for in-kernel drivers of true hardware RNGs.
* Those devices may produce endless random bits and will be throttled
* when our pool is full.
*/
void add_hwgenerator_randomness(const char *buffer, size_t count,
size_t entropy)
{
struct entropy_store *poolp = &input_pool;
if (unlikely(crng_init == 0)) {
crng_fast_load(buffer, count);
return;
}
/* Suspend writing if we're above the trickle threshold.
* We'll be woken up again once below random_write_wakeup_thresh,
* or when the calling thread is about to terminate.
*/
wait_event_interruptible(random_write_wait, kthread_should_stop() ||
ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
mix_pool_bytes(poolp, buffer, count);
credit_entropy_bits(poolp, entropy);
}
EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
/* Handle random seed passed by bootloader.
* If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
* it would be regarded as device data.
* The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
*/
void add_bootloader_randomness(const void *buf, unsigned int size)
{
if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
add_hwgenerator_randomness(buf, size, size * 8);
else
add_device_randomness(buf, size);
}
EXPORT_SYMBOL_GPL(add_bootloader_randomness);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_4240_0 |
crossvul-cpp_data_good_3824_0 | /* xfrm_user.c: User interface to configure xfrm engine.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
*
*/
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/init.h>
#include <linux/security.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/netlink.h>
#include <net/ah.h>
#include <asm/uaccess.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/in6.h>
#endif
static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
{
struct nlattr *rt = attrs[type];
struct xfrm_algo *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_len(algp))
return -EINVAL;
switch (type) {
case XFRMA_ALG_AUTH:
case XFRMA_ALG_CRYPT:
case XFRMA_ALG_COMP:
break;
default:
return -EINVAL;
}
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_auth_trunc(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
struct xfrm_algo_auth *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_auth_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_aead(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
struct xfrm_algo_aead *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < aead_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
xfrm_address_t **addrp)
{
struct nlattr *rt = attrs[type];
if (rt && addrp)
*addrp = nla_data(rt);
}
static inline int verify_sec_ctx_len(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
return -EINVAL;
return 0;
}
static inline int verify_replay(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
if ((p->flags & XFRM_STATE_ESN) && !rt)
return -EINVAL;
if (!rt)
return 0;
if (p->id.proto != IPPROTO_ESP)
return -EINVAL;
if (p->replay_window != 0)
return -EINVAL;
return 0;
}
static int verify_newsa_info(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
int err;
err = -EINVAL;
switch (p->family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
err = -EAFNOSUPPORT;
goto out;
#endif
default:
goto out;
}
err = -EINVAL;
switch (p->id.proto) {
case IPPROTO_AH:
if ((!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC]) ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
case IPPROTO_ESP:
if (attrs[XFRMA_ALG_COMP])
goto out;
if (!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC] &&
!attrs[XFRMA_ALG_CRYPT] &&
!attrs[XFRMA_ALG_AEAD])
goto out;
if ((attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT]) &&
attrs[XFRMA_ALG_AEAD])
goto out;
if (attrs[XFRMA_TFCPAD] &&
p->mode != XFRM_MODE_TUNNEL)
goto out;
break;
case IPPROTO_COMP:
if (!attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
#if IS_ENABLED(CONFIG_IPV6)
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
if (attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ENCAP] ||
attrs[XFRMA_SEC_CTX] ||
attrs[XFRMA_TFCPAD] ||
!attrs[XFRMA_COADDR])
goto out;
break;
#endif
default:
goto out;
}
if ((err = verify_aead(attrs)))
goto out;
if ((err = verify_auth_trunc(attrs)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
goto out;
if ((err = verify_sec_ctx_len(attrs)))
goto out;
if ((err = verify_replay(p, attrs)))
goto out;
err = -EINVAL;
switch (p->mode) {
case XFRM_MODE_TRANSPORT:
case XFRM_MODE_TUNNEL:
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_BEET:
break;
default:
goto out;
}
err = 0;
out:
return err;
}
static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo *ualg;
struct xfrm_algo_auth *p;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
p->alg_key_len = ualg->alg_key_len;
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
*algpp = p;
return 0;
}
static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_auth *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN ||
ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
return -EINVAL;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
if (!p->alg_trunc_len)
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
*algpp = p;
return 0;
}
static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_aead *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
{
int len = 0;
if (xfrm_ctx) {
len += sizeof(struct xfrm_user_sec_ctx);
len += xfrm_ctx->ctx_len;
}
return len;
}
static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&x->id, &p->id, sizeof(x->id));
memcpy(&x->sel, &p->sel, sizeof(x->sel));
memcpy(&x->lft, &p->lft, sizeof(x->lft));
x->props.mode = p->mode;
x->props.replay_window = p->replay_window;
x->props.reqid = p->reqid;
x->props.family = p->family;
memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
x->props.flags = p->flags;
if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
x->sel.family = p->family;
}
/*
* someday when pfkey also has support, we could have the code
* somehow made shareable and move it to xfrm_state.c - JHS
*
*/
static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs)
{
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
if (re) {
struct xfrm_replay_state_esn *replay_esn;
replay_esn = nla_data(re);
memcpy(x->replay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
memcpy(x->preplay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
}
if (rp) {
struct xfrm_replay_state *replay;
replay = nla_data(rp);
memcpy(&x->replay, replay, sizeof(*replay));
memcpy(&x->preplay, replay, sizeof(*replay));
}
if (lt) {
struct xfrm_lifetime_cur *ltime;
ltime = nla_data(lt);
x->curlft.bytes = ltime->bytes;
x->curlft.packets = ltime->packets;
x->curlft.add_time = ltime->add_time;
x->curlft.use_time = ltime->use_time;
}
if (et)
x->replay_maxage = nla_get_u32(et);
if (rt)
x->replay_maxdiff = nla_get_u32(rt);
}
static struct xfrm_state *xfrm_state_construct(struct net *net,
struct xfrm_usersa_info *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto error_no_put;
copy_from_user_state(x, p);
if ((err = attach_aead(&x->aead, &x->props.ealgo,
attrs[XFRMA_ALG_AEAD])))
goto error;
if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH_TRUNC])))
goto error;
if (!x->props.aalgo) {
if ((err = attach_auth(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH])))
goto error;
}
if ((err = attach_one_algo(&x->ealg, &x->props.ealgo,
xfrm_ealg_get_byname,
attrs[XFRMA_ALG_CRYPT])))
goto error;
if ((err = attach_one_algo(&x->calg, &x->props.calgo,
xfrm_calg_get_byname,
attrs[XFRMA_ALG_COMP])))
goto error;
if (attrs[XFRMA_ENCAP]) {
x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
sizeof(*x->encap), GFP_KERNEL);
if (x->encap == NULL)
goto error;
}
if (attrs[XFRMA_TFCPAD])
x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
if (attrs[XFRMA_COADDR]) {
x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
sizeof(*x->coaddr), GFP_KERNEL);
if (x->coaddr == NULL)
goto error;
}
xfrm_mark_get(attrs, &x->mark);
err = __xfrm_init_state(x, false);
if (err)
goto error;
if (attrs[XFRMA_SEC_CTX] &&
security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])))
goto error;
if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
attrs[XFRMA_REPLAY_ESN_VAL])))
goto error;
x->km.seq = p->seq;
x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
/* sysctl_xfrm_aevent_etime is in 100ms units */
x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
if ((err = xfrm_init_replay(x)))
goto error;
/* override default values from above */
xfrm_update_ae_params(x, attrs);
return x;
error:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
error_no_put:
*errp = err;
return NULL;
}
static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_info *p = nlmsg_data(nlh);
struct xfrm_state *x;
int err;
struct km_event c;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newsa_info(p, attrs);
if (err)
return err;
x = xfrm_state_construct(net, p, attrs, &err);
if (!x)
return err;
xfrm_state_hold(x);
if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
security_task_getsecid(current, &sid);
xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
struct xfrm_usersa_id *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = NULL;
struct xfrm_mark m;
int err;
u32 mark = xfrm_mark_get(attrs, &m);
if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
err = -ESRCH;
x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
} else {
xfrm_address_t *saddr = NULL;
verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
if (!saddr) {
err = -EINVAL;
goto out;
}
err = -ESRCH;
x = xfrm_state_lookup_byaddr(net, mark,
&p->daddr, saddr,
p->proto, p->family);
}
out:
if (!x && errp)
*errp = err;
return x;
}
static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err = -ESRCH;
struct km_event c;
struct xfrm_usersa_id *p = nlmsg_data(nlh);
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
return err;
if ((err = security_xfrm_state_delete(x)) != 0)
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
security_task_getsecid(current, &sid);
xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid);
xfrm_state_put(x);
return err;
}
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memset(p, 0, sizeof(*p));
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
struct xfrm_dump_info {
struct sk_buff *in_skb;
struct sk_buff *out_skb;
u32 nlmsg_seq;
u16 nlmsg_flags;
};
static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
{
struct xfrm_user_sec_ctx *uctx;
struct nlattr *attr;
int ctx_size = sizeof(*uctx) + s->ctx_len;
attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
if (attr == NULL)
return -EMSGSIZE;
uctx = nla_data(attr);
uctx->exttype = XFRMA_SEC_CTX;
uctx->len = ctx_size;
uctx->ctx_doi = s->ctx_doi;
uctx->ctx_alg = s->ctx_alg;
uctx->ctx_len = s->ctx_len;
memcpy(uctx + 1, s->ctx_str, s->ctx_len);
return 0;
}
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
/* Don't change this without updating xfrm_sa_len! */
static int copy_to_user_state_extra(struct xfrm_state *x,
struct xfrm_usersa_info *p,
struct sk_buff *skb)
{
int ret = 0;
copy_to_user_state(x, p);
if (x->coaddr) {
ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
if (ret)
goto out;
}
if (x->lastused) {
ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused);
if (ret)
goto out;
}
if (x->aead) {
ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
if (ret)
goto out;
}
if (x->aalg) {
ret = copy_to_user_auth(x->aalg, skb);
if (!ret)
ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC,
xfrm_alg_auth_len(x->aalg), x->aalg);
if (ret)
goto out;
}
if (x->ealg) {
ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
if (ret)
goto out;
}
if (x->calg) {
ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
if (ret)
goto out;
}
if (x->encap) {
ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
if (ret)
goto out;
}
if (x->tfcpad) {
ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
if (ret)
goto out;
}
ret = xfrm_mark_put(skb, &x->mark);
if (ret)
goto out;
if (x->replay_esn) {
ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
if (ret)
goto out;
}
if (x->security)
ret = copy_sec_ctx(x->security, skb);
out:
return ret;
}
static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct xfrm_usersa_info *p;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
err = copy_to_user_state_extra(x, p, skb);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_sa_done(struct netlink_callback *cb)
{
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
xfrm_state_walk_done(walk);
return 0;
}
static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_state_walk_init(walk, 0);
}
(void) xfrm_state_walk(net, walk, dump_one_state, &info);
return skb->len;
}
static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static inline size_t xfrm_spdinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_spdinfo))
+ nla_total_size(sizeof(struct xfrmu_spdhinfo));
}
static int build_spdinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_spdinfo si;
struct xfrmu_spdinfo spc;
struct xfrmu_spdhinfo sph;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_spd_getinfo(net, &si);
spc.incnt = si.incnt;
spc.outcnt = si.outcnt;
spc.fwdcnt = si.fwdcnt;
spc.inscnt = si.inscnt;
spc.outscnt = si.outscnt;
spc.fwdscnt = si.fwdscnt;
sph.spdhcnt = si.spdhcnt;
sph.spdhmcnt = si.spdhmcnt;
err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
if (!err)
err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static inline size_t xfrm_sadinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_sadhinfo))
+ nla_total_size(4); /* XFRMA_SAD_CNT */
}
static int build_sadinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_sadinfo si;
struct xfrmu_sadhinfo sh;
struct nlmsghdr *nlh;
int err;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_sad_getinfo(net, &si);
sh.sadhmcnt = si.sadhmcnt;
sh.sadhcnt = si.sadhcnt;
err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
if (!err)
err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_id *p = nlmsg_data(nlh);
struct xfrm_state *x;
struct sk_buff *resp_skb;
int err = -ESRCH;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
goto out_noput;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
}
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_userspi_info(struct xfrm_userspi_info *p)
{
switch (p->info.id.proto) {
case IPPROTO_AH:
case IPPROTO_ESP:
break;
case IPPROTO_COMP:
/* IPCOMP spi is 16-bits. */
if (p->max >= 0x10000)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (p->min > p->max)
return -EINVAL;
return 0;
}
static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct xfrm_userspi_info *p;
struct sk_buff *resp_skb;
xfrm_address_t *daddr;
int family;
int err;
u32 mark;
struct xfrm_mark m;
p = nlmsg_data(nlh);
err = verify_userspi_info(p);
if (err)
goto out_noput;
family = p->info.family;
daddr = &p->info.id.daddr;
x = NULL;
mark = xfrm_mark_get(attrs, &m);
if (p->info.seq) {
x = xfrm_find_acq_byseq(net, mark, p->info.seq);
if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
p->info.id.proto, daddr,
&p->info.saddr, 1,
family);
err = -ENOENT;
if (x == NULL)
goto out_noput;
err = xfrm_alloc_spi(x, p->min, p->max);
if (err)
goto out;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
goto out;
}
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
out:
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_policy_dir(u8 dir)
{
switch (dir) {
case XFRM_POLICY_IN:
case XFRM_POLICY_OUT:
case XFRM_POLICY_FWD:
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_policy_type(u8 type)
{
switch (type) {
case XFRM_POLICY_TYPE_MAIN:
#ifdef CONFIG_XFRM_SUB_POLICY
case XFRM_POLICY_TYPE_SUB:
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
{
switch (p->share) {
case XFRM_SHARE_ANY:
case XFRM_SHARE_SESSION:
case XFRM_SHARE_USER:
case XFRM_SHARE_UNIQUE:
break;
default:
return -EINVAL;
}
switch (p->action) {
case XFRM_POLICY_ALLOW:
case XFRM_POLICY_BLOCK:
break;
default:
return -EINVAL;
}
switch (p->sel.family) {
case AF_INET:
break;
case AF_INET6:
#if IS_ENABLED(CONFIG_IPV6)
break;
#else
return -EAFNOSUPPORT;
#endif
default:
return -EINVAL;
}
return verify_policy_dir(p->dir);
}
static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
return security_xfrm_policy_alloc(&pol->security, uctx);
}
static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
int nr)
{
int i;
xp->xfrm_nr = nr;
for (i = 0; i < nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
memcpy(&t->saddr, &ut->saddr,
sizeof(xfrm_address_t));
t->reqid = ut->reqid;
t->mode = ut->mode;
t->share = ut->share;
t->optional = ut->optional;
t->aalgos = ut->aalgos;
t->ealgos = ut->ealgos;
t->calgos = ut->calgos;
/* If all masks are ~0, then we allow all algorithms. */
t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
t->encap_family = ut->family;
}
}
static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
{
int i;
if (nr > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < nr; i++) {
/* We never validated the ut->family value, so many
* applications simply leave it at zero. The check was
* never made and ut->family was ignored because all
* templates could be assumed to have the same family as
* the policy itself. Now that we will have ipv4-in-ipv6
* and ipv6-in-ipv4 tunnels, this is no longer true.
*/
if (!ut[i].family)
ut[i].family = family;
switch (ut[i].family) {
case AF_INET:
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
break;
#endif
default:
return -EINVAL;
}
}
return 0;
}
static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_TMPL];
if (!rt) {
pol->xfrm_nr = 0;
} else {
struct xfrm_user_tmpl *utmpl = nla_data(rt);
int nr = nla_len(rt) / sizeof(*utmpl);
int err;
err = validate_tmpl(nr, utmpl, pol->family);
if (err)
return err;
copy_templates(pol, utmpl, nr);
}
return 0;
}
static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
struct xfrm_userpolicy_type *upt;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
if (rt) {
upt = nla_data(rt);
type = upt->type;
}
err = verify_policy_type(type);
if (err)
return err;
*tp = type;
return 0;
}
static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
{
xp->priority = p->priority;
xp->index = p->index;
memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
xp->action = p->action;
xp->flags = p->flags;
xp->family = p->sel.family;
/* XXX xp->share = p->share; */
}
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memset(p, 0, sizeof(*p));
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
{
struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
int err;
if (!xp) {
*errp = -ENOMEM;
return NULL;
}
copy_from_user_policy(xp, p);
err = copy_from_user_policy_type(&xp->type, attrs);
if (err)
goto error;
if (!(err = copy_from_user_tmpl(xp, attrs)))
err = copy_from_user_sec_ctx(xp, attrs);
if (err)
goto error;
xfrm_mark_get(attrs, &xp->mark);
return xp;
error:
*errp = err;
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
struct xfrm_policy *xp;
struct km_event c;
int err;
int excl;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newpolicy_info(p);
if (err)
return err;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
xp = xfrm_policy_construct(net, p, attrs, &err);
if (!xp)
return err;
/* shouldn't excl be based on nlh flags??
* Aha! this is anti-netlink really i.e more pfkey derived
* in netlink excl is a flag and you wouldnt need
* a type XFRM_MSG_UPDPOLICY - JHS */
excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
err = xfrm_policy_insert(p->dir, xp, excl);
security_task_getsecid(current, &sid);
xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid);
if (err) {
security_xfrm_policy_free(xp->security);
kfree(xp);
return err;
}
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
xfrm_pol_put(xp);
return 0;
}
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
{
struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
int i;
if (xp->xfrm_nr == 0)
return 0;
for (i = 0; i < xp->xfrm_nr; i++) {
struct xfrm_user_tmpl *up = &vec[i];
struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
memcpy(&up->id, &kp->id, sizeof(up->id));
up->family = kp->encap_family;
memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
up->reqid = kp->reqid;
up->mode = kp->mode;
up->share = kp->share;
up->optional = kp->optional;
up->aalgos = kp->aalgos;
up->ealgos = kp->ealgos;
up->calgos = kp->calgos;
}
return nla_put(skb, XFRMA_TMPL,
sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
}
static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
{
if (x->security) {
return copy_sec_ctx(x->security, skb);
}
return 0;
}
static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
{
if (xp->security)
return copy_sec_ctx(xp->security, skb);
return 0;
}
static inline size_t userpolicy_type_attrsize(void)
{
#ifdef CONFIG_XFRM_SUB_POLICY
return nla_total_size(sizeof(struct xfrm_userpolicy_type));
#else
return 0;
#endif
}
#ifdef CONFIG_XFRM_SUB_POLICY
static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
struct xfrm_userpolicy_type upt = {
.type = type,
};
return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
}
#else
static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
return 0;
}
#endif
static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct xfrm_userpolicy_info *p;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
nlmsg_end(skb, nlh);
return 0;
}
static int xfrm_dump_policy_done(struct netlink_callback *cb)
{
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
xfrm_policy_walk_done(walk);
return 0;
}
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
struct xfrm_policy *xp,
int dir, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_policy(xp, dir, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_userpolicy_id *p;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct km_event c;
int delete;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
p = nlmsg_data(nlh);
delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel,
ctx, delete, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (!delete) {
struct sk_buff *resp_skb;
resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
NETLINK_CB(skb).pid);
}
} else {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid,
sid);
if (err != 0)
goto out;
c.data.byid = p->index;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
}
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
struct xfrm_usersa_flush *p = nlmsg_data(nlh);
struct xfrm_audit audit_info;
int err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_state_flush(net, p->proto, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.proto = p->proto;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x)
{
size_t replay_size = x->replay_esn ?
xfrm_replay_state_esn_len(x->replay_esn) :
sizeof(struct xfrm_replay_state);
return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
+ nla_total_size(replay_size)
+ nla_total_size(sizeof(struct xfrm_lifetime_cur))
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(4) /* XFRM_AE_RTHR */
+ nla_total_size(4); /* XFRM_AE_ETHR */
}
static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_aevent_id *id;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
if (nlh == NULL)
return -EMSGSIZE;
id = nlmsg_data(nlh);
memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr));
id->sa_id.spi = x->id.spi;
id->sa_id.family = x->props.family;
id->sa_id.proto = x->id.proto;
memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr));
id->reqid = x->props.reqid;
id->flags = c->data.aevent;
if (x->replay_esn) {
err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
} else {
err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
&x->replay);
}
if (err)
goto out_cancel;
err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft);
if (err)
goto out_cancel;
if (id->flags & XFRM_AE_RTHR) {
err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
if (err)
goto out_cancel;
}
if (id->flags & XFRM_AE_ETHR) {
err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
x->replay_maxage * 10 / HZ);
if (err)
goto out_cancel;
}
err = xfrm_mark_put(skb, &x->mark);
if (err)
goto out_cancel;
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct sk_buff *r_skb;
int err;
struct km_event c;
u32 mark;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct xfrm_usersa_id *id = &p->sa_id;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
if (x == NULL)
return -ESRCH;
r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (r_skb == NULL) {
xfrm_state_put(x);
return -ENOMEM;
}
/*
* XXX: is this lock really needed - none of the other
* gets lock (the concern is things getting updated
* while we are still reading) - jhs
*/
spin_lock_bh(&x->lock);
c.data.aevent = p->flags;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
if (build_aevent(r_skb, x, &c) < 0)
BUG();
err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid);
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct km_event c;
int err = - EINVAL;
u32 mark = 0;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
if (!lt && !rp && !re)
return err;
/* pedantic mode - thou shalt sayeth replaceth */
if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
return err;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
if (x == NULL)
return -ESRCH;
if (x->km.state != XFRM_STATE_VALID)
goto out;
err = xfrm_replay_verify_len(x->replay_esn, rp);
if (err)
goto out;
spin_lock_bh(&x->lock);
xfrm_update_ae_params(x, attrs);
spin_unlock_bh(&x->lock);
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.data.aevent = XFRM_AE_CU;
km_state_notify(x, &c);
err = 0;
out:
xfrm_state_put(x);
return err;
}
static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct xfrm_audit audit_info;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_policy_flush(net, type, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.type = type;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_polexpire *up = nlmsg_data(nlh);
struct xfrm_userpolicy_info *p = &up->pol;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err = -ENOENT;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir,
&p->sel, ctx, 0, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (unlikely(xp->walk.dead))
goto out;
err = 0;
if (up->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_policy_delete(xp, p->dir);
xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid);
} else {
// reset the timers here?
WARN(1, "Dont know what to do with soft policy expire\n");
}
km_policy_expired(xp, p->dir, up->hard, current->pid);
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err;
struct xfrm_user_expire *ue = nlmsg_data(nlh);
struct xfrm_usersa_info *p = &ue->state;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
err = -ENOENT;
if (x == NULL)
return err;
spin_lock_bh(&x->lock);
err = -EINVAL;
if (x->km.state != XFRM_STATE_VALID)
goto out;
km_state_expired(x, ue->hard, current->pid);
if (ue->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
__xfrm_state_delete(x);
xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid);
}
err = 0;
out:
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_tmpl *ut;
int i;
struct nlattr *rt = attrs[XFRMA_TMPL];
struct xfrm_mark mark;
struct xfrm_user_acquire *ua = nlmsg_data(nlh);
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto nomem;
xfrm_mark_get(attrs, &mark);
err = verify_newpolicy_info(&ua->policy);
if (err)
goto bad_policy;
/* build an XP */
xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
if (!xp)
goto free_state;
memcpy(&x->id, &ua->id, sizeof(ua->id));
memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
xp->mark.m = x->mark.m = mark.m;
xp->mark.v = x->mark.v = mark.v;
ut = nla_data(rt);
/* extract the templates and for each call km_key */
for (i = 0; i < xp->xfrm_nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&x->id, &t->id, sizeof(x->id));
x->props.mode = t->mode;
x->props.reqid = t->reqid;
x->props.family = ut->family;
t->aalgos = ua->aalgos;
t->ealgos = ua->ealgos;
t->calgos = ua->calgos;
err = km_query(x, t, xp);
}
kfree(x);
kfree(xp);
return 0;
bad_policy:
WARN(1, "BAD policy passed\n");
free_state:
kfree(x);
nomem:
return err;
}
#ifdef CONFIG_XFRM_MIGRATE
static int copy_from_user_migrate(struct xfrm_migrate *ma,
struct xfrm_kmaddress *k,
struct nlattr **attrs, int *num)
{
struct nlattr *rt = attrs[XFRMA_MIGRATE];
struct xfrm_user_migrate *um;
int i, num_migrate;
if (k != NULL) {
struct xfrm_user_kmaddress *uk;
uk = nla_data(attrs[XFRMA_KMADDRESS]);
memcpy(&k->local, &uk->local, sizeof(k->local));
memcpy(&k->remote, &uk->remote, sizeof(k->remote));
k->family = uk->family;
k->reserved = uk->reserved;
}
um = nla_data(rt);
num_migrate = nla_len(rt) / sizeof(*um);
if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++, um++, ma++) {
memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
ma->proto = um->proto;
ma->mode = um->mode;
ma->reqid = um->reqid;
ma->old_family = um->old_family;
ma->new_family = um->new_family;
}
*num = i;
return 0;
}
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress km, *kmp;
u8 type;
int err;
int n = 0;
if (attrs[XFRMA_MIGRATE] == NULL)
return -EINVAL;
kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
if (err)
return err;
if (!n)
return 0;
xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp);
return 0;
}
#else
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
return -ENOPROTOOPT;
}
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
{
struct xfrm_user_migrate um;
memset(&um, 0, sizeof(um));
um.proto = m->proto;
um.mode = m->mode;
um.reqid = m->reqid;
um.old_family = m->old_family;
memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
um.new_family = m->new_family;
memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
}
static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
{
struct xfrm_user_kmaddress uk;
memset(&uk, 0, sizeof(uk));
uk.family = k->family;
uk.reserved = k->reserved;
memcpy(&uk.local, &k->local, sizeof(uk.local));
memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
}
static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma)
{
return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
+ (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
+ nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
+ userpolicy_type_attrsize();
}
static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
int num_migrate, const struct xfrm_kmaddress *k,
const struct xfrm_selector *sel, u8 dir, u8 type)
{
const struct xfrm_migrate *mp;
struct xfrm_userpolicy_id *pol_id;
struct nlmsghdr *nlh;
int i, err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
if (nlh == NULL)
return -EMSGSIZE;
pol_id = nlmsg_data(nlh);
/* copy data from selector, dir, and type to the pol_id */
memset(pol_id, 0, sizeof(*pol_id));
memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
pol_id->dir = dir;
if (k != NULL) {
err = copy_to_user_kmaddress(k, skb);
if (err)
goto out_cancel;
}
err = copy_to_user_policy_type(type, skb);
if (err)
goto out_cancel;
for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
err = copy_to_user_migrate(mp, skb);
if (err)
goto out_cancel;
}
return nlmsg_end(skb, nlh);
out_cancel:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
struct net *net = &init_net;
struct sk_buff *skb;
skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
/* build migrate */
if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC);
}
#else
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
#define XMSGSIZE(type) sizeof(struct type)
static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32),
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32),
};
#undef XMSGSIZE
static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
[XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)},
[XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)},
[XFRMA_LASTUSED] = { .type = NLA_U64},
[XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)},
[XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) },
[XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) },
[XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) },
[XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) },
[XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) },
[XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) },
[XFRMA_REPLAY_THRESH] = { .type = NLA_U32 },
[XFRMA_ETIMER_THRESH] = { .type = NLA_U32 },
[XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)},
[XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) },
[XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) },
[XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) },
[XFRMA_TFCPAD] = { .type = NLA_U32 },
[XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) },
};
static struct xfrm_link {
int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
int (*dump)(struct sk_buff *, struct netlink_callback *);
int (*done)(struct netlink_callback *);
} xfrm_dispatch[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa },
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
.dump = xfrm_dump_sa,
.done = xfrm_dump_sa_done },
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy },
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
.dump = xfrm_dump_policy,
.done = xfrm_dump_policy_done },
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire },
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa },
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy },
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae },
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae },
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate },
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo },
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo },
};
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
struct xfrm_link *link;
int type, err;
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,
xfrma_policy);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
static void xfrm_netlink_rcv(struct sk_buff *skb)
{
mutex_lock(&xfrm_cfg_mutex);
netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
mutex_unlock(&xfrm_cfg_mutex);
}
static inline size_t xfrm_expire_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
+ nla_total_size(sizeof(struct xfrm_mark));
}
static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
err = xfrm_mark_put(skb, &x->mark);
if (err)
return err;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_expire(skb, x, c) < 0) {
kfree_skb(skb);
return -EMSGSIZE;
}
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
static int xfrm_notify_sa_flush(const struct km_event *c)
{
struct net *net = c->net;
struct xfrm_usersa_flush *p;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
if (nlh == NULL) {
kfree_skb(skb);
return -EMSGSIZE;
}
p = nlmsg_data(nlh);
p->proto = c->data.proto;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
}
static inline size_t xfrm_sa_len(struct xfrm_state *x)
{
size_t l = 0;
if (x->aead)
l += nla_total_size(aead_len(x->aead));
if (x->aalg) {
l += nla_total_size(sizeof(struct xfrm_algo) +
(x->aalg->alg_key_len + 7) / 8);
l += nla_total_size(xfrm_alg_auth_len(x->aalg));
}
if (x->ealg)
l += nla_total_size(xfrm_alg_len(x->ealg));
if (x->calg)
l += nla_total_size(sizeof(*x->calg));
if (x->encap)
l += nla_total_size(sizeof(*x->encap));
if (x->tfcpad)
l += nla_total_size(sizeof(x->tfcpad));
if (x->replay_esn)
l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
if (x->security)
l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
x->security->ctx_len);
if (x->coaddr)
l += nla_total_size(sizeof(*x->coaddr));
/* Must count x->lastused as it may become non-zero behind our back. */
l += nla_total_size(sizeof(u64));
return l;
}
static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct xfrm_usersa_info *p;
struct xfrm_usersa_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = xfrm_sa_len(x);
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELSA) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
len += nla_total_size(sizeof(struct xfrm_mark));
}
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELSA) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
id->spi = x->id.spi;
id->family = x->props.family;
id->proto = x->id.proto;
attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
err = copy_to_user_state_extra(x, p, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_EXPIRE:
return xfrm_exp_state_notify(x, c);
case XFRM_MSG_NEWAE:
return xfrm_aevent_state_notify(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_UPDSA:
case XFRM_MSG_NEWSA:
return xfrm_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return xfrm_notify_sa_flush(c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
c->event);
break;
}
return 0;
}
static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x,
struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(xfrm_user_sec_ctx_size(x->security))
+ userpolicy_type_attrsize();
}
static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
struct xfrm_tmpl *xt, struct xfrm_policy *xp,
int dir)
{
__u32 seq = xfrm_get_acqseq();
struct xfrm_user_acquire *ua;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
if (nlh == NULL)
return -EMSGSIZE;
ua = nlmsg_data(nlh);
memcpy(&ua->id, &x->id, sizeof(ua->id));
memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
copy_to_user_policy(xp, &ua->policy, dir);
ua->aalgos = xt->aalgos;
ua->ealgos = xt->ealgos;
ua->calgos = xt->calgos;
ua->seq = x->km.seq = seq;
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_state_sec_ctx(x, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
struct xfrm_policy *xp, int dir)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_acquire(skb, x, xt, xp, dir) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC);
}
/* User gives us xfrm_user_policy_info followed by an array of 0
* or more templates.
*/
static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
struct xfrm_policy *xp;
int nr;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
if (opt != IPV6_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(*p) ||
verify_newpolicy_info(p))
return NULL;
nr = ((len - sizeof(*p)) / sizeof(*ut));
if (validate_tmpl(nr, ut, p->sel.family))
return NULL;
if (p->dir > XFRM_POLICY_OUT)
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
copy_from_user_policy(xp, p);
xp->type = XFRM_POLICY_TYPE_MAIN;
copy_templates(xp, ut, nr);
*dir = p->dir;
return xp;
}
static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(xfrm_user_sec_ctx_size(xp->security))
+ nla_total_size(sizeof(struct xfrm_mark))
+ userpolicy_type_attrsize();
}
static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
int dir, const struct km_event *c)
{
struct xfrm_user_polexpire *upe;
int hard = c->data.hard;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
if (nlh == NULL)
return -EMSGSIZE;
upe = nlmsg_data(nlh);
copy_to_user_policy(xp, &upe->pol, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_sec_ctx(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
upe->hard = !!hard;
return nlmsg_end(skb, nlh);
}
static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_polexpire(skb, xp, dir, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
struct net *net = xp_net(xp);
struct xfrm_userpolicy_info *p;
struct xfrm_userpolicy_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int headlen, err;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELPOLICY) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
}
len += userpolicy_type_attrsize();
len += nla_total_size(sizeof(struct xfrm_mark));
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELPOLICY) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memset(id, 0, sizeof(*id));
id->dir = dir;
if (c->data.byid)
id->index = xp->index;
else
memcpy(&id->sel, &xp->selector, sizeof(id->sel));
attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
err = -EMSGSIZE;
if (attr == NULL)
goto out_free_skb;
p = nla_data(attr);
}
copy_to_user_policy(xp, p, dir);
err = copy_to_user_tmpl(xp, skb);
if (!err)
err = copy_to_user_policy_type(xp->type, skb);
if (!err)
err = xfrm_mark_put(skb, &xp->mark);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_notify_policy_flush(const struct km_event *c)
{
struct net *net = c->net;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int err;
skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
err = -EMSGSIZE;
if (nlh == NULL)
goto out_free_skb;
err = copy_to_user_policy_type(c->data.type, skb);
if (err)
goto out_free_skb;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
out_free_skb:
kfree_skb(skb);
return err;
}
static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
case XFRM_MSG_DELPOLICY:
return xfrm_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
return xfrm_notify_policy_flush(c);
case XFRM_MSG_POLEXPIRE:
return xfrm_exp_policy_notify(xp, dir, c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
c->event);
}
return 0;
}
static inline size_t xfrm_report_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
}
static int build_report(struct sk_buff *skb, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct xfrm_user_report *ur;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
if (nlh == NULL)
return -EMSGSIZE;
ur = nlmsg_data(nlh);
ur->proto = proto;
memcpy(&ur->sel, sel, sizeof(ur->sel));
if (addr) {
int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
if (err) {
nlmsg_cancel(skb, nlh);
return err;
}
}
return nlmsg_end(skb, nlh);
}
static int xfrm_send_report(struct net *net, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct sk_buff *skb;
skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_report(skb, proto, sel, addr) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC);
}
static inline size_t xfrm_mapping_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
}
static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
xfrm_address_t *new_saddr, __be16 new_sport)
{
struct xfrm_user_mapping *um;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
if (nlh == NULL)
return -EMSGSIZE;
um = nlmsg_data(nlh);
memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
um->id.spi = x->id.spi;
um->id.family = x->props.family;
um->id.proto = x->id.proto;
memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
um->new_sport = new_sport;
um->old_sport = x->encap->encap_sport;
um->reqid = x->props.reqid;
return nlmsg_end(skb, nlh);
}
static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
__be16 sport)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
if (x->id.proto != IPPROTO_ESP)
return -EINVAL;
if (!x->encap)
return -EINVAL;
skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_mapping(skb, x, ipaddr, sport) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC);
}
static struct xfrm_mgr netlink_mgr = {
.id = "netlink",
.notify = xfrm_send_state_notify,
.acquire = xfrm_send_acquire,
.compile_policy = xfrm_compile_policy,
.notify_policy = xfrm_send_policy_notify,
.report = xfrm_send_report,
.migrate = xfrm_send_migrate,
.new_mapping = xfrm_send_mapping,
};
static int __net_init xfrm_user_net_init(struct net *net)
{
struct sock *nlsk;
struct netlink_kernel_cfg cfg = {
.groups = XFRMNLGRP_MAX,
.input = xfrm_netlink_rcv,
};
nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg);
if (nlsk == NULL)
return -ENOMEM;
net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
rcu_assign_pointer(net->xfrm.nlsk, nlsk);
return 0;
}
static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->xfrm.nlsk_stash);
}
static struct pernet_operations xfrm_user_net_ops = {
.init = xfrm_user_net_init,
.exit_batch = xfrm_user_net_exit,
};
static int __init xfrm_user_init(void)
{
int rv;
printk(KERN_INFO "Initializing XFRM netlink socket\n");
rv = register_pernet_subsys(&xfrm_user_net_ops);
if (rv < 0)
return rv;
rv = xfrm_register_km(&netlink_mgr);
if (rv < 0)
unregister_pernet_subsys(&xfrm_user_net_ops);
return rv;
}
static void __exit xfrm_user_exit(void)
{
xfrm_unregister_km(&netlink_mgr);
unregister_pernet_subsys(&xfrm_user_net_ops);
}
module_init(xfrm_user_init);
module_exit(xfrm_user_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3824_0 |
crossvul-cpp_data_bad_2490_1 | /* Copyright (c) 2001 Matej Pfajfar.
* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
* Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file entrynodes.c
* \brief Code to manage our fixed first nodes for various functions.
*
* Entry nodes can be guards (for general use) or bridges (for censorship
* circumvention).
*
* In general, we use entry guards to prevent traffic-sampling attacks:
* if we chose every circuit independently, an adversary controlling
* some fraction of paths on the network would observe a sample of every
* user's traffic. Using guards gives users a chance of not being
* profiled.
*
* The current entry guard selection code is designed to try to avoid
* _ever_ trying every guard on the network, to try to stick to guards
* that we've used before, to handle hostile/broken networks, and
* to behave sanely when the network goes up and down.
*
* Our algorithm works as follows: First, we maintain a SAMPLE of guards
* we've seen in the networkstatus consensus. We maintain this sample
* over time, and store it persistently; it is chosen without reference
* to our configuration or firewall rules. Guards remain in the sample
* as they enter and leave the consensus. We expand this sample as
* needed, up to a maximum size.
*
* As a subset of the sample, we maintain a FILTERED SET of the guards
* that we would be willing to use if we could connect to them. The
* filter removes all the guards that we're excluding because they're
* bridges (or not bridges), because we have restrictive firewall rules,
* because of ExcludeNodes, because we of path bias restrictions,
* because they're absent from the network at present, and so on.
*
* As a subset of the filtered set, we keep a REACHABLE FILTERED SET
* (also called a "usable filtered set") of those guards that we call
* "reachable" or "maybe reachable". A guard is reachable if we've
* connected to it more recently than we've failed. A guard is "maybe
* reachable" if we have never tried to connect to it, or if we
* failed to connect to it so long ago that we no longer think our
* failure means it's down.
*
* As a persistent ordered list whose elements are taken from the
* sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
* confirmed when we successfully build a circuit through it, and decide
* to use that circuit. We order the guards on this list by the order
* in which they became confirmed.
*
* And as a final group, we have an ordered list of PRIMARY GUARDS,
* whose elements are taken from the filtered set. We prefer
* confirmed guards to non-confirmed guards for this list, and place
* other restrictions on it. The primary guards are the ones that we
* connect to "when nothing is wrong" -- circuits through them can be used
* immediately.
*
* To build circuits, we take a primary guard if possible -- or a
* reachable filtered confirmed guard if no primary guard is possible --
* or a random reachable filtered guard otherwise. If the guard is
* primary, we can use the circuit immediately on success. Otherwise,
* the guard is now "pending" -- we won't use its circuit unless all
* of the circuits we're trying to build through better guards have
* definitely failed.
*
* While we're building circuits, we track a little "guard state" for
* each circuit. We use this to keep track of whether the circuit is
* one that we can use as soon as its done, or whether it's one that
* we should keep around to see if we can do better. In the latter case,
* a periodic call to entry_guards_upgrade_waiting_circuits() will
* eventually upgrade it.
**/
/* DOCDOC -- expand this.
*
* Information invariants:
*
* [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
*
* [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
* flag is set, set its usable_filtered flag.
*
* [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
*
* [x] Whenever the configuration changes in a relevant way, update the
* filtered/usable flags. (LATER.)
*
* [x] Whenever we add a guard to the sample, make sure its filtered/usable
* flags are set as possible.
*
* [x] Whenever we remove a guard from the sample, remove it from the primary
* and confirmed lists.
*
* [x] When we make a guard confirmed, update the primary list.
*
* [x] When we make a guard filtered or unfiltered, update the primary list.
*
* [x] When we are about to pick a guard, make sure that the primary list is
* full.
*
* [x] Before calling sample_reachable_filtered_entry_guards(), make sure
* that the filtered, primary, and confirmed flags are up-to-date.
*
* [x] Call entry_guard_consider_retry every time we are about to check
* is_usable_filtered or is_reachable, and every time we set
* is_filtered to 1.
*
* [x] Call entry_guards_changed_for_guard_selection() whenever we update
* a persistent field.
*/
#define ENTRYNODES_PRIVATE
#include "or.h"
#include "channel.h"
#include "bridges.h"
#include "circpathbias.h"
#include "circuitbuild.h"
#include "circuitlist.h"
#include "circuitstats.h"
#include "config.h"
#include "confparse.h"
#include "connection.h"
#include "control.h"
#include "directory.h"
#include "entrynodes.h"
#include "main.h"
#include "microdesc.h"
#include "networkstatus.h"
#include "nodelist.h"
#include "policies.h"
#include "router.h"
#include "routerlist.h"
#include "routerparse.h"
#include "routerset.h"
#include "transports.h"
#include "statefile.h"
/** A list of existing guard selection contexts. */
static smartlist_t *guard_contexts = NULL;
/** The currently enabled guard selection context. */
static guard_selection_t *curr_guard_context = NULL;
/** A value of 1 means that at least one context has changed,
* and those changes need to be flushed to disk. */
static int entry_guards_dirty = 0;
static void entry_guard_set_filtered_flags(const or_options_t *options,
guard_selection_t *gs,
entry_guard_t *guard);
static void pathbias_check_use_success_count(entry_guard_t *guard);
static void pathbias_check_close_success_count(entry_guard_t *guard);
static int node_is_possible_guard(const node_t *node);
static int node_passes_guard_filter(const or_options_t *options,
const node_t *node);
static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
const uint8_t *rsa_id_digest,
const char *nickname,
const tor_addr_port_t *bridge_addrport);
static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
const tor_addr_port_t *addrport);
static int entry_guard_obeys_restriction(const entry_guard_t *guard,
const entry_guard_restriction_t *rst);
/** Return 0 if we should apply guardfraction information found in the
* consensus. A specific consensus can be specified with the
* <b>ns</b> argument, if NULL the most recent one will be picked.*/
int
should_apply_guardfraction(const networkstatus_t *ns)
{
/* We need to check the corresponding torrc option and the consensus
* parameter if we need to. */
const or_options_t *options = get_options();
/* If UseGuardFraction is 'auto' then check the same-named consensus
* parameter. If the consensus parameter is not present, default to
* "off". */
if (options->UseGuardFraction == -1) {
return networkstatus_get_param(ns, "UseGuardFraction",
0, /* default to "off" */
0, 1);
}
return options->UseGuardFraction;
}
/** Return true iff we know a descriptor for <b>guard</b> */
static int
guard_has_descriptor(const entry_guard_t *guard)
{
const node_t *node = node_get_by_id(guard->identity);
if (!node)
return 0;
return node_has_descriptor(node);
}
/**
* Try to determine the correct type for a selection named "name",
* if <b>type</b> is GS_TYPE_INFER.
*/
STATIC guard_selection_type_t
guard_selection_infer_type(guard_selection_type_t type,
const char *name)
{
if (type == GS_TYPE_INFER) {
if (!strcmp(name, "bridges"))
type = GS_TYPE_BRIDGE;
else if (!strcmp(name, "restricted"))
type = GS_TYPE_RESTRICTED;
else
type = GS_TYPE_NORMAL;
}
return type;
}
/**
* Allocate and return a new guard_selection_t, with the name <b>name</b>.
*/
STATIC guard_selection_t *
guard_selection_new(const char *name,
guard_selection_type_t type)
{
guard_selection_t *gs;
type = guard_selection_infer_type(type, name);
gs = tor_malloc_zero(sizeof(*gs));
gs->name = tor_strdup(name);
gs->type = type;
gs->sampled_entry_guards = smartlist_new();
gs->confirmed_entry_guards = smartlist_new();
gs->primary_entry_guards = smartlist_new();
return gs;
}
/**
* Return the guard selection called <b>name</b>. If there is none, and
* <b>create_if_absent</b> is true, then create and return it. If there
* is none, and <b>create_if_absent</b> is false, then return NULL.
*/
STATIC guard_selection_t *
get_guard_selection_by_name(const char *name,
guard_selection_type_t type,
int create_if_absent)
{
if (!guard_contexts) {
guard_contexts = smartlist_new();
}
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
if (!strcmp(gs->name, name))
return gs;
} SMARTLIST_FOREACH_END(gs);
if (! create_if_absent)
return NULL;
log_debug(LD_GUARD, "Creating a guard selection called %s", name);
guard_selection_t *new_selection = guard_selection_new(name, type);
smartlist_add(guard_contexts, new_selection);
return new_selection;
}
/**
* Allocate the first guard context that we're planning to use,
* and make it the current context.
*/
static void
create_initial_guard_context(void)
{
tor_assert(! curr_guard_context);
if (!guard_contexts) {
guard_contexts = smartlist_new();
}
guard_selection_type_t type = GS_TYPE_INFER;
const char *name = choose_guard_selection(
get_options(),
networkstatus_get_live_consensus(approx_time()),
NULL,
&type);
tor_assert(name); // "name" can only be NULL if we had an old name.
tor_assert(type != GS_TYPE_INFER);
log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
curr_guard_context = get_guard_selection_by_name(name, type, 1);
}
/** Get current default guard_selection_t, creating it if necessary */
guard_selection_t *
get_guard_selection_info(void)
{
if (!curr_guard_context) {
create_initial_guard_context();
}
return curr_guard_context;
}
/** Return a statically allocated human-readable description of <b>guard</b>
*/
const char *
entry_guard_describe(const entry_guard_t *guard)
{
static char buf[256];
tor_snprintf(buf, sizeof(buf),
"%s ($%s)",
strlen(guard->nickname) ? guard->nickname : "[bridge]",
hex_str(guard->identity, DIGEST_LEN));
return buf;
}
/** Return <b>guard</b>'s 20-byte RSA identity digest */
const char *
entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
{
return guard->identity;
}
/** Return the pathbias state associated with <b>guard</b>. */
guard_pathbias_t *
entry_guard_get_pathbias_state(entry_guard_t *guard)
{
return &guard->pb;
}
HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
/** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
* chosen uniformly at random. We use this before recording persistent
* dates, so that we aren't leaking exactly when we recorded it.
*/
MOCK_IMPL(STATIC time_t,
randomize_time,(time_t now, time_t max_backdate))
{
tor_assert(max_backdate > 0);
time_t earliest = now - max_backdate;
time_t latest = now;
if (earliest <= 0)
earliest = 1;
if (latest <= earliest)
latest = earliest + 1;
return crypto_rand_time_range(earliest, latest);
}
/**
* @name parameters for networkstatus algorithm
*
* These parameters are taken from the consensus; some are overrideable in
* the torrc.
*/
/**@{*/
/**
* We never let our sampled guard set grow larger than this fraction
* of the guards on the network.
*/
STATIC double
get_max_sample_threshold(void)
{
int32_t pct =
networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
1, 100);
return pct / 100.0;
}
/**
* We never let our sampled guard set grow larger than this number.
*/
STATIC int
get_max_sample_size_absolute(void)
{
return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
DFLT_MAX_SAMPLE_SIZE,
1, INT32_MAX);
}
/**
* We always try to make our sample contain at least this many guards.
*/
STATIC int
get_min_filtered_sample_size(void)
{
return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
DFLT_MIN_FILTERED_SAMPLE_SIZE,
1, INT32_MAX);
}
/**
* If a guard is unlisted for this many days in a row, we remove it.
*/
STATIC int
get_remove_unlisted_guards_after_days(void)
{
return networkstatus_get_param(NULL,
"guard-remove-unlisted-guards-after-days",
DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
1, 365*10);
}
/**
* We remove unconfirmed guards from the sample after this many days,
* regardless of whether they are listed or unlisted.
*/
STATIC int
get_guard_lifetime(void)
{
if (get_options()->GuardLifetime >= 86400)
return get_options()->GuardLifetime;
int32_t days;
days = networkstatus_get_param(NULL,
"guard-lifetime-days",
DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
return days * 86400;
}
/**
* We remove confirmed guards from the sample if they were sampled
* GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
*/
STATIC int
get_guard_confirmed_min_lifetime(void)
{
if (get_options()->GuardLifetime >= 86400)
return get_options()->GuardLifetime;
int32_t days;
days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
1, 365*10);
return days * 86400;
}
/**
* How many guards do we try to keep on our primary guard list?
*/
STATIC int
get_n_primary_guards(void)
{
const int n = get_options()->NumEntryGuards;
const int n_dir = get_options()->NumDirectoryGuards;
if (n > 5) {
return MAX(n_dir, n + n / 2);
} else if (n >= 1) {
return MAX(n_dir, n * 2);
}
return networkstatus_get_param(NULL,
"guard-n-primary-guards",
DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
}
/**
* Return the number of the live primary guards we should look at when
* making a circuit.
*/
STATIC int
get_n_primary_guards_to_use(guard_usage_t usage)
{
int configured;
const char *param_name;
int param_default;
if (usage == GUARD_USAGE_DIRGUARD) {
configured = get_options()->NumDirectoryGuards;
param_name = "guard-n-primary-dir-guards-to-use";
param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
} else {
configured = get_options()->NumEntryGuards;
param_name = "guard-n-primary-guards-to-use";
param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
}
if (configured >= 1) {
return configured;
}
return networkstatus_get_param(NULL,
param_name, param_default, 1, INT32_MAX);
}
/**
* If we haven't successfully built or used a circuit in this long, then
* consider that the internet is probably down.
*/
STATIC int
get_internet_likely_down_interval(void)
{
return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
1, INT32_MAX);
}
/**
* If we're trying to connect to a nonprimary guard for at least this
* many seconds, and we haven't gotten the connection to work, we will treat
* lower-priority guards as usable.
*/
STATIC int
get_nonprimary_guard_connect_timeout(void)
{
return networkstatus_get_param(NULL,
"guard-nonprimary-guard-connect-timeout",
DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
1, INT32_MAX);
}
/**
* If a circuit has been sitting around in 'waiting for better guard' state
* for at least this long, we'll expire it.
*/
STATIC int
get_nonprimary_guard_idle_timeout(void)
{
return networkstatus_get_param(NULL,
"guard-nonprimary-guard-idle-timeout",
DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
1, INT32_MAX);
}
/**
* If our configuration retains fewer than this fraction of guards from the
* torrc, we are in a restricted setting.
*/
STATIC double
get_meaningful_restriction_threshold(void)
{
int32_t pct = networkstatus_get_param(NULL,
"guard-meaningful-restriction-percent",
DFLT_MEANINGFUL_RESTRICTION_PERCENT,
1, INT32_MAX);
return pct / 100.0;
}
/**
* If our configuration retains fewer than this fraction of guards from the
* torrc, we are in an extremely restricted setting, and should warn.
*/
STATIC double
get_extreme_restriction_threshold(void)
{
int32_t pct = networkstatus_get_param(NULL,
"guard-extreme-restriction-percent",
DFLT_EXTREME_RESTRICTION_PERCENT,
1, INT32_MAX);
return pct / 100.0;
}
/* Mark <b>guard</b> as maybe reachable again. */
static void
mark_guard_maybe_reachable(entry_guard_t *guard)
{
if (guard->is_reachable != GUARD_REACHABLE_NO) {
return;
}
/* Note that we do not clear failing_since: this guard is now only
* _maybe-reachable_. */
guard->is_reachable = GUARD_REACHABLE_MAYBE;
if (guard->is_filtered_guard)
guard->is_usable_filtered_guard = 1;
}
/**
* Called when the network comes up after having seemed to be down for
* a while: Mark the primary guards as maybe-reachable so that we'll
* try them again.
*/
STATIC void
mark_primary_guards_maybe_reachable(guard_selection_t *gs)
{
tor_assert(gs);
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
mark_guard_maybe_reachable(guard);
} SMARTLIST_FOREACH_END(guard);
}
/* Called when we exhaust all guards in our sampled set: Marks all guards as
maybe-reachable so that we 'll try them again. */
static void
mark_all_guards_maybe_reachable(guard_selection_t *gs)
{
tor_assert(gs);
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
mark_guard_maybe_reachable(guard);
} SMARTLIST_FOREACH_END(guard);
}
/**@}*/
/**
* Given our options and our list of nodes, return the name of the
* guard selection that we should use. Return NULL for "use the
* same selection you were using before.
*/
STATIC const char *
choose_guard_selection(const or_options_t *options,
const networkstatus_t *live_ns,
const guard_selection_t *old_selection,
guard_selection_type_t *type_out)
{
tor_assert(options);
tor_assert(type_out);
if (options->UseBridges) {
*type_out = GS_TYPE_BRIDGE;
return "bridges";
}
if (! live_ns) {
/* without a networkstatus, we can't tell any more than that. */
*type_out = GS_TYPE_NORMAL;
return "default";
}
const smartlist_t *nodes = nodelist_get_list();
int n_guards = 0, n_passing_filter = 0;
SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
if (node_is_possible_guard(node)) {
++n_guards;
if (node_passes_guard_filter(options, node)) {
++n_passing_filter;
}
}
} SMARTLIST_FOREACH_END(node);
/* We use separate 'high' and 'low' thresholds here to prevent flapping
* back and forth */
const int meaningful_threshold_high =
(int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
const int meaningful_threshold_mid =
(int)(n_guards * get_meaningful_restriction_threshold());
const int meaningful_threshold_low =
(int)(n_guards * get_meaningful_restriction_threshold() * .95);
const int extreme_threshold =
(int)(n_guards * get_extreme_restriction_threshold());
/*
If we have no previous selection, then we're "restricted" iff we are
below the meaningful restriction threshold. That's easy enough.
But if we _do_ have a previous selection, we make it a little
"sticky": we only move from "restricted" to "default" when we find
that we're above the threshold plus 5%, and we only move from
"default" to "restricted" when we're below the threshold minus 5%.
That should prevent us from flapping back and forth if we happen to
be hovering very close to the default.
The extreme threshold is for warning only.
*/
static int have_warned_extreme_threshold = 0;
if (n_guards &&
n_passing_filter < extreme_threshold &&
! have_warned_extreme_threshold) {
have_warned_extreme_threshold = 1;
const double exclude_frac =
(n_guards - n_passing_filter) / (double)n_guards;
log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
"guards. That's likely to make you stand out from the "
"rest of the world.", (int)(exclude_frac * 100));
}
/* Easy case: no previous selection. Just check if we are in restricted or
normal guard selection. */
if (old_selection == NULL) {
if (n_passing_filter >= meaningful_threshold_mid) {
*type_out = GS_TYPE_NORMAL;
return "default";
} else {
*type_out = GS_TYPE_RESTRICTED;
return "restricted";
}
}
/* Trickier case: we do have a previous guard selection context. */
tor_assert(old_selection);
/* Use high and low thresholds to decide guard selection, and if we fall in
the middle then keep the current guard selection context. */
if (n_passing_filter >= meaningful_threshold_high) {
*type_out = GS_TYPE_NORMAL;
return "default";
} else if (n_passing_filter < meaningful_threshold_low) {
*type_out = GS_TYPE_RESTRICTED;
return "restricted";
} else {
/* we are in the middle: maintain previous guard selection */
*type_out = old_selection->type;
return old_selection->name;
}
}
/**
* Check whether we should switch from our current guard selection to a
* different one. If so, switch and return 1. Return 0 otherwise.
*
* On a 1 return, the caller should mark all currently live circuits unusable
* for new streams, by calling circuit_mark_all_unused_circs() and
* circuit_mark_all_dirty_circs_as_unusable().
*/
int
update_guard_selection_choice(const or_options_t *options)
{
if (!curr_guard_context) {
create_initial_guard_context();
return 1;
}
guard_selection_type_t type = GS_TYPE_INFER;
const char *new_name = choose_guard_selection(
options,
networkstatus_get_live_consensus(approx_time()),
curr_guard_context,
&type);
tor_assert(new_name);
tor_assert(type != GS_TYPE_INFER);
const char *cur_name = curr_guard_context->name;
if (! strcmp(cur_name, new_name)) {
log_debug(LD_GUARD,
"Staying with guard context \"%s\" (no change)", new_name);
return 0; // No change
}
log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
new_name, cur_name);
guard_selection_t *new_guard_context;
new_guard_context = get_guard_selection_by_name(new_name, type, 1);
tor_assert(new_guard_context);
tor_assert(new_guard_context != curr_guard_context);
curr_guard_context = new_guard_context;
return 1;
}
/**
* Return true iff <b>node</b> has all the flags needed for us to consider it
* a possible guard when sampling guards.
*/
static int
node_is_possible_guard(const node_t *node)
{
/* The "GUARDS" set is all nodes in the nodelist for which this predicate
* holds. */
tor_assert(node);
return (node->is_possible_guard &&
node->is_stable &&
node->is_fast &&
node->is_valid &&
node_is_dir(node));
}
/**
* Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
* NULL if we don't have one. */
STATIC entry_guard_t *
get_sampled_guard_with_id(guard_selection_t *gs,
const uint8_t *rsa_id)
{
tor_assert(gs);
tor_assert(rsa_id);
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
return guard;
} SMARTLIST_FOREACH_END(guard);
return NULL;
}
/** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
* return that guard. Otherwise return NULL. */
static entry_guard_t *
get_sampled_guard_for_bridge(guard_selection_t *gs,
const bridge_info_t *bridge)
{
const uint8_t *id = bridge_get_rsa_id_digest(bridge);
const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
entry_guard_t *guard;
if (BUG(!addrport))
return NULL; // LCOV_EXCL_LINE
guard = get_sampled_guard_by_bridge_addr(gs, addrport);
if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
return NULL;
else
return guard;
}
/** If we know a bridge_info_t matching <b>guard</b>, return that
* bridge. Otherwise return NULL. */
static bridge_info_t *
get_bridge_info_for_guard(const entry_guard_t *guard)
{
const uint8_t *identity = NULL;
if (! tor_digest_is_zero(guard->identity)) {
identity = (const uint8_t *)guard->identity;
}
if (BUG(guard->bridge_addr == NULL))
return NULL;
return get_configured_bridge_by_exact_addr_port_digest(
&guard->bridge_addr->addr,
guard->bridge_addr->port,
(const char*)identity);
}
/**
* Return true iff we have a sampled guard with the RSA identity digest
* <b>rsa_id</b>. */
static inline int
have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
{
return get_sampled_guard_with_id(gs, rsa_id) != NULL;
}
/**
* Allocate a new entry_guard_t object for <b>node</b>, add it to the
* sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
* not currently be a sampled guard in <b>gs</b>.
*/
STATIC entry_guard_t *
entry_guard_add_to_sample(guard_selection_t *gs,
const node_t *node)
{
log_info(LD_GUARD, "Adding %s as to the entry guard sample set.",
node_describe(node));
/* make sure that the guard is not already sampled. */
if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
return NULL; // LCOV_EXCL_LINE
return entry_guard_add_to_sample_impl(gs,
(const uint8_t*)node->identity,
node_get_nickname(node),
NULL);
}
/**
* Backend: adds a new sampled guard to <b>gs</b>, with given identity,
* nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
* we need one of them. nickname is optional. The caller is responsible for
* maintaining the size limit of the SAMPLED_GUARDS set.
*/
static entry_guard_t *
entry_guard_add_to_sample_impl(guard_selection_t *gs,
const uint8_t *rsa_id_digest,
const char *nickname,
const tor_addr_port_t *bridge_addrport)
{
const int GUARD_LIFETIME = get_guard_lifetime();
tor_assert(gs);
// XXXX #20827 take ed25519 identity here too.
/* Make sure we can actually identify the guard. */
if (BUG(!rsa_id_digest && !bridge_addrport))
return NULL; // LCOV_EXCL_LINE
entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
/* persistent fields */
guard->is_persistent = (rsa_id_digest != NULL);
guard->selection_name = tor_strdup(gs->name);
if (rsa_id_digest)
memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
if (nickname)
strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
tor_free(guard->sampled_by_version);
guard->sampled_by_version = tor_strdup(VERSION);
guard->currently_listed = 1;
guard->confirmed_idx = -1;
/* non-persistent fields */
guard->is_reachable = GUARD_REACHABLE_MAYBE;
if (bridge_addrport)
guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
smartlist_add(gs->sampled_entry_guards, guard);
guard->in_selection = gs;
entry_guard_set_filtered_flags(get_options(), gs, guard);
entry_guards_changed_for_guard_selection(gs);
return guard;
}
/**
* Add an entry guard to the "bridges" guard selection sample, with
* information taken from <b>bridge</b>. Return that entry guard.
*/
static entry_guard_t *
entry_guard_add_bridge_to_sample(guard_selection_t *gs,
const bridge_info_t *bridge)
{
const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
tor_assert(addrport);
/* make sure that the guard is not already sampled. */
if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
return NULL; // LCOV_EXCL_LINE
return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
}
/**
* Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
* or NULL if none exists.
*/
static entry_guard_t *
get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
const tor_addr_port_t *addrport)
{
if (! gs)
return NULL;
if (BUG(!addrport))
return NULL;
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
return g;
} SMARTLIST_FOREACH_END(g);
return NULL;
}
/** Update the guard subsystem's knowledge of the identity of the bridge
* at <b>addrport</b>. Idempotent.
*/
void
entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
const uint8_t *rsa_id_digest)
{
guard_selection_t *gs = get_guard_selection_by_name("bridges",
GS_TYPE_BRIDGE,
0);
if (!gs)
return;
entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
if (!g)
return;
int make_persistent = 0;
if (tor_digest_is_zero(g->identity)) {
memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
make_persistent = 1;
} else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
/* Nothing to see here; we learned something we already knew. */
if (BUG(! g->is_persistent))
make_persistent = 1;
} else {
char old_id[HEX_DIGEST_LEN+1];
base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
"we already knew a different one (%s). Ignoring the new info as "
"possibly bogus.",
hex_str((const char *)rsa_id_digest, DIGEST_LEN),
fmt_and_decorate_addr(&addrport->addr), addrport->port,
old_id);
return; // redundant, but let's be clear: we're not making this persistent.
}
if (make_persistent) {
g->is_persistent = 1;
entry_guards_changed_for_guard_selection(gs);
}
}
/**
* Return the number of sampled guards in <b>gs</b> that are "filtered"
* (that is, we're willing to connect to them) and that are "usable"
* (that is, either "reachable" or "maybe reachable").
*
* If a restriction is provided in <b>rst</b>, do not count any guards that
* violate it.
*/
STATIC int
num_reachable_filtered_guards(guard_selection_t *gs,
const entry_guard_restriction_t *rst)
{
int n_reachable_filtered_guards = 0;
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
if (! entry_guard_obeys_restriction(guard, rst))
continue;
if (guard->is_usable_filtered_guard)
++n_reachable_filtered_guards;
} SMARTLIST_FOREACH_END(guard);
return n_reachable_filtered_guards;
}
/** Return the actual maximum size for the sample in <b>gs</b>,
* given that we know about <b>n_guards</b> total. */
static int
get_max_sample_size(guard_selection_t *gs,
int n_guards)
{
const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
const int min_sample = get_min_filtered_sample_size();
/* If we are in bridge mode, expand our sample set as needed without worrying
* about max size. We should respect the user's wishes to use many bridges if
* that's what they have specified in their configuration file. */
if (using_bridges)
return INT_MAX;
const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
const int max_sample_absolute = get_max_sample_size_absolute();
const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
if (max_sample < min_sample)
return min_sample;
else
return max_sample;
}
/**
* Return a smartlist of the all the guards that are not currently
* members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
* this list are node_t pointers in the non-bridge case, and
* bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
* to the number of guards that we found in GUARDS, including those
* that were already sampled.
*/
static smartlist_t *
get_eligible_guards(const or_options_t *options,
guard_selection_t *gs,
int *n_guards_out)
{
/* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
smartlist_t *eligible_guards = smartlist_new();
int n_guards = 0; // total size of "GUARDS"
if (gs->type == GS_TYPE_BRIDGE) {
const smartlist_t *bridges = bridge_list_get();
SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
++n_guards;
if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
continue;
}
smartlist_add(eligible_guards, bridge);
} SMARTLIST_FOREACH_END(bridge);
} else {
const smartlist_t *nodes = nodelist_get_list();
const int n_sampled = smartlist_len(gs->sampled_entry_guards);
/* Build a bloom filter of our current guards: let's keep this O(N). */
digestset_t *sampled_guard_ids = digestset_new(n_sampled);
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
guard) {
digestset_add(sampled_guard_ids, guard->identity);
} SMARTLIST_FOREACH_END(guard);
SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
if (! node_is_possible_guard(node))
continue;
if (gs->type == GS_TYPE_RESTRICTED) {
/* In restricted mode, we apply the filter BEFORE sampling, so
* that we are sampling from the nodes that we might actually
* select. If we sampled first, we might wind up with a sample
* that didn't include any EntryNodes at all. */
if (! node_passes_guard_filter(options, node))
continue;
}
++n_guards;
if (digestset_contains(sampled_guard_ids, node->identity))
continue;
smartlist_add(eligible_guards, (node_t*)node);
} SMARTLIST_FOREACH_END(node);
/* Now we can free that bloom filter. */
digestset_free(sampled_guard_ids);
}
*n_guards_out = n_guards;
return eligible_guards;
}
/** Helper: given a smartlist of either bridge_info_t (if gs->type is
* GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
* add it as a guard, remove it from the list, and return a new
* entry_guard_t. Return NULL on failure. */
static entry_guard_t *
select_and_add_guard_item_for_sample(guard_selection_t *gs,
smartlist_t *eligible_guards)
{
entry_guard_t *added_guard;
if (gs->type == GS_TYPE_BRIDGE) {
const bridge_info_t *bridge = smartlist_choose(eligible_guards);
if (BUG(!bridge))
return NULL; // LCOV_EXCL_LINE
smartlist_remove(eligible_guards, bridge);
added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
} else {
const node_t *node =
node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
if (BUG(!node))
return NULL; // LCOV_EXCL_LINE
smartlist_remove(eligible_guards, node);
added_guard = entry_guard_add_to_sample(gs, node);
}
return added_guard;
}
/** Return true iff we need a consensus to maintain our */
static int
live_consensus_is_missing(const guard_selection_t *gs)
{
tor_assert(gs);
if (gs->type == GS_TYPE_BRIDGE) {
/* We don't update bridges from the consensus; they aren't there. */
return 0;
}
return networkstatus_get_live_consensus(approx_time()) == NULL;
}
/**
* Add new guards to the sampled guards in <b>gs</b> until there are
* enough usable filtered guards, but never grow the sample beyond its
* maximum size. Return the last guard added, or NULL if none were
* added.
*/
STATIC entry_guard_t *
entry_guards_expand_sample(guard_selection_t *gs)
{
tor_assert(gs);
const or_options_t *options = get_options();
if (live_consensus_is_missing(gs)) {
log_info(LD_GUARD, "Not expanding the sample guard set; we have "
"no live consensus.");
return NULL;
}
int n_sampled = smartlist_len(gs->sampled_entry_guards);
entry_guard_t *added_guard = NULL;
int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
int n_guards = 0;
smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
const int max_sample = get_max_sample_size(gs, n_guards);
const int min_filtered_sample = get_min_filtered_sample_size();
log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
"in the sample, and %d eligible guards to extend it with.",
n_sampled, smartlist_len(eligible_guards));
while (n_usable_filtered_guards < min_filtered_sample) {
/* Has our sample grown too large to expand? */
if (n_sampled >= max_sample) {
log_info(LD_GUARD, "Not expanding the guard sample any further; "
"just hit the maximum sample threshold of %d",
max_sample);
goto done;
}
/* Did we run out of guards? */
if (smartlist_len(eligible_guards) == 0) {
/* LCOV_EXCL_START
As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
allow all guards to be sampled, this can't be reached.
*/
log_info(LD_GUARD, "Not expanding the guard sample any further; "
"just ran out of eligible guards");
goto done;
/* LCOV_EXCL_STOP */
}
/* Otherwise we can add at least one new guard. */
added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
if (!added_guard)
goto done; // LCOV_EXCL_LINE -- only fails on BUG.
++n_sampled;
if (added_guard->is_usable_filtered_guard)
++n_usable_filtered_guards;
}
done:
smartlist_free(eligible_guards);
return added_guard;
}
/**
* Helper: <b>guard</b> has just been removed from the sampled guards:
* also remove it from primary and confirmed. */
static void
remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
entry_guard_t *guard)
{
if (guard->is_primary) {
guard->is_primary = 0;
smartlist_remove_keeporder(gs->primary_entry_guards, guard);
} else {
if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
smartlist_remove_keeporder(gs->primary_entry_guards, guard);
}
}
if (guard->confirmed_idx >= 0) {
smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
guard->confirmed_idx = -1;
guard->confirmed_on_date = 0;
} else {
if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
// LCOV_EXCL_START
smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
// LCOV_EXCL_STOP
}
}
}
/** Return true iff <b>guard</b> is currently "listed" -- that is, it
* appears in the consensus, or as a configured bridge (as
* appropriate) */
MOCK_IMPL(STATIC int,
entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
{
if (gs->type == GS_TYPE_BRIDGE) {
return NULL != get_bridge_info_for_guard(guard);
} else {
const node_t *node = node_get_by_id(guard->identity);
return node && node_is_possible_guard(node);
}
}
/**
* Update the status of all sampled guards based on the arrival of a
* new consensus networkstatus document. This will include marking
* some guards as listed or unlisted, and removing expired guards. */
STATIC void
sampled_guards_update_from_consensus(guard_selection_t *gs)
{
tor_assert(gs);
const int REMOVE_UNLISTED_GUARDS_AFTER =
(get_remove_unlisted_guards_after_days() * 86400);
const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
// It's important to use only a live consensus here; we don't want to
// make changes based on anything expired or old.
if (live_consensus_is_missing(gs)) {
log_info(LD_GUARD, "Not updating the sample guard set; we have "
"no live consensus.");
return;
}
log_info(LD_GUARD, "Updating sampled guard status based on received "
"consensus.");
int n_changes = 0;
/* First: Update listed/unlisted. */
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
/* XXXX #20827 check ed ID too */
const int is_listed = entry_guard_is_listed(gs, guard);
if (is_listed && ! guard->currently_listed) {
++n_changes;
guard->currently_listed = 1;
guard->unlisted_since_date = 0;
log_info(LD_GUARD, "Sampled guard %s is now listed again.",
entry_guard_describe(guard));
} else if (!is_listed && guard->currently_listed) {
++n_changes;
guard->currently_listed = 0;
guard->unlisted_since_date = randomize_time(approx_time(),
unlisted_since_slop);
log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
entry_guard_describe(guard));
} else if (is_listed && guard->currently_listed) {
log_debug(LD_GUARD, "Sampled guard %s is still listed.",
entry_guard_describe(guard));
} else {
tor_assert(! is_listed && ! guard->currently_listed);
log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
entry_guard_describe(guard));
}
/* Clean up unlisted_since_date, just in case. */
if (guard->currently_listed && guard->unlisted_since_date) {
++n_changes;
guard->unlisted_since_date = 0;
log_warn(LD_BUG, "Sampled guard %s was listed, but with "
"unlisted_since_date set. Fixing.",
entry_guard_describe(guard));
} else if (!guard->currently_listed && ! guard->unlisted_since_date) {
++n_changes;
guard->unlisted_since_date = randomize_time(approx_time(),
unlisted_since_slop);
log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
"unlisted_since_date unset. Fixing.",
entry_guard_describe(guard));
}
} SMARTLIST_FOREACH_END(guard);
const time_t remove_if_unlisted_since =
approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
const time_t maybe_remove_if_sampled_before =
approx_time() - get_guard_lifetime();
const time_t remove_if_confirmed_before =
approx_time() - get_guard_confirmed_min_lifetime();
/* Then: remove the ones that have been junk for too long */
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
int rmv = 0;
if (guard->currently_listed == 0 &&
guard->unlisted_since_date < remove_if_unlisted_since) {
/*
"We have a live consensus, and {IS_LISTED} is false, and
{FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
days in the past."
*/
log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
"for over %d days", entry_guard_describe(guard),
get_remove_unlisted_guards_after_days());
rmv = 1;
} else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
/* We have a live consensus, and {ADDED_ON_DATE} is over
{GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
"never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
*/
if (guard->confirmed_on_date == 0) {
rmv = 1;
log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
"over %d days ago, but never confirmed.",
entry_guard_describe(guard),
get_guard_lifetime() / 86400);
} else if (guard->confirmed_on_date < remove_if_confirmed_before) {
rmv = 1;
log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
"over %d days ago, and confirmed over %d days ago.",
entry_guard_describe(guard),
get_guard_lifetime() / 86400,
get_guard_confirmed_min_lifetime() / 86400);
}
}
if (rmv) {
++n_changes;
SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
remove_guard_from_confirmed_and_primary_lists(gs, guard);
entry_guard_free(guard);
}
} SMARTLIST_FOREACH_END(guard);
if (n_changes) {
gs->primary_guards_up_to_date = 0;
entry_guards_update_filtered_sets(gs);
/* We don't need to rebuild the confirmed list right here -- we may have
* removed confirmed guards above, but we can't have added any new
* confirmed guards.
*/
entry_guards_changed_for_guard_selection(gs);
}
}
/**
* Return true iff <b>node</b> is a Tor relay that we are configured to
* be able to connect to. */
static int
node_passes_guard_filter(const or_options_t *options,
const node_t *node)
{
/* NOTE: Make sure that this function stays in sync with
* options_transition_affects_entry_guards */
if (routerset_contains_node(options->ExcludeNodes, node))
return 0;
if (options->EntryNodes &&
!routerset_contains_node(options->EntryNodes, node))
return 0;
if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
return 0;
if (node_is_a_configured_bridge(node))
return 0;
return 1;
}
/** Helper: Return true iff <b>bridge</b> passes our configuration
* filter-- if it is a relay that we are configured to be able to
* connect to. */
static int
bridge_passes_guard_filter(const or_options_t *options,
const bridge_info_t *bridge)
{
tor_assert(bridge);
if (!bridge)
return 0;
if (routerset_contains_bridge(options->ExcludeNodes, bridge))
return 0;
/* Ignore entrynodes */
const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
if (!fascist_firewall_allows_address_addr(&addrport->addr,
addrport->port,
FIREWALL_OR_CONNECTION,
0, 0))
return 0;
return 1;
}
/**
* Return true iff <b>guard</b> is a Tor relay that we are configured to
* be able to connect to, and we haven't disabled it for omission from
* the consensus or path bias issues. */
static int
entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
entry_guard_t *guard)
{
if (guard->currently_listed == 0)
return 0;
if (guard->pb.path_bias_disabled)
return 0;
if (gs->type == GS_TYPE_BRIDGE) {
const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
if (bridge == NULL)
return 0;
return bridge_passes_guard_filter(options, bridge);
} else {
const node_t *node = node_get_by_id(guard->identity);
if (node == NULL) {
// This can happen when currently_listed is true, and we're not updating
// it because we don't have a live consensus.
return 0;
}
return node_passes_guard_filter(options, node);
}
}
/**
* Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
* (If <b>rst</b> is NULL, there are no restrictions.)
*/
static int
entry_guard_obeys_restriction(const entry_guard_t *guard,
const entry_guard_restriction_t *rst)
{
tor_assert(guard);
if (! rst)
return 1; // No restriction? No problem.
// Only one kind of restriction exists right now
return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
}
/**
* Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
* flags on <b>guard</b>. */
void
entry_guard_set_filtered_flags(const or_options_t *options,
guard_selection_t *gs,
entry_guard_t *guard)
{
unsigned was_filtered = guard->is_filtered_guard;
guard->is_filtered_guard = 0;
guard->is_usable_filtered_guard = 0;
if (entry_guard_passes_filter(options, gs, guard)) {
guard->is_filtered_guard = 1;
if (guard->is_reachable != GUARD_REACHABLE_NO)
guard->is_usable_filtered_guard = 1;
entry_guard_consider_retry(guard);
}
log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
"reachable_filtered=%d.", entry_guard_describe(guard),
guard->is_filtered_guard, guard->is_usable_filtered_guard);
if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
/* This guard might now be primary or nonprimary. */
gs->primary_guards_up_to_date = 0;
}
}
/**
* Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
* flag on every guard in <b>gs</b>. */
STATIC void
entry_guards_update_filtered_sets(guard_selection_t *gs)
{
const or_options_t *options = get_options();
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
entry_guard_set_filtered_flags(options, gs, guard);
} SMARTLIST_FOREACH_END(guard);
}
/**
* Return a random guard from the reachable filtered sample guards
* in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
* Return NULL if no such guard can be found.
*
* Make sure that the sample is big enough, and that all the filter flags
* are set correctly, before calling this function.
*
* If a restriction is provided in <b>rst</b>, do not return any guards that
* violate it.
**/
STATIC entry_guard_t *
sample_reachable_filtered_entry_guards(guard_selection_t *gs,
const entry_guard_restriction_t *rst,
unsigned flags)
{
tor_assert(gs);
entry_guard_t *result = NULL;
const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
} SMARTLIST_FOREACH_END(guard);
const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
"in the USABLE_FILTERED set.", n_reachable_filtered);
const int min_filtered_sample = get_min_filtered_sample_size();
if (n_reachable_filtered < min_filtered_sample) {
log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
entry_guards_expand_sample(gs);
}
if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
entry_guards_update_primary(gs);
/* Build the set of reachable filtered guards. */
smartlist_t *reachable_filtered_sample = smartlist_new();
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);// redundant, but cheap.
if (! entry_guard_obeys_restriction(guard, rst))
continue;
if (! guard->is_usable_filtered_guard)
continue;
if (exclude_confirmed && guard->confirmed_idx >= 0)
continue;
if (exclude_primary && guard->is_primary)
continue;
if (exclude_pending && guard->is_pending)
continue;
if (need_descriptor && !guard_has_descriptor(guard))
continue;
smartlist_add(reachable_filtered_sample, guard);
} SMARTLIST_FOREACH_END(guard);
log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
flags, smartlist_len(reachable_filtered_sample));
if (smartlist_len(reachable_filtered_sample)) {
result = smartlist_choose(reachable_filtered_sample);
log_info(LD_GUARD, " (Selected %s.)",
result ? entry_guard_describe(result) : "<null>");
}
smartlist_free(reachable_filtered_sample);
return result;
}
/**
* Helper: compare two entry_guard_t by their confirmed_idx values.
* Used to sort the confirmed list.
*/
static int
compare_guards_by_confirmed_idx(const void **a_, const void **b_)
{
const entry_guard_t *a = *a_, *b = *b_;
if (a->confirmed_idx < b->confirmed_idx)
return -1;
else if (a->confirmed_idx > b->confirmed_idx)
return 1;
else
return 0;
}
/**
* Find the confirmed guards from among the sampled guards in <b>gs</b>,
* and put them in confirmed_entry_guards in the correct
* order. Recalculate their indices.
*/
STATIC void
entry_guards_update_confirmed(guard_selection_t *gs)
{
smartlist_clear(gs->confirmed_entry_guards);
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
if (guard->confirmed_idx >= 0)
smartlist_add(gs->confirmed_entry_guards, guard);
} SMARTLIST_FOREACH_END(guard);
smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
int any_changed = 0;
SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
if (guard->confirmed_idx != guard_sl_idx) {
any_changed = 1;
guard->confirmed_idx = guard_sl_idx;
}
} SMARTLIST_FOREACH_END(guard);
gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
if (any_changed) {
entry_guards_changed_for_guard_selection(gs);
}
}
/**
* Mark <b>guard</b> as a confirmed guard -- that is, one that we have
* connected to, and intend to use again.
*/
STATIC void
make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
{
if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
return; // LCOV_EXCL_LINE
if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
return; // LCOV_EXCL_LINE
const int GUARD_LIFETIME = get_guard_lifetime();
guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
entry_guard_describe(guard),
gs->next_confirmed_idx);
guard->confirmed_idx = gs->next_confirmed_idx++;
smartlist_add(gs->confirmed_entry_guards, guard);
// This confirmed guard might kick something else out of the primary
// guards.
gs->primary_guards_up_to_date = 0;
entry_guards_changed_for_guard_selection(gs);
}
/**
* Recalculate the list of primary guards (the ones we'd prefer to use) from
* the filtered sample and the confirmed list.
*/
STATIC void
entry_guards_update_primary(guard_selection_t *gs)
{
tor_assert(gs);
// prevent recursion. Recursion is potentially very bad here.
static int running = 0;
tor_assert(!running);
running = 1;
const int N_PRIMARY_GUARDS = get_n_primary_guards();
smartlist_t *new_primary_guards = smartlist_new();
smartlist_t *old_primary_guards = smartlist_new();
smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
/* Set this flag now, to prevent the calls below from recursing. */
gs->primary_guards_up_to_date = 1;
/* First, can we fill it up with confirmed guards? */
SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
break;
if (! guard->is_filtered_guard)
continue;
guard->is_primary = 1;
smartlist_add(new_primary_guards, guard);
} SMARTLIST_FOREACH_END(guard);
/* Can we keep any older primary guards? First remove all the ones
* that we already kept. */
SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
if (smartlist_contains(new_primary_guards, guard)) {
SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
}
} SMARTLIST_FOREACH_END(guard);
/* Now add any that are still good. */
SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
break;
if (! guard->is_filtered_guard)
continue;
guard->is_primary = 1;
smartlist_add(new_primary_guards, guard);
SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
} SMARTLIST_FOREACH_END(guard);
/* Mark the remaining previous primary guards as non-primary */
SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
guard->is_primary = 0;
} SMARTLIST_FOREACH_END(guard);
/* Finally, fill out the list with sampled guards. */
while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
SAMPLE_EXCLUDE_CONFIRMED|
SAMPLE_EXCLUDE_PRIMARY|
SAMPLE_NO_UPDATE_PRIMARY);
if (!guard)
break;
guard->is_primary = 1;
smartlist_add(new_primary_guards, guard);
}
#if 1
/* Debugging. */
SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
tor_assert_nonfatal(
bool_eq(guard->is_primary,
smartlist_contains(new_primary_guards, guard)));
});
#endif
int any_change = 0;
if (smartlist_len(gs->primary_entry_guards) !=
smartlist_len(new_primary_guards)) {
any_change = 1;
} else {
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
any_change = 1;
}
} SMARTLIST_FOREACH_END(g);
}
if (any_change) {
log_info(LD_GUARD, "Primary entry guards have changed. "
"New primary guard list is: ");
int n = smartlist_len(new_primary_guards);
SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
log_info(LD_GUARD, " %d/%d: %s%s%s",
g_sl_idx+1, n, entry_guard_describe(g),
g->confirmed_idx >= 0 ? " (confirmed)" : "",
g->is_filtered_guard ? "" : " (excluded by filter)");
} SMARTLIST_FOREACH_END(g);
}
smartlist_free(old_primary_guards);
smartlist_free(gs->primary_entry_guards);
gs->primary_entry_guards = new_primary_guards;
gs->primary_guards_up_to_date = 1;
running = 0;
}
/**
* Return the number of seconds after the last attempt at which we should
* retry a guard that has been failing since <b>failing_since</b>.
*/
static int
get_retry_schedule(time_t failing_since, time_t now,
int is_primary)
{
const unsigned SIX_HOURS = 6 * 3600;
const unsigned FOUR_DAYS = 4 * 86400;
const unsigned SEVEN_DAYS = 7 * 86400;
time_t tdiff;
if (now > failing_since) {
tdiff = now - failing_since;
} else {
tdiff = 0;
}
const struct {
time_t maximum; int primary_delay; int nonprimary_delay;
} delays[] = {
{ SIX_HOURS, 10*60, 1*60*60 },
{ FOUR_DAYS, 90*60, 4*60*60 },
{ SEVEN_DAYS, 4*60*60, 18*60*60 },
{ TIME_MAX, 9*60*60, 36*60*60 }
};
unsigned i;
for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
if (tdiff <= delays[i].maximum) {
return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
}
}
/* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
tor_assert_nonfatal_unreached();
return 36*60*60;
/* LCOV_EXCL_STOP */
}
/**
* If <b>guard</b> is unreachable, consider whether enough time has passed
* to consider it maybe-reachable again.
*/
STATIC void
entry_guard_consider_retry(entry_guard_t *guard)
{
if (guard->is_reachable != GUARD_REACHABLE_NO)
return; /* No retry needed. */
const time_t now = approx_time();
const int delay =
get_retry_schedule(guard->failing_since, now, guard->is_primary);
const time_t last_attempt = guard->last_tried_to_connect;
if (BUG(last_attempt == 0) ||
now >= last_attempt + delay) {
/* We should mark this retriable. */
char tbuf[ISO_TIME_LEN+1];
format_local_iso_time(tbuf, last_attempt);
log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
"haven't tried to use it since %s.",
guard->is_primary?"primary ":"",
guard->confirmed_idx>=0?"confirmed ":"",
entry_guard_describe(guard),
tbuf);
guard->is_reachable = GUARD_REACHABLE_MAYBE;
if (guard->is_filtered_guard)
guard->is_usable_filtered_guard = 1;
}
}
/** Tell the entry guards subsystem that we have confirmed that as of
* just now, we're on the internet. */
void
entry_guards_note_internet_connectivity(guard_selection_t *gs)
{
gs->last_time_on_internet = approx_time();
}
/**
* Get a guard for use with a circuit. Prefer to pick a running primary
* guard; then a non-pending running filtered confirmed guard; then a
* non-pending runnable filtered guard. Update the
* <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
* guard as appropriate. Set <b>state_out</b> to the new guard-state
* of the circuit.
*/
STATIC entry_guard_t *
select_entry_guard_for_circuit(guard_selection_t *gs,
guard_usage_t usage,
const entry_guard_restriction_t *rst,
unsigned *state_out)
{
const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
tor_assert(gs);
tor_assert(state_out);
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
int num_entry_guards = get_n_primary_guards_to_use(usage);
smartlist_t *usable_primary_guards = smartlist_new();
/* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
<maybe> or <yes>, return the first such guard." */
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
if (! entry_guard_obeys_restriction(guard, rst))
continue;
if (guard->is_reachable != GUARD_REACHABLE_NO) {
if (need_descriptor && !guard_has_descriptor(guard)) {
continue;
}
*state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
guard->last_tried_to_connect = approx_time();
smartlist_add(usable_primary_guards, guard);
if (smartlist_len(usable_primary_guards) >= num_entry_guards)
break;
}
} SMARTLIST_FOREACH_END(guard);
if (smartlist_len(usable_primary_guards)) {
entry_guard_t *guard = smartlist_choose(usable_primary_guards);
smartlist_free(usable_primary_guards);
log_info(LD_GUARD, "Selected primary guard %s for circuit.",
entry_guard_describe(guard));
return guard;
}
smartlist_free(usable_primary_guards);
/* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
and {USABLE_FILTERED_GUARDS} is nonempty, return the first
entry in that intersection that has {is_pending} set to
false." */
SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
if (guard->is_primary)
continue; /* we already considered this one. */
if (! entry_guard_obeys_restriction(guard, rst))
continue;
entry_guard_consider_retry(guard);
if (guard->is_usable_filtered_guard && ! guard->is_pending) {
if (need_descriptor && !guard_has_descriptor(guard))
continue; /* not a bug */
guard->is_pending = 1;
guard->last_tried_to_connect = approx_time();
*state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
log_info(LD_GUARD, "No primary guards available. Selected confirmed "
"guard %s for circuit. Will try other guards before using "
"this circuit.",
entry_guard_describe(guard));
return guard;
}
} SMARTLIST_FOREACH_END(guard);
/* "Otherwise, if there is no such entry, select a member at
random from {USABLE_FILTERED_GUARDS}." */
{
entry_guard_t *guard;
unsigned flags = 0;
if (need_descriptor)
flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
guard = sample_reachable_filtered_entry_guards(gs,
rst,
SAMPLE_EXCLUDE_CONFIRMED |
SAMPLE_EXCLUDE_PRIMARY |
SAMPLE_EXCLUDE_PENDING |
flags);
if (guard == NULL) {
log_info(LD_GUARD, "Absolutely no sampled guards were available. "
"Marking all guards for retry and starting from top again.");
mark_all_guards_maybe_reachable(gs);
return NULL;
}
guard->is_pending = 1;
guard->last_tried_to_connect = approx_time();
*state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
"random guard %s for circuit. Will try other guards before "
"using this circuit.",
entry_guard_describe(guard));
return guard;
}
}
/**
* Note that we failed to connect to or build circuits through <b>guard</b>.
* Use with a guard returned by select_entry_guard_for_circuit().
*/
STATIC void
entry_guards_note_guard_failure(guard_selection_t *gs,
entry_guard_t *guard)
{
tor_assert(gs);
guard->is_reachable = GUARD_REACHABLE_NO;
guard->is_usable_filtered_guard = 0;
guard->is_pending = 0;
if (guard->failing_since == 0)
guard->failing_since = approx_time();
log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
guard->is_primary?"primary ":"",
guard->confirmed_idx>=0?"confirmed ":"",
entry_guard_describe(guard));
}
/**
* Note that we successfully connected to, and built a circuit through
* <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
* return the new guard-state of the circuit.
*
* Be aware: the circuit is only usable when its guard-state becomes
* GUARD_CIRC_STATE_COMPLETE.
**/
STATIC unsigned
entry_guards_note_guard_success(guard_selection_t *gs,
entry_guard_t *guard,
unsigned old_state)
{
tor_assert(gs);
/* Save this, since we're about to overwrite it. */
const time_t last_time_on_internet = gs->last_time_on_internet;
gs->last_time_on_internet = approx_time();
guard->is_reachable = GUARD_REACHABLE_YES;
guard->failing_since = 0;
guard->is_pending = 0;
if (guard->is_filtered_guard)
guard->is_usable_filtered_guard = 1;
if (guard->confirmed_idx < 0) {
make_guard_confirmed(gs, guard);
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
}
unsigned new_state;
switch (old_state) {
case GUARD_CIRC_STATE_COMPLETE:
case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
new_state = GUARD_CIRC_STATE_COMPLETE;
break;
default:
tor_assert_nonfatal_unreached();
/* Fall through. */
case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
if (guard->is_primary) {
/* XXXX #20832 -- I don't actually like this logic. It seems to make
* us a little more susceptible to evil-ISP attacks. The mitigations
* I'm thinking of, however, aren't local to this point, so I'll leave
* it alone. */
/* This guard may have become primary by virtue of being confirmed.
* If so, the circuit for it is now complete.
*/
new_state = GUARD_CIRC_STATE_COMPLETE;
} else {
new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
}
break;
}
if (! guard->is_primary) {
if (last_time_on_internet + get_internet_likely_down_interval()
< approx_time()) {
mark_primary_guards_maybe_reachable(gs);
}
}
log_info(LD_GUARD, "Recorded success for %s%sguard %s",
guard->is_primary?"primary ":"",
guard->confirmed_idx>=0?"confirmed ":"",
entry_guard_describe(guard));
return new_state;
}
/**
* Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
*/
STATIC int
entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
{
tor_assert(a && b);
if (a == b)
return 0;
/* Confirmed is always better than unconfirmed; lower index better
than higher */
if (a->confirmed_idx < 0) {
if (b->confirmed_idx >= 0)
return 0;
} else {
if (b->confirmed_idx < 0)
return 1;
/* Lower confirmed_idx is better than higher. */
return (a->confirmed_idx < b->confirmed_idx);
}
/* If we reach this point, both are unconfirmed. If one is pending, it
* has higher priority. */
if (a->is_pending) {
if (! b->is_pending)
return 1;
/* Both are pending: earlier last_tried_connect wins. */
return a->last_tried_to_connect < b->last_tried_to_connect;
} else {
if (b->is_pending)
return 0;
/* Neither is pending: priorities are equal. */
return 0;
}
}
/** Release all storage held in <b>restriction</b> */
static void
entry_guard_restriction_free(entry_guard_restriction_t *rst)
{
tor_free(rst);
}
/**
* Release all storage held in <b>state</b>.
*/
void
circuit_guard_state_free(circuit_guard_state_t *state)
{
if (!state)
return;
entry_guard_restriction_free(state->restrictions);
entry_guard_handle_free(state->guard);
tor_free(state);
}
/**
* Pick a suitable entry guard for a circuit in, and place that guard
* in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
* state object that will record whether the circuit is ready to be used
* or not. Return 0 on success; on failure, return -1.
*
* If a restriction is provided in <b>rst</b>, do not return any guards that
* violate it, and remember that restriction in <b>guard_state_out</b> for
* later use. (Takes ownership of the <b>rst</b> object.)
*/
int
entry_guard_pick_for_circuit(guard_selection_t *gs,
guard_usage_t usage,
entry_guard_restriction_t *rst,
const node_t **chosen_node_out,
circuit_guard_state_t **guard_state_out)
{
tor_assert(gs);
tor_assert(chosen_node_out);
tor_assert(guard_state_out);
*chosen_node_out = NULL;
*guard_state_out = NULL;
unsigned state = 0;
entry_guard_t *guard =
select_entry_guard_for_circuit(gs, usage, rst, &state);
if (! guard)
goto fail;
if (BUG(state == 0))
goto fail;
const node_t *node = node_get_by_id(guard->identity);
// XXXX #20827 check Ed ID.
if (! node)
goto fail;
if (BUG(usage != GUARD_USAGE_DIRGUARD && !node_has_descriptor(node)))
goto fail;
*chosen_node_out = node;
*guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t));
(*guard_state_out)->guard = entry_guard_handle_new(guard);
(*guard_state_out)->state = state;
(*guard_state_out)->state_set_at = approx_time();
(*guard_state_out)->restrictions = rst;
return 0;
fail:
entry_guard_restriction_free(rst);
return -1;
}
/**
* Called by the circuit building module when a circuit has succeeded: informs
* the guards code that the guard in *<b>guard_state_p</b> is working, and
* advances the state of the guard module. On a GUARD_USABLE_NEVER return
* value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
* return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
* return value, the circuit should not be used until we find out whether
* preferred guards will work for us.
*/
guard_usable_t
entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
{
if (BUG(*guard_state_p == NULL))
return GUARD_USABLE_NEVER;
entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
if (! guard || BUG(guard->in_selection == NULL))
return GUARD_USABLE_NEVER;
unsigned newstate =
entry_guards_note_guard_success(guard->in_selection, guard,
(*guard_state_p)->state);
(*guard_state_p)->state = newstate;
(*guard_state_p)->state_set_at = approx_time();
if (newstate == GUARD_CIRC_STATE_COMPLETE) {
return GUARD_USABLE_NOW;
} else {
return GUARD_MAYBE_USABLE_LATER;
}
}
/** Cancel the selection of *<b>guard_state_p</b> without declaring
* success or failure. It is safe to call this function if success or
* failure _has_ already been declared. */
void
entry_guard_cancel(circuit_guard_state_t **guard_state_p)
{
if (BUG(*guard_state_p == NULL))
return;
entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
if (! guard)
return;
/* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
* function will only get called in "bug" cases anyway. */
guard->is_pending = 0;
circuit_guard_state_free(*guard_state_p);
*guard_state_p = NULL;
}
/**
* Called by the circuit building module when a circuit has succeeded:
* informs the guards code that the guard in *<b>guard_state_p</b> is
* not working, and advances the state of the guard module.
*/
void
entry_guard_failed(circuit_guard_state_t **guard_state_p)
{
if (BUG(*guard_state_p == NULL))
return;
entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
if (! guard || BUG(guard->in_selection == NULL))
return;
entry_guards_note_guard_failure(guard->in_selection, guard);
(*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
(*guard_state_p)->state_set_at = approx_time();
}
/**
* Run the entry_guard_failed() function on every circuit that is
* pending on <b>chan</b>.
*/
void
entry_guard_chan_failed(channel_t *chan)
{
if (!chan)
return;
smartlist_t *pending = smartlist_new();
circuit_get_all_pending_on_channel(pending, chan);
SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
if (!CIRCUIT_IS_ORIGIN(circ))
continue;
origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
if (origin_circ->guard_state) {
/* We might have no guard state if we didn't use a guard on this
* circuit (eg it's for a fallback directory). */
entry_guard_failed(&origin_circ->guard_state);
}
} SMARTLIST_FOREACH_END(circ);
smartlist_free(pending);
}
/**
* Return true iff every primary guard in <b>gs</b> is believed to
* be unreachable.
*/
STATIC int
entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
{
tor_assert(gs);
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
if (guard->is_reachable != GUARD_REACHABLE_NO)
return 0;
} SMARTLIST_FOREACH_END(guard);
return 1;
}
/** Wrapper for entry_guard_has_higher_priority that compares the
* guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
* priority than <b>b</b>.
*
* If a restriction is provided in <b>rst</b>, then do not consider
* <b>a</b> to have higher priority if it violates the restriction.
*/
static int
circ_state_has_higher_priority(origin_circuit_t *a,
const entry_guard_restriction_t *rst,
origin_circuit_t *b)
{
circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
tor_assert(state_a);
tor_assert(state_b);
entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
if (! guard_a) {
/* Unknown guard -- never higher priority. */
return 0;
} else if (! guard_b) {
/* Known guard -- higher priority than any unknown guard. */
return 1;
} else if (! entry_guard_obeys_restriction(guard_a, rst)) {
/* Restriction violated; guard_a cannot have higher priority. */
return 0;
} else {
/* Both known -- compare.*/
return entry_guard_has_higher_priority(guard_a, guard_b);
}
}
/**
* Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
* and see if any of them that were previously not ready to use for
* guard-related reasons are now ready to use. Place those circuits
* in <b>newly_complete_out</b>, and mark them COMPLETE.
*
* Return 1 if we upgraded any circuits, and 0 otherwise.
*/
int
entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
const smartlist_t *all_circuits_in,
smartlist_t *newly_complete_out)
{
tor_assert(gs);
tor_assert(all_circuits_in);
tor_assert(newly_complete_out);
if (! entry_guards_all_primary_guards_are_down(gs)) {
/* We only upgrade a waiting circuit if the primary guards are all
* down. */
log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
"but not all primary guards were definitely down.");
return 0;
}
int n_waiting = 0;
int n_complete = 0;
int n_complete_blocking = 0;
origin_circuit_t *best_waiting_circuit = NULL;
smartlist_t *all_circuits = smartlist_new();
SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
// We filter out circuits that aren't ours, or which we can't
// reason about.
circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
if (state == NULL)
continue;
entry_guard_t *guard = entry_guard_handle_get(state->guard);
if (!guard || guard->in_selection != gs)
continue;
smartlist_add(all_circuits, circ);
} SMARTLIST_FOREACH_END(circ);
SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
if BUG((state == NULL))
continue;
if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
++n_waiting;
if (! best_waiting_circuit ||
circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
best_waiting_circuit = circ;
}
}
} SMARTLIST_FOREACH_END(circ);
if (! best_waiting_circuit) {
log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
"but didn't find any.");
goto no_change;
}
/* We'll need to keep track of what restrictions were used when picking this
* circuit, so that we don't allow any circuit without those restrictions to
* block it. */
const entry_guard_restriction_t *rst_on_best_waiting =
origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
/* First look at the complete circuits: Do any block this circuit? */
SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
/* "C2 "blocks" C1 if:
* C2 obeys all the restrictions that C1 had to obey, AND
* C2 has higher priority than C1, AND
* Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
or C2 has been <usable_if_no_better_guard> for no more than
{NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
*/
circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
if BUG((state == NULL))
continue;
if (state->state != GUARD_CIRC_STATE_COMPLETE)
continue;
++n_complete;
if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
best_waiting_circuit))
++n_complete_blocking;
} SMARTLIST_FOREACH_END(circ);
if (n_complete_blocking) {
log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
"%d complete and %d guard-stalled. At least one complete "
"circuit had higher priority, so not upgrading.",
n_complete, n_waiting);
goto no_change;
}
/* " * If any circuit C1 is <waiting_for_better_guard>, AND:
* All primary guards have reachable status of <no>.
* There is no circuit C2 that "blocks" C1.
Then, upgrade C1 to <complete>.""
*/
int n_blockers_found = 0;
const time_t state_set_at_cutoff =
approx_time() - get_nonprimary_guard_connect_timeout();
SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
if (BUG(state == NULL))
continue;
if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
continue;
if (state->state_set_at <= state_set_at_cutoff)
continue;
if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
best_waiting_circuit))
++n_blockers_found;
} SMARTLIST_FOREACH_END(circ);
if (n_blockers_found) {
log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
"%d guard-stalled, but %d pending circuit(s) had higher "
"guard priority, so not upgrading.",
n_waiting, n_blockers_found);
goto no_change;
}
/* Okay. We have a best waiting circuit, and we aren't waiting for
anything better. Add all circuits with that priority to the
list, and call them COMPLETE. */
int n_succeeded = 0;
SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
if (BUG(state == NULL))
continue;
if (circ != best_waiting_circuit && rst_on_best_waiting) {
/* Can't upgrade other circ with same priority as best; might
be blocked. */
continue;
}
if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
continue;
if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
continue;
state->state = GUARD_CIRC_STATE_COMPLETE;
state->state_set_at = approx_time();
smartlist_add(newly_complete_out, circ);
++n_succeeded;
} SMARTLIST_FOREACH_END(circ);
log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
"%d guard-stalled, %d complete. %d of the guard-stalled "
"circuit(s) had high enough priority to upgrade.",
n_waiting, n_complete, n_succeeded);
tor_assert_nonfatal(n_succeeded >= 1);
smartlist_free(all_circuits);
return 1;
no_change:
smartlist_free(all_circuits);
return 0;
}
/**
* Return true iff the circuit whose state is <b>guard_state</b> should
* expire.
*/
int
entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
{
if (guard_state == NULL)
return 0;
const time_t expire_if_waiting_since =
approx_time() - get_nonprimary_guard_idle_timeout();
return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
&& guard_state->state_set_at < expire_if_waiting_since);
}
/**
* Update all derived pieces of the guard selection state in <b>gs</b>.
* Return true iff we should stop using all previously generated circuits.
*/
int
entry_guards_update_all(guard_selection_t *gs)
{
sampled_guards_update_from_consensus(gs);
entry_guards_update_filtered_sets(gs);
entry_guards_update_confirmed(gs);
entry_guards_update_primary(gs);
return 0;
}
/**
* Return a newly allocated string for encoding the persistent parts of
* <b>guard</b> to the state file.
*/
STATIC char *
entry_guard_encode_for_state(entry_guard_t *guard)
{
/*
* The meta-format we use is K=V K=V K=V... where K can be any
* characters excepts space and =, and V can be any characters except
* space. The order of entries is not allowed to matter.
* Unrecognized K=V entries are persisted; recognized but erroneous
* entries are corrected.
*/
smartlist_t *result = smartlist_new();
char tbuf[ISO_TIME_LEN+1];
tor_assert(guard);
smartlist_add_asprintf(result, "in=%s", guard->selection_name);
smartlist_add_asprintf(result, "rsa_id=%s",
hex_str(guard->identity, DIGEST_LEN));
if (guard->bridge_addr) {
smartlist_add_asprintf(result, "bridge_addr=%s:%d",
fmt_and_decorate_addr(&guard->bridge_addr->addr),
guard->bridge_addr->port);
}
if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
}
format_iso_time_nospace(tbuf, guard->sampled_on_date);
smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
if (guard->sampled_by_version) {
smartlist_add_asprintf(result, "sampled_by=%s",
guard->sampled_by_version);
}
if (guard->unlisted_since_date > 0) {
format_iso_time_nospace(tbuf, guard->unlisted_since_date);
smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
}
smartlist_add_asprintf(result, "listed=%d",
(int)guard->currently_listed);
if (guard->confirmed_idx >= 0) {
format_iso_time_nospace(tbuf, guard->confirmed_on_date);
smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
}
const double EPSILON = 1.0e-6;
/* Make a copy of the pathbias object, since we will want to update
some of them */
guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
pb->use_successes = pathbias_get_use_success_count(guard);
pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
#define PB_FIELD(field) do { \
if (pb->field >= EPSILON) { \
smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
} \
} while (0)
PB_FIELD(use_attempts);
PB_FIELD(use_successes);
PB_FIELD(circ_attempts);
PB_FIELD(circ_successes);
PB_FIELD(successful_circuits_closed);
PB_FIELD(collapsed_circuits);
PB_FIELD(unusable_circuits);
PB_FIELD(timeouts);
tor_free(pb);
#undef PB_FIELD
if (guard->extra_state_fields)
smartlist_add_strdup(result, guard->extra_state_fields);
char *joined = smartlist_join_strings(result, " ", 0, NULL);
SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
smartlist_free(result);
return joined;
}
/**
* Given a string generated by entry_guard_encode_for_state(), parse it
* (if possible) and return an entry_guard_t object for it. Return NULL
* on complete failure.
*/
STATIC entry_guard_t *
entry_guard_parse_from_state(const char *s)
{
/* Unrecognized entries get put in here. */
smartlist_t *extra = smartlist_new();
/* These fields get parsed from the string. */
char *in = NULL;
char *rsa_id = NULL;
char *nickname = NULL;
char *sampled_on = NULL;
char *sampled_by = NULL;
char *unlisted_since = NULL;
char *listed = NULL;
char *confirmed_on = NULL;
char *confirmed_idx = NULL;
char *bridge_addr = NULL;
// pathbias
char *pb_use_attempts = NULL;
char *pb_use_successes = NULL;
char *pb_circ_attempts = NULL;
char *pb_circ_successes = NULL;
char *pb_successful_circuits_closed = NULL;
char *pb_collapsed_circuits = NULL;
char *pb_unusable_circuits = NULL;
char *pb_timeouts = NULL;
/* Split up the entries. Put the ones we know about in strings and the
* rest in "extra". */
{
smartlist_t *entries = smartlist_new();
strmap_t *vals = strmap_new(); // Maps keyword to location
#define FIELD(f) \
strmap_set(vals, #f, &f);
FIELD(in);
FIELD(rsa_id);
FIELD(nickname);
FIELD(sampled_on);
FIELD(sampled_by);
FIELD(unlisted_since);
FIELD(listed);
FIELD(confirmed_on);
FIELD(confirmed_idx);
FIELD(bridge_addr);
FIELD(pb_use_attempts);
FIELD(pb_use_successes);
FIELD(pb_circ_attempts);
FIELD(pb_circ_successes);
FIELD(pb_successful_circuits_closed);
FIELD(pb_collapsed_circuits);
FIELD(pb_unusable_circuits);
FIELD(pb_timeouts);
#undef FIELD
smartlist_split_string(entries, s, " ",
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
const char *eq = strchr(entry, '=');
if (!eq) {
smartlist_add(extra, entry);
continue;
}
char *key = tor_strndup(entry, eq-entry);
char **target = strmap_get(vals, key);
if (target == NULL || *target != NULL) {
/* unrecognized or already set */
smartlist_add(extra, entry);
tor_free(key);
continue;
}
*target = tor_strdup(eq+1);
tor_free(key);
tor_free(entry);
} SMARTLIST_FOREACH_END(entry);
smartlist_free(entries);
strmap_free(vals, NULL);
}
entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
guard->is_persistent = 1;
if (in == NULL) {
log_warn(LD_CIRC, "Guard missing 'in' field");
goto err;
}
guard->selection_name = in;
in = NULL;
if (rsa_id == NULL) {
log_warn(LD_CIRC, "Guard missing RSA ID field");
goto err;
}
/* Process the identity and nickname. */
if (base16_decode(guard->identity, sizeof(guard->identity),
rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
goto err;
}
if (nickname) {
strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
} else {
guard->nickname[0]='$';
base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
guard->identity, DIGEST_LEN);
}
if (bridge_addr) {
tor_addr_port_t res;
memset(&res, 0, sizeof(res));
int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
&res.addr, &res.port, -1);
if (r == 0)
guard->bridge_addr = tor_memdup(&res, sizeof(res));
/* On error, we already warned. */
}
/* Process the various time fields. */
#define HANDLE_TIME(field) do { \
if (field) { \
int r = parse_iso_time_nospace(field, &field ## _time); \
if (r < 0) { \
log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
#field, escaped(field)); \
field##_time = -1; \
} \
} \
} while (0)
time_t sampled_on_time = 0;
time_t unlisted_since_time = 0;
time_t confirmed_on_time = 0;
HANDLE_TIME(sampled_on);
HANDLE_TIME(unlisted_since);
HANDLE_TIME(confirmed_on);
if (sampled_on_time <= 0)
sampled_on_time = approx_time();
if (unlisted_since_time < 0)
unlisted_since_time = 0;
if (confirmed_on_time < 0)
confirmed_on_time = 0;
#undef HANDLE_TIME
guard->sampled_on_date = sampled_on_time;
guard->unlisted_since_date = unlisted_since_time;
guard->confirmed_on_date = confirmed_on_time;
/* Take sampled_by_version verbatim. */
guard->sampled_by_version = sampled_by;
sampled_by = NULL; /* prevent free */
/* Listed is a boolean */
if (listed && strcmp(listed, "0"))
guard->currently_listed = 1;
/* The index is a nonnegative integer. */
guard->confirmed_idx = -1;
if (confirmed_idx) {
int ok=1;
long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
if (! ok) {
log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
escaped(confirmed_idx));
} else {
guard->confirmed_idx = (int)idx;
}
}
/* Anything we didn't recognize gets crammed together */
if (smartlist_len(extra) > 0) {
guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
}
/* initialize non-persistent fields */
guard->is_reachable = GUARD_REACHABLE_MAYBE;
#define PB_FIELD(field) \
do { \
if (pb_ ## field) { \
int ok = 1; \
double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
if (! ok) { \
log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
#field, pb_ ## field); \
} else { \
guard->pb.field = r; \
} \
} \
} while (0)
PB_FIELD(use_attempts);
PB_FIELD(use_successes);
PB_FIELD(circ_attempts);
PB_FIELD(circ_successes);
PB_FIELD(successful_circuits_closed);
PB_FIELD(collapsed_circuits);
PB_FIELD(unusable_circuits);
PB_FIELD(timeouts);
#undef PB_FIELD
pathbias_check_use_success_count(guard);
pathbias_check_close_success_count(guard);
/* We update everything on this guard later, after we've parsed
* everything. */
goto done;
err:
// only consider it an error if the guard state was totally unparseable.
entry_guard_free(guard);
guard = NULL;
done:
tor_free(in);
tor_free(rsa_id);
tor_free(nickname);
tor_free(sampled_on);
tor_free(sampled_by);
tor_free(unlisted_since);
tor_free(listed);
tor_free(confirmed_on);
tor_free(confirmed_idx);
tor_free(bridge_addr);
tor_free(pb_use_attempts);
tor_free(pb_use_successes);
tor_free(pb_circ_attempts);
tor_free(pb_circ_successes);
tor_free(pb_successful_circuits_closed);
tor_free(pb_collapsed_circuits);
tor_free(pb_unusable_circuits);
tor_free(pb_timeouts);
SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
smartlist_free(extra);
return guard;
}
/**
* Replace the Guards entries in <b>state</b> with a list of all our sampled
* guards.
*/
static void
entry_guards_update_guards_in_state(or_state_t *state)
{
if (!guard_contexts)
return;
config_line_t *lines = NULL;
config_line_t **nextline = &lines;
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
if (guard->is_persistent == 0)
continue;
*nextline = tor_malloc_zero(sizeof(config_line_t));
(*nextline)->key = tor_strdup("Guard");
(*nextline)->value = entry_guard_encode_for_state(guard);
nextline = &(*nextline)->next;
} SMARTLIST_FOREACH_END(guard);
} SMARTLIST_FOREACH_END(gs);
config_free_lines(state->Guard);
state->Guard = lines;
}
/**
* Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
* on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
* check whether replacing would work.)
*/
static int
entry_guards_load_guards_from_state(or_state_t *state, int set)
{
const config_line_t *line = state->Guard;
int n_errors = 0;
if (!guard_contexts)
guard_contexts = smartlist_new();
/* Wipe all our existing guard info. (we shouldn't have any, but
* let's be safe.) */
if (set) {
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
guard_selection_free(gs);
if (curr_guard_context == gs)
curr_guard_context = NULL;
SMARTLIST_DEL_CURRENT(guard_contexts, gs);
} SMARTLIST_FOREACH_END(gs);
}
for ( ; line != NULL; line = line->next) {
entry_guard_t *guard = entry_guard_parse_from_state(line->value);
if (guard == NULL) {
++n_errors;
continue;
}
tor_assert(guard->selection_name);
if (!strcmp(guard->selection_name, "legacy")) {
++n_errors;
entry_guard_free(guard);
continue;
}
if (set) {
guard_selection_t *gs;
gs = get_guard_selection_by_name(guard->selection_name,
GS_TYPE_INFER, 1);
tor_assert(gs);
smartlist_add(gs->sampled_entry_guards, guard);
guard->in_selection = gs;
} else {
entry_guard_free(guard);
}
}
if (set) {
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
entry_guards_update_all(gs);
} SMARTLIST_FOREACH_END(gs);
}
return n_errors ? -1 : 0;
}
/** If <b>digest</b> matches the identity of any node in the
* entry_guards list for the provided guard selection state,
return that node. Else return NULL. */
entry_guard_t *
entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
const char *digest)
{
return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
}
/** Return the node_t associated with a single entry_guard_t. May
* return NULL if the guard is not currently in the consensus. */
const node_t *
entry_guard_find_node(const entry_guard_t *guard)
{
tor_assert(guard);
return node_get_by_id(guard->identity);
}
/** If <b>digest</b> matches the identity of any node in the
* entry_guards list for the default guard selection state,
return that node. Else return NULL. */
entry_guard_t *
entry_guard_get_by_id_digest(const char *digest)
{
return entry_guard_get_by_id_digest_for_guard_selection(
get_guard_selection_info(), digest);
}
/** Release all storage held by <b>e</b>. */
STATIC void
entry_guard_free(entry_guard_t *e)
{
if (!e)
return;
entry_guard_handles_clear(e);
tor_free(e->sampled_by_version);
tor_free(e->extra_state_fields);
tor_free(e->selection_name);
tor_free(e->bridge_addr);
tor_free(e);
}
/** Return 0 if we're fine adding arbitrary routers out of the
* directory to our entry guard list, or return 1 if we have a
* list already and we must stick to it.
*/
int
entry_list_is_constrained(const or_options_t *options)
{
// XXXX #21425 look at the current selection.
if (options->EntryNodes)
return 1;
if (options->UseBridges)
return 1;
return 0;
}
/** Return the number of bridges that have descriptors that are marked with
* purpose 'bridge' and are running.
*/
int
num_bridges_usable(void)
{
int n_options = 0;
tor_assert(get_options()->UseBridges);
guard_selection_t *gs = get_guard_selection_info();
tor_assert(gs->type == GS_TYPE_BRIDGE);
SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
if (guard->is_reachable == GUARD_REACHABLE_NO)
continue;
if (tor_digest_is_zero(guard->identity))
continue;
const node_t *node = node_get_by_id(guard->identity);
if (node && node->ri)
++n_options;
} SMARTLIST_FOREACH_END(guard);
return n_options;
}
/** Check the pathbias use success count of <b>node</b> and disable it if it
* goes over our thresholds. */
static void
pathbias_check_use_success_count(entry_guard_t *node)
{
const or_options_t *options = get_options();
const double EPSILON = 1.0e-9;
/* Note: We rely on the < comparison here to allow us to set a 0
* rate and disable the feature entirely. If refactoring, don't
* change to <= */
if (node->pb.use_attempts > EPSILON &&
pathbias_get_use_success_count(node)/node->pb.use_attempts
< pathbias_get_extreme_use_rate(options) &&
pathbias_get_dropguards(options)) {
node->pb.path_bias_disabled = 1;
log_info(LD_GENERAL,
"Path use bias is too high (%f/%f); disabling node %s",
node->pb.circ_successes, node->pb.circ_attempts,
node->nickname);
}
}
/** Check the pathbias close count of <b>node</b> and disable it if it goes
* over our thresholds. */
static void
pathbias_check_close_success_count(entry_guard_t *node)
{
const or_options_t *options = get_options();
const double EPSILON = 1.0e-9;
/* Note: We rely on the < comparison here to allow us to set a 0
* rate and disable the feature entirely. If refactoring, don't
* change to <= */
if (node->pb.circ_attempts > EPSILON &&
pathbias_get_close_success_count(node)/node->pb.circ_attempts
< pathbias_get_extreme_rate(options) &&
pathbias_get_dropguards(options)) {
node->pb.path_bias_disabled = 1;
log_info(LD_GENERAL,
"Path bias is too high (%f/%f); disabling node %s",
node->pb.circ_successes, node->pb.circ_attempts,
node->nickname);
}
}
/** Parse <b>state</b> and learn about the entry guards it describes.
* If <b>set</b> is true, and there are no errors, replace the guard
* list in the default guard selection context with what we find.
* On success, return 0. On failure, alloc into *<b>msg</b> a string
* describing the error, and return -1.
*/
int
entry_guards_parse_state(or_state_t *state, int set, char **msg)
{
entry_guards_dirty = 0;
int r1 = entry_guards_load_guards_from_state(state, set);
entry_guards_dirty = 0;
if (r1 < 0) {
if (msg && *msg == NULL) {
*msg = tor_strdup("parsing error");
}
return -1;
}
return 0;
}
/** How long will we let a change in our guard nodes stay un-saved
* when we are trying to avoid disk writes? */
#define SLOW_GUARD_STATE_FLUSH_TIME 600
/** How long will we let a change in our guard nodes stay un-saved
* when we are not trying to avoid disk writes? */
#define FAST_GUARD_STATE_FLUSH_TIME 30
/** Our list of entry guards has changed for a particular guard selection
* context, or some element of one of our entry guards has changed for one.
* Write the changes to disk within the next few minutes.
*/
void
entry_guards_changed_for_guard_selection(guard_selection_t *gs)
{
time_t when;
tor_assert(gs != NULL);
entry_guards_dirty = 1;
if (get_options()->AvoidDiskWrites)
when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
else
when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
/* or_state_save() will call entry_guards_update_state() and
entry_guards_update_guards_in_state()
*/
or_state_mark_dirty(get_or_state(), when);
}
/** Our list of entry guards has changed for the default guard selection
* context, or some element of one of our entry guards has changed. Write
* the changes to disk within the next few minutes.
*/
void
entry_guards_changed(void)
{
entry_guards_changed_for_guard_selection(get_guard_selection_info());
}
/** If the entry guard info has not changed, do nothing and return.
* Otherwise, free the EntryGuards piece of <b>state</b> and create
* a new one out of the global entry_guards list, and then mark
* <b>state</b> dirty so it will get saved to disk.
*/
void
entry_guards_update_state(or_state_t *state)
{
entry_guards_dirty = 0;
// Handles all guard info.
entry_guards_update_guards_in_state(state);
entry_guards_dirty = 0;
if (!get_options()->AvoidDiskWrites)
or_state_mark_dirty(get_or_state(), 0);
entry_guards_dirty = 0;
}
/**
* Format a single entry guard in the format expected by the controller.
* Return a newly allocated string.
*/
STATIC char *
getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
{
const char *status = NULL;
time_t when = 0;
const node_t *node;
char tbuf[ISO_TIME_LEN+1];
char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
/* This is going to be a bit tricky, since the status
* codes weren't really intended for prop271 guards.
*
* XXXX use a more appropriate format for exporting this information
*/
if (e->confirmed_idx < 0) {
status = "never-connected";
} else if (! e->currently_listed) {
when = e->unlisted_since_date;
status = "unusable";
} else if (! e->is_filtered_guard) {
status = "unusable";
} else if (e->is_reachable == GUARD_REACHABLE_NO) {
when = e->failing_since;
status = "down";
} else {
status = "up";
}
node = entry_guard_find_node(e);
if (node) {
node_get_verbose_nickname(node, nbuf);
} else {
nbuf[0] = '$';
base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
/* e->nickname field is not very reliable if we don't know about
* this router any longer; don't include it. */
}
char *result = NULL;
if (when) {
format_iso_time(tbuf, when);
tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
} else {
tor_asprintf(&result, "%s %s\n", nbuf, status);
}
return result;
}
/** If <b>question</b> is the string "entry-guards", then dump
* to *<b>answer</b> a newly allocated string describing all of
* the nodes in the global entry_guards list. See control-spec.txt
* for details.
* For backward compatibility, we also handle the string "helper-nodes".
*
* XXX this should be totally redesigned after prop 271 too, and that's
* going to take some control spec work.
* */
int
getinfo_helper_entry_guards(control_connection_t *conn,
const char *question, char **answer,
const char **errmsg)
{
guard_selection_t *gs = get_guard_selection_info();
tor_assert(gs != NULL);
(void) conn;
(void) errmsg;
if (!strcmp(question,"entry-guards") ||
!strcmp(question,"helper-nodes")) {
const smartlist_t *guards;
guards = gs->sampled_entry_guards;
smartlist_t *sl = smartlist_new();
SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
char *cp = getinfo_helper_format_single_entry_guard(e);
smartlist_add(sl, cp);
} SMARTLIST_FOREACH_END(e);
*answer = smartlist_join_strings(sl, "", 0, NULL);
SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
smartlist_free(sl);
}
return 0;
}
/* Given the original bandwidth of a guard and its guardfraction,
* calculate how much bandwidth the guard should have as a guard and
* as a non-guard.
*
* Quoting from proposal236:
*
* Let Wpf denote the weight from the 'bandwidth-weights' line a
* client would apply to N for position p if it had the guard
* flag, Wpn the weight if it did not have the guard flag, and B the
* measured bandwidth of N in the consensus. Then instead of choosing
* N for position p proportionally to Wpf*B or Wpn*B, clients should
* choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
*
* This function fills the <b>guardfraction_bw</b> structure. It sets
* <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
*/
void
guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
int orig_bandwidth,
uint32_t guardfraction_percentage)
{
double guardfraction_fraction;
/* Turn the percentage into a fraction. */
tor_assert(guardfraction_percentage <= 100);
guardfraction_fraction = guardfraction_percentage / 100.0;
long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
tor_assert(guard_bw <= INT_MAX);
guardfraction_bw->guard_bw = (int) guard_bw;
guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
}
/** Helper: Update the status of all entry guards, in whatever algorithm
* is used. Return true if we should stop using all previously generated
* circuits, by calling circuit_mark_all_unused_circs() and
* circuit_mark_all_dirty_circs_as_unusable().
*/
int
guards_update_all(void)
{
int mark_circuits = 0;
if (update_guard_selection_choice(get_options()))
mark_circuits = 1;
tor_assert(curr_guard_context);
if (entry_guards_update_all(curr_guard_context))
mark_circuits = 1;
return mark_circuits;
}
/** Helper: pick a guard for a circuit, with whatever algorithm is
used. */
const node_t *
guards_choose_guard(cpath_build_state_t *state,
circuit_guard_state_t **guard_state_out)
{
const node_t *r = NULL;
const uint8_t *exit_id = NULL;
entry_guard_restriction_t *rst = NULL;
if (state && (exit_id = build_state_get_exit_rsa_id(state))) {
/* We're building to a targeted exit node, so that node can't be
* chosen as our guard for this circuit. Remember that fact in a
* restriction. */
rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
}
if (entry_guard_pick_for_circuit(get_guard_selection_info(),
GUARD_USAGE_TRAFFIC,
rst,
&r,
guard_state_out) < 0) {
tor_assert(r == NULL);
}
return r;
}
/** Remove all currently listed entry guards for a given guard selection
* context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
* after calling this function. */
void
remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
{
// This function shouldn't exist. XXXX
tor_assert(gs != NULL);
char *old_name = tor_strdup(gs->name);
guard_selection_type_t old_type = gs->type;
SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
control_event_guard(entry->nickname, entry->identity, "DROPPED");
});
if (gs == curr_guard_context) {
curr_guard_context = NULL;
}
smartlist_remove(guard_contexts, gs);
guard_selection_free(gs);
gs = get_guard_selection_by_name(old_name, old_type, 1);
entry_guards_changed_for_guard_selection(gs);
tor_free(old_name);
}
/** Remove all currently listed entry guards, so new ones will be chosen.
*
* XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
* command, which is deprecated.
*/
void
remove_all_entry_guards(void)
{
remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
}
/** Helper: pick a directory guard, with whatever algorithm is used. */
const node_t *
guards_choose_dirguard(circuit_guard_state_t **guard_state_out)
{
const node_t *r = NULL;
if (entry_guard_pick_for_circuit(get_guard_selection_info(),
GUARD_USAGE_DIRGUARD,
NULL,
&r,
guard_state_out) < 0) {
tor_assert(r == NULL);
}
return r;
}
/**
* If we're running with a constrained guard set, then maybe mark our guards
* usable. Return 1 if we do; 0 if we don't.
*/
int
guards_retry_optimistic(const or_options_t *options)
{
if (! entry_list_is_constrained(options))
return 0;
mark_primary_guards_maybe_reachable(get_guard_selection_info());
return 1;
}
/**
* Return true iff we know enough directory information to construct
* circuits through all of the primary guards we'd currently use.
*/
int
guard_selection_have_enough_dir_info_to_build_circuits(guard_selection_t *gs)
{
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
int n_missing_descriptors = 0;
int n_considered = 0;
int num_primary_to_check;
/* We want to check for the descriptor of at least the first two primary
* guards in our list, since these are the guards that we typically use for
* circuits. */
num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
num_primary_to_check++;
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
if (guard->is_reachable == GUARD_REACHABLE_NO)
continue;
n_considered++;
if (!guard_has_descriptor(guard))
n_missing_descriptors++;
if (n_considered >= num_primary_to_check)
break;
} SMARTLIST_FOREACH_END(guard);
return n_missing_descriptors == 0;
}
/** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
* the default guard selection. */
int
entry_guards_have_enough_dir_info_to_build_circuits(void)
{
return guard_selection_have_enough_dir_info_to_build_circuits(
get_guard_selection_info());
}
/** Free one guard selection context */
STATIC void
guard_selection_free(guard_selection_t *gs)
{
if (!gs) return;
tor_free(gs->name);
if (gs->sampled_entry_guards) {
SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
entry_guard_free(e));
smartlist_free(gs->sampled_entry_guards);
gs->sampled_entry_guards = NULL;
}
smartlist_free(gs->confirmed_entry_guards);
smartlist_free(gs->primary_entry_guards);
tor_free(gs);
}
/** Release all storage held by the list of entry guards and related
* memory structs. */
void
entry_guards_free_all(void)
{
/* Null out the default */
curr_guard_context = NULL;
/* Free all the guard contexts */
if (guard_contexts != NULL) {
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
guard_selection_free(gs);
} SMARTLIST_FOREACH_END(gs);
smartlist_free(guard_contexts);
guard_contexts = NULL;
}
circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2490_1 |
crossvul-cpp_data_good_4051_0 | /*
* Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Support for IMAP4rev1, with the occasional nod to IMAP 4. */
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "mutt.h"
#include "mx.h"
#include "mailbox.h"
#include "globals.h"
#include "sort.h"
#include "browser.h"
#include "imap_private.h"
#if defined(USE_SSL)
# include "mutt_ssl.h"
#endif
#if defined(USE_ZLIB)
# include "mutt_zstrm.h"
#endif
#include "buffy.h"
#if USE_HCACHE
#include "hcache.h"
#endif
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
/* imap forward declarations */
static char* imap_get_flags (LIST** hflags, char* s);
static int imap_check_capabilities (IMAP_DATA* idata);
static void imap_set_flag (IMAP_DATA* idata, int aclbit, int flag,
const char* str, char* flags, size_t flsize);
/* imap_access: Check permissions on an IMAP mailbox.
* TODO: ACL checks. Right now we assume if it exists we can
* mess with it. */
int imap_access (const char* path)
{
IMAP_DATA* idata;
IMAP_MBOX mx;
char buf[LONG_STRING*2];
char mailbox[LONG_STRING];
char mbox[LONG_STRING];
int rc;
if (imap_parse_path (path, &mx))
return -1;
if (!(idata = imap_conn_find (&mx.account,
option (OPTIMAPPASSIVE) ? MUTT_IMAP_CONN_NONEW : 0)))
{
FREE (&mx.mbox);
return -1;
}
imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
if (!*mailbox)
strfcpy (mailbox, "INBOX", sizeof (mailbox));
/* we may already be in the folder we're checking */
if (!ascii_strcmp(idata->mailbox, mx.mbox))
{
FREE (&mx.mbox);
return 0;
}
FREE (&mx.mbox);
if (imap_mboxcache_get (idata, mailbox, 0))
{
dprint (3, (debugfile, "imap_access: found %s in cache\n", mailbox));
return 0;
}
imap_munge_mbox_name (idata, mbox, sizeof (mbox), mailbox);
if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
else if (mutt_bit_isset (idata->capabilities, STATUS))
snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
else
{
dprint (2, (debugfile, "imap_access: STATUS not supported?\n"));
return -1;
}
if ((rc = imap_exec (idata, buf, IMAP_CMD_FAIL_OK)) < 0)
{
dprint (1, (debugfile, "imap_access: Can't check STATUS of %s\n", mbox));
return rc;
}
return 0;
}
int imap_create_mailbox (IMAP_DATA* idata, char* mailbox)
{
char buf[LONG_STRING*2], mbox[LONG_STRING];
imap_munge_mbox_name (idata, mbox, sizeof (mbox), mailbox);
snprintf (buf, sizeof (buf), "CREATE %s", mbox);
if (imap_exec (idata, buf, 0) != 0)
{
mutt_error (_("CREATE failed: %s"), imap_cmd_trailer (idata));
return -1;
}
return 0;
}
int imap_rename_mailbox (IMAP_DATA* idata, IMAP_MBOX* mx, const char* newname)
{
char oldmbox[LONG_STRING];
char newmbox[LONG_STRING];
BUFFER *b;
int rc = 0;
imap_munge_mbox_name (idata, oldmbox, sizeof (oldmbox), mx->mbox);
imap_munge_mbox_name (idata, newmbox, sizeof (newmbox), newname);
b = mutt_buffer_pool_get ();
mutt_buffer_printf (b, "RENAME %s %s", oldmbox, newmbox);
if (imap_exec (idata, mutt_b2s (b), 0) != 0)
rc = -1;
mutt_buffer_pool_release (&b);
return rc;
}
int imap_delete_mailbox (CONTEXT* ctx, IMAP_MBOX mx)
{
char buf[LONG_STRING*2], mbox[LONG_STRING];
IMAP_DATA *idata;
if (!ctx || !ctx->data)
{
if (!(idata = imap_conn_find (&mx.account,
option (OPTIMAPPASSIVE) ? MUTT_IMAP_CONN_NONEW : 0)))
{
FREE (&mx.mbox);
return -1;
}
}
else
{
idata = ctx->data;
}
imap_munge_mbox_name (idata, mbox, sizeof (mbox), mx.mbox);
snprintf (buf, sizeof (buf), "DELETE %s", mbox);
if (imap_exec ((IMAP_DATA*) idata, buf, 0) != 0)
return -1;
return 0;
}
/* imap_logout_all: close all open connections. Quick and dirty until we can
* make sure we've got all the context we need. */
void imap_logout_all (void)
{
CONNECTION* conn;
CONNECTION* tmp;
conn = mutt_socket_head ();
while (conn)
{
tmp = conn->next;
if (conn->account.type == MUTT_ACCT_TYPE_IMAP && conn->fd >= 0)
{
mutt_message (_("Closing connection to %s..."), conn->account.host);
imap_logout ((IMAP_DATA**) (void*) &conn->data);
mutt_clear_error ();
mutt_socket_free (conn);
}
conn = tmp;
}
}
/* imap_read_literal: read bytes bytes from server into file. Not explicitly
* buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
* Apparently even literals use \r\n-terminated strings ?! */
int imap_read_literal (FILE* fp, IMAP_DATA* idata, unsigned int bytes, progress_t* pbar)
{
unsigned int pos;
char c;
int r = 0;
dprint (2, (debugfile, "imap_read_literal: reading %ld bytes\n", bytes));
for (pos = 0; pos < bytes; pos++)
{
if (mutt_socket_readchar (idata->conn, &c) != 1)
{
dprint (1, (debugfile, "imap_read_literal: error during read, %ld bytes read\n", pos));
idata->status = IMAP_FATAL;
return -1;
}
#if 1
if (r == 1 && c != '\n')
fputc ('\r', fp);
if (c == '\r')
{
r = 1;
continue;
}
else
r = 0;
#endif
fputc (c, fp);
if (pbar && !(pos % 1024))
mutt_progress_update (pbar, pos, -1);
#ifdef DEBUG
if (debuglevel >= IMAP_LOG_LTRL)
fputc (c, debugfile);
#endif
}
return 0;
}
/* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
* context. Must not be done while something has a handle on any headers
* (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
void imap_expunge_mailbox (IMAP_DATA* idata)
{
HEADER* h;
int i, cacheno;
short old_sort;
#ifdef USE_HCACHE
idata->hcache = imap_hcache_open (idata, NULL);
#endif
old_sort = Sort;
Sort = SORT_ORDER;
mutt_sort_headers (idata->ctx, 0);
for (i = 0; i < idata->ctx->msgcount; i++)
{
h = idata->ctx->hdrs[i];
if (h->index == INT_MAX)
{
dprint (2, (debugfile, "Expunging message UID %u.\n", HEADER_DATA (h)->uid));
h->active = 0;
idata->ctx->size -= h->content->length;
imap_cache_del (idata, h);
#if USE_HCACHE
imap_hcache_del (idata, HEADER_DATA(h)->uid);
#endif
/* free cached body from disk, if necessary */
cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN;
if (idata->cache[cacheno].uid == HEADER_DATA(h)->uid &&
idata->cache[cacheno].path)
{
unlink (idata->cache[cacheno].path);
FREE (&idata->cache[cacheno].path);
}
int_hash_delete (idata->uid_hash, HEADER_DATA(h)->uid, h, NULL);
imap_free_header_data ((IMAP_HEADER_DATA**)&h->data);
}
else
{
h->index = i;
/* Mutt has several places where it turns off h->active as a
* hack. For example to avoid FLAG updates, or to exclude from
* imap_exec_msgset.
*
* Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING
* flag becomes set (e.g. a flag update to a modified header),
* this function will be called by imap_cmd_finish().
*
* The mx_update_tables() will free and remove these "inactive" headers,
* despite that an EXPUNGE was not received for them.
* This would result in memory leaks and segfaults due to dangling
* pointers in the msn_index and uid_hash.
*
* So this is another hack to work around the hacks. We don't want to
* remove the messages, so make sure active is on.
*/
h->active = 1;
}
}
#if USE_HCACHE
imap_hcache_close (idata);
#endif
/* We may be called on to expunge at any time. We can't rely on the caller
* to always know to rethread */
mx_update_tables (idata->ctx, 0);
Sort = old_sort;
mutt_sort_headers (idata->ctx, 1);
}
/* imap_check_capabilities: make sure we can log in to this server. */
static int imap_check_capabilities (IMAP_DATA* idata)
{
if (imap_exec (idata, "CAPABILITY", 0) != 0)
{
imap_error ("imap_check_capabilities", idata->buf);
return -1;
}
if (!(mutt_bit_isset(idata->capabilities,IMAP4) ||
mutt_bit_isset(idata->capabilities,IMAP4REV1)))
{
mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
mutt_sleep (2); /* pause a moment to let the user see the error */
return -1;
}
return 0;
}
/**
* imap_conn_find
*
* Returns an authenticated IMAP connection matching account, or NULL
* if that isn't possible.
*
* flags:
* MUTT_IMAP_CONN_NONEW - must be an existing connection
* MUTT_IMAP_CONN_NOSELECT - must not be in the IMAP_SELECTED state.
*/
IMAP_DATA* imap_conn_find (const ACCOUNT* account, int flags)
{
CONNECTION* conn = NULL;
ACCOUNT* creds = NULL;
IMAP_DATA* idata = NULL;
int new = 0;
while ((conn = mutt_conn_find (conn, account)))
{
if (!creds)
creds = &conn->account;
else
memcpy (&conn->account, creds, sizeof (ACCOUNT));
idata = (IMAP_DATA*)conn->data;
if (flags & MUTT_IMAP_CONN_NONEW)
{
if (!idata)
{
/* This should only happen if we've come to the end of the list */
mutt_socket_free (conn);
return NULL;
}
else if (idata->state < IMAP_AUTHENTICATED)
continue;
}
if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED)
continue;
if (idata && idata->status == IMAP_FATAL)
continue;
break;
}
if (!conn)
return NULL; /* this happens when the initial connection fails */
/* The current connection is a new connection */
if (!idata)
{
idata = imap_new_idata ();
conn->data = idata;
idata->conn = conn;
new = 1;
}
if (idata->state == IMAP_DISCONNECTED)
imap_open_connection (idata);
if (idata->state == IMAP_CONNECTED)
{
if (!imap_authenticate (idata))
{
idata->state = IMAP_AUTHENTICATED;
FREE (&idata->capstr);
new = 1;
if (idata->conn->ssf)
dprint (2, (debugfile, "Communication encrypted at %d bits\n",
idata->conn->ssf));
}
else
mutt_account_unsetpass (&idata->conn->account);
}
if (new && idata->state == IMAP_AUTHENTICATED)
{
/* capabilities may have changed */
imap_exec (idata, "CAPABILITY", IMAP_CMD_FAIL_OK);
#if defined(USE_ZLIB)
/* RFC 4978 */
if (mutt_bit_isset (idata->capabilities, COMPRESS_DEFLATE))
{
if (option (OPTIMAPDEFLATE) &&
imap_exec (idata, "COMPRESS DEFLATE", IMAP_CMD_FAIL_OK) == 0)
mutt_zstrm_wrap_conn (idata->conn);
}
#endif
/* enable RFC6855, if the server supports that */
if (mutt_bit_isset (idata->capabilities, ENABLE))
imap_exec (idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE);
/* enable QRESYNC. Advertising QRESYNC also means CONDSTORE
* is supported (even if not advertised), so flip that bit. */
if (mutt_bit_isset (idata->capabilities, QRESYNC))
{
mutt_bit_set (idata->capabilities, CONDSTORE);
if (option (OPTIMAPQRESYNC))
imap_exec (idata, "ENABLE QRESYNC", IMAP_CMD_QUEUE);
}
/* get root delimiter, '/' as default */
idata->delim = '/';
imap_exec (idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE);
if (option (OPTIMAPCHECKSUBSCRIBED))
imap_exec (idata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE);
/* we may need the root delimiter before we open a mailbox */
imap_exec (idata, NULL, IMAP_CMD_FAIL_OK);
}
if (idata->state < IMAP_AUTHENTICATED)
return NULL;
return idata;
}
int imap_open_connection (IMAP_DATA* idata)
{
if (mutt_socket_open (idata->conn) < 0)
return -1;
idata->state = IMAP_CONNECTED;
if (imap_cmd_step (idata) != IMAP_CMD_OK)
{
imap_close_connection (idata);
return -1;
}
if (ascii_strncasecmp ("* OK", idata->buf, 4) == 0)
{
if (ascii_strncasecmp ("* OK [CAPABILITY", idata->buf, 16)
&& imap_check_capabilities (idata))
goto bail;
#if defined(USE_SSL)
/* Attempt STARTTLS if available and desired. */
if (!idata->conn->ssf && (option(OPTSSLFORCETLS) ||
mutt_bit_isset (idata->capabilities, STARTTLS)))
{
int rc;
if (option(OPTSSLFORCETLS))
rc = MUTT_YES;
else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
_("Secure connection with TLS?"))) == -1)
goto err_close_conn;
if (rc == MUTT_YES)
{
if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
goto bail;
if (rc != -2)
{
if (mutt_ssl_starttls (idata->conn))
{
mutt_error (_("Could not negotiate TLS connection"));
mutt_sleep (1);
goto err_close_conn;
}
else
{
/* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
if (imap_exec (idata, "CAPABILITY", 0))
goto bail;
}
}
}
}
if (option(OPTSSLFORCETLS) && ! idata->conn->ssf)
{
mutt_error _("Encrypted connection unavailable");
mutt_sleep (1);
goto err_close_conn;
}
#endif
}
else if (ascii_strncasecmp ("* PREAUTH", idata->buf, 9) == 0)
{
#if defined(USE_SSL)
/* An unencrypted PREAUTH response is most likely a MITM attack.
* Require a confirmation. */
if (!idata->conn->ssf)
{
if (option(OPTSSLFORCETLS) ||
(query_quadoption (OPT_SSLSTARTTLS,
_("Abort unencrypted PREAUTH connection?")) != MUTT_NO))
{
mutt_error _("Encrypted connection unavailable");
mutt_sleep (1);
goto err_close_conn;
}
}
#endif
idata->state = IMAP_AUTHENTICATED;
if (imap_check_capabilities (idata) != 0)
goto bail;
FREE (&idata->capstr);
}
else
{
imap_error ("imap_open_connection()", idata->buf);
goto bail;
}
return 0;
#if defined(USE_SSL)
err_close_conn:
imap_close_connection (idata);
#endif
bail:
FREE (&idata->capstr);
return -1;
}
void imap_close_connection(IMAP_DATA* idata)
{
if (idata->state != IMAP_DISCONNECTED)
{
mutt_socket_close (idata->conn);
idata->state = IMAP_DISCONNECTED;
}
idata->seqno = idata->nextcmd = idata->lastcmd = idata->status = 0;
memset (idata->cmds, 0, sizeof (IMAP_COMMAND) * idata->cmdslots);
}
/* imap_get_flags: Make a simple list out of a FLAGS response.
* return stream following FLAGS response */
static char* imap_get_flags (LIST** hflags, char* s)
{
LIST* flags;
char* flag_word;
char ctmp;
/* sanity-check string */
if (ascii_strncasecmp ("FLAGS", s, 5) != 0)
{
dprint (1, (debugfile, "imap_get_flags: not a FLAGS response: %s\n",
s));
return NULL;
}
s += 5;
SKIPWS(s);
if (*s != '(')
{
dprint (1, (debugfile, "imap_get_flags: bogus FLAGS response: %s\n",
s));
return NULL;
}
/* create list, update caller's flags handle */
flags = mutt_new_list();
*hflags = flags;
while (*s && *s != ')')
{
s++;
SKIPWS(s);
flag_word = s;
while (*s && (*s != ')') && !ISSPACE (*s))
s++;
ctmp = *s;
*s = '\0';
if (*flag_word)
mutt_add_list (flags, flag_word);
*s = ctmp;
}
/* note bad flags response */
if (*s != ')')
{
dprint (1, (debugfile,
"imap_get_flags: Unterminated FLAGS response: %s\n", s));
mutt_free_list (hflags);
return NULL;
}
s++;
return s;
}
static int imap_open_mailbox (CONTEXT* ctx)
{
IMAP_DATA *idata;
IMAP_STATUS* status;
char buf[LONG_STRING];
char bufout[LONG_STRING*2];
int count = 0;
IMAP_MBOX mx, pmx;
int rc;
const char *condstore;
if (imap_parse_path (ctx->path, &mx))
{
mutt_error (_("%s is an invalid IMAP path"), ctx->path);
return -1;
}
/* we require a connection which isn't currently in IMAP_SELECTED state */
if (!(idata = imap_conn_find (&(mx.account), MUTT_IMAP_CONN_NOSELECT)))
goto fail_noidata;
/* once again the context is new */
ctx->data = idata;
/* Clean up path and replace the one in the ctx */
imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
if (!*buf)
strfcpy (buf, "INBOX", sizeof (buf));
FREE(&(idata->mailbox));
idata->mailbox = safe_strdup (buf);
imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
FREE (&(ctx->path));
FREE (&(ctx->realpath));
ctx->path = safe_strdup (buf);
ctx->realpath = safe_strdup (ctx->path);
idata->ctx = ctx;
/* clear mailbox status */
idata->status = 0;
memset (idata->ctx->rights, 0, sizeof (idata->ctx->rights));
idata->newMailCount = 0;
idata->max_msn = 0;
if (!ctx->quiet)
mutt_message (_("Selecting %s..."), idata->mailbox);
imap_munge_mbox_name (idata, buf, sizeof(buf), idata->mailbox);
/* pipeline ACL test */
if (mutt_bit_isset (idata->capabilities, ACL))
{
snprintf (bufout, sizeof (bufout), "MYRIGHTS %s", buf);
imap_exec (idata, bufout, IMAP_CMD_QUEUE);
}
/* assume we have all rights if ACL is unavailable */
else
{
mutt_bit_set (idata->ctx->rights, MUTT_ACL_LOOKUP);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_READ);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_SEEN);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_WRITE);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_INSERT);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_POST);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_CREATE);
mutt_bit_set (idata->ctx->rights, MUTT_ACL_DELETE);
}
/* pipeline the postponed count if possible */
pmx.mbox = NULL;
if (mx_is_imap (Postponed) && !imap_parse_path (Postponed, &pmx)
&& mutt_account_match (&pmx.account, &mx.account))
imap_status (Postponed, 1);
FREE (&pmx.mbox);
#if USE_HCACHE
if (mutt_bit_isset (idata->capabilities, CONDSTORE) &&
option (OPTIMAPCONDSTORE))
condstore = " (CONDSTORE)";
else
#endif
condstore = "";
snprintf (bufout, sizeof (bufout), "%s %s%s",
ctx->readonly ? "EXAMINE" : "SELECT",
buf, condstore);
idata->state = IMAP_SELECTED;
imap_cmd_start (idata, bufout);
status = imap_mboxcache_get (idata, idata->mailbox, 1);
do
{
char *pc;
if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
break;
pc = idata->buf + 2;
/* Obtain list of available flags here, may be overridden by a
* PERMANENTFLAGS tag in the OK response */
if (ascii_strncasecmp ("FLAGS", pc, 5) == 0)
{
/* don't override PERMANENTFLAGS */
if (!idata->flags)
{
dprint (3, (debugfile, "Getting mailbox FLAGS\n"));
if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
goto fail;
}
}
/* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0)
{
dprint (3, (debugfile, "Getting mailbox PERMANENTFLAGS\n"));
/* safe to call on NULL */
mutt_free_list (&(idata->flags));
/* skip "OK [PERMANENT" so syntax is the same as FLAGS */
pc += 13;
if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
goto fail;
}
/* save UIDVALIDITY for the header cache */
else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0)
{
dprint (3, (debugfile, "Getting mailbox UIDVALIDITY\n"));
pc += 3;
pc = imap_next_word (pc);
if (mutt_atoui (pc, &idata->uid_validity) < 0)
goto fail;
status->uidvalidity = idata->uid_validity;
}
else if (ascii_strncasecmp ("OK [UIDNEXT", pc, 11) == 0)
{
dprint (3, (debugfile, "Getting mailbox UIDNEXT\n"));
pc += 3;
pc = imap_next_word (pc);
if (mutt_atoui (pc, &idata->uidnext) < 0)
goto fail;
status->uidnext = idata->uidnext;
}
else if (ascii_strncasecmp ("OK [HIGHESTMODSEQ", pc, 17) == 0)
{
dprint (3, (debugfile, "Getting mailbox HIGHESTMODSEQ\n"));
pc += 3;
pc = imap_next_word (pc);
if (mutt_atoull (pc, &idata->modseq) < 0)
goto fail;
status->modseq = idata->modseq;
}
else if (ascii_strncasecmp ("OK [NOMODSEQ", pc, 12) == 0)
{
dprint (3, (debugfile, "Mailbox has NOMODSEQ set\n"));
status->modseq = idata->modseq = 0;
}
else
{
pc = imap_next_word (pc);
if (!ascii_strncasecmp ("EXISTS", pc, 6))
{
count = idata->newMailCount;
idata->newMailCount = 0;
}
}
}
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_NO)
{
char *s;
s = imap_next_word (idata->buf); /* skip seq */
s = imap_next_word (s); /* Skip response */
mutt_error ("%s", s);
mutt_sleep (2);
goto fail;
}
if (rc != IMAP_CMD_OK)
goto fail;
/* check for READ-ONLY notification */
if (!ascii_strncasecmp (imap_get_qualifier (idata->buf), "[READ-ONLY]", 11) &&
!mutt_bit_isset (idata->capabilities, ACL))
{
dprint (2, (debugfile, "Mailbox is read-only.\n"));
ctx->readonly = 1;
}
#ifdef DEBUG
/* dump the mailbox flags we've found */
if (debuglevel > 2)
{
if (!idata->flags)
dprint (3, (debugfile, "No folder flags found\n"));
else
{
LIST* t = idata->flags;
dprint (3, (debugfile, "Mailbox flags: "));
t = t->next;
while (t)
{
dprint (3, (debugfile, "[%s] ", t->data));
t = t->next;
}
dprint (3, (debugfile, "\n"));
}
}
#endif
if (!(mutt_bit_isset(idata->ctx->rights, MUTT_ACL_DELETE) ||
mutt_bit_isset(idata->ctx->rights, MUTT_ACL_SEEN) ||
mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) ||
mutt_bit_isset(idata->ctx->rights, MUTT_ACL_INSERT)))
ctx->readonly = 1;
ctx->hdrmax = count;
ctx->hdrs = safe_calloc (count, sizeof (HEADER *));
ctx->v2r = safe_calloc (count, sizeof (int));
ctx->msgcount = 0;
if (count && (imap_read_headers (idata, 1, count, 1) < 0))
{
mutt_error _("Error opening mailbox");
mutt_sleep (1);
goto fail;
}
imap_disallow_reopen (ctx);
dprint (2, (debugfile, "imap_open_mailbox: msgcount is %d\n", ctx->msgcount));
FREE (&mx.mbox);
return 0;
fail:
if (idata->state == IMAP_SELECTED)
idata->state = IMAP_AUTHENTICATED;
fail_noidata:
FREE (&mx.mbox);
return -1;
}
static int imap_open_mailbox_append (CONTEXT *ctx, int flags)
{
IMAP_DATA *idata;
char buf[LONG_STRING];
char mailbox[LONG_STRING];
IMAP_MBOX mx;
int rc;
if (imap_parse_path (ctx->path, &mx))
return -1;
/* in APPEND mode, we appear to hijack an existing IMAP connection -
* ctx is brand new and mostly empty */
if (!(idata = imap_conn_find (&(mx.account), 0)))
{
FREE (&mx.mbox);
return -1;
}
ctx->data = idata;
imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
if (!*mailbox)
strfcpy (mailbox, "INBOX", sizeof (mailbox));
FREE (&mx.mbox);
if ((rc = imap_access (ctx->path)) == 0)
return 0;
if (rc == -1)
return -1;
snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
return -1;
if (imap_create_mailbox (idata, mailbox) < 0)
return -1;
return 0;
}
/* imap_logout: Gracefully log out of server. */
void imap_logout (IMAP_DATA** idata)
{
/* we set status here to let imap_handle_untagged know we _expect_ to
* receive a bye response (so it doesn't freak out and close the conn) */
(*idata)->status = IMAP_BYE;
imap_cmd_start (*idata, "LOGOUT");
if (ImapPollTimeout <= 0 ||
mutt_socket_poll ((*idata)->conn, ImapPollTimeout) != 0)
{
while (imap_cmd_step (*idata) == IMAP_CMD_CONTINUE)
;
}
mutt_socket_close ((*idata)->conn);
imap_free_idata (idata);
}
static int imap_open_new_message (MESSAGE *msg, CONTEXT *dest, HEADER *hdr)
{
BUFFER *tmp = NULL;
int rc = -1;
tmp = mutt_buffer_pool_get ();
mutt_buffer_mktemp (tmp);
if ((msg->fp = safe_fopen (mutt_b2s (tmp), "w")) == NULL)
{
mutt_perror (mutt_b2s (tmp));
goto cleanup;
}
msg->path = safe_strdup (mutt_b2s (tmp));
rc = 0;
cleanup:
mutt_buffer_pool_release (&tmp);
return rc;
}
/* imap_set_flag: append str to flags if we currently have permission
* according to aclbit */
static void imap_set_flag (IMAP_DATA* idata, int aclbit, int flag,
const char *str, char *flags, size_t flsize)
{
if (mutt_bit_isset (idata->ctx->rights, aclbit))
if (flag && imap_has_flag (idata->flags, str))
safe_strcat (flags, flsize, str);
}
/* imap_has_flag: do a caseless comparison of the flag against a flag list,
* return 1 if found or flag list has '\*', 0 otherwise */
int imap_has_flag (LIST* flag_list, const char* flag)
{
if (!flag_list)
return 0;
flag_list = flag_list->next;
while (flag_list)
{
if (!ascii_strncasecmp (flag_list->data, flag, strlen (flag_list->data)))
return 1;
if (!ascii_strncmp (flag_list->data, "\\*", strlen (flag_list->data)))
return 1;
flag_list = flag_list->next;
}
return 0;
}
/* Note: headers must be in SORT_ORDER. See imap_exec_msgset for args.
* Pos is an opaque pointer a la strtok. It should be 0 at first call. */
static int imap_make_msg_set (IMAP_DATA* idata, BUFFER* buf, int flag,
int changed, int invert, int* pos)
{
HEADER** hdrs = idata->ctx->hdrs;
int count = 0; /* number of messages in message set */
int match = 0; /* whether current message matches flag condition */
unsigned int setstart = 0; /* start of current message range */
int n;
int started = 0;
hdrs = idata->ctx->hdrs;
for (n = *pos;
(n < idata->ctx->msgcount) && (mutt_buffer_len (buf) < IMAP_MAX_CMDLEN);
n++)
{
match = 0;
/* don't include pending expunged messages.
*
* TODO: can we unset active in cmd_parse_expunge() and
* cmd_parse_vanished() instead of checking for index != INT_MAX. */
if (hdrs[n]->active && (hdrs[n]->index != INT_MAX))
switch (flag)
{
case MUTT_DELETED:
if (hdrs[n]->deleted != HEADER_DATA(hdrs[n])->deleted)
match = invert ^ hdrs[n]->deleted;
break;
case MUTT_FLAG:
if (hdrs[n]->flagged != HEADER_DATA(hdrs[n])->flagged)
match = invert ^ hdrs[n]->flagged;
break;
case MUTT_OLD:
if (hdrs[n]->old != HEADER_DATA(hdrs[n])->old)
match = invert ^ hdrs[n]->old;
break;
case MUTT_READ:
if (hdrs[n]->read != HEADER_DATA(hdrs[n])->read)
match = invert ^ hdrs[n]->read;
break;
case MUTT_REPLIED:
if (hdrs[n]->replied != HEADER_DATA(hdrs[n])->replied)
match = invert ^ hdrs[n]->replied;
break;
case MUTT_TAG:
if (hdrs[n]->tagged)
match = 1;
break;
case MUTT_TRASH:
if (hdrs[n]->deleted && !hdrs[n]->purge)
match = 1;
break;
}
if (match && (!changed || hdrs[n]->changed))
{
count++;
if (setstart == 0)
{
setstart = HEADER_DATA (hdrs[n])->uid;
if (started == 0)
{
mutt_buffer_add_printf (buf, "%u", HEADER_DATA (hdrs[n])->uid);
started = 1;
}
else
mutt_buffer_add_printf (buf, ",%u", HEADER_DATA (hdrs[n])->uid);
}
/* tie up if the last message also matches */
else if (n == idata->ctx->msgcount-1)
mutt_buffer_add_printf (buf, ":%u", HEADER_DATA (hdrs[n])->uid);
}
/* End current set if message doesn't match or we've reached the end
* of the mailbox via inactive messages following the last match. */
else if (setstart && (hdrs[n]->active || n == idata->ctx->msgcount-1))
{
if (HEADER_DATA (hdrs[n-1])->uid > setstart)
mutt_buffer_add_printf (buf, ":%u", HEADER_DATA (hdrs[n-1])->uid);
setstart = 0;
}
}
*pos = n;
return count;
}
/* Prepares commands for all messages matching conditions (must be flushed
* with imap_exec)
* Params:
* idata: IMAP_DATA containing context containing header set
* pre, post: commands are of the form "%s %s %s %s", tag,
* pre, message set, post
* flag: enum of flag type on which to filter
* changed: include only changed messages in message set
* invert: invert sense of flag, eg MUTT_READ matches unread messages
* Returns: number of matched messages, or -1 on failure */
int imap_exec_msgset (IMAP_DATA* idata, const char* pre, const char* post,
int flag, int changed, int invert)
{
HEADER** hdrs = NULL;
short oldsort;
BUFFER* cmd;
int pos;
int rc;
int count = 0, reopen_set = 0;
cmd = mutt_buffer_new ();
/* Unlike imap_sync_mailbox(), this function can be called when
* IMAP_REOPEN_ALLOW is not set. In that case, the caller isn't
* prepared to handle context changes. Resorting may not always
* give the same order, so we must make a copy.
*
* See the comment in imap_sync_mailbox() for the dangers of running
* even queued execs while reopen is set. To prevent memory
* corruption and data loss we must disable reopen for the duration
* of the swapped hdrs.
*/
if (idata->reopen & IMAP_REOPEN_ALLOW)
{
idata->reopen &= ~IMAP_REOPEN_ALLOW;
reopen_set = 1;
}
oldsort = Sort;
if (Sort != SORT_ORDER)
{
hdrs = idata->ctx->hdrs;
idata->ctx->hdrs = safe_malloc (idata->ctx->msgcount * sizeof (HEADER*));
memcpy (idata->ctx->hdrs, hdrs, idata->ctx->msgcount * sizeof (HEADER*));
Sort = SORT_ORDER;
qsort (idata->ctx->hdrs, idata->ctx->msgcount, sizeof (HEADER*),
mutt_get_sort_func (SORT_ORDER));
}
pos = 0;
do
{
mutt_buffer_clear (cmd);
mutt_buffer_add_printf (cmd, "%s ", pre);
rc = imap_make_msg_set (idata, cmd, flag, changed, invert, &pos);
if (rc > 0)
{
mutt_buffer_add_printf (cmd, " %s", post);
if (imap_exec (idata, cmd->data, IMAP_CMD_QUEUE))
{
rc = -1;
goto out;
}
count += rc;
}
}
while (rc > 0);
rc = count;
out:
mutt_buffer_free (&cmd);
if ((oldsort != Sort) || hdrs)
{
Sort = oldsort;
FREE (&idata->ctx->hdrs);
idata->ctx->hdrs = hdrs;
}
if (reopen_set)
idata->reopen |= IMAP_REOPEN_ALLOW;
return rc;
}
/* returns 0 if mutt's flags match cached server flags:
* EXCLUDING the deleted flag. */
static int compare_flags_for_copy (HEADER* h)
{
IMAP_HEADER_DATA* hd = (IMAP_HEADER_DATA*)h->data;
if (h->read != hd->read)
return 1;
if (h->old != hd->old)
return 1;
if (h->flagged != hd->flagged)
return 1;
if (h->replied != hd->replied)
return 1;
return 0;
}
/* Update the IMAP server to reflect the flags for a single message before
* performing a "UID COPY".
* NOTE: This does not sync the "deleted" flag state, because it is not
* desirable to propagate that flag into the copy.
*/
int imap_sync_message_for_copy (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
int *err_continue)
{
char flags[LONG_STRING];
char uid[11];
if (!compare_flags_for_copy (hdr))
{
if (hdr->deleted == HEADER_DATA(hdr)->deleted)
hdr->changed = 0;
return 0;
}
snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
mutt_buffer_clear (cmd);
mutt_buffer_addstr (cmd, "UID STORE ");
mutt_buffer_addstr (cmd, uid);
flags[0] = '\0';
imap_set_flag (idata, MUTT_ACL_SEEN, hdr->read, "\\Seen ",
flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, hdr->old,
"Old ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, hdr->flagged,
"\\Flagged ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, hdr->replied,
"\\Answered ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_DELETE, HEADER_DATA(hdr)->deleted,
"\\Deleted ", flags, sizeof (flags));
/* now make sure we don't lose custom tags */
if (mutt_bit_isset (idata->ctx->rights, MUTT_ACL_WRITE))
imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
mutt_remove_trailing_ws (flags);
/* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
* explicitly revoke all system flags (if we have permission) */
if (!*flags)
{
imap_set_flag (idata, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
imap_set_flag (idata, MUTT_ACL_DELETE, !HEADER_DATA(hdr)->deleted,
"\\Deleted ", flags, sizeof (flags));
mutt_remove_trailing_ws (flags);
mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
}
else
mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
mutt_buffer_addstr (cmd, flags);
mutt_buffer_addstr (cmd, ")");
/* after all this it's still possible to have no flags, if you
* have no ACL rights */
if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
err_continue && (*err_continue != MUTT_YES))
{
*err_continue = imap_continue ("imap_sync_message: STORE failed",
idata->buf);
if (*err_continue != MUTT_YES)
return -1;
}
if (hdr->deleted == HEADER_DATA(hdr)->deleted)
hdr->changed = 0;
return 0;
}
static int sync_helper (IMAP_DATA* idata, int right, int flag, const char* name)
{
int count = 0;
int rc;
char buf[LONG_STRING];
if (!idata->ctx)
return -1;
if (!mutt_bit_isset (idata->ctx->rights, right))
return 0;
if (right == MUTT_ACL_WRITE && !imap_has_flag (idata->flags, name))
return 0;
snprintf (buf, sizeof(buf), "+FLAGS.SILENT (%s)", name);
if ((rc = imap_exec_msgset (idata, "UID STORE", buf, flag, 1, 0)) < 0)
return rc;
count += rc;
buf[0] = '-';
if ((rc = imap_exec_msgset (idata, "UID STORE", buf, flag, 1, 1)) < 0)
return rc;
count += rc;
return count;
}
/* update the IMAP server to reflect message changes done within mutt.
* Arguments
* ctx: the current context
* expunge: 0 or 1 - do expunge?
*/
int imap_sync_mailbox (CONTEXT* ctx, int expunge, int* index_hint)
{
IMAP_DATA* idata;
CONTEXT* appendctx = NULL;
HEADER* h;
HEADER** hdrs = NULL;
int oldsort;
int n;
int rc, quickdel_rc = 0;
idata = (IMAP_DATA*) ctx->data;
if (idata->state < IMAP_SELECTED)
{
dprint (2, (debugfile, "imap_sync_mailbox: no mailbox selected\n"));
return -1;
}
/* This function is only called when the calling code expects the context
* to be changed. */
imap_allow_reopen (ctx);
if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
goto out;
/* if we are expunging anyway, we can do deleted messages very quickly... */
if (expunge && mutt_bit_isset (ctx->rights, MUTT_ACL_DELETE))
{
if ((quickdel_rc = imap_exec_msgset (idata,
"UID STORE", "+FLAGS.SILENT (\\Deleted)",
MUTT_DELETED, 1, 0)) < 0)
{
rc = quickdel_rc;
mutt_error (_("Expunge failed"));
mutt_sleep (1);
goto out;
}
if (quickdel_rc > 0)
{
/* mark these messages as unchanged so second pass ignores them. Done
* here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
for (n = 0; n < ctx->msgcount; n++)
if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
ctx->hdrs[n]->active = 0;
if (!ctx->quiet)
mutt_message (_("Marking %d messages deleted..."), quickdel_rc);
}
}
#if USE_HCACHE
idata->hcache = imap_hcache_open (idata, NULL);
#endif
/* save messages with real (non-flag) changes */
for (n = 0; n < ctx->msgcount; n++)
{
h = ctx->hdrs[n];
if (h->deleted)
{
imap_cache_del (idata, h);
#if USE_HCACHE
imap_hcache_del (idata, HEADER_DATA(h)->uid);
#endif
}
if (h->active && h->changed)
{
#if USE_HCACHE
imap_hcache_put (idata, h);
#endif
/* if the message has been rethreaded or attachments have been deleted
* we delete the message and reupload it.
* This works better if we're expunging, of course. */
/* TODO: why the h->env check? */
if ((h->env && h->env->changed) || h->attach_del)
{
/* NOTE and TODO:
*
* The mx_open_mailbox() in append mode below merely hijacks an existing
* idata; it doesn't reset idata->ctx. imap_append_message() ends up
* using (borrowing) the same idata we are using.
*
* Right after the APPEND operation finishes, the server can send an
* EXISTS notifying of the new message. Then, while still inside
* imap_append_message(), imap_cmd_step() -> imap_cmd_finish() will
* call imap_read_headers() to download those (because the idata's
* reopen_allow is set).
*
* The imap_read_headers() will open (and clobber) the idata->hcache we
* just opened above, then close it.
*
* The easy and less dangerous fix done here (for a stable branch bug
* fix) is to close and reopen the header cache around the operation.
*
* A better fix would be allowing idata->hcache reuse. When that is
* done, the close/reopen in read_headers_condstore_qresync_updates()
* can also be removed. */
#if USE_HCACHE
imap_hcache_close (idata);
#endif
if (!ctx->quiet)
mutt_message (_("Saving changed messages... [%d/%d]"), n+1,
ctx->msgcount);
if (!appendctx)
appendctx = mx_open_mailbox (ctx->path, MUTT_APPEND | MUTT_QUIET, NULL);
if (!appendctx)
dprint (1, (debugfile, "imap_sync_mailbox: Error opening mailbox in append mode\n"));
else
_mutt_save_message (h, appendctx, 1, 0, 0);
/* TODO: why the check for h->env? Is this possible? */
if (h->env)
h->env->changed = 0;
#if USE_HCACHE
idata->hcache = imap_hcache_open (idata, NULL);
#endif
}
}
}
#if USE_HCACHE
imap_hcache_close (idata);
#endif
/* presort here to avoid doing 10 resorts in imap_exec_msgset.
*
* Note: sync_helper() may trigger an imap_exec() if the queue fills
* up. Because IMAP_REOPEN_ALLOW is set, this may result in new
* messages being downloaded or an expunge being processed. For new
* messages this would both result in memory corruption (since we're
* alloc'ing msgcount instead of hdrmax pointers) and data loss of
* the new messages. For an expunge, the restored hdrs would point
* to headers that have been freed.
*
* Since reopen is allowed, we could change this to call
* mutt_sort_headers() before and after instead, but the double sort
* is noticeably slower.
*
* So instead, just turn off reopen_allow for the duration of the
* swapped hdrs. The imap_exec() below flushes the queue out,
* giving the opportunity to process any reopen events.
*/
imap_disallow_reopen (ctx);
oldsort = Sort;
if (Sort != SORT_ORDER)
{
hdrs = ctx->hdrs;
ctx->hdrs = safe_malloc (ctx->msgcount * sizeof (HEADER*));
memcpy (ctx->hdrs, hdrs, ctx->msgcount * sizeof (HEADER*));
Sort = SORT_ORDER;
qsort (ctx->hdrs, ctx->msgcount, sizeof (HEADER*),
mutt_get_sort_func (SORT_ORDER));
}
rc = sync_helper (idata, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted");
if (rc >= 0)
rc |= sync_helper (idata, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged");
if (rc >= 0)
rc |= sync_helper (idata, MUTT_ACL_WRITE, MUTT_OLD, "Old");
if (rc >= 0)
rc |= sync_helper (idata, MUTT_ACL_SEEN, MUTT_READ, "\\Seen");
if (rc >= 0)
rc |= sync_helper (idata, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered");
if ((oldsort != Sort) || hdrs)
{
Sort = oldsort;
FREE (&ctx->hdrs);
ctx->hdrs = hdrs;
}
imap_allow_reopen (ctx);
/* Flush the queued flags if any were changed in sync_helper.
* The real (non-flag) changes loop might have flushed quickdel_rc
* queued commands, so we double check the cmdbuf isn't empty. */
if (((rc > 0) || (quickdel_rc > 0)) && mutt_buffer_len (idata->cmdbuf))
if (imap_exec (idata, NULL, 0) != IMAP_CMD_OK)
rc = -1;
if (rc < 0)
{
if (ctx->closing)
{
if (mutt_yesorno (_("Error saving flags. Close anyway?"), 0) == MUTT_YES)
{
rc = 0;
idata->state = IMAP_AUTHENTICATED;
goto out;
}
}
else
mutt_error _("Error saving flags");
rc = -1;
goto out;
}
/* Update local record of server state to reflect the synchronization just
* completed. imap_read_headers always overwrites hcache-origin flags, so
* there is no need to mutate the hcache after flag-only changes. */
for (n = 0; n < ctx->msgcount; n++)
{
HEADER_DATA(ctx->hdrs[n])->deleted = ctx->hdrs[n]->deleted;
HEADER_DATA(ctx->hdrs[n])->flagged = ctx->hdrs[n]->flagged;
HEADER_DATA(ctx->hdrs[n])->old = ctx->hdrs[n]->old;
HEADER_DATA(ctx->hdrs[n])->read = ctx->hdrs[n]->read;
HEADER_DATA(ctx->hdrs[n])->replied = ctx->hdrs[n]->replied;
ctx->hdrs[n]->changed = 0;
}
ctx->changed = 0;
/* We must send an EXPUNGE command if we're not closing. */
if (expunge && !(ctx->closing) &&
mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE))
{
if (!ctx->quiet)
mutt_message _("Expunging messages from server...");
/* Set expunge bit so we don't get spurious reopened messages */
idata->reopen |= IMAP_EXPUNGE_EXPECTED;
if (imap_exec (idata, "EXPUNGE", 0) != 0)
{
idata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->buf);
rc = -1;
goto out;
}
idata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
}
if (expunge && ctx->closing)
{
imap_exec (idata, "CLOSE", IMAP_CMD_QUEUE);
idata->state = IMAP_AUTHENTICATED;
}
if (option (OPTMESSAGECACHECLEAN))
imap_cache_clean (idata);
rc = 0;
out:
imap_disallow_reopen (ctx);
if (appendctx)
{
mx_fastclose_mailbox (appendctx);
FREE (&appendctx);
}
return rc;
}
/* imap_close_mailbox: clean up IMAP data in CONTEXT */
int imap_close_mailbox (CONTEXT* ctx)
{
IMAP_DATA* idata;
int i;
idata = (IMAP_DATA*) ctx->data;
/* Check to see if the mailbox is actually open */
if (!idata)
return 0;
/* imap_open_mailbox_append() borrows the IMAP_DATA temporarily,
* just for the connection, but does not set idata->ctx to the
* open-append ctx.
*
* So when these are equal, it means we are actually closing the
* mailbox and should clean up idata. Otherwise, we don't want to
* touch idata - it's still being used.
*/
if (ctx == idata->ctx)
{
if (idata->status != IMAP_FATAL && idata->state >= IMAP_SELECTED)
{
/* mx_close_mailbox won't sync if there are no deleted messages
* and the mailbox is unchanged, so we may have to close here */
if (!ctx->deleted)
imap_exec (idata, "CLOSE", IMAP_CMD_QUEUE);
idata->state = IMAP_AUTHENTICATED;
}
idata->reopen = 0;
FREE (&(idata->mailbox));
mutt_free_list (&idata->flags);
idata->ctx = NULL;
hash_destroy (&idata->uid_hash, NULL);
FREE (&idata->msn_index);
idata->msn_index_size = 0;
idata->max_msn = 0;
for (i = 0; i < IMAP_CACHE_LEN; i++)
{
if (idata->cache[i].path)
{
unlink (idata->cache[i].path);
FREE (&idata->cache[i].path);
}
}
mutt_bcache_close (&idata->bcache);
}
/* free IMAP part of headers */
for (i = 0; i < ctx->msgcount; i++)
/* mailbox may not have fully loaded */
if (ctx->hdrs[i] && ctx->hdrs[i]->data)
imap_free_header_data ((IMAP_HEADER_DATA**)&(ctx->hdrs[i]->data));
return 0;
}
/* use the NOOP or IDLE command to poll for new mail
*
* return values:
* MUTT_REOPENED mailbox has been externally modified
* MUTT_NEW_MAIL new mail has arrived!
* 0 no change
* -1 error
*/
int imap_check_mailbox (CONTEXT *ctx, int *index_hint, int force)
{
/* overload keyboard timeout to avoid many mailbox checks in a row.
* Most users don't like having to wait exactly when they press a key. */
IMAP_DATA* idata;
int result = 0;
idata = (IMAP_DATA*) ctx->data;
/* try IDLE first, unless force is set */
if (!force && option (OPTIMAPIDLE) && mutt_bit_isset (idata->capabilities, IDLE)
&& (idata->state != IMAP_IDLE || time(NULL) >= idata->lastread + ImapKeepalive))
{
if (imap_cmd_idle (idata) < 0)
return -1;
}
if (idata->state == IMAP_IDLE)
{
while ((result = mutt_socket_poll (idata->conn, 0)) > 0)
{
if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
{
dprint (1, (debugfile, "Error reading IDLE response\n"));
return -1;
}
}
if (result < 0)
{
dprint (1, (debugfile, "Poll failed, disabling IDLE\n"));
mutt_bit_unset (idata->capabilities, IDLE);
}
}
if ((force ||
(idata->state != IMAP_IDLE && time(NULL) >= idata->lastread + Timeout))
&& imap_exec (idata, "NOOP", IMAP_CMD_POLL) != 0)
return -1;
/* We call this even when we haven't run NOOP in case we have pending
* changes to process, since we can reopen here. */
imap_cmd_finish (idata);
if (idata->check_status & IMAP_EXPUNGE_PENDING)
result = MUTT_REOPENED;
else if (idata->check_status & IMAP_NEWMAIL_PENDING)
result = MUTT_NEW_MAIL;
else if (idata->check_status & IMAP_FLAGS_PENDING)
result = MUTT_FLAGS;
idata->check_status = 0;
return result;
}
static int imap_check_mailbox_reopen (CONTEXT *ctx, int *index_hint)
{
int rc;
imap_allow_reopen (ctx);
rc = imap_check_mailbox (ctx, index_hint, 0);
imap_disallow_reopen (ctx);
return rc;
}
static int imap_save_to_header_cache (CONTEXT *ctx, HEADER *h)
{
int rc = 0;
#ifdef USE_HCACHE
int close_hc = 1;
IMAP_DATA* idata;
idata = (IMAP_DATA *)ctx->data;
if (idata->hcache)
close_hc = 0;
else
idata->hcache = imap_hcache_open (idata, NULL);
rc = imap_hcache_put (idata, h);
if (close_hc)
imap_hcache_close (idata);
#endif
return rc;
}
/* split path into (idata,mailbox name) */
static int imap_get_mailbox (const char* path, IMAP_DATA** hidata, char* buf, size_t blen)
{
IMAP_MBOX mx;
if (imap_parse_path (path, &mx))
{
dprint (1, (debugfile, "imap_get_mailbox: Error parsing %s\n", path));
return -1;
}
if (!(*hidata = imap_conn_find (&(mx.account), option (OPTIMAPPASSIVE) ? MUTT_IMAP_CONN_NONEW : 0)))
{
FREE (&mx.mbox);
return -1;
}
imap_fix_path (*hidata, mx.mbox, buf, blen);
if (!*buf)
strfcpy (buf, "INBOX", blen);
FREE (&mx.mbox);
return 0;
}
/* check for new mail in any subscribed mailboxes. Given a list of mailboxes
* rather than called once for each so that it can batch the commands and
* save on round trips. Returns number of mailboxes with new mail. */
int imap_buffy_check (int force, int check_stats)
{
IMAP_DATA* idata;
IMAP_DATA* lastdata = NULL;
BUFFY* mailbox;
char name[LONG_STRING];
char command[LONG_STRING*2];
char munged[LONG_STRING];
int buffies = 0;
for (mailbox = Incoming; mailbox; mailbox = mailbox->next)
{
/* Init newly-added mailboxes */
if (! mailbox->magic)
{
if (mx_is_imap (mutt_b2s (mailbox->pathbuf)))
mailbox->magic = MUTT_IMAP;
}
if (mailbox->magic != MUTT_IMAP)
continue;
if (mailbox->nopoll)
continue;
if (imap_get_mailbox (mutt_b2s (mailbox->pathbuf), &idata, name, sizeof (name)) < 0)
{
mailbox->new = 0;
continue;
}
/* Don't issue STATUS on the selected mailbox, it will be NOOPed or
* IDLEd elsewhere.
* idata->mailbox may be NULL for connections other than the current
* mailbox's, and shouldn't expand to INBOX in that case. #3216. */
if (idata->mailbox && !imap_mxcmp (name, idata->mailbox))
{
mailbox->new = 0;
continue;
}
if (!mutt_bit_isset (idata->capabilities, IMAP4REV1) &&
!mutt_bit_isset (idata->capabilities, STATUS))
{
dprint (2, (debugfile, "Server doesn't support STATUS\n"));
continue;
}
if (lastdata && idata != lastdata)
{
/* Send commands to previous server. Sorting the buffy list
* may prevent some infelicitous interleavings */
if (imap_exec (lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1)
dprint (1, (debugfile, "Error polling mailboxes\n"));
lastdata = NULL;
}
if (!lastdata)
lastdata = idata;
imap_munge_mbox_name (idata, munged, sizeof (munged), name);
if (check_stats)
snprintf (command, sizeof (command),
"STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT MESSAGES)", munged);
else
snprintf (command, sizeof (command),
"STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT)", munged);
if (imap_exec (idata, command, IMAP_CMD_QUEUE | IMAP_CMD_POLL) < 0)
{
dprint (1, (debugfile, "Error queueing command\n"));
return 0;
}
}
if (lastdata && (imap_exec (lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1))
{
dprint (1, (debugfile, "Error polling mailboxes\n"));
return 0;
}
/* collect results */
for (mailbox = Incoming; mailbox; mailbox = mailbox->next)
{
if (mailbox->magic == MUTT_IMAP && mailbox->new)
buffies++;
}
return buffies;
}
/* imap_status: returns count of messages in mailbox, or -1 on error.
* if queue != 0, queue the command and expect it to have been run
* on the next call (for pipelining the postponed count) */
int imap_status (const char* path, int queue)
{
static int queued = 0;
IMAP_DATA *idata;
char buf[LONG_STRING*2];
char mbox[LONG_STRING];
IMAP_STATUS* status;
if (imap_get_mailbox (path, &idata, buf, sizeof (buf)) < 0)
return -1;
/* We are in the folder we're polling - just return the mailbox count.
*
* Note that imap_mxcmp() converts NULL to "INBOX", so we need to
* make sure the idata really is open to a folder. */
if (idata->ctx && !imap_mxcmp (buf, idata->mailbox))
return idata->ctx->msgcount;
else if (mutt_bit_isset(idata->capabilities,IMAP4REV1) ||
mutt_bit_isset(idata->capabilities,STATUS))
{
imap_munge_mbox_name (idata, mbox, sizeof(mbox), buf);
snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox, "MESSAGES");
imap_unmunge_mbox_name (idata, mbox);
}
else
/* Server does not support STATUS, and this is not the current mailbox.
* There is no lightweight way to check recent arrivals */
return -1;
if (queue)
{
imap_exec (idata, buf, IMAP_CMD_QUEUE);
queued = 1;
return 0;
}
else if (!queued)
imap_exec (idata, buf, 0);
queued = 0;
if ((status = imap_mboxcache_get (idata, mbox, 0)))
return status->messages;
return 0;
}
/* return cached mailbox stats or NULL if create is 0 */
IMAP_STATUS* imap_mboxcache_get (IMAP_DATA* idata, const char* mbox, int create)
{
LIST* cur;
IMAP_STATUS* status;
IMAP_STATUS scache;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
void *puidvalidity = NULL;
void *puidnext = NULL;
void *pmodseq = NULL;
#endif
for (cur = idata->mboxcache; cur; cur = cur->next)
{
status = (IMAP_STATUS*)cur->data;
if (!imap_mxcmp (mbox, status->name))
return status;
}
status = NULL;
/* lame */
if (create)
{
memset (&scache, 0, sizeof (scache));
scache.name = (char*)mbox;
idata->mboxcache = mutt_add_list_n (idata->mboxcache, &scache,
sizeof (scache));
status = imap_mboxcache_get (idata, mbox, 0);
status->name = safe_strdup (mbox);
}
#ifdef USE_HCACHE
hc = imap_hcache_open (idata, mbox);
if (hc)
{
puidvalidity = mutt_hcache_fetch_raw (hc, "/UIDVALIDITY", imap_hcache_keylen);
puidnext = mutt_hcache_fetch_raw (hc, "/UIDNEXT", imap_hcache_keylen);
pmodseq = mutt_hcache_fetch_raw (hc, "/MODSEQ", imap_hcache_keylen);
if (puidvalidity)
{
if (!status)
{
mutt_hcache_free ((void **)&puidvalidity);
mutt_hcache_free ((void **)&puidnext);
mutt_hcache_free ((void **)&pmodseq);
mutt_hcache_close (hc);
return imap_mboxcache_get (idata, mbox, 1);
}
memcpy (&status->uidvalidity, puidvalidity, sizeof(unsigned int));
if (puidnext)
memcpy (&status->uidnext, puidnext, sizeof(unsigned int));
else
status->uidnext = 0;
if (pmodseq)
memcpy (&status->modseq, pmodseq, sizeof(unsigned long long));
else
status->modseq = 0;
dprint (3, (debugfile, "mboxcache: hcache uidvalidity %u, uidnext %u, modseq %llu\n",
status->uidvalidity, status->uidnext, status->modseq));
}
mutt_hcache_free ((void **)&puidvalidity);
mutt_hcache_free ((void **)&puidnext);
mutt_hcache_free ((void **)&pmodseq);
mutt_hcache_close (hc);
}
#endif
return status;
}
void imap_mboxcache_free (IMAP_DATA* idata)
{
LIST* cur;
IMAP_STATUS* status;
for (cur = idata->mboxcache; cur; cur = cur->next)
{
status = (IMAP_STATUS*)cur->data;
FREE (&status->name);
}
mutt_free_list (&idata->mboxcache);
}
/* returns number of patterns in the search that should be done server-side
* (eg are full-text) */
static int do_search (const pattern_t* search, int allpats)
{
int rc = 0;
const pattern_t* pat;
for (pat = search; pat; pat = pat->next)
{
switch (pat->op)
{
case MUTT_BODY:
case MUTT_HEADER:
case MUTT_WHOLE_MSG:
if (pat->stringmatch)
rc++;
break;
default:
if (pat->child && do_search (pat->child, 1))
rc++;
}
if (!allpats)
break;
}
return rc;
}
/* convert mutt pattern_t to IMAP SEARCH command containing only elements
* that require full-text search (mutt already has what it needs for most
* match types, and does a better job (eg server doesn't support regexps). */
static int imap_compile_search (const pattern_t* pat, BUFFER* buf)
{
if (! do_search (pat, 0))
return 0;
if (pat->not)
mutt_buffer_addstr (buf, "NOT ");
if (pat->child)
{
int clauses;
if ((clauses = do_search (pat->child, 1)) > 0)
{
const pattern_t* clause = pat->child;
mutt_buffer_addch (buf, '(');
while (clauses)
{
if (do_search (clause, 0))
{
if (pat->op == MUTT_OR && clauses > 1)
mutt_buffer_addstr (buf, "OR ");
clauses--;
if (imap_compile_search (clause, buf) < 0)
return -1;
if (clauses)
mutt_buffer_addch (buf, ' ');
}
clause = clause->next;
}
mutt_buffer_addch (buf, ')');
}
}
else
{
char term[STRING];
char *delim;
switch (pat->op)
{
case MUTT_HEADER:
mutt_buffer_addstr (buf, "HEADER ");
/* extract header name */
if (! (delim = strchr (pat->p.str, ':')))
{
mutt_error (_("Header search without header name: %s"), pat->p.str);
return -1;
}
*delim = '\0';
imap_quote_string (term, sizeof (term), pat->p.str);
mutt_buffer_addstr (buf, term);
mutt_buffer_addch (buf, ' ');
/* and field */
*delim = ':';
delim++;
SKIPWS(delim);
imap_quote_string (term, sizeof (term), delim);
mutt_buffer_addstr (buf, term);
break;
case MUTT_BODY:
mutt_buffer_addstr (buf, "BODY ");
imap_quote_string (term, sizeof (term), pat->p.str);
mutt_buffer_addstr (buf, term);
break;
case MUTT_WHOLE_MSG:
mutt_buffer_addstr (buf, "TEXT ");
imap_quote_string (term, sizeof (term), pat->p.str);
mutt_buffer_addstr (buf, term);
break;
}
}
return 0;
}
int imap_search (CONTEXT* ctx, const pattern_t* pat)
{
BUFFER buf;
IMAP_DATA* idata = (IMAP_DATA*)ctx->data;
int i;
for (i = 0; i < ctx->msgcount; i++)
ctx->hdrs[i]->matched = 0;
if (!do_search (pat, 1))
return 0;
mutt_buffer_init (&buf);
mutt_buffer_addstr (&buf, "UID SEARCH ");
if (imap_compile_search (pat, &buf) < 0)
{
FREE (&buf.data);
return -1;
}
if (imap_exec (idata, buf.data, 0) < 0)
{
FREE (&buf.data);
return -1;
}
FREE (&buf.data);
return 0;
}
int imap_subscribe (char *path, int subscribe)
{
IMAP_DATA *idata;
char buf[LONG_STRING*2];
char mbox[LONG_STRING];
int mblen;
BUFFER err;
IMAP_MBOX mx;
if (!mx_is_imap (path) || imap_parse_path (path, &mx) || !mx.mbox)
{
mutt_error (_("Bad mailbox name"));
return -1;
}
if (!(idata = imap_conn_find (&(mx.account), 0)))
goto fail;
imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
if (!*buf)
strfcpy (buf, "INBOX", sizeof (buf));
if (option (OPTIMAPCHECKSUBSCRIBED))
{
mutt_buffer_init (&err);
err.dsize = STRING;
err.data = safe_malloc (err.dsize);
mblen = snprintf (mbox, sizeof (mbox), "%smailboxes ",
subscribe ? "" : "un");
imap_quote_string_and_backquotes (mbox + mblen, sizeof(mbox) - mblen,
path);
if (mutt_parse_rc_line (mbox, &err))
dprint (1, (debugfile, "Error adding subscribed mailbox: %s\n", err.data));
FREE (&err.data);
}
if (subscribe)
mutt_message (_("Subscribing to %s..."), buf);
else
mutt_message (_("Unsubscribing from %s..."), buf);
imap_munge_mbox_name (idata, mbox, sizeof(mbox), buf);
snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
if (imap_exec (idata, buf, 0) < 0)
goto fail;
imap_unmunge_mbox_name(idata, mx.mbox);
if (subscribe)
mutt_message (_("Subscribed to %s"), mx.mbox);
else
mutt_message (_("Unsubscribed from %s"), mx.mbox);
FREE (&mx.mbox);
return 0;
fail:
FREE (&mx.mbox);
return -1;
}
/* trim dest to the length of the longest prefix it shares with src,
* returning the length of the trimmed string */
static size_t
longest_common_prefix (char *dest, const char* src, size_t start, size_t dlen)
{
size_t pos = start;
while (pos < dlen && dest[pos] && dest[pos] == src[pos])
pos++;
dest[pos] = '\0';
return pos;
}
/* look for IMAP URLs to complete from defined mailboxes. Could be extended
* to complete over open connections and account/folder hooks too. */
static int
imap_complete_hosts (char *dest, size_t len)
{
BUFFY* mailbox;
CONNECTION* conn;
int rc = -1;
size_t matchlen;
matchlen = mutt_strlen (dest);
for (mailbox = Incoming; mailbox; mailbox = mailbox->next)
{
if (!mutt_strncmp (dest, mutt_b2s (mailbox->pathbuf), matchlen))
{
if (rc)
{
strfcpy (dest, mutt_b2s (mailbox->pathbuf), len);
rc = 0;
}
else
longest_common_prefix (dest, mutt_b2s (mailbox->pathbuf), matchlen, len);
}
}
for (conn = mutt_socket_head (); conn; conn = conn->next)
{
ciss_url_t url;
char urlstr[LONG_STRING];
if (conn->account.type != MUTT_ACCT_TYPE_IMAP)
continue;
mutt_account_tourl (&conn->account, &url);
/* FIXME: how to handle multiple users on the same host? */
url.user = NULL;
url.path = NULL;
url_ciss_tostring (&url, urlstr, sizeof (urlstr), 0);
if (!mutt_strncmp (dest, urlstr, matchlen))
{
if (rc)
{
strfcpy (dest, urlstr, len);
rc = 0;
}
else
longest_common_prefix (dest, urlstr, matchlen, len);
}
}
return rc;
}
/* imap_complete: given a partial IMAP folder path, return a string which
* adds as much to the path as is unique */
int imap_complete(char* dest, size_t dlen, const char* path)
{
IMAP_DATA* idata;
char list[LONG_STRING];
char buf[LONG_STRING*2];
IMAP_LIST listresp;
char completion[LONG_STRING];
int clen;
size_t matchlen = 0;
int completions = 0;
IMAP_MBOX mx;
int rc;
if (imap_parse_path (path, &mx))
{
strfcpy (dest, path, dlen);
return imap_complete_hosts (dest, dlen);
}
/* don't open a new socket just for completion. Instead complete over
* known mailboxes/hooks/etc */
if (!(idata = imap_conn_find (&(mx.account), MUTT_IMAP_CONN_NONEW)))
{
FREE (&mx.mbox);
strfcpy (dest, path, dlen);
return imap_complete_hosts (dest, dlen);
}
/* reformat path for IMAP list, and append wildcard */
/* don't use INBOX in place of "" */
if (mx.mbox && mx.mbox[0])
imap_fix_path (idata, mx.mbox, list, sizeof(list));
else
list[0] = '\0';
/* fire off command */
snprintf (buf, sizeof(buf), "%s \"\" \"%s%%\"",
option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
imap_cmd_start (idata, buf);
/* and see what the results are */
strfcpy (completion, NONULL(mx.mbox), sizeof(completion));
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &listresp;
do
{
listresp.name = NULL;
rc = imap_cmd_step (idata);
if (rc == IMAP_CMD_CONTINUE && listresp.name)
{
/* if the folder isn't selectable, append delimiter to force browse
* to enter it on second tab. */
if (listresp.noselect)
{
clen = strlen(listresp.name);
listresp.name[clen++] = listresp.delim;
listresp.name[clen] = '\0';
}
/* copy in first word */
if (!completions)
{
strfcpy (completion, listresp.name, sizeof(completion));
matchlen = strlen (completion);
completions++;
continue;
}
matchlen = longest_common_prefix (completion, listresp.name, 0, matchlen);
completions++;
}
}
while (rc == IMAP_CMD_CONTINUE);
idata->cmddata = NULL;
if (completions)
{
/* reformat output */
imap_qualify_path (dest, dlen, &mx, completion);
mutt_pretty_mailbox (dest, dlen);
FREE (&mx.mbox);
return 0;
}
return -1;
}
/* imap_fast_trash: use server COPY command to copy deleted
* messages to the trash folder.
* Return codes:
* -1: error
* 0: success
* 1: non-fatal error - try fetch/append */
int imap_fast_trash (CONTEXT* ctx, char* dest)
{
IMAP_DATA* idata;
char mbox[LONG_STRING];
char mmbox[LONG_STRING];
char prompt[LONG_STRING];
int n, rc;
IMAP_MBOX mx;
int triedcreate = 0;
BUFFER *sync_cmd = NULL;
int err_continue = MUTT_NO;
idata = (IMAP_DATA*) ctx->data;
if (imap_parse_path (dest, &mx))
{
dprint (1, (debugfile, "imap_fast_trash: bad destination %s\n", dest));
return -1;
}
/* check that the save-to folder is in the same account */
if (!mutt_account_match (&(CTX_DATA->conn->account), &(mx.account)))
{
dprint (3, (debugfile, "imap_fast_trash: %s not same server as %s\n",
dest, ctx->path));
return 1;
}
imap_fix_path (idata, mx.mbox, mbox, sizeof (mbox));
if (!*mbox)
strfcpy (mbox, "INBOX", sizeof (mbox));
imap_munge_mbox_name (idata, mmbox, sizeof (mmbox), mbox);
sync_cmd = mutt_buffer_new ();
for (n = 0; n < ctx->msgcount; n++)
{
if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed &&
ctx->hdrs[n]->deleted && !ctx->hdrs[n]->purge)
{
rc = imap_sync_message_for_copy (idata, ctx->hdrs[n], sync_cmd, &err_continue);
if (rc < 0)
{
dprint (1, (debugfile, "imap_fast_trash: could not sync\n"));
goto out;
}
}
}
/* loop in case of TRYCREATE */
do
{
rc = imap_exec_msgset (idata, "UID COPY", mmbox, MUTT_TRASH, 0, 0);
if (!rc)
{
dprint (1, (debugfile, "imap_fast_trash: No messages to trash\n"));
rc = -1;
goto out;
}
else if (rc < 0)
{
dprint (1, (debugfile, "could not queue copy\n"));
goto out;
}
else if (!ctx->quiet)
mutt_message (_("Copying %d messages to %s..."), rc, mbox);
/* let's get it on */
rc = imap_exec (idata, NULL, IMAP_CMD_FAIL_OK);
if (rc == -2)
{
if (triedcreate)
{
dprint (1, (debugfile, "Already tried to create mailbox %s\n", mbox));
break;
}
/* bail out if command failed for reasons other than nonexistent target */
if (ascii_strncasecmp (imap_get_qualifier (idata->buf), "[TRYCREATE]", 11))
break;
dprint (3, (debugfile, "imap_fast_trash: server suggests TRYCREATE\n"));
snprintf (prompt, sizeof (prompt), _("Create %s?"), mbox);
if (option (OPTCONFIRMCREATE) && mutt_yesorno (prompt, 1) < 1)
{
mutt_clear_error ();
goto out;
}
if (imap_create_mailbox (idata, mbox) < 0)
break;
triedcreate = 1;
}
}
while (rc == -2);
if (rc != 0)
{
imap_error ("imap_fast_trash", idata->buf);
goto out;
}
rc = 0;
out:
mutt_buffer_free (&sync_cmd);
FREE (&mx.mbox);
return rc < 0 ? -1 : rc;
}
struct mx_ops mx_imap_ops = {
.open = imap_open_mailbox,
.open_append = imap_open_mailbox_append,
.close = imap_close_mailbox,
.open_msg = imap_fetch_message,
.close_msg = imap_close_message,
.commit_msg = imap_commit_message,
.open_new_msg = imap_open_new_message,
.check = imap_check_mailbox_reopen,
.sync = NULL, /* imap syncing is handled by imap_sync_mailbox */
.save_to_header_cache = imap_save_to_header_cache,
};
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_4051_0 |
crossvul-cpp_data_bad_3568_8 | /* -*- Mode: c; c-basic-offset: 2 -*-
*
* raptor_rdfxml.c - Raptor RDF/XML Parser
*
* Copyright (C) 2000-2008, David Beckett http://www.dajobe.org/
* Copyright (C) 2000-2005, University of Bristol, UK http://www.bristol.ac.uk/
*
* This package is Free Software and part of Redland http://librdf.org/
*
* It is licensed under the following three licenses as alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE.html or LICENSE.txt at the top of this package for the
* complete terms and further detail along with the license texts for
* the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.
*
*
*/
#ifdef HAVE_CONFIG_H
#include <raptor_config.h>
#endif
#ifdef WIN32
#include <win32_raptor_config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
/* Raptor includes */
#include "raptor2.h"
#include "raptor_internal.h"
/* Define these for far too much output */
#undef RAPTOR_DEBUG_VERBOSE
#undef RAPTOR_DEBUG_CDATA
/* Raptor structures */
typedef enum {
/* Catch uninitialised state */
RAPTOR_STATE_INVALID = 0,
/* Skipping current tree of elements - used to recover finding
* illegal content, when parsling permissively.
*/
RAPTOR_STATE_SKIPPING,
/* Not in RDF grammar yet - searching for a start element.
*
* This can be <rdf:RDF> (goto NODE_ELEMENT_LIST) but since it is optional,
* the start element can also be one of
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementURIs
*
* If RDF content is assumed, go straight to OBJ
*/
RAPTOR_STATE_UNKNOWN,
/* A list of node elements
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementList
*/
RAPTOR_STATE_NODE_ELEMENT_LIST,
/* Found an <rdf:Description> */
RAPTOR_STATE_DESCRIPTION,
/* Found a property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*/
RAPTOR_STATE_PROPERTYELT,
/* A property element that is an ordinal - rdf:li, rdf:_n
*/
RAPTOR_STATE_MEMBER_PROPERTYELT,
/* Found a node element
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElement
*/
RAPTOR_STATE_NODE_ELEMENT,
/* A property element with rdf:parseType="Literal"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeLiteralPropertyElt
*/
RAPTOR_STATE_PARSETYPE_LITERAL,
/* A property element with rdf:parseType="Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeResourcePropertyElt
*/
RAPTOR_STATE_PARSETYPE_RESOURCE,
/* A property element with rdf:parseType="Collection"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeCollectionPropertyElt
*
* (This also handles daml:Collection)
*/
RAPTOR_STATE_PARSETYPE_COLLECTION,
/* A property element with a rdf:parseType attribute and a value
* not "Literal" or "Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeOtherPropertyElt
*/
RAPTOR_STATE_PARSETYPE_OTHER,
RAPTOR_STATE_PARSETYPE_LAST = RAPTOR_STATE_PARSETYPE_OTHER
} raptor_state;
static const char* const raptor_state_names[RAPTOR_STATE_PARSETYPE_LAST+2] = {
"INVALID",
"SKIPPING",
"UNKNOWN",
"nodeElementList",
"propertyElt",
"Description",
"propertyElt",
"memberPropertyElt",
"nodeElement",
"parseTypeLiteral",
"parseTypeResource",
"parseTypeCollection",
"parseTypeOther"
};
static const char * raptor_rdfxml_state_as_string(raptor_state state)
{
if(state < 1 || state > RAPTOR_STATE_PARSETYPE_LAST)
state = (raptor_state)0;
return raptor_state_names[(int)state];
}
/*
* raptor_rdfxml_check_propertyElement_name:
* @name: rdf namespace term
*
* Check if an rdf namespace name is allowed to be used as a Node Element.
*
* Return value: < 0 if unknown rdf namespace term, 0 if known and not allowed, > 0 if known and allowed
*/
static int
raptor_rdfxml_check_nodeElement_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, name))
return raptor_rdf_ns_terms_info[i].allowed_as_nodeElement;
return -1;
}
/*
* raptor_rdfxml_check_propertyElement_name:
* @name: rdf namespace term
*
* Check if an rdf namespace name is allowed to be used as a Property Element.
*
* Return value: < 0 if unknown rdf namespace term, 0 if known and not allowed, > 0 if known and allowed
*/
static int
raptor_rdfxml_check_propertyElement_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, (const char*)name))
return raptor_rdf_ns_terms_info[i].allowed_as_propertyElement;
return -1;
}
static int
raptor_rdfxml_check_propertyAttribute_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, (const char*)name))
return raptor_rdf_ns_terms_info[i].allowed_as_propertyAttribute;
return -1;
}
typedef enum {
/* undetermined yet - whitespace is stored */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN,
/* literal content - no elements, cdata allowed, whitespace significant
* <propElement> blah </propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL,
/* parseType literal content (WF XML) - all content preserved
* <propElement rdf:parseType="Literal"><em>blah</em></propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL,
/* top-level nodes - 0+ elements expected, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* only used for <rdf:RDF> or implict <rdf:RDF>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES,
/* properties - 0+ elements expected, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* <nodeElement><prop1>blah</prop1> <prop2>blah</prop2> </nodeElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES,
/* property content - all content preserved
* any content type changes when first non-whitespace found
* <propElement>...
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT,
/* resource URI given - no element, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* <propElement rdf:resource="uri"/>
* <propElement rdf:resource="uri"></propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE,
/* skipping content - all content is preserved
* Used when skipping content for unknown parseType-s,
* error recovery, some other reason
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED,
/* parseType Collection - all content preserved
* Parsing of this determined by RDF/XML (Revised) closed collection rules
* <propElement rdf:parseType="Collection">...</propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION,
/* Like above but handles "daml:collection" */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION,
/* dummy for use in strings below */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST
} raptor_rdfxml_element_content_type;
static const struct {
const char * name;
int whitespace_significant;
/* non-blank cdata */
int cdata_allowed;
/* XML element content */
int element_allowed;
/* Do RDF-specific processing? (property attributes, rdf: attributes, ...) */
int rdf_processing;
} rdf_content_type_info[RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST]={
{"Unknown", 1, 1, 1, 0 },
{"Literal", 1, 1, 0, 0 },
{"XML Literal", 1, 1, 1, 0 },
{"Nodes", 0, 0, 1, 1 },
{"Properties", 0, 1, 1, 1 },
{"Property Content",1, 1, 1, 1 },
{"Resource", 0, 0, 0, 0 },
{"Preserved", 1, 1, 1, 0 },
{"Collection", 1, 1, 1, 1 },
{"DAML Collection", 1, 1, 1, 1 },
};
static const char *
raptor_rdfxml_element_content_type_as_string(raptor_rdfxml_element_content_type type)
{
if(type > RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST)
return "INVALID";
return rdf_content_type_info[type].name;
}
/*
* Raptor Element/attributes on stack
*/
struct raptor_rdfxml_element_s {
raptor_world* world;
raptor_xml_element *xml_element;
/* NULL at bottom of stack */
struct raptor_rdfxml_element_s *parent;
/* attributes declared in M&S */
const unsigned char * rdf_attr[RDF_NS_LAST + 1];
/* how many of above seen */
int rdf_attr_count;
/* state that this production matches */
raptor_state state;
/* how to handle the content inside this XML element */
raptor_rdfxml_element_content_type content_type;
/* starting state for children of this element */
raptor_state child_state;
/* starting content type for children of this element */
raptor_rdfxml_element_content_type child_content_type;
/* Reified statement identifier */
raptor_term* reified;
unsigned const char* reified_id;
/* Bag identifier */
raptor_term* bag;
int last_bag_ordinal; /* starts at 0, so first predicate is rdf:_1 */
/* Subject identifier (URI/anon ID), type, source
*
* When the XML element represents a node, this is the identifier
*/
raptor_term* subject;
/* Predicate URI
*
* When the XML element represents a node or predicate,
* this is the identifier of the predicate
*/
raptor_term* predicate;
/* Object identifier (URI/anon ID), type, source
*
* When this XML element generates a statement that needs an object,
* possibly from a child element, this is the identifier of the object
*/
raptor_term* object;
/* URI of datatype of literal */
raptor_uri *object_literal_datatype;
/* last ordinal used, so initialising to 0 works, emitting rdf:_1 first */
int last_ordinal;
/* If this element's parseType is a Collection
* this identifies the anon node of current tail of the collection(list).
*/
const unsigned char *tail_id;
/* RDF/XML specific checks */
/* all cdata so far is whitespace */
unsigned int content_cdata_all_whitespace;
};
typedef struct raptor_rdfxml_element_s raptor_rdfxml_element;
#define RAPTOR_RDFXML_N_CONCEPTS 5
/*
* Raptor parser object
*/
struct raptor_rdfxml_parser_s {
raptor_sax2 *sax2;
/* stack of elements - elements add after current_element */
raptor_rdfxml_element *root_element;
raptor_rdfxml_element *current_element;
raptor_uri* concepts[RAPTOR_RDFXML_N_CONCEPTS];
/* set of seen rdf:ID / rdf:bagID values (with in-scope base URI) */
raptor_id_set* id_set;
void *xml_content;
size_t xml_content_length;
raptor_iostream* iostream;
/* writer for building parseType="Literal" content */
raptor_xml_writer* xml_writer;
};
/* static variables */
#define RAPTOR_DAML_NS_URI(rdf_xml_parser) rdf_xml_parser->concepts[0]
#define RAPTOR_DAML_List_URI(rdf_xml_parser) rdf_xml_parser->concepts[1]
#define RAPTOR_DAML_first_URI(rdf_xml_parser) rdf_xml_parser->concepts[2]
#define RAPTOR_DAML_rest_URI(rdf_xml_parser) rdf_xml_parser->concepts[3]
#define RAPTOR_DAML_nil_URI(rdf_xml_parser) rdf_xml_parser->concepts[4]
/* RAPTOR_RDFXML_N_CONCEPTS defines size of array */
/* prototypes for element functions */
static raptor_rdfxml_element* raptor_rdfxml_element_pop(raptor_rdfxml_parser *rdf_parser);
static void raptor_rdfxml_element_push(raptor_rdfxml_parser *rdf_parser, raptor_rdfxml_element* element);
static int raptor_rdfxml_record_ID(raptor_parser *rdf_parser, raptor_rdfxml_element *element, const unsigned char *id);
/* prototypes for grammar functions */
static void raptor_rdfxml_start_element_grammar(raptor_parser *parser, raptor_rdfxml_element *element);
static void raptor_rdfxml_end_element_grammar(raptor_parser *parser, raptor_rdfxml_element *element);
static void raptor_rdfxml_cdata_grammar(raptor_parser *parser, const unsigned char *s, int len, int is_cdata);
/* prototype for statement related functions */
static void raptor_rdfxml_generate_statement(raptor_parser *rdf_parser, raptor_term *subject, raptor_uri *predicate_uri, raptor_term *object, raptor_term *reified, raptor_rdfxml_element *bag_element);
/* Prototypes for parsing data functions */
static int raptor_rdfxml_parse_init(raptor_parser* rdf_parser, const char *name);
static void raptor_rdfxml_parse_terminate(raptor_parser *rdf_parser);
static int raptor_rdfxml_parse_start(raptor_parser* rdf_parser);
static int raptor_rdfxml_parse_chunk(raptor_parser* rdf_parser, const unsigned char *buffer, size_t len, int is_end);
static void raptor_rdfxml_update_document_locator(raptor_parser *rdf_parser);
static raptor_uri* raptor_rdfxml_inscope_base_uri(raptor_parser *rdf_parser);
static raptor_rdfxml_element*
raptor_rdfxml_element_pop(raptor_rdfxml_parser *rdf_xml_parser)
{
raptor_rdfxml_element *element = rdf_xml_parser->current_element;
if(!element)
return NULL;
rdf_xml_parser->current_element = element->parent;
if(rdf_xml_parser->root_element == element) /* just deleted root */
rdf_xml_parser->root_element = NULL;
return element;
}
static void
raptor_rdfxml_element_push(raptor_rdfxml_parser *rdf_xml_parser, raptor_rdfxml_element* element)
{
element->parent = rdf_xml_parser->current_element;
rdf_xml_parser->current_element = element;
if(!rdf_xml_parser->root_element)
rdf_xml_parser->root_element = element;
}
static void
raptor_free_rdfxml_element(raptor_rdfxml_element *element)
{
int i;
/* Free special RDF M&S attributes */
for(i = 0; i <= RDF_NS_LAST; i++)
if(element->rdf_attr[i])
RAPTOR_FREE(char*, element->rdf_attr[i]);
if(element->subject)
raptor_free_term(element->subject);
if(element->predicate)
raptor_free_term(element->predicate);
if(element->object)
raptor_free_term(element->object);
if(element->bag)
raptor_free_term(element->bag);
if(element->reified)
raptor_free_term(element->reified);
if(element->tail_id)
RAPTOR_FREE(char*, (char*)element->tail_id);
if(element->object_literal_datatype)
raptor_free_uri(element->object_literal_datatype);
if(element->reified_id)
RAPTOR_FREE(char*, (char*)element->reified_id);
RAPTOR_FREE(raptor_rdfxml_element, element);
}
static void
raptor_rdfxml_sax2_new_namespace_handler(void *user_data,
raptor_namespace* nspace)
{
raptor_parser* rdf_parser;
const unsigned char* namespace_name;
size_t namespace_name_len;
raptor_uri* uri = raptor_namespace_get_uri(nspace);
rdf_parser = (raptor_parser*)user_data;
raptor_parser_start_namespace(rdf_parser, nspace);
if(!uri)
return;
namespace_name = raptor_uri_as_counted_string(uri, &namespace_name_len);
if(namespace_name_len == raptor_rdf_namespace_uri_len-1 &&
!strncmp((const char*)namespace_name,
(const char*)raptor_rdf_namespace_uri,
namespace_name_len)) {
const unsigned char *prefix = raptor_namespace_get_prefix(nspace);
raptor_parser_warning(rdf_parser,
"Declaring a namespace with prefix %s to URI %s - one letter short of the RDF namespace URI and probably a mistake.",
prefix, namespace_name);
}
if(namespace_name_len > raptor_rdf_namespace_uri_len &&
!strncmp((const char*)namespace_name,
(const char*)raptor_rdf_namespace_uri,
raptor_rdf_namespace_uri_len)) {
raptor_parser_error(rdf_parser,
"Declaring a namespace URI %s to which the RDF namespace URI is a prefix is forbidden.",
namespace_name);
}
}
static void
raptor_rdfxml_start_element_handler(void *user_data,
raptor_xml_element* xml_element)
{
raptor_parser* rdf_parser;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
int ns_attributes_count = 0;
raptor_qname** named_attrs = NULL;
int i;
int count_bumped = 0;
rdf_parser = (raptor_parser*)user_data;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return;
raptor_rdfxml_update_document_locator(rdf_parser);
/* Create new element structure */
element = RAPTOR_CALLOC(raptor_rdfxml_element*, 1, sizeof(*element));
if(!element) {
raptor_parser_fatal_error(rdf_parser, "Out of memory");
rdf_parser->failed = 1;
return;
}
element->world = rdf_parser->world;
element->xml_element = xml_element;
raptor_rdfxml_element_push(rdf_xml_parser, element);
named_attrs = raptor_xml_element_get_attributes(xml_element);
ns_attributes_count = raptor_xml_element_get_attributes_count(xml_element);
/* RDF-specific processing of attributes */
if(ns_attributes_count) {
raptor_qname** new_named_attrs;
int offset = 0;
raptor_rdfxml_element* parent_element;
parent_element = element->parent;
/* Allocate new array to move namespaced-attributes to if
* rdf processing is performed
*/
new_named_attrs = RAPTOR_CALLOC(raptor_qname**, ns_attributes_count,
sizeof(raptor_qname*));
if(!new_named_attrs) {
raptor_parser_fatal_error(rdf_parser, "Out of memory");
rdf_parser->failed = 1;
return;
}
for(i = 0; i < ns_attributes_count; i++) {
raptor_qname* attr = named_attrs[i];
/* If:
* 1 We are handling RDF content and RDF processing is allowed on
* this element
* OR
* 2 We are not handling RDF content and
* this element is at the top level (top level Desc. / typedNode)
* i.e. we have no parent
* then handle the RDF attributes
*/
if((parent_element &&
rdf_content_type_info[parent_element->child_content_type].rdf_processing) ||
!parent_element) {
/* Save pointers to some RDF M&S attributes */
/* If RDF namespace-prefixed attributes */
if(attr->nspace && attr->nspace->is_rdf_ms) {
const unsigned char *attr_name = attr->local_name;
int j;
for(j = 0; j <= RDF_NS_LAST; j++)
if(!strcmp((const char*)attr_name,
raptor_rdf_ns_terms_info[j].name)) {
element->rdf_attr[j] = attr->value;
element->rdf_attr_count++;
/* Delete it if it was stored elsewhere */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Found RDF namespace attribute '%s' URI %s\n",
(char*)attr_name, attr->value);
#endif
/* make sure value isn't deleted from qname structure */
attr->value = NULL;
raptor_free_qname(attr);
attr = NULL;
break;
}
} /* end if RDF namespaced-prefixed attributes */
if(!attr)
continue;
/* If non namespace-prefixed RDF attributes found on an element */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES) &&
!attr->nspace) {
const unsigned char *attr_name = attr->local_name;
int j;
for(j = 0; j <= RDF_NS_LAST; j++)
if(!strcmp((const char*)attr_name,
raptor_rdf_ns_terms_info[j].name)) {
element->rdf_attr[j] = attr->value;
element->rdf_attr_count++;
if(!raptor_rdf_ns_terms_info[j].allowed_unprefixed_on_attribute)
raptor_parser_warning(rdf_parser,
"Using rdf attribute '%s' without the RDF namespace has been deprecated.",
attr_name);
/* Delete it if it was stored elsewhere */
/* make sure value isn't deleted from qname structure */
attr->value = NULL;
raptor_free_qname(attr);
attr = NULL;
break;
}
} /* end if non-namespace prefixed RDF attributes */
if(!attr)
continue;
} /* end if leave literal XML alone */
if(attr)
new_named_attrs[offset++] = attr;
}
/* new attribute count is set from attributes that haven't been skipped */
ns_attributes_count = offset;
if(!ns_attributes_count) {
/* all attributes were deleted so delete the new array */
RAPTOR_FREE(raptor_qname_array, new_named_attrs);
new_named_attrs = NULL;
}
RAPTOR_FREE(raptor_qname_array, named_attrs);
named_attrs = new_named_attrs;
raptor_xml_element_set_attributes(xml_element,
named_attrs, ns_attributes_count);
} /* end if ns_attributes_count */
/* start from unknown; if we have a parent, it may set this */
element->state = RAPTOR_STATE_UNKNOWN;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN;
if(element->parent &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN) {
element->content_type = element->parent->child_content_type;
if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* If parent has an rdf:resource, this element should not be here */
raptor_parser_error(rdf_parser,
"property element '%s' has multiple object node elements, skipping.",
parent_el_name->local_name);
element->state = RAPTOR_STATE_SKIPPING;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
} else {
if(!element->parent->child_state) {
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error: no parent element child_state set",
__func__);
return;
}
element->state = element->parent->child_state;
element->parent->xml_element->content_element_seen++;
count_bumped++;
/* leave literal XML alone */
if(!rdf_content_type_info[element->content_type].cdata_allowed) {
if(element->parent->xml_element->content_element_seen &&
element->parent->xml_element->content_cdata_seen) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* Uh oh - mixed content, the parent element has cdata too */
raptor_parser_warning(rdf_parser, "element '%s' has mixed content.",
parent_el_name->local_name);
}
/* If there is some existing all-whitespace content cdata
* before this node element, delete it
*/
if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES &&
element->parent->xml_element->content_element_seen &&
element->parent->content_cdata_all_whitespace &&
element->parent->xml_element->content_cdata_length) {
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
raptor_free_stringbuffer(element->parent->xml_element->content_cdata_sb);
element->parent->xml_element->content_cdata_sb = NULL;
element->parent->xml_element->content_cdata_length = 0;
}
} /* end if leave literal XML alone */
} /* end if parent has no rdf:resource */
} /* end if element->parent */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Using content type %s\n",
rdf_content_type_info[element->content_type].name);
fprintf(stderr, "raptor_rdfxml_start_element_handler: Start ns-element: ");
raptor_print_xml_element(xml_element, stderr);
#endif
/* Check for non namespaced stuff when not in a parseType literal, other */
if(rdf_content_type_info[element->content_type].rdf_processing) {
const raptor_namespace* ns;
ns = raptor_xml_element_get_name(xml_element)->nspace;
/* The element */
/* If has no namespace or the namespace has no name (xmlns="") */
if((!ns || (ns && !raptor_namespace_get_uri(ns))) && element->parent) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
raptor_parser_error(rdf_parser,
"Using an element '%s' without a namespace is forbidden.",
parent_el_name->local_name);
element->state = RAPTOR_STATE_SKIPPING;
/* Remove count above so that parent thinks this is empty */
if(count_bumped)
element->parent->xml_element->content_element_seen--;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
}
/* Check for any remaining non-namespaced attributes */
if(named_attrs) {
for(i = 0; i < ns_attributes_count; i++) {
raptor_qname *attr = named_attrs[i];
/* Check if any attributes are non-namespaced */
if(!attr->nspace ||
(attr->nspace && !raptor_namespace_get_uri(attr->nspace))) {
raptor_parser_error(rdf_parser,
"Using an attribute '%s' without a namespace is forbidden.",
attr->local_name);
raptor_free_qname(attr);
named_attrs[i] = NULL;
}
}
}
}
if(element->rdf_attr[RDF_NS_aboutEach] ||
element->rdf_attr[RDF_NS_aboutEachPrefix]) {
raptor_parser_warning(rdf_parser,
"element '%s' has aboutEach / aboutEachPrefix, skipping.",
raptor_xml_element_get_name(xml_element)->local_name);
element->state = RAPTOR_STATE_SKIPPING;
/* Remove count above so that parent thinks this is empty */
if(count_bumped)
element->parent->xml_element->content_element_seen--;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
}
/* Right, now ready to enter the grammar */
raptor_rdfxml_start_element_grammar(rdf_parser, element);
return;
}
static void
raptor_rdfxml_end_element_handler(void *user_data,
raptor_xml_element* xml_element)
{
raptor_parser* rdf_parser;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
rdf_parser = (raptor_parser*)user_data;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(!rdf_parser->failed) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_rdfxml_end_element_grammar(rdf_parser,
rdf_xml_parser->current_element);
}
element = raptor_rdfxml_element_pop(rdf_xml_parser);
if(element) {
if(element->parent) {
/* Do not change this; PROPERTYELT will turn into MEMBER if necessary
* See the switch case for MEMBER / PROPERTYELT where the test is done.
*
* PARSETYPE_RESOURCE should never be propogated up since it
* will turn the next child (node) element into a property
*/
if(element->state != RAPTOR_STATE_MEMBER_PROPERTYELT &&
element->state != RAPTOR_STATE_PARSETYPE_RESOURCE)
element->parent->child_state = element->state;
}
raptor_free_rdfxml_element(element);
}
}
/* cdata (and ignorable whitespace for libxml).
* s 0 terminated is for libxml
*/
static void
raptor_rdfxml_characters_handler(void *user_data,
raptor_xml_element* xml_element,
const unsigned char *s, int len)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_cdata_grammar(rdf_parser, s, len, 0);
}
/* cdata (and ignorable whitespace for libxml).
* s is 0 terminated for libxml2
*/
static void
raptor_rdfxml_cdata_handler(void *user_data, raptor_xml_element* xml_element,
const unsigned char *s, int len)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_cdata_grammar(rdf_parser, s, len, 1);
}
/* comment handler
* s is 0 terminated
*/
static void
raptor_rdfxml_comment_handler(void *user_data, raptor_xml_element* xml_element,
const unsigned char *s)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
if(rdf_parser->failed || !xml_element)
return;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
element = rdf_xml_parser->current_element;
if(element) {
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL)
raptor_xml_writer_comment(rdf_xml_parser->xml_writer, s);
}
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("XML Comment '%s'\n", s);
#endif
}
static const unsigned char* const daml_namespace_uri_string = (const unsigned char*)"http://www.daml.org/2001/03/daml+oil#";
static const int daml_namespace_uri_string_len = 37;
static int
raptor_rdfxml_parse_init(raptor_parser* rdf_parser, const char *name)
{
raptor_rdfxml_parser* rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
raptor_sax2* sax2;
raptor_world* world = rdf_parser->world;
/* Allocate sax2 object */
sax2 = raptor_new_sax2(rdf_parser->world, &rdf_parser->locator, rdf_parser);
rdf_xml_parser->sax2 = sax2;
if(!sax2)
return 1;
/* Initialize sax2 element handlers */
raptor_sax2_set_start_element_handler(sax2, raptor_rdfxml_start_element_handler);
raptor_sax2_set_end_element_handler(sax2, raptor_rdfxml_end_element_handler);
raptor_sax2_set_characters_handler(sax2, raptor_rdfxml_characters_handler);
raptor_sax2_set_cdata_handler(sax2, raptor_rdfxml_cdata_handler);
raptor_sax2_set_comment_handler(sax2, raptor_rdfxml_comment_handler);
raptor_sax2_set_namespace_handler(sax2, raptor_rdfxml_sax2_new_namespace_handler);
/* Allocate uris */
RAPTOR_DAML_NS_URI(rdf_xml_parser) = raptor_new_uri_from_counted_string(world,
daml_namespace_uri_string,
daml_namespace_uri_string_len);
RAPTOR_DAML_List_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"List");
RAPTOR_DAML_first_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser) ,(const unsigned char *)"first");
RAPTOR_DAML_rest_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"rest");
RAPTOR_DAML_nil_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"nil");
/* Check for uri allocation failures */
if(!RAPTOR_DAML_NS_URI(rdf_xml_parser) ||
!RAPTOR_DAML_List_URI(rdf_xml_parser) ||
!RAPTOR_DAML_first_URI(rdf_xml_parser) ||
!RAPTOR_DAML_rest_URI(rdf_xml_parser) ||
!RAPTOR_DAML_nil_URI(rdf_xml_parser))
return 1;
/* Everything succeeded */
return 0;
}
static int
raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
static void
raptor_rdfxml_parse_terminate(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
int i;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_xml_parser->sax2) {
raptor_free_sax2(rdf_xml_parser->sax2);
rdf_xml_parser->sax2 = NULL;
}
while( (element = raptor_rdfxml_element_pop(rdf_xml_parser)) )
raptor_free_rdfxml_element(element);
for(i = 0; i < RAPTOR_RDFXML_N_CONCEPTS; i++) {
raptor_uri* concept_uri = rdf_xml_parser->concepts[i];
if(concept_uri) {
raptor_free_uri(concept_uri);
rdf_xml_parser->concepts[i] = NULL;
}
}
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
}
static int
raptor_rdfxml_parse_recognise_syntax(raptor_parser_factory* factory,
const unsigned char *buffer, size_t len,
const unsigned char *identifier,
const unsigned char *suffix,
const char *mime_type)
{
int score = 0;
if(suffix) {
if(!strcmp((const char*)suffix, "rdf") ||
!strcmp((const char*)suffix, "rdfs") ||
!strcmp((const char*)suffix, "foaf") ||
!strcmp((const char*)suffix, "doap") ||
!strcmp((const char*)suffix, "owl") ||
!strcmp((const char*)suffix, "daml"))
score = 9;
if(!strcmp((const char*)suffix, "rss"))
score = 3;
}
if(identifier) {
if(strstr((const char*)identifier, "rss1"))
score += 5;
else if(!suffix && strstr((const char*)identifier, "rss"))
score += 3;
else if(!suffix && strstr((const char*)identifier, "rdf"))
score += 2;
else if(!suffix && strstr((const char*)identifier, "RDF"))
score += 2;
}
if(mime_type) {
if(strstr((const char*)mime_type, "html"))
score -= 4;
else if(!strcmp((const char*)mime_type, "text/rdf"))
score += 7;
else if(!strcmp((const char*)mime_type, "application/xml"))
score += 5;
}
if(buffer && len) {
/* Check it's an XML namespace declared and not N3 or Turtle which
* mention the namespace URI but not in this form.
*/
#define HAS_RDF_XMLNS1 (raptor_memstr((const char*)buffer, len, "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS2 (raptor_memstr((const char*)buffer, len, "xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS3 (raptor_memstr((const char*)buffer, len, "xmlns=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS4 (raptor_memstr((const char*)buffer, len, "xmlns='http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_ENTITY1 (raptor_memstr((const char*)buffer, len, "<!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>") != NULL)
#define HAS_RDF_ENTITY2 (raptor_memstr((const char*)buffer, len, "<!ENTITY rdf \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">") != NULL)
#define HAS_RDF_ENTITY3 (raptor_memstr((const char*)buffer, len, "xmlns:rdf=\"&rdf;\"") != NULL)
#define HAS_RDF_ENTITY4 (raptor_memstr((const char*)buffer, len, "xmlns:rdf='&rdf;'") != NULL)
#define HAS_HTML_NS (raptor_memstr((const char*)buffer, len, "http://www.w3.org/1999/xhtml") != NULL)
#define HAS_HTML_ROOT (raptor_memstr((const char*)buffer, len, "<html") != NULL)
if(!HAS_HTML_NS && !HAS_HTML_ROOT &&
(HAS_RDF_XMLNS1 || HAS_RDF_XMLNS2 || HAS_RDF_XMLNS3 || HAS_RDF_XMLNS4 ||
HAS_RDF_ENTITY1 || HAS_RDF_ENTITY2 || HAS_RDF_ENTITY3 || HAS_RDF_ENTITY4)
) {
int has_rdf_RDF = (raptor_memstr((const char*)buffer, len, "<rdf:RDF") != NULL);
int has_rdf_Description = (raptor_memstr((const char*)buffer, len, "rdf:Description") != NULL);
int has_rdf_about = (raptor_memstr((const char*)buffer, len, "rdf:about") != NULL);
score += 7;
if(has_rdf_RDF)
score++;
if(has_rdf_Description)
score++;
if(has_rdf_about)
score++;
}
}
return score;
}
static int
raptor_rdfxml_parse_chunk(raptor_parser* rdf_parser,
const unsigned char *buffer,
size_t len, int is_end)
{
raptor_rdfxml_parser* rdf_xml_parser;
int rc;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return 1;
rc = raptor_sax2_parse_chunk(rdf_xml_parser->sax2, buffer, len, is_end);
if(is_end) {
if(rdf_parser->emitted_default_graph) {
raptor_parser_end_graph(rdf_parser, NULL, 0);
rdf_parser->emitted_default_graph--;
}
}
return rc;
}
static void
raptor_rdfxml_generate_statement(raptor_parser *rdf_parser,
raptor_term *subject_term,
raptor_uri *predicate_uri,
raptor_term *object_term,
raptor_term *reified_term,
raptor_rdfxml_element* bag_element)
{
raptor_statement *statement = &rdf_parser->statement;
raptor_term* predicate_term = NULL;
int free_reified_term = 0;
if(rdf_parser->failed)
return;
#ifdef RAPTOR_DEBUG_VERBOSE
if(!subject_term)
RAPTOR_FATAL1("Statement has no subject\n");
if(!predicate_uri)
RAPTOR_FATAL1("Statement has no predicate\n");
if(!object_term)
RAPTOR_FATAL1("Statement has no object\n");
#endif
predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri);
if(!predicate_term)
return;
statement->subject = subject_term;
statement->predicate = predicate_term;
statement->object = object_term;
#ifdef RAPTOR_DEBUG_VERBOSE
fprintf(stderr, "raptor_rdfxml_generate_statement: Generating statement: ");
raptor_statement_print(statement, stderr);
fputc('\n', stderr);
#endif
if(!rdf_parser->emitted_default_graph) {
raptor_parser_start_graph(rdf_parser, NULL, 0);
rdf_parser->emitted_default_graph++;
}
if(!rdf_parser->statement_handler)
goto generate_tidy;
/* Generate the statement; or is it a fact? */
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* the bagID mess */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID) &&
bag_element && bag_element->bag) {
raptor_term* bag = bag_element->bag;
raptor_uri* bag_predicate_uri = NULL;
raptor_term* bag_predicate_term = NULL;
statement->subject = bag;
bag_element->last_bag_ordinal++;
/* new URI object */
bag_predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world,
bag_element->last_bag_ordinal);
if(!bag_predicate_uri)
goto generate_tidy;
bag_predicate_term = raptor_new_term_from_uri(rdf_parser->world,
bag_predicate_uri);
raptor_free_uri(bag_predicate_uri);
if(!bag_predicate_term)
goto generate_tidy;
statement->predicate = bag_predicate_term;
if(!reified_term || !reified_term->value.blank.string) {
unsigned char *reified_id = NULL;
/* reified_term is NULL so generate a bag ID */
reified_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!reified_id)
goto generate_tidy;
reified_term = raptor_new_term_from_blank(rdf_parser->world, reified_id);
RAPTOR_FREE(char*, reified_id);
if(!reified_term)
goto generate_tidy;
free_reified_term = 1;
}
statement->object = reified_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
if(bag_predicate_term)
raptor_free_term(bag_predicate_term);
}
/* return if is there no reified ID (that is valid) */
if(!reified_term || !reified_term->value.blank.string)
goto generate_tidy;
/* otherwise generate reified statements */
statement->subject = reified_term;
statement->predicate = RAPTOR_RDF_type_term(rdf_parser->world);
statement->object = RAPTOR_RDF_Statement_term(rdf_parser->world);
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_subject_term(rdf_parser->world);
statement->object = subject_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_predicate_term(rdf_parser->world);
statement->object = predicate_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_object_term(rdf_parser->world);
statement->object = object_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
generate_tidy:
/* Tidy up things allocated here */
if(predicate_term)
raptor_free_term(predicate_term);
if(free_reified_term && reified_term)
raptor_free_term(reified_term);
}
/**
* raptor_rdfxml_element_has_property_attributes:
* @element: element with the property attributes
*
* Return true if the element has at least one property attribute.
*
**/
static int
raptor_rdfxml_element_has_property_attributes(raptor_rdfxml_element *element)
{
int i;
if(element->xml_element->attribute_count > 0)
return 1;
/* look for rdf: properties */
for(i = 0; i <= RDF_NS_LAST; i++) {
if(element->rdf_attr[i] &&
raptor_rdf_ns_terms_info[i].type != RAPTOR_TERM_TYPE_UNKNOWN)
return 1;
}
return 0;
}
/**
* raptor_rdfxml_process_property_attributes:
* @rdf_parser: Raptor parser object
* @attributes_element: element with the property attributes
* @resource_element: element that defines the resource URI
* subject->value etc.
* @property_node_identifier: Use this identifier for the resource URI
* and count any ordinals for it locally
*
* Process the property attributes for an element for a given resource.
*
**/
static int
raptor_rdfxml_process_property_attributes(raptor_parser *rdf_parser,
raptor_rdfxml_element *attributes_element,
raptor_rdfxml_element *resource_element,
raptor_term *property_node_identifier)
{
unsigned int i;
raptor_term *resource_identifier;
resource_identifier = property_node_identifier ? property_node_identifier : resource_element->subject;
/* Process attributes as propAttr* = * (propName="string")*
*/
for(i = 0; i < attributes_element->xml_element->attribute_count; i++) {
raptor_qname* attr = attributes_element->xml_element->attributes[i];
const unsigned char *name;
const unsigned char *value;
int handled = 0;
if(!attr)
continue;
name = attr->local_name;
value = attr->value;
if(!attr->nspace) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Using property attribute '%s' without a namespace is forbidden.",
name);
continue;
}
if(!raptor_unicode_check_utf8_nfc_string(value, strlen((const char*)value),
NULL)) {
const char *message;
message = "Property attribute '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, name, value);
else
raptor_parser_warning(rdf_parser, message, name, value);
continue;
}
/* Generate the property statement using one of these properties:
* 1) rdf:_n
* 2) the URI from the rdf:* attribute where allowed
* 3) otherwise forbidden (including rdf:li)
*/
if(attr->nspace->is_rdf_ms) {
/* is rdf: namespace */
if(*name == '_') {
int ordinal;
/* recognise rdf:_ */
name++;
ordinal = raptor_check_ordinal(name);
if(ordinal < 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Illegal ordinal value %d in property attribute '%s' seen on containing element '%s'.",
ordinal, attr->local_name, name);
}
} else {
int rc;
raptor_rdfxml_update_document_locator(rdf_parser);
rc = raptor_rdfxml_check_propertyAttribute_name((const char*)name);
if(!rc)
raptor_parser_error(rdf_parser,
"RDF term %s is forbidden as a property attribute.",
name);
else if(rc < 0)
raptor_parser_warning(rdf_parser,
"Unknown RDF namespace property attribute '%s'.",
name);
}
} /* end is RDF namespace property */
if(!handled) {
raptor_term* object_term;
object_term = raptor_new_term_from_literal(rdf_parser->world,
(unsigned char*)value,
NULL, NULL);
/* else not rdf: namespace or unknown in rdf: namespace so
* generate a statement with a literal object
*/
raptor_rdfxml_generate_statement(rdf_parser,
resource_identifier,
attr->uri,
object_term,
NULL, /* Property attributes are never reified*/
resource_element);
raptor_free_term(object_term);
}
} /* end for ... attributes */
/* Handle rdf property attributes
* (only rdf:type and rdf:value at present)
*/
for(i = 0; i <= RDF_NS_LAST; i++) {
const unsigned char *value = attributes_element->rdf_attr[i];
size_t value_len;
int object_is_literal;
raptor_uri *property_uri;
raptor_term* object_term;
if(!value)
continue;
value_len = strlen((const char*)value);
object_is_literal = (raptor_rdf_ns_terms_info[i].type == RAPTOR_TERM_TYPE_LITERAL);
if(raptor_rdf_ns_terms_info[i].type == RAPTOR_TERM_TYPE_UNKNOWN) {
const char *name = raptor_rdf_ns_terms_info[i].name;
int rc = raptor_rdfxml_check_propertyAttribute_name(name);
if(!rc) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"RDF term %s is forbidden as a property attribute.",
name);
continue;
} else if(rc < 0)
raptor_parser_warning(rdf_parser,
"Unknown RDF namespace property attribute '%s'.",
name);
}
if(object_is_literal &&
!raptor_unicode_check_utf8_nfc_string(value, value_len, NULL)) {
const char *message;
message = "Property attribute '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message,
raptor_rdf_ns_terms_info[i].name, value);
else
raptor_parser_warning(rdf_parser, message,
raptor_rdf_ns_terms_info[i].name, value);
continue;
}
property_uri = raptor_new_uri_for_rdf_concept(rdf_parser->world,
(const unsigned char*)raptor_rdf_ns_terms_info[i].name);
if(object_is_literal) {
object_term = raptor_new_term_from_literal(rdf_parser->world,
(unsigned char*)value,
NULL, NULL);
} else {
raptor_uri *base_uri;
raptor_uri *object_uri;
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
object_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri, value);
object_term = raptor_new_term_from_uri(rdf_parser->world, object_uri);
raptor_free_uri(object_uri);
}
raptor_rdfxml_generate_statement(rdf_parser,
resource_identifier,
property_uri,
object_term,
NULL, /* Property attributes are never reified*/
resource_element);
raptor_free_term(object_term);
raptor_free_uri(property_uri);
} /* end for rdf:property values */
return 0;
}
static void
raptor_rdfxml_start_element_grammar(raptor_parser *rdf_parser,
raptor_rdfxml_element *element)
{
raptor_rdfxml_parser *rdf_xml_parser;
int finished;
raptor_state state;
raptor_xml_element* xml_element;
raptor_qname* el_qname;
const unsigned char *el_name;
int element_in_rdf_ns;
int rc = 0;
raptor_uri* base_uri;
raptor_uri* element_name_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
xml_element = element->xml_element;
el_qname = raptor_xml_element_get_name(xml_element);
el_name = el_qname->local_name;
element_in_rdf_ns = (el_qname->nspace && el_qname->nspace->is_rdf_ms);
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
element_name_uri = el_qname->uri;
state = element->state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Starting in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
finished = 0;
while(!finished) {
switch(state) {
case RAPTOR_STATE_SKIPPING:
element->child_state = state;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
finished = 1;
break;
case RAPTOR_STATE_UNKNOWN:
/* found <rdf:RDF> ? */
if(element_in_rdf_ns) {
if(raptor_uri_equals(element_name_uri,
RAPTOR_RDF_RDF_URI(rdf_parser->world))) {
element->child_state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES;
/* Yes - need more content before can continue,
* so wait for another element
*/
finished = 1;
break;
}
if(raptor_uri_equals(element_name_uri,
RAPTOR_RDF_Description_URI(rdf_parser->world))) {
state = RAPTOR_STATE_DESCRIPTION;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
/* Yes - found something so move immediately to description */
break;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_nodeElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a node element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
}
/* If scanning for element, can continue */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING)) {
finished = 1;
break;
}
/* Otherwise the choice of the next state can be made
* from the current element by the OBJ state
*/
state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES;
break;
case RAPTOR_STATE_NODE_ELEMENT_LIST:
/* Handling
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementList
*
* Everything goes to nodeElement
*/
state = RAPTOR_STATE_NODE_ELEMENT;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
break;
case RAPTOR_STATE_DESCRIPTION:
case RAPTOR_STATE_NODE_ELEMENT:
case RAPTOR_STATE_PARSETYPE_RESOURCE:
case RAPTOR_STATE_PARSETYPE_COLLECTION:
/* Handling <rdf:Description> or other node element
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElement
*
* or a property element acting as a node element for
* rdf:parseType="Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeResourcePropertyElt
* or rdf:parseType="Collection" (and daml:Collection)
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeCollectionPropertyElt
*
* Only create a bag if bagID given
*/
if(!element_name_uri) {
/* We cannot handle this */
raptor_parser_warning(rdf_parser, "Using node element '%s' without a namespace is forbidden.",
el_qname->local_name);
raptor_rdfxml_update_document_locator(rdf_parser);
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_nodeElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a node element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
if(element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION &&
element->parent &&
(element->parent->state == RAPTOR_STATE_PROPERTYELT ||
element->parent->state == RAPTOR_STATE_MEMBER_PROPERTYELT) &&
element->parent->xml_element->content_element_seen > 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser, "The enclosing property already has an object");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(state == RAPTOR_STATE_NODE_ELEMENT ||
state == RAPTOR_STATE_DESCRIPTION ||
state == RAPTOR_STATE_PARSETYPE_COLLECTION) {
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_Description_URI(rdf_parser->world)))
state = RAPTOR_STATE_DESCRIPTION;
else
state = RAPTOR_STATE_NODE_ELEMENT;
}
if((element->rdf_attr[RDF_NS_ID]!=NULL) +
(element->rdf_attr[RDF_NS_about]!=NULL) +
(element->rdf_attr[RDF_NS_nodeID]!=NULL) > 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser, "Multiple attributes of rdf:ID, rdf:about and rdf:nodeID on element '%s' - only one allowed.", el_name);
}
if(element->rdf_attr[RDF_NS_ID]) {
unsigned char* subject_id;
raptor_uri* subject_uri;
subject_id = (unsigned char*)element->rdf_attr[RDF_NS_ID];
if(!raptor_valid_xml_ID(rdf_parser, subject_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:ID value '%s'",
subject_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, subject_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:ID value '%s'",
subject_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* after this, subject_id is the owner of the ID string */
element->rdf_attr[RDF_NS_ID] = NULL;
subject_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!subject_uri)
goto oom;
element->subject = raptor_new_term_from_uri(rdf_parser->world,
subject_uri);
raptor_free_uri(subject_uri);
if(!element->subject)
goto oom;
} else if(element->rdf_attr[RDF_NS_about]) {
raptor_uri* subject_uri;
subject_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri,
(const unsigned char*)element->rdf_attr[RDF_NS_about]);
if(!subject_uri)
goto oom;
element->subject = raptor_new_term_from_uri(rdf_parser->world,
subject_uri);
raptor_free_uri(subject_uri);
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_about]);
element->rdf_attr[RDF_NS_about] = NULL;
if(!element->subject)
goto oom;
} else if(element->rdf_attr[RDF_NS_nodeID]) {
unsigned char* subject_id;
subject_id = raptor_world_internal_generate_id(rdf_parser->world,
(unsigned char*)element->rdf_attr[RDF_NS_nodeID]);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
element->rdf_attr[RDF_NS_nodeID] = NULL;
if(!element->subject)
goto oom;
if(!raptor_valid_xml_ID(rdf_parser, element->subject->value.blank.string)) {
raptor_parser_error(rdf_parser, "Illegal rdf:nodeID value '%s'",
(const char*)element->subject->value.blank.string);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
} else if(element->parent &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION &&
element->parent->object) {
/* copy from parent (property element), it has a URI for us */
element->subject = raptor_term_copy(element->parent->object);
} else {
unsigned char* subject_id;
subject_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!element->subject)
goto oom;
}
if(element->rdf_attr[RDF_NS_bagID]) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
unsigned char* bag_id;
raptor_uri* bag_uri = NULL;
bag_id = (unsigned char*)element->rdf_attr[RDF_NS_bagID];
element->rdf_attr[RDF_NS_bagID] = NULL;
bag_uri = raptor_new_uri_from_id(rdf_parser->world,
base_uri, bag_id);
if(!bag_uri) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
element->bag = raptor_new_term_from_uri(rdf_parser->world, bag_uri);
raptor_free_uri(bag_uri);
if(!raptor_valid_xml_ID(rdf_parser, bag_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, bag_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
RAPTOR_FREE(char*, bag_id);
raptor_parser_warning(rdf_parser, "rdf:bagID is deprecated.");
raptor_rdfxml_generate_statement(rdf_parser,
element->bag,
RAPTOR_RDF_type_URI(rdf_parser->world),
RAPTOR_RDF_Bag_term(rdf_parser->world),
NULL,
NULL);
} else {
/* bagID forbidden */
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden.");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
}
if(element->parent) {
/* In a rdf:parseType="Collection" the resources are appended
* to the list at the genid element->parent->tail_id
*/
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION ||
element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
/* <idList> rdf:type rdf:List */
const unsigned char * idList;
raptor_uri *predicate_uri;
raptor_term* idList_term;
raptor_term* object_term;
idList = raptor_world_generate_bnodeid(rdf_parser->world);
if(!idList)
goto oom;
/* idList string is saved below in element->parent->tail_id */
idList_term = raptor_new_term_from_blank(rdf_parser->world, idList);
if(!idList_term) {
RAPTOR_FREE(char*, idList);
goto oom;
}
if((element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ||
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST)) {
raptor_uri* class_uri = NULL;
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
class_uri = RAPTOR_DAML_List_URI(rdf_xml_parser);
object_term = raptor_new_term_from_uri(rdf_parser->world,
class_uri);
} else
object_term = raptor_term_copy(RAPTOR_RDF_List_term(rdf_parser->world));
raptor_rdfxml_generate_statement(rdf_parser,
idList_term,
RAPTOR_RDF_type_URI(rdf_parser->world),
object_term,
NULL,
element);
raptor_free_term(object_term);
}
predicate_uri = (element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ? RAPTOR_DAML_first_URI(rdf_xml_parser) : RAPTOR_RDF_first_URI(rdf_parser->world);
/* <idList> rdf:first <element->uri> */
raptor_rdfxml_generate_statement(rdf_parser,
idList_term,
predicate_uri,
element->subject,
NULL,
NULL);
/* If there is no rdf:parseType="Collection" */
if(!element->parent->tail_id) {
/* Free any existing object still around.
* I suspect this can never happen.
*/
if(element->parent->object)
raptor_free_term(element->parent->object);
element->parent->object = raptor_new_term_from_blank(rdf_parser->world,
idList);
} else {
raptor_term* tail_id_term;
tail_id_term = raptor_new_term_from_blank(rdf_parser->world,
element->parent->tail_id);
predicate_uri = (element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ? RAPTOR_DAML_rest_URI(rdf_xml_parser) : RAPTOR_RDF_rest_URI(rdf_parser->world);
/* _:tail_id rdf:rest _:listRest */
raptor_rdfxml_generate_statement(rdf_parser,
tail_id_term,
predicate_uri,
idList_term,
NULL,
NULL);
raptor_free_term(tail_id_term);
}
/* update new tail */
if(element->parent->tail_id)
RAPTOR_FREE(char*, (char*)element->parent->tail_id);
element->parent->tail_id = idList;
raptor_free_term(idList_term);
} else if(element->parent->state != RAPTOR_STATE_UNKNOWN &&
element->state != RAPTOR_STATE_PARSETYPE_RESOURCE) {
/* If there is a parent element (property) containing this
* element (node) and it has no object, set it from this subject
*/
if(element->parent->object) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Tried to set multiple objects of a statement");
} else {
/* Store URI of this node in our parent as the property object */
element->parent->object = raptor_term_copy(element->subject);
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
}
}
/* If this is a node element, generate the rdf:type statement
* from this node
*/
if(state == RAPTOR_STATE_NODE_ELEMENT) {
raptor_term* el_name_term;
el_name_term = raptor_new_term_from_uri(rdf_parser->world,
element_name_uri);
raptor_rdfxml_generate_statement(rdf_parser,
element->subject,
RAPTOR_RDF_type_URI(rdf_parser->world),
el_name_term,
element->reified,
element);
raptor_free_term(el_name_term);
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element, NULL))
goto oom;
/* for both productions now need some more content or
* property elements before can do any more work.
*/
element->child_state = RAPTOR_STATE_PROPERTYELT;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_OTHER:
/* FALLTHROUGH */
case RAPTOR_STATE_PARSETYPE_LITERAL:
raptor_xml_writer_start_element(rdf_xml_parser->xml_writer, xml_element);
element->child_state = RAPTOR_STATE_PARSETYPE_LITERAL;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
finished = 1;
break;
/* Handle all the detail of the various options of property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*
* All the attributes must be scanned here to see what additional
* property element work is needed. No triples are generated
* until the end of this element, until it is clear if the
* element was empty.
*/
case RAPTOR_STATE_MEMBER_PROPERTYELT:
case RAPTOR_STATE_PROPERTYELT:
if(!element_name_uri) {
raptor_parser_error(rdf_parser, "Using property element '%s' without a namespace is forbidden.",
raptor_xml_element_get_name(element->parent->xml_element)->local_name);
raptor_rdfxml_update_document_locator(rdf_parser);
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* Handling rdf:li as a property, noting special processing */
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_li_URI(rdf_parser->world))) {
state = RAPTOR_STATE_MEMBER_PROPERTYELT;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_propertyElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a property element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
/* rdf:ID on a property element - reify a statement.
* Allowed on all property element forms
*/
if(element->rdf_attr[RDF_NS_ID]) {
raptor_uri *reified_uri;
element->reified_id = element->rdf_attr[RDF_NS_ID];
element->rdf_attr[RDF_NS_ID] = NULL;
reified_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
element->reified_id);
if(!reified_uri)
goto oom;
element->reified = raptor_new_term_from_uri(rdf_parser->world,
reified_uri);
raptor_free_uri(reified_uri);
if(!element->reified)
goto oom;
if(!raptor_valid_xml_ID(rdf_parser, element->reified_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:ID value '%s'",
element->reified_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, element->reified_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:ID value '%s'",
element->reified_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
}
/* rdf:datatype on a property element.
* Only allowed for
* http://www.w3.org/TR/rdf-syntax-grammar/#literalPropertyElt
*/
if(element->rdf_attr[RDF_NS_datatype]) {
raptor_uri *datatype_uri;
datatype_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri,
(const unsigned char*)element->rdf_attr[RDF_NS_datatype]);
element->object_literal_datatype = datatype_uri;
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_datatype]);
element->rdf_attr[RDF_NS_datatype] = NULL;
if(!element->object_literal_datatype)
goto oom;
}
if(element->rdf_attr[RDF_NS_bagID]) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
if(element->rdf_attr[RDF_NS_resource] ||
element->rdf_attr[RDF_NS_parseType]) {
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden on property element '%s' with an rdf:resource or rdf:parseType attribute.", el_name);
/* prevent this being used later either */
element->rdf_attr[RDF_NS_bagID] = NULL;
} else {
unsigned char* bag_id;
raptor_uri* bag_uri;
bag_id = (unsigned char*)element->rdf_attr[RDF_NS_bagID];
element->rdf_attr[RDF_NS_bagID] = NULL;
bag_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
bag_id);
if(!bag_uri) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
element->bag = raptor_new_term_from_uri(rdf_parser->world,
bag_uri);
raptor_free_uri(bag_uri);
if(!element->bag) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
if(!raptor_valid_xml_ID(rdf_parser, bag_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, bag_id)) {
raptor_parser_error(rdf_parser,
"Duplicated rdf:bagID value '%s'", bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
RAPTOR_FREE(char*, bag_id);
finished = 1;
break;
}
RAPTOR_FREE(char*, bag_id);
raptor_parser_warning(rdf_parser, "rdf:bagID is deprecated.");
}
} else {
/* bagID forbidden */
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden.");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
} /* if rdf:bagID on property element */
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT;
if(element->rdf_attr[RDF_NS_parseType]) {
const unsigned char *parse_type;
int i;
int is_parseType_Literal = 0;
parse_type = element->rdf_attr[RDF_NS_parseType];
if(raptor_rdfxml_element_has_property_attributes(element)) {
raptor_parser_error(rdf_parser, "Property attributes cannot be used with rdf:parseType='%s'", parse_type);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* Check for bad combinations of things with parseType */
for(i = 0; i <= RDF_NS_LAST; i++)
if(element->rdf_attr[i] && i != RDF_NS_parseType) {
raptor_parser_error(rdf_parser, "Attribute '%s' cannot be used with rdf:parseType='%s'", raptor_rdf_ns_terms_info[i].name, parse_type);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(!strcmp((char*)parse_type, "Literal"))
is_parseType_Literal = 1;
else if(!strcmp((char*)parse_type, "Resource")) {
unsigned char* subject_id;
state = RAPTOR_STATE_PARSETYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PROPERTYELT;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
/* create a node for the subject of the contained properties */
subject_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!element->subject)
goto oom;
} else if(!strcmp((char*)parse_type, "Collection")) {
/* An rdf:parseType="Collection" appears as a single node */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PARSETYPE_COLLECTION;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION;
} else {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES) &&
!raptor_strcasecmp((char*)parse_type, "daml:collection")) {
/* A DAML collection appears as a single node */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PARSETYPE_COLLECTION;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION;
} else {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_WARN_OTHER_PARSETYPES)) {
raptor_parser_warning(rdf_parser, "Unknown rdf:parseType value '%s' taken as 'Literal'", parse_type);
}
is_parseType_Literal = 1;
}
}
if(is_parseType_Literal) {
raptor_xml_writer* xml_writer;
/* rdf:parseType="Literal" - explicitly or default
* if the parseType value is not recognised
*/
rdf_xml_parser->xml_content = NULL;
rdf_xml_parser->xml_content_length = 0;
rdf_xml_parser->iostream =
raptor_new_iostream_to_string(rdf_parser->world,
&rdf_xml_parser->xml_content,
&rdf_xml_parser->xml_content_length,
raptor_alloc_memory);
if(!rdf_xml_parser->iostream)
goto oom;
xml_writer = raptor_new_xml_writer(rdf_parser->world, NULL,
rdf_xml_parser->iostream);
rdf_xml_parser->xml_writer = xml_writer;
if(!rdf_xml_parser->xml_writer)
goto oom;
raptor_xml_writer_set_option(rdf_xml_parser->xml_writer,
RAPTOR_OPTION_WRITER_XML_DECLARATION,
NULL, 0);
element->child_state = RAPTOR_STATE_PARSETYPE_LITERAL;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
}
} else {
/* Can only be the empty property element case
* http://www.w3.org/TR/rdf-syntax-grammar/#emptyPropertyElt
*/
/* The presence of the rdf:resource or rdf:nodeID
* attributes is checked at element close time
*/
/*
* Assign reified URI here so we don't reify property attributes
* using this id
*/
if(element->reified_id && !element->reified) {
raptor_uri* reified_uri;
reified_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
element->reified_id);
if(!reified_uri)
goto oom;
element->reified = raptor_new_term_from_uri(rdf_parser->world,
reified_uri);
raptor_free_uri(reified_uri);
if(!element->reified)
goto oom;
}
if(element->rdf_attr[RDF_NS_resource] ||
element->rdf_attr[RDF_NS_nodeID]) {
/* Done - wait for end of this element to end in order to
* check the element was empty as expected */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
} else {
/* Otherwise process content in obj (value) state */
element->child_state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT;
}
}
finished = 1;
break;
case RAPTOR_STATE_INVALID:
default:
raptor_parser_fatal_error(rdf_parser,
"%s Internal error - unexpected parser state %d - %s",
__func__,
state, raptor_rdfxml_state_as_string(state));
finished = 1;
} /* end switch */
if(state != element->state) {
element->state = state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Moved to state %d - %s\n", state,
raptor_rdfxml_state_as_string(state));
#endif
}
} /* end while */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
return;
oom:
raptor_parser_fatal_error(rdf_parser, "Out of memory, skipping");
element->state = RAPTOR_STATE_SKIPPING;
}
static void
raptor_rdfxml_end_element_grammar(raptor_parser *rdf_parser,
raptor_rdfxml_element *element)
{
raptor_rdfxml_parser *rdf_xml_parser;
raptor_state state;
int finished;
raptor_xml_element* xml_element = element->xml_element;
raptor_qname* el_qname;
const unsigned char *el_name;
int element_in_rdf_ns;
raptor_uri* element_name_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
el_qname = raptor_xml_element_get_name(xml_element);
el_name = el_qname->local_name;
element_in_rdf_ns= (el_qname->nspace && el_qname->nspace->is_rdf_ms);
element_name_uri = el_qname->uri;
state = element->state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Starting in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
finished= 0;
while(!finished) {
switch(state) {
case RAPTOR_STATE_SKIPPING:
finished = 1;
break;
case RAPTOR_STATE_UNKNOWN:
finished = 1;
break;
case RAPTOR_STATE_NODE_ELEMENT_LIST:
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_RDF_URI(rdf_parser->world))) {
/* end of RDF - boo hoo */
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
}
/* When scanning, another element ending is outside the RDF
* world so this can happen without further work
*/
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING)) {
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
}
/* otherwise found some junk after RDF content in an RDF-only
* document (probably never get here since this would be
* a mismatched XML tag and cause an error earlier)
*/
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_warning(rdf_parser,
"Element '%s' ended, expected end of RDF element",
el_name);
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
case RAPTOR_STATE_DESCRIPTION:
case RAPTOR_STATE_NODE_ELEMENT:
case RAPTOR_STATE_PARSETYPE_RESOURCE:
/* If there is a parent element containing this element and
* the parent isn't a description, has an identifier,
* create the statement between this node using parent property
* (Need to check for identifier so that top-level typed nodes
* don't get connect to <rdf:RDF> parent element)
*/
if(state == RAPTOR_STATE_NODE_ELEMENT &&
element->parent && element->parent->subject) {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
element->subject,
NULL,
element);
} else if(state == RAPTOR_STATE_PARSETYPE_RESOURCE &&
element->parent && element->parent->subject) {
/* Handle rdf:li as the rdf:parseType="resource" property */
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_li_URI(rdf_parser->world))) {
raptor_uri* ordinal_predicate_uri;
element->parent->last_ordinal++;
ordinal_predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world, element->parent->last_ordinal);
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
ordinal_predicate_uri,
element->subject,
element->reified,
element->parent);
raptor_free_uri(ordinal_predicate_uri);
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
element->subject,
element->reified,
element->parent);
}
}
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_COLLECTION:
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_OTHER:
/* FALLTHROUGH */
case RAPTOR_STATE_PARSETYPE_LITERAL:
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
raptor_xml_writer_end_element(rdf_xml_parser->xml_writer, xml_element);
finished = 1;
break;
case RAPTOR_STATE_PROPERTYELT:
case RAPTOR_STATE_MEMBER_PROPERTYELT:
/* A property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*
* Literal content part is handled here.
* The element content is handled in the internal states
* Empty content is checked here.
*/
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT) {
if(xml_element->content_cdata_seen)
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
else if(xml_element->content_element_seen)
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
else {
/* Empty Literal */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
}
}
/* Handle terminating a rdf:parseType="Collection" list */
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION ||
element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_term* nil_term;
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_uri* nil_uri = RAPTOR_DAML_nil_URI(rdf_xml_parser);
nil_term = raptor_new_term_from_uri(rdf_parser->world, nil_uri);
} else {
nil_term = raptor_term_copy(RAPTOR_RDF_nil_term(rdf_parser->world));
}
if(!element->tail_id) {
/* If No List: set object of statement to rdf:nil */
element->object = raptor_term_copy(nil_term);
} else {
raptor_uri* rest_uri = NULL;
raptor_term* tail_id_term;
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION)
rest_uri = RAPTOR_DAML_rest_URI(rdf_xml_parser);
else
rest_uri = RAPTOR_RDF_rest_URI(rdf_parser->world);
tail_id_term = raptor_new_term_from_blank(rdf_parser->world,
element->tail_id);
/* terminate the list */
raptor_rdfxml_generate_statement(rdf_parser,
tail_id_term,
rest_uri,
nil_term,
NULL,
NULL);
raptor_free_term(tail_id_term);
}
raptor_free_term(nil_term);
} /* end rdf:parseType="Collection" termination */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
switch(element->content_type) {
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE:
if(raptor_rdfxml_element_has_property_attributes(element) &&
element->child_state == RAPTOR_STATE_DESCRIPTION) {
raptor_parser_error(rdf_parser,
"Property element '%s' has both property attributes and a node element content",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(!element->object) {
if(element->rdf_attr[RDF_NS_resource]) {
raptor_uri* resource_uri;
resource_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
raptor_rdfxml_inscope_base_uri(rdf_parser),
(const unsigned char*)element->rdf_attr[RDF_NS_resource]);
if(!resource_uri)
goto oom;
element->object = raptor_new_term_from_uri(rdf_parser->world,
resource_uri);
raptor_free_uri(resource_uri);
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_resource]);
element->rdf_attr[RDF_NS_resource] = NULL;
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
} else if(element->rdf_attr[RDF_NS_nodeID]) {
unsigned char* resource_id;
resource_id = raptor_world_internal_generate_id(rdf_parser->world,
(unsigned char*)element->rdf_attr[RDF_NS_nodeID]);
if(!resource_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
resource_id);
RAPTOR_FREE(char*, resource_id);
element->rdf_attr[RDF_NS_nodeID] = NULL;
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
if(!raptor_valid_xml_ID(rdf_parser,
element->object->value.blank.string)) {
raptor_parser_error(rdf_parser, "Illegal rdf:nodeID value '%s'", (const char*)element->object->value.blank.string);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
} else {
unsigned char* resource_id;
resource_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!resource_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
resource_id);
RAPTOR_FREE(char*, resource_id);
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element->parent,
element->object))
goto oom;
}
/* We know object is a resource, so delete any unsignficant
* whitespace so that FALLTHROUGH code below finds the object.
*/
if(xml_element->content_cdata_length) {
raptor_free_stringbuffer(xml_element->content_cdata_sb);
xml_element->content_cdata_sb = NULL;
xml_element->content_cdata_length = 0;
}
/* FALLTHROUGH */
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL:
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
/* Only an empty literal can have a rdf:bagID */
if(element->bag) {
if(xml_element->content_cdata_length > 0) {
raptor_parser_error(rdf_parser,
"rdf:bagID is forbidden on a literal property element '%s'.",
el_name);
/* prevent this being used later either */
element->rdf_attr[RDF_NS_bagID] = NULL;
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->bag,
RAPTOR_RDF_type_URI(rdf_parser->world),
RAPTOR_RDF_Bag_term(rdf_parser->world),
NULL,
NULL);
}
}
} /* if rdf:bagID */
/* If there is empty literal content with properties
* generate a node to hang properties off
*/
if(raptor_rdfxml_element_has_property_attributes(element) &&
xml_element->content_cdata_length > 0) {
raptor_parser_error(rdf_parser,
"Literal property element '%s' has property attributes",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL &&
raptor_rdfxml_element_has_property_attributes(element) &&
!element->object) {
unsigned char* object_id;
object_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!object_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
object_id);
RAPTOR_FREE(char*, object_id);
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element,
element->object))
goto oom;
}
/* just be friendly to older compilers and don't declare
* variables in the middle of a block
*/
if(1) {
raptor_uri *predicate_uri = NULL;
int predicate_ordinal = -1;
raptor_term* object_term = NULL;
if(state == RAPTOR_STATE_MEMBER_PROPERTYELT) {
predicate_ordinal = ++element->parent->last_ordinal;
predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world,
predicate_ordinal);
} else {
predicate_uri = element_name_uri;
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL) {
unsigned char* literal = NULL;
raptor_uri* literal_datatype;
unsigned char* literal_language = NULL;
/* an empty stringbuffer - empty CDATA - is OK */
if(raptor_stringbuffer_length(xml_element->content_cdata_sb)) {
literal = raptor_stringbuffer_as_string(xml_element->content_cdata_sb);
if(!literal)
goto oom;
}
literal_datatype = element->object_literal_datatype;
if(!literal_datatype)
literal_language = (unsigned char*)raptor_sax2_inscope_xml_language(rdf_xml_parser->sax2);
if(!literal_datatype && literal &&
!raptor_unicode_check_utf8_nfc_string(literal,
xml_element->content_cdata_length,
NULL)) {
const char *message;
message = "Property element '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, el_name, literal);
else
raptor_parser_warning(rdf_parser, message, el_name, literal);
}
object_term = raptor_new_term_from_literal(rdf_parser->world,
literal,
literal_datatype,
literal_language);
} else {
object_term = raptor_term_copy(element->object);
}
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
predicate_uri,
object_term,
element->reified,
element->parent);
if(predicate_ordinal >= 0)
raptor_free_uri(predicate_uri);
raptor_free_term(object_term);
}
break;
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL:
{
unsigned char *buffer;
size_t length;
raptor_term* xmlliteral_term = NULL;
if(rdf_xml_parser->xml_writer) {
raptor_xml_writer_flush(rdf_xml_parser->xml_writer);
raptor_free_iostream(rdf_xml_parser->iostream);
rdf_xml_parser->iostream = NULL;
buffer = (unsigned char*)rdf_xml_parser->xml_content;
length = rdf_xml_parser->xml_content_length;
} else {
buffer = raptor_stringbuffer_as_string(xml_element->content_cdata_sb);
length = xml_element->content_cdata_length;
}
if(!raptor_unicode_check_utf8_nfc_string(buffer, length, NULL)) {
const char *message;
message = "Property element '%s' has XML literal content not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, el_name, buffer);
else
raptor_parser_warning(rdf_parser, message, el_name, buffer);
}
xmlliteral_term = raptor_new_term_from_literal(rdf_parser->world,
buffer,
RAPTOR_RDF_XMLLiteral_URI(rdf_parser->world),
NULL);
if(state == RAPTOR_STATE_MEMBER_PROPERTYELT) {
raptor_uri* predicate_uri;
element->parent->last_ordinal++;
predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world, element->parent->last_ordinal);
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
predicate_uri,
xmlliteral_term,
element->reified,
element->parent);
raptor_free_uri(predicate_uri);
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
xmlliteral_term,
element->reified,
element->parent);
}
raptor_free_term(xmlliteral_term);
/* Finish the xml writer iostream for parseType="Literal" */
if(rdf_xml_parser->xml_writer) {
raptor_free_xml_writer(rdf_xml_parser->xml_writer);
RAPTOR_FREE(char*, rdf_xml_parser->xml_content);
rdf_xml_parser->xml_content = NULL;
rdf_xml_parser->xml_content_length = 0;
}
}
break;
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST:
default:
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error in state RAPTOR_STATE_PROPERTYELT - got unexpected content type %s (%d)",
__func__,
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
} /* end switch */
finished = 1;
break;
case RAPTOR_STATE_INVALID:
default:
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error - unexpected parser state %d - %s",
__func__,
state,
raptor_rdfxml_state_as_string(state));
finished = 1;
} /* end switch */
if(state != element->state) {
element->state = state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Moved to state %d - %s\n", state,
raptor_rdfxml_state_as_string(state));
#endif
}
} /* end while */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
return;
oom:
raptor_parser_fatal_error(rdf_parser, "Out of memory, skipping");
element->state = RAPTOR_STATE_SKIPPING;
}
static void
raptor_rdfxml_cdata_grammar(raptor_parser *rdf_parser,
const unsigned char *s, int len,
int is_cdata)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
raptor_xml_element* xml_element;
raptor_state state;
int all_whitespace = 1;
int i;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return;
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG2("Adding characters (is_cdata=%d): '", is_cdata);
(void)fwrite(s, 1, len, stderr);
fprintf(stderr, "' (%d bytes)\n", len);
#endif
for(i = 0; i < len; i++)
if(!isspace(s[i])) {
all_whitespace = 0;
break;
}
element = rdf_xml_parser->current_element;
/* this file is very broke - probably not XML, whatever */
if(!element)
return;
xml_element = element->xml_element;
raptor_rdfxml_update_document_locator(rdf_parser);
/* cdata never changes the parser state
* and the containing element state always determines what to do.
* Use the child_state first if there is one, since that applies
*/
state = element->child_state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Working in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
if(state == RAPTOR_STATE_SKIPPING)
return;
if(state == RAPTOR_STATE_UNKNOWN) {
/* Ignore all cdata if still looking for RDF */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING))
return;
/* Ignore all whitespace cdata before first element */
if(all_whitespace)
return;
/* This probably will never happen since that would make the
* XML not be well-formed
*/
raptor_parser_warning(rdf_parser, "Character data before RDF element.");
}
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES) {
/* If found non-whitespace content, move to literal content */
if(!all_whitespace)
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
}
if(!rdf_content_type_info[element->child_content_type].whitespace_significant) {
/* Whitespace is ignored except for literal or preserved content types */
if(all_whitespace) {
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG2("Ignoring whitespace cdata inside element '%s'\n",
raptor_xml_element_get_name(element->parent->xml_element)->local_name);
#endif
return;
}
if(xml_element->content_cdata_seen && xml_element->content_element_seen) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* Uh oh - mixed content, this element has elements too */
raptor_parser_warning(rdf_parser, "element '%s' has mixed content.",
parent_el_name->local_name);
}
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT) {
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type changed to %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
}
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL)
raptor_xml_writer_cdata_counted(rdf_xml_parser->xml_writer, s, len);
else {
raptor_stringbuffer_append_counted_string(xml_element->content_cdata_sb,
s, len, 1);
element->content_cdata_all_whitespace &= all_whitespace;
/* adjust stored length */
xml_element->content_cdata_length += len;
}
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG3("Content cdata now: %d bytes\n",
xml_element->content_cdata_length);
#endif
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
}
/**
* raptor_rdfxml_inscope_base_uri:
* @rdf_parser: Raptor parser object
*
* Return the in-scope base URI.
*
* Looks for the innermost xml:base on an element or document URI
*
* Return value: The URI string value or NULL on failure.
**/
static raptor_uri*
raptor_rdfxml_inscope_base_uri(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_uri* base_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
base_uri = raptor_sax2_inscope_base_uri(rdf_xml_parser->sax2);
if(!base_uri)
base_uri = rdf_parser->base_uri;
return base_uri;
}
/**
* raptor_rdfxml_record_ID:
* @rdf_parser: Raptor parser object
* @element: Current element
* @id: ID string
*
* Record an rdf:ID / rdf:bagID value (with xml base) and check it hasn't been seen already.
*
* Record and check the ID values, if they have been seen already.
* per in-scope-base URI.
*
* Return value: non-zero if already seen, or failure
**/
static int
raptor_rdfxml_record_ID(raptor_parser *rdf_parser,
raptor_rdfxml_element *element,
const unsigned char *id)
{
raptor_rdfxml_parser *rdf_xml_parser;
raptor_uri* base_uri;
size_t id_len;
int rc;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(!RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID))
return 0;
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
id_len = strlen((const char*)id);
rc = raptor_id_set_add(rdf_xml_parser->id_set, base_uri, id, id_len);
return (rc != 0);
}
static void
raptor_rdfxml_update_document_locator(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser *rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
raptor_sax2_update_document_locator(rdf_xml_parser->sax2,
&rdf_parser->locator);
}
static void
raptor_rdfxml_parse_finish_factory(raptor_parser_factory* factory)
{
}
static const char* const rdfxml_names[3] = { "rdfxml", "raptor", NULL};
static const char* const rdfxml_uri_strings[3] = {
"http://www.w3.org/ns/formats/RDF_XML",
"http://www.w3.org/TR/rdf-syntax-grammar",
NULL
};
#define RDFXML_TYPES_COUNT 2
static const raptor_type_q rdfxml_types[RDFXML_TYPES_COUNT + 1] = {
{ "application/rdf+xml", 19, 10},
{ "text/rdf", 8, 6},
{ NULL, 0, 0}
};
static int
raptor_rdfxml_parser_register_factory(raptor_parser_factory *factory)
{
int rc = 0;
factory->desc.names = rdfxml_names;
factory->desc.mime_types = rdfxml_types;
factory->desc.label = "RDF/XML";
factory->desc.uri_strings = rdfxml_uri_strings;
factory->desc.flags = RAPTOR_SYNTAX_NEED_BASE_URI;
factory->context_length = sizeof(raptor_rdfxml_parser);
factory->init = raptor_rdfxml_parse_init;
factory->terminate = raptor_rdfxml_parse_terminate;
factory->start = raptor_rdfxml_parse_start;
factory->chunk = raptor_rdfxml_parse_chunk;
factory->finish_factory = raptor_rdfxml_parse_finish_factory;
factory->recognise_syntax = raptor_rdfxml_parse_recognise_syntax;
return rc;
}
int
raptor_init_parser_rdfxml(raptor_world* world)
{
return !raptor_world_register_parser_factory(world,
&raptor_rdfxml_parser_register_factory);
}
#if defined(RAPTOR_DEBUG) && RAPTOR_DEBUG > 1
void
raptor_rdfxml_parser_stats_print(raptor_rdfxml_parser* rdf_xml_parser,
FILE *stream)
{
fputs("rdf:ID set ", stream);
raptor_id_set_stats_print(rdf_xml_parser->id_set, stream);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3568_8 |
crossvul-cpp_data_bad_5678_1 | /*
* algif_skcipher: User-space interface for skcipher algorithms
*
* This file provides the user-space API for symmetric key ciphers.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/scatterwalk.h>
#include <crypto/skcipher.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct skcipher_sg_list {
struct list_head list;
int cur;
struct scatterlist sg[0];
};
struct skcipher_ctx {
struct list_head tsgl;
struct af_alg_sgl rsgl;
void *iv;
struct af_alg_completion completion;
unsigned used;
unsigned int len;
bool more;
bool merge;
bool enc;
struct ablkcipher_request req;
};
#define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \
sizeof(struct scatterlist) - 1)
static inline int skcipher_sndbuf(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
ctx->used, 0);
}
static inline bool skcipher_writable(struct sock *sk)
{
return PAGE_SIZE <= skcipher_sndbuf(sk);
}
static int skcipher_alloc_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg = NULL;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
if (!list_empty(&ctx->tsgl))
sg = sgl->sg;
if (!sg || sgl->cur >= MAX_SGL_ENTS) {
sgl = sock_kmalloc(sk, sizeof(*sgl) +
sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1),
GFP_KERNEL);
if (!sgl)
return -ENOMEM;
sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
sgl->cur = 0;
if (sg)
scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
list_add_tail(&sgl->list, &ctx->tsgl);
}
return 0;
}
static void skcipher_pull_sgl(struct sock *sk, int used)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
int i;
while (!list_empty(&ctx->tsgl)) {
sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list,
list);
sg = sgl->sg;
for (i = 0; i < sgl->cur; i++) {
int plen = min_t(int, used, sg[i].length);
if (!sg_page(sg + i))
continue;
sg[i].length -= plen;
sg[i].offset += plen;
used -= plen;
ctx->used -= plen;
if (sg[i].length)
return;
put_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
}
list_del(&sgl->list);
sock_kfree_s(sk, sgl,
sizeof(*sgl) + sizeof(sgl->sg[0]) *
(MAX_SGL_ENTS + 1));
}
if (!ctx->used)
ctx->merge = 0;
}
static void skcipher_free_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
skcipher_pull_sgl(sk, ctx->used);
}
static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags)
{
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT)
return -EAGAIN;
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void skcipher_wmem_wakeup(struct sock *sk)
{
struct socket_wq *wq;
if (!skcipher_writable(sk))
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static int skcipher_wait_for_data(struct sock *sk, unsigned flags)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT) {
return -EAGAIN;
}
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, ctx->used)) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
return err;
}
static void skcipher_data_wakeup(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct socket_wq *wq;
if (!ctx->used)
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
rcu_read_unlock();
}
static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t size)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
unsigned ivsize = crypto_ablkcipher_ivsize(tfm);
struct skcipher_sg_list *sgl;
struct af_alg_control con = {};
long copied = 0;
bool enc = 0;
int err;
int i;
if (msg->msg_controllen) {
err = af_alg_cmsg_send(msg, &con);
if (err)
return err;
switch (con.op) {
case ALG_OP_ENCRYPT:
enc = 1;
break;
case ALG_OP_DECRYPT:
enc = 0;
break;
default:
return -EINVAL;
}
if (con.iv && con.iv->ivlen != ivsize)
return -EINVAL;
}
err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!ctx->used) {
ctx->enc = enc;
if (con.iv)
memcpy(ctx->iv, con.iv->iv, ivsize);
}
while (size) {
struct scatterlist *sg;
unsigned long len = size;
int plen;
if (ctx->merge) {
sgl = list_entry(ctx->tsgl.prev,
struct skcipher_sg_list, list);
sg = sgl->sg + sgl->cur - 1;
len = min_t(unsigned long, len,
PAGE_SIZE - sg->offset - sg->length);
err = memcpy_fromiovec(page_address(sg_page(sg)) +
sg->offset + sg->length,
msg->msg_iov, len);
if (err)
goto unlock;
sg->length += len;
ctx->merge = (sg->offset + sg->length) &
(PAGE_SIZE - 1);
ctx->used += len;
copied += len;
size -= len;
continue;
}
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, msg->msg_flags);
if (err)
goto unlock;
}
len = min_t(unsigned long, len, skcipher_sndbuf(sk));
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
sg = sgl->sg;
do {
i = sgl->cur;
plen = min_t(int, len, PAGE_SIZE);
sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
err = -ENOMEM;
if (!sg_page(sg + i))
goto unlock;
err = memcpy_fromiovec(page_address(sg_page(sg + i)),
msg->msg_iov, plen);
if (err) {
__free_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
goto unlock;
}
sg[i].length = plen;
len -= plen;
ctx->used += plen;
copied += plen;
size -= plen;
sgl->cur++;
} while (len && sgl->cur < MAX_SGL_ENTS);
ctx->merge = plen & (PAGE_SIZE - 1);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static ssize_t skcipher_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
int err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!size)
goto done;
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, flags);
if (err)
goto unlock;
}
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
ctx->merge = 0;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
get_page(page);
sg_set_page(sgl->sg + sgl->cur, page, size, offset);
sgl->cur++;
ctx->used += size;
done:
ctx->more = flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return err ?: size;
}
static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static unsigned int skcipher_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
if (ctx->used)
mask |= POLLIN | POLLRDNORM;
if (skcipher_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static struct proto_ops algif_skcipher_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.accept = sock_no_accept,
.setsockopt = sock_no_setsockopt,
.release = af_alg_release,
.sendmsg = skcipher_sendmsg,
.sendpage = skcipher_sendpage,
.recvmsg = skcipher_recvmsg,
.poll = skcipher_poll,
};
static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ablkcipher(name, type, mask);
}
static void skcipher_release(void *private)
{
crypto_free_ablkcipher(private);
}
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ablkcipher_setkey(private, key, keylen);
}
static void skcipher_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
skcipher_free_sgl(sk);
sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ablkcipher_request_set_tfm(&ctx->req, private);
ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_skcipher = {
.bind = skcipher_bind,
.release = skcipher_release,
.setkey = skcipher_setkey,
.accept = skcipher_accept_parent,
.ops = &algif_skcipher_ops,
.name = "skcipher",
.owner = THIS_MODULE
};
static int __init algif_skcipher_init(void)
{
return af_alg_register_type(&algif_type_skcipher);
}
static void __exit algif_skcipher_exit(void)
{
int err = af_alg_unregister_type(&algif_type_skcipher);
BUG_ON(err);
}
module_init(algif_skcipher_init);
module_exit(algif_skcipher_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_5678_1 |
crossvul-cpp_data_bad_2559_0 | /******************************************************************************
*
* Back-end of the driver for virtual block devices. This portion of the
* driver exports a 'unified' block-device interface that can be accessed
* by any operating system that implements a compatible front end. A
* reference front-end implementation can be found in:
* drivers/block/xen-blkfront.c
*
* Copyright (c) 2003-2004, Keir Fraser & Steve Hand
* Copyright (c) 2005, Christopher Clark
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#define pr_fmt(fmt) "xen-blkback: " fmt
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <linux/bitmap.h>
#include <xen/events.h>
#include <xen/page.h>
#include <xen/xen.h>
#include <asm/xen/hypervisor.h>
#include <asm/xen/hypercall.h>
#include <xen/balloon.h>
#include <xen/grant_table.h>
#include "common.h"
/*
* Maximum number of unused free pages to keep in the internal buffer.
* Setting this to a value too low will reduce memory used in each backend,
* but can have a performance penalty.
*
* A sane value is xen_blkif_reqs * BLKIF_MAX_SEGMENTS_PER_REQUEST, but can
* be set to a lower value that might degrade performance on some intensive
* IO workloads.
*/
static int xen_blkif_max_buffer_pages = 1024;
module_param_named(max_buffer_pages, xen_blkif_max_buffer_pages, int, 0644);
MODULE_PARM_DESC(max_buffer_pages,
"Maximum number of free pages to keep in each block backend buffer");
/*
* Maximum number of grants to map persistently in blkback. For maximum
* performance this should be the total numbers of grants that can be used
* to fill the ring, but since this might become too high, specially with
* the use of indirect descriptors, we set it to a value that provides good
* performance without using too much memory.
*
* When the list of persistent grants is full we clean it up using a LRU
* algorithm.
*/
static int xen_blkif_max_pgrants = 1056;
module_param_named(max_persistent_grants, xen_blkif_max_pgrants, int, 0644);
MODULE_PARM_DESC(max_persistent_grants,
"Maximum number of grants to map persistently");
/*
* Maximum number of rings/queues blkback supports, allow as many queues as there
* are CPUs if user has not specified a value.
*/
unsigned int xenblk_max_queues;
module_param_named(max_queues, xenblk_max_queues, uint, 0644);
MODULE_PARM_DESC(max_queues,
"Maximum number of hardware queues per virtual disk." \
"By default it is the number of online CPUs.");
/*
* Maximum order of pages to be used for the shared ring between front and
* backend, 4KB page granularity is used.
*/
unsigned int xen_blkif_max_ring_order = XENBUS_MAX_RING_GRANT_ORDER;
module_param_named(max_ring_page_order, xen_blkif_max_ring_order, int, S_IRUGO);
MODULE_PARM_DESC(max_ring_page_order, "Maximum order of pages to be used for the shared ring");
/*
* The LRU mechanism to clean the lists of persistent grants needs to
* be executed periodically. The time interval between consecutive executions
* of the purge mechanism is set in ms.
*/
#define LRU_INTERVAL 100
/*
* When the persistent grants list is full we will remove unused grants
* from the list. The percent number of grants to be removed at each LRU
* execution.
*/
#define LRU_PERCENT_CLEAN 5
/* Run-time switchable: /sys/module/blkback/parameters/ */
static unsigned int log_stats;
module_param(log_stats, int, 0644);
#define BLKBACK_INVALID_HANDLE (~0)
/* Number of free pages to remove on each call to gnttab_free_pages */
#define NUM_BATCH_FREE_PAGES 10
static inline int get_free_page(struct xen_blkif_ring *ring, struct page **page)
{
unsigned long flags;
spin_lock_irqsave(&ring->free_pages_lock, flags);
if (list_empty(&ring->free_pages)) {
BUG_ON(ring->free_pages_num != 0);
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
return gnttab_alloc_pages(1, page);
}
BUG_ON(ring->free_pages_num == 0);
page[0] = list_first_entry(&ring->free_pages, struct page, lru);
list_del(&page[0]->lru);
ring->free_pages_num--;
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
return 0;
}
static inline void put_free_pages(struct xen_blkif_ring *ring, struct page **page,
int num)
{
unsigned long flags;
int i;
spin_lock_irqsave(&ring->free_pages_lock, flags);
for (i = 0; i < num; i++)
list_add(&page[i]->lru, &ring->free_pages);
ring->free_pages_num += num;
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
}
static inline void shrink_free_pagepool(struct xen_blkif_ring *ring, int num)
{
/* Remove requested pages in batches of NUM_BATCH_FREE_PAGES */
struct page *page[NUM_BATCH_FREE_PAGES];
unsigned int num_pages = 0;
unsigned long flags;
spin_lock_irqsave(&ring->free_pages_lock, flags);
while (ring->free_pages_num > num) {
BUG_ON(list_empty(&ring->free_pages));
page[num_pages] = list_first_entry(&ring->free_pages,
struct page, lru);
list_del(&page[num_pages]->lru);
ring->free_pages_num--;
if (++num_pages == NUM_BATCH_FREE_PAGES) {
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
gnttab_free_pages(num_pages, page);
spin_lock_irqsave(&ring->free_pages_lock, flags);
num_pages = 0;
}
}
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
if (num_pages != 0)
gnttab_free_pages(num_pages, page);
}
#define vaddr(page) ((unsigned long)pfn_to_kaddr(page_to_pfn(page)))
static int do_block_io_op(struct xen_blkif_ring *ring);
static int dispatch_rw_block_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req);
static void make_response(struct xen_blkif_ring *ring, u64 id,
unsigned short op, int st);
#define foreach_grant_safe(pos, n, rbtree, node) \
for ((pos) = container_of(rb_first((rbtree)), typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL; \
&(pos)->node != NULL; \
(pos) = container_of(n, typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL)
/*
* We don't need locking around the persistent grant helpers
* because blkback uses a single-thread for each backend, so we
* can be sure that this functions will never be called recursively.
*
* The only exception to that is put_persistent_grant, that can be called
* from interrupt context (by xen_blkbk_unmap), so we have to use atomic
* bit operations to modify the flags of a persistent grant and to count
* the number of used grants.
*/
static int add_persistent_gnt(struct xen_blkif_ring *ring,
struct persistent_gnt *persistent_gnt)
{
struct rb_node **new = NULL, *parent = NULL;
struct persistent_gnt *this;
struct xen_blkif *blkif = ring->blkif;
if (ring->persistent_gnt_c >= xen_blkif_max_pgrants) {
if (!blkif->vbd.overflow_max_grants)
blkif->vbd.overflow_max_grants = 1;
return -EBUSY;
}
/* Figure out where to put new node */
new = &ring->persistent_gnts.rb_node;
while (*new) {
this = container_of(*new, struct persistent_gnt, node);
parent = *new;
if (persistent_gnt->gnt < this->gnt)
new = &((*new)->rb_left);
else if (persistent_gnt->gnt > this->gnt)
new = &((*new)->rb_right);
else {
pr_alert_ratelimited("trying to add a gref that's already in the tree\n");
return -EINVAL;
}
}
bitmap_zero(persistent_gnt->flags, PERSISTENT_GNT_FLAGS_SIZE);
set_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
/* Add new node and rebalance tree. */
rb_link_node(&(persistent_gnt->node), parent, new);
rb_insert_color(&(persistent_gnt->node), &ring->persistent_gnts);
ring->persistent_gnt_c++;
atomic_inc(&ring->persistent_gnt_in_use);
return 0;
}
static struct persistent_gnt *get_persistent_gnt(struct xen_blkif_ring *ring,
grant_ref_t gref)
{
struct persistent_gnt *data;
struct rb_node *node = NULL;
node = ring->persistent_gnts.rb_node;
while (node) {
data = container_of(node, struct persistent_gnt, node);
if (gref < data->gnt)
node = node->rb_left;
else if (gref > data->gnt)
node = node->rb_right;
else {
if(test_bit(PERSISTENT_GNT_ACTIVE, data->flags)) {
pr_alert_ratelimited("requesting a grant already in use\n");
return NULL;
}
set_bit(PERSISTENT_GNT_ACTIVE, data->flags);
atomic_inc(&ring->persistent_gnt_in_use);
return data;
}
}
return NULL;
}
static void put_persistent_gnt(struct xen_blkif_ring *ring,
struct persistent_gnt *persistent_gnt)
{
if(!test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
pr_alert_ratelimited("freeing a grant already unused\n");
set_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
clear_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
atomic_dec(&ring->persistent_gnt_in_use);
}
static void free_persistent_gnts(struct xen_blkif_ring *ring, struct rb_root *root,
unsigned int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
int segs_to_unmap = 0;
struct gntab_unmap_queue_data unmap_data;
unmap_data.pages = pages;
unmap_data.unmap_ops = unmap;
unmap_data.kunmap_ops = NULL;
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
(unsigned long) pfn_to_kaddr(page_to_pfn(
persistent_gnt->page)),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST ||
!rb_next(&persistent_gnt->node)) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
segs_to_unmap = 0;
}
rb_erase(&persistent_gnt->node, root);
kfree(persistent_gnt);
num--;
}
BUG_ON(num != 0);
}
void xen_blkbk_unmap_purged_grants(struct work_struct *work)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
int segs_to_unmap = 0;
struct xen_blkif_ring *ring = container_of(work, typeof(*ring), persistent_purge_work);
struct gntab_unmap_queue_data unmap_data;
unmap_data.pages = pages;
unmap_data.unmap_ops = unmap;
unmap_data.kunmap_ops = NULL;
while(!list_empty(&ring->persistent_purge_list)) {
persistent_gnt = list_first_entry(&ring->persistent_purge_list,
struct persistent_gnt,
remove_node);
list_del(&persistent_gnt->remove_node);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
vaddr(persistent_gnt->page),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
segs_to_unmap = 0;
}
kfree(persistent_gnt);
}
if (segs_to_unmap > 0) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
}
}
static void purge_persistent_gnt(struct xen_blkif_ring *ring)
{
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
unsigned int num_clean, total;
bool scan_used = false, clean_used = false;
struct rb_root *root;
if (ring->persistent_gnt_c < xen_blkif_max_pgrants ||
(ring->persistent_gnt_c == xen_blkif_max_pgrants &&
!ring->blkif->vbd.overflow_max_grants)) {
goto out;
}
if (work_busy(&ring->persistent_purge_work)) {
pr_alert_ratelimited("Scheduled work from previous purge is still busy, cannot purge list\n");
goto out;
}
num_clean = (xen_blkif_max_pgrants / 100) * LRU_PERCENT_CLEAN;
num_clean = ring->persistent_gnt_c - xen_blkif_max_pgrants + num_clean;
num_clean = min(ring->persistent_gnt_c, num_clean);
if ((num_clean == 0) ||
(num_clean > (ring->persistent_gnt_c - atomic_read(&ring->persistent_gnt_in_use))))
goto out;
/*
* At this point, we can assure that there will be no calls
* to get_persistent_grant (because we are executing this code from
* xen_blkif_schedule), there can only be calls to put_persistent_gnt,
* which means that the number of currently used grants will go down,
* but never up, so we will always be able to remove the requested
* number of grants.
*/
total = num_clean;
pr_debug("Going to purge %u persistent grants\n", num_clean);
BUG_ON(!list_empty(&ring->persistent_purge_list));
root = &ring->persistent_gnts;
purge_list:
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
if (clean_used) {
clear_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
continue;
}
if (test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
continue;
if (!scan_used &&
(test_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags)))
continue;
rb_erase(&persistent_gnt->node, root);
list_add(&persistent_gnt->remove_node,
&ring->persistent_purge_list);
if (--num_clean == 0)
goto finished;
}
/*
* If we get here it means we also need to start cleaning
* grants that were used since last purge in order to cope
* with the requested num
*/
if (!scan_used && !clean_used) {
pr_debug("Still missing %u purged frames\n", num_clean);
scan_used = true;
goto purge_list;
}
finished:
if (!clean_used) {
pr_debug("Finished scanning for grants to clean, removing used flag\n");
clean_used = true;
goto purge_list;
}
ring->persistent_gnt_c -= (total - num_clean);
ring->blkif->vbd.overflow_max_grants = 0;
/* We can defer this work */
schedule_work(&ring->persistent_purge_work);
pr_debug("Purged %u/%u\n", (total - num_clean), total);
out:
return;
}
/*
* Retrieve from the 'pending_reqs' a free pending_req structure to be used.
*/
static struct pending_req *alloc_req(struct xen_blkif_ring *ring)
{
struct pending_req *req = NULL;
unsigned long flags;
spin_lock_irqsave(&ring->pending_free_lock, flags);
if (!list_empty(&ring->pending_free)) {
req = list_entry(ring->pending_free.next, struct pending_req,
free_list);
list_del(&req->free_list);
}
spin_unlock_irqrestore(&ring->pending_free_lock, flags);
return req;
}
/*
* Return the 'pending_req' structure back to the freepool. We also
* wake up the thread if it was waiting for a free page.
*/
static void free_req(struct xen_blkif_ring *ring, struct pending_req *req)
{
unsigned long flags;
int was_empty;
spin_lock_irqsave(&ring->pending_free_lock, flags);
was_empty = list_empty(&ring->pending_free);
list_add(&req->free_list, &ring->pending_free);
spin_unlock_irqrestore(&ring->pending_free_lock, flags);
if (was_empty)
wake_up(&ring->pending_free_wq);
}
/*
* Routines for managing virtual block devices (vbds).
*/
static int xen_vbd_translate(struct phys_req *req, struct xen_blkif *blkif,
int operation)
{
struct xen_vbd *vbd = &blkif->vbd;
int rc = -EACCES;
if ((operation != REQ_OP_READ) && vbd->readonly)
goto out;
if (likely(req->nr_sects)) {
blkif_sector_t end = req->sector_number + req->nr_sects;
if (unlikely(end < req->sector_number))
goto out;
if (unlikely(end > vbd_sz(vbd)))
goto out;
}
req->dev = vbd->pdevice;
req->bdev = vbd->bdev;
rc = 0;
out:
return rc;
}
static void xen_vbd_resize(struct xen_blkif *blkif)
{
struct xen_vbd *vbd = &blkif->vbd;
struct xenbus_transaction xbt;
int err;
struct xenbus_device *dev = xen_blkbk_xenbus(blkif->be);
unsigned long long new_size = vbd_sz(vbd);
pr_info("VBD Resize: Domid: %d, Device: (%d, %d)\n",
blkif->domid, MAJOR(vbd->pdevice), MINOR(vbd->pdevice));
pr_info("VBD Resize: new size %llu\n", new_size);
vbd->size = new_size;
again:
err = xenbus_transaction_start(&xbt);
if (err) {
pr_warn("Error starting transaction\n");
return;
}
err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
(unsigned long long)vbd_sz(vbd));
if (err) {
pr_warn("Error writing new size\n");
goto abort;
}
/*
* Write the current state; we will use this to synchronize
* the front-end. If the current state is "connected" the
* front-end will get the new size information online.
*/
err = xenbus_printf(xbt, dev->nodename, "state", "%d", dev->state);
if (err) {
pr_warn("Error writing the state\n");
goto abort;
}
err = xenbus_transaction_end(xbt, 0);
if (err == -EAGAIN)
goto again;
if (err)
pr_warn("Error ending transaction\n");
return;
abort:
xenbus_transaction_end(xbt, 1);
}
/*
* Notification from the guest OS.
*/
static void blkif_notify_work(struct xen_blkif_ring *ring)
{
ring->waiting_reqs = 1;
wake_up(&ring->wq);
}
irqreturn_t xen_blkif_be_int(int irq, void *dev_id)
{
blkif_notify_work(dev_id);
return IRQ_HANDLED;
}
/*
* SCHEDULER FUNCTIONS
*/
static void print_stats(struct xen_blkif_ring *ring)
{
pr_info("(%s): oo %3llu | rd %4llu | wr %4llu | f %4llu"
" | ds %4llu | pg: %4u/%4d\n",
current->comm, ring->st_oo_req,
ring->st_rd_req, ring->st_wr_req,
ring->st_f_req, ring->st_ds_req,
ring->persistent_gnt_c,
xen_blkif_max_pgrants);
ring->st_print = jiffies + msecs_to_jiffies(10 * 1000);
ring->st_rd_req = 0;
ring->st_wr_req = 0;
ring->st_oo_req = 0;
ring->st_ds_req = 0;
}
int xen_blkif_schedule(void *arg)
{
struct xen_blkif_ring *ring = arg;
struct xen_blkif *blkif = ring->blkif;
struct xen_vbd *vbd = &blkif->vbd;
unsigned long timeout;
int ret;
set_freezable();
while (!kthread_should_stop()) {
if (try_to_freeze())
continue;
if (unlikely(vbd->size != vbd_sz(vbd)))
xen_vbd_resize(blkif);
timeout = msecs_to_jiffies(LRU_INTERVAL);
timeout = wait_event_interruptible_timeout(
ring->wq,
ring->waiting_reqs || kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
timeout = wait_event_interruptible_timeout(
ring->pending_free_wq,
!list_empty(&ring->pending_free) ||
kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
ring->waiting_reqs = 0;
smp_mb(); /* clear flag *before* checking for work */
ret = do_block_io_op(ring);
if (ret > 0)
ring->waiting_reqs = 1;
if (ret == -EACCES)
wait_event_interruptible(ring->shutdown_wq,
kthread_should_stop());
purge_gnt_list:
if (blkif->vbd.feature_gnt_persistent &&
time_after(jiffies, ring->next_lru)) {
purge_persistent_gnt(ring);
ring->next_lru = jiffies + msecs_to_jiffies(LRU_INTERVAL);
}
/* Shrink if we have more than xen_blkif_max_buffer_pages */
shrink_free_pagepool(ring, xen_blkif_max_buffer_pages);
if (log_stats && time_after(jiffies, ring->st_print))
print_stats(ring);
}
/* Drain pending purge work */
flush_work(&ring->persistent_purge_work);
if (log_stats)
print_stats(ring);
ring->xenblkd = NULL;
return 0;
}
/*
* Remove persistent grants and empty the pool of free pages
*/
void xen_blkbk_free_caches(struct xen_blkif_ring *ring)
{
/* Free all persistent grant pages */
if (!RB_EMPTY_ROOT(&ring->persistent_gnts))
free_persistent_gnts(ring, &ring->persistent_gnts,
ring->persistent_gnt_c);
BUG_ON(!RB_EMPTY_ROOT(&ring->persistent_gnts));
ring->persistent_gnt_c = 0;
/* Since we are shutting down remove all pages from the buffer */
shrink_free_pagepool(ring, 0 /* All */);
}
static unsigned int xen_blkbk_unmap_prepare(
struct xen_blkif_ring *ring,
struct grant_page **pages,
unsigned int num,
struct gnttab_unmap_grant_ref *unmap_ops,
struct page **unmap_pages)
{
unsigned int i, invcount = 0;
for (i = 0; i < num; i++) {
if (pages[i]->persistent_gnt != NULL) {
put_persistent_gnt(ring, pages[i]->persistent_gnt);
continue;
}
if (pages[i]->handle == BLKBACK_INVALID_HANDLE)
continue;
unmap_pages[invcount] = pages[i]->page;
gnttab_set_unmap_op(&unmap_ops[invcount], vaddr(pages[i]->page),
GNTMAP_host_map, pages[i]->handle);
pages[i]->handle = BLKBACK_INVALID_HANDLE;
invcount++;
}
return invcount;
}
static void xen_blkbk_unmap_and_respond_callback(int result, struct gntab_unmap_queue_data *data)
{
struct pending_req *pending_req = (struct pending_req *)(data->data);
struct xen_blkif_ring *ring = pending_req->ring;
struct xen_blkif *blkif = ring->blkif;
/* BUG_ON used to reproduce existing behaviour,
but is this the best way to deal with this? */
BUG_ON(result);
put_free_pages(ring, data->pages, data->count);
make_response(ring, pending_req->id,
pending_req->operation, pending_req->status);
free_req(ring, pending_req);
/*
* Make sure the request is freed before releasing blkif,
* or there could be a race between free_req and the
* cleanup done in xen_blkif_free during shutdown.
*
* NB: The fact that we might try to wake up pending_free_wq
* before drain_complete (in case there's a drain going on)
* it's not a problem with our current implementation
* because we can assure there's no thread waiting on
* pending_free_wq if there's a drain going on, but it has
* to be taken into account if the current model is changed.
*/
if (atomic_dec_and_test(&ring->inflight) && atomic_read(&blkif->drain)) {
complete(&blkif->drain_complete);
}
xen_blkif_put(blkif);
}
static void xen_blkbk_unmap_and_respond(struct pending_req *req)
{
struct gntab_unmap_queue_data* work = &req->gnttab_unmap_data;
struct xen_blkif_ring *ring = req->ring;
struct grant_page **pages = req->segments;
unsigned int invcount;
invcount = xen_blkbk_unmap_prepare(ring, pages, req->nr_segs,
req->unmap, req->unmap_pages);
work->data = req;
work->done = xen_blkbk_unmap_and_respond_callback;
work->unmap_ops = req->unmap;
work->kunmap_ops = NULL;
work->pages = req->unmap_pages;
work->count = invcount;
gnttab_unmap_refs_async(&req->gnttab_unmap_data);
}
/*
* Unmap the grant references.
*
* This could accumulate ops up to the batch size to reduce the number
* of hypercalls, but since this is only used in error paths there's
* no real need.
*/
static void xen_blkbk_unmap(struct xen_blkif_ring *ring,
struct grant_page *pages[],
int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *unmap_pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
unsigned int invcount = 0;
int ret;
while (num) {
unsigned int batch = min(num, BLKIF_MAX_SEGMENTS_PER_REQUEST);
invcount = xen_blkbk_unmap_prepare(ring, pages, batch,
unmap, unmap_pages);
if (invcount) {
ret = gnttab_unmap_refs(unmap, NULL, unmap_pages, invcount);
BUG_ON(ret);
put_free_pages(ring, unmap_pages, invcount);
}
pages += batch;
num -= batch;
}
}
static int xen_blkbk_map(struct xen_blkif_ring *ring,
struct grant_page *pages[],
int num, bool ro)
{
struct gnttab_map_grant_ref map[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages_to_gnt[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt = NULL;
phys_addr_t addr = 0;
int i, seg_idx, new_map_idx;
int segs_to_map = 0;
int ret = 0;
int last_map = 0, map_until = 0;
int use_persistent_gnts;
struct xen_blkif *blkif = ring->blkif;
use_persistent_gnts = (blkif->vbd.feature_gnt_persistent);
/*
* Fill out preq.nr_sects with proper amount of sectors, and setup
* assign map[..] with the PFN of the page in our domain with the
* corresponding grant reference for each page.
*/
again:
for (i = map_until; i < num; i++) {
uint32_t flags;
if (use_persistent_gnts) {
persistent_gnt = get_persistent_gnt(
ring,
pages[i]->gref);
}
if (persistent_gnt) {
/*
* We are using persistent grants and
* the grant is already mapped
*/
pages[i]->page = persistent_gnt->page;
pages[i]->persistent_gnt = persistent_gnt;
} else {
if (get_free_page(ring, &pages[i]->page))
goto out_of_memory;
addr = vaddr(pages[i]->page);
pages_to_gnt[segs_to_map] = pages[i]->page;
pages[i]->persistent_gnt = NULL;
flags = GNTMAP_host_map;
if (!use_persistent_gnts && ro)
flags |= GNTMAP_readonly;
gnttab_set_map_op(&map[segs_to_map++], addr,
flags, pages[i]->gref,
blkif->domid);
}
map_until = i + 1;
if (segs_to_map == BLKIF_MAX_SEGMENTS_PER_REQUEST)
break;
}
if (segs_to_map) {
ret = gnttab_map_refs(map, NULL, pages_to_gnt, segs_to_map);
BUG_ON(ret);
}
/*
* Now swizzle the MFN in our domain with the MFN from the other domain
* so that when we access vaddr(pending_req,i) it has the contents of
* the page from the other domain.
*/
for (seg_idx = last_map, new_map_idx = 0; seg_idx < map_until; seg_idx++) {
if (!pages[seg_idx]->persistent_gnt) {
/* This is a newly mapped grant */
BUG_ON(new_map_idx >= segs_to_map);
if (unlikely(map[new_map_idx].status != 0)) {
pr_debug("invalid buffer -- could not remap it\n");
put_free_pages(ring, &pages[seg_idx]->page, 1);
pages[seg_idx]->handle = BLKBACK_INVALID_HANDLE;
ret |= 1;
goto next;
}
pages[seg_idx]->handle = map[new_map_idx].handle;
} else {
continue;
}
if (use_persistent_gnts &&
ring->persistent_gnt_c < xen_blkif_max_pgrants) {
/*
* We are using persistent grants, the grant is
* not mapped but we might have room for it.
*/
persistent_gnt = kmalloc(sizeof(struct persistent_gnt),
GFP_KERNEL);
if (!persistent_gnt) {
/*
* If we don't have enough memory to
* allocate the persistent_gnt struct
* map this grant non-persistenly
*/
goto next;
}
persistent_gnt->gnt = map[new_map_idx].ref;
persistent_gnt->handle = map[new_map_idx].handle;
persistent_gnt->page = pages[seg_idx]->page;
if (add_persistent_gnt(ring,
persistent_gnt)) {
kfree(persistent_gnt);
persistent_gnt = NULL;
goto next;
}
pages[seg_idx]->persistent_gnt = persistent_gnt;
pr_debug("grant %u added to the tree of persistent grants, using %u/%u\n",
persistent_gnt->gnt, ring->persistent_gnt_c,
xen_blkif_max_pgrants);
goto next;
}
if (use_persistent_gnts && !blkif->vbd.overflow_max_grants) {
blkif->vbd.overflow_max_grants = 1;
pr_debug("domain %u, device %#x is using maximum number of persistent grants\n",
blkif->domid, blkif->vbd.handle);
}
/*
* We could not map this grant persistently, so use it as
* a non-persistent grant.
*/
next:
new_map_idx++;
}
segs_to_map = 0;
last_map = map_until;
if (map_until != num)
goto again;
return ret;
out_of_memory:
pr_alert("%s: out of memory\n", __func__);
put_free_pages(ring, pages_to_gnt, segs_to_map);
return -ENOMEM;
}
static int xen_blkbk_map_seg(struct pending_req *pending_req)
{
int rc;
rc = xen_blkbk_map(pending_req->ring, pending_req->segments,
pending_req->nr_segs,
(pending_req->operation != BLKIF_OP_READ));
return rc;
}
static int xen_blkbk_parse_indirect(struct blkif_request *req,
struct pending_req *pending_req,
struct seg_buf seg[],
struct phys_req *preq)
{
struct grant_page **pages = pending_req->indirect_pages;
struct xen_blkif_ring *ring = pending_req->ring;
int indirect_grefs, rc, n, nseg, i;
struct blkif_request_segment *segments = NULL;
nseg = pending_req->nr_segs;
indirect_grefs = INDIRECT_PAGES(nseg);
BUG_ON(indirect_grefs > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
for (i = 0; i < indirect_grefs; i++)
pages[i]->gref = req->u.indirect.indirect_grefs[i];
rc = xen_blkbk_map(ring, pages, indirect_grefs, true);
if (rc)
goto unmap;
for (n = 0, i = 0; n < nseg; n++) {
uint8_t first_sect, last_sect;
if ((n % SEGS_PER_INDIRECT_FRAME) == 0) {
/* Map indirect segments */
if (segments)
kunmap_atomic(segments);
segments = kmap_atomic(pages[n/SEGS_PER_INDIRECT_FRAME]->page);
}
i = n % SEGS_PER_INDIRECT_FRAME;
pending_req->segments[n]->gref = segments[i].gref;
first_sect = READ_ONCE(segments[i].first_sect);
last_sect = READ_ONCE(segments[i].last_sect);
if (last_sect >= (XEN_PAGE_SIZE >> 9) || last_sect < first_sect) {
rc = -EINVAL;
goto unmap;
}
seg[n].nsec = last_sect - first_sect + 1;
seg[n].offset = first_sect << 9;
preq->nr_sects += seg[n].nsec;
}
unmap:
if (segments)
kunmap_atomic(segments);
xen_blkbk_unmap(ring, pages, indirect_grefs);
return rc;
}
static int dispatch_discard_io(struct xen_blkif_ring *ring,
struct blkif_request *req)
{
int err = 0;
int status = BLKIF_RSP_OKAY;
struct xen_blkif *blkif = ring->blkif;
struct block_device *bdev = blkif->vbd.bdev;
unsigned long secure;
struct phys_req preq;
xen_blkif_get(blkif);
preq.sector_number = req->u.discard.sector_number;
preq.nr_sects = req->u.discard.nr_sectors;
err = xen_vbd_translate(&preq, blkif, REQ_OP_WRITE);
if (err) {
pr_warn("access denied: DISCARD [%llu->%llu] on dev=%04x\n",
preq.sector_number,
preq.sector_number + preq.nr_sects, blkif->vbd.pdevice);
goto fail_response;
}
ring->st_ds_req++;
secure = (blkif->vbd.discard_secure &&
(req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?
BLKDEV_DISCARD_SECURE : 0;
err = blkdev_issue_discard(bdev, req->u.discard.sector_number,
req->u.discard.nr_sectors,
GFP_KERNEL, secure);
fail_response:
if (err == -EOPNOTSUPP) {
pr_debug("discard op failed, not supported\n");
status = BLKIF_RSP_EOPNOTSUPP;
} else if (err)
status = BLKIF_RSP_ERROR;
make_response(ring, req->u.discard.id, req->operation, status);
xen_blkif_put(blkif);
return err;
}
static int dispatch_other_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req)
{
free_req(ring, pending_req);
make_response(ring, req->u.other.id, req->operation,
BLKIF_RSP_EOPNOTSUPP);
return -EIO;
}
static void xen_blk_drain_io(struct xen_blkif_ring *ring)
{
struct xen_blkif *blkif = ring->blkif;
atomic_set(&blkif->drain, 1);
do {
if (atomic_read(&ring->inflight) == 0)
break;
wait_for_completion_interruptible_timeout(
&blkif->drain_complete, HZ);
if (!atomic_read(&blkif->drain))
break;
} while (!kthread_should_stop());
atomic_set(&blkif->drain, 0);
}
/*
* Completion callback on the bio's. Called as bh->b_end_io()
*/
static void __end_block_io_op(struct pending_req *pending_req, int error)
{
/* An error fails the entire request. */
if ((pending_req->operation == BLKIF_OP_FLUSH_DISKCACHE) &&
(error == -EOPNOTSUPP)) {
pr_debug("flush diskcache op failed, not supported\n");
xen_blkbk_flush_diskcache(XBT_NIL, pending_req->ring->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if ((pending_req->operation == BLKIF_OP_WRITE_BARRIER) &&
(error == -EOPNOTSUPP)) {
pr_debug("write barrier op failed, not supported\n");
xen_blkbk_barrier(XBT_NIL, pending_req->ring->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if (error) {
pr_debug("Buffer not up-to-date at end of operation,"
" error=%d\n", error);
pending_req->status = BLKIF_RSP_ERROR;
}
/*
* If all of the bio's have completed it is time to unmap
* the grant references associated with 'request' and provide
* the proper response on the ring.
*/
if (atomic_dec_and_test(&pending_req->pendcnt))
xen_blkbk_unmap_and_respond(pending_req);
}
/*
* bio callback.
*/
static void end_block_io_op(struct bio *bio)
{
__end_block_io_op(bio->bi_private, bio->bi_error);
bio_put(bio);
}
/*
* Function to copy the from the ring buffer the 'struct blkif_request'
* (which has the sectors we want, number of them, grant references, etc),
* and transmute it to the block API to hand it over to the proper block disk.
*/
static int
__do_block_io_op(struct xen_blkif_ring *ring)
{
union blkif_back_rings *blk_rings = &ring->blk_rings;
struct blkif_request req;
struct pending_req *pending_req;
RING_IDX rc, rp;
int more_to_do = 0;
rc = blk_rings->common.req_cons;
rp = blk_rings->common.sring->req_prod;
rmb(); /* Ensure we see queued requests up to 'rp'. */
if (RING_REQUEST_PROD_OVERFLOW(&blk_rings->common, rp)) {
rc = blk_rings->common.rsp_prod_pvt;
pr_warn("Frontend provided bogus ring requests (%d - %d = %d). Halting ring processing on dev=%04x\n",
rp, rc, rp - rc, ring->blkif->vbd.pdevice);
return -EACCES;
}
while (rc != rp) {
if (RING_REQUEST_CONS_OVERFLOW(&blk_rings->common, rc))
break;
if (kthread_should_stop()) {
more_to_do = 1;
break;
}
pending_req = alloc_req(ring);
if (NULL == pending_req) {
ring->st_oo_req++;
more_to_do = 1;
break;
}
switch (ring->blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(&req, RING_GET_REQUEST(&blk_rings->native, rc), sizeof(req));
break;
case BLKIF_PROTOCOL_X86_32:
blkif_get_x86_32_req(&req, RING_GET_REQUEST(&blk_rings->x86_32, rc));
break;
case BLKIF_PROTOCOL_X86_64:
blkif_get_x86_64_req(&req, RING_GET_REQUEST(&blk_rings->x86_64, rc));
break;
default:
BUG();
}
blk_rings->common.req_cons = ++rc; /* before make_response() */
/* Apply all sanity checks to /private copy/ of request. */
barrier();
switch (req.operation) {
case BLKIF_OP_READ:
case BLKIF_OP_WRITE:
case BLKIF_OP_WRITE_BARRIER:
case BLKIF_OP_FLUSH_DISKCACHE:
case BLKIF_OP_INDIRECT:
if (dispatch_rw_block_io(ring, &req, pending_req))
goto done;
break;
case BLKIF_OP_DISCARD:
free_req(ring, pending_req);
if (dispatch_discard_io(ring, &req))
goto done;
break;
default:
if (dispatch_other_io(ring, &req, pending_req))
goto done;
break;
}
/* Yield point for this unbounded loop. */
cond_resched();
}
done:
return more_to_do;
}
static int
do_block_io_op(struct xen_blkif_ring *ring)
{
union blkif_back_rings *blk_rings = &ring->blk_rings;
int more_to_do;
do {
more_to_do = __do_block_io_op(ring);
if (more_to_do)
break;
RING_FINAL_CHECK_FOR_REQUESTS(&blk_rings->common, more_to_do);
} while (more_to_do);
return more_to_do;
}
/*
* Transmutation of the 'struct blkif_request' to a proper 'struct bio'
* and call the 'submit_bio' to pass it to the underlying storage.
*/
static int dispatch_rw_block_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req)
{
struct phys_req preq;
struct seg_buf *seg = pending_req->seg;
unsigned int nseg;
struct bio *bio = NULL;
struct bio **biolist = pending_req->biolist;
int i, nbio = 0;
int operation;
int operation_flags = 0;
struct blk_plug plug;
bool drain = false;
struct grant_page **pages = pending_req->segments;
unsigned short req_operation;
req_operation = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.indirect_op : req->operation;
if ((req->operation == BLKIF_OP_INDIRECT) &&
(req_operation != BLKIF_OP_READ) &&
(req_operation != BLKIF_OP_WRITE)) {
pr_debug("Invalid indirect operation (%u)\n", req_operation);
goto fail_response;
}
switch (req_operation) {
case BLKIF_OP_READ:
ring->st_rd_req++;
operation = REQ_OP_READ;
break;
case BLKIF_OP_WRITE:
ring->st_wr_req++;
operation = REQ_OP_WRITE;
operation_flags = REQ_SYNC | REQ_IDLE;
break;
case BLKIF_OP_WRITE_BARRIER:
drain = true;
case BLKIF_OP_FLUSH_DISKCACHE:
ring->st_f_req++;
operation = REQ_OP_WRITE;
operation_flags = REQ_PREFLUSH;
break;
default:
operation = 0; /* make gcc happy */
goto fail_response;
break;
}
/* Check that the number of segments is sane. */
nseg = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.nr_segments : req->u.rw.nr_segments;
if (unlikely(nseg == 0 && operation_flags != REQ_PREFLUSH) ||
unlikely((req->operation != BLKIF_OP_INDIRECT) &&
(nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) ||
unlikely((req->operation == BLKIF_OP_INDIRECT) &&
(nseg > MAX_INDIRECT_SEGMENTS))) {
pr_debug("Bad number of segments in request (%d)\n", nseg);
/* Haven't submitted any bio's yet. */
goto fail_response;
}
preq.nr_sects = 0;
pending_req->ring = ring;
pending_req->id = req->u.rw.id;
pending_req->operation = req_operation;
pending_req->status = BLKIF_RSP_OKAY;
pending_req->nr_segs = nseg;
if (req->operation != BLKIF_OP_INDIRECT) {
preq.dev = req->u.rw.handle;
preq.sector_number = req->u.rw.sector_number;
for (i = 0; i < nseg; i++) {
pages[i]->gref = req->u.rw.seg[i].gref;
seg[i].nsec = req->u.rw.seg[i].last_sect -
req->u.rw.seg[i].first_sect + 1;
seg[i].offset = (req->u.rw.seg[i].first_sect << 9);
if ((req->u.rw.seg[i].last_sect >= (XEN_PAGE_SIZE >> 9)) ||
(req->u.rw.seg[i].last_sect <
req->u.rw.seg[i].first_sect))
goto fail_response;
preq.nr_sects += seg[i].nsec;
}
} else {
preq.dev = req->u.indirect.handle;
preq.sector_number = req->u.indirect.sector_number;
if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq))
goto fail_response;
}
if (xen_vbd_translate(&preq, ring->blkif, operation) != 0) {
pr_debug("access denied: %s of [%llu,%llu] on dev=%04x\n",
operation == REQ_OP_READ ? "read" : "write",
preq.sector_number,
preq.sector_number + preq.nr_sects,
ring->blkif->vbd.pdevice);
goto fail_response;
}
/*
* This check _MUST_ be done after xen_vbd_translate as the preq.bdev
* is set there.
*/
for (i = 0; i < nseg; i++) {
if (((int)preq.sector_number|(int)seg[i].nsec) &
((bdev_logical_block_size(preq.bdev) >> 9) - 1)) {
pr_debug("Misaligned I/O request from domain %d\n",
ring->blkif->domid);
goto fail_response;
}
}
/* Wait on all outstanding I/O's and once that has been completed
* issue the flush.
*/
if (drain)
xen_blk_drain_io(pending_req->ring);
/*
* If we have failed at this point, we need to undo the M2P override,
* set gnttab_set_unmap_op on all of the grant references and perform
* the hypercall to unmap the grants - that is all done in
* xen_blkbk_unmap.
*/
if (xen_blkbk_map_seg(pending_req))
goto fail_flush;
/*
* This corresponding xen_blkif_put is done in __end_block_io_op, or
* below (in "!bio") if we are handling a BLKIF_OP_DISCARD.
*/
xen_blkif_get(ring->blkif);
atomic_inc(&ring->inflight);
for (i = 0; i < nseg; i++) {
while ((bio == NULL) ||
(bio_add_page(bio,
pages[i]->page,
seg[i].nsec << 9,
seg[i].offset) == 0)) {
int nr_iovecs = min_t(int, (nseg-i), BIO_MAX_PAGES);
bio = bio_alloc(GFP_KERNEL, nr_iovecs);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
bio->bi_iter.bi_sector = preq.sector_number;
bio_set_op_attrs(bio, operation, operation_flags);
}
preq.sector_number += seg[i].nsec;
}
/* This will be hit if the operation was a flush or discard. */
if (!bio) {
BUG_ON(operation_flags != REQ_PREFLUSH);
bio = bio_alloc(GFP_KERNEL, 0);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
bio_set_op_attrs(bio, operation, operation_flags);
}
atomic_set(&pending_req->pendcnt, nbio);
blk_start_plug(&plug);
for (i = 0; i < nbio; i++)
submit_bio(biolist[i]);
/* Let the I/Os go.. */
blk_finish_plug(&plug);
if (operation == REQ_OP_READ)
ring->st_rd_sect += preq.nr_sects;
else if (operation == REQ_OP_WRITE)
ring->st_wr_sect += preq.nr_sects;
return 0;
fail_flush:
xen_blkbk_unmap(ring, pending_req->segments,
pending_req->nr_segs);
fail_response:
/* Haven't submitted any bio's yet. */
make_response(ring, req->u.rw.id, req_operation, BLKIF_RSP_ERROR);
free_req(ring, pending_req);
msleep(1); /* back off a bit */
return -EIO;
fail_put_bio:
for (i = 0; i < nbio; i++)
bio_put(biolist[i]);
atomic_set(&pending_req->pendcnt, 1);
__end_block_io_op(pending_req, -EINVAL);
msleep(1); /* back off a bit */
return -EIO;
}
/*
* Put a response on the ring on how the operation fared.
*/
static void make_response(struct xen_blkif_ring *ring, u64 id,
unsigned short op, int st)
{
struct blkif_response resp;
unsigned long flags;
union blkif_back_rings *blk_rings;
int notify;
resp.id = id;
resp.operation = op;
resp.status = st;
spin_lock_irqsave(&ring->blk_ring_lock, flags);
blk_rings = &ring->blk_rings;
/* Place on the response ring for the relevant domain. */
switch (ring->blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(RING_GET_RESPONSE(&blk_rings->native, blk_rings->native.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_32:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_32, blk_rings->x86_32.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_64:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_64, blk_rings->x86_64.rsp_prod_pvt),
&resp, sizeof(resp));
break;
default:
BUG();
}
blk_rings->common.rsp_prod_pvt++;
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blk_rings->common, notify);
spin_unlock_irqrestore(&ring->blk_ring_lock, flags);
if (notify)
notify_remote_via_irq(ring->irq);
}
static int __init xen_blkif_init(void)
{
int rc = 0;
if (!xen_domain())
return -ENODEV;
if (xen_blkif_max_ring_order > XENBUS_MAX_RING_GRANT_ORDER) {
pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
xen_blkif_max_ring_order, XENBUS_MAX_RING_GRANT_ORDER);
xen_blkif_max_ring_order = XENBUS_MAX_RING_GRANT_ORDER;
}
if (xenblk_max_queues == 0)
xenblk_max_queues = num_online_cpus();
rc = xen_blkif_interface_init();
if (rc)
goto failed_init;
rc = xen_blkif_xenbus_init();
if (rc)
goto failed_init;
failed_init:
return rc;
}
module_init(xen_blkif_init);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_ALIAS("xen-backend:vbd");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_2559_0 |
crossvul-cpp_data_good_4936_0 | /*
* Copyright(c) 2006 - 2007 Atheros Corporation. All rights reserved.
* Copyright(c) 2007 - 2008 Chris Snook <csnook@redhat.com>
*
* Derived from Intel e1000 driver
* Copyright(c) 1999 - 2005 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/atomic.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/hardirq.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/irqflags.h>
#include <linux/irqreturn.h>
#include <linux/mii.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/pm.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/tcp.h>
#include <linux/timer.h>
#include <linux/types.h>
#include <linux/workqueue.h>
#include "atl2.h"
#define ATL2_DRV_VERSION "2.2.3"
static const char atl2_driver_name[] = "atl2";
static const char atl2_driver_string[] = "Atheros(R) L2 Ethernet Driver";
static const char atl2_copyright[] = "Copyright (c) 2007 Atheros Corporation.";
static const char atl2_driver_version[] = ATL2_DRV_VERSION;
static const struct ethtool_ops atl2_ethtool_ops;
MODULE_AUTHOR("Atheros Corporation <xiong.huang@atheros.com>, Chris Snook <csnook@redhat.com>");
MODULE_DESCRIPTION("Atheros Fast Ethernet Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(ATL2_DRV_VERSION);
/*
* atl2_pci_tbl - PCI Device ID Table
*/
static const struct pci_device_id atl2_pci_tbl[] = {
{PCI_DEVICE(PCI_VENDOR_ID_ATTANSIC, PCI_DEVICE_ID_ATTANSIC_L2)},
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, atl2_pci_tbl);
static void atl2_check_options(struct atl2_adapter *adapter);
/**
* atl2_sw_init - Initialize general software structures (struct atl2_adapter)
* @adapter: board private structure to initialize
*
* atl2_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
*/
static int atl2_sw_init(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_id = pdev->subsystem_device;
hw->revision_id = pdev->revision;
pci_read_config_word(pdev, PCI_COMMAND, &hw->pci_cmd_word);
adapter->wol = 0;
adapter->ict = 50000; /* ~100ms */
adapter->link_speed = SPEED_0; /* hardware init */
adapter->link_duplex = FULL_DUPLEX;
hw->phy_configured = false;
hw->preamble_len = 7;
hw->ipgt = 0x60;
hw->min_ifg = 0x50;
hw->ipgr1 = 0x40;
hw->ipgr2 = 0x60;
hw->retry_buf = 2;
hw->max_retry = 0xf;
hw->lcol = 0x37;
hw->jam_ipg = 7;
hw->fc_rxd_hi = 0;
hw->fc_rxd_lo = 0;
hw->max_frame_size = adapter->netdev->mtu;
spin_lock_init(&adapter->stats_lock);
set_bit(__ATL2_DOWN, &adapter->flags);
return 0;
}
/**
* atl2_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
*/
static void atl2_set_multi(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u32 rctl;
u32 hash_value;
/* Check for Promiscuous and All Multicast modes */
rctl = ATL2_READ_REG(hw, REG_MAC_CTRL);
if (netdev->flags & IFF_PROMISC) {
rctl |= MAC_CTRL_PROMIS_EN;
} else if (netdev->flags & IFF_ALLMULTI) {
rctl |= MAC_CTRL_MC_ALL_EN;
rctl &= ~MAC_CTRL_PROMIS_EN;
} else
rctl &= ~(MAC_CTRL_PROMIS_EN | MAC_CTRL_MC_ALL_EN);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, rctl);
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
/* comoute mc addresses' hash value ,and put it into hash table */
netdev_for_each_mc_addr(ha, netdev) {
hash_value = atl2_hash_mc_addr(hw, ha->addr);
atl2_hash_set(hw, hash_value);
}
}
static void init_ring_ptrs(struct atl2_adapter *adapter)
{
/* Read / Write Ptr Initialize: */
adapter->txd_write_ptr = 0;
atomic_set(&adapter->txd_read_ptr, 0);
adapter->rxd_read_ptr = 0;
adapter->rxd_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, 0);
adapter->txs_next_clear = 0;
}
/**
* atl2_configure - Configure Transmit&Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Tx /Rx unit of the MAC after a reset.
*/
static int atl2_configure(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
u32 value;
/* clear interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0xffffffff);
/* set MAC Address */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG(hw, REG_MAC_STA_ADDR, value);
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG(hw, (REG_MAC_STA_ADDR+4), value);
/* HI base address */
ATL2_WRITE_REG(hw, REG_DESC_BASE_ADDR_HI,
(u32)((adapter->ring_dma & 0xffffffff00000000ULL) >> 32));
/* LO base address */
ATL2_WRITE_REG(hw, REG_TXD_BASE_ADDR_LO,
(u32)(adapter->txd_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_TXS_BASE_ADDR_LO,
(u32)(adapter->txs_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_RXD_BASE_ADDR_LO,
(u32)(adapter->rxd_dma & 0x00000000ffffffffULL));
/* element count */
ATL2_WRITE_REGW(hw, REG_TXD_MEM_SIZE, (u16)(adapter->txd_ring_size/4));
ATL2_WRITE_REGW(hw, REG_TXS_MEM_SIZE, (u16)adapter->txs_ring_size);
ATL2_WRITE_REGW(hw, REG_RXD_BUF_NUM, (u16)adapter->rxd_ring_size);
/* config Internal SRAM */
/*
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_tx_end);
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_rx_end);
*/
/* config IPG/IFG */
value = (((u32)hw->ipgt & MAC_IPG_IFG_IPGT_MASK) <<
MAC_IPG_IFG_IPGT_SHIFT) |
(((u32)hw->min_ifg & MAC_IPG_IFG_MIFG_MASK) <<
MAC_IPG_IFG_MIFG_SHIFT) |
(((u32)hw->ipgr1 & MAC_IPG_IFG_IPGR1_MASK) <<
MAC_IPG_IFG_IPGR1_SHIFT)|
(((u32)hw->ipgr2 & MAC_IPG_IFG_IPGR2_MASK) <<
MAC_IPG_IFG_IPGR2_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_IPG_IFG, value);
/* config Half-Duplex Control */
value = ((u32)hw->lcol & MAC_HALF_DUPLX_CTRL_LCOL_MASK) |
(((u32)hw->max_retry & MAC_HALF_DUPLX_CTRL_RETRY_MASK) <<
MAC_HALF_DUPLX_CTRL_RETRY_SHIFT) |
MAC_HALF_DUPLX_CTRL_EXC_DEF_EN |
(0xa << MAC_HALF_DUPLX_CTRL_ABEBT_SHIFT) |
(((u32)hw->jam_ipg & MAC_HALF_DUPLX_CTRL_JAMIPG_MASK) <<
MAC_HALF_DUPLX_CTRL_JAMIPG_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_HALF_DUPLX_CTRL, value);
/* set Interrupt Moderator Timer */
ATL2_WRITE_REGW(hw, REG_IRQ_MODU_TIMER_INIT, adapter->imt);
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_ITIMER_EN);
/* set Interrupt Clear Timer */
ATL2_WRITE_REGW(hw, REG_CMBDISDMA_TIMER, adapter->ict);
/* set MTU */
ATL2_WRITE_REG(hw, REG_MTU, adapter->netdev->mtu +
ENET_HEADER_SIZE + VLAN_SIZE + ETHERNET_FCS_SIZE);
/* 1590 */
ATL2_WRITE_REG(hw, REG_TX_CUT_THRESH, 0x177);
/* flow control */
ATL2_WRITE_REGW(hw, REG_PAUSE_ON_TH, hw->fc_rxd_hi);
ATL2_WRITE_REGW(hw, REG_PAUSE_OFF_TH, hw->fc_rxd_lo);
/* Init mailbox */
ATL2_WRITE_REGW(hw, REG_MB_TXD_WR_IDX, (u16)adapter->txd_write_ptr);
ATL2_WRITE_REGW(hw, REG_MB_RXD_RD_IDX, (u16)adapter->rxd_read_ptr);
/* enable DMA read/write */
ATL2_WRITE_REGB(hw, REG_DMAR, DMAR_EN);
ATL2_WRITE_REGB(hw, REG_DMAW, DMAW_EN);
value = ATL2_READ_REG(&adapter->hw, REG_ISR);
if ((value & ISR_PHY_LINKDOWN) != 0)
value = 1; /* config failed */
else
value = 0;
/* clear all interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0x3fffffff);
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return value;
}
/**
* atl2_setup_ring_resources - allocate Tx / RX descriptor resources
* @adapter: board private structure
*
* Return 0 on success, negative on failure
*/
static s32 atl2_setup_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int size;
u8 offset = 0;
/* real ring DMA buffer */
adapter->ring_size = size =
adapter->txd_ring_size * 1 + 7 + /* dword align */
adapter->txs_ring_size * 4 + 7 + /* dword align */
adapter->rxd_ring_size * 1536 + 127; /* 128bytes align */
adapter->ring_vir_addr = pci_alloc_consistent(pdev, size,
&adapter->ring_dma);
if (!adapter->ring_vir_addr)
return -ENOMEM;
memset(adapter->ring_vir_addr, 0, adapter->ring_size);
/* Init TXD Ring */
adapter->txd_dma = adapter->ring_dma ;
offset = (adapter->txd_dma & 0x7) ? (8 - (adapter->txd_dma & 0x7)) : 0;
adapter->txd_dma += offset;
adapter->txd_ring = adapter->ring_vir_addr + offset;
/* Init TXS Ring */
adapter->txs_dma = adapter->txd_dma + adapter->txd_ring_size;
offset = (adapter->txs_dma & 0x7) ? (8 - (adapter->txs_dma & 0x7)) : 0;
adapter->txs_dma += offset;
adapter->txs_ring = (struct tx_pkt_status *)
(((u8 *)adapter->txd_ring) + (adapter->txd_ring_size + offset));
/* Init RXD Ring */
adapter->rxd_dma = adapter->txs_dma + adapter->txs_ring_size * 4;
offset = (adapter->rxd_dma & 127) ?
(128 - (adapter->rxd_dma & 127)) : 0;
if (offset > 7)
offset -= 8;
else
offset += (128 - 8);
adapter->rxd_dma += offset;
adapter->rxd_ring = (struct rx_desc *) (((u8 *)adapter->txs_ring) +
(adapter->txs_ring_size * 4 + offset));
/*
* Read / Write Ptr Initialize:
* init_ring_ptrs(adapter);
*/
return 0;
}
/**
* atl2_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
*/
static inline void atl2_irq_enable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, IMR_NORMAL_MASK);
ATL2_WRITE_FLUSH(&adapter->hw);
}
/**
* atl2_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
*/
static inline void atl2_irq_disable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(&adapter->hw);
synchronize_irq(adapter->pdev->irq);
}
static void __atl2_vlan_mode(netdev_features_t features, u32 *ctrl)
{
if (features & NETIF_F_HW_VLAN_CTAG_RX) {
/* enable VLAN tag insert/strip */
*ctrl |= MAC_CTRL_RMV_VLAN;
} else {
/* disable VLAN tag insert/strip */
*ctrl &= ~MAC_CTRL_RMV_VLAN;
}
}
static void atl2_vlan_mode(struct net_device *netdev,
netdev_features_t features)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 ctrl;
atl2_irq_disable(adapter);
ctrl = ATL2_READ_REG(&adapter->hw, REG_MAC_CTRL);
__atl2_vlan_mode(features, &ctrl);
ATL2_WRITE_REG(&adapter->hw, REG_MAC_CTRL, ctrl);
atl2_irq_enable(adapter);
}
static void atl2_restore_vlan(struct atl2_adapter *adapter)
{
atl2_vlan_mode(adapter->netdev, adapter->netdev->features);
}
static netdev_features_t atl2_fix_features(struct net_device *netdev,
netdev_features_t features)
{
/*
* Since there is no support for separate rx/tx vlan accel
* enable/disable make sure tx flag is always in same state as rx.
*/
if (features & NETIF_F_HW_VLAN_CTAG_RX)
features |= NETIF_F_HW_VLAN_CTAG_TX;
else
features &= ~NETIF_F_HW_VLAN_CTAG_TX;
return features;
}
static int atl2_set_features(struct net_device *netdev,
netdev_features_t features)
{
netdev_features_t changed = netdev->features ^ features;
if (changed & NETIF_F_HW_VLAN_CTAG_RX)
atl2_vlan_mode(netdev, features);
return 0;
}
static void atl2_intr_rx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct rx_desc *rxd;
struct sk_buff *skb;
do {
rxd = adapter->rxd_ring+adapter->rxd_write_ptr;
if (!rxd->status.update)
break; /* end of tx */
/* clear this flag at once */
rxd->status.update = 0;
if (rxd->status.ok && rxd->status.pkt_size >= 60) {
int rx_size = (int)(rxd->status.pkt_size - 4);
/* alloc new buffer */
skb = netdev_alloc_skb_ip_align(netdev, rx_size);
if (NULL == skb) {
/*
* Check that some rx space is free. If not,
* free one and mark stats->rx_dropped++.
*/
netdev->stats.rx_dropped++;
break;
}
memcpy(skb->data, rxd->packet, rx_size);
skb_put(skb, rx_size);
skb->protocol = eth_type_trans(skb, netdev);
if (rxd->status.vlan) {
u16 vlan_tag = (rxd->status.vtag>>4) |
((rxd->status.vtag&7) << 13) |
((rxd->status.vtag&8) << 9);
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlan_tag);
}
netif_rx(skb);
netdev->stats.rx_bytes += rx_size;
netdev->stats.rx_packets++;
} else {
netdev->stats.rx_errors++;
if (rxd->status.ok && rxd->status.pkt_size <= 60)
netdev->stats.rx_length_errors++;
if (rxd->status.mcast)
netdev->stats.multicast++;
if (rxd->status.crc)
netdev->stats.rx_crc_errors++;
if (rxd->status.align)
netdev->stats.rx_frame_errors++;
}
/* advance write ptr */
if (++adapter->rxd_write_ptr == adapter->rxd_ring_size)
adapter->rxd_write_ptr = 0;
} while (1);
/* update mailbox? */
adapter->rxd_read_ptr = adapter->rxd_write_ptr;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_RXD_RD_IDX, adapter->rxd_read_ptr);
}
static void atl2_intr_tx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 txd_read_ptr;
u32 txs_write_ptr;
struct tx_pkt_status *txs;
struct tx_pkt_header *txph;
int free_hole = 0;
do {
txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
txs = adapter->txs_ring + txs_write_ptr;
if (!txs->update)
break; /* tx stop here */
free_hole = 1;
txs->update = 0;
if (++txs_write_ptr == adapter->txs_ring_size)
txs_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, (int)txs_write_ptr);
txd_read_ptr = (u32) atomic_read(&adapter->txd_read_ptr);
txph = (struct tx_pkt_header *)
(((u8 *)adapter->txd_ring) + txd_read_ptr);
if (txph->pkt_size != txs->pkt_size) {
struct tx_pkt_status *old_txs = txs;
printk(KERN_WARNING
"%s: txs packet size not consistent with txd"
" txd_:0x%08x, txs_:0x%08x!\n",
adapter->netdev->name,
*(u32 *)txph, *(u32 *)txs);
printk(KERN_WARNING
"txd read ptr: 0x%x\n",
txd_read_ptr);
txs = adapter->txs_ring + txs_write_ptr;
printk(KERN_WARNING
"txs-behind:0x%08x\n",
*(u32 *)txs);
if (txs_write_ptr < 2) {
txs = adapter->txs_ring +
(adapter->txs_ring_size +
txs_write_ptr - 2);
} else {
txs = adapter->txs_ring + (txs_write_ptr - 2);
}
printk(KERN_WARNING
"txs-before:0x%08x\n",
*(u32 *)txs);
txs = old_txs;
}
/* 4for TPH */
txd_read_ptr += (((u32)(txph->pkt_size) + 7) & ~3);
if (txd_read_ptr >= adapter->txd_ring_size)
txd_read_ptr -= adapter->txd_ring_size;
atomic_set(&adapter->txd_read_ptr, (int)txd_read_ptr);
/* tx statistics: */
if (txs->ok) {
netdev->stats.tx_bytes += txs->pkt_size;
netdev->stats.tx_packets++;
}
else
netdev->stats.tx_errors++;
if (txs->defer)
netdev->stats.collisions++;
if (txs->abort_col)
netdev->stats.tx_aborted_errors++;
if (txs->late_col)
netdev->stats.tx_window_errors++;
if (txs->underun)
netdev->stats.tx_fifo_errors++;
} while (1);
if (free_hole) {
if (netif_queue_stopped(adapter->netdev) &&
netif_carrier_ok(adapter->netdev))
netif_wake_queue(adapter->netdev);
}
}
static void atl2_check_for_link(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u16 phy_data = 0;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
spin_unlock(&adapter->stats_lock);
/* notify upper layer link down ASAP */
if (!(phy_data & BMSR_LSTATUS)) { /* Link Down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
printk(KERN_INFO "%s: %s NIC Link is Down\n",
atl2_driver_name, netdev->name);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
}
schedule_work(&adapter->link_chg_task);
}
static inline void atl2_clear_phy_int(struct atl2_adapter *adapter)
{
u16 phy_data;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, 19, &phy_data);
spin_unlock(&adapter->stats_lock);
}
/**
* atl2_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
*/
static irqreturn_t atl2_intr(int irq, void *data)
{
struct atl2_adapter *adapter = netdev_priv(data);
struct atl2_hw *hw = &adapter->hw;
u32 status;
status = ATL2_READ_REG(hw, REG_ISR);
if (0 == status)
return IRQ_NONE;
/* link event */
if (status & ISR_PHY)
atl2_clear_phy_int(adapter);
/* clear ISR status, and Enable CMB DMA/Disable Interrupt */
ATL2_WRITE_REG(hw, REG_ISR, status | ISR_DIS_INT);
/* check if PCIE PHY Link down */
if (status & ISR_PHY_LINKDOWN) {
if (netif_running(adapter->netdev)) { /* reset MAC */
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
}
/* check if DMA read/write error? */
if (status & (ISR_DMAR_TO_RST | ISR_DMAW_TO_RST)) {
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
/* link event */
if (status & (ISR_PHY | ISR_MANUAL)) {
adapter->netdev->stats.tx_carrier_errors++;
atl2_check_for_link(adapter);
}
/* transmit event */
if (status & ISR_TX_EVENT)
atl2_intr_tx(adapter);
/* rx exception */
if (status & ISR_RX_EVENT)
atl2_intr_rx(adapter);
/* re-enable Interrupt */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return IRQ_HANDLED;
}
static int atl2_request_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int flags, err = 0;
flags = IRQF_SHARED;
adapter->have_msi = true;
err = pci_enable_msi(adapter->pdev);
if (err)
adapter->have_msi = false;
if (adapter->have_msi)
flags &= ~IRQF_SHARED;
return request_irq(adapter->pdev->irq, atl2_intr, flags, netdev->name,
netdev);
}
/**
* atl2_free_ring_resources - Free Tx / RX descriptor Resources
* @adapter: board private structure
*
* Free all transmit software resources
*/
static void atl2_free_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
pci_free_consistent(pdev, adapter->ring_size, adapter->ring_vir_addr,
adapter->ring_dma);
}
/**
* atl2_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
*/
static int atl2_open(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
int err;
u32 val;
/* disallow open during test */
if (test_bit(__ATL2_TESTING, &adapter->flags))
return -EBUSY;
/* allocate transmit descriptors */
err = atl2_setup_ring_resources(adapter);
if (err)
return err;
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
goto err_init_hw;
}
/* hardware has been reset, we need to reload some things */
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
atl2_restore_vlan(adapter);
if (atl2_configure(adapter)) {
err = -EIO;
goto err_config;
}
err = atl2_request_irq(adapter);
if (err)
goto err_req_irq;
clear_bit(__ATL2_DOWN, &adapter->flags);
mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + 4*HZ));
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL,
val | MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
return 0;
err_init_hw:
err_req_irq:
err_config:
atl2_free_ring_resources(adapter);
atl2_reset_hw(&adapter->hw);
return err;
}
static void atl2_down(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
set_bit(__ATL2_DOWN, &adapter->flags);
netif_tx_disable(netdev);
/* reset MAC to disable all RX/TX */
atl2_reset_hw(&adapter->hw);
msleep(1);
atl2_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
clear_bit(0, &adapter->cfg_phy);
netif_carrier_off(netdev);
adapter->link_speed = SPEED_0;
adapter->link_duplex = -1;
}
static void atl2_free_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
#ifdef CONFIG_PCI_MSI
if (adapter->have_msi)
pci_disable_msi(adapter->pdev);
#endif
}
/**
* atl2_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
*/
static int atl2_close(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
atl2_free_irq(adapter);
atl2_free_ring_resources(adapter);
return 0;
}
static inline int TxsFreeUnit(struct atl2_adapter *adapter)
{
u32 txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
return (adapter->txs_next_clear >= txs_write_ptr) ?
(int) (adapter->txs_ring_size - adapter->txs_next_clear +
txs_write_ptr - 1) :
(int) (txs_write_ptr - adapter->txs_next_clear - 1);
}
static inline int TxdFreeBytes(struct atl2_adapter *adapter)
{
u32 txd_read_ptr = (u32)atomic_read(&adapter->txd_read_ptr);
return (adapter->txd_write_ptr >= txd_read_ptr) ?
(int) (adapter->txd_ring_size - adapter->txd_write_ptr +
txd_read_ptr - 1) :
(int) (txd_read_ptr - adapter->txd_write_ptr - 1);
}
static netdev_tx_t atl2_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct tx_pkt_header *txph;
u32 offset, copy_len;
int txs_unused;
int txbuf_unused;
if (test_bit(__ATL2_DOWN, &adapter->flags)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (unlikely(skb->len <= 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
txs_unused = TxsFreeUnit(adapter);
txbuf_unused = TxdFreeBytes(adapter);
if (skb->len + sizeof(struct tx_pkt_header) + 4 > txbuf_unused ||
txs_unused < 1) {
/* not enough resources */
netif_stop_queue(netdev);
return NETDEV_TX_BUSY;
}
offset = adapter->txd_write_ptr;
txph = (struct tx_pkt_header *) (((u8 *)adapter->txd_ring) + offset);
*(u32 *)txph = 0;
txph->pkt_size = skb->len;
offset += 4;
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
copy_len = adapter->txd_ring_size - offset;
if (copy_len >= skb->len) {
memcpy(((u8 *)adapter->txd_ring) + offset, skb->data, skb->len);
offset += ((u32)(skb->len + 3) & ~3);
} else {
memcpy(((u8 *)adapter->txd_ring)+offset, skb->data, copy_len);
memcpy((u8 *)adapter->txd_ring, skb->data+copy_len,
skb->len-copy_len);
offset = ((u32)(skb->len-copy_len + 3) & ~3);
}
#ifdef NETIF_F_HW_VLAN_CTAG_TX
if (skb_vlan_tag_present(skb)) {
u16 vlan_tag = skb_vlan_tag_get(skb);
vlan_tag = (vlan_tag << 4) |
(vlan_tag >> 13) |
((vlan_tag >> 9) & 0x8);
txph->ins_vlan = 1;
txph->vlan = vlan_tag;
}
#endif
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
adapter->txd_write_ptr = offset;
/* clear txs before send */
adapter->txs_ring[adapter->txs_next_clear].update = 0;
if (++adapter->txs_next_clear == adapter->txs_ring_size)
adapter->txs_next_clear = 0;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_TXD_WR_IDX,
(adapter->txd_write_ptr >> 2));
mmiowb();
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/**
* atl2_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
*/
static int atl2_change_mtu(struct net_device *netdev, int new_mtu)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
if ((new_mtu < 40) || (new_mtu > (ETH_DATA_LEN + VLAN_SIZE)))
return -EINVAL;
/* set MTU */
if (hw->max_frame_size != new_mtu) {
netdev->mtu = new_mtu;
ATL2_WRITE_REG(hw, REG_MTU, new_mtu + ENET_HEADER_SIZE +
VLAN_SIZE + ETHERNET_FCS_SIZE);
}
return 0;
}
/**
* atl2_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
*/
static int atl2_set_mac(struct net_device *netdev, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
if (netif_running(netdev))
return -EBUSY;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac_addr, addr->sa_data, netdev->addr_len);
atl2_set_mac_addr(&adapter->hw);
return 0;
}
static int atl2_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
unsigned long flags;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = 0;
break;
case SIOCGMIIREG:
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_read_phy_reg(&adapter->hw,
data->reg_num & 0x1F, &data->val_out)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
case SIOCSMIIREG:
if (data->reg_num & ~(0x1F))
return -EFAULT;
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_write_phy_reg(&adapter->hw, data->reg_num,
data->val_in)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int atl2_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return atl2_mii_ioctl(netdev, ifr, cmd);
#ifdef ETHTOOL_OPS_COMPAT
case SIOCETHTOOL:
return ethtool_ioctl(ifr);
#endif
default:
return -EOPNOTSUPP;
}
}
/**
* atl2_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
*/
static void atl2_tx_timeout(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
schedule_work(&adapter->reset_task);
}
/**
* atl2_watchdog - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_watchdog(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
u32 drop_rxd, drop_rxs;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
drop_rxd = ATL2_READ_REG(&adapter->hw, REG_STS_RXD_OV);
drop_rxs = ATL2_READ_REG(&adapter->hw, REG_STS_RXS_OV);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
adapter->netdev->stats.rx_over_errors += drop_rxd + drop_rxs;
/* Reset the timer */
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 4 * HZ));
}
}
/**
* atl2_phy_config - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_phy_config(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
struct atl2_hw *hw = &adapter->hw;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_write_phy_reg(hw, MII_ADVERTISE, hw->mii_autoneg_adv_reg);
atl2_write_phy_reg(hw, MII_BMCR, MII_CR_RESET | MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
clear_bit(0, &adapter->cfg_phy);
}
static int atl2_up(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0;
u32 val;
/* hardware has been reset, we need to reload some things */
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
return err;
}
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
atl2_restore_vlan(adapter);
if (atl2_configure(adapter)) {
err = -EIO;
goto err_up;
}
clear_bit(__ATL2_DOWN, &adapter->flags);
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL, val |
MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
err_up:
return err;
}
static void atl2_reinit_locked(struct atl2_adapter *adapter)
{
WARN_ON(in_interrupt());
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
atl2_down(adapter);
atl2_up(adapter);
clear_bit(__ATL2_RESETTING, &adapter->flags);
}
static void atl2_reset_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
adapter = container_of(work, struct atl2_adapter, reset_task);
atl2_reinit_locked(adapter);
}
static void atl2_setup_mac_ctrl(struct atl2_adapter *adapter)
{
u32 value;
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
/* Config MAC CTRL Register */
value = MAC_CTRL_TX_EN | MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
/* duplex */
if (FULL_DUPLEX == adapter->link_duplex)
value |= MAC_CTRL_DUPLX;
/* flow control */
value |= (MAC_CTRL_TX_FLOW | MAC_CTRL_RX_FLOW);
/* PAD & CRC */
value |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
/* preamble length */
value |= (((u32)adapter->hw.preamble_len & MAC_CTRL_PRMLEN_MASK) <<
MAC_CTRL_PRMLEN_SHIFT);
/* vlan */
__atl2_vlan_mode(netdev->features, &value);
/* filter mode */
value |= MAC_CTRL_BC_EN;
if (netdev->flags & IFF_PROMISC)
value |= MAC_CTRL_PROMIS_EN;
else if (netdev->flags & IFF_ALLMULTI)
value |= MAC_CTRL_MC_ALL_EN;
/* half retry buffer */
value |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) << MAC_CTRL_HALF_LEFT_BUF_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
}
static int atl2_check_link(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
int ret_val;
u16 speed, duplex, phy_data;
int reconfig = 0;
/* MII_BMSR must read twise */
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
if (!(phy_data&BMSR_LSTATUS)) { /* link down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
return 0;
}
/* Link Up */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val)
return ret_val;
switch (hw->MediaType) {
case MEDIA_TYPE_100M_FULL:
if (speed != SPEED_100 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_100M_HALF:
if (speed != SPEED_100 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_FULL:
if (speed != SPEED_10 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_HALF:
if (speed != SPEED_10 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
}
/* link result is our setting */
if (reconfig == 0) {
if (adapter->link_speed != speed ||
adapter->link_duplex != duplex) {
adapter->link_speed = speed;
adapter->link_duplex = duplex;
atl2_setup_mac_ctrl(adapter);
printk(KERN_INFO "%s: %s NIC Link is Up<%d Mbps %s>\n",
atl2_driver_name, netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex");
}
if (!netif_carrier_ok(netdev)) { /* Link down -> Up */
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
return 0;
}
/* change original link status */
if (netif_carrier_ok(netdev)) {
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
/* auto-neg, insert timer to re-config phy
* (if interval smaller than 5 seconds, something strange) */
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
if (!test_and_set_bit(0, &adapter->cfg_phy))
mod_timer(&adapter->phy_config_timer,
round_jiffies(jiffies + 5 * HZ));
}
return 0;
}
/**
* atl2_link_chg_task - deal with link change event Out of interrupt context
*/
static void atl2_link_chg_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
unsigned long flags;
adapter = container_of(work, struct atl2_adapter, link_chg_task);
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_check_link(adapter);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
static void atl2_setup_pcicmd(struct pci_dev *pdev)
{
u16 cmd;
pci_read_config_word(pdev, PCI_COMMAND, &cmd);
if (cmd & PCI_COMMAND_INTX_DISABLE)
cmd &= ~PCI_COMMAND_INTX_DISABLE;
if (cmd & PCI_COMMAND_IO)
cmd &= ~PCI_COMMAND_IO;
if (0 == (cmd & PCI_COMMAND_MEMORY))
cmd |= PCI_COMMAND_MEMORY;
if (0 == (cmd & PCI_COMMAND_MASTER))
cmd |= PCI_COMMAND_MASTER;
pci_write_config_word(pdev, PCI_COMMAND, cmd);
/*
* some motherboards BIOS(PXE/EFI) driver may set PME
* while they transfer control to OS (Windows/Linux)
* so we should clear this bit before NIC work normally
*/
pci_write_config_dword(pdev, REG_PM_CTRLSTAT, 0);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void atl2_poll_controller(struct net_device *netdev)
{
disable_irq(netdev->irq);
atl2_intr(netdev->irq, netdev);
enable_irq(netdev->irq);
}
#endif
static const struct net_device_ops atl2_netdev_ops = {
.ndo_open = atl2_open,
.ndo_stop = atl2_close,
.ndo_start_xmit = atl2_xmit_frame,
.ndo_set_rx_mode = atl2_set_multi,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = atl2_set_mac,
.ndo_change_mtu = atl2_change_mtu,
.ndo_fix_features = atl2_fix_features,
.ndo_set_features = atl2_set_features,
.ndo_do_ioctl = atl2_ioctl,
.ndo_tx_timeout = atl2_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = atl2_poll_controller,
#endif
};
/**
* atl2_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in atl2_pci_tbl
*
* Returns 0 on success, negative on failure
*
* atl2_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
*/
static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
netdev->ethtool_ops = &atl2_ethtool_ops;
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
netdev->hw_features = NETIF_F_HW_VLAN_CTAG_RX;
netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX);
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
setup_timer(&adapter->watchdog_timer, atl2_watchdog,
(unsigned long)adapter);
setup_timer(&adapter->phy_config_timer, atl2_phy_config,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* atl2_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* atl2_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
*/
/* FIXME: write the original MAC address back in case it was changed from a
* BIOS-set value, as in atl1 -- CHS */
static void atl2_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
/* flush_scheduled work may reschedule our watchdog task, so
* explicitly disable watchdog tasks from being rescheduled */
set_bit(__ATL2_DOWN, &adapter->flags);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
cancel_work_sync(&adapter->reset_task);
cancel_work_sync(&adapter->link_chg_task);
unregister_netdev(netdev);
atl2_force_ps(&adapter->hw);
iounmap(adapter->hw.hw_addr);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
static int atl2_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u16 speed, duplex;
u32 ctrl = 0;
u32 wufc = adapter->wol;
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
if (ctrl & BMSR_LSTATUS)
wufc &= ~ATLX_WUFC_LNKC;
if (0 != (ctrl & BMSR_LSTATUS) && 0 != wufc) {
u32 ret_val;
/* get current link speed & duplex */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val) {
printk(KERN_DEBUG
"%s: get speed&duplex error while suspend\n",
atl2_driver_name);
goto wol_dis;
}
ctrl = 0;
/* turn on magic packet wol */
if (wufc & ATLX_WUFC_MAG)
ctrl |= (WOL_MAGIC_EN | WOL_MAGIC_PME_EN);
/* ignore Link Chg event when Link is up */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
/* Config MAC CTRL Register */
ctrl = MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
if (FULL_DUPLEX == adapter->link_duplex)
ctrl |= MAC_CTRL_DUPLX;
ctrl |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
ctrl |= (((u32)adapter->hw.preamble_len &
MAC_CTRL_PRMLEN_MASK) << MAC_CTRL_PRMLEN_SHIFT);
ctrl |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) <<
MAC_CTRL_HALF_LEFT_BUF_SHIFT);
if (wufc & ATLX_WUFC_MAG) {
/* magic packet maybe Broadcast&multicast&Unicast */
ctrl |= MAC_CTRL_BC_EN;
}
ATL2_WRITE_REG(hw, REG_MAC_CTRL, ctrl);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
if (0 == (ctrl&BMSR_LSTATUS) && 0 != (wufc&ATLX_WUFC_LNKC)) {
/* link is down, so only LINK CHG WOL event enable */
ctrl |= (WOL_LINK_CHG_EN | WOL_LINK_CHG_PME_EN);
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
wol_dis:
/* WOL disabled */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
atl2_force_ps(hw);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 0);
suspend_exit:
if (netif_running(netdev))
atl2_free_irq(adapter);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
#ifdef CONFIG_PM
static int atl2_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR
"atl2: Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
ATL2_READ_REG(&adapter->hw, REG_WOL_CTRL); /* clear WOL status */
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
ATL2_WRITE_REG(&adapter->hw, REG_WOL_CTRL, 0);
if (netif_running(netdev)) {
err = atl2_request_irq(adapter);
if (err)
return err;
}
atl2_reset_hw(&adapter->hw);
if (netif_running(netdev))
atl2_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void atl2_shutdown(struct pci_dev *pdev)
{
atl2_suspend(pdev, PMSG_SUSPEND);
}
static struct pci_driver atl2_driver = {
.name = atl2_driver_name,
.id_table = atl2_pci_tbl,
.probe = atl2_probe,
.remove = atl2_remove,
/* Power Management Hooks */
.suspend = atl2_suspend,
#ifdef CONFIG_PM
.resume = atl2_resume,
#endif
.shutdown = atl2_shutdown,
};
/**
* atl2_init_module - Driver Registration Routine
*
* atl2_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
*/
static int __init atl2_init_module(void)
{
printk(KERN_INFO "%s - version %s\n", atl2_driver_string,
atl2_driver_version);
printk(KERN_INFO "%s\n", atl2_copyright);
return pci_register_driver(&atl2_driver);
}
module_init(atl2_init_module);
/**
* atl2_exit_module - Driver Exit Cleanup Routine
*
* atl2_exit_module is called just before the driver is removed
* from memory.
*/
static void __exit atl2_exit_module(void)
{
pci_unregister_driver(&atl2_driver);
}
module_exit(atl2_exit_module);
static void atl2_read_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_read_config_word(adapter->pdev, reg, value);
}
static void atl2_write_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_write_config_word(adapter->pdev, reg, *value);
}
static int atl2_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
ecmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_TP);
ecmd->advertising = ADVERTISED_TP;
ecmd->advertising |= ADVERTISED_Autoneg;
ecmd->advertising |= hw->autoneg_advertised;
ecmd->port = PORT_TP;
ecmd->phy_address = 0;
ecmd->transceiver = XCVR_INTERNAL;
if (adapter->link_speed != SPEED_0) {
ethtool_cmd_speed_set(ecmd, adapter->link_speed);
if (adapter->link_duplex == FULL_DUPLEX)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
} else {
ethtool_cmd_speed_set(ecmd, SPEED_UNKNOWN);
ecmd->duplex = DUPLEX_UNKNOWN;
}
ecmd->autoneg = AUTONEG_ENABLE;
return 0;
}
static int atl2_set_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
if (ecmd->autoneg == AUTONEG_ENABLE) {
#define MY_ADV_MASK (ADVERTISE_10_HALF | \
ADVERTISE_10_FULL | \
ADVERTISE_100_HALF| \
ADVERTISE_100_FULL)
if ((ecmd->advertising & MY_ADV_MASK) == MY_ADV_MASK) {
hw->MediaType = MEDIA_TYPE_AUTO_SENSOR;
hw->autoneg_advertised = MY_ADV_MASK;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_FULL) {
hw->MediaType = MEDIA_TYPE_100M_FULL;
hw->autoneg_advertised = ADVERTISE_100_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_HALF) {
hw->MediaType = MEDIA_TYPE_100M_HALF;
hw->autoneg_advertised = ADVERTISE_100_HALF;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_FULL) {
hw->MediaType = MEDIA_TYPE_10M_FULL;
hw->autoneg_advertised = ADVERTISE_10_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_HALF) {
hw->MediaType = MEDIA_TYPE_10M_HALF;
hw->autoneg_advertised = ADVERTISE_10_HALF;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
ecmd->advertising = hw->autoneg_advertised |
ADVERTISED_TP | ADVERTISED_Autoneg;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
/* reset the link */
if (netif_running(adapter->netdev)) {
atl2_down(adapter);
atl2_up(adapter);
} else
atl2_reset_hw(&adapter->hw);
clear_bit(__ATL2_RESETTING, &adapter->flags);
return 0;
}
static u32 atl2_get_msglevel(struct net_device *netdev)
{
return 0;
}
/*
* It's sane for this to be empty, but we might want to take advantage of this.
*/
static void atl2_set_msglevel(struct net_device *netdev, u32 data)
{
}
static int atl2_get_regs_len(struct net_device *netdev)
{
#define ATL2_REGS_LEN 42
return sizeof(u32) * ATL2_REGS_LEN;
}
static void atl2_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *regs_buff = p;
u16 phy_data;
memset(p, 0, sizeof(u32) * ATL2_REGS_LEN);
regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id;
regs_buff[0] = ATL2_READ_REG(hw, REG_VPD_CAP);
regs_buff[1] = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
regs_buff[2] = ATL2_READ_REG(hw, REG_SPI_FLASH_CONFIG);
regs_buff[3] = ATL2_READ_REG(hw, REG_TWSI_CTRL);
regs_buff[4] = ATL2_READ_REG(hw, REG_PCIE_DEV_MISC_CTRL);
regs_buff[5] = ATL2_READ_REG(hw, REG_MASTER_CTRL);
regs_buff[6] = ATL2_READ_REG(hw, REG_MANUAL_TIMER_INIT);
regs_buff[7] = ATL2_READ_REG(hw, REG_IRQ_MODU_TIMER_INIT);
regs_buff[8] = ATL2_READ_REG(hw, REG_PHY_ENABLE);
regs_buff[9] = ATL2_READ_REG(hw, REG_CMBDISDMA_TIMER);
regs_buff[10] = ATL2_READ_REG(hw, REG_IDLE_STATUS);
regs_buff[11] = ATL2_READ_REG(hw, REG_MDIO_CTRL);
regs_buff[12] = ATL2_READ_REG(hw, REG_SERDES_LOCK);
regs_buff[13] = ATL2_READ_REG(hw, REG_MAC_CTRL);
regs_buff[14] = ATL2_READ_REG(hw, REG_MAC_IPG_IFG);
regs_buff[15] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
regs_buff[16] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR+4);
regs_buff[17] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE);
regs_buff[18] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE+4);
regs_buff[19] = ATL2_READ_REG(hw, REG_MAC_HALF_DUPLX_CTRL);
regs_buff[20] = ATL2_READ_REG(hw, REG_MTU);
regs_buff[21] = ATL2_READ_REG(hw, REG_WOL_CTRL);
regs_buff[22] = ATL2_READ_REG(hw, REG_SRAM_TXRAM_END);
regs_buff[23] = ATL2_READ_REG(hw, REG_DESC_BASE_ADDR_HI);
regs_buff[24] = ATL2_READ_REG(hw, REG_TXD_BASE_ADDR_LO);
regs_buff[25] = ATL2_READ_REG(hw, REG_TXD_MEM_SIZE);
regs_buff[26] = ATL2_READ_REG(hw, REG_TXS_BASE_ADDR_LO);
regs_buff[27] = ATL2_READ_REG(hw, REG_TXS_MEM_SIZE);
regs_buff[28] = ATL2_READ_REG(hw, REG_RXD_BASE_ADDR_LO);
regs_buff[29] = ATL2_READ_REG(hw, REG_RXD_BUF_NUM);
regs_buff[30] = ATL2_READ_REG(hw, REG_DMAR);
regs_buff[31] = ATL2_READ_REG(hw, REG_TX_CUT_THRESH);
regs_buff[32] = ATL2_READ_REG(hw, REG_DMAW);
regs_buff[33] = ATL2_READ_REG(hw, REG_PAUSE_ON_TH);
regs_buff[34] = ATL2_READ_REG(hw, REG_PAUSE_OFF_TH);
regs_buff[35] = ATL2_READ_REG(hw, REG_MB_TXD_WR_IDX);
regs_buff[36] = ATL2_READ_REG(hw, REG_MB_RXD_RD_IDX);
regs_buff[38] = ATL2_READ_REG(hw, REG_ISR);
regs_buff[39] = ATL2_READ_REG(hw, REG_IMR);
atl2_read_phy_reg(hw, MII_BMCR, &phy_data);
regs_buff[40] = (u32)phy_data;
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
regs_buff[41] = (u32)phy_data;
}
static int atl2_get_eeprom_len(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (!atl2_check_eeprom_exist(&adapter->hw))
return 512;
else
return 0;
}
static int atl2_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
int first_dword, last_dword;
int ret_val = 0;
int i;
if (eeprom->len == 0)
return -EINVAL;
if (atl2_check_eeprom_exist(hw))
return -EINVAL;
eeprom->magic = hw->vendor_id | (hw->device_id << 16);
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(sizeof(u32) * (last_dword - first_dword + 1),
GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
for (i = first_dword; i < last_dword; i++) {
if (!atl2_read_eeprom(hw, i*4, &(eeprom_buff[i-first_dword]))) {
ret_val = -EIO;
goto free;
}
}
memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 3),
eeprom->len);
free:
kfree(eeprom_buff);
return ret_val;
}
static int atl2_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
u32 *ptr;
int max_len, first_dword, last_dword, ret_val = 0;
int i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16)))
return -EFAULT;
max_len = 512;
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = eeprom_buff;
if (eeprom->offset & 3) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
if (!atl2_read_eeprom(hw, first_dword*4, &(eeprom_buff[0]))) {
ret_val = -EIO;
goto out;
}
ptr++;
}
if (((eeprom->offset + eeprom->len) & 3)) {
/*
* need read/modify/write of last changed EEPROM word
* only the first byte of the word is being modified
*/
if (!atl2_read_eeprom(hw, last_dword * 4,
&(eeprom_buff[last_dword - first_dword]))) {
ret_val = -EIO;
goto out;
}
}
/* Device's eeprom is always little-endian, word addressable */
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_dword - first_dword + 1; i++) {
if (!atl2_write_eeprom(hw, ((first_dword+i)*4), eeprom_buff[i])) {
ret_val = -EIO;
goto out;
}
}
out:
kfree(eeprom_buff);
return ret_val;
}
static void atl2_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
strlcpy(drvinfo->driver, atl2_driver_name, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, atl2_driver_version,
sizeof(drvinfo->version));
strlcpy(drvinfo->fw_version, "L2", sizeof(drvinfo->fw_version));
strlcpy(drvinfo->bus_info, pci_name(adapter->pdev),
sizeof(drvinfo->bus_info));
}
static void atl2_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
wol->supported = WAKE_MAGIC;
wol->wolopts = 0;
if (adapter->wol & ATLX_WUFC_EX)
wol->wolopts |= WAKE_UCAST;
if (adapter->wol & ATLX_WUFC_MC)
wol->wolopts |= WAKE_MCAST;
if (adapter->wol & ATLX_WUFC_BC)
wol->wolopts |= WAKE_BCAST;
if (adapter->wol & ATLX_WUFC_MAG)
wol->wolopts |= WAKE_MAGIC;
if (adapter->wol & ATLX_WUFC_LNKC)
wol->wolopts |= WAKE_PHY;
}
static int atl2_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE))
return -EOPNOTSUPP;
if (wol->wolopts & (WAKE_UCAST | WAKE_BCAST | WAKE_MCAST))
return -EOPNOTSUPP;
/* these settings will always override what we currently have */
adapter->wol = 0;
if (wol->wolopts & WAKE_MAGIC)
adapter->wol |= ATLX_WUFC_MAG;
if (wol->wolopts & WAKE_PHY)
adapter->wol |= ATLX_WUFC_LNKC;
return 0;
}
static int atl2_nway_reset(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
atl2_reinit_locked(adapter);
return 0;
}
static const struct ethtool_ops atl2_ethtool_ops = {
.get_settings = atl2_get_settings,
.set_settings = atl2_set_settings,
.get_drvinfo = atl2_get_drvinfo,
.get_regs_len = atl2_get_regs_len,
.get_regs = atl2_get_regs,
.get_wol = atl2_get_wol,
.set_wol = atl2_set_wol,
.get_msglevel = atl2_get_msglevel,
.set_msglevel = atl2_set_msglevel,
.nway_reset = atl2_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = atl2_get_eeprom_len,
.get_eeprom = atl2_get_eeprom,
.set_eeprom = atl2_set_eeprom,
};
#define LBYTESWAP(a) ((((a) & 0x00ff00ff) << 8) | \
(((a) & 0xff00ff00) >> 8))
#define LONGSWAP(a) ((LBYTESWAP(a) << 16) | (LBYTESWAP(a) >> 16))
#define SHORTSWAP(a) (((a) << 8) | ((a) >> 8))
/*
* Reset the transmit and receive units; mask and clear all interrupts.
*
* hw - Struct containing variables accessed by shared code
* return : 0 or idle status (if error)
*/
static s32 atl2_reset_hw(struct atl2_hw *hw)
{
u32 icr;
u16 pci_cfg_cmd_word;
int i;
/* Workaround for PCI problem when BIOS sets MMRBC incorrectly. */
atl2_read_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
if ((pci_cfg_cmd_word &
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) !=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) {
pci_cfg_cmd_word |=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER);
atl2_write_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
}
/* Clear Interrupt mask to stop board from generating
* interrupts & Clear any pending interrupt events
*/
/* FIXME */
/* ATL2_WRITE_REG(hw, REG_IMR, 0); */
/* ATL2_WRITE_REG(hw, REG_ISR, 0xffffffff); */
/* Issue Soft Reset to the MAC. This will reset the chip's
* transmit, receive, DMA. It will not effect
* the current PCI configuration. The global reset bit is self-
* clearing, and should clear within a microsecond.
*/
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_SOFT_RST);
wmb();
msleep(1); /* delay about 1ms */
/* Wait at least 10ms for All module to be Idle */
for (i = 0; i < 10; i++) {
icr = ATL2_READ_REG(hw, REG_IDLE_STATUS);
if (!icr)
break;
msleep(1); /* delay 1 ms */
cpu_relax();
}
if (icr)
return icr;
return 0;
}
#define CUSTOM_SPI_CS_SETUP 2
#define CUSTOM_SPI_CLK_HI 2
#define CUSTOM_SPI_CLK_LO 2
#define CUSTOM_SPI_CS_HOLD 2
#define CUSTOM_SPI_CS_HI 3
static struct atl2_spi_flash_dev flash_table[] =
{
/* MFR WRSR READ PROGRAM WREN WRDI RDSR RDID SECTOR_ERASE CHIP_ERASE */
{"Atmel", 0x0, 0x03, 0x02, 0x06, 0x04, 0x05, 0x15, 0x52, 0x62 },
{"SST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0x90, 0x20, 0x60 },
{"ST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0xAB, 0xD8, 0xC7 },
};
static bool atl2_spi_read(struct atl2_hw *hw, u32 addr, u32 *buf)
{
int i;
u32 value;
ATL2_WRITE_REG(hw, REG_SPI_DATA, 0);
ATL2_WRITE_REG(hw, REG_SPI_ADDR, addr);
value = SPI_FLASH_CTRL_WAIT_READY |
(CUSTOM_SPI_CS_SETUP & SPI_FLASH_CTRL_CS_SETUP_MASK) <<
SPI_FLASH_CTRL_CS_SETUP_SHIFT |
(CUSTOM_SPI_CLK_HI & SPI_FLASH_CTRL_CLK_HI_MASK) <<
SPI_FLASH_CTRL_CLK_HI_SHIFT |
(CUSTOM_SPI_CLK_LO & SPI_FLASH_CTRL_CLK_LO_MASK) <<
SPI_FLASH_CTRL_CLK_LO_SHIFT |
(CUSTOM_SPI_CS_HOLD & SPI_FLASH_CTRL_CS_HOLD_MASK) <<
SPI_FLASH_CTRL_CS_HOLD_SHIFT |
(CUSTOM_SPI_CS_HI & SPI_FLASH_CTRL_CS_HI_MASK) <<
SPI_FLASH_CTRL_CS_HI_SHIFT |
(0x1 & SPI_FLASH_CTRL_INS_MASK) << SPI_FLASH_CTRL_INS_SHIFT;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
value |= SPI_FLASH_CTRL_START;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
for (i = 0; i < 10; i++) {
msleep(1);
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (!(value & SPI_FLASH_CTRL_START))
break;
}
if (value & SPI_FLASH_CTRL_START)
return false;
*buf = ATL2_READ_REG(hw, REG_SPI_DATA);
return true;
}
/*
* get_permanent_address
* return 0 if get valid mac address,
*/
static int get_permanent_address(struct atl2_hw *hw)
{
u32 Addr[2];
u32 i, Control;
u16 Register;
u8 EthAddr[ETH_ALEN];
bool KeyValid;
if (is_valid_ether_addr(hw->perm_mac_addr))
return 0;
Addr[0] = 0;
Addr[1] = 0;
if (!atl2_check_eeprom_exist(hw)) { /* eeprom exists */
Register = 0;
KeyValid = false;
/* Read out all EEPROM content */
i = 0;
while (1) {
if (atl2_read_eeprom(hw, i + 0x100, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register ==
(REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
/* assume data end while encount an invalid KEYWORD */
break;
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
return 1;
}
/* see if SPI flash exists? */
Addr[0] = 0;
Addr[1] = 0;
Register = 0;
KeyValid = false;
i = 0;
while (1) {
if (atl2_spi_read(hw, i + 0x1f000, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register == (REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
break; /* data end */
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *)&Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
/* maybe MAC-address is from BIOS */
Addr[0] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
Addr[1] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR + 4);
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
return 1;
}
/*
* Reads the adapter's MAC address from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_read_mac_addr(struct atl2_hw *hw)
{
if (get_permanent_address(hw)) {
/* for test */
/* FIXME: shouldn't we use eth_random_addr() here? */
hw->perm_mac_addr[0] = 0x00;
hw->perm_mac_addr[1] = 0x13;
hw->perm_mac_addr[2] = 0x74;
hw->perm_mac_addr[3] = 0x00;
hw->perm_mac_addr[4] = 0x5c;
hw->perm_mac_addr[5] = 0x38;
}
memcpy(hw->mac_addr, hw->perm_mac_addr, ETH_ALEN);
return 0;
}
/*
* Hashes an address to determine its location in the multicast table
*
* hw - Struct containing variables accessed by shared code
* mc_addr - the multicast address to hash
*
* atl2_hash_mc_addr
* purpose
* set hash value for a multicast address
* hash calcu processing :
* 1. calcu 32bit CRC for multicast address
* 2. reverse crc with MSB to LSB
*/
static u32 atl2_hash_mc_addr(struct atl2_hw *hw, u8 *mc_addr)
{
u32 crc32, value;
int i;
value = 0;
crc32 = ether_crc_le(6, mc_addr);
for (i = 0; i < 32; i++)
value |= (((crc32 >> i) & 1) << (31 - i));
return value;
}
/*
* Sets the bit in the multicast table corresponding to the hash value.
*
* hw - Struct containing variables accessed by shared code
* hash_value - Multicast address hash value
*/
static void atl2_hash_set(struct atl2_hw *hw, u32 hash_value)
{
u32 hash_bit, hash_reg;
u32 mta;
/* The HASH Table is a register array of 2 32-bit registers.
* It is treated like an array of 64 bits. We want to set
* bit BitArray[hash_value]. So we figure out what register
* the bit is in, read it, OR in the new bit, then write
* back the new value. The register is determined by the
* upper 7 bits of the hash value and the bit within that
* register are determined by the lower 5 bits of the value.
*/
hash_reg = (hash_value >> 31) & 0x1;
hash_bit = (hash_value >> 26) & 0x1F;
mta = ATL2_READ_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg);
mta |= (1 << hash_bit);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg, mta);
}
/*
* atl2_init_pcie - init PCIE module
*/
static void atl2_init_pcie(struct atl2_hw *hw)
{
u32 value;
value = LTSSM_TEST_MODE_DEF;
ATL2_WRITE_REG(hw, REG_LTSSM_TEST_MODE, value);
value = PCIE_DLL_TX_CTRL1_DEF;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, value);
}
static void atl2_init_flash_opcode(struct atl2_hw *hw)
{
if (hw->flash_vendor >= ARRAY_SIZE(flash_table))
hw->flash_vendor = 0; /* ATMEL */
/* Init OP table */
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_PROGRAM,
flash_table[hw->flash_vendor].cmdPROGRAM);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_SC_ERASE,
flash_table[hw->flash_vendor].cmdSECTOR_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_CHIP_ERASE,
flash_table[hw->flash_vendor].cmdCHIP_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDID,
flash_table[hw->flash_vendor].cmdRDID);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WREN,
flash_table[hw->flash_vendor].cmdWREN);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDSR,
flash_table[hw->flash_vendor].cmdRDSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WRSR,
flash_table[hw->flash_vendor].cmdWRSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_READ,
flash_table[hw->flash_vendor].cmdREAD);
}
/********************************************************************
* Performs basic configuration of the adapter.
*
* hw - Struct containing variables accessed by shared code
* Assumes that the controller has previously been reset and is in a
* post-reset uninitialized state. Initializes multicast table,
* and Calls routines to setup link
* Leaves the transmit and receive units disabled and uninitialized.
********************************************************************/
static s32 atl2_init_hw(struct atl2_hw *hw)
{
u32 ret_val = 0;
atl2_init_pcie(hw);
/* Zero out the Multicast HASH table */
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
atl2_init_flash_opcode(hw);
ret_val = atl2_phy_init(hw);
return ret_val;
}
/*
* Detects the current speed and duplex settings of the hardware.
*
* hw - Struct containing variables accessed by shared code
* speed - Speed of the connection
* duplex - Duplex setting of the connection
*/
static s32 atl2_get_speed_and_duplex(struct atl2_hw *hw, u16 *speed,
u16 *duplex)
{
s32 ret_val;
u16 phy_data;
/* Read PHY Specific Status Register (17) */
ret_val = atl2_read_phy_reg(hw, MII_ATLX_PSSR, &phy_data);
if (ret_val)
return ret_val;
if (!(phy_data & MII_ATLX_PSSR_SPD_DPLX_RESOLVED))
return ATLX_ERR_PHY_RES;
switch (phy_data & MII_ATLX_PSSR_SPEED) {
case MII_ATLX_PSSR_100MBS:
*speed = SPEED_100;
break;
case MII_ATLX_PSSR_10MBS:
*speed = SPEED_10;
break;
default:
return ATLX_ERR_PHY_SPEED;
}
if (phy_data & MII_ATLX_PSSR_DPLX)
*duplex = FULL_DUPLEX;
else
*duplex = HALF_DUPLEX;
return 0;
}
/*
* Reads the value from a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to read
*/
static s32 atl2_read_phy_reg(struct atl2_hw *hw, u16 reg_addr, u16 *phy_data)
{
u32 val;
int i;
val = ((u32)(reg_addr & MDIO_REG_ADDR_MASK)) << MDIO_REG_ADDR_SHIFT |
MDIO_START |
MDIO_SUP_PREAMBLE |
MDIO_RW |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY))) {
*phy_data = (u16)val;
return 0;
}
return ATLX_ERR_PHY;
}
/*
* Writes a value to a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to write
* data - data to write to the PHY
*/
static s32 atl2_write_phy_reg(struct atl2_hw *hw, u32 reg_addr, u16 phy_data)
{
int i;
u32 val;
val = ((u32)(phy_data & MDIO_DATA_MASK)) << MDIO_DATA_SHIFT |
(reg_addr & MDIO_REG_ADDR_MASK) << MDIO_REG_ADDR_SHIFT |
MDIO_SUP_PREAMBLE |
MDIO_START |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY)))
return 0;
return ATLX_ERR_PHY;
}
/*
* Configures PHY autoneg and flow control advertisement settings
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_phy_setup_autoneg_adv(struct atl2_hw *hw)
{
s32 ret_val;
s16 mii_autoneg_adv_reg;
/* Read the MII Auto-Neg Advertisement Register (Address 4). */
mii_autoneg_adv_reg = MII_AR_DEFAULT_CAP_MASK;
/* Need to parse autoneg_advertised and set up
* the appropriate PHY registers. First we will parse for
* autoneg_advertised software override. Since we can advertise
* a plethora of combinations, we need to check each bit
* individually.
*/
/* First we clear all the 10/100 mb speed bits in the Auto-Neg
* Advertisement Register (Address 4) and the 1000 mb speed bits in
* the 1000Base-T Control Register (Address 9). */
mii_autoneg_adv_reg &= ~MII_AR_SPEED_MASK;
/* Need to parse MediaType and setup the
* appropriate PHY registers. */
switch (hw->MediaType) {
case MEDIA_TYPE_AUTO_SENSOR:
mii_autoneg_adv_reg |=
(MII_AR_10T_HD_CAPS |
MII_AR_10T_FD_CAPS |
MII_AR_100TX_HD_CAPS|
MII_AR_100TX_FD_CAPS);
hw->autoneg_advertised =
ADVERTISE_10_HALF |
ADVERTISE_10_FULL |
ADVERTISE_100_HALF|
ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_FULL:
mii_autoneg_adv_reg |= MII_AR_100TX_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_HALF:
mii_autoneg_adv_reg |= MII_AR_100TX_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_HALF;
break;
case MEDIA_TYPE_10M_FULL:
mii_autoneg_adv_reg |= MII_AR_10T_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_FULL;
break;
default:
mii_autoneg_adv_reg |= MII_AR_10T_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_HALF;
break;
}
/* flow control fixed to enable all */
mii_autoneg_adv_reg |= (MII_AR_ASM_DIR | MII_AR_PAUSE);
hw->mii_autoneg_adv_reg = mii_autoneg_adv_reg;
ret_val = atl2_write_phy_reg(hw, MII_ADVERTISE, mii_autoneg_adv_reg);
if (ret_val)
return ret_val;
return 0;
}
/*
* Resets the PHY and make all config validate
*
* hw - Struct containing variables accessed by shared code
*
* Sets bit 15 and 12 of the MII Control regiser (for F001 bug)
*/
static s32 atl2_phy_commit(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_data;
phy_data = MII_CR_RESET | MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
ret_val = atl2_write_phy_reg(hw, MII_BMCR, phy_data);
if (ret_val) {
u32 val;
int i;
/* pcie serdes link may be down ! */
for (i = 0; i < 25; i++) {
msleep(1);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
}
if (0 != (val & (MDIO_START | MDIO_BUSY))) {
printk(KERN_ERR "atl2: PCIe link down for at least 25ms !\n");
return ret_val;
}
}
return 0;
}
static s32 atl2_phy_init(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_val;
if (hw->phy_configured)
return 0;
/* Enable PHY */
ATL2_WRITE_REGW(hw, REG_PHY_ENABLE, 1);
ATL2_WRITE_FLUSH(hw);
msleep(1);
/* check if the PHY is in powersaving mode */
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
/* 024E / 124E 0r 0274 / 1274 ? */
if (phy_val & 0x1000) {
phy_val &= ~0x1000;
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val);
}
msleep(1);
/*Enable PHY LinkChange Interrupt */
ret_val = atl2_write_phy_reg(hw, 18, 0xC00);
if (ret_val)
return ret_val;
/* setup AutoNeg parameters */
ret_val = atl2_phy_setup_autoneg_adv(hw);
if (ret_val)
return ret_val;
/* SW.Reset & En-Auto-Neg to restart Auto-Neg */
ret_val = atl2_phy_commit(hw);
if (ret_val)
return ret_val;
hw->phy_configured = true;
return ret_val;
}
static void atl2_set_mac_addr(struct atl2_hw *hw)
{
u32 value;
/* 00-0B-6A-F6-00-DC
* 0: 6AF600DC 1: 000B
* low dword */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 0, value);
/* hight dword */
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 1, value);
}
/*
* check_eeprom_exist
* return 0 if eeprom exist
*/
static int atl2_check_eeprom_exist(struct atl2_hw *hw)
{
u32 value;
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (value & SPI_FLASH_CTRL_EN_VPD) {
value &= ~SPI_FLASH_CTRL_EN_VPD;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
}
value = ATL2_READ_REGW(hw, REG_PCIE_CAP_LIST);
return ((value & 0xFF00) == 0x6C00) ? 0 : 1;
}
/* FIXME: This doesn't look right. -- CHS */
static bool atl2_write_eeprom(struct atl2_hw *hw, u32 offset, u32 value)
{
return true;
}
static bool atl2_read_eeprom(struct atl2_hw *hw, u32 Offset, u32 *pValue)
{
int i;
u32 Control;
if (Offset & 0x3)
return false; /* address do not align */
ATL2_WRITE_REG(hw, REG_VPD_DATA, 0);
Control = (Offset & VPD_CAP_VPD_ADDR_MASK) << VPD_CAP_VPD_ADDR_SHIFT;
ATL2_WRITE_REG(hw, REG_VPD_CAP, Control);
for (i = 0; i < 10; i++) {
msleep(2);
Control = ATL2_READ_REG(hw, REG_VPD_CAP);
if (Control & VPD_CAP_VPD_FLAG)
break;
}
if (Control & VPD_CAP_VPD_FLAG) {
*pValue = ATL2_READ_REG(hw, REG_VPD_DATA);
return true;
}
return false; /* timeout */
}
static void atl2_force_ps(struct atl2_hw *hw)
{
u16 phy_val;
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val | 0x1000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 2);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0x3000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 3);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0);
}
/* This is the only thing that needs to be changed to adjust the
* maximum number of ports that the driver can manage.
*/
#define ATL2_MAX_NIC 4
#define OPTION_UNSET -1
#define OPTION_DISABLED 0
#define OPTION_ENABLED 1
/* All parameters are treated the same, as an integer array of values.
* This macro just reduces the need to repeat the same declaration code
* over and over (plus this helps to avoid typo bugs).
*/
#define ATL2_PARAM_INIT {[0 ... ATL2_MAX_NIC] = OPTION_UNSET}
#ifndef module_param_array
/* Module Parameters are always initialized to -1, so that the driver
* can tell the difference between no user specified value or the
* user asking for the default value.
* The true default values are loaded in when atl2_check_options is called.
*
* This is a GCC extension to ANSI C.
* See the item "Labeled Elements in Initializers" in the section
* "Extensions to the C Language Family" of the GCC documentation.
*/
#define ATL2_PARAM(X, desc) \
static const int X[ATL2_MAX_NIC + 1] = ATL2_PARAM_INIT; \
MODULE_PARM(X, "1-" __MODULE_STRING(ATL2_MAX_NIC) "i"); \
MODULE_PARM_DESC(X, desc);
#else
#define ATL2_PARAM(X, desc) \
static int X[ATL2_MAX_NIC+1] = ATL2_PARAM_INIT; \
static unsigned int num_##X; \
module_param_array_named(X, X, int, &num_##X, 0); \
MODULE_PARM_DESC(X, desc);
#endif
/*
* Transmit Memory Size
* Valid Range: 64-2048
* Default Value: 128
*/
#define ATL2_MIN_TX_MEMSIZE 4 /* 4KB */
#define ATL2_MAX_TX_MEMSIZE 64 /* 64KB */
#define ATL2_DEFAULT_TX_MEMSIZE 8 /* 8KB */
ATL2_PARAM(TxMemSize, "Bytes of Transmit Memory");
/*
* Receive Memory Block Count
* Valid Range: 16-512
* Default Value: 128
*/
#define ATL2_MIN_RXD_COUNT 16
#define ATL2_MAX_RXD_COUNT 512
#define ATL2_DEFAULT_RXD_COUNT 64
ATL2_PARAM(RxMemBlock, "Number of receive memory block");
/*
* User Specified MediaType Override
*
* Valid Range: 0-5
* - 0 - auto-negotiate at all supported speeds
* - 1 - only link at 1000Mbps Full Duplex
* - 2 - only link at 100Mbps Full Duplex
* - 3 - only link at 100Mbps Half Duplex
* - 4 - only link at 10Mbps Full Duplex
* - 5 - only link at 10Mbps Half Duplex
* Default Value: 0
*/
ATL2_PARAM(MediaType, "MediaType Select");
/*
* Interrupt Moderate Timer in units of 2048 ns (~2 us)
* Valid Range: 10-65535
* Default Value: 45000(90ms)
*/
#define INT_MOD_DEFAULT_CNT 100 /* 200us */
#define INT_MOD_MAX_CNT 65000
#define INT_MOD_MIN_CNT 50
ATL2_PARAM(IntModTimer, "Interrupt Moderator Timer");
/*
* FlashVendor
* Valid Range: 0-2
* 0 - Atmel
* 1 - SST
* 2 - ST
*/
ATL2_PARAM(FlashVendor, "SPI Flash Vendor");
#define AUTONEG_ADV_DEFAULT 0x2F
#define AUTONEG_ADV_MASK 0x2F
#define FLOW_CONTROL_DEFAULT FLOW_CONTROL_FULL
#define FLASH_VENDOR_DEFAULT 0
#define FLASH_VENDOR_MIN 0
#define FLASH_VENDOR_MAX 2
struct atl2_option {
enum { enable_option, range_option, list_option } type;
char *name;
char *err;
int def;
union {
struct { /* range_option info */
int min;
int max;
} r;
struct { /* list_option info */
int nr;
struct atl2_opt_list { int i; char *str; } *p;
} l;
} arg;
};
static int atl2_validate_option(int *value, struct atl2_option *opt)
{
int i;
struct atl2_opt_list *ent;
if (*value == OPTION_UNSET) {
*value = opt->def;
return 0;
}
switch (opt->type) {
case enable_option:
switch (*value) {
case OPTION_ENABLED:
printk(KERN_INFO "%s Enabled\n", opt->name);
return 0;
case OPTION_DISABLED:
printk(KERN_INFO "%s Disabled\n", opt->name);
return 0;
}
break;
case range_option:
if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) {
printk(KERN_INFO "%s set to %i\n", opt->name, *value);
return 0;
}
break;
case list_option:
for (i = 0; i < opt->arg.l.nr; i++) {
ent = &opt->arg.l.p[i];
if (*value == ent->i) {
if (ent->str[0] != '\0')
printk(KERN_INFO "%s\n", ent->str);
return 0;
}
}
break;
default:
BUG();
}
printk(KERN_INFO "Invalid %s specified (%i) %s\n",
opt->name, *value, opt->err);
*value = opt->def;
return -1;
}
/**
* atl2_check_options - Range Checking for Command Line Parameters
* @adapter: board private structure
*
* This routine checks all command line parameters for valid user
* input. If an invalid value is given, or if no user specified
* value exists, a default value is used. The final value is stored
* in a variable in the adapter structure.
*/
static void atl2_check_options(struct atl2_adapter *adapter)
{
int val;
struct atl2_option opt;
int bd = adapter->bd_number;
if (bd >= ATL2_MAX_NIC) {
printk(KERN_NOTICE "Warning: no configuration for board #%i\n",
bd);
printk(KERN_NOTICE "Using defaults for all values\n");
#ifndef module_param_array
bd = ATL2_MAX_NIC;
#endif
}
/* Bytes of Transmit Memory */
opt.type = range_option;
opt.name = "Bytes of Transmit Memory";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_TX_MEMSIZE);
opt.def = ATL2_DEFAULT_TX_MEMSIZE;
opt.arg.r.min = ATL2_MIN_TX_MEMSIZE;
opt.arg.r.max = ATL2_MAX_TX_MEMSIZE;
#ifdef module_param_array
if (num_TxMemSize > bd) {
#endif
val = TxMemSize[bd];
atl2_validate_option(&val, &opt);
adapter->txd_ring_size = ((u32) val) * 1024;
#ifdef module_param_array
} else
adapter->txd_ring_size = ((u32)opt.def) * 1024;
#endif
/* txs ring size: */
adapter->txs_ring_size = adapter->txd_ring_size / 128;
if (adapter->txs_ring_size > 160)
adapter->txs_ring_size = 160;
/* Receive Memory Block Count */
opt.type = range_option;
opt.name = "Number of receive memory block";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_RXD_COUNT);
opt.def = ATL2_DEFAULT_RXD_COUNT;
opt.arg.r.min = ATL2_MIN_RXD_COUNT;
opt.arg.r.max = ATL2_MAX_RXD_COUNT;
#ifdef module_param_array
if (num_RxMemBlock > bd) {
#endif
val = RxMemBlock[bd];
atl2_validate_option(&val, &opt);
adapter->rxd_ring_size = (u32)val;
/* FIXME */
/* ((u16)val)&~1; */ /* even number */
#ifdef module_param_array
} else
adapter->rxd_ring_size = (u32)opt.def;
#endif
/* init RXD Flow control value */
adapter->hw.fc_rxd_hi = (adapter->rxd_ring_size / 8) * 7;
adapter->hw.fc_rxd_lo = (ATL2_MIN_RXD_COUNT / 8) >
(adapter->rxd_ring_size / 12) ? (ATL2_MIN_RXD_COUNT / 8) :
(adapter->rxd_ring_size / 12);
/* Interrupt Moderate Timer */
opt.type = range_option;
opt.name = "Interrupt Moderate Timer";
opt.err = "using default of " __MODULE_STRING(INT_MOD_DEFAULT_CNT);
opt.def = INT_MOD_DEFAULT_CNT;
opt.arg.r.min = INT_MOD_MIN_CNT;
opt.arg.r.max = INT_MOD_MAX_CNT;
#ifdef module_param_array
if (num_IntModTimer > bd) {
#endif
val = IntModTimer[bd];
atl2_validate_option(&val, &opt);
adapter->imt = (u16) val;
#ifdef module_param_array
} else
adapter->imt = (u16)(opt.def);
#endif
/* Flash Vendor */
opt.type = range_option;
opt.name = "SPI Flash Vendor";
opt.err = "using default of " __MODULE_STRING(FLASH_VENDOR_DEFAULT);
opt.def = FLASH_VENDOR_DEFAULT;
opt.arg.r.min = FLASH_VENDOR_MIN;
opt.arg.r.max = FLASH_VENDOR_MAX;
#ifdef module_param_array
if (num_FlashVendor > bd) {
#endif
val = FlashVendor[bd];
atl2_validate_option(&val, &opt);
adapter->hw.flash_vendor = (u8) val;
#ifdef module_param_array
} else
adapter->hw.flash_vendor = (u8)(opt.def);
#endif
/* MediaType */
opt.type = range_option;
opt.name = "Speed/Duplex Selection";
opt.err = "using default of " __MODULE_STRING(MEDIA_TYPE_AUTO_SENSOR);
opt.def = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.min = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.max = MEDIA_TYPE_10M_HALF;
#ifdef module_param_array
if (num_MediaType > bd) {
#endif
val = MediaType[bd];
atl2_validate_option(&val, &opt);
adapter->hw.MediaType = (u16) val;
#ifdef module_param_array
} else
adapter->hw.MediaType = (u16)(opt.def);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_4936_0 |
crossvul-cpp_data_good_1508_5 | /*
Copyright (C) 2009 RedHat inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <sys/statvfs.h>
#include "internal_libabrt.h"
int low_free_space(unsigned setting_MaxCrashReportsSize, const char *dump_location)
{
struct statvfs vfs;
if (statvfs(dump_location, &vfs) != 0)
{
perror_msg("statvfs('%s')", dump_location);
return 0;
}
/* Check that at least MaxCrashReportsSize/4 MBs are free */
/* fs_free_mb_x4 ~= vfs.f_bfree * vfs.f_bsize * 4, expressed in MBytes.
* Need to neither overflow nor round f_bfree down too much. */
unsigned long fs_free_mb_x4 = ((unsigned long long)vfs.f_bfree / (1024/4)) * vfs.f_bsize / 1024;
if (fs_free_mb_x4 < setting_MaxCrashReportsSize)
{
error_msg("Only %luMiB is available on %s",
fs_free_mb_x4 / 4, dump_location);
return 1;
}
return 0;
}
/* rhbz#539551: "abrt going crazy when crashing process is respawned".
* Check total size of problem dirs, if it overflows,
* delete oldest/biggest dirs.
*/
void trim_problem_dirs(const char *dirname, double cap_size, const char *exclude_path)
{
const char *excluded_basename = NULL;
if (exclude_path)
{
unsigned len_dirname = strlen(dirname);
/* Trim trailing '/'s, but dont trim name "/" to "" */
while (len_dirname > 1 && dirname[len_dirname-1] == '/')
len_dirname--;
if (strncmp(dirname, exclude_path, len_dirname) == 0
&& exclude_path[len_dirname] == '/'
) {
/* exclude_path is "dirname/something" */
excluded_basename = exclude_path + len_dirname + 1;
}
}
log_debug("excluded_basename:'%s'", excluded_basename);
int count = 20;
while (--count >= 0)
{
/* We exclude our own dir from candidates for deletion (3rd param): */
char *worst_basename = NULL;
double cur_size = get_dirsize_find_largest_dir(dirname, &worst_basename, excluded_basename);
if (cur_size <= cap_size || !worst_basename)
{
log_info("cur_size:%.0f cap_size:%.0f, no (more) trimming", cur_size, cap_size);
free(worst_basename);
break;
}
log("%s is %.0f bytes (more than %.0fMiB), deleting '%s'",
dirname, cur_size, cap_size / (1024*1024), worst_basename);
char *d = concat_path_file(dirname, worst_basename);
free(worst_basename);
delete_dump_dir(d);
free(d);
}
}
/**
*
* @param[out] status See `man 2 wait` for status information.
* @return Malloc'ed string
*/
static char* exec_vp(char **args, int redirect_stderr, int exec_timeout_sec, int *status)
{
/* Nuke everything which may make setlocale() switch to non-POSIX locale:
* we need to avoid having gdb output in some obscure language.
*/
static const char *const env_vec[] = {
"LANG",
"LC_ALL",
"LC_COLLATE",
"LC_CTYPE",
"LC_MESSAGES",
"LC_MONETARY",
"LC_NUMERIC",
"LC_TIME",
/* Workaround for
* http://sourceware.org/bugzilla/show_bug.cgi?id=9622
* (gdb emitting ESC sequences even with -batch)
*/
"TERM",
NULL
};
int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET;
if (redirect_stderr)
flags |= EXECFLG_ERR2OUT;
VERB1 flags &= ~EXECFLG_QUIET;
int pipeout[2];
pid_t child = fork_execv_on_steroids(flags, args, pipeout, (char**)env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0);
/* We use this function to run gdb and unstrip. Bugs in gdb or corrupted
* coredumps were observed to cause gdb to enter infinite loop.
* Therefore we have a (largish) timeout, after which we kill the child.
*/
ndelay_on(pipeout[0]);
int t = time(NULL); /* int is enough, no need to use time_t */
int endtime = t + exec_timeout_sec;
struct strbuf *buf_out = strbuf_new();
while (1)
{
int timeout = endtime - t;
if (timeout < 0)
{
kill(child, SIGKILL);
strbuf_append_strf(buf_out, "\n"
"Timeout exceeded: %u seconds, killing %s.\n"
"Looks like gdb hung while generating backtrace.\n"
"This may be a bug in gdb. Consider submitting a bug report to gdb developers.\n"
"Please attach coredump from this crash to the bug report if you do.\n",
exec_timeout_sec, args[0]
);
break;
}
/* We don't check poll result - checking read result is enough */
struct pollfd pfd;
pfd.fd = pipeout[0];
pfd.events = POLLIN;
poll(&pfd, 1, timeout * 1000);
char buff[1024];
int r = read(pipeout[0], buff, sizeof(buff) - 1);
if (r <= 0)
{
/* I did see EAGAIN happening here */
if (r < 0 && errno == EAGAIN)
goto next;
break;
}
buff[r] = '\0';
strbuf_append_str(buf_out, buff);
next:
t = time(NULL);
}
close(pipeout[0]);
/* Prevent having zombie child process, and maybe collect status
* (note that status == NULL is ok too) */
safe_waitpid(child, status, 0);
return strbuf_free_nobuf(buf_out);
}
char *run_unstrip_n(const char *dump_dir_name, unsigned timeout_sec)
{
int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET;
VERB1 flags &= ~EXECFLG_QUIET;
int pipeout[2];
char* args[4];
args[0] = (char*)"eu-unstrip";
args[1] = xasprintf("--core=%s/"FILENAME_COREDUMP, dump_dir_name);
args[2] = (char*)"-n";
args[3] = NULL;
pid_t child = fork_execv_on_steroids(flags, args, pipeout, /*env_vec:*/ NULL, /*dir:*/ NULL, /*uid(unused):*/ 0);
free(args[1]);
/* Bugs in unstrip or corrupted coredumps can cause it to enter infinite loop.
* Therefore we have a (largish) timeout, after which we kill the child.
*/
ndelay_on(pipeout[0]);
int t = time(NULL); /* int is enough, no need to use time_t */
int endtime = t + timeout_sec;
struct strbuf *buf_out = strbuf_new();
while (1)
{
int timeout = endtime - t;
if (timeout < 0)
{
kill(child, SIGKILL);
strbuf_free(buf_out);
buf_out = NULL;
break;
}
/* We don't check poll result - checking read result is enough */
struct pollfd pfd;
pfd.fd = pipeout[0];
pfd.events = POLLIN;
poll(&pfd, 1, timeout * 1000);
char buff[1024];
int r = read(pipeout[0], buff, sizeof(buff) - 1);
if (r <= 0)
{
/* I did see EAGAIN happening here */
if (r < 0 && errno == EAGAIN)
goto next;
break;
}
buff[r] = '\0';
strbuf_append_str(buf_out, buff);
next:
t = time(NULL);
}
close(pipeout[0]);
/* Prevent having zombie child process */
int status;
safe_waitpid(child, &status, 0);
if (status != 0 || buf_out == NULL)
{
/* unstrip didnt exit with exit code 0, or we timed out */
strbuf_free(buf_out);
return NULL;
}
return strbuf_free_nobuf(buf_out);
}
char *get_backtrace(const char *dump_dir_name, unsigned timeout_sec, const char *debuginfo_dirs)
{
INITIALIZE_LIBABRT();
struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
if (!dd)
return NULL;
char *executable = dd_load_text(dd, FILENAME_EXECUTABLE);
dd_close(dd);
/* Let user know what's going on */
log(_("Generating backtrace"));
unsigned i = 0;
char *args[25];
args[i++] = (char*)"gdb";
args[i++] = (char*)"-batch";
struct strbuf *set_debug_file_directory = strbuf_new();
unsigned auto_load_base_index = 0;
if(debuginfo_dirs == NULL)
{
// set non-existent debug file directory to prevent resolving
// function names - we need offsets for core backtrace.
strbuf_append_str(set_debug_file_directory, "set debug-file-directory /");
}
else
{
strbuf_append_str(set_debug_file_directory, "set debug-file-directory /usr/lib/debug");
struct strbuf *debug_directories = strbuf_new();
const char *p = debuginfo_dirs;
while (1)
{
while (*p == ':')
p++;
if (*p == '\0')
break;
const char *colon_or_nul = strchrnul(p, ':');
strbuf_append_strf(debug_directories, "%s%.*s/usr/lib/debug", (debug_directories->len == 0 ? "" : ":"),
(int)(colon_or_nul - p), p);
p = colon_or_nul;
}
strbuf_append_strf(set_debug_file_directory, ":%s", debug_directories->buf);
args[i++] = (char*)"-iex";
auto_load_base_index = i;
args[i++] = xasprintf("add-auto-load-safe-path %s", debug_directories->buf);
args[i++] = (char*)"-iex";
args[i++] = xasprintf("add-auto-load-scripts-directory %s", debug_directories->buf);
strbuf_free(debug_directories);
}
args[i++] = (char*)"-ex";
const unsigned debug_dir_cmd_index = i++;
args[debug_dir_cmd_index] = strbuf_free_nobuf(set_debug_file_directory);
/* "file BINARY_FILE" is needed, without it gdb cannot properly
* unwind the stack. Currently the unwind information is located
* in .eh_frame which is stored only in binary, not in coredump
* or debuginfo.
*
* Fedora GDB does not strictly need it, it will find the binary
* by its build-id. But for binaries either without build-id
* (= built on non-Fedora GCC) or which do not have
* their debuginfo rpm installed gdb would not find BINARY_FILE
* so it is still makes sense to supply "file BINARY_FILE".
*
* Unfortunately, "file BINARY_FILE" doesn't work well if BINARY_FILE
* was deleted (as often happens during system updates):
* gdb uses specified BINARY_FILE
* even if it is completely unrelated to the coredump.
* See https://bugzilla.redhat.com/show_bug.cgi?id=525721
*
* TODO: check mtimes on COREFILE and BINARY_FILE and not supply
* BINARY_FILE if it is newer (to at least avoid gdb complaining).
*/
args[i++] = (char*)"-ex";
const unsigned file_cmd_index = i++;
args[file_cmd_index] = xasprintf("file %s", executable);
free(executable);
args[i++] = (char*)"-ex";
const unsigned core_cmd_index = i++;
args[core_cmd_index] = xasprintf("core-file %s/"FILENAME_COREDUMP, dump_dir_name);
args[i++] = (char*)"-ex";
const unsigned bt_cmd_index = i++;
/*args[9] = ... see below */
args[i++] = (char*)"-ex";
args[i++] = (char*)"info sharedlib";
/* glibc's abort() stores its message in __abort_msg variable */
args[i++] = (char*)"-ex";
args[i++] = (char*)"print (char*)__abort_msg";
args[i++] = (char*)"-ex";
args[i++] = (char*)"print (char*)__glib_assert_msg";
args[i++] = (char*)"-ex";
args[i++] = (char*)"info all-registers";
args[i++] = (char*)"-ex";
const unsigned dis_cmd_index = i++;
args[dis_cmd_index] = (char*)"disassemble";
args[i++] = NULL;
/* Get the backtrace, but try to cap its size */
/* Limit bt depth. With no limit, gdb sometimes OOMs the machine */
unsigned bt_depth = 1024;
const char *thread_apply_all = "thread apply all";
const char *full = " full";
char *bt = NULL;
while (1)
{
args[bt_cmd_index] = xasprintf("%s backtrace %u%s", thread_apply_all, bt_depth, full);
bt = exec_vp(args, /*redirect_stderr:*/ 1, timeout_sec, NULL);
free(args[bt_cmd_index]);
if ((bt && strnlen(bt, 256*1024) < 256*1024) || bt_depth <= 32)
{
break;
}
bt_depth /= 2;
if (bt)
log("Backtrace is too big (%u bytes), reducing depth to %u",
(unsigned)strlen(bt), bt_depth);
else
/* (NB: in fact, current impl. of exec_vp() never returns NULL) */
log("Failed to generate backtrace, reducing depth to %u",
bt_depth);
free(bt);
/* Replace -ex disassemble (which disasms entire function $pc points to)
* to a version which analyzes limited, small patch of code around $pc.
* (Users reported a case where bare "disassemble" attempted to process
* entire .bss).
* TODO: what if "$pc-N" underflows? in my test, this happens:
* Dump of assembler code from 0xfffffffffffffff0 to 0x30:
* End of assembler dump.
* (IOW: "empty" dump)
*/
args[dis_cmd_index] = (char*)"disassemble $pc-20, $pc+64";
if (bt_depth <= 64 && thread_apply_all[0] != '\0')
{
/* This program likely has gazillion threads, dont try to bt them all */
bt_depth = 128;
thread_apply_all = "";
}
if (bt_depth <= 64 && full[0] != '\0')
{
/* Looks like there are gigantic local structures or arrays, disable "full" bt */
bt_depth = 128;
full = "";
}
}
if (auto_load_base_index > 0)
{
free(args[auto_load_base_index]);
free(args[auto_load_base_index + 2]);
}
free(args[debug_dir_cmd_index]);
free(args[file_cmd_index]);
free(args[core_cmd_index]);
return bt;
}
char* problem_data_save(problem_data_t *pd)
{
load_abrt_conf();
struct dump_dir *dd = NULL;
if (g_settings_privatereports)
dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0);
else
dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location);
char *problem_id = NULL;
if (dd)
{
problem_id = xstrdup(dd->dd_dirname);
dd_close(dd);
}
log_info("problem id: '%s'", problem_id);
return problem_id;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1508_5 |
crossvul-cpp_data_good_1829_2 | /***********************************************************************/
/* */
/* OCaml */
/* */
/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
/* */
/* Copyright 1996 Institut National de Recherche en Informatique et */
/* en Automatique. All rights reserved. This file is distributed */
/* under the terms of the GNU Library General Public License, with */
/* the special exception on linking described in file ../LICENSE. */
/* */
/***********************************************************************/
/* 1. Allocation functions doing the same work as the macros in the
case where [Setup_for_gc] and [Restore_after_gc] are no-ops.
2. Convenience functions related to allocation.
*/
#include <string.h>
#include "caml/alloc.h"
#include "caml/custom.h"
#include "caml/major_gc.h"
#include "caml/memory.h"
#include "caml/mlvalues.h"
#include "caml/stacks.h"
#define Setup_for_gc
#define Restore_after_gc
CAMLexport value caml_alloc (mlsize_t wosize, tag_t tag)
{
value result;
mlsize_t i;
Assert (tag < 256);
Assert (tag != Infix_tag);
if (wosize == 0){
result = Atom (tag);
}else if (wosize <= Max_young_wosize){
Alloc_small (result, wosize, tag);
if (tag < No_scan_tag){
for (i = 0; i < wosize; i++) Field (result, i) = Val_unit;
}
}else{
result = caml_alloc_shr (wosize, tag);
if (tag < No_scan_tag){
for (i = 0; i < wosize; i++) Field (result, i) = Val_unit;
}
result = caml_check_urgent_gc (result);
}
return result;
}
CAMLexport value caml_alloc_small (mlsize_t wosize, tag_t tag)
{
value result;
Assert (wosize > 0);
Assert (wosize <= Max_young_wosize);
Assert (tag < 256);
Alloc_small (result, wosize, tag);
return result;
}
/* [n] is a number of words (fields) */
CAMLexport value caml_alloc_tuple(mlsize_t n)
{
return caml_alloc(n, 0);
}
/* [len] is a number of bytes (chars) */
CAMLexport value caml_alloc_string (mlsize_t len)
{
value result;
mlsize_t offset_index;
mlsize_t wosize = (len + sizeof (value)) / sizeof (value);
if (wosize <= Max_young_wosize) {
Alloc_small (result, wosize, String_tag);
}else{
result = caml_alloc_shr (wosize, String_tag);
result = caml_check_urgent_gc (result);
}
Field (result, wosize - 1) = 0;
offset_index = Bsize_wsize (wosize) - 1;
Byte (result, offset_index) = offset_index - len;
return result;
}
/* [len] is a number of words.
[mem] and [max] are relative (without unit).
*/
CAMLexport value caml_alloc_final (mlsize_t len, final_fun fun,
mlsize_t mem, mlsize_t max)
{
return caml_alloc_custom(caml_final_custom_operations(fun),
len * sizeof(value), mem, max);
}
CAMLexport value caml_copy_string(char const *s)
{
int len;
value res;
len = strlen(s);
res = caml_alloc_string(len);
memmove(String_val(res), s, len);
return res;
}
CAMLexport value caml_alloc_array(value (*funct)(char const *),
char const ** arr)
{
CAMLparam0 ();
mlsize_t nbr, n;
CAMLlocal2 (v, result);
nbr = 0;
while (arr[nbr] != 0) nbr++;
if (nbr == 0) {
CAMLreturn (Atom(0));
} else {
result = caml_alloc (nbr, 0);
for (n = 0; n < nbr; n++) {
/* The two statements below must be separate because of evaluation
order (don't take the address &Field(result, n) before
calling funct, which may cause a GC and move result). */
v = funct(arr[n]);
caml_modify(&Field(result, n), v);
}
CAMLreturn (result);
}
}
CAMLexport value caml_copy_string_array(char const ** arr)
{
return caml_alloc_array(caml_copy_string, arr);
}
CAMLexport int caml_convert_flag_list(value list, int *flags)
{
int res;
res = 0;
while (list != Val_int(0)) {
res |= flags[Int_val(Field(list, 0))];
list = Field(list, 1);
}
return res;
}
/* For compiling let rec over values */
/* [size] is a [value] representing number of words (fields) */
CAMLprim value caml_alloc_dummy(value size)
{
mlsize_t wosize = Long_val(size);
if (wosize == 0) return Atom(0);
return caml_alloc (wosize, 0);
}
/* [size] is a [value] representing number of words (fields) */
CAMLprim value caml_alloc_dummy_function(value size,value arity)
{
/* the arity argument is used by the js_of_ocaml runtime */
return caml_alloc_dummy(size);
}
/* [size] is a [value] representing number of floats. */
CAMLprim value caml_alloc_dummy_float (value size)
{
mlsize_t wosize = Long_val(size) * Double_wosize;
if (wosize == 0) return Atom(0);
return caml_alloc (wosize, 0);
}
CAMLprim value caml_update_dummy(value dummy, value newval)
{
mlsize_t size, i;
tag_t tag;
size = Wosize_val(newval);
tag = Tag_val (newval);
Assert (size == Wosize_val(dummy));
Assert (tag < No_scan_tag || tag == Double_array_tag);
Tag_val(dummy) = tag;
if (tag == Double_array_tag){
size = Wosize_val (newval) / Double_wosize;
for (i = 0; i < size; i++){
Store_double_field (dummy, i, Double_field (newval, i));
}
}else{
for (i = 0; i < size; i++){
caml_modify (&Field(dummy, i), Field(newval, i));
}
}
return Val_unit;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_1829_2 |
crossvul-cpp_data_good_5049_0 | /*
* af_llc.c - LLC User Interface SAPs
* Description:
* Functions in this module are implementation of socket based llc
* communications for the Linux operating system. Support of llc class
* one and class two is provided via SOCK_DGRAM and SOCK_STREAM
* respectively.
*
* An llc2 connection is (mac + sap), only one llc2 sap connection
* is allowed per mac. Though one sap may have multiple mac + sap
* connections.
*
* Copyright (c) 2001 by Jay Schulist <jschlst@samba.org>
* 2002-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/llc.h>
#include <net/llc_sap.h>
#include <net/llc_pdu.h>
#include <net/llc_conn.h>
#include <net/tcp_states.h>
/* remember: uninitialized global data is zeroed because its in .bss */
static u16 llc_ui_sap_last_autoport = LLC_SAP_DYN_START;
static u16 llc_ui_sap_link_no_max[256];
static struct sockaddr_llc llc_ui_addrnull;
static const struct proto_ops llc_ui_ops;
static long llc_ui_wait_for_conn(struct sock *sk, long timeout);
static int llc_ui_wait_for_disc(struct sock *sk, long timeout);
static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout);
#if 0
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
/* Maybe we'll add some more in the future. */
#define LLC_CMSG_PKTINFO 1
/**
* llc_ui_next_link_no - return the next unused link number for a sap
* @sap: Address of sap to get link number from.
*
* Return the next unused link number for a given sap.
*/
static inline u16 llc_ui_next_link_no(int sap)
{
return llc_ui_sap_link_no_max[sap]++;
}
/**
* llc_proto_type - return eth protocol for ARP header type
* @arphrd: ARP header type.
*
* Given an ARP header type return the corresponding ethernet protocol.
*/
static inline __be16 llc_proto_type(u16 arphrd)
{
return htons(ETH_P_802_2);
}
/**
* llc_ui_addr_null - determines if a address structure is null
* @addr: Address to test if null.
*/
static inline u8 llc_ui_addr_null(struct sockaddr_llc *addr)
{
return !memcmp(addr, &llc_ui_addrnull, sizeof(*addr));
}
/**
* llc_ui_header_len - return length of llc header based on operation
* @sk: Socket which contains a valid llc socket type.
* @addr: Complete sockaddr_llc structure received from the user.
*
* Provide the length of the llc header depending on what kind of
* operation the user would like to perform and the type of socket.
* Returns the correct llc header length.
*/
static inline u8 llc_ui_header_len(struct sock *sk, struct sockaddr_llc *addr)
{
u8 rc = LLC_PDU_LEN_U;
if (addr->sllc_test || addr->sllc_xid)
rc = LLC_PDU_LEN_U;
else if (sk->sk_type == SOCK_STREAM)
rc = LLC_PDU_LEN_I;
return rc;
}
/**
* llc_ui_send_data - send data via reliable llc2 connection
* @sk: Connection the socket is using.
* @skb: Data the user wishes to send.
* @noblock: can we block waiting for data?
*
* Send data via reliable llc2 connection.
* Returns 0 upon success, non-zero if action did not succeed.
*/
static int llc_ui_send_data(struct sock* sk, struct sk_buff *skb, int noblock)
{
struct llc_sock* llc = llc_sk(sk);
int rc = 0;
if (unlikely(llc_data_accept_state(llc->state) ||
llc->remote_busy_flag ||
llc->p_flag)) {
long timeout = sock_sndtimeo(sk, noblock);
rc = llc_ui_wait_for_busy_core(sk, timeout);
}
if (unlikely(!rc))
rc = llc_build_and_send_pkt(sk, skb);
return rc;
}
static void llc_ui_sk_init(struct socket *sock, struct sock *sk)
{
sock_graft(sk, sock);
sk->sk_type = sock->type;
sock->ops = &llc_ui_ops;
}
static struct proto llc_proto = {
.name = "LLC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct llc_sock),
.slab_flags = SLAB_DESTROY_BY_RCU,
};
/**
* llc_ui_create - alloc and init a new llc_ui socket
* @net: network namespace (must be default network)
* @sock: Socket to initialize and attach allocated sk to.
* @protocol: Unused.
* @kern: on behalf of kernel or userspace
*
* Allocate and initialize a new llc_ui socket, validate the user wants a
* socket type we have available.
* Returns 0 upon success, negative upon failure.
*/
static int llc_ui_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
int rc = -ESOCKTNOSUPPORT;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
if (likely(sock->type == SOCK_DGRAM || sock->type == SOCK_STREAM)) {
rc = -ENOMEM;
sk = llc_sk_alloc(net, PF_LLC, GFP_KERNEL, &llc_proto, kern);
if (sk) {
rc = 0;
llc_ui_sk_init(sock, sk);
}
}
return rc;
}
/**
* llc_ui_release - shutdown socket
* @sock: Socket to release.
*
* Shutdown and deallocate an existing socket.
*/
static int llc_ui_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct llc_sock *llc;
if (unlikely(sk == NULL))
goto out;
sock_hold(sk);
lock_sock(sk);
llc = llc_sk(sk);
dprintk("%s: closing local(%02X) remote(%02X)\n", __func__,
llc->laddr.lsap, llc->daddr.lsap);
if (!llc_send_disc(sk))
llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo);
if (!sock_flag(sk, SOCK_ZAPPED))
llc_sap_remove_socket(llc->sap, sk);
release_sock(sk);
if (llc->dev)
dev_put(llc->dev);
sock_put(sk);
llc_sk_free(sk);
out:
return 0;
}
/**
* llc_ui_autoport - provide dynamically allocate SAP number
*
* Provide the caller with a dynamically allocated SAP number according
* to the rules that are set in this function. Returns: 0, upon failure,
* SAP number otherwise.
*/
static int llc_ui_autoport(void)
{
struct llc_sap *sap;
int i, tries = 0;
while (tries < LLC_SAP_DYN_TRIES) {
for (i = llc_ui_sap_last_autoport;
i < LLC_SAP_DYN_STOP; i += 2) {
sap = llc_sap_find(i);
if (!sap) {
llc_ui_sap_last_autoport = i + 2;
goto out;
}
llc_sap_put(sap);
}
llc_ui_sap_last_autoport = LLC_SAP_DYN_START;
tries++;
}
i = 0;
out:
return i;
}
/**
* llc_ui_autobind - automatically bind a socket to a sap
* @sock: socket to bind
* @addr: address to connect to
*
* Used by llc_ui_connect and llc_ui_sendmsg when the user hasn't
* specifically used llc_ui_bind to bind to an specific address/sap
*
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_autobind(struct socket *sock, struct sockaddr_llc *addr)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap;
int rc = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED))
goto out;
rc = -ENODEV;
if (sk->sk_bound_dev_if) {
llc->dev = dev_get_by_index(&init_net, sk->sk_bound_dev_if);
if (llc->dev && addr->sllc_arphrd != llc->dev->type) {
dev_put(llc->dev);
llc->dev = NULL;
}
} else
llc->dev = dev_getfirstbyhwtype(&init_net, addr->sllc_arphrd);
if (!llc->dev)
goto out;
rc = -EUSERS;
llc->laddr.lsap = llc_ui_autoport();
if (!llc->laddr.lsap)
goto out;
rc = -EBUSY; /* some other network layer is using the sap */
sap = llc_sap_open(llc->laddr.lsap, NULL);
if (!sap)
goto out;
memcpy(llc->laddr.mac, llc->dev->dev_addr, IFHWADDRLEN);
memcpy(&llc->addr, addr, sizeof(llc->addr));
/* assign new connection to its SAP */
llc_sap_add_socket(sap, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out:
return rc;
}
/**
* llc_ui_bind - bind a socket to a specific address.
* @sock: Socket to bind an address to.
* @uaddr: Address the user wants the socket bound to.
* @addrlen: Length of the uaddr structure.
*
* Bind a socket to a specific address. For llc a user is able to bind to
* a specific sap only or mac + sap.
* If the user desires to bind to a specific mac + sap, it is possible to
* have multiple sap connections via multiple macs.
* Bind and autobind for that matter must enforce the correct sap usage
* otherwise all hell will break loose.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen)
{
struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap;
int rc = -EINVAL;
dprintk("%s: binding %02X\n", __func__, addr->sllc_sap);
if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr)))
goto out;
rc = -EAFNOSUPPORT;
if (unlikely(addr->sllc_family != AF_LLC))
goto out;
rc = -ENODEV;
rcu_read_lock();
if (sk->sk_bound_dev_if) {
llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if);
if (llc->dev) {
if (!addr->sllc_arphrd)
addr->sllc_arphrd = llc->dev->type;
if (is_zero_ether_addr(addr->sllc_mac))
memcpy(addr->sllc_mac, llc->dev->dev_addr,
IFHWADDRLEN);
if (addr->sllc_arphrd != llc->dev->type ||
!ether_addr_equal(addr->sllc_mac,
llc->dev->dev_addr)) {
rc = -EINVAL;
llc->dev = NULL;
}
}
} else
llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd,
addr->sllc_mac);
if (llc->dev)
dev_hold(llc->dev);
rcu_read_unlock();
if (!llc->dev)
goto out;
if (!addr->sllc_sap) {
rc = -EUSERS;
addr->sllc_sap = llc_ui_autoport();
if (!addr->sllc_sap)
goto out;
}
sap = llc_sap_find(addr->sllc_sap);
if (!sap) {
sap = llc_sap_open(addr->sllc_sap, NULL);
rc = -EBUSY; /* some other network layer is using the sap */
if (!sap)
goto out;
} else {
struct llc_addr laddr, daddr;
struct sock *ask;
memset(&laddr, 0, sizeof(laddr));
memset(&daddr, 0, sizeof(daddr));
/*
* FIXME: check if the address is multicast,
* only SOCK_DGRAM can do this.
*/
memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN);
laddr.lsap = addr->sllc_sap;
rc = -EADDRINUSE; /* mac + sap clash. */
ask = llc_lookup_established(sap, &daddr, &laddr);
if (ask) {
sock_put(ask);
goto out_put;
}
}
llc->laddr.lsap = addr->sllc_sap;
memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN);
memcpy(&llc->addr, addr, sizeof(llc->addr));
/* assign new connection to its SAP */
llc_sap_add_socket(sap, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out_put:
llc_sap_put(sap);
out:
return rc;
}
/**
* llc_ui_shutdown - shutdown a connect llc2 socket.
* @sock: Socket to shutdown.
* @how: What part of the socket to shutdown.
*
* Shutdown a connected llc2 socket. Currently this function only supports
* shutting down both sends and receives (2), we could probably make this
* function such that a user can shutdown only half the connection but not
* right now.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int rc = -ENOTCONN;
lock_sock(sk);
if (unlikely(sk->sk_state != TCP_ESTABLISHED))
goto out;
rc = -EINVAL;
if (how != 2)
goto out;
rc = llc_send_disc(sk);
if (!rc)
rc = llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo);
/* Wake up anyone sleeping in poll */
sk->sk_state_change(sk);
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_connect - Connect to a remote llc2 mac + sap.
* @sock: Socket which will be connected to the remote destination.
* @uaddr: Remote and possibly the local address of the new connection.
* @addrlen: Size of uaddr structure.
* @flags: Operational flags specified by the user.
*
* Connect to a remote llc2 mac + sap. The caller must specify the
* destination mac and address to connect to. If the user hasn't previously
* called bind(2) with a smac the address of the first interface of the
* specified arp type will be used.
* This function will autobind if user did not previously call bind.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_connect(struct socket *sock, struct sockaddr *uaddr,
int addrlen, int flags)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(addrlen != sizeof(*addr)))
goto out;
rc = -EAFNOSUPPORT;
if (unlikely(addr->sllc_family != AF_LLC))
goto out;
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EALREADY;
if (unlikely(sock->state == SS_CONNECTING))
goto out;
/* bind connection to sap if user hasn't done it. */
if (sock_flag(sk, SOCK_ZAPPED)) {
/* bind to sap with null dev, exclusive */
rc = llc_ui_autobind(sock, addr);
if (rc)
goto out;
}
llc->daddr.lsap = addr->sllc_sap;
memcpy(llc->daddr.mac, addr->sllc_mac, IFHWADDRLEN);
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
llc->link = llc_ui_next_link_no(llc->sap->laddr.lsap);
rc = llc_establish_connection(sk, llc->dev->dev_addr,
addr->sllc_mac, addr->sllc_sap);
if (rc) {
dprintk("%s: llc_ui_send_conn failed :-(\n", __func__);
sock->state = SS_UNCONNECTED;
sk->sk_state = TCP_CLOSE;
goto out;
}
if (sk->sk_state == TCP_SYN_SENT) {
const long timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
if (!timeo || !llc_ui_wait_for_conn(sk, timeo))
goto out;
rc = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
}
if (sk->sk_state == TCP_CLOSE)
goto sock_error;
sock->state = SS_CONNECTED;
rc = 0;
out:
release_sock(sk);
return rc;
sock_error:
rc = sock_error(sk) ? : -ECONNABORTED;
sock->state = SS_UNCONNECTED;
goto out;
}
/**
* llc_ui_listen - allow a normal socket to accept incoming connections
* @sock: Socket to allow incoming connections on.
* @backlog: Number of connections to queue.
*
* Allow a normal socket to accept incoming connections.
* Returns 0 upon success, negative otherwise.
*/
static int llc_ui_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(sock->state != SS_UNCONNECTED))
goto out;
rc = -EOPNOTSUPP;
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EAGAIN;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
rc = 0;
if (!(unsigned int)backlog) /* BSDism */
backlog = 1;
sk->sk_max_ack_backlog = backlog;
if (sk->sk_state != TCP_LISTEN) {
sk->sk_ack_backlog = 0;
sk->sk_state = TCP_LISTEN;
}
sk->sk_socket->flags |= __SO_ACCEPTCON;
out:
release_sock(sk);
return rc;
}
static int llc_ui_wait_for_disc(struct sock *sk, long timeout)
{
DEFINE_WAIT(wait);
int rc = 0;
while (1) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (sk_wait_event(sk, &timeout, sk->sk_state == TCP_CLOSE))
break;
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = -EAGAIN;
if (!timeout)
break;
rc = 0;
}
finish_wait(sk_sleep(sk), &wait);
return rc;
}
static long llc_ui_wait_for_conn(struct sock *sk, long timeout)
{
DEFINE_WAIT(wait);
while (1) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT))
break;
if (signal_pending(current) || !timeout)
break;
}
finish_wait(sk_sleep(sk), &wait);
return timeout;
}
static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout)
{
DEFINE_WAIT(wait);
struct llc_sock *llc = llc_sk(sk);
int rc;
while (1) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
rc = 0;
if (sk_wait_event(sk, &timeout,
(sk->sk_shutdown & RCV_SHUTDOWN) ||
(!llc_data_accept_state(llc->state) &&
!llc->remote_busy_flag &&
!llc->p_flag)))
break;
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = -EAGAIN;
if (!timeout)
break;
}
finish_wait(sk_sleep(sk), &wait);
return rc;
}
static int llc_wait_data(struct sock *sk, long timeo)
{
int rc;
while (1) {
/*
* POSIX 1003.1g mandates this order.
*/
rc = sock_error(sk);
if (rc)
break;
rc = 0;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
rc = -EAGAIN;
if (!timeo)
break;
rc = sock_intr_errno(timeo);
if (signal_pending(current))
break;
rc = 0;
if (sk_wait_data(sk, &timeo, NULL))
break;
}
return rc;
}
static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(skb->sk);
if (llc->cmsg_flags & LLC_CMSG_PKTINFO) {
struct llc_pktinfo info;
memset(&info, 0, sizeof(info));
info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex;
llc_pdu_decode_dsap(skb, &info.lpi_sap);
llc_pdu_decode_da(skb, info.lpi_mac);
put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info);
}
}
/**
* llc_ui_accept - accept a new incoming connection.
* @sock: Socket which connections arrive on.
* @newsock: Socket to move incoming connection to.
* @flags: User specified operational flags.
*
* Accept a new incoming connection.
* Returns 0 upon success, negative otherwise.
*/
static int llc_ui_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk, *newsk;
struct llc_sock *llc, *newllc;
struct sk_buff *skb;
int rc = -EOPNOTSUPP;
dprintk("%s: accepting on %02X\n", __func__,
llc_sk(sk)->laddr.lsap);
lock_sock(sk);
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EINVAL;
if (unlikely(sock->state != SS_UNCONNECTED ||
sk->sk_state != TCP_LISTEN))
goto out;
/* wait for a connection to arrive. */
if (skb_queue_empty(&sk->sk_receive_queue)) {
rc = llc_wait_data(sk, sk->sk_rcvtimeo);
if (rc)
goto out;
}
dprintk("%s: got a new connection on %02X\n", __func__,
llc_sk(sk)->laddr.lsap);
skb = skb_dequeue(&sk->sk_receive_queue);
rc = -EINVAL;
if (!skb->sk)
goto frees;
rc = 0;
newsk = skb->sk;
/* attach connection to a new socket. */
llc_ui_sk_init(newsock, newsk);
sock_reset_flag(newsk, SOCK_ZAPPED);
newsk->sk_state = TCP_ESTABLISHED;
newsock->state = SS_CONNECTED;
llc = llc_sk(sk);
newllc = llc_sk(newsk);
memcpy(&newllc->addr, &llc->addr, sizeof(newllc->addr));
newllc->link = llc_ui_next_link_no(newllc->laddr.lsap);
/* put original socket back into a clean listen state. */
sk->sk_state = TCP_LISTEN;
sk->sk_ack_backlog--;
dprintk("%s: ok success on %02X, client on %02X\n", __func__,
llc_sk(sk)->addr.sllc_sap, newllc->daddr.lsap);
frees:
kfree_skb(skb);
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_recvmsg - copy received data to the socket user.
* @sock: Socket to copy data from.
* @msg: Various user space related information.
* @len: Size of user buffer.
* @flags: User specified flags.
*
* Copy received data to the socket user.
* Returns non-negative upon success, negative otherwise.
*/
static int llc_ui_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
DECLARE_SOCKADDR(struct sockaddr_llc *, uaddr, msg->msg_name);
const int nonblock = flags & MSG_DONTWAIT;
struct sk_buff *skb = NULL;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
unsigned long cpu_flags;
size_t copied = 0;
u32 peek_seq = 0;
u32 *seq, skb_len;
unsigned long used;
int target; /* Read at least this many bytes */
long timeo;
lock_sock(sk);
copied = -ENOTCONN;
if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN))
goto out;
timeo = sock_rcvtimeo(sk, nonblock);
seq = &llc->copied_seq;
if (flags & MSG_PEEK) {
peek_seq = llc->copied_seq;
seq = &peek_seq;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
copied = 0;
do {
u32 offset;
/*
* We need to check signals first, to get correct SIGURG
* handling. FIXME: Need to check this doesn't impact 1003.1g
* and move it down to the bottom of the loop
*/
if (signal_pending(current)) {
if (copied)
break;
copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
break;
}
/* Next get a buffer. */
skb = skb_peek(&sk->sk_receive_queue);
if (skb) {
offset = *seq;
goto found_ok_skb;
}
/* Well, if we have backlog, try to process it now yet. */
if (copied >= target && !sk->sk_backlog.tail)
break;
if (copied) {
if (sk->sk_err ||
sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
!timeo ||
(flags & MSG_PEEK))
break;
} else {
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
copied = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) {
if (!sock_flag(sk, SOCK_DONE)) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
copied = -ENOTCONN;
break;
}
break;
}
if (!timeo) {
copied = -EAGAIN;
break;
}
}
if (copied >= target) { /* Do not sleep, just process backlog. */
release_sock(sk);
lock_sock(sk);
} else
sk_wait_data(sk, &timeo, NULL);
if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) {
net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n",
current->comm,
task_pid_nr(current));
peek_seq = llc->copied_seq;
}
continue;
found_ok_skb:
skb_len = skb->len;
/* Ok so how much can we use? */
used = skb->len - offset;
if (len < used)
used = len;
if (!(flags & MSG_TRUNC)) {
int rc = skb_copy_datagram_msg(skb, offset, msg, used);
if (rc) {
/* Exception. Bailout! */
if (!copied)
copied = -EFAULT;
break;
}
}
*seq += used;
copied += used;
len -= used;
/* For non stream protcols we get one packet per recvmsg call */
if (sk->sk_type != SOCK_STREAM)
goto copy_uaddr;
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb);
spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
/* Partial read */
if (used + offset < skb_len)
continue;
} while (len > 0);
out:
release_sock(sk);
return copied;
copy_uaddr:
if (uaddr != NULL && skb != NULL) {
memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr));
msg->msg_namelen = sizeof(*uaddr);
}
if (llc_sk(sk)->cmsg_flags)
llc_cmsg_rcv(msg, skb);
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb);
spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
goto out;
}
/**
* llc_ui_sendmsg - Transmit data provided by the socket user.
* @sock: Socket to transmit data from.
* @msg: Various user related information.
* @len: Length of data to transmit.
*
* Transmit data provided by the socket user.
* Returns non-negative upon success, negative otherwise.
*/
static int llc_ui_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_llc *, addr, msg->msg_name);
int flags = msg->msg_flags;
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
size_t size = 0;
int rc = -EINVAL, copied = 0, hdrlen;
dprintk("%s: sending from %02X to %02X\n", __func__,
llc->laddr.lsap, llc->daddr.lsap);
lock_sock(sk);
if (addr) {
if (msg->msg_namelen < sizeof(*addr))
goto release;
} else {
if (llc_ui_addr_null(&llc->addr))
goto release;
addr = &llc->addr;
}
/* must bind connection to sap if user hasn't done it. */
if (sock_flag(sk, SOCK_ZAPPED)) {
/* bind to sap with null dev, exclusive. */
rc = llc_ui_autobind(sock, addr);
if (rc)
goto release;
}
hdrlen = llc->dev->hard_header_len + llc_ui_header_len(sk, addr);
size = hdrlen + len;
if (size > llc->dev->mtu)
size = llc->dev->mtu;
copied = size - hdrlen;
release_sock(sk);
skb = sock_alloc_send_skb(sk, size, noblock, &rc);
lock_sock(sk);
if (!skb)
goto release;
skb->dev = llc->dev;
skb->protocol = llc_proto_type(addr->sllc_arphrd);
skb_reserve(skb, hdrlen);
rc = memcpy_from_msg(skb_put(skb, copied), msg, copied);
if (rc)
goto out;
if (sk->sk_type == SOCK_DGRAM || addr->sllc_ua) {
llc_build_and_send_ui_pkt(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
if (addr->sllc_test) {
llc_build_and_send_test_pkt(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
if (addr->sllc_xid) {
llc_build_and_send_xid_pkt(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
rc = -ENOPROTOOPT;
if (!(sk->sk_type == SOCK_STREAM && !addr->sllc_ua))
goto out;
rc = llc_ui_send_data(sk, skb, noblock);
out:
if (rc) {
kfree_skb(skb);
release:
dprintk("%s: failed sending from %02X to %02X: %d\n",
__func__, llc->laddr.lsap, llc->daddr.lsap, rc);
}
release_sock(sk);
return rc ? : copied;
}
/**
* llc_ui_getname - return the address info of a socket
* @sock: Socket to get address of.
* @uaddr: Address structure to return information.
* @uaddrlen: Length of address structure.
* @peer: Does user want local or remote address information.
*
* Return the address information of a socket.
*/
static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddrlen, int peer)
{
struct sockaddr_llc sllc;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
int rc = -EBADF;
memset(&sllc, 0, sizeof(sllc));
lock_sock(sk);
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
*uaddrlen = sizeof(sllc);
if (peer) {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if(llc->dev)
sllc.sllc_arphrd = llc->dev->type;
sllc.sllc_sap = llc->daddr.lsap;
memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN);
} else {
rc = -EINVAL;
if (!llc->sap)
goto out;
sllc.sllc_sap = llc->sap->laddr.lsap;
if (llc->dev) {
sllc.sllc_arphrd = llc->dev->type;
memcpy(&sllc.sllc_mac, llc->dev->dev_addr,
IFHWADDRLEN);
}
}
rc = 0;
sllc.sllc_family = AF_LLC;
memcpy(uaddr, &sllc, sizeof(sllc));
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_ioctl - io controls for PF_LLC
* @sock: Socket to get/set info
* @cmd: command
* @arg: optional argument for cmd
*
* get/set info on llc sockets
*/
static int llc_ui_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
return -ENOIOCTLCMD;
}
/**
* llc_ui_setsockopt - set various connection specific parameters.
* @sock: Socket to set options on.
* @level: Socket level user is requesting operations on.
* @optname: Operation name.
* @optval: User provided operation data.
* @optlen: Length of optval.
*
* Set various connection specific parameters.
*/
static int llc_ui_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
unsigned int opt;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(level != SOL_LLC || optlen != sizeof(int)))
goto out;
rc = get_user(opt, (int __user *)optval);
if (rc)
goto out;
rc = -EINVAL;
switch (optname) {
case LLC_OPT_RETRY:
if (opt > LLC_OPT_MAX_RETRY)
goto out;
llc->n2 = opt;
break;
case LLC_OPT_SIZE:
if (opt > LLC_OPT_MAX_SIZE)
goto out;
llc->n1 = opt;
break;
case LLC_OPT_ACK_TMR_EXP:
if (opt > LLC_OPT_MAX_ACK_TMR_EXP)
goto out;
llc->ack_timer.expire = opt * HZ;
break;
case LLC_OPT_P_TMR_EXP:
if (opt > LLC_OPT_MAX_P_TMR_EXP)
goto out;
llc->pf_cycle_timer.expire = opt * HZ;
break;
case LLC_OPT_REJ_TMR_EXP:
if (opt > LLC_OPT_MAX_REJ_TMR_EXP)
goto out;
llc->rej_sent_timer.expire = opt * HZ;
break;
case LLC_OPT_BUSY_TMR_EXP:
if (opt > LLC_OPT_MAX_BUSY_TMR_EXP)
goto out;
llc->busy_state_timer.expire = opt * HZ;
break;
case LLC_OPT_TX_WIN:
if (opt > LLC_OPT_MAX_WIN)
goto out;
llc->k = opt;
break;
case LLC_OPT_RX_WIN:
if (opt > LLC_OPT_MAX_WIN)
goto out;
llc->rw = opt;
break;
case LLC_OPT_PKTINFO:
if (opt)
llc->cmsg_flags |= LLC_CMSG_PKTINFO;
else
llc->cmsg_flags &= ~LLC_CMSG_PKTINFO;
break;
default:
rc = -ENOPROTOOPT;
goto out;
}
rc = 0;
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_getsockopt - get connection specific socket info
* @sock: Socket to get information from.
* @level: Socket level user is requesting operations on.
* @optname: Operation name.
* @optval: Variable to return operation data in.
* @optlen: Length of optval.
*
* Get connection specific socket information.
*/
static int llc_ui_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
int val = 0, len = 0, rc = -EINVAL;
lock_sock(sk);
if (unlikely(level != SOL_LLC))
goto out;
rc = get_user(len, optlen);
if (rc)
goto out;
rc = -EINVAL;
if (len != sizeof(int))
goto out;
switch (optname) {
case LLC_OPT_RETRY:
val = llc->n2; break;
case LLC_OPT_SIZE:
val = llc->n1; break;
case LLC_OPT_ACK_TMR_EXP:
val = llc->ack_timer.expire / HZ; break;
case LLC_OPT_P_TMR_EXP:
val = llc->pf_cycle_timer.expire / HZ; break;
case LLC_OPT_REJ_TMR_EXP:
val = llc->rej_sent_timer.expire / HZ; break;
case LLC_OPT_BUSY_TMR_EXP:
val = llc->busy_state_timer.expire / HZ; break;
case LLC_OPT_TX_WIN:
val = llc->k; break;
case LLC_OPT_RX_WIN:
val = llc->rw; break;
case LLC_OPT_PKTINFO:
val = (llc->cmsg_flags & LLC_CMSG_PKTINFO) != 0;
break;
default:
rc = -ENOPROTOOPT;
goto out;
}
rc = 0;
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
rc = -EFAULT;
out:
release_sock(sk);
return rc;
}
static const struct net_proto_family llc_ui_family_ops = {
.family = PF_LLC,
.create = llc_ui_create,
.owner = THIS_MODULE,
};
static const struct proto_ops llc_ui_ops = {
.family = PF_LLC,
.owner = THIS_MODULE,
.release = llc_ui_release,
.bind = llc_ui_bind,
.connect = llc_ui_connect,
.socketpair = sock_no_socketpair,
.accept = llc_ui_accept,
.getname = llc_ui_getname,
.poll = datagram_poll,
.ioctl = llc_ui_ioctl,
.listen = llc_ui_listen,
.shutdown = llc_ui_shutdown,
.setsockopt = llc_ui_setsockopt,
.getsockopt = llc_ui_getsockopt,
.sendmsg = llc_ui_sendmsg,
.recvmsg = llc_ui_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const char llc_proc_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the proc_fs entries\n";
static const char llc_sysctl_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the sysctl entries\n";
static const char llc_sock_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the network family\n";
static int __init llc2_init(void)
{
int rc = proto_register(&llc_proto, 0);
if (rc != 0)
goto out;
llc_build_offset_table();
llc_station_init();
llc_ui_sap_last_autoport = LLC_SAP_DYN_START;
rc = llc_proc_init();
if (rc != 0) {
printk(llc_proc_err_msg);
goto out_station;
}
rc = llc_sysctl_init();
if (rc) {
printk(llc_sysctl_err_msg);
goto out_proc;
}
rc = sock_register(&llc_ui_family_ops);
if (rc) {
printk(llc_sock_err_msg);
goto out_sysctl;
}
llc_add_pack(LLC_DEST_SAP, llc_sap_handler);
llc_add_pack(LLC_DEST_CONN, llc_conn_handler);
out:
return rc;
out_sysctl:
llc_sysctl_exit();
out_proc:
llc_proc_exit();
out_station:
llc_station_exit();
proto_unregister(&llc_proto);
goto out;
}
static void __exit llc2_exit(void)
{
llc_station_exit();
llc_remove_pack(LLC_DEST_SAP);
llc_remove_pack(LLC_DEST_CONN);
sock_unregister(PF_LLC);
llc_proc_exit();
llc_sysctl_exit();
proto_unregister(&llc_proto);
}
module_init(llc2_init);
module_exit(llc2_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Procom 1997, Jay Schullist 2001, Arnaldo C. Melo 2001-2003");
MODULE_DESCRIPTION("IEEE 802.2 PF_LLC support");
MODULE_ALIAS_NETPROTO(PF_LLC);
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_5049_0 |
crossvul-cpp_data_bad_5760_0 | #include "sb_pci_mp.h"
#include <linux/module.h>
#include <linux/parport.h>
extern struct parport *parport_pc_probe_port(unsigned long base_lo,
unsigned long base_hi,
int irq, int dma,
struct device *dev,
int irqflags);
static struct mp_device_t mp_devs[MAX_MP_DEV];
static int mp_nrpcibrds = sizeof(mp_pciboards)/sizeof(mppcibrd_t);
static int NR_BOARD=0;
static int NR_PORTS=0;
static struct mp_port multi_ports[MAX_MP_PORT];
static struct irq_info irq_lists[NR_IRQS];
static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset);
static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value);
static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset);
static int sb1054_get_register(struct sb_uart_port *port, int page, int reg);
static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value);
static void SendATCommand(struct mp_port *mtpt);
static int set_deep_fifo(struct sb_uart_port *port, int status);
static int get_deep_fifo(struct sb_uart_port *port);
static int get_device_type(int arg);
static int set_auto_rts(struct sb_uart_port *port, int status);
static void mp_stop(struct tty_struct *tty);
static void __mp_start(struct tty_struct *tty);
static void mp_start(struct tty_struct *tty);
static void mp_tasklet_action(unsigned long data);
static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear);
static int mp_startup(struct sb_uart_state *state, int init_hw);
static void mp_shutdown(struct sb_uart_state *state);
static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios);
static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c);
static int mp_put_char(struct tty_struct *tty, unsigned char ch);
static void mp_put_chars(struct tty_struct *tty);
static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count);
static int mp_write_room(struct tty_struct *tty);
static int mp_chars_in_buffer(struct tty_struct *tty);
static void mp_flush_buffer(struct tty_struct *tty);
static void mp_send_xchar(struct tty_struct *tty, char ch);
static void mp_throttle(struct tty_struct *tty);
static void mp_unthrottle(struct tty_struct *tty);
static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo);
static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo);
static int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value);
static int mp_tiocmget(struct tty_struct *tty);
static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear);
static int mp_break_ctl(struct tty_struct *tty, int break_state);
static int mp_do_autoconfig(struct sb_uart_state *state);
static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg);
static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt);
static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios);
static void mp_close(struct tty_struct *tty, struct file *filp);
static void mp_wait_until_sent(struct tty_struct *tty, int timeout);
static void mp_hangup(struct tty_struct *tty);
static void mp_update_termios(struct sb_uart_state *state);
static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state);
static struct sb_uart_state *uart_get(struct uart_driver *drv, int line);
static int mp_open(struct tty_struct *tty, struct file *filp);
static const char *mp_type(struct sb_uart_port *port);
static void mp_change_pm(struct sb_uart_state *state, int pm_state);
static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port);
static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port);
static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state);
static int mp_register_driver(struct uart_driver *drv);
static void mp_unregister_driver(struct uart_driver *drv);
static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port);
static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port);
static void autoconfig(struct mp_port *mtpt, unsigned int probeflags);
static void autoconfig_irq(struct mp_port *mtpt);
static void multi_stop_tx(struct sb_uart_port *port);
static void multi_start_tx(struct sb_uart_port *port);
static void multi_stop_rx(struct sb_uart_port *port);
static void multi_enable_ms(struct sb_uart_port *port);
static _INLINE_ void receive_chars(struct mp_port *mtpt, int *status );
static _INLINE_ void transmit_chars(struct mp_port *mtpt);
static _INLINE_ void check_modem_status(struct mp_port *mtpt);
static inline void multi_handle_port(struct mp_port *mtpt);
static irqreturn_t multi_interrupt(int irq, void *dev_id);
static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt);
static int serial_link_irq_chain(struct mp_port *mtpt);
static void serial_unlink_irq_chain(struct mp_port *mtpt);
static void multi_timeout(unsigned long data);
static unsigned int multi_tx_empty(struct sb_uart_port *port);
static unsigned int multi_get_mctrl(struct sb_uart_port *port);
static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl);
static void multi_break_ctl(struct sb_uart_port *port, int break_state);
static int multi_startup(struct sb_uart_port *port);
static void multi_shutdown(struct sb_uart_port *port);
static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud);
static void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old);
static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate);
static void multi_release_std_resource(struct mp_port *mtpt);
static void multi_release_port(struct sb_uart_port *port);
static int multi_request_port(struct sb_uart_port *port);
static void multi_config_port(struct sb_uart_port *port, int flags);
static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser);
static const char *multi_type(struct sb_uart_port *port);
static void __init multi_init_ports(void);
static void __init multi_register_ports(struct uart_driver *drv);
static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd);
static int deep[256];
static int deep_count;
static int fcr_arr[256];
static int fcr_count;
static int ttr[256];
static int ttr_count;
static int rtr[256];
static int rtr_count;
module_param_array(deep,int,&deep_count,0);
module_param_array(fcr_arr,int,&fcr_count,0);
module_param_array(ttr,int,&ttr_count,0);
module_param_array(rtr,int,&rtr_count,0);
static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset)
{
return inb(mtpt->port.iobase + offset);
}
static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value)
{
outb(value, mtpt->port.iobase + offset);
}
static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset)
{
return inb(mtpt->option_base_addr + offset);
}
static int sb1053a_get_interface(struct mp_port *mtpt, int port_num)
{
unsigned long option_base_addr = mtpt->option_base_addr;
unsigned int interface = 0;
switch (port_num)
{
case 0:
case 1:
/* set GPO[1:0] = 00 */
outb(0x00, option_base_addr + MP_OPTR_GPODR);
break;
case 2:
case 3:
/* set GPO[1:0] = 01 */
outb(0x01, option_base_addr + MP_OPTR_GPODR);
break;
case 4:
case 5:
/* set GPO[1:0] = 10 */
outb(0x02, option_base_addr + MP_OPTR_GPODR);
break;
default:
break;
}
port_num &= 0x1;
/* get interface */
interface = inb(option_base_addr + MP_OPTR_IIR0 + port_num);
/* set GPO[1:0] = 11 */
outb(0x03, option_base_addr + MP_OPTR_GPODR);
return (interface);
}
static int sb1054_get_register(struct sb_uart_port *port, int page, int reg)
{
int ret = 0;
unsigned int lcr = 0;
unsigned int mcr = 0;
unsigned int tmp = 0;
if( page <= 0)
{
printk(" page 0 can not use this fuction\n");
return -1;
}
switch(page)
{
case 1:
lcr = SB105X_GET_LCR(port);
tmp = lcr | SB105X_LCR_DLAB;
SB105X_PUT_LCR(port, tmp);
tmp = SB105X_GET_LCR(port);
ret = SB105X_GET_REG(port,reg);
SB105X_PUT_LCR(port,lcr);
break;
case 2:
mcr = SB105X_GET_MCR(port);
tmp = mcr | SB105X_MCR_P2S;
SB105X_PUT_MCR(port,tmp);
ret = SB105X_GET_REG(port,reg);
SB105X_PUT_MCR(port,mcr);
break;
case 3:
lcr = SB105X_GET_LCR(port);
tmp = lcr | SB105X_LCR_BF;
SB105X_PUT_LCR(port,tmp);
SB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P3KEY);
ret = SB105X_GET_REG(port,reg);
SB105X_PUT_LCR(port,lcr);
break;
case 4:
lcr = SB105X_GET_LCR(port);
tmp = lcr | SB105X_LCR_BF;
SB105X_PUT_LCR(port,tmp);
SB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P4KEY);
ret = SB105X_GET_REG(port,reg);
SB105X_PUT_LCR(port,lcr);
break;
default:
printk(" error invalid page number \n");
return -1;
}
return ret;
}
static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value)
{
int lcr = 0;
int mcr = 0;
int ret = 0;
if( page <= 0)
{
printk(" page 0 can not use this fuction\n");
return -1;
}
switch(page)
{
case 1:
lcr = SB105X_GET_LCR(port);
SB105X_PUT_LCR(port, lcr | SB105X_LCR_DLAB);
SB105X_PUT_REG(port,reg,value);
SB105X_PUT_LCR(port, lcr);
ret = 1;
break;
case 2:
mcr = SB105X_GET_MCR(port);
SB105X_PUT_MCR(port, mcr | SB105X_MCR_P2S);
SB105X_PUT_REG(port,reg,value);
SB105X_PUT_MCR(port, mcr);
ret = 1;
break;
case 3:
lcr = SB105X_GET_LCR(port);
SB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);
SB105X_PUT_PSR(port, SB105X_PSR_P3KEY);
SB105X_PUT_REG(port,reg,value);
SB105X_PUT_LCR(port, lcr);
ret = 1;
break;
case 4:
lcr = SB105X_GET_LCR(port);
SB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);
SB105X_PUT_PSR(port, SB105X_PSR_P4KEY);
SB105X_PUT_REG(port,reg,value);
SB105X_PUT_LCR(port, lcr);
ret = 1;
break;
default:
printk(" error invalid page number \n");
return -1;
}
return ret;
}
static int set_multidrop_mode(struct sb_uart_port *port, unsigned int mode)
{
int mdr = SB105XA_MDR_NPS;
if (mode & MDMODE_ENABLE)
{
mdr |= SB105XA_MDR_MDE;
}
if (1) //(mode & MDMODE_AUTO)
{
int efr = 0;
mdr |= SB105XA_MDR_AME;
efr = sb1054_get_register(port, PAGE_3, SB105X_EFR);
efr |= SB105X_EFR_SCD;
sb1054_set_register(port, PAGE_3, SB105X_EFR, efr);
}
sb1054_set_register(port, PAGE_1, SB105XA_MDR, mdr);
port->mdmode &= ~0x6;
port->mdmode |= mode;
printk("[%d] multidrop init: %x\n", port->line, port->mdmode);
return 0;
}
static int get_multidrop_addr(struct sb_uart_port *port)
{
return sb1054_get_register(port, PAGE_3, SB105X_XOFF2);
}
static int set_multidrop_addr(struct sb_uart_port *port, unsigned int addr)
{
sb1054_set_register(port, PAGE_3, SB105X_XOFF2, addr);
return 0;
}
static void SendATCommand(struct mp_port *mtpt)
{
// a t cr lf
unsigned char ch[] = {0x61,0x74,0x0d,0x0a,0x0};
unsigned char lineControl;
unsigned char i=0;
unsigned char Divisor = 0xc;
lineControl = serial_inp(mtpt,UART_LCR);
serial_outp(mtpt,UART_LCR,(lineControl | UART_LCR_DLAB));
serial_outp(mtpt,UART_DLL,(Divisor & 0xff));
serial_outp(mtpt,UART_DLM,(Divisor & 0xff00)>>8); //baudrate is 4800
serial_outp(mtpt,UART_LCR,lineControl);
serial_outp(mtpt,UART_LCR,0x03); // N-8-1
serial_outp(mtpt,UART_FCR,7);
serial_outp(mtpt,UART_MCR,0x3);
while(ch[i]){
while((serial_inp(mtpt,UART_LSR) & 0x60) !=0x60){
;
}
serial_outp(mtpt,0,ch[i++]);
}
}// end of SendATCommand()
static int set_deep_fifo(struct sb_uart_port *port, int status)
{
int afr_status = 0;
afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);
if(status == ENABLE)
{
afr_status |= SB105X_AFR_AFEN;
}
else
{
afr_status &= ~SB105X_AFR_AFEN;
}
sb1054_set_register(port,PAGE_4,SB105X_AFR,afr_status);
sb1054_set_register(port,PAGE_4,SB105X_TTR,ttr[port->line]);
sb1054_set_register(port,PAGE_4,SB105X_RTR,rtr[port->line]);
afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);
return afr_status;
}
static int get_device_type(int arg)
{
int ret;
ret = inb(mp_devs[arg].option_reg_addr+MP_OPTR_DIR0);
ret = (ret & 0xf0) >> 4;
switch (ret)
{
case DIR_UART_16C550:
return PORT_16C55X;
case DIR_UART_16C1050:
return PORT_16C105X;
case DIR_UART_16C1050A:
/*
if (mtpt->port.line < 2)
{
return PORT_16C105XA;
}
else
{
if (mtpt->device->device_id & 0x50)
{
return PORT_16C55X;
}
else
{
return PORT_16C105X;
}
}*/
return PORT_16C105XA;
default:
return PORT_UNKNOWN;
}
}
static int get_deep_fifo(struct sb_uart_port *port)
{
int afr_status = 0;
afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);
return afr_status;
}
static int set_auto_rts(struct sb_uart_port *port, int status)
{
int atr_status = 0;
#if 0
int efr_status = 0;
efr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);
if(status == ENABLE)
efr_status |= SB105X_EFR_ARTS;
else
efr_status &= ~SB105X_EFR_ARTS;
sb1054_set_register(port,PAGE_3,SB105X_EFR,efr_status);
efr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);
#endif
//ATR
atr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);
switch(status)
{
case RS422PTP:
atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_A80);
break;
case RS422MD:
atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);
break;
case RS485NE:
atr_status = (SB105X_ATR_RCMS) | (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);
break;
case RS485ECHO:
atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);
break;
}
sb1054_set_register(port,PAGE_3,SB105X_ATR,atr_status);
atr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);
return atr_status;
}
static void mp_stop(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
port->ops->stop_tx(port);
spin_unlock_irqrestore(&port->lock, flags);
}
static void __mp_start(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
if (!uart_circ_empty(&state->info->xmit) && state->info->xmit.buf &&
!tty->stopped && !tty->hw_stopped)
port->ops->start_tx(port);
}
static void mp_start(struct tty_struct *tty)
{
__mp_start(tty);
}
static void mp_tasklet_action(unsigned long data)
{
struct sb_uart_state *state = (struct sb_uart_state *)data;
struct tty_struct *tty;
printk("tasklet is called!\n");
tty = state->info->tty;
tty_wakeup(tty);
}
static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear)
{
unsigned int old;
old = port->mctrl;
port->mctrl = (old & ~clear) | set;
if (old != port->mctrl)
port->ops->set_mctrl(port, port->mctrl);
}
#define uart_set_mctrl(port,set) mp_update_mctrl(port,set,0)
#define uart_clear_mctrl(port,clear) mp_update_mctrl(port,0,clear)
static int mp_startup(struct sb_uart_state *state, int init_hw)
{
struct sb_uart_info *info = state->info;
struct sb_uart_port *port = state->port;
unsigned long page;
int retval = 0;
if (info->flags & UIF_INITIALIZED)
return 0;
if (info->tty)
set_bit(TTY_IO_ERROR, &info->tty->flags);
if (port->type == PORT_UNKNOWN)
return 0;
if (!info->xmit.buf) {
page = get_zeroed_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
info->xmit.buf = (unsigned char *) page;
uart_circ_clear(&info->xmit);
}
retval = port->ops->startup(port);
if (retval == 0) {
if (init_hw) {
mp_change_speed(state, NULL);
if (info->tty->termios.c_cflag & CBAUD)
uart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR);
}
info->flags |= UIF_INITIALIZED;
clear_bit(TTY_IO_ERROR, &info->tty->flags);
}
if (retval && capable(CAP_SYS_ADMIN))
retval = 0;
return retval;
}
static void mp_shutdown(struct sb_uart_state *state)
{
struct sb_uart_info *info = state->info;
struct sb_uart_port *port = state->port;
if (info->tty)
set_bit(TTY_IO_ERROR, &info->tty->flags);
if (info->flags & UIF_INITIALIZED) {
info->flags &= ~UIF_INITIALIZED;
if (!info->tty || (info->tty->termios.c_cflag & HUPCL))
uart_clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
wake_up_interruptible(&info->delta_msr_wait);
port->ops->shutdown(port);
synchronize_irq(port->irq);
}
tasklet_kill(&info->tlet);
if (info->xmit.buf) {
free_page((unsigned long)info->xmit.buf);
info->xmit.buf = NULL;
}
}
static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios)
{
struct tty_struct *tty = state->info->tty;
struct sb_uart_port *port = state->port;
if (!tty || port->type == PORT_UNKNOWN)
return;
if (tty->termios.c_cflag & CRTSCTS)
state->info->flags |= UIF_CTS_FLOW;
else
state->info->flags &= ~UIF_CTS_FLOW;
if (tty->termios.c_cflag & CLOCAL)
state->info->flags &= ~UIF_CHECK_CD;
else
state->info->flags |= UIF_CHECK_CD;
port->ops->set_termios(port, &tty->termios, old_termios);
}
static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c)
{
unsigned long flags;
int ret = 0;
if (!circ->buf)
return 0;
spin_lock_irqsave(&port->lock, flags);
if (uart_circ_chars_free(circ) != 0) {
circ->buf[circ->head] = c;
circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
ret = 1;
}
spin_unlock_irqrestore(&port->lock, flags);
return ret;
}
static int mp_put_char(struct tty_struct *tty, unsigned char ch)
{
struct sb_uart_state *state = tty->driver_data;
return __mp_put_char(state->port, &state->info->xmit, ch);
}
static void mp_put_chars(struct tty_struct *tty)
{
mp_start(tty);
}
static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port;
struct circ_buf *circ;
int c, ret = 0;
if (!state || !state->info) {
return -EL3HLT;
}
port = state->port;
circ = &state->info->xmit;
if (!circ->buf)
return 0;
while (1) {
c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
if (count < c)
c = count;
if (c <= 0)
break;
memcpy(circ->buf + circ->head, buf, c);
circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
buf += c;
count -= c;
ret += c;
}
mp_start(tty);
return ret;
}
static int mp_write_room(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
return uart_circ_chars_free(&state->info->xmit);
}
static int mp_chars_in_buffer(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
return uart_circ_chars_pending(&state->info->xmit);
}
static void mp_flush_buffer(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port;
unsigned long flags;
if (!state || !state->info) {
return;
}
port = state->port;
spin_lock_irqsave(&port->lock, flags);
uart_circ_clear(&state->info->xmit);
spin_unlock_irqrestore(&port->lock, flags);
wake_up_interruptible(&tty->write_wait);
tty_wakeup(tty);
}
static void mp_send_xchar(struct tty_struct *tty, char ch)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
unsigned long flags;
if (port->ops->send_xchar)
port->ops->send_xchar(port, ch);
else {
port->x_char = ch;
if (ch) {
spin_lock_irqsave(&port->lock, flags);
port->ops->start_tx(port);
spin_unlock_irqrestore(&port->lock, flags);
}
}
}
static void mp_throttle(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
if (I_IXOFF(tty))
mp_send_xchar(tty, STOP_CHAR(tty));
if (tty->termios.c_cflag & CRTSCTS)
uart_clear_mctrl(state->port, TIOCM_RTS);
}
static void mp_unthrottle(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
if (I_IXOFF(tty)) {
if (port->x_char)
port->x_char = 0;
else
mp_send_xchar(tty, START_CHAR(tty));
}
if (tty->termios.c_cflag & CRTSCTS)
uart_set_mctrl(port, TIOCM_RTS);
}
static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo)
{
struct sb_uart_port *port = state->port;
struct serial_struct tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.type = port->type;
tmp.line = port->line;
tmp.port = port->iobase;
if (HIGH_BITS_OFFSET)
tmp.port_high = (long) port->iobase >> HIGH_BITS_OFFSET;
tmp.irq = port->irq;
tmp.flags = port->flags;
tmp.xmit_fifo_size = port->fifosize;
tmp.baud_base = port->uartclk / 16;
tmp.close_delay = state->close_delay;
tmp.closing_wait = state->closing_wait == USF_CLOSING_WAIT_NONE ?
ASYNC_CLOSING_WAIT_NONE :
state->closing_wait;
tmp.custom_divisor = port->custom_divisor;
tmp.hub6 = port->hub6;
tmp.io_type = port->iotype;
tmp.iomem_reg_shift = port->regshift;
tmp.iomem_base = (void *)port->mapbase;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo)
{
struct serial_struct new_serial;
struct sb_uart_port *port = state->port;
unsigned long new_port;
unsigned int change_irq, change_port, closing_wait;
unsigned int old_custom_divisor;
unsigned int old_flags, new_flags;
int retval = 0;
if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
return -EFAULT;
new_port = new_serial.port;
if (HIGH_BITS_OFFSET)
new_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET;
new_serial.irq = irq_canonicalize(new_serial.irq);
closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?
USF_CLOSING_WAIT_NONE : new_serial.closing_wait;
MP_STATE_LOCK(state);
change_irq = new_serial.irq != port->irq;
change_port = new_port != port->iobase ||
(unsigned long)new_serial.iomem_base != port->mapbase ||
new_serial.hub6 != port->hub6 ||
new_serial.io_type != port->iotype ||
new_serial.iomem_reg_shift != port->regshift ||
new_serial.type != port->type;
old_flags = port->flags;
new_flags = new_serial.flags;
old_custom_divisor = port->custom_divisor;
if (!capable(CAP_SYS_ADMIN)) {
retval = -EPERM;
if (change_irq || change_port ||
(new_serial.baud_base != port->uartclk / 16) ||
(new_serial.close_delay != state->close_delay) ||
(closing_wait != state->closing_wait) ||
(new_serial.xmit_fifo_size != port->fifosize) ||
(((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
goto exit;
port->flags = ((port->flags & ~UPF_USR_MASK) |
(new_flags & UPF_USR_MASK));
port->custom_divisor = new_serial.custom_divisor;
goto check_and_exit;
}
if (port->ops->verify_port)
retval = port->ops->verify_port(port, &new_serial);
if ((new_serial.irq >= NR_IRQS) || (new_serial.irq < 0) ||
(new_serial.baud_base < 9600))
retval = -EINVAL;
if (retval)
goto exit;
if (change_port || change_irq) {
retval = -EBUSY;
if (uart_users(state) > 1)
goto exit;
mp_shutdown(state);
}
if (change_port) {
unsigned long old_iobase, old_mapbase;
unsigned int old_type, old_iotype, old_hub6, old_shift;
old_iobase = port->iobase;
old_mapbase = port->mapbase;
old_type = port->type;
old_hub6 = port->hub6;
old_iotype = port->iotype;
old_shift = port->regshift;
if (old_type != PORT_UNKNOWN)
port->ops->release_port(port);
port->iobase = new_port;
port->type = new_serial.type;
port->hub6 = new_serial.hub6;
port->iotype = new_serial.io_type;
port->regshift = new_serial.iomem_reg_shift;
port->mapbase = (unsigned long)new_serial.iomem_base;
if (port->type != PORT_UNKNOWN) {
retval = port->ops->request_port(port);
} else {
retval = 0;
}
if (retval && old_type != PORT_UNKNOWN) {
port->iobase = old_iobase;
port->type = old_type;
port->hub6 = old_hub6;
port->iotype = old_iotype;
port->regshift = old_shift;
port->mapbase = old_mapbase;
retval = port->ops->request_port(port);
if (retval)
port->type = PORT_UNKNOWN;
retval = -EBUSY;
}
}
port->irq = new_serial.irq;
port->uartclk = new_serial.baud_base * 16;
port->flags = (port->flags & ~UPF_CHANGE_MASK) |
(new_flags & UPF_CHANGE_MASK);
port->custom_divisor = new_serial.custom_divisor;
state->close_delay = new_serial.close_delay;
state->closing_wait = closing_wait;
port->fifosize = new_serial.xmit_fifo_size;
if (state->info->tty)
state->info->tty->low_latency =
(port->flags & UPF_LOW_LATENCY) ? 1 : 0;
check_and_exit:
retval = 0;
if (port->type == PORT_UNKNOWN)
goto exit;
if (state->info->flags & UIF_INITIALIZED) {
if (((old_flags ^ port->flags) & UPF_SPD_MASK) ||
old_custom_divisor != port->custom_divisor) {
if (port->flags & UPF_SPD_MASK) {
printk(KERN_NOTICE
"%s sets custom speed on ttyMP%d. This "
"is deprecated.\n", current->comm,
port->line);
}
mp_change_speed(state, NULL);
}
} else
retval = mp_startup(state, 1);
exit:
MP_STATE_UNLOCK(state);
return retval;
}
static int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value)
{
struct sb_uart_port *port = state->port;
unsigned int result;
result = port->ops->tx_empty(port);
if (port->x_char ||
((uart_circ_chars_pending(&state->info->xmit) > 0) &&
!state->info->tty->stopped && !state->info->tty->hw_stopped))
result &= ~TIOCSER_TEMT;
return put_user(result, value);
}
static int mp_tiocmget(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
int result = -EIO;
MP_STATE_LOCK(state);
if (!(tty->flags & (1 << TTY_IO_ERROR))) {
result = port->mctrl;
spin_lock_irq(&port->lock);
result |= port->ops->get_mctrl(port);
spin_unlock_irq(&port->lock);
}
MP_STATE_UNLOCK(state);
return result;
}
static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
int ret = -EIO;
MP_STATE_LOCK(state);
if (!(tty->flags & (1 << TTY_IO_ERROR))) {
mp_update_mctrl(port, set, clear);
ret = 0;
}
MP_STATE_UNLOCK(state);
return ret;
}
static int mp_break_ctl(struct tty_struct *tty, int break_state)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
MP_STATE_LOCK(state);
if (port->type != PORT_UNKNOWN)
port->ops->break_ctl(port, break_state);
MP_STATE_UNLOCK(state);
return 0;
}
static int mp_do_autoconfig(struct sb_uart_state *state)
{
struct sb_uart_port *port = state->port;
int flags, ret;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (mutex_lock_interruptible(&state->mutex))
return -ERESTARTSYS;
ret = -EBUSY;
if (uart_users(state) == 1) {
mp_shutdown(state);
if (port->type != PORT_UNKNOWN)
port->ops->release_port(port);
flags = UART_CONFIG_TYPE;
if (port->flags & UPF_AUTO_IRQ)
flags |= UART_CONFIG_IRQ;
port->ops->config_port(port, flags);
ret = mp_startup(state, 1);
}
MP_STATE_UNLOCK(state);
return ret;
}
static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg)
{
struct sb_uart_port *port = state->port;
DECLARE_WAITQUEUE(wait, current);
struct sb_uart_icount cprev, cnow;
int ret;
spin_lock_irq(&port->lock);
memcpy(&cprev, &port->icount, sizeof(struct sb_uart_icount));
port->ops->enable_ms(port);
spin_unlock_irq(&port->lock);
add_wait_queue(&state->info->delta_msr_wait, &wait);
for (;;) {
spin_lock_irq(&port->lock);
memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));
spin_unlock_irq(&port->lock);
set_current_state(TASK_INTERRUPTIBLE);
if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||
((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
ret = 0;
break;
}
schedule();
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
cprev = cnow;
}
current->state = TASK_RUNNING;
remove_wait_queue(&state->info->delta_msr_wait, &wait);
return ret;
}
static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt)
{
struct serial_icounter_struct icount;
struct sb_uart_icount cnow;
struct sb_uart_port *port = state->port;
spin_lock_irq(&port->lock);
memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));
spin_unlock_irq(&port->lock);
icount.cts = cnow.cts;
icount.dsr = cnow.dsr;
icount.rng = cnow.rng;
icount.dcd = cnow.dcd;
icount.rx = cnow.rx;
icount.tx = cnow.tx;
icount.frame = cnow.frame;
icount.overrun = cnow.overrun;
icount.parity = cnow.parity;
icount.brk = cnow.brk;
icount.buf_overrun = cnow.buf_overrun;
return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0;
}
static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
{
struct sb_uart_state *state = tty->driver_data;
struct mp_port *info = (struct mp_port *)state->port;
int ret = -ENOIOCTLCMD;
switch (cmd) {
case TIOCSMULTIDROP:
/* set multi-drop mode enable or disable, and default operation mode is H/W mode */
if (info->port.type == PORT_16C105XA)
{
//arg &= ~0x6;
//state->port->mdmode = 0;
return set_multidrop_mode((struct sb_uart_port *)info, (unsigned int)arg);
}
ret = -ENOTSUPP;
break;
case GETDEEPFIFO:
ret = get_deep_fifo(state->port);
return ret;
case SETDEEPFIFO:
ret = set_deep_fifo(state->port,arg);
deep[state->port->line] = arg;
return ret;
case SETTTR:
if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){
ret = sb1054_set_register(state->port,PAGE_4,SB105X_TTR,arg);
ttr[state->port->line] = arg;
}
return ret;
case SETRTR:
if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){
ret = sb1054_set_register(state->port,PAGE_4,SB105X_RTR,arg);
rtr[state->port->line] = arg;
}
return ret;
case GETTTR:
if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){
ret = sb1054_get_register(state->port,PAGE_4,SB105X_TTR);
}
return ret;
case GETRTR:
if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){
ret = sb1054_get_register(state->port,PAGE_4,SB105X_RTR);
}
return ret;
case SETFCR:
if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){
ret = sb1054_set_register(state->port,PAGE_1,SB105X_FCR,arg);
}
else{
serial_out(info,2,arg);
}
return ret;
case TIOCSMDADDR:
/* set multi-drop address */
if (info->port.type == PORT_16C105XA)
{
state->port->mdmode |= MDMODE_ADDR;
return set_multidrop_addr((struct sb_uart_port *)info, (unsigned int)arg);
}
ret = -ENOTSUPP;
break;
case TIOCGMDADDR:
/* set multi-drop address */
if ((info->port.type == PORT_16C105XA) && (state->port->mdmode & MDMODE_ADDR))
{
return get_multidrop_addr((struct sb_uart_port *)info);
}
ret = -ENOTSUPP;
break;
case TIOCSENDADDR:
/* send address in multi-drop mode */
if ((info->port.type == PORT_16C105XA)
&& (state->port->mdmode & (MDMODE_ENABLE)))
{
if (mp_chars_in_buffer(tty) > 0)
{
tty_wait_until_sent(tty, 0);
}
//while ((serial_in(info, UART_LSR) & 0x60) != 0x60);
//while (sb1054_get_register(state->port, PAGE_2, SB105X_TFCR) != 0);
while ((serial_in(info, UART_LSR) & 0x60) != 0x60);
serial_out(info, UART_SCR, (int)arg);
}
break;
case TIOCGSERIAL:
ret = mp_get_info(state, (struct serial_struct *)arg);
break;
case TIOCSSERIAL:
ret = mp_set_info(state, (struct serial_struct *)arg);
break;
case TIOCSERCONFIG:
ret = mp_do_autoconfig(state);
break;
case TIOCSERGWILD: /* obsolete */
case TIOCSERSWILD: /* obsolete */
ret = 0;
break;
/* for Multiport */
case TIOCGNUMOFPORT: /* Get number of ports */
return NR_PORTS;
case TIOCGGETDEVID:
return mp_devs[arg].device_id;
case TIOCGGETREV:
return mp_devs[arg].revision;
case TIOCGGETNRPORTS:
return mp_devs[arg].nr_ports;
case TIOCGGETBDNO:
return NR_BOARD;
case TIOCGGETINTERFACE:
if (mp_devs[arg].revision == 0xc0)
{
/* for SB16C1053APCI */
return (sb1053a_get_interface(info, info->port.line));
}
else
{
return (inb(mp_devs[arg].option_reg_addr+MP_OPTR_IIR0+(state->port->line/8)));
}
case TIOCGGETPORTTYPE:
ret = get_device_type(arg);;
return ret;
case TIOCSMULTIECHO: /* set to multi-drop mode(RS422) or echo mode(RS485)*/
outb( ( inb(info->interface_config_addr) & ~0x03 ) | 0x01 ,
info->interface_config_addr);
return 0;
case TIOCSPTPNOECHO: /* set to multi-drop mode(RS422) or echo mode(RS485) */
outb( ( inb(info->interface_config_addr) & ~0x03 ) ,
info->interface_config_addr);
return 0;
}
if (ret != -ENOIOCTLCMD)
goto out;
if (tty->flags & (1 << TTY_IO_ERROR)) {
ret = -EIO;
goto out;
}
switch (cmd) {
case TIOCMIWAIT:
ret = mp_wait_modem_status(state, arg);
break;
case TIOCGICOUNT:
ret = mp_get_count(state, (struct serial_icounter_struct *)arg);
break;
}
if (ret != -ENOIOCTLCMD)
goto out;
MP_STATE_LOCK(state);
switch (cmd) {
case TIOCSERGETLSR: /* Get line status register */
ret = mp_get_lsr_info(state, (unsigned int *)arg);
break;
default: {
struct sb_uart_port *port = state->port;
if (port->ops->ioctl)
ret = port->ops->ioctl(port, cmd, arg);
break;
}
}
MP_STATE_UNLOCK(state);
out:
return ret;
}
static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios)
{
struct sb_uart_state *state = tty->driver_data;
unsigned long flags;
unsigned int cflag = tty->termios.c_cflag;
#define RELEVANT_IFLAG(iflag) ((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
if ((cflag ^ old_termios->c_cflag) == 0 &&
RELEVANT_IFLAG(tty->termios.c_iflag ^ old_termios->c_iflag) == 0)
return;
mp_change_speed(state, old_termios);
if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
uart_clear_mctrl(state->port, TIOCM_RTS | TIOCM_DTR);
if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
unsigned int mask = TIOCM_DTR;
if (!(cflag & CRTSCTS) ||
!test_bit(TTY_THROTTLED, &tty->flags))
mask |= TIOCM_RTS;
uart_set_mctrl(state->port, mask);
}
if ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) {
spin_lock_irqsave(&state->port->lock, flags);
tty->hw_stopped = 0;
__mp_start(tty);
spin_unlock_irqrestore(&state->port->lock, flags);
}
if (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) {
spin_lock_irqsave(&state->port->lock, flags);
if (!(state->port->ops->get_mctrl(state->port) & TIOCM_CTS)) {
tty->hw_stopped = 1;
state->port->ops->stop_tx(state->port);
}
spin_unlock_irqrestore(&state->port->lock, flags);
}
}
static void mp_close(struct tty_struct *tty, struct file *filp)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port;
printk("mp_close!\n");
if (!state || !state->port)
return;
port = state->port;
printk("close1 %d\n", __LINE__);
MP_STATE_LOCK(state);
printk("close2 %d\n", __LINE__);
if (tty_hung_up_p(filp))
goto done;
printk("close3 %d\n", __LINE__);
if ((tty->count == 1) && (state->count != 1)) {
printk("mp_close: bad serial port count; tty->count is 1, "
"state->count is %d\n", state->count);
state->count = 1;
}
printk("close4 %d\n", __LINE__);
if (--state->count < 0) {
printk("rs_close: bad serial port count for ttyMP%d: %d\n",
port->line, state->count);
state->count = 0;
}
if (state->count)
goto done;
tty->closing = 1;
printk("close5 %d\n", __LINE__);
if (state->closing_wait != USF_CLOSING_WAIT_NONE)
tty_wait_until_sent(tty, state->closing_wait);
printk("close6 %d\n", __LINE__);
if (state->info->flags & UIF_INITIALIZED) {
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
port->ops->stop_rx(port);
spin_unlock_irqrestore(&port->lock, flags);
mp_wait_until_sent(tty, port->timeout);
}
printk("close7 %d\n", __LINE__);
mp_shutdown(state);
printk("close8 %d\n", __LINE__);
mp_flush_buffer(tty);
tty_ldisc_flush(tty);
tty->closing = 0;
state->info->tty = NULL;
if (state->info->blocked_open)
{
if (state->close_delay)
{
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(state->close_delay);
}
}
else
{
mp_change_pm(state, 3);
}
printk("close8 %d\n", __LINE__);
state->info->flags &= ~UIF_NORMAL_ACTIVE;
wake_up_interruptible(&state->info->open_wait);
done:
printk("close done\n");
MP_STATE_UNLOCK(state);
module_put(THIS_MODULE);
}
static void mp_wait_until_sent(struct tty_struct *tty, int timeout)
{
struct sb_uart_state *state = tty->driver_data;
struct sb_uart_port *port = state->port;
unsigned long char_time, expire;
if (port->type == PORT_UNKNOWN || port->fifosize == 0)
return;
char_time = (port->timeout - HZ/50) / port->fifosize;
char_time = char_time / 5;
if (char_time == 0)
char_time = 1;
if (timeout && timeout < char_time)
char_time = timeout;
if (timeout == 0 || timeout > 2 * port->timeout)
timeout = 2 * port->timeout;
expire = jiffies + timeout;
while (!port->ops->tx_empty(port)) {
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(char_time);
if (signal_pending(current))
break;
if (time_after(jiffies, expire))
break;
}
set_current_state(TASK_RUNNING); /* might not be needed */
}
static void mp_hangup(struct tty_struct *tty)
{
struct sb_uart_state *state = tty->driver_data;
MP_STATE_LOCK(state);
if (state->info && state->info->flags & UIF_NORMAL_ACTIVE) {
mp_flush_buffer(tty);
mp_shutdown(state);
state->count = 0;
state->info->flags &= ~UIF_NORMAL_ACTIVE;
state->info->tty = NULL;
wake_up_interruptible(&state->info->open_wait);
wake_up_interruptible(&state->info->delta_msr_wait);
}
MP_STATE_UNLOCK(state);
}
static void mp_update_termios(struct sb_uart_state *state)
{
struct tty_struct *tty = state->info->tty;
struct sb_uart_port *port = state->port;
if (!(tty->flags & (1 << TTY_IO_ERROR))) {
mp_change_speed(state, NULL);
if (tty->termios.c_cflag & CBAUD)
uart_set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
}
static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state)
{
DECLARE_WAITQUEUE(wait, current);
struct sb_uart_info *info = state->info;
struct sb_uart_port *port = state->port;
unsigned int mctrl;
info->blocked_open++;
state->count--;
add_wait_queue(&info->open_wait, &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (tty_hung_up_p(filp) || info->tty == NULL)
break;
if (!(info->flags & UIF_INITIALIZED))
break;
if ((filp->f_flags & O_NONBLOCK) ||
(info->tty->termios.c_cflag & CLOCAL) ||
(info->tty->flags & (1 << TTY_IO_ERROR))) {
break;
}
if (info->tty->termios.c_cflag & CBAUD)
uart_set_mctrl(port, TIOCM_DTR);
spin_lock_irq(&port->lock);
port->ops->enable_ms(port);
mctrl = port->ops->get_mctrl(port);
spin_unlock_irq(&port->lock);
if (mctrl & TIOCM_CAR)
break;
MP_STATE_UNLOCK(state);
schedule();
MP_STATE_LOCK(state);
if (signal_pending(current))
break;
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&info->open_wait, &wait);
state->count++;
info->blocked_open--;
if (signal_pending(current))
return -ERESTARTSYS;
if (!info->tty || tty_hung_up_p(filp))
return -EAGAIN;
return 0;
}
static struct sb_uart_state *uart_get(struct uart_driver *drv, int line)
{
struct sb_uart_state *state;
MP_MUTEX_LOCK(mp_mutex);
state = drv->state + line;
if (mutex_lock_interruptible(&state->mutex)) {
state = ERR_PTR(-ERESTARTSYS);
goto out;
}
state->count++;
if (!state->port) {
state->count--;
MP_STATE_UNLOCK(state);
state = ERR_PTR(-ENXIO);
goto out;
}
if (!state->info) {
state->info = kmalloc(sizeof(struct sb_uart_info), GFP_KERNEL);
if (state->info) {
memset(state->info, 0, sizeof(struct sb_uart_info));
init_waitqueue_head(&state->info->open_wait);
init_waitqueue_head(&state->info->delta_msr_wait);
state->port->info = state->info;
tasklet_init(&state->info->tlet, mp_tasklet_action,
(unsigned long)state);
} else {
state->count--;
MP_STATE_UNLOCK(state);
state = ERR_PTR(-ENOMEM);
}
}
out:
MP_MUTEX_UNLOCK(mp_mutex);
return state;
}
static int mp_open(struct tty_struct *tty, struct file *filp)
{
struct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;
struct sb_uart_state *state;
int retval;
int line = tty->index;
struct mp_port *mtpt;
retval = -ENODEV;
if (line >= tty->driver->num)
goto fail;
state = uart_get(drv, line);
if (IS_ERR(state)) {
retval = PTR_ERR(state);
goto fail;
}
mtpt = (struct mp_port *)state->port;
tty->driver_data = state;
tty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0;
tty->alt_speed = 0;
state->info->tty = tty;
if (tty_hung_up_p(filp)) {
retval = -EAGAIN;
state->count--;
MP_STATE_UNLOCK(state);
goto fail;
}
if (state->count == 1)
mp_change_pm(state, 0);
retval = mp_startup(state, 0);
if (retval == 0)
retval = mp_block_til_ready(filp, state);
MP_STATE_UNLOCK(state);
if (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) {
state->info->flags |= UIF_NORMAL_ACTIVE;
mp_update_termios(state);
}
uart_clear_mctrl(state->port, TIOCM_RTS);
try_module_get(THIS_MODULE);
fail:
return retval;
}
static const char *mp_type(struct sb_uart_port *port)
{
const char *str = NULL;
if (port->ops->type)
str = port->ops->type(port);
if (!str)
str = "unknown";
return str;
}
static void mp_change_pm(struct sb_uart_state *state, int pm_state)
{
struct sb_uart_port *port = state->port;
if (port->ops->pm)
port->ops->pm(port, pm_state, state->pm_state);
state->pm_state = pm_state;
}
static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port)
{
char address[64];
switch (port->iotype) {
case UPIO_PORT:
snprintf(address, sizeof(address),"I/O 0x%x", port->iobase);
break;
case UPIO_HUB6:
snprintf(address, sizeof(address),"I/O 0x%x offset 0x%x", port->iobase, port->hub6);
break;
case UPIO_MEM:
snprintf(address, sizeof(address),"MMIO 0x%lx", port->mapbase);
break;
default:
snprintf(address, sizeof(address),"*unknown*" );
strlcpy(address, "*unknown*", sizeof(address));
break;
}
printk( "%s%d at %s (irq = %d) is a %s\n",
drv->dev_name, port->line, address, port->irq, mp_type(port));
}
static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port)
{
unsigned int flags;
if (!port->iobase && !port->mapbase && !port->membase)
{
DPRINTK("%s error \n",__FUNCTION__);
return;
}
flags = UART_CONFIG_TYPE;
if (port->flags & UPF_AUTO_IRQ)
flags |= UART_CONFIG_IRQ;
if (port->flags & UPF_BOOT_AUTOCONF) {
port->type = PORT_UNKNOWN;
port->ops->config_port(port, flags);
}
if (port->type != PORT_UNKNOWN) {
unsigned long flags;
mp_report_port(drv, port);
spin_lock_irqsave(&port->lock, flags);
port->ops->set_mctrl(port, 0);
spin_unlock_irqrestore(&port->lock, flags);
mp_change_pm(state, 3);
}
}
static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state)
{
struct sb_uart_port *port = state->port;
struct sb_uart_info *info = state->info;
if (info && info->tty)
tty_hangup(info->tty);
MP_STATE_LOCK(state);
state->info = NULL;
if (port->type != PORT_UNKNOWN)
port->ops->release_port(port);
port->type = PORT_UNKNOWN;
if (info) {
tasklet_kill(&info->tlet);
kfree(info);
}
MP_STATE_UNLOCK(state);
}
static struct tty_operations mp_ops = {
.open = mp_open,
.close = mp_close,
.write = mp_write,
.put_char = mp_put_char,
.flush_chars = mp_put_chars,
.write_room = mp_write_room,
.chars_in_buffer= mp_chars_in_buffer,
.flush_buffer = mp_flush_buffer,
.ioctl = mp_ioctl,
.throttle = mp_throttle,
.unthrottle = mp_unthrottle,
.send_xchar = mp_send_xchar,
.set_termios = mp_set_termios,
.stop = mp_stop,
.start = mp_start,
.hangup = mp_hangup,
.break_ctl = mp_break_ctl,
.wait_until_sent= mp_wait_until_sent,
#ifdef CONFIG_PROC_FS
.proc_fops = NULL,
#endif
.tiocmget = mp_tiocmget,
.tiocmset = mp_tiocmset,
};
static int mp_register_driver(struct uart_driver *drv)
{
struct tty_driver *normal = NULL;
int i, retval;
drv->state = kmalloc(sizeof(struct sb_uart_state) * drv->nr, GFP_KERNEL);
retval = -ENOMEM;
if (!drv->state)
{
printk("SB PCI Error: Kernel memory allocation error!\n");
goto out;
}
memset(drv->state, 0, sizeof(struct sb_uart_state) * drv->nr);
normal = alloc_tty_driver(drv->nr);
if (!normal)
{
printk("SB PCI Error: tty allocation error!\n");
goto out;
}
drv->tty_driver = normal;
normal->owner = drv->owner;
normal->magic = TTY_DRIVER_MAGIC;
normal->driver_name = drv->driver_name;
normal->name = drv->dev_name;
normal->major = drv->major;
normal->minor_start = drv->minor;
normal->num = MAX_MP_PORT ;
normal->type = TTY_DRIVER_TYPE_SERIAL;
normal->subtype = SERIAL_TYPE_NORMAL;
normal->init_termios = tty_std_termios;
normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
normal->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
normal->driver_state = drv;
tty_set_operations(normal, &mp_ops);
for (i = 0; i < drv->nr; i++) {
struct sb_uart_state *state = drv->state + i;
state->close_delay = 500;
state->closing_wait = 30000;
mutex_init(&state->mutex);
}
retval = tty_register_driver(normal);
out:
if (retval < 0) {
printk("Register tty driver Fail!\n");
put_tty_driver(normal);
kfree(drv->state);
}
return retval;
}
void mp_unregister_driver(struct uart_driver *drv)
{
struct tty_driver *normal = NULL;
normal = drv->tty_driver;
if (!normal)
{
return;
}
tty_unregister_driver(normal);
put_tty_driver(normal);
drv->tty_driver = NULL;
if (drv->state)
{
kfree(drv->state);
}
}
static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port)
{
struct sb_uart_state *state;
int ret = 0;
if (port->line >= drv->nr)
return -EINVAL;
state = drv->state + port->line;
MP_MUTEX_LOCK(mp_mutex);
if (state->port) {
ret = -EINVAL;
goto out;
}
state->port = port;
spin_lock_init(&port->lock);
port->cons = drv->cons;
port->info = state->info;
mp_configure_port(drv, state, port);
tty_register_device(drv->tty_driver, port->line, port->dev);
out:
MP_MUTEX_UNLOCK(mp_mutex);
return ret;
}
static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port)
{
struct sb_uart_state *state = drv->state + port->line;
if (state->port != port)
printk(KERN_ALERT "Removing wrong port: %p != %p\n",
state->port, port);
MP_MUTEX_LOCK(mp_mutex);
tty_unregister_device(drv->tty_driver, port->line);
mp_unconfigure_port(drv, state);
state->port = NULL;
MP_MUTEX_UNLOCK(mp_mutex);
return 0;
}
static void autoconfig(struct mp_port *mtpt, unsigned int probeflags)
{
unsigned char status1, scratch, scratch2, scratch3;
unsigned char save_lcr, save_mcr;
unsigned long flags;
unsigned char u_type;
unsigned char b_ret = 0;
if (!mtpt->port.iobase && !mtpt->port.mapbase && !mtpt->port.membase)
return;
DEBUG_AUTOCONF("ttyMP%d: autoconf (0x%04x, 0x%p): ",
mtpt->port.line, mtpt->port.iobase, mtpt->port.membase);
spin_lock_irqsave(&mtpt->port.lock, flags);
if (!(mtpt->port.flags & UPF_BUGGY_UART)) {
scratch = serial_inp(mtpt, UART_IER);
serial_outp(mtpt, UART_IER, 0);
#ifdef __i386__
outb(0xff, 0x080);
#endif
scratch2 = serial_inp(mtpt, UART_IER) & 0x0f;
serial_outp(mtpt, UART_IER, 0x0F);
#ifdef __i386__
outb(0, 0x080);
#endif
scratch3 = serial_inp(mtpt, UART_IER) & 0x0F;
serial_outp(mtpt, UART_IER, scratch);
if (scratch2 != 0 || scratch3 != 0x0F) {
DEBUG_AUTOCONF("IER test failed (%02x, %02x) ",
scratch2, scratch3);
goto out;
}
}
save_mcr = serial_in(mtpt, UART_MCR);
save_lcr = serial_in(mtpt, UART_LCR);
if (!(mtpt->port.flags & UPF_SKIP_TEST)) {
serial_outp(mtpt, UART_MCR, UART_MCR_LOOP | 0x0A);
status1 = serial_inp(mtpt, UART_MSR) & 0xF0;
serial_outp(mtpt, UART_MCR, save_mcr);
if (status1 != 0x90) {
DEBUG_AUTOCONF("LOOP test failed (%02x) ",
status1);
goto out;
}
}
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR, 0);
serial_outp(mtpt, UART_LCR, 0);
serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);
scratch = serial_in(mtpt, UART_IIR) >> 6;
DEBUG_AUTOCONF("iir=%d ", scratch);
if(mtpt->device->nr_ports >= 8)
b_ret = read_option_register(mtpt,(MP_OPTR_DIR0 + ((mtpt->port.line)/8)));
else
b_ret = read_option_register(mtpt,MP_OPTR_DIR0);
u_type = (b_ret & 0xf0) >> 4;
if(mtpt->port.type == PORT_UNKNOWN )
{
switch (u_type)
{
case DIR_UART_16C550:
mtpt->port.type = PORT_16C55X;
break;
case DIR_UART_16C1050:
mtpt->port.type = PORT_16C105X;
break;
case DIR_UART_16C1050A:
if (mtpt->port.line < 2)
{
mtpt->port.type = PORT_16C105XA;
}
else
{
if (mtpt->device->device_id & 0x50)
{
mtpt->port.type = PORT_16C55X;
}
else
{
mtpt->port.type = PORT_16C105X;
}
}
break;
default:
mtpt->port.type = PORT_UNKNOWN;
break;
}
}
if(mtpt->port.type == PORT_UNKNOWN )
{
printk("unknow2\n");
switch (scratch) {
case 0:
case 1:
mtpt->port.type = PORT_UNKNOWN;
break;
case 2:
case 3:
mtpt->port.type = PORT_16C55X;
break;
}
}
serial_outp(mtpt, UART_LCR, save_lcr);
mtpt->port.fifosize = uart_config[mtpt->port.type].dfl_xmit_fifo_size;
mtpt->capabilities = uart_config[mtpt->port.type].flags;
if (mtpt->port.type == PORT_UNKNOWN)
goto out;
serial_outp(mtpt, UART_MCR, save_mcr);
serial_outp(mtpt, UART_FCR, (UART_FCR_ENABLE_FIFO |
UART_FCR_CLEAR_RCVR |
UART_FCR_CLEAR_XMIT));
serial_outp(mtpt, UART_FCR, 0);
(void)serial_in(mtpt, UART_RX);
serial_outp(mtpt, UART_IER, 0);
out:
spin_unlock_irqrestore(&mtpt->port.lock, flags);
DEBUG_AUTOCONF("type=%s\n", uart_config[mtpt->port.type].name);
}
static void autoconfig_irq(struct mp_port *mtpt)
{
unsigned char save_mcr, save_ier;
unsigned long irqs;
int irq;
/* forget possible initially masked and pending IRQ */
probe_irq_off(probe_irq_on());
save_mcr = serial_inp(mtpt, UART_MCR);
save_ier = serial_inp(mtpt, UART_IER);
serial_outp(mtpt, UART_MCR, UART_MCR_OUT1 | UART_MCR_OUT2);
irqs = probe_irq_on();
serial_outp(mtpt, UART_MCR, 0);
serial_outp(mtpt, UART_MCR,
UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2);
serial_outp(mtpt, UART_IER, 0x0f); /* enable all intrs */
(void)serial_inp(mtpt, UART_LSR);
(void)serial_inp(mtpt, UART_RX);
(void)serial_inp(mtpt, UART_IIR);
(void)serial_inp(mtpt, UART_MSR);
serial_outp(mtpt, UART_TX, 0xFF);
irq = probe_irq_off(irqs);
serial_outp(mtpt, UART_MCR, save_mcr);
serial_outp(mtpt, UART_IER, save_ier);
mtpt->port.irq = (irq > 0) ? irq : 0;
}
static void multi_stop_tx(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
if (mtpt->ier & UART_IER_THRI) {
mtpt->ier &= ~UART_IER_THRI;
serial_out(mtpt, UART_IER, mtpt->ier);
}
tasklet_schedule(&port->info->tlet);
}
static void multi_start_tx(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
if (!(mtpt->ier & UART_IER_THRI)) {
mtpt->ier |= UART_IER_THRI;
serial_out(mtpt, UART_IER, mtpt->ier);
}
}
static void multi_stop_rx(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
mtpt->ier &= ~UART_IER_RLSI;
mtpt->port.read_status_mask &= ~UART_LSR_DR;
serial_out(mtpt, UART_IER, mtpt->ier);
}
static void multi_enable_ms(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
mtpt->ier |= UART_IER_MSI;
serial_out(mtpt, UART_IER, mtpt->ier);
}
static _INLINE_ void receive_chars(struct mp_port *mtpt, int *status )
{
struct tty_struct *tty = mtpt->port.info->tty;
unsigned char lsr = *status;
int max_count = 256;
unsigned char ch;
char flag;
//lsr &= mtpt->port.read_status_mask;
do {
if ((lsr & UART_LSR_PE) && (mtpt->port.mdmode & MDMODE_ENABLE))
{
ch = serial_inp(mtpt, UART_RX);
}
else if (lsr & UART_LSR_SPECIAL)
{
flag = 0;
ch = serial_inp(mtpt, UART_RX);
if (lsr & UART_LSR_BI)
{
mtpt->port.icount.brk++;
flag = TTY_BREAK;
if (sb_uart_handle_break(&mtpt->port))
goto ignore_char;
}
if (lsr & UART_LSR_PE)
{
mtpt->port.icount.parity++;
flag = TTY_PARITY;
}
if (lsr & UART_LSR_FE)
{
mtpt->port.icount.frame++;
flag = TTY_FRAME;
}
if (lsr & UART_LSR_OE)
{
mtpt->port.icount.overrun++;
flag = TTY_OVERRUN;
}
tty_insert_flip_char(tty, ch, flag);
}
else
{
ch = serial_inp(mtpt, UART_RX);
tty_insert_flip_char(tty, ch, 0);
}
ignore_char:
lsr = serial_inp(mtpt, UART_LSR);
} while ((lsr & UART_LSR_DR) && (max_count-- > 0));
tty_flip_buffer_push(tty);
}
static _INLINE_ void transmit_chars(struct mp_port *mtpt)
{
struct circ_buf *xmit = &mtpt->port.info->xmit;
int count;
if (mtpt->port.x_char) {
serial_outp(mtpt, UART_TX, mtpt->port.x_char);
mtpt->port.icount.tx++;
mtpt->port.x_char = 0;
return;
}
if (uart_circ_empty(xmit) || uart_tx_stopped(&mtpt->port)) {
multi_stop_tx(&mtpt->port);
return;
}
count = uart_circ_chars_pending(xmit);
if(count > mtpt->port.fifosize)
{
count = mtpt->port.fifosize;
}
printk("[%d] mdmode: %x\n", mtpt->port.line, mtpt->port.mdmode);
do {
#if 0
/* check multi-drop mode */
if ((mtpt->port.mdmode & (MDMODE_ENABLE | MDMODE_ADDR)) == (MDMODE_ENABLE | MDMODE_ADDR))
{
printk("send address\n");
/* send multi-drop address */
serial_out(mtpt, UART_SCR, xmit->buf[xmit->tail]);
}
else
#endif
{
serial_out(mtpt, UART_TX, xmit->buf[xmit->tail]);
}
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
mtpt->port.icount.tx++;
} while (--count > 0);
}
static _INLINE_ void check_modem_status(struct mp_port *mtpt)
{
int status;
status = serial_in(mtpt, UART_MSR);
if ((status & UART_MSR_ANY_DELTA) == 0)
return;
if (status & UART_MSR_TERI)
mtpt->port.icount.rng++;
if (status & UART_MSR_DDSR)
mtpt->port.icount.dsr++;
if (status & UART_MSR_DDCD)
sb_uart_handle_dcd_change(&mtpt->port, status & UART_MSR_DCD);
if (status & UART_MSR_DCTS)
sb_uart_handle_cts_change(&mtpt->port, status & UART_MSR_CTS);
wake_up_interruptible(&mtpt->port.info->delta_msr_wait);
}
static inline void multi_handle_port(struct mp_port *mtpt)
{
unsigned int status = serial_inp(mtpt, UART_LSR);
//printk("lsr: %x\n", status);
if ((status & UART_LSR_DR) || (status & UART_LSR_SPECIAL))
receive_chars(mtpt, &status);
check_modem_status(mtpt);
if (status & UART_LSR_THRE)
{
if ((mtpt->port.type == PORT_16C105X)
|| (mtpt->port.type == PORT_16C105XA))
transmit_chars(mtpt);
else
{
if (mtpt->interface >= RS485NE)
uart_set_mctrl(&mtpt->port, TIOCM_RTS);
transmit_chars(mtpt);
if (mtpt->interface >= RS485NE)
{
while((status=serial_in(mtpt,UART_LSR) &0x60)!=0x60);
uart_clear_mctrl(&mtpt->port, TIOCM_RTS);
}
}
}
}
static irqreturn_t multi_interrupt(int irq, void *dev_id)
{
struct irq_info *iinfo = dev_id;
struct list_head *lhead, *end = NULL;
int pass_counter = 0;
spin_lock(&iinfo->lock);
lhead = iinfo->head;
do {
struct mp_port *mtpt;
unsigned int iir;
mtpt = list_entry(lhead, struct mp_port, list);
iir = serial_in(mtpt, UART_IIR);
printk("interrupt! port %d, iir 0x%x\n", mtpt->port.line, iir); //wlee
if (!(iir & UART_IIR_NO_INT))
{
printk("interrupt handle\n");
spin_lock(&mtpt->port.lock);
multi_handle_port(mtpt);
spin_unlock(&mtpt->port.lock);
end = NULL;
} else if (end == NULL)
end = lhead;
lhead = lhead->next;
if (lhead == iinfo->head && pass_counter++ > PASS_LIMIT)
{
printk(KERN_ERR "multi: too much work for "
"irq%d\n", irq);
printk( "multi: too much work for "
"irq%d\n", irq);
break;
}
} while (lhead != end);
spin_unlock(&iinfo->lock);
return IRQ_HANDLED;
}
static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt)
{
spin_lock_irq(&i->lock);
if (!list_empty(i->head)) {
if (i->head == &mtpt->list)
i->head = i->head->next;
list_del(&mtpt->list);
} else {
i->head = NULL;
}
spin_unlock_irq(&i->lock);
}
static int serial_link_irq_chain(struct mp_port *mtpt)
{
struct irq_info *i = irq_lists + mtpt->port.irq;
int ret, irq_flags = mtpt->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0;
spin_lock_irq(&i->lock);
if (i->head) {
list_add(&mtpt->list, i->head);
spin_unlock_irq(&i->lock);
ret = 0;
} else {
INIT_LIST_HEAD(&mtpt->list);
i->head = &mtpt->list;
spin_unlock_irq(&i->lock);
ret = request_irq(mtpt->port.irq, multi_interrupt,
irq_flags, "serial", i);
if (ret < 0)
serial_do_unlink(i, mtpt);
}
return ret;
}
static void serial_unlink_irq_chain(struct mp_port *mtpt)
{
struct irq_info *i = irq_lists + mtpt->port.irq;
if (list_empty(i->head))
{
free_irq(mtpt->port.irq, i);
}
serial_do_unlink(i, mtpt);
}
static void multi_timeout(unsigned long data)
{
struct mp_port *mtpt = (struct mp_port *)data;
spin_lock(&mtpt->port.lock);
multi_handle_port(mtpt);
spin_unlock(&mtpt->port.lock);
mod_timer(&mtpt->timer, jiffies+1 );
}
static unsigned int multi_tx_empty(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned long flags;
unsigned int ret;
spin_lock_irqsave(&mtpt->port.lock, flags);
ret = serial_in(mtpt, UART_LSR) & UART_LSR_TEMT ? TIOCSER_TEMT : 0;
spin_unlock_irqrestore(&mtpt->port.lock, flags);
return ret;
}
static unsigned int multi_get_mctrl(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned char status;
unsigned int ret;
status = serial_in(mtpt, UART_MSR);
ret = 0;
if (status & UART_MSR_DCD)
ret |= TIOCM_CAR;
if (status & UART_MSR_RI)
ret |= TIOCM_RNG;
if (status & UART_MSR_DSR)
ret |= TIOCM_DSR;
if (status & UART_MSR_CTS)
ret |= TIOCM_CTS;
return ret;
}
static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned char mcr = 0;
mctrl &= 0xff;
if (mctrl & TIOCM_RTS)
mcr |= UART_MCR_RTS;
if (mctrl & TIOCM_DTR)
mcr |= UART_MCR_DTR;
if (mctrl & TIOCM_OUT1)
mcr |= UART_MCR_OUT1;
if (mctrl & TIOCM_OUT2)
mcr |= UART_MCR_OUT2;
if (mctrl & TIOCM_LOOP)
mcr |= UART_MCR_LOOP;
serial_out(mtpt, UART_MCR, mcr);
}
static void multi_break_ctl(struct sb_uart_port *port, int break_state)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned long flags;
spin_lock_irqsave(&mtpt->port.lock, flags);
if (break_state == -1)
mtpt->lcr |= UART_LCR_SBC;
else
mtpt->lcr &= ~UART_LCR_SBC;
serial_out(mtpt, UART_LCR, mtpt->lcr);
spin_unlock_irqrestore(&mtpt->port.lock, flags);
}
static int multi_startup(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned long flags;
int retval;
mtpt->capabilities = uart_config[mtpt->port.type].flags;
mtpt->mcr = 0;
if (mtpt->capabilities & UART_CLEAR_FIFO) {
serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);
serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |
UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT);
serial_outp(mtpt, UART_FCR, 0);
}
(void) serial_inp(mtpt, UART_LSR);
(void) serial_inp(mtpt, UART_RX);
(void) serial_inp(mtpt, UART_IIR);
(void) serial_inp(mtpt, UART_MSR);
//test-wlee 9-bit disable
serial_outp(mtpt, UART_MSR, 0);
if (!(mtpt->port.flags & UPF_BUGGY_UART) &&
(serial_inp(mtpt, UART_LSR) == 0xff)) {
printk("ttyS%d: LSR safety check engaged!\n", mtpt->port.line);
//return -ENODEV;
}
if ((!is_real_interrupt(mtpt->port.irq)) || (mtpt->poll_type==TYPE_POLL)) {
unsigned int timeout = mtpt->port.timeout;
timeout = timeout > 6 ? (timeout / 2 - 2) : 1;
mtpt->timer.data = (unsigned long)mtpt;
mod_timer(&mtpt->timer, jiffies + timeout);
}
else
{
retval = serial_link_irq_chain(mtpt);
if (retval)
return retval;
}
serial_outp(mtpt, UART_LCR, UART_LCR_WLEN8);
spin_lock_irqsave(&mtpt->port.lock, flags);
if ((is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_INTERRUPT))
mtpt->port.mctrl |= TIOCM_OUT2;
multi_set_mctrl(&mtpt->port, mtpt->port.mctrl);
spin_unlock_irqrestore(&mtpt->port.lock, flags);
mtpt->ier = UART_IER_RLSI | UART_IER_RDI;
serial_outp(mtpt, UART_IER, mtpt->ier);
(void) serial_inp(mtpt, UART_LSR);
(void) serial_inp(mtpt, UART_RX);
(void) serial_inp(mtpt, UART_IIR);
(void) serial_inp(mtpt, UART_MSR);
return 0;
}
static void multi_shutdown(struct sb_uart_port *port)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned long flags;
mtpt->ier = 0;
serial_outp(mtpt, UART_IER, 0);
spin_lock_irqsave(&mtpt->port.lock, flags);
mtpt->port.mctrl &= ~TIOCM_OUT2;
multi_set_mctrl(&mtpt->port, mtpt->port.mctrl);
spin_unlock_irqrestore(&mtpt->port.lock, flags);
serial_out(mtpt, UART_LCR, serial_inp(mtpt, UART_LCR) & ~UART_LCR_SBC);
serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |
UART_FCR_CLEAR_RCVR |
UART_FCR_CLEAR_XMIT);
serial_outp(mtpt, UART_FCR, 0);
(void) serial_in(mtpt, UART_RX);
if ((!is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_POLL))
{
del_timer_sync(&mtpt->timer);
}
else
{
serial_unlink_irq_chain(mtpt);
}
}
static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud)
{
unsigned int quot;
if ((port->flags & UPF_MAGIC_MULTIPLIER) &&
baud == (port->uartclk/4))
quot = 0x8001;
else if ((port->flags & UPF_MAGIC_MULTIPLIER) &&
baud == (port->uartclk/8))
quot = 0x8002;
else
quot = sb_uart_get_divisor(port, baud);
return quot;
}
static void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old)
{
struct mp_port *mtpt = (struct mp_port *)port;
unsigned char cval, fcr = 0;
unsigned long flags;
unsigned int baud, quot;
switch (termios->c_cflag & CSIZE) {
case CS5:
cval = 0x00;
break;
case CS6:
cval = 0x01;
break;
case CS7:
cval = 0x02;
break;
default:
case CS8:
cval = 0x03;
break;
}
if (termios->c_cflag & CSTOPB)
cval |= 0x04;
if (termios->c_cflag & PARENB)
cval |= UART_LCR_PARITY;
if (!(termios->c_cflag & PARODD))
cval |= UART_LCR_EPAR;
#ifdef CMSPAR
if (termios->c_cflag & CMSPAR)
cval |= UART_LCR_SPAR;
#endif
baud = sb_uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);
quot = multi_get_divisor(port, baud);
if (mtpt->capabilities & UART_USE_FIFO) {
//if (baud < 2400)
// fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1;
//else
// fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8;
// fcr = UART_FCR_ENABLE_FIFO | 0x90;
fcr = fcr_arr[mtpt->port.line];
}
spin_lock_irqsave(&mtpt->port.lock, flags);
sb_uart_update_timeout(port, termios->c_cflag, baud);
mtpt->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR;
if (termios->c_iflag & INPCK)
mtpt->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE;
if (termios->c_iflag & (BRKINT | PARMRK))
mtpt->port.read_status_mask |= UART_LSR_BI;
mtpt->port.ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
mtpt->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE;
if (termios->c_iflag & IGNBRK) {
mtpt->port.ignore_status_mask |= UART_LSR_BI;
if (termios->c_iflag & IGNPAR)
mtpt->port.ignore_status_mask |= UART_LSR_OE;
}
if ((termios->c_cflag & CREAD) == 0)
mtpt->port.ignore_status_mask |= UART_LSR_DR;
mtpt->ier &= ~UART_IER_MSI;
if (UART_ENABLE_MS(&mtpt->port, termios->c_cflag))
mtpt->ier |= UART_IER_MSI;
serial_out(mtpt, UART_IER, mtpt->ier);
if (mtpt->capabilities & UART_STARTECH) {
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR,
termios->c_cflag & CRTSCTS ? UART_EFR_CTS :0);
}
serial_outp(mtpt, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */
serial_outp(mtpt, UART_DLL, quot & 0xff); /* LS of divisor */
serial_outp(mtpt, UART_DLM, quot >> 8); /* MS of divisor */
serial_outp(mtpt, UART_LCR, cval); /* reset DLAB */
mtpt->lcr = cval; /* Save LCR */
if (fcr & UART_FCR_ENABLE_FIFO) {
/* emulated UARTs (Lucent Venus 167x) need two steps */
serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);
}
serial_outp(mtpt, UART_FCR, fcr); /* set fcr */
if ((mtpt->port.type == PORT_16C105X)
|| (mtpt->port.type == PORT_16C105XA))
{
if(deep[mtpt->port.line]!=0)
set_deep_fifo(port, ENABLE);
if (mtpt->interface != RS232)
set_auto_rts(port,mtpt->interface);
}
else
{
if (mtpt->interface >= RS485NE)
{
uart_clear_mctrl(&mtpt->port, TIOCM_RTS);
}
}
if(mtpt->device->device_id == PCI_DEVICE_ID_MP4M)
{
SendATCommand(mtpt);
printk("SendATCommand\n");
}
multi_set_mctrl(&mtpt->port, mtpt->port.mctrl);
spin_unlock_irqrestore(&mtpt->port.lock, flags);
}
static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate)
{
struct mp_port *mtpt = (struct mp_port *)port;
if (state) {
if (mtpt->capabilities & UART_STARTECH) {
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR, UART_EFR_ECB);
serial_outp(mtpt, UART_LCR, 0);
serial_outp(mtpt, UART_IER, UART_IERX_SLEEP);
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR, 0);
serial_outp(mtpt, UART_LCR, 0);
}
if (mtpt->pm)
mtpt->pm(port, state, oldstate);
}
else
{
if (mtpt->capabilities & UART_STARTECH) {
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR, UART_EFR_ECB);
serial_outp(mtpt, UART_LCR, 0);
serial_outp(mtpt, UART_IER, 0);
serial_outp(mtpt, UART_LCR, 0xBF);
serial_outp(mtpt, UART_EFR, 0);
serial_outp(mtpt, UART_LCR, 0);
}
if (mtpt->pm)
mtpt->pm(port, state, oldstate);
}
}
static void multi_release_std_resource(struct mp_port *mtpt)
{
unsigned int size = 8 << mtpt->port.regshift;
switch (mtpt->port.iotype) {
case UPIO_MEM:
if (!mtpt->port.mapbase)
break;
if (mtpt->port.flags & UPF_IOREMAP) {
iounmap(mtpt->port.membase);
mtpt->port.membase = NULL;
}
release_mem_region(mtpt->port.mapbase, size);
break;
case UPIO_HUB6:
case UPIO_PORT:
release_region(mtpt->port.iobase,size);
break;
}
}
static void multi_release_port(struct sb_uart_port *port)
{
}
static int multi_request_port(struct sb_uart_port *port)
{
return 0;
}
static void multi_config_port(struct sb_uart_port *port, int flags)
{
struct mp_port *mtpt = (struct mp_port *)port;
int probeflags = PROBE_ANY;
if (flags & UART_CONFIG_TYPE)
autoconfig(mtpt, probeflags);
if (mtpt->port.type != PORT_UNKNOWN && flags & UART_CONFIG_IRQ)
autoconfig_irq(mtpt);
if (mtpt->port.type == PORT_UNKNOWN)
multi_release_std_resource(mtpt);
}
static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser)
{
if (ser->irq >= NR_IRQS || ser->irq < 0 ||
ser->baud_base < 9600 || ser->type < PORT_UNKNOWN ||
ser->type == PORT_STARTECH)
return -EINVAL;
return 0;
}
static const char *multi_type(struct sb_uart_port *port)
{
int type = port->type;
if (type >= ARRAY_SIZE(uart_config))
type = 0;
return uart_config[type].name;
}
static struct sb_uart_ops multi_pops = {
.tx_empty = multi_tx_empty,
.set_mctrl = multi_set_mctrl,
.get_mctrl = multi_get_mctrl,
.stop_tx = multi_stop_tx,
.start_tx = multi_start_tx,
.stop_rx = multi_stop_rx,
.enable_ms = multi_enable_ms,
.break_ctl = multi_break_ctl,
.startup = multi_startup,
.shutdown = multi_shutdown,
.set_termios = multi_set_termios,
.pm = multi_pm,
.type = multi_type,
.release_port = multi_release_port,
.request_port = multi_request_port,
.config_port = multi_config_port,
.verify_port = multi_verify_port,
};
static struct uart_driver multi_reg = {
.owner = THIS_MODULE,
.driver_name = "goldel_tulip",
.dev_name = "ttyMP",
.major = SB_TTY_MP_MAJOR,
.minor = 0,
.nr = MAX_MP_PORT,
.cons = NULL,
};
static void __init multi_init_ports(void)
{
struct mp_port *mtpt;
static int first = 1;
int i,j,k;
unsigned char osc;
unsigned char b_ret = 0;
static struct mp_device_t *sbdev;
if (!first)
return;
first = 0;
mtpt = multi_ports;
for (k=0;k<NR_BOARD;k++)
{
sbdev = &mp_devs[k];
for (i = 0; i < sbdev->nr_ports; i++, mtpt++)
{
mtpt->device = sbdev;
mtpt->port.iobase = sbdev->uart_access_addr + 8*i;
mtpt->port.irq = sbdev->irq;
if ( ((sbdev->device_id == PCI_DEVICE_ID_MP4)&&(sbdev->revision==0x91)))
mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i;
else if (sbdev->revision == 0xc0)
mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + (i & 0x1);
else
mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i/8;
mtpt->option_base_addr = sbdev->option_reg_addr;
mtpt->poll_type = sbdev->poll_type;
mtpt->port.uartclk = BASE_BAUD * 16;
/* get input clock information */
osc = inb(sbdev->option_reg_addr + MP_OPTR_DIR0 + i/8) & 0x0F;
if (osc==0x0f)
osc = 0;
for(j=0;j<osc;j++)
mtpt->port.uartclk *= 2;
mtpt->port.flags |= STD_COM_FLAGS | UPF_SHARE_IRQ ;
mtpt->port.iotype = UPIO_PORT;
mtpt->port.ops = &multi_pops;
if (sbdev->revision == 0xc0)
{
/* for SB16C1053APCI */
b_ret = sb1053a_get_interface(mtpt, i);
}
else
{
b_ret = read_option_register(mtpt,(MP_OPTR_IIR0 + i/8));
printk("IIR_RET = %x\n",b_ret);
}
/* default to RS232 */
mtpt->interface = RS232;
if (IIR_RS422 == (b_ret & IIR_TYPE_MASK))
mtpt->interface = RS422PTP;
if (IIR_RS485 == (b_ret & IIR_TYPE_MASK))
mtpt->interface = RS485NE;
}
}
}
static void __init multi_register_ports(struct uart_driver *drv)
{
int i;
multi_init_ports();
for (i = 0; i < NR_PORTS; i++) {
struct mp_port *mtpt = &multi_ports[i];
mtpt->port.line = i;
mtpt->port.ops = &multi_pops;
init_timer(&mtpt->timer);
mtpt->timer.function = multi_timeout;
mp_add_one_port(drv, &mtpt->port);
}
}
/**
* pci_remap_base - remap BAR value of pci device
*
* PARAMETERS
* pcidev - pci_dev structure address
* offset - BAR offset PCI_BASE_ADDRESS_0 ~ PCI_BASE_ADDRESS_4
* address - address to be changed BAR value
* size - size of address space
*
* RETURNS
* If this function performs successful, it returns 0. Otherwise, It returns -1.
*/
static int pci_remap_base(struct pci_dev *pcidev, unsigned int offset,
unsigned int address, unsigned int size)
{
#if 0
struct resource *root;
unsigned index = (offset - 0x10) >> 2;
#endif
pci_write_config_dword(pcidev, offset, address);
#if 0
root = pcidev->resource[index].parent;
release_resource(&pcidev->resource[index]);
address &= ~0x1;
pcidev->resource[index].start = address;
pcidev->resource[index].end = address + size - 1;
if (request_resource(root, &pcidev->resource[index]) != NULL)
{
printk(KERN_ERR "pci remap conflict!! 0x%x\n", address);
return (-1);
}
#endif
return (0);
}
static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd)
{
static struct mp_device_t *sbdev = mp_devs;
unsigned long addr = 0;
int j;
struct resource *ret = NULL;
sbdev->device_id = brd.device_id;
pci_read_config_byte(pcidev, PCI_CLASS_REVISION, &(sbdev->revision));
sbdev->name = brd.name;
sbdev->uart_access_addr = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;
/* check revision. The SB16C1053APCI's option i/o address is BAR4 */
if (sbdev->revision == 0xc0)
{
/* SB16C1053APCI */
sbdev->option_reg_addr = pcidev->resource[4].start & PCI_BASE_ADDRESS_IO_MASK;
}
else
{
sbdev->option_reg_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;
}
#if 1
if (sbdev->revision == 0xc0)
{
outb(0x00, sbdev->option_reg_addr + MP_OPTR_GPOCR);
inb(sbdev->option_reg_addr + MP_OPTR_GPOCR);
outb(0x83, sbdev->option_reg_addr + MP_OPTR_GPOCR);
}
#endif
sbdev->irq = pcidev->irq;
if ((brd.device_id & 0x0800) || !(brd.device_id &0xff00))
{
sbdev->poll_type = TYPE_INTERRUPT;
}
else
{
sbdev->poll_type = TYPE_POLL;
}
/* codes which is specific to each board*/
switch(brd.device_id){
case PCI_DEVICE_ID_MP1 :
case PCIE_DEVICE_ID_MP1 :
case PCIE_DEVICE_ID_MP1E :
case PCIE_DEVICE_ID_GT_MP1 :
sbdev->nr_ports = 1;
break;
case PCI_DEVICE_ID_MP2 :
case PCIE_DEVICE_ID_MP2 :
case PCIE_DEVICE_ID_GT_MP2 :
case PCIE_DEVICE_ID_MP2B :
case PCIE_DEVICE_ID_MP2E :
sbdev->nr_ports = 2;
/* serial base address remap */
if (sbdev->revision == 0xc0)
{
int prev_port_addr = 0;
pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);
}
break;
case PCI_DEVICE_ID_MP4 :
case PCI_DEVICE_ID_MP4A :
case PCIE_DEVICE_ID_MP4 :
case PCI_DEVICE_ID_GT_MP4 :
case PCI_DEVICE_ID_GT_MP4A :
case PCIE_DEVICE_ID_GT_MP4 :
case PCI_DEVICE_ID_MP4M :
case PCIE_DEVICE_ID_MP4B :
sbdev->nr_ports = 4;
if(sbdev->revision == 0x91){
sbdev->reserved_addr[0] = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;
outb(0x03 , sbdev->reserved_addr[0] + 0x01);
outb(0x03 , sbdev->reserved_addr[0] + 0x02);
outb(0x01 , sbdev->reserved_addr[0] + 0x20);
outb(0x00 , sbdev->reserved_addr[0] + 0x21);
request_region(sbdev->reserved_addr[0], 32, sbdev->name);
sbdev->uart_access_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;
sbdev->option_reg_addr = pcidev->resource[2].start & PCI_BASE_ADDRESS_IO_MASK;
}
/* SB16C1053APCI */
if (sbdev->revision == 0xc0)
{
int prev_port_addr = 0;
pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 8);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 24, 8);
}
break;
case PCI_DEVICE_ID_MP6 :
case PCI_DEVICE_ID_MP6A :
case PCI_DEVICE_ID_GT_MP6 :
case PCI_DEVICE_ID_GT_MP6A :
sbdev->nr_ports = 6;
/* SB16C1053APCI */
if (sbdev->revision == 0xc0)
{
int prev_port_addr = 0;
pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 16);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 32, 16);
}
break;
case PCI_DEVICE_ID_MP8 :
case PCIE_DEVICE_ID_MP8 :
case PCI_DEVICE_ID_GT_MP8 :
case PCIE_DEVICE_ID_GT_MP8 :
case PCIE_DEVICE_ID_MP8B :
sbdev->nr_ports = 8;
break;
case PCI_DEVICE_ID_MP32 :
case PCIE_DEVICE_ID_MP32 :
case PCI_DEVICE_ID_GT_MP32 :
case PCIE_DEVICE_ID_GT_MP32 :
{
int portnum_hex=0;
portnum_hex = inb(sbdev->option_reg_addr);
sbdev->nr_ports = ((portnum_hex/16)*10) + (portnum_hex % 16);
}
break;
#ifdef CONFIG_PARPORT_PC
case PCI_DEVICE_ID_MP2S1P :
sbdev->nr_ports = 2;
/* SB16C1053APCI */
if (sbdev->revision == 0xc0)
{
int prev_port_addr = 0;
pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);
pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);
}
/* add PC compatible parallel port */
parport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);
break;
case PCI_DEVICE_ID_MP1P :
/* add PC compatible parallel port */
parport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);
break;
#endif
}
ret = request_region(sbdev->uart_access_addr, (8*sbdev->nr_ports), sbdev->name);
if (sbdev->revision == 0xc0)
{
ret = request_region(sbdev->option_reg_addr, 0x40, sbdev->name);
}
else
{
ret = request_region(sbdev->option_reg_addr, 0x20, sbdev->name);
}
NR_BOARD++;
NR_PORTS += sbdev->nr_ports;
/* Enable PCI interrupt */
addr = sbdev->option_reg_addr + MP_OPTR_IMR0;
for(j=0; j < (sbdev->nr_ports/8)+1; j++)
{
if (sbdev->poll_type == TYPE_INTERRUPT)
{
outb(0xff,addr +j);
}
}
sbdev++;
return 0;
}
static int __init multi_init(void)
{
int ret, i;
struct pci_dev *dev = NULL;
if(fcr_count==0)
{
for(i=0;i<256;i++)
{
fcr_arr[i] = 0x01;
}
}
if(deep_count==0)
{
for(i=0;i<256;i++)
{
deep[i] = 1;
}
}
if(rtr_count==0)
{
for(i=0;i<256;i++)
{
rtr[i] = 0x10;
}
}
if(ttr_count==0)
{
for(i=0;i<256;i++)
{
ttr[i] = 0x38;
}
}
printk("MULTI INIT\n");
for( i=0; i< mp_nrpcibrds; i++)
{
while( (dev = pci_get_device(mp_pciboards[i].vendor_id, mp_pciboards[i].device_id, dev) ) )
{
printk("FOUND~~~\n");
// Cent OS bug fix
// if (mp_pciboards[i].device_id & 0x0800)
{
int status;
pci_disable_device(dev);
status = pci_enable_device(dev);
if (status != 0)
{
printk("Multiport Board Enable Fail !\n\n");
status = -ENXIO;
return status;
}
}
init_mp_dev(dev, mp_pciboards[i]);
}
}
for (i = 0; i < NR_IRQS; i++)
spin_lock_init(&irq_lists[i].lock);
ret = mp_register_driver(&multi_reg);
if (ret >= 0)
multi_register_ports(&multi_reg);
return ret;
}
static void __exit multi_exit(void)
{
int i;
for (i = 0; i < NR_PORTS; i++)
mp_remove_one_port(&multi_reg, &multi_ports[i].port);
mp_unregister_driver(&multi_reg);
}
module_init(multi_init);
module_exit(multi_exit);
MODULE_DESCRIPTION("SystemBase Multiport PCI/PCIe CORE");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_5760_0 |
crossvul-cpp_data_good_3416_0 | /*
* Apple HTTP Live Streaming demuxer
* Copyright (c) 2010 Martin Storsjo
* Copyright (c) 2013 Anssi Hannula
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Apple HTTP Live Streaming demuxer
* http://tools.ietf.org/html/draft-pantos-http-live-streaming
*/
#include "libavutil/avstring.h"
#include "libavutil/avassert.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/time.h"
#include "avformat.h"
#include "internal.h"
#include "avio_internal.h"
#include "id3v2.h"
#define INITIAL_BUFFER_SIZE 32768
#define MAX_FIELD_LEN 64
#define MAX_CHARACTERISTICS_LEN 512
#define MPEG_TIME_BASE 90000
#define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
/*
* An apple http stream consists of a playlist with media segment files,
* played sequentially. There may be several playlists with the same
* video content, in different bandwidth variants, that are played in
* parallel (preferably only one bandwidth variant at a time). In this case,
* the user supplied the url to a main playlist that only lists the variant
* playlists.
*
* If the main playlist doesn't point at any variants, we still create
* one anonymous toplevel variant for this, to maintain the structure.
*/
enum KeyType {
KEY_NONE,
KEY_AES_128,
KEY_SAMPLE_AES
};
struct segment {
int64_t duration;
int64_t url_offset;
int64_t size;
char *url;
char *key;
enum KeyType key_type;
uint8_t iv[16];
/* associated Media Initialization Section, treated as a segment */
struct segment *init_section;
};
struct rendition;
enum PlaylistType {
PLS_TYPE_UNSPECIFIED,
PLS_TYPE_EVENT,
PLS_TYPE_VOD
};
/*
* Each playlist has its own demuxer. If it currently is active,
* it has an open AVIOContext too, and potentially an AVPacket
* containing the next packet from this stream.
*/
struct playlist {
char url[MAX_URL_SIZE];
AVIOContext pb;
uint8_t* read_buffer;
AVIOContext *input;
AVFormatContext *parent;
int index;
AVFormatContext *ctx;
AVPacket pkt;
int has_noheader_flag;
/* main demuxer streams associated with this playlist
* indexed by the subdemuxer stream indexes */
AVStream **main_streams;
int n_main_streams;
int finished;
enum PlaylistType type;
int64_t target_duration;
int start_seq_no;
int n_segments;
struct segment **segments;
int needed, cur_needed;
int cur_seq_no;
int64_t cur_seg_offset;
int64_t last_load_time;
/* Currently active Media Initialization Section */
struct segment *cur_init_section;
uint8_t *init_sec_buf;
unsigned int init_sec_buf_size;
unsigned int init_sec_data_len;
unsigned int init_sec_buf_read_offset;
char key_url[MAX_URL_SIZE];
uint8_t key[16];
/* ID3 timestamp handling (elementary audio streams have ID3 timestamps
* (and possibly other ID3 tags) in the beginning of each segment) */
int is_id3_timestamped; /* -1: not yet known */
int64_t id3_mpegts_timestamp; /* in mpegts tb */
int64_t id3_offset; /* in stream original tb */
uint8_t* id3_buf; /* temp buffer for id3 parsing */
unsigned int id3_buf_size;
AVDictionary *id3_initial; /* data from first id3 tag */
int id3_found; /* ID3 tag found at some point */
int id3_changed; /* ID3 tag data has changed at some point */
ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
int64_t seek_timestamp;
int seek_flags;
int seek_stream_index; /* into subdemuxer stream array */
/* Renditions associated with this playlist, if any.
* Alternative rendition playlists have a single rendition associated
* with them, and variant main Media Playlists may have
* multiple (playlist-less) renditions associated with them. */
int n_renditions;
struct rendition **renditions;
/* Media Initialization Sections (EXT-X-MAP) associated with this
* playlist, if any. */
int n_init_sections;
struct segment **init_sections;
};
/*
* Renditions are e.g. alternative subtitle or audio streams.
* The rendition may either be an external playlist or it may be
* contained in the main Media Playlist of the variant (in which case
* playlist is NULL).
*/
struct rendition {
enum AVMediaType type;
struct playlist *playlist;
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
int disposition;
};
struct variant {
int bandwidth;
/* every variant contains at least the main Media Playlist in index 0 */
int n_playlists;
struct playlist **playlists;
char audio_group[MAX_FIELD_LEN];
char video_group[MAX_FIELD_LEN];
char subtitles_group[MAX_FIELD_LEN];
};
typedef struct HLSContext {
AVClass *class;
AVFormatContext *ctx;
int n_variants;
struct variant **variants;
int n_playlists;
struct playlist **playlists;
int n_renditions;
struct rendition **renditions;
int cur_seq_no;
int live_start_index;
int first_packet;
int64_t first_timestamp;
int64_t cur_timestamp;
AVIOInterruptCB *interrupt_callback;
char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
char *http_proxy; ///< holds the address of the HTTP proxy server
AVDictionary *avio_opts;
int strict_std_compliance;
char *allowed_extensions;
} HLSContext;
static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
{
int len = ff_get_line(s, buf, maxlen);
while (len > 0 && av_isspace(buf[len - 1]))
buf[--len] = '\0';
return len;
}
static void free_segment_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_segments; i++) {
av_freep(&pls->segments[i]->key);
av_freep(&pls->segments[i]->url);
av_freep(&pls->segments[i]);
}
av_freep(&pls->segments);
pls->n_segments = 0;
}
static void free_init_section_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_init_sections; i++) {
av_freep(&pls->init_sections[i]->url);
av_freep(&pls->init_sections[i]);
}
av_freep(&pls->init_sections);
pls->n_init_sections = 0;
}
static void free_playlist_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
free_segment_list(pls);
free_init_section_list(pls);
av_freep(&pls->main_streams);
av_freep(&pls->renditions);
av_freep(&pls->id3_buf);
av_dict_free(&pls->id3_initial);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
av_freep(&pls->init_sec_buf);
av_packet_unref(&pls->pkt);
av_freep(&pls->pb.buffer);
if (pls->input)
ff_format_io_close(c->ctx, &pls->input);
if (pls->ctx) {
pls->ctx->pb = NULL;
avformat_close_input(&pls->ctx);
}
av_free(pls);
}
av_freep(&c->playlists);
av_freep(&c->cookies);
av_freep(&c->user_agent);
av_freep(&c->headers);
av_freep(&c->http_proxy);
c->n_playlists = 0;
}
static void free_variant_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
av_freep(&var->playlists);
av_free(var);
}
av_freep(&c->variants);
c->n_variants = 0;
}
static void free_rendition_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_renditions; i++)
av_freep(&c->renditions[i]);
av_freep(&c->renditions);
c->n_renditions = 0;
}
/*
* Used to reset a statically allocated AVPacket to a clean slate,
* containing no data.
*/
static void reset_packet(AVPacket *pkt)
{
av_init_packet(pkt);
pkt->data = NULL;
}
static struct playlist *new_playlist(HLSContext *c, const char *url,
const char *base)
{
struct playlist *pls = av_mallocz(sizeof(struct playlist));
if (!pls)
return NULL;
reset_packet(&pls->pkt);
ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
pls->seek_timestamp = AV_NOPTS_VALUE;
pls->is_id3_timestamped = -1;
pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
dynarray_add(&c->playlists, &c->n_playlists, pls);
return pls;
}
struct variant_info {
char bandwidth[20];
/* variant group ids: */
char audio[MAX_FIELD_LEN];
char video[MAX_FIELD_LEN];
char subtitles[MAX_FIELD_LEN];
};
static struct variant *new_variant(HLSContext *c, struct variant_info *info,
const char *url, const char *base)
{
struct variant *var;
struct playlist *pls;
pls = new_playlist(c, url, base);
if (!pls)
return NULL;
var = av_mallocz(sizeof(struct variant));
if (!var)
return NULL;
if (info) {
var->bandwidth = atoi(info->bandwidth);
strcpy(var->audio_group, info->audio);
strcpy(var->video_group, info->video);
strcpy(var->subtitles_group, info->subtitles);
}
dynarray_add(&c->variants, &c->n_variants, var);
dynarray_add(&var->playlists, &var->n_playlists, pls);
return var;
}
static void handle_variant_args(struct variant_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "BANDWIDTH=", key_len)) {
*dest = info->bandwidth;
*dest_len = sizeof(info->bandwidth);
} else if (!strncmp(key, "AUDIO=", key_len)) {
*dest = info->audio;
*dest_len = sizeof(info->audio);
} else if (!strncmp(key, "VIDEO=", key_len)) {
*dest = info->video;
*dest_len = sizeof(info->video);
} else if (!strncmp(key, "SUBTITLES=", key_len)) {
*dest = info->subtitles;
*dest_len = sizeof(info->subtitles);
}
}
struct key_info {
char uri[MAX_URL_SIZE];
char method[11];
char iv[35];
};
static void handle_key_args(struct key_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "METHOD=", key_len)) {
*dest = info->method;
*dest_len = sizeof(info->method);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "IV=", key_len)) {
*dest = info->iv;
*dest_len = sizeof(info->iv);
}
}
struct init_section_info {
char uri[MAX_URL_SIZE];
char byterange[32];
};
static struct segment *new_init_section(struct playlist *pls,
struct init_section_info *info,
const char *url_base)
{
struct segment *sec;
char *ptr;
char tmp_str[MAX_URL_SIZE];
if (!info->uri[0])
return NULL;
sec = av_mallocz(sizeof(*sec));
if (!sec)
return NULL;
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
sec->url = av_strdup(tmp_str);
if (!sec->url) {
av_free(sec);
return NULL;
}
if (info->byterange[0]) {
sec->size = strtoll(info->byterange, NULL, 10);
ptr = strchr(info->byterange, '@');
if (ptr)
sec->url_offset = strtoll(ptr+1, NULL, 10);
} else {
/* the entire file is the init section */
sec->size = -1;
}
dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
return sec;
}
static void handle_init_section_args(struct init_section_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "BYTERANGE=", key_len)) {
*dest = info->byterange;
*dest_len = sizeof(info->byterange);
}
}
struct rendition_info {
char type[16];
char uri[MAX_URL_SIZE];
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char assoc_language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
char defaultr[4];
char forced[4];
char characteristics[MAX_CHARACTERISTICS_LEN];
};
static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
const char *url_base)
{
struct rendition *rend;
enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
char *characteristic;
char *chr_ptr;
char *saveptr;
if (!strcmp(info->type, "AUDIO"))
type = AVMEDIA_TYPE_AUDIO;
else if (!strcmp(info->type, "VIDEO"))
type = AVMEDIA_TYPE_VIDEO;
else if (!strcmp(info->type, "SUBTITLES"))
type = AVMEDIA_TYPE_SUBTITLE;
else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
/* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
* AVC SEI RBSP anyway */
return NULL;
if (type == AVMEDIA_TYPE_UNKNOWN)
return NULL;
/* URI is mandatory for subtitles as per spec */
if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
return NULL;
/* TODO: handle subtitles (each segment has to parsed separately) */
if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
if (type == AVMEDIA_TYPE_SUBTITLE)
return NULL;
rend = av_mallocz(sizeof(struct rendition));
if (!rend)
return NULL;
dynarray_add(&c->renditions, &c->n_renditions, rend);
rend->type = type;
strcpy(rend->group_id, info->group_id);
strcpy(rend->language, info->language);
strcpy(rend->name, info->name);
/* add the playlist if this is an external rendition */
if (info->uri[0]) {
rend->playlist = new_playlist(c, info->uri, url_base);
if (rend->playlist)
dynarray_add(&rend->playlist->renditions,
&rend->playlist->n_renditions, rend);
}
if (info->assoc_language[0]) {
int langlen = strlen(rend->language);
if (langlen < sizeof(rend->language) - 3) {
rend->language[langlen] = ',';
strncpy(rend->language + langlen + 1, info->assoc_language,
sizeof(rend->language) - langlen - 2);
}
}
if (!strcmp(info->defaultr, "YES"))
rend->disposition |= AV_DISPOSITION_DEFAULT;
if (!strcmp(info->forced, "YES"))
rend->disposition |= AV_DISPOSITION_FORCED;
chr_ptr = info->characteristics;
while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
else if (!strcmp(characteristic, "public.accessibility.describes-video"))
rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
chr_ptr = NULL;
}
return rend;
}
static void handle_rendition_args(struct rendition_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "TYPE=", key_len)) {
*dest = info->type;
*dest_len = sizeof(info->type);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "GROUP-ID=", key_len)) {
*dest = info->group_id;
*dest_len = sizeof(info->group_id);
} else if (!strncmp(key, "LANGUAGE=", key_len)) {
*dest = info->language;
*dest_len = sizeof(info->language);
} else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
*dest = info->assoc_language;
*dest_len = sizeof(info->assoc_language);
} else if (!strncmp(key, "NAME=", key_len)) {
*dest = info->name;
*dest_len = sizeof(info->name);
} else if (!strncmp(key, "DEFAULT=", key_len)) {
*dest = info->defaultr;
*dest_len = sizeof(info->defaultr);
} else if (!strncmp(key, "FORCED=", key_len)) {
*dest = info->forced;
*dest_len = sizeof(info->forced);
} else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
*dest = info->characteristics;
*dest_len = sizeof(info->characteristics);
}
/*
* ignored:
* - AUTOSELECT: client may autoselect based on e.g. system language
* - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
*/
}
/* used by parse_playlist to allocate a new variant+playlist when the
* playlist is detected to be a Media Playlist (not Master Playlist)
* and we have no parent Master Playlist (parsing of which would have
* allocated the variant and playlist already)
* *pls == NULL => Master Playlist or parentless Media Playlist
* *pls != NULL => parented Media Playlist, playlist+variant allocated */
static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
{
if (*pls)
return 0;
if (!new_variant(c, NULL, url, NULL))
return AVERROR(ENOMEM);
*pls = c->playlists[c->n_playlists - 1];
return 0;
}
static void update_options(char **dest, const char *name, void *src)
{
av_freep(dest);
av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
if (*dest && !strlen(*dest))
av_freep(dest);
}
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
AVDictionary *opts, AVDictionary *opts2, int *is_http)
{
HLSContext *c = s->priv_data;
AVDictionary *tmp = NULL;
const char *proto_name = NULL;
int ret;
av_dict_copy(&tmp, opts, 0);
av_dict_copy(&tmp, opts2, 0);
if (av_strstart(url, "crypto", NULL)) {
if (url[6] == '+' || url[6] == ':')
proto_name = avio_find_protocol_name(url + 7);
}
if (!proto_name)
proto_name = avio_find_protocol_name(url);
if (!proto_name)
return AVERROR_INVALIDDATA;
// only http(s) & file are allowed
if (av_strstart(proto_name, "file", NULL)) {
if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
av_log(s, AV_LOG_ERROR,
"Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
"If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
url);
return AVERROR_INVALIDDATA;
}
} else if (av_strstart(proto_name, "http", NULL)) {
;
} else
return AVERROR_INVALIDDATA;
if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
;
else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
;
else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
return AVERROR_INVALIDDATA;
ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
if (ret >= 0) {
// update cookies on http response with setcookies.
char *new_cookies = NULL;
if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
if (new_cookies) {
av_free(c->cookies);
c->cookies = new_cookies;
}
av_dict_set(&opts, "cookies", c->cookies, 0);
}
av_dict_free(&tmp);
if (is_http)
*is_http = av_strstart(proto_name, "http", NULL);
return ret;
}
static int parse_playlist(HLSContext *c, const char *url,
struct playlist *pls, AVIOContext *in)
{
int ret = 0, is_segment = 0, is_variant = 0;
int64_t duration = 0;
enum KeyType key_type = KEY_NONE;
uint8_t iv[16] = "";
int has_iv = 0;
char key[MAX_URL_SIZE] = "";
char line[MAX_URL_SIZE];
const char *ptr;
int close_in = 0;
int64_t seg_offset = 0;
int64_t seg_size = -1;
uint8_t *new_url = NULL;
struct variant_info variant_info;
char tmp_str[MAX_URL_SIZE];
struct segment *cur_init_section = NULL;
if (!in) {
#if 1
AVDictionary *opts = NULL;
close_in = 1;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&opts, "seekable", "0", 0);
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
av_dict_free(&opts);
if (ret < 0)
return ret;
#else
ret = open_in(c, &in, url);
if (ret < 0)
return ret;
close_in = 1;
#endif
}
if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
url = new_url;
read_chomp_line(in, line, sizeof(line));
if (strcmp(line, "#EXTM3U")) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (pls) {
free_segment_list(pls);
pls->finished = 0;
pls->type = PLS_TYPE_UNSPECIFIED;
}
while (!avio_feof(in)) {
read_chomp_line(in, line, sizeof(line));
if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
is_variant = 1;
memset(&variant_info, 0, sizeof(variant_info));
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
&variant_info);
} else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
struct key_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
&info);
key_type = KEY_NONE;
has_iv = 0;
if (!strcmp(info.method, "AES-128"))
key_type = KEY_AES_128;
if (!strcmp(info.method, "SAMPLE-AES"))
key_type = KEY_SAMPLE_AES;
if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
ff_hex_to_data(iv, info.iv + 2);
has_iv = 1;
}
av_strlcpy(key, info.uri, sizeof(key));
} else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
struct rendition_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
&info);
new_rendition(c, &info, url);
} else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->start_seq_no = atoi(ptr);
} else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
if (!strcmp(ptr, "EVENT"))
pls->type = PLS_TYPE_EVENT;
else if (!strcmp(ptr, "VOD"))
pls->type = PLS_TYPE_VOD;
} else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
struct init_section_info info = {{0}};
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
&info);
cur_init_section = new_init_section(pls, &info, url);
} else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
if (pls)
pls->finished = 1;
} else if (av_strstart(line, "#EXTINF:", &ptr)) {
is_segment = 1;
duration = atof(ptr) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
seg_size = strtoll(ptr, NULL, 10);
ptr = strchr(ptr, '@');
if (ptr)
seg_offset = strtoll(ptr+1, NULL, 10);
} else if (av_strstart(line, "#", NULL)) {
continue;
} else if (line[0]) {
if (is_variant) {
if (!new_variant(c, &variant_info, line, url)) {
ret = AVERROR(ENOMEM);
goto fail;
}
is_variant = 0;
}
if (is_segment) {
struct segment *seg;
if (!pls) {
if (!new_variant(c, 0, url, NULL)) {
ret = AVERROR(ENOMEM);
goto fail;
}
pls = c->playlists[c->n_playlists - 1];
}
seg = av_malloc(sizeof(struct segment));
if (!seg) {
ret = AVERROR(ENOMEM);
goto fail;
}
seg->duration = duration;
seg->key_type = key_type;
if (has_iv) {
memcpy(seg->iv, iv, sizeof(iv));
} else {
int seq = pls->start_seq_no + pls->n_segments;
memset(seg->iv, 0, sizeof(seg->iv));
AV_WB32(seg->iv + 12, seq);
}
if (key_type != KEY_NONE) {
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
seg->key = av_strdup(tmp_str);
if (!seg->key) {
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
} else {
seg->key = NULL;
}
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
seg->url = av_strdup(tmp_str);
if (!seg->url) {
av_free(seg->key);
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
dynarray_add(&pls->segments, &pls->n_segments, seg);
is_segment = 0;
seg->size = seg_size;
if (seg_size >= 0) {
seg->url_offset = seg_offset;
seg_offset += seg_size;
seg_size = -1;
} else {
seg->url_offset = 0;
seg_offset = 0;
}
seg->init_section = cur_init_section;
}
}
}
if (pls)
pls->last_load_time = av_gettime_relative();
fail:
av_free(new_url);
if (close_in)
ff_format_io_close(c->ctx, &in);
return ret;
}
static struct segment *current_segment(struct playlist *pls)
{
return pls->segments[pls->cur_seq_no - pls->start_seq_no];
}
enum ReadFromURLMode {
READ_NORMAL,
READ_COMPLETE,
};
static int read_from_url(struct playlist *pls, struct segment *seg,
uint8_t *buf, int buf_size,
enum ReadFromURLMode mode)
{
int ret;
/* limit read if the segment was only a part of a file */
if (seg->size >= 0)
buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
if (mode == READ_COMPLETE) {
ret = avio_read(pls->input, buf, buf_size);
if (ret != buf_size)
av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
} else
ret = avio_read(pls->input, buf, buf_size);
if (ret > 0)
pls->cur_seg_offset += ret;
return ret;
}
/* Parse the raw ID3 data and pass contents to caller */
static void parse_id3(AVFormatContext *s, AVIOContext *pb,
AVDictionary **metadata, int64_t *dts,
ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
{
static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
ID3v2ExtraMeta *meta;
ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
for (meta = *extra_meta; meta; meta = meta->next) {
if (!strcmp(meta->tag, "PRIV")) {
ID3v2ExtraMetaPRIV *priv = meta->data;
if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
/* 33-bit MPEG timestamp */
int64_t ts = AV_RB64(priv->data);
av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
if ((ts & ~((1ULL << 33) - 1)) == 0)
*dts = ts;
else
av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
}
} else if (!strcmp(meta->tag, "APIC") && apic)
*apic = meta->data;
}
}
/* Check if the ID3 metadata contents have changed */
static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
ID3v2ExtraMetaAPIC *apic)
{
AVDictionaryEntry *entry = NULL;
AVDictionaryEntry *oldentry;
/* check that no keys have changed values */
while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
return 1;
}
/* check if apic appeared */
if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
return 1;
if (apic) {
int size = pls->ctx->streams[1]->attached_pic.size;
if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
return 1;
if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
return 1;
}
return 0;
}
/* Parse ID3 data and handle the found data */
static void handle_id3(AVIOContext *pb, struct playlist *pls)
{
AVDictionary *metadata = NULL;
ID3v2ExtraMetaAPIC *apic = NULL;
ID3v2ExtraMeta *extra_meta = NULL;
int64_t timestamp = AV_NOPTS_VALUE;
parse_id3(pls->ctx, pb, &metadata, ×tamp, &apic, &extra_meta);
if (timestamp != AV_NOPTS_VALUE) {
pls->id3_mpegts_timestamp = timestamp;
pls->id3_offset = 0;
}
if (!pls->id3_found) {
/* initial ID3 tags */
av_assert0(!pls->id3_deferred_extra);
pls->id3_found = 1;
/* get picture attachment and set text metadata */
if (pls->ctx->nb_streams)
ff_id3v2_parse_apic(pls->ctx, &extra_meta);
else
/* demuxer not yet opened, defer picture attachment */
pls->id3_deferred_extra = extra_meta;
av_dict_copy(&pls->ctx->metadata, metadata, 0);
pls->id3_initial = metadata;
} else {
if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
pls->id3_changed = 1;
}
av_dict_free(&metadata);
}
if (!pls->id3_deferred_extra)
ff_id3v2_free_extra_meta(&extra_meta);
}
static void intercept_id3(struct playlist *pls, uint8_t *buf,
int buf_size, int *len)
{
/* intercept id3 tags, we do not want to pass them to the raw
* demuxer on all segment switches */
int bytes;
int id3_buf_pos = 0;
int fill_buf = 0;
struct segment *seg = current_segment(pls);
/* gather all the id3 tags */
while (1) {
/* see if we can retrieve enough data for ID3 header */
if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
if (bytes > 0) {
if (bytes == ID3v2_HEADER_SIZE - *len)
/* no EOF yet, so fill the caller buffer again after
* we have stripped the ID3 tags */
fill_buf = 1;
*len += bytes;
} else if (*len <= 0) {
/* error/EOF */
*len = bytes;
fill_buf = 0;
}
}
if (*len < ID3v2_HEADER_SIZE)
break;
if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
int taglen = ff_id3v2_tag_len(buf);
int tag_got_bytes = FFMIN(taglen, *len);
int remaining = taglen - tag_got_bytes;
if (taglen > maxsize) {
av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
taglen, maxsize);
break;
}
/*
* Copy the id3 tag to our temporary id3 buffer.
* We could read a small id3 tag directly without memcpy, but
* we would still need to copy the large tags, and handling
* both of those cases together with the possibility for multiple
* tags would make the handling a bit complex.
*/
pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
if (!pls->id3_buf)
break;
memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
id3_buf_pos += tag_got_bytes;
/* strip the intercepted bytes */
*len -= tag_got_bytes;
memmove(buf, buf + tag_got_bytes, *len);
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
if (remaining > 0) {
/* read the rest of the tag in */
if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
break;
id3_buf_pos += remaining;
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
}
} else {
/* no more ID3 tags */
break;
}
}
/* re-fill buffer for the caller unless EOF */
if (*len >= 0 && (fill_buf || *len == 0)) {
bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
/* ignore error if we already had some data */
if (bytes >= 0)
*len += bytes;
else if (*len == 0)
*len = bytes;
}
if (pls->id3_buf) {
/* Now parse all the ID3 tags */
AVIOContext id3ioctx;
ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
handle_id3(&id3ioctx, pls);
}
if (pls->is_id3_timestamped == -1)
pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
}
static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
{
AVDictionary *opts = NULL;
int ret;
int is_http = 0;
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
av_dict_set(&opts, "seekable", "0", 0);
if (seg->size >= 0) {
/* try to restrict the HTTP request to the part we want
* (if this is in fact a HTTP request) */
av_dict_set_int(&opts, "offset", seg->url_offset, 0);
av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
}
av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
seg->url, seg->url_offset, pls->index);
if (seg->key_type == KEY_NONE) {
ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts, &is_http);
} else if (seg->key_type == KEY_AES_128) {
AVDictionary *opts2 = NULL;
char iv[33], key[33], url[MAX_URL_SIZE];
if (strcmp(seg->key, pls->key_url)) {
AVIOContext *pb;
if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
ret = avio_read(pb, pls->key, sizeof(pls->key));
if (ret != sizeof(pls->key)) {
av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
seg->key);
}
ff_format_io_close(pls->parent, &pb);
} else {
av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
seg->key);
}
av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
}
ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
iv[32] = key[32] = '\0';
if (strstr(seg->url, "://"))
snprintf(url, sizeof(url), "crypto+%s", seg->url);
else
snprintf(url, sizeof(url), "crypto:%s", seg->url);
av_dict_copy(&opts2, c->avio_opts, 0);
av_dict_set(&opts2, "key", key, 0);
av_dict_set(&opts2, "iv", iv, 0);
ret = open_url(pls->parent, &pls->input, url, opts2, opts, &is_http);
av_dict_free(&opts2);
if (ret < 0) {
goto cleanup;
}
ret = 0;
} else if (seg->key_type == KEY_SAMPLE_AES) {
av_log(pls->parent, AV_LOG_ERROR,
"SAMPLE-AES encryption is not supported yet\n");
ret = AVERROR_PATCHWELCOME;
}
else
ret = AVERROR(ENOSYS);
/* Seek to the requested position. If this was a HTTP request, the offset
* should already be where want it to, but this allows e.g. local testing
* without a HTTP server.
*
* This is not done for HTTP at all as avio_seek() does internal bookkeeping
* of file offset which is out-of-sync with the actual offset when "offset"
* AVOption is used with http protocol, causing the seek to not be a no-op
* as would be expected. Wrong offset received from the server will not be
* noticed without the call, though.
*/
if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
if (seekret < 0) {
av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
ret = seekret;
ff_format_io_close(pls->parent, &pls->input);
}
}
cleanup:
av_dict_free(&opts);
pls->cur_seg_offset = 0;
return ret;
}
static int update_init_section(struct playlist *pls, struct segment *seg)
{
static const int max_init_section_size = 1024*1024;
HLSContext *c = pls->parent->priv_data;
int64_t sec_size;
int64_t urlsize;
int ret;
if (seg->init_section == pls->cur_init_section)
return 0;
pls->cur_init_section = NULL;
if (!seg->init_section)
return 0;
ret = open_input(c, pls, seg->init_section);
if (ret < 0) {
av_log(pls->parent, AV_LOG_WARNING,
"Failed to open an initialization section in playlist %d\n",
pls->index);
return ret;
}
if (seg->init_section->size >= 0)
sec_size = seg->init_section->size;
else if ((urlsize = avio_size(pls->input)) >= 0)
sec_size = urlsize;
else
sec_size = max_init_section_size;
av_log(pls->parent, AV_LOG_DEBUG,
"Downloading an initialization section of size %"PRId64"\n",
sec_size);
sec_size = FFMIN(sec_size, max_init_section_size);
av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
pls->init_sec_buf_size, READ_COMPLETE);
ff_format_io_close(pls->parent, &pls->input);
if (ret < 0)
return ret;
pls->cur_init_section = seg->init_section;
pls->init_sec_data_len = ret;
pls->init_sec_buf_read_offset = 0;
/* spec says audio elementary streams do not have media initialization
* sections, so there should be no ID3 timestamps */
pls->is_id3_timestamped = 0;
return 0;
}
static int64_t default_reload_interval(struct playlist *pls)
{
return pls->n_segments > 0 ?
pls->segments[pls->n_segments - 1]->duration :
pls->target_duration;
}
static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
static void add_renditions_to_variant(HLSContext *c, struct variant *var,
enum AVMediaType type, const char *group_id)
{
int i;
for (i = 0; i < c->n_renditions; i++) {
struct rendition *rend = c->renditions[i];
if (rend->type == type && !strcmp(rend->group_id, group_id)) {
if (rend->playlist)
/* rendition is an external playlist
* => add the playlist to the variant */
dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
else
/* rendition is part of the variant main Media Playlist
* => add the rendition to the main Media Playlist */
dynarray_add(&var->playlists[0]->renditions,
&var->playlists[0]->n_renditions,
rend);
}
}
}
static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
enum AVMediaType type)
{
int rend_idx = 0;
int i;
for (i = 0; i < pls->n_main_streams; i++) {
AVStream *st = pls->main_streams[i];
if (st->codecpar->codec_type != type)
continue;
for (; rend_idx < pls->n_renditions; rend_idx++) {
struct rendition *rend = pls->renditions[rend_idx];
if (rend->type != type)
continue;
if (rend->language[0])
av_dict_set(&st->metadata, "language", rend->language, 0);
if (rend->name[0])
av_dict_set(&st->metadata, "comment", rend->name, 0);
st->disposition |= rend->disposition;
}
if (rend_idx >=pls->n_renditions)
break;
}
}
/* if timestamp was in valid range: returns 1 and sets seq_no
* if not: returns 0 and sets seq_no to closest segment */
static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
int64_t timestamp, int *seq_no)
{
int i;
int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
if (timestamp < pos) {
*seq_no = pls->start_seq_no;
return 0;
}
for (i = 0; i < pls->n_segments; i++) {
int64_t diff = pos + pls->segments[i]->duration - timestamp;
if (diff > 0) {
*seq_no = pls->start_seq_no + i;
return 1;
}
pos += pls->segments[i]->duration;
}
*seq_no = pls->start_seq_no + pls->n_segments - 1;
return 0;
}
static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
{
int seq_no;
if (!pls->finished && !c->first_packet &&
av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
/* reload the playlist since it was suspended */
parse_playlist(c, pls->url, pls, NULL);
/* If playback is already in progress (we are just selecting a new
* playlist) and this is a complete file, find the matching segment
* by counting durations. */
if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
return seq_no;
}
if (!pls->finished) {
if (!c->first_packet && /* we are doing a segment selection during playback */
c->cur_seq_no >= pls->start_seq_no &&
c->cur_seq_no < pls->start_seq_no + pls->n_segments)
/* While spec 3.4.3 says that we cannot assume anything about the
* content at the same sequence number on different playlists,
* in practice this seems to work and doing it otherwise would
* require us to download a segment to inspect its timestamps. */
return c->cur_seq_no;
/* If this is a live stream, start live_start_index segments from the
* start or end */
if (c->live_start_index < 0)
return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
else
return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
}
/* Otherwise just start on the first segment. */
return pls->start_seq_no;
}
static int save_avio_options(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
static const char *opts[] = {
"headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
const char **opt = opts;
uint8_t *buf;
int ret = 0;
while (*opt) {
if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
ret = av_dict_set(&c->avio_opts, *opt, buf,
AV_DICT_DONT_STRDUP_VAL);
if (ret < 0)
return ret;
}
opt++;
}
return ret;
}
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
int flags, AVDictionary **opts)
{
av_log(s, AV_LOG_ERROR,
"A HLS playlist item '%s' referred to an external file '%s'. "
"Opening this file was forbidden for security reasons\n",
s->filename, url);
return AVERROR(EPERM);
}
static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
{
HLSContext *c = s->priv_data;
int i, j;
int bandwidth = -1;
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
for (j = 0; j < v->n_playlists; j++) {
if (v->playlists[j] != pls)
continue;
av_program_add_stream_index(s, i, stream->index);
if (bandwidth < 0)
bandwidth = v->bandwidth;
else if (bandwidth != v->bandwidth)
bandwidth = -1; /* stream in multiple variants with different bandwidths */
}
}
if (bandwidth >= 0)
av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
}
static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
{
int err;
err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
if (err < 0)
return err;
if (pls->is_id3_timestamped) /* custom timestamps via id3 */
avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
else
avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
st->internal->need_context_update = 1;
return 0;
}
/* add new subdemuxer streams to our context, if any */
static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
{
int err;
while (pls->n_main_streams < pls->ctx->nb_streams) {
int ist_idx = pls->n_main_streams;
AVStream *st = avformat_new_stream(s, NULL);
AVStream *ist = pls->ctx->streams[ist_idx];
if (!st)
return AVERROR(ENOMEM);
st->id = pls->index;
dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
add_stream_to_programs(s, pls, st);
err = set_stream_info_from_input_stream(st, pls, ist);
if (err < 0)
return err;
}
return 0;
}
static void update_noheader_flag(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
int flag_needed = 0;
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->has_noheader_flag) {
flag_needed = 1;
break;
}
}
if (flag_needed)
s->ctx_flags |= AVFMTCTX_NOHEADER;
else
s->ctx_flags &= ~AVFMTCTX_NOHEADER;
}
static int hls_close(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
free_playlist_list(c);
free_variant_list(c);
free_rendition_list(c);
av_dict_free(&c->avio_opts);
return 0;
}
static int hls_read_header(AVFormatContext *s)
{
void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
HLSContext *c = s->priv_data;
int ret = 0, i;
int highest_cur_seq_no = 0;
c->ctx = s;
c->interrupt_callback = &s->interrupt_callback;
c->strict_std_compliance = s->strict_std_compliance;
c->first_packet = 1;
c->first_timestamp = AV_NOPTS_VALUE;
c->cur_timestamp = AV_NOPTS_VALUE;
if (u) {
// get the previous user agent & set back to null if string size is zero
update_options(&c->user_agent, "user_agent", u);
// get the previous cookies & set back to null if string size is zero
update_options(&c->cookies, "cookies", u);
// get the previous headers & set back to null if string size is zero
update_options(&c->headers, "headers", u);
// get the previous http proxt & set back to null if string size is zero
update_options(&c->http_proxy, "http_proxy", u);
}
if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
goto fail;
if ((ret = save_avio_options(s)) < 0)
goto fail;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&c->avio_opts, "seekable", "0", 0);
if (c->n_variants == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If the playlist only contained playlists (Master Playlist),
* parse each individual playlist. */
if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
goto fail;
}
}
if (c->variants[0]->playlists[0]->n_segments == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If this isn't a live stream, calculate the total duration of the
* stream. */
if (c->variants[0]->playlists[0]->finished) {
int64_t duration = 0;
for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
duration += c->variants[0]->playlists[0]->segments[i]->duration;
s->duration = duration;
}
/* Associate renditions with variants */
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
if (var->audio_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
if (var->video_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
if (var->subtitles_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
}
/* Create a program for each variant */
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
AVProgram *program;
program = av_new_program(s, i);
if (!program)
goto fail;
av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
}
/* Select the starting segments */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->n_segments == 0)
continue;
pls->cur_seq_no = select_cur_seq_no(c, pls);
highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
}
/* Open the demuxer for each playlist */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
AVInputFormat *in_fmt = NULL;
if (!(pls->ctx = avformat_alloc_context())) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (pls->n_segments == 0)
continue;
pls->index = i;
pls->needed = 1;
pls->parent = s;
/*
* If this is a live stream and this playlist looks like it is one segment
* behind, try to sync it up so that every substream starts at the same
* time position (so e.g. avformat_find_stream_info() will see packets from
* all active streams within the first few seconds). This is not very generic,
* though, as the sequence numbers are technically independent.
*/
if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
pls->cur_seq_no = highest_cur_seq_no;
}
pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
if (!pls->read_buffer){
ret = AVERROR(ENOMEM);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
read_data, NULL, NULL);
pls->pb.seekable = 0;
ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
NULL, 0, 0);
if (ret < 0) {
/* Free the ctx - it isn't initialized properly at this point,
* so avformat_close_input shouldn't be called. If
* avformat_open_input fails below, it frees and zeros the
* context, so it doesn't need any special treatment like this. */
av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
pls->ctx->pb = &pls->pb;
pls->ctx->io_open = nested_io_open;
pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
goto fail;
ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
if (ret < 0)
goto fail;
if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
avformat_queue_attached_pictures(pls->ctx);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
pls->id3_deferred_extra = NULL;
}
if (pls->is_id3_timestamped == -1)
av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
/*
* For ID3 timestamped raw audio streams we need to detect the packet
* durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
* but for other streams we can rely on our user calling avformat_find_stream_info()
* on us if they want to.
*/
if (pls->is_id3_timestamped) {
ret = avformat_find_stream_info(pls->ctx, NULL);
if (ret < 0)
goto fail;
}
pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
/* Create new AVStreams for each stream in this playlist */
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0)
goto fail;
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
}
update_noheader_flag(s);
return 0;
fail:
hls_close(s);
return ret;
}
static int recheck_discard_flags(AVFormatContext *s, int first)
{
HLSContext *c = s->priv_data;
int i, changed = 0;
/* Check if any new streams are needed */
for (i = 0; i < c->n_playlists; i++)
c->playlists[i]->cur_needed = 0;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
struct playlist *pls = c->playlists[s->streams[i]->id];
if (st->discard < AVDISCARD_ALL)
pls->cur_needed = 1;
}
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->cur_needed && !pls->needed) {
pls->needed = 1;
changed = 1;
pls->cur_seq_no = select_cur_seq_no(c, pls);
pls->pb.eof_reached = 0;
if (c->cur_timestamp != AV_NOPTS_VALUE) {
/* catch up */
pls->seek_timestamp = c->cur_timestamp;
pls->seek_flags = AVSEEK_FLAG_ANY;
pls->seek_stream_index = -1;
}
av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
} else if (first && !pls->cur_needed && pls->needed) {
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
pls->needed = 0;
changed = 1;
av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
}
}
return changed;
}
static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
{
if (pls->id3_offset >= 0) {
pls->pkt.dts = pls->id3_mpegts_timestamp +
av_rescale_q(pls->id3_offset,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
if (pls->pkt.duration)
pls->id3_offset += pls->pkt.duration;
else
pls->id3_offset = -1;
} else {
/* there have been packets with unknown duration
* since the last id3 tag, should not normally happen */
pls->pkt.dts = AV_NOPTS_VALUE;
}
if (pls->pkt.duration)
pls->pkt.duration = av_rescale_q(pls->pkt.duration,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
pls->pkt.pts = AV_NOPTS_VALUE;
}
static AVRational get_timebase(struct playlist *pls)
{
if (pls->is_id3_timestamped)
return MPEG_TIME_BASE_Q;
return pls->ctx->streams[pls->pkt.stream_index]->time_base;
}
static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
int64_t ts_b, struct playlist *pls_b)
{
int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
}
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
{
HLSContext *c = s->priv_data;
int ret, i, minplaylist = -1;
recheck_discard_flags(s, c->first_packet);
c->first_packet = 0;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
/* Make sure we've got one buffered packet from each open playlist
* stream */
if (pls->needed && !pls->pkt.data) {
while (1) {
int64_t ts_diff;
AVRational tb;
ret = av_read_frame(pls->ctx, &pls->pkt);
if (ret < 0) {
if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
return ret;
reset_packet(&pls->pkt);
break;
} else {
/* stream_index check prevents matching picture attachments etc. */
if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
/* audio elementary streams are id3 timestamped */
fill_timing_for_id3_timestamped_stream(pls);
}
if (c->first_timestamp == AV_NOPTS_VALUE &&
pls->pkt.dts != AV_NOPTS_VALUE)
c->first_timestamp = av_rescale_q(pls->pkt.dts,
get_timebase(pls), AV_TIME_BASE_Q);
}
if (pls->seek_timestamp == AV_NOPTS_VALUE)
break;
if (pls->seek_stream_index < 0 ||
pls->seek_stream_index == pls->pkt.stream_index) {
if (pls->pkt.dts == AV_NOPTS_VALUE) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
tb = get_timebase(pls);
ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
tb.den, AV_ROUND_DOWN) -
pls->seek_timestamp;
if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
pls->pkt.flags & AV_PKT_FLAG_KEY)) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
}
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
}
}
/* Check if this stream has the packet with the lowest dts */
if (pls->pkt.data) {
struct playlist *minpls = minplaylist < 0 ?
NULL : c->playlists[minplaylist];
if (minplaylist < 0) {
minplaylist = i;
} else {
int64_t dts = pls->pkt.dts;
int64_t mindts = minpls->pkt.dts;
if (dts == AV_NOPTS_VALUE ||
(mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
minplaylist = i;
}
}
}
/* If we got a packet, return it */
if (minplaylist >= 0) {
struct playlist *pls = c->playlists[minplaylist];
AVStream *ist;
AVStream *st;
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0) {
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return ret;
}
/* check if noheader flag has been cleared by the subdemuxer */
if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
pls->has_noheader_flag = 0;
update_noheader_flag(s);
}
if (pls->pkt.stream_index >= pls->n_main_streams) {
av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return AVERROR_BUG;
}
ist = pls->ctx->streams[pls->pkt.stream_index];
st = pls->main_streams[pls->pkt.stream_index];
*pkt = pls->pkt;
pkt->stream_index = st->index;
reset_packet(&c->playlists[minplaylist]->pkt);
if (pkt->dts != AV_NOPTS_VALUE)
c->cur_timestamp = av_rescale_q(pkt->dts,
ist->time_base,
AV_TIME_BASE_Q);
/* There may be more situations where this would be useful, but this at least
* handles newly probed codecs properly (i.e. request_probe by mpegts). */
if (ist->codecpar->codec_id != st->codecpar->codec_id) {
ret = set_stream_info_from_input_stream(st, pls, ist);
if (ret < 0) {
av_packet_unref(pkt);
return ret;
}
}
return 0;
}
return AVERROR_EOF;
}
static int hls_read_seek(AVFormatContext *s, int stream_index,
int64_t timestamp, int flags)
{
HLSContext *c = s->priv_data;
struct playlist *seek_pls = NULL;
int i, seq_no;
int j;
int stream_subdemuxer_index;
int64_t first_timestamp, seek_timestamp, duration;
if ((flags & AVSEEK_FLAG_BYTE) ||
!(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
return AVERROR(ENOSYS);
first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
s->streams[stream_index]->time_base.den,
flags & AVSEEK_FLAG_BACKWARD ?
AV_ROUND_DOWN : AV_ROUND_UP);
duration = s->duration == AV_NOPTS_VALUE ?
0 : s->duration;
if (0 < duration && duration < seek_timestamp - first_timestamp)
return AVERROR(EIO);
/* find the playlist with the specified stream */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
for (j = 0; j < pls->n_main_streams; j++) {
if (pls->main_streams[j] == s->streams[stream_index]) {
seek_pls = pls;
stream_subdemuxer_index = j;
break;
}
}
}
/* check if the timestamp is valid for the playlist with the
* specified stream index */
if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
return AVERROR(EIO);
/* set segment now so we do not need to search again below */
seek_pls->cur_seq_no = seq_no;
seek_pls->seek_stream_index = stream_subdemuxer_index;
for (i = 0; i < c->n_playlists; i++) {
/* Reset reading */
struct playlist *pls = c->playlists[i];
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
pls->pb.eof_reached = 0;
/* Clear any buffered data */
pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
/* Reset the pos, to let the mpegts demuxer know we've seeked. */
pls->pb.pos = 0;
/* Flush the packet queue of the subdemuxer. */
ff_read_frame_flush(pls->ctx);
pls->seek_timestamp = seek_timestamp;
pls->seek_flags = flags;
if (pls != seek_pls) {
/* set closest segment seq_no for playlists not handled above */
find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
/* seek the playlist to the given position without taking
* keyframes into account since this playlist does not have the
* specified stream where we should look for the keyframes */
pls->seek_stream_index = -1;
pls->seek_flags |= AVSEEK_FLAG_ANY;
}
}
c->cur_timestamp = seek_timestamp;
return 0;
}
static int hls_probe(AVProbeData *p)
{
/* Require #EXTM3U at the start, and either one of the ones below
* somewhere for a proper match. */
if (strncmp(p->buf, "#EXTM3U", 7))
return 0;
if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
return AVPROBE_SCORE_MAX;
return 0;
}
#define OFFSET(x) offsetof(HLSContext, x)
#define FLAGS AV_OPT_FLAG_DECODING_PARAM
static const AVOption hls_options[] = {
{"live_start_index", "segment index to start live streams at (negative values are from the end)",
OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
{"allowed_extensions", "List of file extensions that hls is allowed to access",
OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
{.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"},
INT_MIN, INT_MAX, FLAGS},
{NULL}
};
static const AVClass hls_class = {
.class_name = "hls,applehttp",
.item_name = av_default_item_name,
.option = hls_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVInputFormat ff_hls_demuxer = {
.name = "hls,applehttp",
.long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
.priv_class = &hls_class,
.priv_data_size = sizeof(HLSContext),
.read_probe = hls_probe,
.read_header = hls_read_header,
.read_packet = hls_read_packet,
.read_close = hls_close,
.read_seek = hls_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3416_0 |
crossvul-cpp_data_good_3568_8 | /* -*- Mode: c; c-basic-offset: 2 -*-
*
* raptor_rdfxml.c - Raptor RDF/XML Parser
*
* Copyright (C) 2000-2008, David Beckett http://www.dajobe.org/
* Copyright (C) 2000-2005, University of Bristol, UK http://www.bristol.ac.uk/
*
* This package is Free Software and part of Redland http://librdf.org/
*
* It is licensed under the following three licenses as alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE.html or LICENSE.txt at the top of this package for the
* complete terms and further detail along with the license texts for
* the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.
*
*
*/
#ifdef HAVE_CONFIG_H
#include <raptor_config.h>
#endif
#ifdef WIN32
#include <win32_raptor_config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
/* Raptor includes */
#include "raptor2.h"
#include "raptor_internal.h"
/* Define these for far too much output */
#undef RAPTOR_DEBUG_VERBOSE
#undef RAPTOR_DEBUG_CDATA
/* Raptor structures */
typedef enum {
/* Catch uninitialised state */
RAPTOR_STATE_INVALID = 0,
/* Skipping current tree of elements - used to recover finding
* illegal content, when parsling permissively.
*/
RAPTOR_STATE_SKIPPING,
/* Not in RDF grammar yet - searching for a start element.
*
* This can be <rdf:RDF> (goto NODE_ELEMENT_LIST) but since it is optional,
* the start element can also be one of
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementURIs
*
* If RDF content is assumed, go straight to OBJ
*/
RAPTOR_STATE_UNKNOWN,
/* A list of node elements
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementList
*/
RAPTOR_STATE_NODE_ELEMENT_LIST,
/* Found an <rdf:Description> */
RAPTOR_STATE_DESCRIPTION,
/* Found a property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*/
RAPTOR_STATE_PROPERTYELT,
/* A property element that is an ordinal - rdf:li, rdf:_n
*/
RAPTOR_STATE_MEMBER_PROPERTYELT,
/* Found a node element
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElement
*/
RAPTOR_STATE_NODE_ELEMENT,
/* A property element with rdf:parseType="Literal"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeLiteralPropertyElt
*/
RAPTOR_STATE_PARSETYPE_LITERAL,
/* A property element with rdf:parseType="Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeResourcePropertyElt
*/
RAPTOR_STATE_PARSETYPE_RESOURCE,
/* A property element with rdf:parseType="Collection"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeCollectionPropertyElt
*
* (This also handles daml:Collection)
*/
RAPTOR_STATE_PARSETYPE_COLLECTION,
/* A property element with a rdf:parseType attribute and a value
* not "Literal" or "Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeOtherPropertyElt
*/
RAPTOR_STATE_PARSETYPE_OTHER,
RAPTOR_STATE_PARSETYPE_LAST = RAPTOR_STATE_PARSETYPE_OTHER
} raptor_state;
static const char* const raptor_state_names[RAPTOR_STATE_PARSETYPE_LAST+2] = {
"INVALID",
"SKIPPING",
"UNKNOWN",
"nodeElementList",
"propertyElt",
"Description",
"propertyElt",
"memberPropertyElt",
"nodeElement",
"parseTypeLiteral",
"parseTypeResource",
"parseTypeCollection",
"parseTypeOther"
};
static const char * raptor_rdfxml_state_as_string(raptor_state state)
{
if(state < 1 || state > RAPTOR_STATE_PARSETYPE_LAST)
state = (raptor_state)0;
return raptor_state_names[(int)state];
}
/*
* raptor_rdfxml_check_propertyElement_name:
* @name: rdf namespace term
*
* Check if an rdf namespace name is allowed to be used as a Node Element.
*
* Return value: < 0 if unknown rdf namespace term, 0 if known and not allowed, > 0 if known and allowed
*/
static int
raptor_rdfxml_check_nodeElement_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, name))
return raptor_rdf_ns_terms_info[i].allowed_as_nodeElement;
return -1;
}
/*
* raptor_rdfxml_check_propertyElement_name:
* @name: rdf namespace term
*
* Check if an rdf namespace name is allowed to be used as a Property Element.
*
* Return value: < 0 if unknown rdf namespace term, 0 if known and not allowed, > 0 if known and allowed
*/
static int
raptor_rdfxml_check_propertyElement_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, (const char*)name))
return raptor_rdf_ns_terms_info[i].allowed_as_propertyElement;
return -1;
}
static int
raptor_rdfxml_check_propertyAttribute_name(const char *name)
{
int i;
if(*name == '_')
return 1;
for(i = 0; raptor_rdf_ns_terms_info[i].name; i++)
if(!strcmp(raptor_rdf_ns_terms_info[i].name, (const char*)name))
return raptor_rdf_ns_terms_info[i].allowed_as_propertyAttribute;
return -1;
}
typedef enum {
/* undetermined yet - whitespace is stored */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN,
/* literal content - no elements, cdata allowed, whitespace significant
* <propElement> blah </propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL,
/* parseType literal content (WF XML) - all content preserved
* <propElement rdf:parseType="Literal"><em>blah</em></propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL,
/* top-level nodes - 0+ elements expected, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* only used for <rdf:RDF> or implict <rdf:RDF>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES,
/* properties - 0+ elements expected, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* <nodeElement><prop1>blah</prop1> <prop2>blah</prop2> </nodeElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES,
/* property content - all content preserved
* any content type changes when first non-whitespace found
* <propElement>...
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT,
/* resource URI given - no element, no cdata, whitespace ignored,
* any non-whitespace cdata is error
* <propElement rdf:resource="uri"/>
* <propElement rdf:resource="uri"></propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE,
/* skipping content - all content is preserved
* Used when skipping content for unknown parseType-s,
* error recovery, some other reason
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED,
/* parseType Collection - all content preserved
* Parsing of this determined by RDF/XML (Revised) closed collection rules
* <propElement rdf:parseType="Collection">...</propElement>
*/
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION,
/* Like above but handles "daml:collection" */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION,
/* dummy for use in strings below */
RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST
} raptor_rdfxml_element_content_type;
static const struct {
const char * name;
int whitespace_significant;
/* non-blank cdata */
int cdata_allowed;
/* XML element content */
int element_allowed;
/* Do RDF-specific processing? (property attributes, rdf: attributes, ...) */
int rdf_processing;
} rdf_content_type_info[RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST]={
{"Unknown", 1, 1, 1, 0 },
{"Literal", 1, 1, 0, 0 },
{"XML Literal", 1, 1, 1, 0 },
{"Nodes", 0, 0, 1, 1 },
{"Properties", 0, 1, 1, 1 },
{"Property Content",1, 1, 1, 1 },
{"Resource", 0, 0, 0, 0 },
{"Preserved", 1, 1, 1, 0 },
{"Collection", 1, 1, 1, 1 },
{"DAML Collection", 1, 1, 1, 1 },
};
static const char *
raptor_rdfxml_element_content_type_as_string(raptor_rdfxml_element_content_type type)
{
if(type > RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST)
return "INVALID";
return rdf_content_type_info[type].name;
}
/*
* Raptor Element/attributes on stack
*/
struct raptor_rdfxml_element_s {
raptor_world* world;
raptor_xml_element *xml_element;
/* NULL at bottom of stack */
struct raptor_rdfxml_element_s *parent;
/* attributes declared in M&S */
const unsigned char * rdf_attr[RDF_NS_LAST + 1];
/* how many of above seen */
int rdf_attr_count;
/* state that this production matches */
raptor_state state;
/* how to handle the content inside this XML element */
raptor_rdfxml_element_content_type content_type;
/* starting state for children of this element */
raptor_state child_state;
/* starting content type for children of this element */
raptor_rdfxml_element_content_type child_content_type;
/* Reified statement identifier */
raptor_term* reified;
unsigned const char* reified_id;
/* Bag identifier */
raptor_term* bag;
int last_bag_ordinal; /* starts at 0, so first predicate is rdf:_1 */
/* Subject identifier (URI/anon ID), type, source
*
* When the XML element represents a node, this is the identifier
*/
raptor_term* subject;
/* Predicate URI
*
* When the XML element represents a node or predicate,
* this is the identifier of the predicate
*/
raptor_term* predicate;
/* Object identifier (URI/anon ID), type, source
*
* When this XML element generates a statement that needs an object,
* possibly from a child element, this is the identifier of the object
*/
raptor_term* object;
/* URI of datatype of literal */
raptor_uri *object_literal_datatype;
/* last ordinal used, so initialising to 0 works, emitting rdf:_1 first */
int last_ordinal;
/* If this element's parseType is a Collection
* this identifies the anon node of current tail of the collection(list).
*/
const unsigned char *tail_id;
/* RDF/XML specific checks */
/* all cdata so far is whitespace */
unsigned int content_cdata_all_whitespace;
};
typedef struct raptor_rdfxml_element_s raptor_rdfxml_element;
#define RAPTOR_RDFXML_N_CONCEPTS 5
/*
* Raptor parser object
*/
struct raptor_rdfxml_parser_s {
raptor_sax2 *sax2;
/* stack of elements - elements add after current_element */
raptor_rdfxml_element *root_element;
raptor_rdfxml_element *current_element;
raptor_uri* concepts[RAPTOR_RDFXML_N_CONCEPTS];
/* set of seen rdf:ID / rdf:bagID values (with in-scope base URI) */
raptor_id_set* id_set;
void *xml_content;
size_t xml_content_length;
raptor_iostream* iostream;
/* writer for building parseType="Literal" content */
raptor_xml_writer* xml_writer;
};
/* static variables */
#define RAPTOR_DAML_NS_URI(rdf_xml_parser) rdf_xml_parser->concepts[0]
#define RAPTOR_DAML_List_URI(rdf_xml_parser) rdf_xml_parser->concepts[1]
#define RAPTOR_DAML_first_URI(rdf_xml_parser) rdf_xml_parser->concepts[2]
#define RAPTOR_DAML_rest_URI(rdf_xml_parser) rdf_xml_parser->concepts[3]
#define RAPTOR_DAML_nil_URI(rdf_xml_parser) rdf_xml_parser->concepts[4]
/* RAPTOR_RDFXML_N_CONCEPTS defines size of array */
/* prototypes for element functions */
static raptor_rdfxml_element* raptor_rdfxml_element_pop(raptor_rdfxml_parser *rdf_parser);
static void raptor_rdfxml_element_push(raptor_rdfxml_parser *rdf_parser, raptor_rdfxml_element* element);
static int raptor_rdfxml_record_ID(raptor_parser *rdf_parser, raptor_rdfxml_element *element, const unsigned char *id);
/* prototypes for grammar functions */
static void raptor_rdfxml_start_element_grammar(raptor_parser *parser, raptor_rdfxml_element *element);
static void raptor_rdfxml_end_element_grammar(raptor_parser *parser, raptor_rdfxml_element *element);
static void raptor_rdfxml_cdata_grammar(raptor_parser *parser, const unsigned char *s, int len, int is_cdata);
/* prototype for statement related functions */
static void raptor_rdfxml_generate_statement(raptor_parser *rdf_parser, raptor_term *subject, raptor_uri *predicate_uri, raptor_term *object, raptor_term *reified, raptor_rdfxml_element *bag_element);
/* Prototypes for parsing data functions */
static int raptor_rdfxml_parse_init(raptor_parser* rdf_parser, const char *name);
static void raptor_rdfxml_parse_terminate(raptor_parser *rdf_parser);
static int raptor_rdfxml_parse_start(raptor_parser* rdf_parser);
static int raptor_rdfxml_parse_chunk(raptor_parser* rdf_parser, const unsigned char *buffer, size_t len, int is_end);
static void raptor_rdfxml_update_document_locator(raptor_parser *rdf_parser);
static raptor_uri* raptor_rdfxml_inscope_base_uri(raptor_parser *rdf_parser);
static raptor_rdfxml_element*
raptor_rdfxml_element_pop(raptor_rdfxml_parser *rdf_xml_parser)
{
raptor_rdfxml_element *element = rdf_xml_parser->current_element;
if(!element)
return NULL;
rdf_xml_parser->current_element = element->parent;
if(rdf_xml_parser->root_element == element) /* just deleted root */
rdf_xml_parser->root_element = NULL;
return element;
}
static void
raptor_rdfxml_element_push(raptor_rdfxml_parser *rdf_xml_parser, raptor_rdfxml_element* element)
{
element->parent = rdf_xml_parser->current_element;
rdf_xml_parser->current_element = element;
if(!rdf_xml_parser->root_element)
rdf_xml_parser->root_element = element;
}
static void
raptor_free_rdfxml_element(raptor_rdfxml_element *element)
{
int i;
/* Free special RDF M&S attributes */
for(i = 0; i <= RDF_NS_LAST; i++)
if(element->rdf_attr[i])
RAPTOR_FREE(char*, element->rdf_attr[i]);
if(element->subject)
raptor_free_term(element->subject);
if(element->predicate)
raptor_free_term(element->predicate);
if(element->object)
raptor_free_term(element->object);
if(element->bag)
raptor_free_term(element->bag);
if(element->reified)
raptor_free_term(element->reified);
if(element->tail_id)
RAPTOR_FREE(char*, (char*)element->tail_id);
if(element->object_literal_datatype)
raptor_free_uri(element->object_literal_datatype);
if(element->reified_id)
RAPTOR_FREE(char*, (char*)element->reified_id);
RAPTOR_FREE(raptor_rdfxml_element, element);
}
static void
raptor_rdfxml_sax2_new_namespace_handler(void *user_data,
raptor_namespace* nspace)
{
raptor_parser* rdf_parser;
const unsigned char* namespace_name;
size_t namespace_name_len;
raptor_uri* uri = raptor_namespace_get_uri(nspace);
rdf_parser = (raptor_parser*)user_data;
raptor_parser_start_namespace(rdf_parser, nspace);
if(!uri)
return;
namespace_name = raptor_uri_as_counted_string(uri, &namespace_name_len);
if(namespace_name_len == raptor_rdf_namespace_uri_len-1 &&
!strncmp((const char*)namespace_name,
(const char*)raptor_rdf_namespace_uri,
namespace_name_len)) {
const unsigned char *prefix = raptor_namespace_get_prefix(nspace);
raptor_parser_warning(rdf_parser,
"Declaring a namespace with prefix %s to URI %s - one letter short of the RDF namespace URI and probably a mistake.",
prefix, namespace_name);
}
if(namespace_name_len > raptor_rdf_namespace_uri_len &&
!strncmp((const char*)namespace_name,
(const char*)raptor_rdf_namespace_uri,
raptor_rdf_namespace_uri_len)) {
raptor_parser_error(rdf_parser,
"Declaring a namespace URI %s to which the RDF namespace URI is a prefix is forbidden.",
namespace_name);
}
}
static void
raptor_rdfxml_start_element_handler(void *user_data,
raptor_xml_element* xml_element)
{
raptor_parser* rdf_parser;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
int ns_attributes_count = 0;
raptor_qname** named_attrs = NULL;
int i;
int count_bumped = 0;
rdf_parser = (raptor_parser*)user_data;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return;
raptor_rdfxml_update_document_locator(rdf_parser);
/* Create new element structure */
element = RAPTOR_CALLOC(raptor_rdfxml_element*, 1, sizeof(*element));
if(!element) {
raptor_parser_fatal_error(rdf_parser, "Out of memory");
rdf_parser->failed = 1;
return;
}
element->world = rdf_parser->world;
element->xml_element = xml_element;
raptor_rdfxml_element_push(rdf_xml_parser, element);
named_attrs = raptor_xml_element_get_attributes(xml_element);
ns_attributes_count = raptor_xml_element_get_attributes_count(xml_element);
/* RDF-specific processing of attributes */
if(ns_attributes_count) {
raptor_qname** new_named_attrs;
int offset = 0;
raptor_rdfxml_element* parent_element;
parent_element = element->parent;
/* Allocate new array to move namespaced-attributes to if
* rdf processing is performed
*/
new_named_attrs = RAPTOR_CALLOC(raptor_qname**, ns_attributes_count,
sizeof(raptor_qname*));
if(!new_named_attrs) {
raptor_parser_fatal_error(rdf_parser, "Out of memory");
rdf_parser->failed = 1;
return;
}
for(i = 0; i < ns_attributes_count; i++) {
raptor_qname* attr = named_attrs[i];
/* If:
* 1 We are handling RDF content and RDF processing is allowed on
* this element
* OR
* 2 We are not handling RDF content and
* this element is at the top level (top level Desc. / typedNode)
* i.e. we have no parent
* then handle the RDF attributes
*/
if((parent_element &&
rdf_content_type_info[parent_element->child_content_type].rdf_processing) ||
!parent_element) {
/* Save pointers to some RDF M&S attributes */
/* If RDF namespace-prefixed attributes */
if(attr->nspace && attr->nspace->is_rdf_ms) {
const unsigned char *attr_name = attr->local_name;
int j;
for(j = 0; j <= RDF_NS_LAST; j++)
if(!strcmp((const char*)attr_name,
raptor_rdf_ns_terms_info[j].name)) {
element->rdf_attr[j] = attr->value;
element->rdf_attr_count++;
/* Delete it if it was stored elsewhere */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Found RDF namespace attribute '%s' URI %s\n",
(char*)attr_name, attr->value);
#endif
/* make sure value isn't deleted from qname structure */
attr->value = NULL;
raptor_free_qname(attr);
attr = NULL;
break;
}
} /* end if RDF namespaced-prefixed attributes */
if(!attr)
continue;
/* If non namespace-prefixed RDF attributes found on an element */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES) &&
!attr->nspace) {
const unsigned char *attr_name = attr->local_name;
int j;
for(j = 0; j <= RDF_NS_LAST; j++)
if(!strcmp((const char*)attr_name,
raptor_rdf_ns_terms_info[j].name)) {
element->rdf_attr[j] = attr->value;
element->rdf_attr_count++;
if(!raptor_rdf_ns_terms_info[j].allowed_unprefixed_on_attribute)
raptor_parser_warning(rdf_parser,
"Using rdf attribute '%s' without the RDF namespace has been deprecated.",
attr_name);
/* Delete it if it was stored elsewhere */
/* make sure value isn't deleted from qname structure */
attr->value = NULL;
raptor_free_qname(attr);
attr = NULL;
break;
}
} /* end if non-namespace prefixed RDF attributes */
if(!attr)
continue;
} /* end if leave literal XML alone */
if(attr)
new_named_attrs[offset++] = attr;
}
/* new attribute count is set from attributes that haven't been skipped */
ns_attributes_count = offset;
if(!ns_attributes_count) {
/* all attributes were deleted so delete the new array */
RAPTOR_FREE(raptor_qname_array, new_named_attrs);
new_named_attrs = NULL;
}
RAPTOR_FREE(raptor_qname_array, named_attrs);
named_attrs = new_named_attrs;
raptor_xml_element_set_attributes(xml_element,
named_attrs, ns_attributes_count);
} /* end if ns_attributes_count */
/* start from unknown; if we have a parent, it may set this */
element->state = RAPTOR_STATE_UNKNOWN;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN;
if(element->parent &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN) {
element->content_type = element->parent->child_content_type;
if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* If parent has an rdf:resource, this element should not be here */
raptor_parser_error(rdf_parser,
"property element '%s' has multiple object node elements, skipping.",
parent_el_name->local_name);
element->state = RAPTOR_STATE_SKIPPING;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
} else {
if(!element->parent->child_state) {
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error: no parent element child_state set",
__func__);
return;
}
element->state = element->parent->child_state;
element->parent->xml_element->content_element_seen++;
count_bumped++;
/* leave literal XML alone */
if(!rdf_content_type_info[element->content_type].cdata_allowed) {
if(element->parent->xml_element->content_element_seen &&
element->parent->xml_element->content_cdata_seen) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* Uh oh - mixed content, the parent element has cdata too */
raptor_parser_warning(rdf_parser, "element '%s' has mixed content.",
parent_el_name->local_name);
}
/* If there is some existing all-whitespace content cdata
* before this node element, delete it
*/
if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES &&
element->parent->xml_element->content_element_seen &&
element->parent->content_cdata_all_whitespace &&
element->parent->xml_element->content_cdata_length) {
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
raptor_free_stringbuffer(element->parent->xml_element->content_cdata_sb);
element->parent->xml_element->content_cdata_sb = NULL;
element->parent->xml_element->content_cdata_length = 0;
}
} /* end if leave literal XML alone */
} /* end if parent has no rdf:resource */
} /* end if element->parent */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Using content type %s\n",
rdf_content_type_info[element->content_type].name);
fprintf(stderr, "raptor_rdfxml_start_element_handler: Start ns-element: ");
raptor_print_xml_element(xml_element, stderr);
#endif
/* Check for non namespaced stuff when not in a parseType literal, other */
if(rdf_content_type_info[element->content_type].rdf_processing) {
const raptor_namespace* ns;
ns = raptor_xml_element_get_name(xml_element)->nspace;
/* The element */
/* If has no namespace or the namespace has no name (xmlns="") */
if((!ns || (ns && !raptor_namespace_get_uri(ns))) && element->parent) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
raptor_parser_error(rdf_parser,
"Using an element '%s' without a namespace is forbidden.",
parent_el_name->local_name);
element->state = RAPTOR_STATE_SKIPPING;
/* Remove count above so that parent thinks this is empty */
if(count_bumped)
element->parent->xml_element->content_element_seen--;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
}
/* Check for any remaining non-namespaced attributes */
if(named_attrs) {
for(i = 0; i < ns_attributes_count; i++) {
raptor_qname *attr = named_attrs[i];
/* Check if any attributes are non-namespaced */
if(!attr->nspace ||
(attr->nspace && !raptor_namespace_get_uri(attr->nspace))) {
raptor_parser_error(rdf_parser,
"Using an attribute '%s' without a namespace is forbidden.",
attr->local_name);
raptor_free_qname(attr);
named_attrs[i] = NULL;
}
}
}
}
if(element->rdf_attr[RDF_NS_aboutEach] ||
element->rdf_attr[RDF_NS_aboutEachPrefix]) {
raptor_parser_warning(rdf_parser,
"element '%s' has aboutEach / aboutEachPrefix, skipping.",
raptor_xml_element_get_name(xml_element)->local_name);
element->state = RAPTOR_STATE_SKIPPING;
/* Remove count above so that parent thinks this is empty */
if(count_bumped)
element->parent->xml_element->content_element_seen--;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
}
/* Right, now ready to enter the grammar */
raptor_rdfxml_start_element_grammar(rdf_parser, element);
return;
}
static void
raptor_rdfxml_end_element_handler(void *user_data,
raptor_xml_element* xml_element)
{
raptor_parser* rdf_parser;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
rdf_parser = (raptor_parser*)user_data;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(!rdf_parser->failed) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_rdfxml_end_element_grammar(rdf_parser,
rdf_xml_parser->current_element);
}
element = raptor_rdfxml_element_pop(rdf_xml_parser);
if(element) {
if(element->parent) {
/* Do not change this; PROPERTYELT will turn into MEMBER if necessary
* See the switch case for MEMBER / PROPERTYELT where the test is done.
*
* PARSETYPE_RESOURCE should never be propogated up since it
* will turn the next child (node) element into a property
*/
if(element->state != RAPTOR_STATE_MEMBER_PROPERTYELT &&
element->state != RAPTOR_STATE_PARSETYPE_RESOURCE)
element->parent->child_state = element->state;
}
raptor_free_rdfxml_element(element);
}
}
/* cdata (and ignorable whitespace for libxml).
* s 0 terminated is for libxml
*/
static void
raptor_rdfxml_characters_handler(void *user_data,
raptor_xml_element* xml_element,
const unsigned char *s, int len)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_cdata_grammar(rdf_parser, s, len, 0);
}
/* cdata (and ignorable whitespace for libxml).
* s is 0 terminated for libxml2
*/
static void
raptor_rdfxml_cdata_handler(void *user_data, raptor_xml_element* xml_element,
const unsigned char *s, int len)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_cdata_grammar(rdf_parser, s, len, 1);
}
/* comment handler
* s is 0 terminated
*/
static void
raptor_rdfxml_comment_handler(void *user_data, raptor_xml_element* xml_element,
const unsigned char *s)
{
raptor_parser* rdf_parser = (raptor_parser*)user_data;
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
if(rdf_parser->failed || !xml_element)
return;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
element = rdf_xml_parser->current_element;
if(element) {
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL)
raptor_xml_writer_comment(rdf_xml_parser->xml_writer, s);
}
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("XML Comment '%s'\n", s);
#endif
}
static const unsigned char* const daml_namespace_uri_string = (const unsigned char*)"http://www.daml.org/2001/03/daml+oil#";
static const int daml_namespace_uri_string_len = 37;
static int
raptor_rdfxml_parse_init(raptor_parser* rdf_parser, const char *name)
{
raptor_rdfxml_parser* rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
raptor_sax2* sax2;
raptor_world* world = rdf_parser->world;
/* Allocate sax2 object */
sax2 = raptor_new_sax2(rdf_parser->world, &rdf_parser->locator, rdf_parser);
rdf_xml_parser->sax2 = sax2;
if(!sax2)
return 1;
/* Initialize sax2 element handlers */
raptor_sax2_set_start_element_handler(sax2, raptor_rdfxml_start_element_handler);
raptor_sax2_set_end_element_handler(sax2, raptor_rdfxml_end_element_handler);
raptor_sax2_set_characters_handler(sax2, raptor_rdfxml_characters_handler);
raptor_sax2_set_cdata_handler(sax2, raptor_rdfxml_cdata_handler);
raptor_sax2_set_comment_handler(sax2, raptor_rdfxml_comment_handler);
raptor_sax2_set_namespace_handler(sax2, raptor_rdfxml_sax2_new_namespace_handler);
/* Allocate uris */
RAPTOR_DAML_NS_URI(rdf_xml_parser) = raptor_new_uri_from_counted_string(world,
daml_namespace_uri_string,
daml_namespace_uri_string_len);
RAPTOR_DAML_List_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"List");
RAPTOR_DAML_first_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser) ,(const unsigned char *)"first");
RAPTOR_DAML_rest_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"rest");
RAPTOR_DAML_nil_URI(rdf_xml_parser) = raptor_new_uri_from_uri_local_name(world, RAPTOR_DAML_NS_URI(rdf_xml_parser), (const unsigned char *)"nil");
/* Check for uri allocation failures */
if(!RAPTOR_DAML_NS_URI(rdf_xml_parser) ||
!RAPTOR_DAML_List_URI(rdf_xml_parser) ||
!RAPTOR_DAML_first_URI(rdf_xml_parser) ||
!RAPTOR_DAML_rest_URI(rdf_xml_parser) ||
!RAPTOR_DAML_nil_URI(rdf_xml_parser))
return 1;
/* Everything succeeded */
return 0;
}
static int
raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
static void
raptor_rdfxml_parse_terminate(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
int i;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_xml_parser->sax2) {
raptor_free_sax2(rdf_xml_parser->sax2);
rdf_xml_parser->sax2 = NULL;
}
while( (element = raptor_rdfxml_element_pop(rdf_xml_parser)) )
raptor_free_rdfxml_element(element);
for(i = 0; i < RAPTOR_RDFXML_N_CONCEPTS; i++) {
raptor_uri* concept_uri = rdf_xml_parser->concepts[i];
if(concept_uri) {
raptor_free_uri(concept_uri);
rdf_xml_parser->concepts[i] = NULL;
}
}
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
}
static int
raptor_rdfxml_parse_recognise_syntax(raptor_parser_factory* factory,
const unsigned char *buffer, size_t len,
const unsigned char *identifier,
const unsigned char *suffix,
const char *mime_type)
{
int score = 0;
if(suffix) {
if(!strcmp((const char*)suffix, "rdf") ||
!strcmp((const char*)suffix, "rdfs") ||
!strcmp((const char*)suffix, "foaf") ||
!strcmp((const char*)suffix, "doap") ||
!strcmp((const char*)suffix, "owl") ||
!strcmp((const char*)suffix, "daml"))
score = 9;
if(!strcmp((const char*)suffix, "rss"))
score = 3;
}
if(identifier) {
if(strstr((const char*)identifier, "rss1"))
score += 5;
else if(!suffix && strstr((const char*)identifier, "rss"))
score += 3;
else if(!suffix && strstr((const char*)identifier, "rdf"))
score += 2;
else if(!suffix && strstr((const char*)identifier, "RDF"))
score += 2;
}
if(mime_type) {
if(strstr((const char*)mime_type, "html"))
score -= 4;
else if(!strcmp((const char*)mime_type, "text/rdf"))
score += 7;
else if(!strcmp((const char*)mime_type, "application/xml"))
score += 5;
}
if(buffer && len) {
/* Check it's an XML namespace declared and not N3 or Turtle which
* mention the namespace URI but not in this form.
*/
#define HAS_RDF_XMLNS1 (raptor_memstr((const char*)buffer, len, "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS2 (raptor_memstr((const char*)buffer, len, "xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS3 (raptor_memstr((const char*)buffer, len, "xmlns=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_XMLNS4 (raptor_memstr((const char*)buffer, len, "xmlns='http://www.w3.org/1999/02/22-rdf-syntax-ns#") != NULL)
#define HAS_RDF_ENTITY1 (raptor_memstr((const char*)buffer, len, "<!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>") != NULL)
#define HAS_RDF_ENTITY2 (raptor_memstr((const char*)buffer, len, "<!ENTITY rdf \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">") != NULL)
#define HAS_RDF_ENTITY3 (raptor_memstr((const char*)buffer, len, "xmlns:rdf=\"&rdf;\"") != NULL)
#define HAS_RDF_ENTITY4 (raptor_memstr((const char*)buffer, len, "xmlns:rdf='&rdf;'") != NULL)
#define HAS_HTML_NS (raptor_memstr((const char*)buffer, len, "http://www.w3.org/1999/xhtml") != NULL)
#define HAS_HTML_ROOT (raptor_memstr((const char*)buffer, len, "<html") != NULL)
if(!HAS_HTML_NS && !HAS_HTML_ROOT &&
(HAS_RDF_XMLNS1 || HAS_RDF_XMLNS2 || HAS_RDF_XMLNS3 || HAS_RDF_XMLNS4 ||
HAS_RDF_ENTITY1 || HAS_RDF_ENTITY2 || HAS_RDF_ENTITY3 || HAS_RDF_ENTITY4)
) {
int has_rdf_RDF = (raptor_memstr((const char*)buffer, len, "<rdf:RDF") != NULL);
int has_rdf_Description = (raptor_memstr((const char*)buffer, len, "rdf:Description") != NULL);
int has_rdf_about = (raptor_memstr((const char*)buffer, len, "rdf:about") != NULL);
score += 7;
if(has_rdf_RDF)
score++;
if(has_rdf_Description)
score++;
if(has_rdf_about)
score++;
}
}
return score;
}
static int
raptor_rdfxml_parse_chunk(raptor_parser* rdf_parser,
const unsigned char *buffer,
size_t len, int is_end)
{
raptor_rdfxml_parser* rdf_xml_parser;
int rc;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return 1;
rc = raptor_sax2_parse_chunk(rdf_xml_parser->sax2, buffer, len, is_end);
if(is_end) {
if(rdf_parser->emitted_default_graph) {
raptor_parser_end_graph(rdf_parser, NULL, 0);
rdf_parser->emitted_default_graph--;
}
}
return rc;
}
static void
raptor_rdfxml_generate_statement(raptor_parser *rdf_parser,
raptor_term *subject_term,
raptor_uri *predicate_uri,
raptor_term *object_term,
raptor_term *reified_term,
raptor_rdfxml_element* bag_element)
{
raptor_statement *statement = &rdf_parser->statement;
raptor_term* predicate_term = NULL;
int free_reified_term = 0;
if(rdf_parser->failed)
return;
#ifdef RAPTOR_DEBUG_VERBOSE
if(!subject_term)
RAPTOR_FATAL1("Statement has no subject\n");
if(!predicate_uri)
RAPTOR_FATAL1("Statement has no predicate\n");
if(!object_term)
RAPTOR_FATAL1("Statement has no object\n");
#endif
predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri);
if(!predicate_term)
return;
statement->subject = subject_term;
statement->predicate = predicate_term;
statement->object = object_term;
#ifdef RAPTOR_DEBUG_VERBOSE
fprintf(stderr, "raptor_rdfxml_generate_statement: Generating statement: ");
raptor_statement_print(statement, stderr);
fputc('\n', stderr);
#endif
if(!rdf_parser->emitted_default_graph) {
raptor_parser_start_graph(rdf_parser, NULL, 0);
rdf_parser->emitted_default_graph++;
}
if(!rdf_parser->statement_handler)
goto generate_tidy;
/* Generate the statement; or is it a fact? */
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* the bagID mess */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID) &&
bag_element && bag_element->bag) {
raptor_term* bag = bag_element->bag;
raptor_uri* bag_predicate_uri = NULL;
raptor_term* bag_predicate_term = NULL;
statement->subject = bag;
bag_element->last_bag_ordinal++;
/* new URI object */
bag_predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world,
bag_element->last_bag_ordinal);
if(!bag_predicate_uri)
goto generate_tidy;
bag_predicate_term = raptor_new_term_from_uri(rdf_parser->world,
bag_predicate_uri);
raptor_free_uri(bag_predicate_uri);
if(!bag_predicate_term)
goto generate_tidy;
statement->predicate = bag_predicate_term;
if(!reified_term || !reified_term->value.blank.string) {
unsigned char *reified_id = NULL;
/* reified_term is NULL so generate a bag ID */
reified_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!reified_id)
goto generate_tidy;
reified_term = raptor_new_term_from_blank(rdf_parser->world, reified_id);
RAPTOR_FREE(char*, reified_id);
if(!reified_term)
goto generate_tidy;
free_reified_term = 1;
}
statement->object = reified_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
if(bag_predicate_term)
raptor_free_term(bag_predicate_term);
}
/* return if is there no reified ID (that is valid) */
if(!reified_term || !reified_term->value.blank.string)
goto generate_tidy;
/* otherwise generate reified statements */
statement->subject = reified_term;
statement->predicate = RAPTOR_RDF_type_term(rdf_parser->world);
statement->object = RAPTOR_RDF_Statement_term(rdf_parser->world);
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_subject_term(rdf_parser->world);
statement->object = subject_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_predicate_term(rdf_parser->world);
statement->object = predicate_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
/* statement->subject = reified_term; */
statement->predicate = RAPTOR_RDF_object_term(rdf_parser->world);
statement->object = object_term;
(*rdf_parser->statement_handler)(rdf_parser->user_data, statement);
generate_tidy:
/* Tidy up things allocated here */
if(predicate_term)
raptor_free_term(predicate_term);
if(free_reified_term && reified_term)
raptor_free_term(reified_term);
}
/**
* raptor_rdfxml_element_has_property_attributes:
* @element: element with the property attributes
*
* Return true if the element has at least one property attribute.
*
**/
static int
raptor_rdfxml_element_has_property_attributes(raptor_rdfxml_element *element)
{
int i;
if(element->xml_element->attribute_count > 0)
return 1;
/* look for rdf: properties */
for(i = 0; i <= RDF_NS_LAST; i++) {
if(element->rdf_attr[i] &&
raptor_rdf_ns_terms_info[i].type != RAPTOR_TERM_TYPE_UNKNOWN)
return 1;
}
return 0;
}
/**
* raptor_rdfxml_process_property_attributes:
* @rdf_parser: Raptor parser object
* @attributes_element: element with the property attributes
* @resource_element: element that defines the resource URI
* subject->value etc.
* @property_node_identifier: Use this identifier for the resource URI
* and count any ordinals for it locally
*
* Process the property attributes for an element for a given resource.
*
**/
static int
raptor_rdfxml_process_property_attributes(raptor_parser *rdf_parser,
raptor_rdfxml_element *attributes_element,
raptor_rdfxml_element *resource_element,
raptor_term *property_node_identifier)
{
unsigned int i;
raptor_term *resource_identifier;
resource_identifier = property_node_identifier ? property_node_identifier : resource_element->subject;
/* Process attributes as propAttr* = * (propName="string")*
*/
for(i = 0; i < attributes_element->xml_element->attribute_count; i++) {
raptor_qname* attr = attributes_element->xml_element->attributes[i];
const unsigned char *name;
const unsigned char *value;
int handled = 0;
if(!attr)
continue;
name = attr->local_name;
value = attr->value;
if(!attr->nspace) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Using property attribute '%s' without a namespace is forbidden.",
name);
continue;
}
if(!raptor_unicode_check_utf8_nfc_string(value, strlen((const char*)value),
NULL)) {
const char *message;
message = "Property attribute '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, name, value);
else
raptor_parser_warning(rdf_parser, message, name, value);
continue;
}
/* Generate the property statement using one of these properties:
* 1) rdf:_n
* 2) the URI from the rdf:* attribute where allowed
* 3) otherwise forbidden (including rdf:li)
*/
if(attr->nspace->is_rdf_ms) {
/* is rdf: namespace */
if(*name == '_') {
int ordinal;
/* recognise rdf:_ */
name++;
ordinal = raptor_check_ordinal(name);
if(ordinal < 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Illegal ordinal value %d in property attribute '%s' seen on containing element '%s'.",
ordinal, attr->local_name, name);
}
} else {
int rc;
raptor_rdfxml_update_document_locator(rdf_parser);
rc = raptor_rdfxml_check_propertyAttribute_name((const char*)name);
if(!rc)
raptor_parser_error(rdf_parser,
"RDF term %s is forbidden as a property attribute.",
name);
else if(rc < 0)
raptor_parser_warning(rdf_parser,
"Unknown RDF namespace property attribute '%s'.",
name);
}
} /* end is RDF namespace property */
if(!handled) {
raptor_term* object_term;
object_term = raptor_new_term_from_literal(rdf_parser->world,
(unsigned char*)value,
NULL, NULL);
/* else not rdf: namespace or unknown in rdf: namespace so
* generate a statement with a literal object
*/
raptor_rdfxml_generate_statement(rdf_parser,
resource_identifier,
attr->uri,
object_term,
NULL, /* Property attributes are never reified*/
resource_element);
raptor_free_term(object_term);
}
} /* end for ... attributes */
/* Handle rdf property attributes
* (only rdf:type and rdf:value at present)
*/
for(i = 0; i <= RDF_NS_LAST; i++) {
const unsigned char *value = attributes_element->rdf_attr[i];
size_t value_len;
int object_is_literal;
raptor_uri *property_uri;
raptor_term* object_term;
if(!value)
continue;
value_len = strlen((const char*)value);
object_is_literal = (raptor_rdf_ns_terms_info[i].type == RAPTOR_TERM_TYPE_LITERAL);
if(raptor_rdf_ns_terms_info[i].type == RAPTOR_TERM_TYPE_UNKNOWN) {
const char *name = raptor_rdf_ns_terms_info[i].name;
int rc = raptor_rdfxml_check_propertyAttribute_name(name);
if(!rc) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"RDF term %s is forbidden as a property attribute.",
name);
continue;
} else if(rc < 0)
raptor_parser_warning(rdf_parser,
"Unknown RDF namespace property attribute '%s'.",
name);
}
if(object_is_literal &&
!raptor_unicode_check_utf8_nfc_string(value, value_len, NULL)) {
const char *message;
message = "Property attribute '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message,
raptor_rdf_ns_terms_info[i].name, value);
else
raptor_parser_warning(rdf_parser, message,
raptor_rdf_ns_terms_info[i].name, value);
continue;
}
property_uri = raptor_new_uri_for_rdf_concept(rdf_parser->world,
(const unsigned char*)raptor_rdf_ns_terms_info[i].name);
if(object_is_literal) {
object_term = raptor_new_term_from_literal(rdf_parser->world,
(unsigned char*)value,
NULL, NULL);
} else {
raptor_uri *base_uri;
raptor_uri *object_uri;
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
object_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri, value);
object_term = raptor_new_term_from_uri(rdf_parser->world, object_uri);
raptor_free_uri(object_uri);
}
raptor_rdfxml_generate_statement(rdf_parser,
resource_identifier,
property_uri,
object_term,
NULL, /* Property attributes are never reified*/
resource_element);
raptor_free_term(object_term);
raptor_free_uri(property_uri);
} /* end for rdf:property values */
return 0;
}
static void
raptor_rdfxml_start_element_grammar(raptor_parser *rdf_parser,
raptor_rdfxml_element *element)
{
raptor_rdfxml_parser *rdf_xml_parser;
int finished;
raptor_state state;
raptor_xml_element* xml_element;
raptor_qname* el_qname;
const unsigned char *el_name;
int element_in_rdf_ns;
int rc = 0;
raptor_uri* base_uri;
raptor_uri* element_name_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
xml_element = element->xml_element;
el_qname = raptor_xml_element_get_name(xml_element);
el_name = el_qname->local_name;
element_in_rdf_ns = (el_qname->nspace && el_qname->nspace->is_rdf_ms);
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
element_name_uri = el_qname->uri;
state = element->state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Starting in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
finished = 0;
while(!finished) {
switch(state) {
case RAPTOR_STATE_SKIPPING:
element->child_state = state;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED;
finished = 1;
break;
case RAPTOR_STATE_UNKNOWN:
/* found <rdf:RDF> ? */
if(element_in_rdf_ns) {
if(raptor_uri_equals(element_name_uri,
RAPTOR_RDF_RDF_URI(rdf_parser->world))) {
element->child_state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES;
/* Yes - need more content before can continue,
* so wait for another element
*/
finished = 1;
break;
}
if(raptor_uri_equals(element_name_uri,
RAPTOR_RDF_Description_URI(rdf_parser->world))) {
state = RAPTOR_STATE_DESCRIPTION;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
/* Yes - found something so move immediately to description */
break;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_nodeElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a node element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
}
/* If scanning for element, can continue */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING)) {
finished = 1;
break;
}
/* Otherwise the choice of the next state can be made
* from the current element by the OBJ state
*/
state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES;
break;
case RAPTOR_STATE_NODE_ELEMENT_LIST:
/* Handling
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElementList
*
* Everything goes to nodeElement
*/
state = RAPTOR_STATE_NODE_ELEMENT;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
break;
case RAPTOR_STATE_DESCRIPTION:
case RAPTOR_STATE_NODE_ELEMENT:
case RAPTOR_STATE_PARSETYPE_RESOURCE:
case RAPTOR_STATE_PARSETYPE_COLLECTION:
/* Handling <rdf:Description> or other node element
* http://www.w3.org/TR/rdf-syntax-grammar/#nodeElement
*
* or a property element acting as a node element for
* rdf:parseType="Resource"
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeResourcePropertyElt
* or rdf:parseType="Collection" (and daml:Collection)
* http://www.w3.org/TR/rdf-syntax-grammar/#parseTypeCollectionPropertyElt
*
* Only create a bag if bagID given
*/
if(!element_name_uri) {
/* We cannot handle this */
raptor_parser_warning(rdf_parser, "Using node element '%s' without a namespace is forbidden.",
el_qname->local_name);
raptor_rdfxml_update_document_locator(rdf_parser);
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_nodeElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a node element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
if(element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION &&
element->parent &&
(element->parent->state == RAPTOR_STATE_PROPERTYELT ||
element->parent->state == RAPTOR_STATE_MEMBER_PROPERTYELT) &&
element->parent->xml_element->content_element_seen > 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser, "The enclosing property already has an object");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(state == RAPTOR_STATE_NODE_ELEMENT ||
state == RAPTOR_STATE_DESCRIPTION ||
state == RAPTOR_STATE_PARSETYPE_COLLECTION) {
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_Description_URI(rdf_parser->world)))
state = RAPTOR_STATE_DESCRIPTION;
else
state = RAPTOR_STATE_NODE_ELEMENT;
}
if((element->rdf_attr[RDF_NS_ID]!=NULL) +
(element->rdf_attr[RDF_NS_about]!=NULL) +
(element->rdf_attr[RDF_NS_nodeID]!=NULL) > 1) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser, "Multiple attributes of rdf:ID, rdf:about and rdf:nodeID on element '%s' - only one allowed.", el_name);
}
if(element->rdf_attr[RDF_NS_ID]) {
unsigned char* subject_id;
raptor_uri* subject_uri;
subject_id = (unsigned char*)element->rdf_attr[RDF_NS_ID];
if(!raptor_valid_xml_ID(rdf_parser, subject_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:ID value '%s'",
subject_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, subject_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:ID value '%s'",
subject_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* after this, subject_id is the owner of the ID string */
element->rdf_attr[RDF_NS_ID] = NULL;
subject_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!subject_uri)
goto oom;
element->subject = raptor_new_term_from_uri(rdf_parser->world,
subject_uri);
raptor_free_uri(subject_uri);
if(!element->subject)
goto oom;
} else if(element->rdf_attr[RDF_NS_about]) {
raptor_uri* subject_uri;
subject_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri,
(const unsigned char*)element->rdf_attr[RDF_NS_about]);
if(!subject_uri)
goto oom;
element->subject = raptor_new_term_from_uri(rdf_parser->world,
subject_uri);
raptor_free_uri(subject_uri);
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_about]);
element->rdf_attr[RDF_NS_about] = NULL;
if(!element->subject)
goto oom;
} else if(element->rdf_attr[RDF_NS_nodeID]) {
unsigned char* subject_id;
subject_id = raptor_world_internal_generate_id(rdf_parser->world,
(unsigned char*)element->rdf_attr[RDF_NS_nodeID]);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
element->rdf_attr[RDF_NS_nodeID] = NULL;
if(!element->subject)
goto oom;
if(!raptor_valid_xml_ID(rdf_parser, element->subject->value.blank.string)) {
raptor_parser_error(rdf_parser, "Illegal rdf:nodeID value '%s'",
(const char*)element->subject->value.blank.string);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
} else if(element->parent &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION &&
element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION &&
element->parent->object) {
/* copy from parent (property element), it has a URI for us */
element->subject = raptor_term_copy(element->parent->object);
} else {
unsigned char* subject_id;
subject_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!element->subject)
goto oom;
}
if(element->rdf_attr[RDF_NS_bagID]) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
unsigned char* bag_id;
raptor_uri* bag_uri = NULL;
bag_id = (unsigned char*)element->rdf_attr[RDF_NS_bagID];
element->rdf_attr[RDF_NS_bagID] = NULL;
bag_uri = raptor_new_uri_from_id(rdf_parser->world,
base_uri, bag_id);
if(!bag_uri) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
element->bag = raptor_new_term_from_uri(rdf_parser->world, bag_uri);
raptor_free_uri(bag_uri);
if(!raptor_valid_xml_ID(rdf_parser, bag_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, bag_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
RAPTOR_FREE(char*, bag_id);
raptor_parser_warning(rdf_parser, "rdf:bagID is deprecated.");
raptor_rdfxml_generate_statement(rdf_parser,
element->bag,
RAPTOR_RDF_type_URI(rdf_parser->world),
RAPTOR_RDF_Bag_term(rdf_parser->world),
NULL,
NULL);
} else {
/* bagID forbidden */
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden.");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
}
if(element->parent) {
/* In a rdf:parseType="Collection" the resources are appended
* to the list at the genid element->parent->tail_id
*/
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION ||
element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
/* <idList> rdf:type rdf:List */
const unsigned char * idList;
raptor_uri *predicate_uri;
raptor_term* idList_term;
raptor_term* object_term;
idList = raptor_world_generate_bnodeid(rdf_parser->world);
if(!idList)
goto oom;
/* idList string is saved below in element->parent->tail_id */
idList_term = raptor_new_term_from_blank(rdf_parser->world, idList);
if(!idList_term) {
RAPTOR_FREE(char*, idList);
goto oom;
}
if((element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ||
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST)) {
raptor_uri* class_uri = NULL;
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
class_uri = RAPTOR_DAML_List_URI(rdf_xml_parser);
object_term = raptor_new_term_from_uri(rdf_parser->world,
class_uri);
} else
object_term = raptor_term_copy(RAPTOR_RDF_List_term(rdf_parser->world));
raptor_rdfxml_generate_statement(rdf_parser,
idList_term,
RAPTOR_RDF_type_URI(rdf_parser->world),
object_term,
NULL,
element);
raptor_free_term(object_term);
}
predicate_uri = (element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ? RAPTOR_DAML_first_URI(rdf_xml_parser) : RAPTOR_RDF_first_URI(rdf_parser->world);
/* <idList> rdf:first <element->uri> */
raptor_rdfxml_generate_statement(rdf_parser,
idList_term,
predicate_uri,
element->subject,
NULL,
NULL);
/* If there is no rdf:parseType="Collection" */
if(!element->parent->tail_id) {
/* Free any existing object still around.
* I suspect this can never happen.
*/
if(element->parent->object)
raptor_free_term(element->parent->object);
element->parent->object = raptor_new_term_from_blank(rdf_parser->world,
idList);
} else {
raptor_term* tail_id_term;
tail_id_term = raptor_new_term_from_blank(rdf_parser->world,
element->parent->tail_id);
predicate_uri = (element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) ? RAPTOR_DAML_rest_URI(rdf_xml_parser) : RAPTOR_RDF_rest_URI(rdf_parser->world);
/* _:tail_id rdf:rest _:listRest */
raptor_rdfxml_generate_statement(rdf_parser,
tail_id_term,
predicate_uri,
idList_term,
NULL,
NULL);
raptor_free_term(tail_id_term);
}
/* update new tail */
if(element->parent->tail_id)
RAPTOR_FREE(char*, (char*)element->parent->tail_id);
element->parent->tail_id = idList;
raptor_free_term(idList_term);
} else if(element->parent->state != RAPTOR_STATE_UNKNOWN &&
element->state != RAPTOR_STATE_PARSETYPE_RESOURCE) {
/* If there is a parent element (property) containing this
* element (node) and it has no object, set it from this subject
*/
if(element->parent->object) {
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_error(rdf_parser,
"Tried to set multiple objects of a statement");
} else {
/* Store URI of this node in our parent as the property object */
element->parent->object = raptor_term_copy(element->subject);
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
}
}
/* If this is a node element, generate the rdf:type statement
* from this node
*/
if(state == RAPTOR_STATE_NODE_ELEMENT) {
raptor_term* el_name_term;
el_name_term = raptor_new_term_from_uri(rdf_parser->world,
element_name_uri);
raptor_rdfxml_generate_statement(rdf_parser,
element->subject,
RAPTOR_RDF_type_URI(rdf_parser->world),
el_name_term,
element->reified,
element);
raptor_free_term(el_name_term);
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element, NULL))
goto oom;
/* for both productions now need some more content or
* property elements before can do any more work.
*/
element->child_state = RAPTOR_STATE_PROPERTYELT;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_OTHER:
/* FALLTHROUGH */
case RAPTOR_STATE_PARSETYPE_LITERAL:
raptor_xml_writer_start_element(rdf_xml_parser->xml_writer, xml_element);
element->child_state = RAPTOR_STATE_PARSETYPE_LITERAL;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
finished = 1;
break;
/* Handle all the detail of the various options of property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*
* All the attributes must be scanned here to see what additional
* property element work is needed. No triples are generated
* until the end of this element, until it is clear if the
* element was empty.
*/
case RAPTOR_STATE_MEMBER_PROPERTYELT:
case RAPTOR_STATE_PROPERTYELT:
if(!element_name_uri) {
raptor_parser_error(rdf_parser, "Using property element '%s' without a namespace is forbidden.",
raptor_xml_element_get_name(element->parent->xml_element)->local_name);
raptor_rdfxml_update_document_locator(rdf_parser);
element->state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* Handling rdf:li as a property, noting special processing */
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_li_URI(rdf_parser->world))) {
state = RAPTOR_STATE_MEMBER_PROPERTYELT;
}
if(element_in_rdf_ns) {
rc = raptor_rdfxml_check_propertyElement_name((const char*)el_name);
if(!rc) {
raptor_parser_error(rdf_parser,
"rdf:%s is forbidden as a property element.",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
} else if(rc < 0) {
raptor_parser_warning(rdf_parser,
"rdf:%s is an unknown RDF namespaced element.",
el_name);
}
}
/* rdf:ID on a property element - reify a statement.
* Allowed on all property element forms
*/
if(element->rdf_attr[RDF_NS_ID]) {
raptor_uri *reified_uri;
element->reified_id = element->rdf_attr[RDF_NS_ID];
element->rdf_attr[RDF_NS_ID] = NULL;
reified_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
element->reified_id);
if(!reified_uri)
goto oom;
element->reified = raptor_new_term_from_uri(rdf_parser->world,
reified_uri);
raptor_free_uri(reified_uri);
if(!element->reified)
goto oom;
if(!raptor_valid_xml_ID(rdf_parser, element->reified_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:ID value '%s'",
element->reified_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, element->reified_id)) {
raptor_parser_error(rdf_parser, "Duplicated rdf:ID value '%s'",
element->reified_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
}
/* rdf:datatype on a property element.
* Only allowed for
* http://www.w3.org/TR/rdf-syntax-grammar/#literalPropertyElt
*/
if(element->rdf_attr[RDF_NS_datatype]) {
raptor_uri *datatype_uri;
datatype_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
base_uri,
(const unsigned char*)element->rdf_attr[RDF_NS_datatype]);
element->object_literal_datatype = datatype_uri;
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_datatype]);
element->rdf_attr[RDF_NS_datatype] = NULL;
if(!element->object_literal_datatype)
goto oom;
}
if(element->rdf_attr[RDF_NS_bagID]) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
if(element->rdf_attr[RDF_NS_resource] ||
element->rdf_attr[RDF_NS_parseType]) {
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden on property element '%s' with an rdf:resource or rdf:parseType attribute.", el_name);
/* prevent this being used later either */
element->rdf_attr[RDF_NS_bagID] = NULL;
} else {
unsigned char* bag_id;
raptor_uri* bag_uri;
bag_id = (unsigned char*)element->rdf_attr[RDF_NS_bagID];
element->rdf_attr[RDF_NS_bagID] = NULL;
bag_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
bag_id);
if(!bag_uri) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
element->bag = raptor_new_term_from_uri(rdf_parser->world,
bag_uri);
raptor_free_uri(bag_uri);
if(!element->bag) {
RAPTOR_FREE(char*, bag_id);
goto oom;
}
if(!raptor_valid_xml_ID(rdf_parser, bag_id)) {
raptor_parser_error(rdf_parser, "Illegal rdf:bagID value '%s'",
bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
RAPTOR_FREE(char*, bag_id);
break;
}
if(raptor_rdfxml_record_ID(rdf_parser, element, bag_id)) {
raptor_parser_error(rdf_parser,
"Duplicated rdf:bagID value '%s'", bag_id);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
RAPTOR_FREE(char*, bag_id);
finished = 1;
break;
}
RAPTOR_FREE(char*, bag_id);
raptor_parser_warning(rdf_parser, "rdf:bagID is deprecated.");
}
} else {
/* bagID forbidden */
raptor_parser_error(rdf_parser, "rdf:bagID is forbidden.");
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
} /* if rdf:bagID on property element */
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT;
if(element->rdf_attr[RDF_NS_parseType]) {
const unsigned char *parse_type;
int i;
int is_parseType_Literal = 0;
parse_type = element->rdf_attr[RDF_NS_parseType];
if(raptor_rdfxml_element_has_property_attributes(element)) {
raptor_parser_error(rdf_parser, "Property attributes cannot be used with rdf:parseType='%s'", parse_type);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
finished = 1;
break;
}
/* Check for bad combinations of things with parseType */
for(i = 0; i <= RDF_NS_LAST; i++)
if(element->rdf_attr[i] && i != RDF_NS_parseType) {
raptor_parser_error(rdf_parser, "Attribute '%s' cannot be used with rdf:parseType='%s'", raptor_rdf_ns_terms_info[i].name, parse_type);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(!strcmp((char*)parse_type, "Literal"))
is_parseType_Literal = 1;
else if(!strcmp((char*)parse_type, "Resource")) {
unsigned char* subject_id;
state = RAPTOR_STATE_PARSETYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PROPERTYELT;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
/* create a node for the subject of the contained properties */
subject_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!subject_id)
goto oom;
element->subject = raptor_new_term_from_blank(rdf_parser->world,
subject_id);
RAPTOR_FREE(char*, subject_id);
if(!element->subject)
goto oom;
} else if(!strcmp((char*)parse_type, "Collection")) {
/* An rdf:parseType="Collection" appears as a single node */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PARSETYPE_COLLECTION;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION;
} else {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES) &&
!raptor_strcasecmp((char*)parse_type, "daml:collection")) {
/* A DAML collection appears as a single node */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
element->child_state = RAPTOR_STATE_PARSETYPE_COLLECTION;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION;
} else {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_WARN_OTHER_PARSETYPES)) {
raptor_parser_warning(rdf_parser, "Unknown rdf:parseType value '%s' taken as 'Literal'", parse_type);
}
is_parseType_Literal = 1;
}
}
if(is_parseType_Literal) {
raptor_xml_writer* xml_writer;
/* rdf:parseType="Literal" - explicitly or default
* if the parseType value is not recognised
*/
rdf_xml_parser->xml_content = NULL;
rdf_xml_parser->xml_content_length = 0;
rdf_xml_parser->iostream =
raptor_new_iostream_to_string(rdf_parser->world,
&rdf_xml_parser->xml_content,
&rdf_xml_parser->xml_content_length,
raptor_alloc_memory);
if(!rdf_xml_parser->iostream)
goto oom;
xml_writer = raptor_new_xml_writer(rdf_parser->world, NULL,
rdf_xml_parser->iostream);
rdf_xml_parser->xml_writer = xml_writer;
if(!rdf_xml_parser->xml_writer)
goto oom;
raptor_xml_writer_set_option(rdf_xml_parser->xml_writer,
RAPTOR_OPTION_WRITER_XML_DECLARATION,
NULL, 0);
element->child_state = RAPTOR_STATE_PARSETYPE_LITERAL;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
}
} else {
/* Can only be the empty property element case
* http://www.w3.org/TR/rdf-syntax-grammar/#emptyPropertyElt
*/
/* The presence of the rdf:resource or rdf:nodeID
* attributes is checked at element close time
*/
/*
* Assign reified URI here so we don't reify property attributes
* using this id
*/
if(element->reified_id && !element->reified) {
raptor_uri* reified_uri;
reified_uri = raptor_new_uri_from_id(rdf_parser->world, base_uri,
element->reified_id);
if(!reified_uri)
goto oom;
element->reified = raptor_new_term_from_uri(rdf_parser->world,
reified_uri);
raptor_free_uri(reified_uri);
if(!element->reified)
goto oom;
}
if(element->rdf_attr[RDF_NS_resource] ||
element->rdf_attr[RDF_NS_nodeID]) {
/* Done - wait for end of this element to end in order to
* check the element was empty as expected */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
} else {
/* Otherwise process content in obj (value) state */
element->child_state = RAPTOR_STATE_NODE_ELEMENT_LIST;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT;
}
}
finished = 1;
break;
case RAPTOR_STATE_INVALID:
default:
raptor_parser_fatal_error(rdf_parser,
"%s Internal error - unexpected parser state %d - %s",
__func__,
state, raptor_rdfxml_state_as_string(state));
finished = 1;
} /* end switch */
if(state != element->state) {
element->state = state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Moved to state %d - %s\n", state,
raptor_rdfxml_state_as_string(state));
#endif
}
} /* end while */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
return;
oom:
raptor_parser_fatal_error(rdf_parser, "Out of memory, skipping");
element->state = RAPTOR_STATE_SKIPPING;
}
static void
raptor_rdfxml_end_element_grammar(raptor_parser *rdf_parser,
raptor_rdfxml_element *element)
{
raptor_rdfxml_parser *rdf_xml_parser;
raptor_state state;
int finished;
raptor_xml_element* xml_element = element->xml_element;
raptor_qname* el_qname;
const unsigned char *el_name;
int element_in_rdf_ns;
raptor_uri* element_name_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
el_qname = raptor_xml_element_get_name(xml_element);
el_name = el_qname->local_name;
element_in_rdf_ns= (el_qname->nspace && el_qname->nspace->is_rdf_ms);
element_name_uri = el_qname->uri;
state = element->state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Starting in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
finished= 0;
while(!finished) {
switch(state) {
case RAPTOR_STATE_SKIPPING:
finished = 1;
break;
case RAPTOR_STATE_UNKNOWN:
finished = 1;
break;
case RAPTOR_STATE_NODE_ELEMENT_LIST:
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_RDF_URI(rdf_parser->world))) {
/* end of RDF - boo hoo */
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
}
/* When scanning, another element ending is outside the RDF
* world so this can happen without further work
*/
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING)) {
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
}
/* otherwise found some junk after RDF content in an RDF-only
* document (probably never get here since this would be
* a mismatched XML tag and cause an error earlier)
*/
raptor_rdfxml_update_document_locator(rdf_parser);
raptor_parser_warning(rdf_parser,
"Element '%s' ended, expected end of RDF element",
el_name);
state = RAPTOR_STATE_UNKNOWN;
finished = 1;
break;
case RAPTOR_STATE_DESCRIPTION:
case RAPTOR_STATE_NODE_ELEMENT:
case RAPTOR_STATE_PARSETYPE_RESOURCE:
/* If there is a parent element containing this element and
* the parent isn't a description, has an identifier,
* create the statement between this node using parent property
* (Need to check for identifier so that top-level typed nodes
* don't get connect to <rdf:RDF> parent element)
*/
if(state == RAPTOR_STATE_NODE_ELEMENT &&
element->parent && element->parent->subject) {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
element->subject,
NULL,
element);
} else if(state == RAPTOR_STATE_PARSETYPE_RESOURCE &&
element->parent && element->parent->subject) {
/* Handle rdf:li as the rdf:parseType="resource" property */
if(element_in_rdf_ns &&
raptor_uri_equals(element_name_uri,
RAPTOR_RDF_li_URI(rdf_parser->world))) {
raptor_uri* ordinal_predicate_uri;
element->parent->last_ordinal++;
ordinal_predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world, element->parent->last_ordinal);
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
ordinal_predicate_uri,
element->subject,
element->reified,
element->parent);
raptor_free_uri(ordinal_predicate_uri);
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
element->subject,
element->reified,
element->parent);
}
}
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_COLLECTION:
finished = 1;
break;
case RAPTOR_STATE_PARSETYPE_OTHER:
/* FALLTHROUGH */
case RAPTOR_STATE_PARSETYPE_LITERAL:
element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL;
raptor_xml_writer_end_element(rdf_xml_parser->xml_writer, xml_element);
finished = 1;
break;
case RAPTOR_STATE_PROPERTYELT:
case RAPTOR_STATE_MEMBER_PROPERTYELT:
/* A property element
* http://www.w3.org/TR/rdf-syntax-grammar/#propertyElt
*
* Literal content part is handled here.
* The element content is handled in the internal states
* Empty content is checked here.
*/
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT) {
if(xml_element->content_cdata_seen)
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
else if(xml_element->content_element_seen)
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES;
else {
/* Empty Literal */
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
}
}
/* Handle terminating a rdf:parseType="Collection" list */
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION ||
element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_term* nil_term;
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) {
raptor_uri* nil_uri = RAPTOR_DAML_nil_URI(rdf_xml_parser);
nil_term = raptor_new_term_from_uri(rdf_parser->world, nil_uri);
} else {
nil_term = raptor_term_copy(RAPTOR_RDF_nil_term(rdf_parser->world));
}
if(!element->tail_id) {
/* If No List: set object of statement to rdf:nil */
element->object = raptor_term_copy(nil_term);
} else {
raptor_uri* rest_uri = NULL;
raptor_term* tail_id_term;
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION)
rest_uri = RAPTOR_DAML_rest_URI(rdf_xml_parser);
else
rest_uri = RAPTOR_RDF_rest_URI(rdf_parser->world);
tail_id_term = raptor_new_term_from_blank(rdf_parser->world,
element->tail_id);
/* terminate the list */
raptor_rdfxml_generate_statement(rdf_parser,
tail_id_term,
rest_uri,
nil_term,
NULL,
NULL);
raptor_free_term(tail_id_term);
}
raptor_free_term(nil_term);
} /* end rdf:parseType="Collection" termination */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
switch(element->content_type) {
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE:
if(raptor_rdfxml_element_has_property_attributes(element) &&
element->child_state == RAPTOR_STATE_DESCRIPTION) {
raptor_parser_error(rdf_parser,
"Property element '%s' has both property attributes and a node element content",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(!element->object) {
if(element->rdf_attr[RDF_NS_resource]) {
raptor_uri* resource_uri;
resource_uri = raptor_new_uri_relative_to_base(rdf_parser->world,
raptor_rdfxml_inscope_base_uri(rdf_parser),
(const unsigned char*)element->rdf_attr[RDF_NS_resource]);
if(!resource_uri)
goto oom;
element->object = raptor_new_term_from_uri(rdf_parser->world,
resource_uri);
raptor_free_uri(resource_uri);
RAPTOR_FREE(char*, element->rdf_attr[RDF_NS_resource]);
element->rdf_attr[RDF_NS_resource] = NULL;
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
} else if(element->rdf_attr[RDF_NS_nodeID]) {
unsigned char* resource_id;
resource_id = raptor_world_internal_generate_id(rdf_parser->world,
(unsigned char*)element->rdf_attr[RDF_NS_nodeID]);
if(!resource_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
resource_id);
RAPTOR_FREE(char*, resource_id);
element->rdf_attr[RDF_NS_nodeID] = NULL;
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
if(!raptor_valid_xml_ID(rdf_parser,
element->object->value.blank.string)) {
raptor_parser_error(rdf_parser, "Illegal rdf:nodeID value '%s'", (const char*)element->object->value.blank.string);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
} else {
unsigned char* resource_id;
resource_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!resource_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
resource_id);
RAPTOR_FREE(char*, resource_id);
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element->parent,
element->object))
goto oom;
}
/* We know object is a resource, so delete any unsignficant
* whitespace so that FALLTHROUGH code below finds the object.
*/
if(xml_element->content_cdata_length) {
raptor_free_stringbuffer(xml_element->content_cdata_sb);
xml_element->content_cdata_sb = NULL;
xml_element->content_cdata_length = 0;
}
/* FALLTHROUGH */
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL:
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL) {
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_BAGID)) {
/* Only an empty literal can have a rdf:bagID */
if(element->bag) {
if(xml_element->content_cdata_length > 0) {
raptor_parser_error(rdf_parser,
"rdf:bagID is forbidden on a literal property element '%s'.",
el_name);
/* prevent this being used later either */
element->rdf_attr[RDF_NS_bagID] = NULL;
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->bag,
RAPTOR_RDF_type_URI(rdf_parser->world),
RAPTOR_RDF_Bag_term(rdf_parser->world),
NULL,
NULL);
}
}
} /* if rdf:bagID */
/* If there is empty literal content with properties
* generate a node to hang properties off
*/
if(raptor_rdfxml_element_has_property_attributes(element) &&
xml_element->content_cdata_length > 0) {
raptor_parser_error(rdf_parser,
"Literal property element '%s' has property attributes",
el_name);
state = RAPTOR_STATE_SKIPPING;
element->child_state = RAPTOR_STATE_SKIPPING;
break;
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL &&
raptor_rdfxml_element_has_property_attributes(element) &&
!element->object) {
unsigned char* object_id;
object_id = raptor_world_generate_bnodeid(rdf_parser->world);
if(!object_id)
goto oom;
element->object = raptor_new_term_from_blank(rdf_parser->world,
object_id);
RAPTOR_FREE(char*, object_id);
if(!element->object)
goto oom;
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE;
}
if(raptor_rdfxml_process_property_attributes(rdf_parser, element,
element,
element->object))
goto oom;
}
/* just be friendly to older compilers and don't declare
* variables in the middle of a block
*/
if(1) {
raptor_uri *predicate_uri = NULL;
int predicate_ordinal = -1;
raptor_term* object_term = NULL;
if(state == RAPTOR_STATE_MEMBER_PROPERTYELT) {
predicate_ordinal = ++element->parent->last_ordinal;
predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world,
predicate_ordinal);
} else {
predicate_uri = element_name_uri;
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL) {
unsigned char* literal = NULL;
raptor_uri* literal_datatype;
unsigned char* literal_language = NULL;
/* an empty stringbuffer - empty CDATA - is OK */
if(raptor_stringbuffer_length(xml_element->content_cdata_sb)) {
literal = raptor_stringbuffer_as_string(xml_element->content_cdata_sb);
if(!literal)
goto oom;
}
literal_datatype = element->object_literal_datatype;
if(!literal_datatype)
literal_language = (unsigned char*)raptor_sax2_inscope_xml_language(rdf_xml_parser->sax2);
if(!literal_datatype && literal &&
!raptor_unicode_check_utf8_nfc_string(literal,
xml_element->content_cdata_length,
NULL)) {
const char *message;
message = "Property element '%s' has a string not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, el_name, literal);
else
raptor_parser_warning(rdf_parser, message, el_name, literal);
}
object_term = raptor_new_term_from_literal(rdf_parser->world,
literal,
literal_datatype,
literal_language);
} else {
object_term = raptor_term_copy(element->object);
}
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
predicate_uri,
object_term,
element->reified,
element->parent);
if(predicate_ordinal >= 0)
raptor_free_uri(predicate_uri);
raptor_free_term(object_term);
}
break;
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL:
{
unsigned char *buffer;
size_t length;
raptor_term* xmlliteral_term = NULL;
if(rdf_xml_parser->xml_writer) {
raptor_xml_writer_flush(rdf_xml_parser->xml_writer);
raptor_free_iostream(rdf_xml_parser->iostream);
rdf_xml_parser->iostream = NULL;
buffer = (unsigned char*)rdf_xml_parser->xml_content;
length = rdf_xml_parser->xml_content_length;
} else {
buffer = raptor_stringbuffer_as_string(xml_element->content_cdata_sb);
length = xml_element->content_cdata_length;
}
if(!raptor_unicode_check_utf8_nfc_string(buffer, length, NULL)) {
const char *message;
message = "Property element '%s' has XML literal content not in Unicode Normal Form C: %s";
raptor_rdfxml_update_document_locator(rdf_parser);
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NON_NFC_FATAL))
raptor_parser_error(rdf_parser, message, el_name, buffer);
else
raptor_parser_warning(rdf_parser, message, el_name, buffer);
}
xmlliteral_term = raptor_new_term_from_literal(rdf_parser->world,
buffer,
RAPTOR_RDF_XMLLiteral_URI(rdf_parser->world),
NULL);
if(state == RAPTOR_STATE_MEMBER_PROPERTYELT) {
raptor_uri* predicate_uri;
element->parent->last_ordinal++;
predicate_uri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world, element->parent->last_ordinal);
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
predicate_uri,
xmlliteral_term,
element->reified,
element->parent);
raptor_free_uri(predicate_uri);
} else {
raptor_rdfxml_generate_statement(rdf_parser,
element->parent->subject,
element_name_uri,
xmlliteral_term,
element->reified,
element->parent);
}
raptor_free_term(xmlliteral_term);
/* Finish the xml writer iostream for parseType="Literal" */
if(rdf_xml_parser->xml_writer) {
raptor_free_xml_writer(rdf_xml_parser->xml_writer);
RAPTOR_FREE(char*, rdf_xml_parser->xml_content);
rdf_xml_parser->xml_content = NULL;
rdf_xml_parser->xml_content_length = 0;
}
}
break;
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_NODES:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN:
case RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LAST:
default:
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error in state RAPTOR_STATE_PROPERTYELT - got unexpected content type %s (%d)",
__func__,
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
} /* end switch */
finished = 1;
break;
case RAPTOR_STATE_INVALID:
default:
raptor_parser_fatal_error(rdf_parser,
"%s: Internal error - unexpected parser state %d - %s",
__func__,
state,
raptor_rdfxml_state_as_string(state));
finished = 1;
} /* end switch */
if(state != element->state) {
element->state = state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Moved to state %d - %s\n", state,
raptor_rdfxml_state_as_string(state));
#endif
}
} /* end while */
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
return;
oom:
raptor_parser_fatal_error(rdf_parser, "Out of memory, skipping");
element->state = RAPTOR_STATE_SKIPPING;
}
static void
raptor_rdfxml_cdata_grammar(raptor_parser *rdf_parser,
const unsigned char *s, int len,
int is_cdata)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_rdfxml_element* element;
raptor_xml_element* xml_element;
raptor_state state;
int all_whitespace = 1;
int i;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(rdf_parser->failed)
return;
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG2("Adding characters (is_cdata=%d): '", is_cdata);
(void)fwrite(s, 1, len, stderr);
fprintf(stderr, "' (%d bytes)\n", len);
#endif
for(i = 0; i < len; i++)
if(!isspace(s[i])) {
all_whitespace = 0;
break;
}
element = rdf_xml_parser->current_element;
/* this file is very broke - probably not XML, whatever */
if(!element)
return;
xml_element = element->xml_element;
raptor_rdfxml_update_document_locator(rdf_parser);
/* cdata never changes the parser state
* and the containing element state always determines what to do.
* Use the child_state first if there is one, since that applies
*/
state = element->child_state;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Working in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
if(state == RAPTOR_STATE_SKIPPING)
return;
if(state == RAPTOR_STATE_UNKNOWN) {
/* Ignore all cdata if still looking for RDF */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_SCANNING))
return;
/* Ignore all whitespace cdata before first element */
if(all_whitespace)
return;
/* This probably will never happen since that would make the
* XML not be well-formed
*/
raptor_parser_warning(rdf_parser, "Character data before RDF element.");
}
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES) {
/* If found non-whitespace content, move to literal content */
if(!all_whitespace)
element->child_content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
}
if(!rdf_content_type_info[element->child_content_type].whitespace_significant) {
/* Whitespace is ignored except for literal or preserved content types */
if(all_whitespace) {
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG2("Ignoring whitespace cdata inside element '%s'\n",
raptor_xml_element_get_name(element->parent->xml_element)->local_name);
#endif
return;
}
if(xml_element->content_cdata_seen && xml_element->content_element_seen) {
raptor_qname* parent_el_name;
parent_el_name = raptor_xml_element_get_name(element->parent->xml_element);
/* Uh oh - mixed content, this element has elements too */
raptor_parser_warning(rdf_parser, "element '%s' has mixed content.",
parent_el_name->local_name);
}
}
if(element->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTY_CONTENT) {
element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_LITERAL;
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG3("Content type changed to %s (%d)\n",
raptor_rdfxml_element_content_type_as_string(element->content_type),
element->content_type);
#endif
}
if(element->child_content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_XML_LITERAL)
raptor_xml_writer_cdata_counted(rdf_xml_parser->xml_writer, s, len);
else {
raptor_stringbuffer_append_counted_string(xml_element->content_cdata_sb,
s, len, 1);
element->content_cdata_all_whitespace &= all_whitespace;
/* adjust stored length */
xml_element->content_cdata_length += len;
}
#ifdef RAPTOR_DEBUG_CDATA
RAPTOR_DEBUG3("Content cdata now: %d bytes\n",
xml_element->content_cdata_length);
#endif
#ifdef RAPTOR_DEBUG_VERBOSE
RAPTOR_DEBUG2("Ending in state %s\n", raptor_rdfxml_state_as_string(state));
#endif
}
/**
* raptor_rdfxml_inscope_base_uri:
* @rdf_parser: Raptor parser object
*
* Return the in-scope base URI.
*
* Looks for the innermost xml:base on an element or document URI
*
* Return value: The URI string value or NULL on failure.
**/
static raptor_uri*
raptor_rdfxml_inscope_base_uri(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser* rdf_xml_parser;
raptor_uri* base_uri;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
base_uri = raptor_sax2_inscope_base_uri(rdf_xml_parser->sax2);
if(!base_uri)
base_uri = rdf_parser->base_uri;
return base_uri;
}
/**
* raptor_rdfxml_record_ID:
* @rdf_parser: Raptor parser object
* @element: Current element
* @id: ID string
*
* Record an rdf:ID / rdf:bagID value (with xml base) and check it hasn't been seen already.
*
* Record and check the ID values, if they have been seen already.
* per in-scope-base URI.
*
* Return value: non-zero if already seen, or failure
**/
static int
raptor_rdfxml_record_ID(raptor_parser *rdf_parser,
raptor_rdfxml_element *element,
const unsigned char *id)
{
raptor_rdfxml_parser *rdf_xml_parser;
raptor_uri* base_uri;
size_t id_len;
int rc;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
if(!RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID))
return 0;
base_uri = raptor_rdfxml_inscope_base_uri(rdf_parser);
id_len = strlen((const char*)id);
rc = raptor_id_set_add(rdf_xml_parser->id_set, base_uri, id, id_len);
return (rc != 0);
}
static void
raptor_rdfxml_update_document_locator(raptor_parser *rdf_parser)
{
raptor_rdfxml_parser *rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
raptor_sax2_update_document_locator(rdf_xml_parser->sax2,
&rdf_parser->locator);
}
static void
raptor_rdfxml_parse_finish_factory(raptor_parser_factory* factory)
{
}
static const char* const rdfxml_names[3] = { "rdfxml", "raptor", NULL};
static const char* const rdfxml_uri_strings[3] = {
"http://www.w3.org/ns/formats/RDF_XML",
"http://www.w3.org/TR/rdf-syntax-grammar",
NULL
};
#define RDFXML_TYPES_COUNT 2
static const raptor_type_q rdfxml_types[RDFXML_TYPES_COUNT + 1] = {
{ "application/rdf+xml", 19, 10},
{ "text/rdf", 8, 6},
{ NULL, 0, 0}
};
static int
raptor_rdfxml_parser_register_factory(raptor_parser_factory *factory)
{
int rc = 0;
factory->desc.names = rdfxml_names;
factory->desc.mime_types = rdfxml_types;
factory->desc.label = "RDF/XML";
factory->desc.uri_strings = rdfxml_uri_strings;
factory->desc.flags = RAPTOR_SYNTAX_NEED_BASE_URI;
factory->context_length = sizeof(raptor_rdfxml_parser);
factory->init = raptor_rdfxml_parse_init;
factory->terminate = raptor_rdfxml_parse_terminate;
factory->start = raptor_rdfxml_parse_start;
factory->chunk = raptor_rdfxml_parse_chunk;
factory->finish_factory = raptor_rdfxml_parse_finish_factory;
factory->recognise_syntax = raptor_rdfxml_parse_recognise_syntax;
return rc;
}
int
raptor_init_parser_rdfxml(raptor_world* world)
{
return !raptor_world_register_parser_factory(world,
&raptor_rdfxml_parser_register_factory);
}
#if defined(RAPTOR_DEBUG) && RAPTOR_DEBUG > 1
void
raptor_rdfxml_parser_stats_print(raptor_rdfxml_parser* rdf_xml_parser,
FILE *stream)
{
fputs("rdf:ID set ", stream);
raptor_id_set_stats_print(rdf_xml_parser->id_set, stream);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_3568_8 |
crossvul-cpp_data_good_837_0 | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
* Written by Alex Tomas <alex@clusterfs.com>
*
* Architecture independence:
* Copyright (c) 2005, Bull S.A.
* Written by Pierre Peiffer <pierre.peiffer@bull.net>
*/
/*
* Extents support for EXT4
*
* TODO:
* - ext4*_error() should be used in some situations
* - analyze all BUG()/BUG_ON(), use -EIO where appropriate
* - smart tree reduction
*/
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/jbd2.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/fiemap.h>
#include <linux/backing-dev.h>
#include "ext4_jbd2.h"
#include "ext4_extents.h"
#include "xattr.h"
#include <trace/events/ext4.h>
/*
* used by extent splitting.
*/
#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
due to ENOSPC */
#define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
#define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
#define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
#define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
static __le32 ext4_extent_block_csum(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
EXT4_EXTENT_TAIL_OFFSET(eh));
return cpu_to_le32(csum);
}
static int ext4_extent_block_csum_verify(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
et = find_ext4_extent_tail(eh);
if (et->et_checksum != ext4_extent_block_csum(inode, eh))
return 0;
return 1;
}
static void ext4_extent_block_csum_set(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
et = find_ext4_extent_tail(eh);
et->et_checksum = ext4_extent_block_csum(inode, eh);
}
static int ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags);
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags);
static int ext4_find_delayed_extent(struct inode *inode,
struct extent_status *newes);
static int ext4_ext_truncate_extend_restart(handle_t *handle,
struct inode *inode,
int needed)
{
int err;
if (!ext4_handle_valid(handle))
return 0;
if (handle->h_buffer_credits >= needed)
return 0;
/*
* If we need to extend the journal get a few extra blocks
* while we're at it for efficiency's sake.
*/
needed += 3;
err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
if (err <= 0)
return err;
err = ext4_truncate_restart_trans(handle, inode, needed);
if (err == 0)
err = -EAGAIN;
return err;
}
/*
* could return:
* - EROFS
* - ENOMEM
*/
static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
if (path->p_bh) {
/* path points to block */
BUFFER_TRACE(path->p_bh, "get_write_access");
return ext4_journal_get_write_access(handle, path->p_bh);
}
/* path points to leaf/index in inode body */
/* we use in-core data, no need to protect them */
return 0;
}
/*
* could return:
* - EROFS
* - ENOMEM
* - EIO
*/
int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
struct inode *inode, struct ext4_ext_path *path)
{
int err;
WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
if (path->p_bh) {
ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
/* path points to block */
err = __ext4_handle_dirty_metadata(where, line, handle,
inode, path->p_bh);
} else {
/* path points to leaf/index in inode body */
err = ext4_mark_inode_dirty(handle, inode);
}
return err;
}
static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t block)
{
if (path) {
int depth = path->p_depth;
struct ext4_extent *ex;
/*
* Try to predict block placement assuming that we are
* filling in a file which will eventually be
* non-sparse --- i.e., in the case of libbfd writing
* an ELF object sections out-of-order but in a way
* the eventually results in a contiguous object or
* executable file, or some database extending a table
* space file. However, this is actually somewhat
* non-ideal if we are writing a sparse file such as
* qemu or KVM writing a raw image file that is going
* to stay fairly sparse, since it will end up
* fragmenting the file system's free space. Maybe we
* should have some hueristics or some way to allow
* userspace to pass a hint to file system,
* especially if the latter case turns out to be
* common.
*/
ex = path[depth].p_ext;
if (ex) {
ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
if (block > ext_block)
return ext_pblk + (block - ext_block);
else
return ext_pblk - (ext_block - block);
}
/* it looks like index is empty;
* try to find starting block from index itself */
if (path[depth].p_bh)
return path[depth].p_bh->b_blocknr;
}
/* OK. use inode's group */
return ext4_inode_to_goal_block(inode);
}
/*
* Allocation for a meta data block
*/
static ext4_fsblk_t
ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex, int *err, unsigned int flags)
{
ext4_fsblk_t goal, newblock;
goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, err);
return newblock;
}
static inline int ext4_ext_space_block(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 6)
size = 6;
#endif
return size;
}
static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 5)
size = 5;
#endif
return size;
}
static inline int ext4_ext_space_root(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 3)
size = 3;
#endif
return size;
}
static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 4)
size = 4;
#endif
return size;
}
static inline int
ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath, ext4_lblk_t lblk,
int nofail)
{
struct ext4_ext_path *path = *ppath;
int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
(nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
}
/*
* Calculate the number of metadata blocks needed
* to allocate @blocks
* Worse case is one block per extent
*/
int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
{
struct ext4_inode_info *ei = EXT4_I(inode);
int idxs;
idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent_idx));
/*
* If the new delayed allocation block is contiguous with the
* previous da block, it can share index blocks with the
* previous block, so we only need to allocate a new index
* block every idxs leaf blocks. At ldxs**2 blocks, we need
* an additional index block, and at ldxs**3 blocks, yet
* another index blocks.
*/
if (ei->i_da_metadata_calc_len &&
ei->i_da_metadata_calc_last_lblock+1 == lblock) {
int num = 0;
if ((ei->i_da_metadata_calc_len % idxs) == 0)
num++;
if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
num++;
if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
num++;
ei->i_da_metadata_calc_len = 0;
} else
ei->i_da_metadata_calc_len++;
ei->i_da_metadata_calc_last_lblock++;
return num;
}
/*
* In the worst case we need a new set of index blocks at
* every level of the inode's extent tree.
*/
ei->i_da_metadata_calc_len = 1;
ei->i_da_metadata_calc_last_lblock = lblock;
return ext_depth(inode) + 1;
}
static int
ext4_ext_max_entries(struct inode *inode, int depth)
{
int max;
if (depth == ext_depth(inode)) {
if (depth == 0)
max = ext4_ext_space_root(inode, 1);
else
max = ext4_ext_space_root_idx(inode, 1);
} else {
if (depth == 0)
max = ext4_ext_space_block(inode, 1);
else
max = ext4_ext_space_block_idx(inode, 1);
}
return max;
}
static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
{
ext4_fsblk_t block = ext4_ext_pblock(ext);
int len = ext4_ext_get_actual_len(ext);
ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
/*
* We allow neither:
* - zero length
* - overflow/wrap-around
*/
if (lblock + len <= lblock)
return 0;
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
}
static int ext4_valid_extent_idx(struct inode *inode,
struct ext4_extent_idx *ext_idx)
{
ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
}
static int ext4_valid_extent_entries(struct inode *inode,
struct ext4_extent_header *eh,
int depth)
{
unsigned short entries;
if (eh->eh_entries == 0)
return 1;
entries = le16_to_cpu(eh->eh_entries);
if (depth == 0) {
/* leaf entries */
struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
ext4_fsblk_t pblock = 0;
ext4_lblk_t lblock = 0;
ext4_lblk_t prev = 0;
int len = 0;
while (entries) {
if (!ext4_valid_extent(inode, ext))
return 0;
/* Check for overlapping extents */
lblock = le32_to_cpu(ext->ee_block);
len = ext4_ext_get_actual_len(ext);
if ((lblock <= prev) && prev) {
pblock = ext4_ext_pblock(ext);
es->s_last_error_block = cpu_to_le64(pblock);
return 0;
}
ext++;
entries--;
prev = lblock + len - 1;
}
} else {
struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
while (entries) {
if (!ext4_valid_extent_idx(inode, ext_idx))
return 0;
ext_idx++;
entries--;
}
}
return 1;
}
static int __ext4_ext_check(const char *function, unsigned int line,
struct inode *inode, struct ext4_extent_header *eh,
int depth, ext4_fsblk_t pblk)
{
const char *error_msg;
int max = 0, err = -EFSCORRUPTED;
if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
error_msg = "invalid magic";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
error_msg = "unexpected eh_depth";
goto corrupted;
}
if (unlikely(eh->eh_max == 0)) {
error_msg = "invalid eh_max";
goto corrupted;
}
max = ext4_ext_max_entries(inode, depth);
if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
error_msg = "too large eh_max";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
error_msg = "invalid eh_entries";
goto corrupted;
}
if (!ext4_valid_extent_entries(inode, eh, depth)) {
error_msg = "invalid extent entries";
goto corrupted;
}
if (unlikely(depth > 32)) {
error_msg = "too large eh_depth";
goto corrupted;
}
/* Verify checksum on non-root extent tree nodes */
if (ext_depth(inode) != depth &&
!ext4_extent_block_csum_verify(inode, eh)) {
error_msg = "extent tree corrupted";
err = -EFSBADCRC;
goto corrupted;
}
return 0;
corrupted:
ext4_error_inode(inode, function, line, 0,
"pblk %llu bad header/extent: %s - magic %x, "
"entries %u, max %u(%u), depth %u(%u)",
(unsigned long long) pblk, error_msg,
le16_to_cpu(eh->eh_magic),
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
max, le16_to_cpu(eh->eh_depth), depth);
return err;
}
#define ext4_ext_check(inode, eh, depth, pblk) \
__ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
int ext4_ext_check_inode(struct inode *inode)
{
return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
}
static struct buffer_head *
__read_extent_tree_block(const char *function, unsigned int line,
struct inode *inode, ext4_fsblk_t pblk, int depth,
int flags)
{
struct buffer_head *bh;
int err;
bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return ERR_PTR(-ENOMEM);
if (!bh_uptodate_or_lock(bh)) {
trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
err = bh_submit_read(bh);
if (err < 0)
goto errout;
}
if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
return bh;
err = __ext4_ext_check(function, line, inode,
ext_block_hdr(bh), depth, pblk);
if (err)
goto errout;
set_buffer_verified(bh);
/*
* If this is a leaf block, cache all of its entries
*/
if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
struct ext4_extent_header *eh = ext_block_hdr(bh);
struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
ext4_lblk_t prev = 0;
int i;
for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
unsigned int status = EXTENT_STATUS_WRITTEN;
ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
int len = ext4_ext_get_actual_len(ex);
if (prev && (prev != lblk))
ext4_es_cache_extent(inode, prev,
lblk - prev, ~0,
EXTENT_STATUS_HOLE);
if (ext4_ext_is_unwritten(ex))
status = EXTENT_STATUS_UNWRITTEN;
ext4_es_cache_extent(inode, lblk, len,
ext4_ext_pblock(ex), status);
prev = lblk + len;
}
}
return bh;
errout:
put_bh(bh);
return ERR_PTR(err);
}
#define read_extent_tree_block(inode, pblk, depth, flags) \
__read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
(depth), (flags))
/*
* This function is called to cache a file's extent information in the
* extent status tree
*/
int ext4_ext_precache(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_ext_path *path = NULL;
struct buffer_head *bh;
int i = 0, depth, ret = 0;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return 0; /* not an extent-mapped inode */
down_read(&ei->i_data_sem);
depth = ext_depth(inode);
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (path == NULL) {
up_read(&ei->i_data_sem);
return -ENOMEM;
}
/* Don't cache anything if there are no external extent blocks */
if (depth == 0)
goto out;
path[0].p_hdr = ext_inode_hdr(inode);
ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
if (ret)
goto out;
path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
while (i >= 0) {
/*
* If this is a leaf block or we've reached the end of
* the index block, go up
*/
if ((i == depth) ||
path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
bh = read_extent_tree_block(inode,
ext4_idx_pblock(path[i].p_idx++),
depth - i - 1,
EXT4_EX_FORCE_CACHE);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
break;
}
i++;
path[i].p_bh = bh;
path[i].p_hdr = ext_block_hdr(bh);
path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
}
ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
out:
up_read(&ei->i_data_sem);
ext4_ext_drop_refs(path);
kfree(path);
return ret;
}
#ifdef EXT_DEBUG
static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
{
int k, l = path->p_depth;
ext_debug("path:");
for (k = 0; k <= l; k++, path++) {
if (path->p_idx) {
ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
} else if (path->p_ext) {
ext_debug(" %d:[%d]%d:%llu ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext),
ext4_ext_pblock(path->p_ext));
} else
ext_debug(" []");
}
ext_debug("\n");
}
static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
{
int depth = ext_depth(inode);
struct ext4_extent_header *eh;
struct ext4_extent *ex;
int i;
if (!path)
return;
eh = path[depth].p_hdr;
ex = EXT_FIRST_EXTENT(eh);
ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
}
ext_debug("\n");
}
static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
ext4_fsblk_t newblock, int level)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
if (depth != level) {
struct ext4_extent_idx *idx;
idx = path[level].p_idx;
while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
ext_debug("%d: move %d:%llu in new index %llu\n", level,
le32_to_cpu(idx->ei_block),
ext4_idx_pblock(idx),
newblock);
idx++;
}
return;
}
ex = path[depth].p_ext;
while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
le32_to_cpu(ex->ee_block),
ext4_ext_pblock(ex),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
newblock);
ex++;
}
}
#else
#define ext4_ext_show_path(inode, path)
#define ext4_ext_show_leaf(inode, path)
#define ext4_ext_show_move(inode, path, newblock, level)
#endif
void ext4_ext_drop_refs(struct ext4_ext_path *path)
{
int depth, i;
if (!path)
return;
depth = path->p_depth;
for (i = 0; i <= depth; i++, path++)
if (path->p_bh) {
brelse(path->p_bh);
path->p_bh = NULL;
}
}
/*
* ext4_ext_binsearch_idx:
* binary search for the closest index of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch_idx(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent_idx *r, *l, *m;
ext_debug("binsearch for %u(idx): ", block);
l = EXT_FIRST_INDEX(eh) + 1;
r = EXT_LAST_INDEX(eh);
while (l <= r) {
m = l + (r - l) / 2;
if (block < le32_to_cpu(m->ei_block))
r = m - 1;
else
l = m + 1;
ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
m, le32_to_cpu(m->ei_block),
r, le32_to_cpu(r->ei_block));
}
path->p_idx = l - 1;
ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent_idx *chix, *ix;
int k;
chix = ix = EXT_FIRST_INDEX(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
if (k != 0 &&
le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
printk(KERN_DEBUG "k=%d, ix=0x%p, "
"first=0x%p\n", k,
ix, EXT_FIRST_INDEX(eh));
printk(KERN_DEBUG "%u <= %u\n",
le32_to_cpu(ix->ei_block),
le32_to_cpu(ix[-1].ei_block));
}
BUG_ON(k && le32_to_cpu(ix->ei_block)
<= le32_to_cpu(ix[-1].ei_block));
if (block < le32_to_cpu(ix->ei_block))
break;
chix = ix;
}
BUG_ON(chix != path->p_idx);
}
#endif
}
/*
* ext4_ext_binsearch:
* binary search for closest extent of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent *r, *l, *m;
if (eh->eh_entries == 0) {
/*
* this leaf is empty:
* we get such a leaf in split/add case
*/
return;
}
ext_debug("binsearch for %u: ", block);
l = EXT_FIRST_EXTENT(eh) + 1;
r = EXT_LAST_EXTENT(eh);
while (l <= r) {
m = l + (r - l) / 2;
if (block < le32_to_cpu(m->ee_block))
r = m - 1;
else
l = m + 1;
ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
m, le32_to_cpu(m->ee_block),
r, le32_to_cpu(r->ee_block));
}
path->p_ext = l - 1;
ext_debug(" -> %d:%llu:[%d]%d ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_pblock(path->p_ext),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent *chex, *ex;
int k;
chex = ex = EXT_FIRST_EXTENT(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
BUG_ON(k && le32_to_cpu(ex->ee_block)
<= le32_to_cpu(ex[-1].ee_block));
if (block < le32_to_cpu(ex->ee_block))
break;
chex = ex;
}
BUG_ON(chex != path->p_ext);
}
#endif
}
int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
{
struct ext4_extent_header *eh;
eh = ext_inode_hdr(inode);
eh->eh_depth = 0;
eh->eh_entries = 0;
eh->eh_magic = EXT4_EXT_MAGIC;
eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
ext4_mark_inode_dirty(handle, inode);
return 0;
}
struct ext4_ext_path *
ext4_find_extent(struct inode *inode, ext4_lblk_t block,
struct ext4_ext_path **orig_path, int flags)
{
struct ext4_extent_header *eh;
struct buffer_head *bh;
struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
short int depth, i, ppos = 0;
int ret;
eh = ext_inode_hdr(inode);
depth = ext_depth(inode);
if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
depth);
ret = -EFSCORRUPTED;
goto err;
}
if (path) {
ext4_ext_drop_refs(path);
if (depth > path[0].p_maxdepth) {
kfree(path);
*orig_path = path = NULL;
}
}
if (!path) {
/* account possible depth increase */
path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (unlikely(!path))
return ERR_PTR(-ENOMEM);
path[0].p_maxdepth = depth + 1;
}
path[0].p_hdr = eh;
path[0].p_bh = NULL;
i = depth;
/* walk through the tree */
while (i) {
ext_debug("depth %d: num %d, max %d\n",
ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
ext4_ext_binsearch_idx(inode, path + ppos, block);
path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
flags);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
goto err;
}
eh = ext_block_hdr(bh);
ppos++;
path[ppos].p_bh = bh;
path[ppos].p_hdr = eh;
}
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
path[ppos].p_idx = NULL;
/* find extent */
ext4_ext_binsearch(inode, path + ppos, block);
/* if not an empty leaf */
if (path[ppos].p_ext)
path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
ext4_ext_show_path(inode, path);
return path;
err:
ext4_ext_drop_refs(path);
kfree(path);
if (orig_path)
*orig_path = NULL;
return ERR_PTR(ret);
}
/*
* ext4_ext_insert_index:
* insert new index [@logical;@ptr] into the block at @curp;
* check where to insert: before @curp or after @curp
*/
static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
struct ext4_ext_path *curp,
int logical, ext4_fsblk_t ptr)
{
struct ext4_extent_idx *ix;
int len, err;
err = ext4_ext_get_access(handle, inode, curp);
if (err)
return err;
if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
EXT4_ERROR_INODE(inode,
"logical %d == ei_block %d!",
logical, le32_to_cpu(curp->p_idx->ei_block));
return -EFSCORRUPTED;
}
if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
>= le16_to_cpu(curp->p_hdr->eh_max))) {
EXT4_ERROR_INODE(inode,
"eh_entries %d >= eh_max %d!",
le16_to_cpu(curp->p_hdr->eh_entries),
le16_to_cpu(curp->p_hdr->eh_max));
return -EFSCORRUPTED;
}
if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
/* insert after */
ext_debug("insert new index %d after: %llu\n", logical, ptr);
ix = curp->p_idx + 1;
} else {
/* insert before */
ext_debug("insert new index %d before: %llu\n", logical, ptr);
ix = curp->p_idx;
}
len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
BUG_ON(len < 0);
if (len > 0) {
ext_debug("insert new index %d: "
"move %d indices from 0x%p to 0x%p\n",
logical, len, ix, ix + 1);
memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
}
if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
return -EFSCORRUPTED;
}
ix->ei_block = cpu_to_le32(logical);
ext4_idx_store_pblock(ix, ptr);
le16_add_cpu(&curp->p_hdr->eh_entries, 1);
if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
return -EFSCORRUPTED;
}
err = ext4_ext_dirty(handle, inode, curp);
ext4_std_error(inode->i_sb, err);
return err;
}
/*
* ext4_ext_split:
* inserts new subtree into the path, using free index entry
* at depth @at:
* - allocates all needed blocks (new leaf and all intermediate index blocks)
* - makes decision where to split
* - moves remaining extents and index entries (right to the split point)
* into the newly allocated blocks
* - initializes subtree
*/
static int ext4_ext_split(handle_t *handle, struct inode *inode,
unsigned int flags,
struct ext4_ext_path *path,
struct ext4_extent *newext, int at)
{
struct buffer_head *bh = NULL;
int depth = ext_depth(inode);
struct ext4_extent_header *neh;
struct ext4_extent_idx *fidx;
int i = at, k, m, a;
ext4_fsblk_t newblock, oldblock;
__le32 border;
ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
int err = 0;
size_t ext_size = 0;
/* make decision: where to split? */
/* FIXME: now decision is simplest: at current extent */
/* if current leaf will be split, then we should use
* border from split point */
if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
return -EFSCORRUPTED;
}
if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
border = path[depth].p_ext[1].ee_block;
ext_debug("leaf will be split."
" next leaf starts at %d\n",
le32_to_cpu(border));
} else {
border = newext->ee_block;
ext_debug("leaf will be added."
" next leaf starts at %d\n",
le32_to_cpu(border));
}
/*
* If error occurs, then we break processing
* and mark filesystem read-only. index won't
* be inserted and tree will be in consistent
* state. Next mount will repair buffers too.
*/
/*
* Get array to track all allocated blocks.
* We need this to handle errors and free blocks
* upon them.
*/
ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
if (!ablocks)
return -ENOMEM;
/* allocate all needed blocks */
ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
for (a = 0; a < depth - at; a++) {
newblock = ext4_ext_new_meta_block(handle, inode, path,
newext, &err, flags);
if (newblock == 0)
goto cleanup;
ablocks[a] = newblock;
}
/* initialize new leaf */
newblock = ablocks[--a];
if (unlikely(newblock == 0)) {
EXT4_ERROR_INODE(inode, "newblock == 0!");
err = -EFSCORRUPTED;
goto cleanup;
}
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = 0;
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_depth = 0;
/* move remainder of path[depth] to the new leaf */
if (unlikely(path[depth].p_hdr->eh_entries !=
path[depth].p_hdr->eh_max)) {
EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
path[depth].p_hdr->eh_entries,
path[depth].p_hdr->eh_max);
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy from next extent */
m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
ext4_ext_show_move(inode, path, newblock, depth);
if (m) {
struct ext4_extent *ex;
ex = EXT_FIRST_EXTENT(neh);
memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old leaf */
if (m) {
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto cleanup;
}
/* create intermediate indexes */
k = depth - at - 1;
if (unlikely(k < 0)) {
EXT4_ERROR_INODE(inode, "k %d < 0!", k);
err = -EFSCORRUPTED;
goto cleanup;
}
if (k)
ext_debug("create %d intermediate indices\n", k);
/* insert new index into current index block */
/* current depth stored in i var */
i = depth - 1;
while (k--) {
oldblock = newblock;
newblock = ablocks[--a];
bh = sb_getblk(inode->i_sb, newblock);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = cpu_to_le16(1);
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
neh->eh_depth = cpu_to_le16(depth - i);
fidx = EXT_FIRST_INDEX(neh);
fidx->ei_block = border;
ext4_idx_store_pblock(fidx, oldblock);
ext_debug("int.index at %d (block %llu): %u -> %llu\n",
i, newblock, le32_to_cpu(border), oldblock);
/* move remainder of path[i] to the new index block */
if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
EXT_LAST_INDEX(path[i].p_hdr))) {
EXT4_ERROR_INODE(inode,
"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
le32_to_cpu(path[i].p_ext->ee_block));
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy indexes */
m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
EXT_MAX_INDEX(path[i].p_hdr));
ext4_ext_show_move(inode, path, newblock, i);
if (m) {
memmove(++fidx, path[i].p_idx,
sizeof(struct ext4_extent_idx) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
(sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
memset(bh->b_data + ext_size, 0,
inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old index */
if (m) {
err = ext4_ext_get_access(handle, inode, path + i);
if (err)
goto cleanup;
le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + i);
if (err)
goto cleanup;
}
i--;
}
/* insert new index */
err = ext4_ext_insert_index(handle, inode, path + at,
le32_to_cpu(border), newblock);
cleanup:
if (bh) {
if (buffer_locked(bh))
unlock_buffer(bh);
brelse(bh);
}
if (err) {
/* free all allocated blocks in error case */
for (i = 0; i < depth; i++) {
if (!ablocks[i])
continue;
ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
EXT4_FREE_BLOCKS_METADATA);
}
}
kfree(ablocks);
return err;
}
/*
* ext4_ext_grow_indepth:
* implements tree growing procedure:
* - allocates new block
* - moves top-level data (index block or leaf) into the new block
* - initializes new top-level, creating index that points to the
* just created block
*/
static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
unsigned int flags)
{
struct ext4_extent_header *neh;
struct buffer_head *bh;
ext4_fsblk_t newblock, goal = 0;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
int err = 0;
size_t ext_size = 0;
/* Try to prepend new index to old one */
if (ext_depth(inode))
goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
if (goal > le32_to_cpu(es->s_first_data_block)) {
flags |= EXT4_MB_HINT_TRY_GOAL;
goal--;
} else
goal = ext4_inode_to_goal_block(inode);
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, &err);
if (newblock == 0)
return err;
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return -ENOMEM;
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err) {
unlock_buffer(bh);
goto out;
}
ext_size = sizeof(EXT4_I(inode)->i_data);
/* move top-level index/leaf into new block */
memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
/* zero out unused area in the extent block */
memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
/* set size of new block */
neh = ext_block_hdr(bh);
/* old root could have indexes or leaves
* so calculate e_max right way */
if (ext_depth(inode))
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
else
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto out;
/* Update top-level index: num,max,pointer */
neh = ext_inode_hdr(inode);
neh->eh_entries = cpu_to_le16(1);
ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
if (neh->eh_depth == 0) {
/* Root extent block becomes index block */
neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
EXT_FIRST_INDEX(neh)->ei_block =
EXT_FIRST_EXTENT(neh)->ee_block;
}
ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
le16_add_cpu(&neh->eh_depth, 1);
ext4_mark_inode_dirty(handle, inode);
out:
brelse(bh);
return err;
}
/*
* ext4_ext_create_new_leaf:
* finds empty index and adds new leaf.
* if no free index is found, then it requests in-depth growing.
*/
static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
unsigned int mb_flags,
unsigned int gb_flags,
struct ext4_ext_path **ppath,
struct ext4_extent *newext)
{
struct ext4_ext_path *path = *ppath;
struct ext4_ext_path *curp;
int depth, i, err = 0;
repeat:
i = depth = ext_depth(inode);
/* walk up to the tree and look for free index entry */
curp = path + depth;
while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
i--;
curp--;
}
/* we use already allocated block for index block,
* so subsequent data blocks should be contiguous */
if (EXT_HAS_FREE_INDEX(curp)) {
/* if we found index with free entry, then use that
* entry: create all needed subtree and add new leaf */
err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path))
err = PTR_ERR(path);
} else {
/* tree is full, time to grow in depth */
err = ext4_ext_grow_indepth(handle, inode, mb_flags);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
/*
* only first (depth 0 -> 1) produces free space;
* in all other cases we have to split the grown tree
*/
depth = ext_depth(inode);
if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
/* now we need to split */
goto repeat;
}
}
out:
return err;
}
/*
* search the closest allocated block to the left for *logical
* and returns it at @logical + it's physical address at @phys
* if *logical is the smallest allocated block, the function
* returns 0 at @phys
* return value contains 0 (success) or error code
*/
static int ext4_ext_search_left(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys)
{
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
int depth, ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
*logical, le32_to_cpu(ex->ee_block));
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
depth);
return -EFSCORRUPTED;
}
}
return 0;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
*phys = ext4_ext_pblock(ex) + ee_len - 1;
return 0;
}
/*
* search the closest allocated block to the right for *logical
* and returns it at @logical + it's physical address at @phys
* if *logical is the largest allocated block, the function
* returns 0 at @phys
* return value contains 0 (success) or error code
*/
static int ext4_ext_search_right(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys,
struct ext4_extent **ret_ex)
{
struct buffer_head *bh = NULL;
struct ext4_extent_header *eh;
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
ext4_fsblk_t block;
int depth; /* Note, NOT eh_depth; depth from top of tree */
int ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"first_extent(path[%d].p_hdr) != ex",
depth);
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix != EXT_FIRST_INDEX *logical %d!",
*logical);
return -EFSCORRUPTED;
}
}
goto found_extent;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
/* next allocated block in this leaf */
ex++;
goto found_extent;
}
/* go up and search for index to the right */
while (--depth >= 0) {
ix = path[depth].p_idx;
if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
goto got_index;
}
/* we've gone up to the root and found no index to the right */
return 0;
got_index:
/* we've found index to the right, let's
* follow it and find the closest allocated
* block to the right */
ix++;
block = ext4_idx_pblock(ix);
while (++depth < path->p_depth) {
/* subtract from p_depth to get proper eh_depth */
bh = read_extent_tree_block(inode, block,
path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ix = EXT_FIRST_INDEX(eh);
block = ext4_idx_pblock(ix);
put_bh(bh);
}
bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ex = EXT_FIRST_EXTENT(eh);
found_extent:
*logical = le32_to_cpu(ex->ee_block);
*phys = ext4_ext_pblock(ex);
*ret_ex = ex;
if (bh)
put_bh(bh);
return 0;
}
/*
* ext4_ext_next_allocated_block:
* returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
* NOTE: it considers block number from index entry as
* allocated block. Thus, index entries have to be consistent
* with leaves.
*/
ext4_lblk_t
ext4_ext_next_allocated_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
if (depth == 0 && path->p_ext == NULL)
return EXT_MAX_BLOCKS;
while (depth >= 0) {
if (depth == path->p_depth) {
/* leaf */
if (path[depth].p_ext &&
path[depth].p_ext !=
EXT_LAST_EXTENT(path[depth].p_hdr))
return le32_to_cpu(path[depth].p_ext[1].ee_block);
} else {
/* index */
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return le32_to_cpu(path[depth].p_idx[1].ei_block);
}
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_next_leaf_block:
* returns first allocated block from next leaf or EXT_MAX_BLOCKS
*/
static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
/* zero-tree has no leaf blocks at all */
if (depth == 0)
return EXT_MAX_BLOCKS;
/* go to index block */
depth--;
while (depth >= 0) {
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return (ext4_lblk_t)
le32_to_cpu(path[depth].p_idx[1].ei_block);
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_correct_indexes:
* if leaf gets modified and modified extent is first in the leaf,
* then we have to correct all indexes above.
* TODO: do we need to correct tree in all cases?
*/
static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent_header *eh;
int depth = ext_depth(inode);
struct ext4_extent *ex;
__le32 border;
int k, err = 0;
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
if (unlikely(ex == NULL || eh == NULL)) {
EXT4_ERROR_INODE(inode,
"ex %p == NULL or eh %p == NULL", ex, eh);
return -EFSCORRUPTED;
}
if (depth == 0) {
/* there is no tree at all */
return 0;
}
if (ex != EXT_FIRST_EXTENT(eh)) {
/* we correct tree if first leaf got modified only */
return 0;
}
/*
* TODO: we need correction if border is smaller than current one
*/
k = depth - 1;
border = path[depth].p_ext->ee_block;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
return err;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
return err;
while (k--) {
/* change all left-side indexes */
if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
break;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
break;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
break;
}
return err;
}
int
ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
struct ext4_extent *ex2)
{
unsigned short ext1_ee_len, ext2_ee_len;
if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
return 0;
ext1_ee_len = ext4_ext_get_actual_len(ex1);
ext2_ee_len = ext4_ext_get_actual_len(ex2);
if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
le32_to_cpu(ex2->ee_block))
return 0;
/*
* To allow future support for preallocated extents to be added
* as an RO_COMPAT feature, refuse to merge to extents if
* this can result in the top bit of ee_len being set.
*/
if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
return 0;
/*
* The check for IO to unwritten extent is somewhat racy as we
* increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
* dropping i_data_sem. But reserved blocks should save us in that
* case.
*/
if (ext4_ext_is_unwritten(ex1) &&
(ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
atomic_read(&EXT4_I(inode)->i_unwritten) ||
(ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
return 0;
#ifdef AGGRESSIVE_TEST
if (ext1_ee_len >= 4)
return 0;
#endif
if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
return 1;
return 0;
}
/*
* This function tries to merge the "ex" extent to the next extent in the tree.
* It always tries to merge towards right. If you want to merge towards
* left, pass "ex - 1" as argument instead of "ex".
* Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
* 1 if they got merged.
*/
static int ext4_ext_try_to_merge_right(struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex)
{
struct ext4_extent_header *eh;
unsigned int depth, len;
int merge_done = 0, unwritten;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
while (ex < EXT_LAST_EXTENT(eh)) {
if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
break;
/* merge with next extent! */
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(ex + 1));
if (unwritten)
ext4_ext_mark_unwritten(ex);
if (ex + 1 < EXT_LAST_EXTENT(eh)) {
len = (EXT_LAST_EXTENT(eh) - ex - 1)
* sizeof(struct ext4_extent);
memmove(ex + 1, ex + 2, len);
}
le16_add_cpu(&eh->eh_entries, -1);
merge_done = 1;
WARN_ON(eh->eh_entries == 0);
if (!eh->eh_entries)
EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
}
return merge_done;
}
/*
* This function does a very simple check to see if we can collapse
* an extent tree with a single extent tree leaf block into the inode.
*/
static void ext4_ext_try_to_merge_up(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path)
{
size_t s;
unsigned max_root = ext4_ext_space_root(inode, 0);
ext4_fsblk_t blk;
if ((path[0].p_depth != 1) ||
(le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
(le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
return;
/*
* We need to modify the block allocation bitmap and the block
* group descriptor to release the extent tree block. If we
* can't get the journal credits, give up.
*/
if (ext4_journal_extend(handle, 2))
return;
/*
* Copy the extent data up to the inode
*/
blk = ext4_idx_pblock(path[0].p_idx);
s = le16_to_cpu(path[1].p_hdr->eh_entries) *
sizeof(struct ext4_extent_idx);
s += sizeof(struct ext4_extent_header);
path[1].p_maxdepth = path[0].p_maxdepth;
memcpy(path[0].p_hdr, path[1].p_hdr, s);
path[0].p_depth = 0;
path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
path[0].p_hdr->eh_max = cpu_to_le16(max_root);
brelse(path[1].p_bh);
ext4_free_blocks(handle, inode, NULL, blk, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
}
/*
* This function tries to merge the @ex extent to neighbours in the tree.
* return 1 if merge left else 0.
*/
static void ext4_ext_try_to_merge(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex) {
struct ext4_extent_header *eh;
unsigned int depth;
int merge_done = 0;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
if (ex > EXT_FIRST_EXTENT(eh))
merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
if (!merge_done)
(void) ext4_ext_try_to_merge_right(inode, path, ex);
ext4_ext_try_to_merge_up(handle, inode, path);
}
/*
* check if a portion of the "newext" extent overlaps with an
* existing extent.
*
* If there is an overlap discovered, it updates the length of the newext
* such that there will be no overlap, and then returns 1.
* If there is no overlap found, it returns 0.
*/
static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
struct inode *inode,
struct ext4_extent *newext,
struct ext4_ext_path *path)
{
ext4_lblk_t b1, b2;
unsigned int depth, len1;
unsigned int ret = 0;
b1 = le32_to_cpu(newext->ee_block);
len1 = ext4_ext_get_actual_len(newext);
depth = ext_depth(inode);
if (!path[depth].p_ext)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
/*
* get the next allocated block if the extent in the path
* is before the requested block(s)
*/
if (b2 < b1) {
b2 = ext4_ext_next_allocated_block(path);
if (b2 == EXT_MAX_BLOCKS)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, b2);
}
/* check for wrap through zero on extent logical start block*/
if (b1 + len1 < b1) {
len1 = EXT_MAX_BLOCKS - b1;
newext->ee_len = cpu_to_le16(len1);
ret = 1;
}
/* check for overlap */
if (b1 + len1 > b2) {
newext->ee_len = cpu_to_le16(b2 - b1);
ret = 1;
}
out:
return ret;
}
/*
* ext4_ext_insert_extent:
* tries to merge requsted extent into the existing extent or
* inserts requested extent as new one into the tree,
* creating new leaf in the no-space case.
*/
int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_extent *newext, int gb_flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
int mb_flags = 0, unwritten;
if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
mb_flags |= EXT4_MB_DELALLOC_RESERVED;
if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
return -EFSCORRUPTED;
}
depth = ext_depth(inode);
ex = path[depth].p_ext;
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* try to insert block into found extent and return */
if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
/*
* Try to see whether we should rather test the extent on
* right from ex, or from the left of ex. This is because
* ext4_find_extent() can return either extent on the
* left, or on the right from the searched position. This
* will make merging more effective.
*/
if (ex < EXT_LAST_EXTENT(eh) &&
(le32_to_cpu(ex->ee_block) +
ext4_ext_get_actual_len(ex) <
le32_to_cpu(newext->ee_block))) {
ex += 1;
goto prepend;
} else if ((ex > EXT_FIRST_EXTENT(eh)) &&
(le32_to_cpu(newext->ee_block) +
ext4_ext_get_actual_len(newext) <
le32_to_cpu(ex->ee_block)))
ex -= 1;
/* Try to append newex to the ex */
if (ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug("append [%d]%d block to %u:[%d]%d"
"(from %llu)\n",
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
prepend:
/* Try to prepend newex to the ex */
if (ext4_can_extents_be_merged(inode, newext, ex)) {
ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
"(from %llu)\n",
le32_to_cpu(newext->ee_block),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_block = newext->ee_block;
ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
}
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = EXT_MAX_BLOCKS;
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
next = ext4_ext_next_leaf_block(path);
if (next != EXT_MAX_BLOCKS) {
ext_debug("next leaf block - %u\n", next);
BUG_ON(npath != NULL);
npath = ext4_find_extent(inode, next, NULL, 0);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug("next leaf isn't full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto has_space;
}
ext_debug("next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
mb_flags |= EXT4_MB_USE_RESERVED;
err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
ppath, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext));
nearex = EXT_FIRST_EXTENT(eh);
} else {
if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* Insert after */
ext_debug("insert %u:%llu:[%d]%d before: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
nearex++;
} else {
/* Insert before */
BUG_ON(newext->ee_block == nearex->ee_block);
ext_debug("insert %u:%llu:[%d]%d after: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
}
len = EXT_LAST_EXTENT(eh) - nearex + 1;
if (len > 0) {
ext_debug("insert %u:%llu:[%d]%d: "
"move %d extents from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
len, nearex, nearex + 1);
memmove(nearex + 1, nearex,
len * sizeof(struct ext4_extent));
}
}
le16_add_cpu(&eh->eh_entries, 1);
path[depth].p_ext = nearex;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents */
if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, nearex);
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
cleanup:
ext4_ext_drop_refs(npath);
kfree(npath);
return err;
}
static int ext4_fill_fiemap_extents(struct inode *inode,
ext4_lblk_t block, ext4_lblk_t num,
struct fiemap_extent_info *fieinfo)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ex;
struct extent_status es;
ext4_lblk_t next, next_del, start = 0, end = 0;
ext4_lblk_t last = block + num;
int exists, depth = 0, err = 0;
unsigned int flags = 0;
unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
while (block < last && block != EXT_MAX_BLOCKS) {
num = last - block;
/* find extent for this block */
down_read(&EXT4_I(inode)->i_data_sem);
path = ext4_find_extent(inode, block, &path, 0);
if (IS_ERR(path)) {
up_read(&EXT4_I(inode)->i_data_sem);
err = PTR_ERR(path);
path = NULL;
break;
}
depth = ext_depth(inode);
if (unlikely(path[depth].p_hdr == NULL)) {
up_read(&EXT4_I(inode)->i_data_sem);
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
err = -EFSCORRUPTED;
break;
}
ex = path[depth].p_ext;
next = ext4_ext_next_allocated_block(path);
flags = 0;
exists = 0;
if (!ex) {
/* there is no extent yet, so try to allocate
* all requested space */
start = block;
end = block + num;
} else if (le32_to_cpu(ex->ee_block) > block) {
/* need to allocate space before found extent */
start = block;
end = le32_to_cpu(ex->ee_block);
if (block + num < end)
end = block + num;
} else if (block >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
/* need to allocate space after found extent */
start = block;
end = block + num;
if (end >= next)
end = next;
} else if (block >= le32_to_cpu(ex->ee_block)) {
/*
* some part of requested space is covered
* by found extent
*/
start = block;
end = le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex);
if (block + num < end)
end = block + num;
exists = 1;
} else {
BUG();
}
BUG_ON(end <= start);
if (!exists) {
es.es_lblk = start;
es.es_len = end - start;
es.es_pblk = 0;
} else {
es.es_lblk = le32_to_cpu(ex->ee_block);
es.es_len = ext4_ext_get_actual_len(ex);
es.es_pblk = ext4_ext_pblock(ex);
if (ext4_ext_is_unwritten(ex))
flags |= FIEMAP_EXTENT_UNWRITTEN;
}
/*
* Find delayed extent and update es accordingly. We call
* it even in !exists case to find out whether es is the
* last existing extent or not.
*/
next_del = ext4_find_delayed_extent(inode, &es);
if (!exists && next_del) {
exists = 1;
flags |= (FIEMAP_EXTENT_DELALLOC |
FIEMAP_EXTENT_UNKNOWN);
}
up_read(&EXT4_I(inode)->i_data_sem);
if (unlikely(es.es_len == 0)) {
EXT4_ERROR_INODE(inode, "es.es_len == 0");
err = -EFSCORRUPTED;
break;
}
/*
* This is possible iff next == next_del == EXT_MAX_BLOCKS.
* we need to check next == EXT_MAX_BLOCKS because it is
* possible that an extent is with unwritten and delayed
* status due to when an extent is delayed allocated and
* is allocated by fallocate status tree will track both of
* them in a extent.
*
* So we could return a unwritten and delayed extent, and
* its block is equal to 'next'.
*/
if (next == next_del && next == EXT_MAX_BLOCKS) {
flags |= FIEMAP_EXTENT_LAST;
if (unlikely(next_del != EXT_MAX_BLOCKS ||
next != EXT_MAX_BLOCKS)) {
EXT4_ERROR_INODE(inode,
"next extent == %u, next "
"delalloc extent = %u",
next, next_del);
err = -EFSCORRUPTED;
break;
}
}
if (exists) {
err = fiemap_fill_next_extent(fieinfo,
(__u64)es.es_lblk << blksize_bits,
(__u64)es.es_pblk << blksize_bits,
(__u64)es.es_len << blksize_bits,
flags);
if (err < 0)
break;
if (err == 1) {
err = 0;
break;
}
}
block = es.es_lblk + es.es_len;
}
ext4_ext_drop_refs(path);
kfree(path);
return err;
}
/*
* ext4_ext_determine_hole - determine hole around given block
* @inode: inode we lookup in
* @path: path in extent tree to @lblk
* @lblk: pointer to logical block around which we want to determine hole
*
* Determine hole length (and start if easily possible) around given logical
* block. We don't try too hard to find the beginning of the hole but @path
* actually points to extent before @lblk, we provide it.
*
* The function returns the length of a hole starting at @lblk. We update @lblk
* to the beginning of the hole if we managed to find it.
*/
static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *lblk)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
ext4_lblk_t len;
ex = path[depth].p_ext;
if (ex == NULL) {
/* there is no extent yet, so gap is [0;-] */
*lblk = 0;
len = EXT_MAX_BLOCKS;
} else if (*lblk < le32_to_cpu(ex->ee_block)) {
len = le32_to_cpu(ex->ee_block) - *lblk;
} else if (*lblk >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
ext4_lblk_t next;
*lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
next = ext4_ext_next_allocated_block(path);
BUG_ON(next == *lblk);
len = next - *lblk;
} else {
BUG();
}
return len;
}
/*
* ext4_ext_put_gap_in_cache:
* calculate boundaries of the gap that the requested block fits into
* and cache this gap
*/
static void
ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
ext4_lblk_t hole_len)
{
struct extent_status es;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
hole_start + hole_len - 1, &es);
if (es.es_len) {
/* There's delayed extent containing lblock? */
if (es.es_lblk <= hole_start)
return;
hole_len = min(es.es_lblk - hole_start, hole_len);
}
ext_debug(" -> %u:%u\n", hole_start, hole_len);
ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
EXTENT_STATUS_HOLE);
}
/*
* ext4_ext_rm_idx:
* removes index from the index block.
*/
static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path, int depth)
{
int err;
ext4_fsblk_t leaf;
/* free index block */
depth--;
path = path + depth;
leaf = ext4_idx_pblock(path->p_idx);
if (unlikely(path->p_hdr->eh_entries == 0)) {
EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
return -EFSCORRUPTED;
}
err = ext4_ext_get_access(handle, inode, path);
if (err)
return err;
if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
len *= sizeof(struct ext4_extent_idx);
memmove(path->p_idx, path->p_idx + 1, len);
}
le16_add_cpu(&path->p_hdr->eh_entries, -1);
err = ext4_ext_dirty(handle, inode, path);
if (err)
return err;
ext_debug("index is empty, remove it, free block %llu\n", leaf);
trace_ext4_ext_rm_idx(inode, leaf);
ext4_free_blocks(handle, inode, NULL, leaf, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
while (--depth >= 0) {
if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
break;
path--;
err = ext4_ext_get_access(handle, inode, path);
if (err)
break;
path->p_idx->ei_block = (path+1)->p_idx->ei_block;
err = ext4_ext_dirty(handle, inode, path);
if (err)
break;
}
return err;
}
/*
* ext4_ext_calc_credits_for_single_extent:
* This routine returns max. credits that needed to insert an extent
* to the extent tree.
* When pass the actual path, the caller should calculate credits
* under i_data_sem.
*/
int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
struct ext4_ext_path *path)
{
if (path) {
int depth = ext_depth(inode);
int ret = 0;
/* probably there is space in leaf? */
if (le16_to_cpu(path[depth].p_hdr->eh_entries)
< le16_to_cpu(path[depth].p_hdr->eh_max)) {
/*
* There are some space in the leaf tree, no
* need to account for leaf block credit
*
* bitmaps and block group descriptor blocks
* and other metadata blocks still need to be
* accounted.
*/
/* 1 bitmap, 1 block group descriptor */
ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
return ret;
}
}
return ext4_chunk_trans_blocks(inode, nrblocks);
}
/*
* How many index/leaf blocks need to change/allocate to add @extents extents?
*
* If we add a single extent, then in the worse case, each tree level
* index/leaf need to be changed in case of the tree split.
*
* If more extents are inserted, they could cause the whole tree split more
* than once, but this is really rare.
*/
int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
{
int index;
int depth;
/* If we are converting the inline data, only one is needed here. */
if (ext4_has_inline_data(inode))
return 1;
depth = ext_depth(inode);
if (extents <= 1)
index = depth * 2;
else
index = depth * 3;
return index;
}
static inline int get_default_free_blocks_flags(struct inode *inode)
{
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
else if (ext4_should_journal_data(inode))
return EXT4_FREE_BLOCKS_FORGET;
return 0;
}
/*
* ext4_rereserve_cluster - increment the reserved cluster count when
* freeing a cluster with a pending reservation
*
* @inode - file containing the cluster
* @lblk - logical block in cluster to be reserved
*
* Increments the reserved cluster count and adjusts quota in a bigalloc
* file system when freeing a partial cluster containing at least one
* delayed and unwritten block. A partial cluster meeting that
* requirement will have a pending reservation. If so, the
* RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
* defer reserved and allocated space accounting to a subsequent call
* to this function.
*/
static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
spin_lock(&ei->i_block_reservation_lock);
ei->i_reserved_data_blocks++;
percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
spin_unlock(&ei->i_block_reservation_lock);
percpu_counter_add(&sbi->s_freeclusters_counter, 1);
ext4_remove_pending(inode, lblk);
}
static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
struct ext4_extent *ex,
struct partial_cluster *partial,
ext4_lblk_t from, ext4_lblk_t to)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
ext4_fsblk_t last_pblk, pblk;
ext4_lblk_t num;
int flags;
/* only extent tail removal is allowed */
if (from < le32_to_cpu(ex->ee_block) ||
to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
ext4_error(sbi->s_sb,
"strange request: removal(2) %u-%u from %u:%u",
from, to, le32_to_cpu(ex->ee_block), ee_len);
return 0;
}
#ifdef EXTENTS_STATS
spin_lock(&sbi->s_ext_stats_lock);
sbi->s_ext_blocks += ee_len;
sbi->s_ext_extents++;
if (ee_len < sbi->s_ext_min)
sbi->s_ext_min = ee_len;
if (ee_len > sbi->s_ext_max)
sbi->s_ext_max = ee_len;
if (ext_depth(inode) > sbi->s_depth_max)
sbi->s_depth_max = ext_depth(inode);
spin_unlock(&sbi->s_ext_stats_lock);
#endif
trace_ext4_remove_blocks(inode, ex, from, to, partial);
/*
* if we have a partial cluster, and it's different from the
* cluster of the last block in the extent, we free it
*/
last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
if (partial->state != initial &&
partial->pclu != EXT4_B2C(sbi, last_pblk)) {
if (partial->state == tofree) {
flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
num = le32_to_cpu(ex->ee_block) + ee_len - from;
pblk = ext4_ext_pblock(ex) + ee_len - num;
/*
* We free the partial cluster at the end of the extent (if any),
* unless the cluster is used by another extent (partial_cluster
* state is nofree). If a partial cluster exists here, it must be
* shared with the last block in the extent.
*/
flags = get_default_free_blocks_flags(inode);
/* partial, left end cluster aligned, right end unaligned */
if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
(EXT4_LBLK_CMASK(sbi, to) >= from) &&
(partial->state != nofree)) {
if (ext4_is_pending(inode, to))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_PBLK_CMASK(sbi, last_pblk),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, to);
partial->state = initial;
flags = get_default_free_blocks_flags(inode);
}
flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
/*
* For bigalloc file systems, we never free a partial cluster
* at the beginning of the extent. Instead, we check to see if we
* need to free it on a subsequent call to ext4_remove_blocks,
* or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
*/
flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
/* reset the partial cluster if we've freed past it */
if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
partial->state = initial;
/*
* If we've freed the entire extent but the beginning is not left
* cluster aligned and is not marked as ineligible for freeing we
* record the partial cluster at the beginning of the extent. It
* wasn't freed by the preceding ext4_free_blocks() call, and we
* need to look farther to the left to determine if it's to be freed
* (not shared with another extent). Else, reset the partial
* cluster - we're either done freeing or the beginning of the
* extent is left cluster aligned.
*/
if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
if (partial->state == initial) {
partial->pclu = EXT4_B2C(sbi, pblk);
partial->lblk = from;
partial->state = tofree;
}
} else {
partial->state = initial;
}
return 0;
}
/*
* ext4_ext_rm_leaf() Removes the extents associated with the
* blocks appearing between "start" and "end". Both "start"
* and "end" must appear in the same extent or EIO is returned.
*
* @handle: The journal handle
* @inode: The files inode
* @path: The path to the leaf
* @partial_cluster: The cluster which we'll have to free if all extents
* has been released from it. However, if this value is
* negative, it's a cluster just to the right of the
* punched region and it must not be freed.
* @start: The first block to remove
* @end: The last block to remove
*/
static int
ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct partial_cluster *partial,
ext4_lblk_t start, ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int err = 0, correct_index = 0;
int depth = ext_depth(inode), credits;
struct ext4_extent_header *eh;
ext4_lblk_t a, b;
unsigned num;
ext4_lblk_t ex_ee_block;
unsigned short ex_ee_len;
unsigned unwritten = 0;
struct ext4_extent *ex;
ext4_fsblk_t pblk;
/* the header must be checked already in ext4_ext_remove_space() */
ext_debug("truncate since %u in leaf to %u\n", start, end);
if (!path[depth].p_hdr)
path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* find where to start removing */
ex = path[depth].p_ext;
if (!ex)
ex = EXT_LAST_EXTENT(eh);
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_rm_leaf(inode, start, ex, partial);
while (ex >= EXT_FIRST_EXTENT(eh) &&
ex_ee_block + ex_ee_len > start) {
if (ext4_ext_is_unwritten(ex))
unwritten = 1;
else
unwritten = 0;
ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
unwritten, ex_ee_len);
path[depth].p_ext = ex;
a = ex_ee_block > start ? ex_ee_block : start;
b = ex_ee_block+ex_ee_len - 1 < end ?
ex_ee_block+ex_ee_len - 1 : end;
ext_debug(" border %u:%u\n", a, b);
/* If this extent is beyond the end of the hole, skip it */
if (end < ex_ee_block) {
/*
* We're going to skip this extent and move to another,
* so note that its first cluster is in use to avoid
* freeing it when removing blocks. Eventually, the
* right edge of the truncated/punched region will
* be just to the left.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex);
partial->pclu = EXT4_B2C(sbi, pblk);
partial->state = nofree;
}
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
continue;
} else if (b != ex_ee_block + ex_ee_len - 1) {
EXT4_ERROR_INODE(inode,
"can not handle truncate %u:%u "
"on extent %u:%u",
start, end, ex_ee_block,
ex_ee_block + ex_ee_len - 1);
err = -EFSCORRUPTED;
goto out;
} else if (a != ex_ee_block) {
/* remove tail of the extent */
num = a - ex_ee_block;
} else {
/* remove whole extent: excellent! */
num = 0;
}
/*
* 3 for leaf, sb, and inode plus 2 (bmap and group
* descriptor) for each block group; assume two block
* groups plus ex_ee_len/blocks_per_block_group for
* the worst case
*/
credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
if (ex == EXT_FIRST_EXTENT(eh)) {
correct_index = 1;
credits += (ext_depth(inode)) + 1;
}
credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
err = ext4_ext_truncate_extend_restart(handle, inode, credits);
if (err)
goto out;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
if (err)
goto out;
if (num == 0)
/* this extent is removed; mark slot entirely unused */
ext4_ext_store_pblock(ex, 0);
ex->ee_len = cpu_to_le16(num);
/*
* Do not mark unwritten if all the blocks in the
* extent have been removed.
*/
if (unwritten && num)
ext4_ext_mark_unwritten(ex);
/*
* If the extent was completely released,
* we need to remove it from the leaf
*/
if (num == 0) {
if (end != EXT_MAX_BLOCKS - 1) {
/*
* For hole punching, we need to scoot all the
* extents up when an extent is removed so that
* we dont have blank extents in the middle
*/
memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
sizeof(struct ext4_extent));
/* Now get rid of the one at the end */
memset(EXT_LAST_EXTENT(eh), 0,
sizeof(struct ext4_extent));
}
le16_add_cpu(&eh->eh_entries, -1);
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
ext4_ext_pblock(ex));
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
}
if (correct_index && eh->eh_entries)
err = ext4_ext_correct_indexes(handle, inode, path);
/*
* If there's a partial cluster and at least one extent remains in
* the leaf, free the partial cluster if it isn't shared with the
* current extent. If it is shared with the current extent
* we reset the partial cluster because we've reached the start of the
* truncated/punched region and we're done removing blocks.
*/
if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
if (partial->pclu != EXT4_B2C(sbi, pblk)) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
/* if this leaf is free, then we should
* remove it from index block above */
if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
err = ext4_ext_rm_idx(handle, inode, path, depth);
out:
return err;
}
/*
* ext4_ext_more_to_rm:
* returns 1 if current index has to be freed (even partial)
*/
static int
ext4_ext_more_to_rm(struct ext4_ext_path *path)
{
BUG_ON(path->p_idx == NULL);
if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
return 0;
/*
* if truncate on deeper level happened, it wasn't partial,
* so we have to consider current index for truncation
*/
if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
return 0;
return 1;
}
int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int depth = ext_depth(inode);
struct ext4_ext_path *path = NULL;
struct partial_cluster partial;
handle_t *handle;
int i = 0, err = 0;
partial.pclu = 0;
partial.lblk = 0;
partial.state = initial;
ext_debug("truncate since %u to %u\n", start, end);
/* probably first extent we're gonna free will be last in block */
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
again:
trace_ext4_ext_remove_space(inode, start, end, depth);
/*
* Check if we are removing extents inside the extent tree. If that
* is the case, we are going to punch a hole inside the extent tree
* so we have to check whether we need to split the extent covering
* the last block to remove so we can easily remove the part of it
* in ext4_ext_rm_leaf().
*/
if (end < EXT_MAX_BLOCKS - 1) {
struct ext4_extent *ex;
ext4_lblk_t ee_block, ex_end, lblk;
ext4_fsblk_t pblk;
/* find extent for or closest extent to this block */
path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path)) {
ext4_journal_stop(handle);
return PTR_ERR(path);
}
depth = ext_depth(inode);
/* Leaf not may not exist only if inode has no blocks at all */
ex = path[depth].p_ext;
if (!ex) {
if (depth) {
EXT4_ERROR_INODE(inode,
"path[%d].p_hdr == NULL",
depth);
err = -EFSCORRUPTED;
}
goto out;
}
ee_block = le32_to_cpu(ex->ee_block);
ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
/*
* See if the last block is inside the extent, if so split
* the extent at 'end' block so we can easily remove the
* tail of the first part of the split extent in
* ext4_ext_rm_leaf().
*/
if (end >= ee_block && end < ex_end) {
/*
* If we're going to split the extent, note that
* the cluster containing the block after 'end' is
* in use to avoid freeing it when removing blocks.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
/*
* Split the extent in two so that 'end' is the last
* block in the first new extent. Also we should not
* fail removing space due to ENOSPC so try to use
* reserved block if that happens.
*/
err = ext4_force_split_extent_at(handle, inode, &path,
end + 1, 1);
if (err < 0)
goto out;
} else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
partial.state == initial) {
/*
* If we're punching, there's an extent to the right.
* If the partial cluster hasn't been set, set it to
* that extent's first cluster and its state to nofree
* so it won't be freed should it contain blocks to be
* removed. If it's already set (tofree/nofree), we're
* retrying and keep the original partial cluster info
* so a cluster marked tofree as a result of earlier
* extent removal is not lost.
*/
lblk = ex_end + 1;
err = ext4_ext_search_right(inode, path, &lblk, &pblk,
&ex);
if (err)
goto out;
if (pblk) {
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
}
}
/*
* We start scanning from right side, freeing all the blocks
* after i_size and walking into the tree depth-wise.
*/
depth = ext_depth(inode);
if (path) {
int k = i = depth;
while (--k > 0)
path[k].p_block =
le16_to_cpu(path[k].p_hdr->eh_entries)+1;
} else {
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (path == NULL) {
ext4_journal_stop(handle);
return -ENOMEM;
}
path[0].p_maxdepth = path[0].p_depth = depth;
path[0].p_hdr = ext_inode_hdr(inode);
i = 0;
if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
err = -EFSCORRUPTED;
goto out;
}
}
err = 0;
while (i >= 0 && err == 0) {
if (i == depth) {
/* this is leaf block */
err = ext4_ext_rm_leaf(handle, inode, path,
&partial, start, end);
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
/* this is index block */
if (!path[i].p_hdr) {
ext_debug("initialize header\n");
path[i].p_hdr = ext_block_hdr(path[i].p_bh);
}
if (!path[i].p_idx) {
/* this level hasn't been touched yet */
path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
ext_debug("init index ptr: hdr 0x%p, num %d\n",
path[i].p_hdr,
le16_to_cpu(path[i].p_hdr->eh_entries));
} else {
/* we were already here, see at next index */
path[i].p_idx--;
}
ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
i, EXT_FIRST_INDEX(path[i].p_hdr),
path[i].p_idx);
if (ext4_ext_more_to_rm(path + i)) {
struct buffer_head *bh;
/* go to the next level */
ext_debug("move to level %d (block %llu)\n",
i + 1, ext4_idx_pblock(path[i].p_idx));
memset(path + i + 1, 0, sizeof(*path));
bh = read_extent_tree_block(inode,
ext4_idx_pblock(path[i].p_idx), depth - i - 1,
EXT4_EX_NOCACHE);
if (IS_ERR(bh)) {
/* should we reset i_size? */
err = PTR_ERR(bh);
break;
}
/* Yield here to deal with large extent trees.
* Should be a no-op if we did IO above. */
cond_resched();
if (WARN_ON(i + 1 > depth)) {
err = -EFSCORRUPTED;
break;
}
path[i + 1].p_bh = bh;
/* save actual number of indexes since this
* number is changed at the next iteration */
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
i++;
} else {
/* we finished processing this index, go up */
if (path[i].p_hdr->eh_entries == 0 && i > 0) {
/* index is empty, remove it;
* handle must be already prepared by the
* truncatei_leaf() */
err = ext4_ext_rm_idx(handle, inode, path, i);
}
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
ext_debug("return to level %d\n", i);
}
}
trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
path->p_hdr->eh_entries);
/*
* if there's a partial cluster and we have removed the first extent
* in the file, then we also free the partial cluster, if any
*/
if (partial.state == tofree && err == 0) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial.lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial.pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial.lblk);
partial.state = initial;
}
/* TODO: flexible tree reduction should be here */
if (path->p_hdr->eh_entries == 0) {
/*
* truncate to zero freed all the tree,
* so we need to correct eh_depth
*/
err = ext4_ext_get_access(handle, inode, path);
if (err == 0) {
ext_inode_hdr(inode)->eh_depth = 0;
ext_inode_hdr(inode)->eh_max =
cpu_to_le16(ext4_ext_space_root(inode, 0));
err = ext4_ext_dirty(handle, inode, path);
}
}
out:
ext4_ext_drop_refs(path);
kfree(path);
path = NULL;
if (err == -EAGAIN)
goto again;
ext4_journal_stop(handle);
return err;
}
/*
* called at mount time
*/
void ext4_ext_init(struct super_block *sb)
{
/*
* possible initialization would be here
*/
if (ext4_has_feature_extents(sb)) {
#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
printk(KERN_INFO "EXT4-fs: file extents enabled"
#ifdef AGGRESSIVE_TEST
", aggressive tests"
#endif
#ifdef CHECK_BINSEARCH
", check binsearch"
#endif
#ifdef EXTENTS_STATS
", stats"
#endif
"\n");
#endif
#ifdef EXTENTS_STATS
spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
EXT4_SB(sb)->s_ext_min = 1 << 30;
EXT4_SB(sb)->s_ext_max = 0;
#endif
}
}
/*
* called at umount time
*/
void ext4_ext_release(struct super_block *sb)
{
if (!ext4_has_feature_extents(sb))
return;
#ifdef EXTENTS_STATS
if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
struct ext4_sb_info *sbi = EXT4_SB(sb);
printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
sbi->s_ext_blocks, sbi->s_ext_extents,
sbi->s_ext_blocks / sbi->s_ext_extents);
printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
}
#endif
}
static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
{
ext4_lblk_t ee_block;
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
if (ee_len == 0)
return 0;
return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
EXTENT_STATUS_WRITTEN);
}
/* FIXME!! we need to try to merge to left or right after zero-out */
static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
{
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
ee_len);
}
/*
* ext4_split_extent_at() splits an extent at given block.
*
* @handle: the journal handle
* @inode: the file inode
* @path: the path to the extent
* @split: the logical block where the extent is splitted.
* @split_flags: indicates if the extent could be zeroout if split fails, and
* the states(init or unwritten) of new extents.
* @flags: flags used to insert new extent to extent tree.
*
*
* Splits extent [a, b] into two extents [a, @split) and [@split, b], states
* of which are deterimined by split_flag.
*
* There are two cases:
* a> the extent are splitted into two extent.
* b> split is not needed, and just mark the extent.
*
* return 0 on success.
*/
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_fsblk_t newblock;
ext4_lblk_t ee_block;
struct ext4_extent *ex, newex, orig_ex, zero_ex;
struct ext4_extent *ex2 = NULL;
unsigned int ee_len, depth;
int err = 0;
BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
(EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
ext_debug("ext4_split_extents_at: inode %lu, logical"
"block %llu\n", inode->i_ino, (unsigned long long)split);
ext4_ext_show_leaf(inode, path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
newblock = split - ee_block + ext4_ext_pblock(ex);
BUG_ON(split < ee_block || split >= (ee_block + ee_len));
BUG_ON(!ext4_ext_is_unwritten(ex) &&
split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (split == ee_block) {
/*
* case b: block @split is the block that the extent begins with
* then we just change the state of the extent, and splitting
* is not needed.
*/
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex);
else
ext4_ext_mark_initialized(ex);
if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
}
/* case a */
memcpy(&orig_ex, ex, sizeof(orig_ex));
ex->ee_len = cpu_to_le16(split - ee_block);
if (split_flag & EXT4_EXT_MARK_UNWRIT1)
ext4_ext_mark_unwritten(ex);
/*
* path may lead to new leaf, not to original leaf any more
* after ext4_ext_insert_extent() returns,
*/
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto fix_extent_len;
ex2 = &newex;
ex2->ee_block = cpu_to_le32(split);
ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
ext4_ext_store_pblock(ex2, newblock);
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex2);
err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
if (split_flag & EXT4_EXT_DATA_VALID1) {
err = ext4_ext_zeroout(inode, ex2);
zero_ex.ee_block = ex2->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex2));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex2));
} else {
err = ext4_ext_zeroout(inode, ex);
zero_ex.ee_block = ex->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex));
}
} else {
err = ext4_ext_zeroout(inode, &orig_ex);
zero_ex.ee_block = orig_ex.ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(&orig_ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(&orig_ex));
}
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_len = cpu_to_le16(ee_len);
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (err)
goto fix_extent_len;
/* update extent status tree */
err = ext4_zeroout_es(inode, &zero_ex);
goto out;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err;
fix_extent_len:
ex->ee_len = orig_ex.ee_len;
ext4_ext_dirty(handle, inode, path + path->p_depth);
return err;
}
/*
* ext4_split_extents() splits an extent and mark extent which is covered
* by @map as split_flags indicates
*
* It may result in splitting the extent into multiple extents (up to three)
* There are three possibilities:
* a> There is no split required
* b> Splits in two extents: Split is happening at either end of the extent
* c> Splits in three extents: Somone is splitting in middle of the extent
*
*/
static int ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len, depth;
int err = 0;
int unwritten;
int split_flag1, flags1;
int allocated = map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
unwritten = ext4_ext_is_unwritten(ex);
if (map->m_lblk + map->m_len < ee_block + ee_len) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
if (unwritten)
split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
if (split_flag & EXT4_EXT_DATA_VALID2)
split_flag1 |= EXT4_EXT_DATA_VALID1;
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk + map->m_len, split_flag1, flags1);
if (err)
goto out;
} else {
allocated = ee_len - (map->m_lblk - ee_block);
}
/*
* Update path is required because previous ext4_split_extent_at() may
* result in split of original leaf or extent zeroout.
*/
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
unwritten = ext4_ext_is_unwritten(ex);
split_flag1 = 0;
if (map->m_lblk >= ee_block) {
split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
if (unwritten) {
split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT2);
}
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk, split_flag1, flags);
if (err)
goto out;
}
ext4_ext_show_leaf(inode, path);
out:
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() if someone tries to write
* to an unwritten extent. It may result in splitting the unwritten
* extent into multiple extents (up to three - one initialized and two
* unwritten).
* There are three possibilities:
* a> There is no split required: Entire extent should be initialized
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* Pre-conditions:
* - The extent pointed to by 'path' is unwritten.
* - The extent pointed to by 'path' contains a superset
* of the logical span [map->m_lblk, map->m_lblk + map->m_len).
*
* Post-conditions on success:
* - the returned value is the number of blocks beyond map->l_lblk
* that are allocated and initialized.
* It is guaranteed to be >= map->m_len.
*/
static int ext4_ext_convert_to_initialized(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_sb_info *sbi;
struct ext4_extent_header *eh;
struct ext4_map_blocks split_map;
struct ext4_extent zero_ex1, zero_ex2;
struct ext4_extent *ex, *abut_ex;
ext4_lblk_t ee_block, eof_block;
unsigned int ee_len, depth, map_len = map->m_len;
int allocated = 0, max_zeroout = 0;
int err = 0;
int split_flag = EXT4_EXT_DATA_VALID2;
ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map_len);
sbi = EXT4_SB(inode->i_sb);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map_len)
eof_block = map->m_lblk + map_len;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
zero_ex1.ee_len = 0;
zero_ex2.ee_len = 0;
trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
/* Pre-conditions */
BUG_ON(!ext4_ext_is_unwritten(ex));
BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
/*
* Attempt to transfer newly initialized blocks from the currently
* unwritten extent to its neighbor. This is much cheaper
* than an insertion followed by a merge as those involve costly
* memmove() calls. Transferring to the left is the common case in
* steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
* followed by append writes.
*
* Limitations of the current logic:
* - L1: we do not deal with writes covering the whole extent.
* This would require removing the extent if the transfer
* is possible.
* - L2: we only attempt to merge with an extent stored in the
* same extent tree node.
*/
if ((map->m_lblk == ee_block) &&
/* See if we can merge left */
(map_len < ee_len) && /*L1*/
(ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
ext4_lblk_t prev_lblk;
ext4_fsblk_t prev_pblk, ee_pblk;
unsigned int prev_len;
abut_ex = ex - 1;
prev_lblk = le32_to_cpu(abut_ex->ee_block);
prev_len = ext4_ext_get_actual_len(abut_ex);
prev_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((prev_lblk + prev_len) == ee_block) && /*C2*/
((prev_pblk + prev_len) == ee_pblk) && /*C3*/
(prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of ex by 'map_len' blocks */
ex->ee_block = cpu_to_le32(ee_block + map_len);
ext4_ext_store_pblock(ex, ee_pblk + map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
} else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
(map_len < ee_len) && /*L1*/
ex < EXT_LAST_EXTENT(eh)) { /*L2*/
/* See if we can merge right */
ext4_lblk_t next_lblk;
ext4_fsblk_t next_pblk, ee_pblk;
unsigned int next_len;
abut_ex = ex + 1;
next_lblk = le32_to_cpu(abut_ex->ee_block);
next_len = ext4_ext_get_actual_len(abut_ex);
next_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((map->m_lblk + map_len) == next_lblk) && /*C2*/
((ee_pblk + ee_len) == next_pblk) && /*C3*/
(next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of abut_ex by 'map_len' blocks */
abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(next_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
}
if (allocated) {
/* Mark the block containing both extents as dirty */
ext4_ext_dirty(handle, inode, path + depth);
/* Update path to point to the right extent */
path[depth].p_ext = abut_ex;
goto out;
} else
allocated = ee_len - (map->m_lblk - ee_block);
WARN_ON(map->m_lblk < ee_block);
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully inside i_size or new_size.
*/
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
if (EXT4_EXT_MAY_ZEROOUT & split_flag)
max_zeroout = sbi->s_extent_max_zeroout_kb >>
(inode->i_sb->s_blocksize_bits - 10);
if (IS_ENCRYPTED(inode))
max_zeroout = 0;
/*
* five cases:
* 1. split the extent into three extents.
* 2. split the extent into two extents, zeroout the head of the first
* extent.
* 3. split the extent into two extents, zeroout the tail of the second
* extent.
* 4. split the extent into two extents with out zeroout.
* 5. no splitting needed, just possibly zeroout the head and / or the
* tail of the extent.
*/
split_map.m_lblk = map->m_lblk;
split_map.m_len = map->m_len;
if (max_zeroout && (allocated > split_map.m_len)) {
if (allocated <= max_zeroout) {
/* case 3 or 5 */
zero_ex1.ee_block =
cpu_to_le32(split_map.m_lblk +
split_map.m_len);
zero_ex1.ee_len =
cpu_to_le16(allocated - split_map.m_len);
ext4_ext_store_pblock(&zero_ex1,
ext4_ext_pblock(ex) + split_map.m_lblk +
split_map.m_len - ee_block);
err = ext4_ext_zeroout(inode, &zero_ex1);
if (err)
goto out;
split_map.m_len = allocated;
}
if (split_map.m_lblk - ee_block + split_map.m_len <
max_zeroout) {
/* case 2 or 5 */
if (split_map.m_lblk != ee_block) {
zero_ex2.ee_block = ex->ee_block;
zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
ee_block);
ext4_ext_store_pblock(&zero_ex2,
ext4_ext_pblock(ex));
err = ext4_ext_zeroout(inode, &zero_ex2);
if (err)
goto out;
}
split_map.m_len += split_map.m_lblk - ee_block;
split_map.m_lblk = ee_block;
allocated = map->m_len;
}
}
err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
flags);
if (err > 0)
err = 0;
out:
/* If we have gotten a failure, don't zero out status tree */
if (!err) {
err = ext4_zeroout_es(inode, &zero_ex1);
if (!err)
err = ext4_zeroout_es(inode, &zero_ex2);
}
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() from
* ext4_get_blocks_dio_write() when DIO to write
* to an unwritten extent.
*
* Writing to an unwritten extent may result in splitting the unwritten
* extent into multiple initialized/unwritten extents (up to three)
* There are three possibilities:
* a> There is no split required: Entire extent should be unwritten
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* This works the same way in the case of initialized -> unwritten conversion.
*
* One of more index blocks maybe needed if the extent tree grow after
* the unwritten extent split. To prevent ENOSPC occur at the IO
* complete, we need to split the unwritten extent before DIO submit
* the IO. The unwritten extent called at this time will be split
* into three unwritten extent(at most). After IO complete, the part
* being filled will be convert to initialized by the end_io callback function
* via ext4_convert_unwritten_extents().
*
* Returns the size of unwritten extent to be written on success.
*/
static int ext4_split_convert_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
__func__, inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
/* Convert to unwritten */
if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
split_flag |= EXT4_EXT_DATA_VALID1;
/* Convert to initialized */
} else if (flags & EXT4_GET_BLOCKS_CONVERT) {
split_flag |= ee_block + ee_len <= eof_block ?
EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
}
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
}
static int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)ee_block, ee_len);
/* If extent is larger than requested it is a clear sign that we still
* have some extent state machine issues left. So extent_split is still
* required.
* TODO: Once all related issues will be fixed this situation should be
* illegal.
*/
if (ee_block != map->m_lblk || ee_len > map->m_len) {
#ifdef EXT4_DEBUG
ext4_warning("Inode (%ld) finished: extent logical block %llu,"
" len %u; IO logical block %llu, len %u",
inode->i_ino, (unsigned long long)ee_block, ee_len,
(unsigned long long)map->m_lblk, map->m_len);
#endif
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
/*
* Handle EOFBLOCKS_FL flag, clearing it if necessary
*/
static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
ext4_lblk_t lblk,
struct ext4_ext_path *path,
unsigned int len)
{
int i, depth;
struct ext4_extent_header *eh;
struct ext4_extent *last_ex;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
return 0;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
/*
* We're going to remove EOFBLOCKS_FL entirely in future so we
* do not care for this case anymore. Simply remove the flag
* if there are no extents.
*/
if (unlikely(!eh->eh_entries))
goto out;
last_ex = EXT_LAST_EXTENT(eh);
/*
* We should clear the EOFBLOCKS_FL flag if we are writing the
* last block in the last extent in the file. We test this by
* first checking to see if the caller to
* ext4_ext_get_blocks() was interested in the last block (or
* a block beyond the last block) in the current extent. If
* this turns out to be false, we can bail out from this
* function immediately.
*/
if (lblk + len < le32_to_cpu(last_ex->ee_block) +
ext4_ext_get_actual_len(last_ex))
return 0;
/*
* If the caller does appear to be planning to write at or
* beyond the end of the current extent, we then test to see
* if the current extent is the last extent in the file, by
* checking to make sure it was reached via the rightmost node
* at each level of the tree.
*/
for (i = depth-1; i >= 0; i--)
if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
return 0;
out:
ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
return ext4_mark_inode_dirty(handle, inode);
}
static int
convert_initialized_extent(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
unsigned int allocated)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
/*
* Make sure that the extent is no bigger than we support with
* unwritten extent
*/
if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug("%s: inode %lu, logical"
"block %llu, max_blocks %u\n", __func__, inode->i_ino,
(unsigned long long)ee_block, ee_len);
if (ee_block != map->m_lblk || ee_len > map->m_len) {
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/* first mark the extent as unwritten */
ext4_ext_mark_unwritten(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (err)
return err;
ext4_ext_show_leaf(inode, path);
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
if (err)
return err;
map->m_flags |= EXT4_MAP_UNWRITTEN;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
return allocated;
}
static int
ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
struct ext4_ext_path *path = *ppath;
int ret = 0;
int err = 0;
ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
"block %llu, max_blocks %u, flags %x, allocated %u\n",
inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/*
* When writing into unwritten space, we should not fail to
* allocate metadata blocks for the new extent block if needed.
*/
flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
allocated, newblock);
/* get_block() before submit the IO, split the extent */
if (flags & EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_convert_extents(handle, inode, map, ppath,
flags | EXT4_GET_BLOCKS_CONVERT);
if (ret <= 0)
goto out;
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if (flags & EXT4_GET_BLOCKS_CONVERT) {
if (flags & EXT4_GET_BLOCKS_ZERO) {
if (allocated > map->m_len)
allocated = map->m_len;
err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
allocated);
if (err < 0)
goto out2;
}
ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
ppath);
if (ret >= 0) {
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, map->m_len);
} else
err = ret;
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto map_out;
}
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
map->m_len);
if (err < 0)
goto out2;
}
out1:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_pblk = newblock;
map->m_len = allocated;
out2:
return err ? err : allocated;
}
/*
* get_implied_cluster_alloc - check to see if the requested
* allocation (in the map structure) overlaps with a cluster already
* allocated in an extent.
* @sb The filesystem superblock structure
* @map The requested lblk->pblk mapping
* @ex The extent structure which might contain an implied
* cluster allocation
*
* This function is called by ext4_ext_map_blocks() after we failed to
* find blocks that were already in the inode's extent tree. Hence,
* we know that the beginning of the requested region cannot overlap
* the extent from the inode's extent tree. There are three cases we
* want to catch. The first is this case:
*
* |--- cluster # N--|
* |--- extent ---| |---- requested region ---|
* |==========|
*
* The second case that we need to test for is this one:
*
* |--------- cluster # N ----------------|
* |--- requested region --| |------- extent ----|
* |=======================|
*
* The third case is when the requested region lies between two extents
* within the same cluster:
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*
* In each of the above cases, we need to set the map->m_pblk and
* map->m_len so it corresponds to the return the extent labelled as
* "|====|" from cluster #N, since it is already in use for data in
* cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
* signal to ext4_ext_map_blocks() that map->m_pblk should be treated
* as a new "allocated" block region. Otherwise, we will return 0 and
* ext4_ext_map_blocks() will then allocate one or more new clusters
* by calling ext4_mb_new_blocks().
*/
static int get_implied_cluster_alloc(struct super_block *sb,
struct ext4_map_blocks *map,
struct ext4_extent *ex,
struct ext4_ext_path *path)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ext4_lblk_t ex_cluster_start, ex_cluster_end;
ext4_lblk_t rr_cluster_start;
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
/* The extent passed in that we are trying to match */
ex_cluster_start = EXT4_B2C(sbi, ee_block);
ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
/* The requested region passed into ext4_map_blocks() */
rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
if ((rr_cluster_start == ex_cluster_end) ||
(rr_cluster_start == ex_cluster_start)) {
if (rr_cluster_start == ex_cluster_end)
ee_start += ee_len - 1;
map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
map->m_len = min(map->m_len,
(unsigned) sbi->s_cluster_ratio - c_offset);
/*
* Check for and handle this case:
*
* |--------- cluster # N-------------|
* |------- extent ----|
* |--- requested region ---|
* |===========|
*/
if (map->m_lblk < ee_block)
map->m_len = min(map->m_len, ee_block - map->m_lblk);
/*
* Check for the case where there is already another allocated
* block to the right of 'ex' but before the end of the cluster.
*
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*/
if (map->m_lblk > ee_block) {
ext4_lblk_t next = ext4_ext_next_allocated_block(path);
map->m_len = min(map->m_len, next - map->m_lblk);
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
return 1;
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
return 0;
}
/*
* Block allocation/map/preallocation routine for extents based files
*
*
* Need to be called with
* down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
* (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
*
* return > 0, number of of blocks already mapped/allocated
* if create == 0 and these are pre-allocated blocks
* buffer head is unmapped
* otherwise blocks are mapped
*
* return = 0, if plain look up failed (blocks have not been allocated)
* buffer head is unmapped
*
* return < 0, error case.
*/
int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent newex, *ex, *ex2;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_fsblk_t newblock = 0;
int free_on_err = 0, err = 0, depth, ret;
unsigned int allocated = 0, offset = 0;
unsigned int allocated_clusters = 0;
struct ext4_allocation_request ar;
ext4_lblk_t cluster_offset;
bool map_from_cluster = false;
ext_debug("blocks %u/%u requested for inode %lu\n",
map->m_lblk, map->m_len, inode->i_ino);
trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
/* find extent for this block */
path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out2;
}
depth = ext_depth(inode);
/*
* consistent leaf must not be empty;
* this situation is possible, though, _during_ tree modification;
* this is why assert can't be put in ext4_find_extent()
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode, "bad extent address "
"lblock: %lu, depth: %d pblock %lld",
(unsigned long) map->m_lblk, depth,
path[depth].p_block);
err = -EFSCORRUPTED;
goto out2;
}
ex = path[depth].p_ext;
if (ex) {
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len;
/*
* unwritten extents are treated as holes, except that
* we split out initialized portions during a write.
*/
ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
/* if found extent covers block, simply return it */
if (in_range(map->m_lblk, ee_block, ee_len)) {
newblock = map->m_lblk - ee_block + ee_start;
/* number of remaining blocks in the extent */
allocated = ee_len - (map->m_lblk - ee_block);
ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
ee_block, ee_len, newblock);
/*
* If the extent is initialized check whether the
* caller wants to convert it to unwritten.
*/
if ((!ext4_ext_is_unwritten(ex)) &&
(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
allocated = convert_initialized_extent(
handle, inode, map, &path,
allocated);
goto out2;
} else if (!ext4_ext_is_unwritten(ex))
goto out;
ret = ext4_ext_handle_unwritten_extents(
handle, inode, map, &path, flags,
allocated, newblock);
if (ret < 0)
err = ret;
else
allocated = ret;
goto out2;
}
}
/*
* requested block isn't allocated yet;
* we couldn't try to create block if create flag is zero
*/
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
ext4_lblk_t hole_start, hole_len;
hole_start = map->m_lblk;
hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
/*
* put just found gap into cache to speed up
* subsequent requests
*/
ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
/* Update hole_len to reflect hole size after map->m_lblk */
if (hole_start != map->m_lblk)
hole_len -= map->m_lblk - hole_start;
map->m_pblk = 0;
map->m_len = min_t(unsigned int, map->m_len, hole_len);
goto out2;
}
/*
* Okay, we need to do block allocation.
*/
newex.ee_block = cpu_to_le32(map->m_lblk);
cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
/*
* If we are doing bigalloc, check to see if the extent returned
* by ext4_find_extent() implies a cluster we can use.
*/
if (cluster_offset && ex &&
get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/* find neighbour allocated blocks */
ar.lleft = map->m_lblk;
err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
if (err)
goto out2;
ar.lright = map->m_lblk;
ex2 = NULL;
err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
if (err)
goto out2;
/* Check if the extent after searching to the right implies a
* cluster we can use. */
if ((sbi->s_cluster_ratio > 1) && ex2 &&
get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/*
* See if request is beyond maximum number of blocks we can have in
* a single extent. For an initialized extent this limit is
* EXT_INIT_MAX_LEN and for an unwritten extent this limit is
* EXT_UNWRITTEN_MAX_LEN.
*/
if (map->m_len > EXT_INIT_MAX_LEN &&
!(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_INIT_MAX_LEN;
else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_UNWRITTEN_MAX_LEN;
/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
newex.ee_len = cpu_to_le16(map->m_len);
err = ext4_ext_check_overlap(sbi, inode, &newex, path);
if (err)
allocated = ext4_ext_get_actual_len(&newex);
else
allocated = map->m_len;
/* allocate new block */
ar.inode = inode;
ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
ar.logical = map->m_lblk;
/*
* We calculate the offset from the beginning of the cluster
* for the logical block number, since when we allocate a
* physical cluster, the physical block should start at the
* same offset from the beginning of the cluster. This is
* needed so that future calls to get_implied_cluster_alloc()
* work correctly.
*/
offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
ar.goal -= offset;
ar.logical -= offset;
if (S_ISREG(inode->i_mode))
ar.flags = EXT4_MB_HINT_DATA;
else
/* disable in-core preallocation for non-regular files */
ar.flags = 0;
if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
ar.flags |= EXT4_MB_HINT_NOPREALLOC;
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ar.flags |= EXT4_MB_DELALLOC_RESERVED;
if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
ar.flags |= EXT4_MB_USE_RESERVED;
newblock = ext4_mb_new_blocks(handle, &ar, &err);
if (!newblock)
goto out2;
ext_debug("allocate new block: goal %llu, found %llu/%u\n",
ar.goal, newblock, allocated);
free_on_err = 1;
allocated_clusters = ar.len;
ar.len = EXT4_C2B(sbi, ar.len) - offset;
if (ar.len > allocated)
ar.len = allocated;
got_allocated_blocks:
/* try to insert new extent into found leaf and return */
ext4_ext_store_pblock(&newex, newblock + offset);
newex.ee_len = cpu_to_le16(ar.len);
/* Mark unwritten */
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
ext4_ext_mark_unwritten(&newex);
map->m_flags |= EXT4_MAP_UNWRITTEN;
}
err = 0;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, ar.len);
if (!err)
err = ext4_ext_insert_extent(handle, inode, &path,
&newex, flags);
if (err && free_on_err) {
int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
/* free data blocks we just allocated */
/* not a good idea to call discard here directly,
* but otherwise we'd need to call it every free() */
ext4_discard_preallocations(inode);
ext4_free_blocks(handle, inode, NULL, newblock,
EXT4_C2B(sbi, allocated_clusters), fb_flags);
goto out2;
}
/* previous routine could use block we allocated */
newblock = ext4_ext_pblock(&newex);
allocated = ext4_ext_get_actual_len(&newex);
if (allocated > map->m_len)
allocated = map->m_len;
map->m_flags |= EXT4_MAP_NEW;
/*
* Reduce the reserved cluster count to reflect successful deferred
* allocation of delayed allocated clusters or direct allocation of
* clusters discovered to be delayed allocated. Once allocated, a
* cluster is not included in the reserved count.
*/
if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
/*
* When allocating delayed allocated clusters, simply
* reduce the reserved cluster count and claim quota
*/
ext4_da_update_reserve_space(inode, allocated_clusters,
1);
} else {
ext4_lblk_t lblk, len;
unsigned int n;
/*
* When allocating non-delayed allocated clusters
* (from fallocate, filemap, DIO, or clusters
* allocated when delalloc has been disabled by
* ext4_nonda_switch), reduce the reserved cluster
* count by the number of allocated clusters that
* have previously been delayed allocated. Quota
* has been claimed by ext4_mb_new_blocks() above,
* so release the quota reservations made for any
* previously delayed allocated clusters.
*/
lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
len = allocated_clusters << sbi->s_cluster_bits;
n = ext4_es_delayed_clu(inode, lblk, len);
if (n > 0)
ext4_da_update_reserve_space(inode, (int) n, 0);
}
}
/*
* Cache the extent and update transaction to commit on fdatasync only
* when it is _not_ an unwritten extent.
*/
if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
else
ext4_update_inode_fsync_trans(handle, inode, 0);
out:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
map->m_len = allocated;
out2:
ext4_ext_drop_refs(path);
kfree(path);
trace_ext4_ext_map_blocks_exit(inode, flags, map,
err ? err : allocated);
return err ? err : allocated;
}
int ext4_ext_truncate(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t last_block;
int err = 0;
/*
* TODO: optimization is possible here.
* Probably we need not scan at all,
* because page truncation is enough.
*/
/* we have to know where to truncate from in crash case */
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_mark_inode_dirty(handle, inode);
if (err)
return err;
last_block = (inode->i_size + sb->s_blocksize - 1)
>> EXT4_BLOCK_SIZE_BITS(sb);
retry:
err = ext4_es_remove_extent(inode, last_block,
EXT_MAX_BLOCKS - last_block);
if (err == -ENOMEM) {
cond_resched();
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto retry;
}
if (err)
return err;
return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
}
static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
ext4_lblk_t len, loff_t new_size,
int flags)
{
struct inode *inode = file_inode(file);
handle_t *handle;
int ret = 0;
int ret2 = 0;
int retries = 0;
int depth = 0;
struct ext4_map_blocks map;
unsigned int credits;
loff_t epos;
BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
map.m_lblk = offset;
map.m_len = len;
/*
* Don't normalize the request if it can fit in one extent so
* that it doesn't get unnecessarily split into multiple
* extents.
*/
if (len <= EXT_UNWRITTEN_MAX_LEN)
flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
retry:
while (ret >= 0 && len) {
/*
* Recalculate credits when extent tree depth changes.
*/
if (depth != ext_depth(inode)) {
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
}
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
ret = ext4_map_blocks(handle, inode, &map, flags);
if (ret <= 0) {
ext4_debug("inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ext4_mark_inode_dirty(handle, inode);
ret2 = ext4_journal_stop(handle);
break;
}
map.m_lblk += ret;
map.m_len = len = len - ret;
epos = (loff_t)map.m_lblk << inode->i_blkbits;
inode->i_ctime = current_time(inode);
if (new_size) {
if (epos > new_size)
epos = new_size;
if (ext4_update_inode_size(inode, epos) & 0x1)
inode->i_mtime = inode->i_ctime;
} else {
if (epos > inode->i_size)
ext4_set_inode_flag(inode,
EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
ret2 = ext4_journal_stop(handle);
if (ret2)
break;
}
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries)) {
ret = 0;
goto retry;
}
return ret > 0 ? ret2 : ret;
}
static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
inode_lock(inode);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > i_size_read(inode) ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Wait all existing dio workers, newcomers will block on i_mutex */
inode_dio_wait(inode);
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/*
* Prevent page faults from reinstantiating pages we have
* released from page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret) {
up_write(&EXT4_I(inode)->i_mmap_sem);
goto out_mutex;
}
ret = ext4_update_disksize_before_punch(inode, offset, len);
if (ret) {
up_write(&EXT4_I(inode)->i_mmap_sem);
goto out_mutex;
}
/* Now release the pages and zero block aligned part of pages */
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = current_time(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags);
up_write(&EXT4_I(inode)->i_mmap_sem);
if (ret)
goto out_mutex;
}
if (!partial_begin && !partial_end)
goto out_mutex;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_mutex;
}
inode->i_mtime = inode->i_ctime = current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* preallocate space for a file. This implements ext4's fallocate file
* operation, which gets called from sys_fallocate system call.
* For block-mapped files, posix_fallocate should fall back to the method
* of writing zeroes to the required new blocks (the same behavior which is
* expected for file systems which do not support fallocate() system call).
*/
long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
loff_t new_size = 0;
unsigned int max_blocks;
int ret = 0;
int flags;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
/*
* Encrypted inodes can't handle collapse range or insert
* range since we would need to re-encrypt blocks with a
* different IV or XTS tweak (which are based on the logical
* block number).
*
* XXX It's not clear why zero range isn't working, but we'll
* leave it disabled for encrypted inodes for now. This is a
* bug we should fix....
*/
if (IS_ENCRYPTED(inode) &&
(mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
FALLOC_FL_ZERO_RANGE)))
return -EOPNOTSUPP;
/* Return error if mode is not supported */
if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
FALLOC_FL_INSERT_RANGE))
return -EOPNOTSUPP;
if (mode & FALLOC_FL_PUNCH_HOLE)
return ext4_punch_hole(inode, offset, len);
ret = ext4_convert_inline_data(inode);
if (ret)
return ret;
if (mode & FALLOC_FL_COLLAPSE_RANGE)
return ext4_collapse_range(inode, offset, len);
if (mode & FALLOC_FL_INSERT_RANGE)
return ext4_insert_range(inode, offset, len);
if (mode & FALLOC_FL_ZERO_RANGE)
return ext4_zero_range(file, offset, len, mode);
trace_ext4_fallocate_enter(inode, offset, len, mode);
lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
inode_lock(inode);
/*
* We only support preallocation for extent-based files only
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > i_size_read(inode) ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out;
}
/* Wait all existing dio workers, newcomers will block on i_mutex */
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
if (ret)
goto out;
if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
EXT4_I(inode)->i_sync_tid);
}
out:
inode_unlock(inode);
trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
return ret;
}
/*
* This function convert a range of blocks to written extents
* The caller of this function will pass the start offset and the size.
* all unwritten extents within this range will be converted to
* written extents.
*
* This function is called from the direct IO end io call back
* function, to convert the fallocated extents after IO is completed.
* Returns 0 on success.
*/
int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
loff_t offset, ssize_t len)
{
unsigned int max_blocks;
int ret = 0;
int ret2 = 0;
struct ext4_map_blocks map;
unsigned int credits, blkbits = inode->i_blkbits;
map.m_lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
/*
* This is somewhat ugly but the idea is clear: When transaction is
* reserved, everything goes into it. Otherwise we rather start several
* smaller transactions for conversion of each extent separately.
*/
if (handle) {
handle = ext4_journal_start_reserved(handle,
EXT4_HT_EXT_CONVERT);
if (IS_ERR(handle))
return PTR_ERR(handle);
credits = 0;
} else {
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, max_blocks);
}
while (ret >= 0 && ret < max_blocks) {
map.m_lblk += ret;
map.m_len = (max_blocks -= ret);
if (credits) {
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
}
ret = ext4_map_blocks(handle, inode, &map,
EXT4_GET_BLOCKS_IO_CONVERT_EXT);
if (ret <= 0)
ext4_warning(inode->i_sb,
"inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ext4_mark_inode_dirty(handle, inode);
if (credits)
ret2 = ext4_journal_stop(handle);
if (ret <= 0 || ret2)
break;
}
if (!credits)
ret2 = ext4_journal_stop(handle);
return ret > 0 ? ret2 : ret;
}
/*
* If newes is not existing extent (newes->ec_pblk equals zero) find
* delayed extent at start of newes and update newes accordingly and
* return start of the next delayed extent.
*
* If newes is existing extent (newes->ec_pblk is not equal zero)
* return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
* extent found. Leave newes unmodified.
*/
static int ext4_find_delayed_extent(struct inode *inode,
struct extent_status *newes)
{
struct extent_status es;
ext4_lblk_t block, next_del;
if (newes->es_pblk == 0) {
ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
newes->es_lblk,
newes->es_lblk + newes->es_len - 1,
&es);
/*
* No extent in extent-tree contains block @newes->es_pblk,
* then the block may stay in 1)a hole or 2)delayed-extent.
*/
if (es.es_len == 0)
/* A hole found. */
return 0;
if (es.es_lblk > newes->es_lblk) {
/* A hole found. */
newes->es_len = min(es.es_lblk - newes->es_lblk,
newes->es_len);
return 0;
}
newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
}
block = newes->es_lblk + newes->es_len;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed, block,
EXT_MAX_BLOCKS, &es);
if (es.es_len == 0)
next_del = EXT_MAX_BLOCKS;
else
next_del = es.es_lblk;
return next_del;
}
/* fiemap flags we can handle specified here */
#define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
static int ext4_xattr_fiemap(struct inode *inode,
struct fiemap_extent_info *fieinfo)
{
__u64 physical = 0;
__u64 length;
__u32 flags = FIEMAP_EXTENT_LAST;
int blockbits = inode->i_sb->s_blocksize_bits;
int error = 0;
/* in-inode? */
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
struct ext4_iloc iloc;
int offset; /* offset of xattr in inode */
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
physical = (__u64)iloc.bh->b_blocknr << blockbits;
offset = EXT4_GOOD_OLD_INODE_SIZE +
EXT4_I(inode)->i_extra_isize;
physical += offset;
length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
flags |= FIEMAP_EXTENT_DATA_INLINE;
brelse(iloc.bh);
} else { /* external block */
physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
length = inode->i_sb->s_blocksize;
}
if (physical)
error = fiemap_fill_next_extent(fieinfo, 0, physical,
length, flags);
return (error < 0 ? error : 0);
}
int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
ext4_lblk_t start_blk;
int error = 0;
if (ext4_has_inline_data(inode)) {
int has_inline = 1;
error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
start, len);
if (has_inline)
return error;
}
if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
error = ext4_ext_precache(inode);
if (error)
return error;
}
/* fallback to generic here if not in extents fmt */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
return generic_block_fiemap(inode, fieinfo, start, len,
ext4_get_block);
if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
return -EBADR;
if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
error = ext4_xattr_fiemap(inode, fieinfo);
} else {
ext4_lblk_t len_blks;
__u64 last_blk;
start_blk = start >> inode->i_sb->s_blocksize_bits;
last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
if (last_blk >= EXT_MAX_BLOCKS)
last_blk = EXT_MAX_BLOCKS-1;
len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
/*
* Walk the extent tree gathering extent information
* and pushing extents back to the user.
*/
error = ext4_fill_fiemap_extents(inode, start_blk,
len_blks, fieinfo);
}
return error;
}
/*
* ext4_access_path:
* Function to access the path buffer for marking it dirty.
* It also checks if there are sufficient credits left in the journal handle
* to update path.
*/
static int
ext4_access_path(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
int credits, err;
if (!ext4_handle_valid(handle))
return 0;
/*
* Check if need to extend journal credits
* 3 for leaf, sb, and inode plus 2 (bmap and group
* descriptor) for each block group; assume two block
* groups
*/
if (handle->h_buffer_credits < 7) {
credits = ext4_writepage_trans_blocks(inode);
err = ext4_ext_truncate_extend_restart(handle, inode, credits);
/* EAGAIN is success */
if (err && err != -EAGAIN)
return err;
}
err = ext4_ext_get_access(handle, inode, path);
return err;
}
/*
* ext4_ext_shift_path_extents:
* Shift the extents of a path structure lying between path[depth].p_ext
* and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
* if it is right shift or left shift operation.
*/
static int
ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
struct inode *inode, handle_t *handle,
enum SHIFT_DIRECTION SHIFT)
{
int depth, err = 0;
struct ext4_extent *ex_start, *ex_last;
bool update = 0;
depth = path->p_depth;
while (depth >= 0) {
if (depth == path->p_depth) {
ex_start = path[depth].p_ext;
if (!ex_start)
return -EFSCORRUPTED;
ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
err = ext4_access_path(handle, inode, path + depth);
if (err)
goto out;
if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
update = 1;
while (ex_start <= ex_last) {
if (SHIFT == SHIFT_LEFT) {
le32_add_cpu(&ex_start->ee_block,
-shift);
/* Try to merge to the left. */
if ((ex_start >
EXT_FIRST_EXTENT(path[depth].p_hdr))
&&
ext4_ext_try_to_merge_right(inode,
path, ex_start - 1))
ex_last--;
else
ex_start++;
} else {
le32_add_cpu(&ex_last->ee_block, shift);
ext4_ext_try_to_merge_right(inode, path,
ex_last);
ex_last--;
}
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
if (--depth < 0 || !update)
break;
}
/* Update index too */
err = ext4_access_path(handle, inode, path + depth);
if (err)
goto out;
if (SHIFT == SHIFT_LEFT)
le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
else
le32_add_cpu(&path[depth].p_idx->ei_block, shift);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
/* we are done if current index is not a starting index */
if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
break;
depth--;
}
out:
return err;
}
/*
* ext4_ext_shift_extents:
* All the extents which lies in the range from @start to the last allocated
* block for the @inode are shifted either towards left or right (depending
* upon @SHIFT) by @shift blocks.
* On success, 0 is returned, error otherwise.
*/
static int
ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
ext4_lblk_t start, ext4_lblk_t shift,
enum SHIFT_DIRECTION SHIFT)
{
struct ext4_ext_path *path;
int ret = 0, depth;
struct ext4_extent *extent;
ext4_lblk_t stop, *iterator, ex_start, ex_end;
/* Let path point to the last extent */
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent)
goto out;
stop = le32_to_cpu(extent->ee_block);
/*
* For left shifts, make sure the hole on the left is big enough to
* accommodate the shift. For right shifts, make sure the last extent
* won't be shifted beyond EXT_MAX_BLOCKS.
*/
if (SHIFT == SHIFT_LEFT) {
path = ext4_find_extent(inode, start - 1, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (extent) {
ex_start = le32_to_cpu(extent->ee_block);
ex_end = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
ex_start = 0;
ex_end = 0;
}
if ((start == ex_start && shift > ex_start) ||
(shift > start - ex_end)) {
ret = -EINVAL;
goto out;
}
} else {
if (shift > EXT_MAX_BLOCKS -
(stop + ext4_ext_get_actual_len(extent))) {
ret = -EINVAL;
goto out;
}
}
/*
* In case of left shift, iterator points to start and it is increased
* till we reach stop. In case of right shift, iterator points to stop
* and it is decreased till we reach start.
*/
if (SHIFT == SHIFT_LEFT)
iterator = &start;
else
iterator = &stop;
/*
* Its safe to start updating extents. Start and stop are unsigned, so
* in case of right shift if extent with 0 block is reached, iterator
* becomes NULL to indicate the end of the loop.
*/
while (iterator && start <= stop) {
path = ext4_find_extent(inode, *iterator, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) *iterator);
return -EFSCORRUPTED;
}
if (SHIFT == SHIFT_LEFT && *iterator >
le32_to_cpu(extent->ee_block)) {
/* Hole, move to the next extent */
if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
path[depth].p_ext++;
} else {
*iterator = ext4_ext_next_allocated_block(path);
continue;
}
}
if (SHIFT == SHIFT_LEFT) {
extent = EXT_LAST_EXTENT(path[depth].p_hdr);
*iterator = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
if (le32_to_cpu(extent->ee_block) > 0)
*iterator = le32_to_cpu(extent->ee_block) - 1;
else
/* Beginning is reached, end of the loop */
iterator = NULL;
/* Update path extent in case we need to stop */
while (le32_to_cpu(extent->ee_block) < start)
extent++;
path[depth].p_ext = extent;
}
ret = ext4_ext_shift_path_extents(path, shift, inode,
handle, SHIFT);
if (ret)
break;
}
out:
ext4_ext_drop_refs(path);
kfree(path);
return ret;
}
/*
* ext4_collapse_range:
* This implements the fallocate's collapse range functionality for ext4
* Returns: 0 and non-zero on error.
*/
int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t punch_start, punch_stop;
handle_t *handle;
unsigned int credits;
loff_t new_size, ioffset;
int ret;
/*
* We need to test this early because xfstests assumes that a
* collapse range of (0, 1) will return EOPNOTSUPP if the file
* system does not support collapse range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Collapse range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
trace_ext4_collapse_range(inode, offset, len);
punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
inode_lock(inode);
/*
* There is no need to overlap collapse range with EOF, in which case
* it is effectively a truncate operation
*/
if (offset + len >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down offset to be aligned with page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/*
* Write tail of the last page before removed range since it will get
* removed from the page cache below.
*/
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
if (ret)
goto out_mmap;
/*
* Write data that will be shifted to preserve them when discarding
* page cache below. We are also protected from pages becoming dirty
* by i_mmap_sem.
*/
ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, punch_start,
EXT_MAX_BLOCKS - punch_start);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ext4_discard_preallocations(inode);
ret = ext4_ext_shift_extents(inode, handle, punch_stop,
punch_stop - punch_start, SHIFT_LEFT);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
new_size = i_size_read(inode) - len;
i_size_write(inode, new_size);
EXT4_I(inode)->i_disksize = new_size;
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode->i_ctime = current_time(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* ext4_insert_range:
* This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
* The data blocks starting from @offset to the EOF are shifted by @len
* towards right to create a hole in the @inode. Inode size is increased
* by len bytes.
* Returns 0 on success, error otherwise.
*/
int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
handle_t *handle;
struct ext4_ext_path *path;
struct ext4_extent *extent;
ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
unsigned int credits, ee_len;
int ret = 0, depth, split_flag = 0;
loff_t ioffset;
/*
* We need to test this early because xfstests assumes that an
* insert range of (0, 1) will return EOPNOTSUPP if the file
* system does not support insert range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Insert range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_insert_range(inode, offset, len);
offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
inode_lock(inode);
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Check for wrap through zero */
if (inode->i_size + len > inode->i_sb->s_maxbytes) {
ret = -EFBIG;
goto out_mutex;
}
/* Offset should be less than i_size */
if (offset >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down to align start offset to page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
/* Expand file to avoid data loss if there is error while shifting */
inode->i_size += len;
EXT4_I(inode)->i_disksize += len;
inode->i_mtime = inode->i_ctime = current_time(inode);
ret = ext4_mark_inode_dirty(handle, inode);
if (ret)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
path = ext4_find_extent(inode, offset_lblk, NULL, 0);
if (IS_ERR(path)) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
depth = ext_depth(inode);
extent = path[depth].p_ext;
if (extent) {
ee_start_lblk = le32_to_cpu(extent->ee_block);
ee_len = ext4_ext_get_actual_len(extent);
/*
* If offset_lblk is not the starting block of extent, split
* the extent @offset_lblk
*/
if ((offset_lblk > ee_start_lblk) &&
(offset_lblk < (ee_start_lblk + ee_len))) {
if (ext4_ext_is_unwritten(extent))
split_flag = EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
ret = ext4_split_extent_at(handle, inode, &path,
offset_lblk, split_flag,
EXT4_EX_NOCACHE |
EXT4_GET_BLOCKS_PRE_IO |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
}
ext4_ext_drop_refs(path);
kfree(path);
if (ret < 0) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
} else {
ext4_ext_drop_refs(path);
kfree(path);
}
ret = ext4_es_remove_extent(inode, offset_lblk,
EXT_MAX_BLOCKS - offset_lblk);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
/*
* if offset_lblk lies in a hole which is at start of file, use
* ee_start_lblk to shift extents
*/
ret = ext4_ext_shift_extents(inode, handle,
ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
len_lblk, SHIFT_RIGHT);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
out_mutex:
inode_unlock(inode);
return ret;
}
/**
* ext4_swap_extents - Swap extents between two inodes
*
* @inode1: First inode
* @inode2: Second inode
* @lblk1: Start block for first inode
* @lblk2: Start block for second inode
* @count: Number of blocks to swap
* @unwritten: Mark second inode's extents as unwritten after swap
* @erp: Pointer to save error value
*
* This helper routine does exactly what is promise "swap extents". All other
* stuff such as page-cache locking consistency, bh mapping consistency or
* extent's data copying must be performed by caller.
* Locking:
* i_mutex is held for both inodes
* i_data_sem is locked for write for both inodes
* Assumptions:
* All pages from requested range are locked for both inodes
*/
int
ext4_swap_extents(handle_t *handle, struct inode *inode1,
struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
ext4_lblk_t count, int unwritten, int *erp)
{
struct ext4_ext_path *path1 = NULL;
struct ext4_ext_path *path2 = NULL;
int replaced_count = 0;
BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
BUG_ON(!inode_is_locked(inode1));
BUG_ON(!inode_is_locked(inode2));
*erp = ext4_es_remove_extent(inode1, lblk1, count);
if (unlikely(*erp))
return 0;
*erp = ext4_es_remove_extent(inode2, lblk2, count);
if (unlikely(*erp))
return 0;
while (count) {
struct ext4_extent *ex1, *ex2, tmp_ex;
ext4_lblk_t e1_blk, e2_blk;
int e1_len, e2_len, len;
int split = 0;
path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path1)) {
*erp = PTR_ERR(path1);
path1 = NULL;
finish:
count = 0;
goto repeat;
}
path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path2)) {
*erp = PTR_ERR(path2);
path2 = NULL;
goto finish;
}
ex1 = path1[path1->p_depth].p_ext;
ex2 = path2[path2->p_depth].p_ext;
/* Do we have somthing to swap ? */
if (unlikely(!ex2 || !ex1))
goto finish;
e1_blk = le32_to_cpu(ex1->ee_block);
e2_blk = le32_to_cpu(ex2->ee_block);
e1_len = ext4_ext_get_actual_len(ex1);
e2_len = ext4_ext_get_actual_len(ex2);
/* Hole handling */
if (!in_range(lblk1, e1_blk, e1_len) ||
!in_range(lblk2, e2_blk, e2_len)) {
ext4_lblk_t next1, next2;
/* if hole after extent, then go to next extent */
next1 = ext4_ext_next_allocated_block(path1);
next2 = ext4_ext_next_allocated_block(path2);
/* If hole before extent, then shift to that extent */
if (e1_blk > lblk1)
next1 = e1_blk;
if (e2_blk > lblk2)
next2 = e2_blk;
/* Do we have something to swap */
if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
goto finish;
/* Move to the rightest boundary */
len = next1 - lblk1;
if (len < next2 - lblk2)
len = next2 - lblk2;
if (len > count)
len = count;
lblk1 += len;
lblk2 += len;
count -= len;
goto repeat;
}
/* Prepare left boundary */
if (e1_blk < lblk1) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1, 0);
if (unlikely(*erp))
goto finish;
}
if (e2_blk < lblk2) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2, 0);
if (unlikely(*erp))
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
/* Prepare right boundary */
len = count;
if (len > e1_blk + e1_len - lblk1)
len = e1_blk + e1_len - lblk1;
if (len > e2_blk + e2_len - lblk2)
len = e2_blk + e2_len - lblk2;
if (len != e1_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1 + len, 0);
if (unlikely(*erp))
goto finish;
}
if (len != e2_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2 + len, 0);
if (*erp)
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
BUG_ON(e2_len != e1_len);
*erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
if (unlikely(*erp))
goto finish;
/* Both extents are fully inside boundaries. Swap it now */
tmp_ex = *ex1;
ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
ex1->ee_len = cpu_to_le16(e2_len);
ex2->ee_len = cpu_to_le16(e1_len);
if (unwritten)
ext4_ext_mark_unwritten(ex2);
if (ext4_ext_is_unwritten(&tmp_ex))
ext4_ext_mark_unwritten(ex1);
ext4_ext_try_to_merge(handle, inode2, path2, ex2);
ext4_ext_try_to_merge(handle, inode1, path1, ex1);
*erp = ext4_ext_dirty(handle, inode2, path2 +
path2->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_dirty(handle, inode1, path1 +
path1->p_depth);
/*
* Looks scarry ah..? second inode already points to new blocks,
* and it was successfully dirtied. But luckily error may happen
* only due to journal error, so full transaction will be
* aborted anyway.
*/
if (unlikely(*erp))
goto finish;
lblk1 += len;
lblk2 += len;
replaced_count += len;
count -= len;
repeat:
ext4_ext_drop_refs(path1);
kfree(path1);
ext4_ext_drop_refs(path2);
kfree(path2);
path1 = path2 = NULL;
}
return replaced_count;
}
/*
* ext4_clu_mapped - determine whether any block in a logical cluster has
* been mapped to a physical cluster
*
* @inode - file containing the logical cluster
* @lclu - logical cluster of interest
*
* Returns 1 if any block in the logical cluster is mapped, signifying
* that a physical cluster has been allocated for it. Otherwise,
* returns 0. Can also return negative error codes. Derived from
* ext4_ext_map_blocks().
*/
int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_ext_path *path;
int depth, mapped = 0, err = 0;
struct ext4_extent *extent;
ext4_lblk_t first_lblk, first_lclu, last_lclu;
/* search for the extent closest to the first block in the cluster */
path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out;
}
depth = ext_depth(inode);
/*
* A consistent leaf must not be empty. This situation is possible,
* though, _during_ tree modification, and it's why an assert can't
* be put in ext4_find_extent().
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode,
"bad extent address - lblock: %lu, depth: %d, pblock: %lld",
(unsigned long) EXT4_C2B(sbi, lclu),
depth, path[depth].p_block);
err = -EFSCORRUPTED;
goto out;
}
extent = path[depth].p_ext;
/* can't be mapped if the extent tree is empty */
if (extent == NULL)
goto out;
first_lblk = le32_to_cpu(extent->ee_block);
first_lclu = EXT4_B2C(sbi, first_lblk);
/*
* Three possible outcomes at this point - found extent spanning
* the target cluster, to the left of the target cluster, or to the
* right of the target cluster. The first two cases are handled here.
* The last case indicates the target cluster is not mapped.
*/
if (lclu >= first_lclu) {
last_lclu = EXT4_B2C(sbi, first_lblk +
ext4_ext_get_actual_len(extent) - 1);
if (lclu <= last_lclu) {
mapped = 1;
} else {
first_lblk = ext4_ext_next_allocated_block(path);
first_lclu = EXT4_B2C(sbi, first_lblk);
if (lclu == first_lclu)
mapped = 1;
}
}
out:
ext4_ext_drop_refs(path);
kfree(path);
return err ? err : mapped;
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_837_0 |
crossvul-cpp_data_good_438_3 | /*
* Soft: Keepalived is a failover program for the LVS project
* <www.linuxvirtualserver.org>. It monitor & manipulate
* a loadbalanced server pool using multi-layer checks.
*
* Part: Dynamic data structure definition.
*
* Author: Alexandre Cassen, <acassen@linux-vs.org>
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com>
*/
#include "config.h"
#include <unistd.h>
#include <pwd.h>
#include "global_data.h"
#include "list.h"
#include "logger.h"
#include "parser.h"
#include "utils.h"
#include "main.h"
#include "memory.h"
#ifdef _WITH_VRRP_
#include "vrrp.h"
#include "vrrp_ipaddress.h"
#endif
#if HAVE_DECL_RLIMIT_RTTIME == 1
#include "process.h"
#endif
/* global vars */
data_t *global_data = NULL;
data_t *old_global_data = NULL;
/* Default settings */
static void
set_default_router_id(data_t *data, char *new_id)
{
if (!new_id || !new_id[0])
return;
data->router_id = MALLOC(strlen(new_id)+1);
strcpy(data->router_id, new_id);
}
static void
set_default_email_from(data_t * data, const char *hostname)
{
struct passwd *pwd = NULL;
size_t len;
if (!hostname || !hostname[0])
return;
pwd = getpwuid(getuid());
if (!pwd)
return;
len = strlen(hostname) + strlen(pwd->pw_name) + 2;
data->email_from = MALLOC(len);
if (!data->email_from)
return;
snprintf(data->email_from, len, "%s@%s", pwd->pw_name, hostname);
}
static void
set_default_smtp_connection_timeout(data_t * data)
{
data->smtp_connection_to = DEFAULT_SMTP_CONNECTION_TIMEOUT;
}
#ifdef _WITH_VRRP_
static void
set_default_mcast_group(data_t * data)
{
inet_stosockaddr(INADDR_VRRP_GROUP, 0, (struct sockaddr_storage *)&data->vrrp_mcast_group4);
inet_stosockaddr(INADDR6_VRRP_GROUP, 0, (struct sockaddr_storage *)&data->vrrp_mcast_group6);
}
static void
set_vrrp_defaults(data_t * data)
{
data->vrrp_garp_rep = VRRP_GARP_REP;
data->vrrp_garp_refresh.tv_sec = VRRP_GARP_REFRESH;
data->vrrp_garp_refresh_rep = VRRP_GARP_REFRESH_REP;
data->vrrp_garp_delay = VRRP_GARP_DELAY;
data->vrrp_garp_lower_prio_delay = PARAMETER_UNSET;
data->vrrp_garp_lower_prio_rep = PARAMETER_UNSET;
data->vrrp_lower_prio_no_advert = false;
data->vrrp_higher_prio_send_advert = false;
data->vrrp_version = VRRP_VERSION_2;
strcpy(data->vrrp_iptables_inchain, "INPUT");
#ifdef _HAVE_LIBIPSET_
data->using_ipsets = true;
strcpy(data->vrrp_ipset_address, "keepalived");
strcpy(data->vrrp_ipset_address6, "keepalived6");
strcpy(data->vrrp_ipset_address_iface6, "keepalived_if6");
#endif
data->vrrp_check_unicast_src = false;
data->vrrp_skip_check_adv_addr = false;
data->vrrp_strict = false;
}
#endif
/* email facility functions */
static void
free_email(void *data)
{
FREE(data);
}
static void
dump_email(FILE *fp, void *data)
{
char *addr = data;
conf_write(fp, " Email notification = %s", addr);
}
void
alloc_email(char *addr)
{
size_t size = strlen(addr);
char *new;
new = (char *) MALLOC(size + 1);
memcpy(new, addr, size + 1);
list_add(global_data->email, new);
}
/* data facility functions */
data_t *
alloc_global_data(void)
{
data_t *new;
if (global_data)
return global_data;
new = (data_t *) MALLOC(sizeof(data_t));
new->email = alloc_list(free_email, dump_email);
new->smtp_alert = -1;
#ifdef _WITH_VRRP_
new->smtp_alert_vrrp = -1;
#endif
#ifdef _WITH_LVS_
new->smtp_alert_checker = -1;
#endif
#ifdef _WITH_VRRP_
set_default_mcast_group(new);
set_vrrp_defaults(new);
#endif
new->notify_fifo.fd = -1;
#ifdef _WITH_VRRP_
new->vrrp_notify_fifo.fd = -1;
#if HAVE_DECL_RLIMIT_RTTIME == 1
new->vrrp_rlimit_rt = RT_RLIMIT_DEFAULT;
#endif
new->vrrp_rx_bufs_multiples = 3;
#endif
#ifdef _WITH_LVS_
new->lvs_notify_fifo.fd = -1;
#if HAVE_DECL_RLIMIT_RTTIME == 1
new->checker_rlimit_rt = RT_RLIMIT_DEFAULT;
#endif
#ifdef _WITH_BFD_
#if HAVE_DECL_RLIMIT_RTTIME == 1
new->bfd_rlimit_rt = RT_RLIMIT_DEFAULT;
#endif
#endif
#endif
#ifdef _WITH_SNMP_
if (snmp) {
#ifdef _WITH_SNMP_VRRP_
new->enable_snmp_vrrp = true;
#endif
#ifdef _WITH_SNMP_RFCV2_
new->enable_snmp_rfcv2 = true;
#endif
#ifdef _WITH_SNMP_RFCV3_
new->enable_snmp_rfcv3 = true;
#endif
#ifdef _WITH_SNMP_CHECKER_
new->enable_snmp_checker = true;
#endif
}
if (snmp_socket) {
new->snmp_socket = MALLOC(strlen(snmp_socket + 1));
strcpy(new->snmp_socket, snmp_socket);
}
#endif
#ifdef _WITH_LVS_
#ifdef _WITH_VRRP_
new->lvs_syncd.syncid = PARAMETER_UNSET;
#ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_
new->lvs_syncd.mcast_group.ss_family = AF_UNSPEC;
#endif
#endif
#endif
return new;
}
void
init_global_data(data_t * data, data_t *old_global_data)
{
/* If this is a reload and we are running in a network namespace,
* we may not be able to get local_name, so preserve it */
char unknown_name[] = "[unknown]";
/* If we are running in a network namespace, we may not be
* able to get our local name now, so re-use original */
if (old_global_data) {
data->local_name = old_global_data->local_name;
old_global_data->local_name = NULL;
}
if (!data->local_name &&
(!data->router_id ||
(data->smtp_server.ss_family &&
(!data->smtp_helo_name ||
!data->email_from)))) {
data->local_name = get_local_name();
/* If for some reason get_local_name() fails, we need to have
* some string in local_name, otherwise keepalived can segfault */
if (!data->local_name) {
data->local_name = MALLOC(sizeof(unknown_name));
strcpy(data->local_name, unknown_name);
}
}
if (!data->router_id)
set_default_router_id(data, data->local_name);
if (data->smtp_server.ss_family) {
if (!data->smtp_connection_to)
set_default_smtp_connection_timeout(data);
if (strcmp(data->local_name, unknown_name)) {
if (!data->email_from)
set_default_email_from(data, data->local_name);
if (!data->smtp_helo_name)
data->smtp_helo_name = data->local_name;
}
}
/* Check that there aren't conflicts with the notify FIFOs */
#ifdef _WITH_VRRP_
/* If the global and vrrp notify FIFOs are the same, then data will be
* duplicated on the FIFO */
if (
#ifndef _DEBUG_
prog_type == PROG_TYPE_VRRP &&
#endif
data->notify_fifo.name && data->vrrp_notify_fifo.name &&
!strcmp(data->notify_fifo.name, data->vrrp_notify_fifo.name)) {
log_message(LOG_INFO, "notify FIFO %s has been specified for global and vrrp FIFO - ignoring vrrp FIFO", data->vrrp_notify_fifo.name);
FREE_PTR(data->vrrp_notify_fifo.name);
data->vrrp_notify_fifo.name = NULL;
free_notify_script(&data->vrrp_notify_fifo.script);
}
#endif
#ifdef _WITH_LVS_
/* If the global and LVS notify FIFOs are the same, then data will be
* duplicated on the FIFO */
#ifndef _DEBUG_
if (prog_type == PROG_TYPE_CHECKER)
#endif
{
if (data->notify_fifo.name && data->lvs_notify_fifo.name &&
!strcmp(data->notify_fifo.name, data->lvs_notify_fifo.name)) {
log_message(LOG_INFO, "notify FIFO %s has been specified for global and LVS FIFO - ignoring LVS FIFO", data->lvs_notify_fifo.name);
FREE_PTR(data->lvs_notify_fifo.name);
data->lvs_notify_fifo.name = NULL;
free_notify_script(&data->lvs_notify_fifo.script);
}
#ifdef _WITH_VRRP_
/* If LVS and VRRP use the same FIFO, they cannot both have a script for the FIFO.
* Use the VRRP script and ignore the LVS script */
if (data->lvs_notify_fifo.name && data->vrrp_notify_fifo.name &&
!strcmp(data->lvs_notify_fifo.name, data->vrrp_notify_fifo.name) &&
data->lvs_notify_fifo.script &&
data->vrrp_notify_fifo.script) {
log_message(LOG_INFO, "LVS notify FIFO and vrrp FIFO are the same both with scripts - ignoring LVS FIFO script");
free_notify_script(&data->lvs_notify_fifo.script);
}
#endif
}
#endif
}
void
free_global_data(data_t * data)
{
if (!data)
return;
free_list(&data->email);
#if HAVE_DECL_CLONE_NEWNET
FREE_PTR(data->network_namespace);
#endif
FREE_PTR(data->instance_name);
FREE_PTR(data->router_id);
FREE_PTR(data->email_from);
FREE_PTR(data->smtp_helo_name);
FREE_PTR(data->local_name);
#ifdef _WITH_SNMP_
FREE_PTR(data->snmp_socket);
#endif
#if defined _WITH_LVS_ && defined _WITH_VRRP_
FREE_PTR(data->lvs_syncd.ifname);
FREE_PTR(data->lvs_syncd.vrrp_name);
#endif
FREE_PTR(data->notify_fifo.name);
free_notify_script(&data->notify_fifo.script);
#ifdef _WITH_VRRP_
FREE_PTR(data->default_ifname);
FREE_PTR(data->vrrp_notify_fifo.name);
free_notify_script(&data->vrrp_notify_fifo.script);
#endif
#ifdef _WITH_LVS_
FREE_PTR(data->lvs_notify_fifo.name);
free_notify_script(&data->lvs_notify_fifo.script);
#endif
FREE(data);
}
void
dump_global_data(FILE *fp, data_t * data)
{
#ifdef _WITH_VRRP_
char buf[64];
#endif
if (!data)
return;
conf_write(fp, "------< Global definitions >------");
#if HAVE_DECL_CLONE_NEWNET
conf_write(fp, " Network namespace = %s", data->network_namespace ? data->network_namespace : "(default)");
#endif
if (data->instance_name)
conf_write(fp, " Instance name = %s", data->instance_name);
if (data->router_id)
conf_write(fp, " Router ID = %s", data->router_id);
if (data->smtp_server.ss_family) {
conf_write(fp, " Smtp server = %s", inet_sockaddrtos(&data->smtp_server));
conf_write(fp, " Smtp server port = %u", ntohs(inet_sockaddrport(&data->smtp_server)));
}
if (data->smtp_helo_name)
conf_write(fp, " Smtp HELO name = %s" , data->smtp_helo_name);
if (data->smtp_connection_to)
conf_write(fp, " Smtp server connection timeout = %lu"
, data->smtp_connection_to / TIMER_HZ);
if (data->email_from) {
conf_write(fp, " Email notification from = %s"
, data->email_from);
dump_list(fp, data->email);
}
conf_write(fp, " Default smtp_alert = %s",
data->smtp_alert == -1 ? "unset" : data->smtp_alert ? "on" : "off");
#ifdef _WITH_VRRP_
conf_write(fp, " Default smtp_alert_vrrp = %s",
data->smtp_alert_vrrp == -1 ? "unset" : data->smtp_alert_vrrp ? "on" : "off");
#endif
#ifdef _WITH_LVS_
conf_write(fp, " Default smtp_alert_checker = %s",
data->smtp_alert_checker == -1 ? "unset" : data->smtp_alert_checker ? "on" : "off");
#endif
#ifdef _WITH_VRRP_
conf_write(fp, " Dynamic interfaces = %s", data->dynamic_interfaces ? "true" : "false");
if (data->dynamic_interfaces)
conf_write(fp, " Allow interface changes = %s", data->allow_if_changes ? "true" : "false");
if (data->no_email_faults)
conf_write(fp, " Send emails for fault transitions = off");
#endif
#ifdef _WITH_LVS_
if (data->lvs_tcp_timeout)
conf_write(fp, " LVS TCP timeout = %d", data->lvs_tcp_timeout);
if (data->lvs_tcpfin_timeout)
conf_write(fp, " LVS TCP FIN timeout = %d", data->lvs_tcpfin_timeout);
if (data->lvs_udp_timeout)
conf_write(fp, " LVS TCP timeout = %d", data->lvs_udp_timeout);
#ifdef _WITH_VRRP_
#ifndef _DEBUG_
if (prog_type == PROG_TYPE_VRRP)
#endif
conf_write(fp, " Default interface = %s", data->default_ifp ? data->default_ifp->ifname : DFLT_INT);
if (data->lvs_syncd.vrrp) {
conf_write(fp, " LVS syncd vrrp instance = %s"
, data->lvs_syncd.vrrp->iname);
if (data->lvs_syncd.ifname)
conf_write(fp, " LVS syncd interface = %s"
, data->lvs_syncd.ifname);
conf_write(fp, " LVS syncd syncid = %u"
, data->lvs_syncd.syncid);
#ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_
if (data->lvs_syncd.sync_maxlen)
conf_write(fp, " LVS syncd maxlen = %u", data->lvs_syncd.sync_maxlen);
if (data->lvs_syncd.mcast_group.ss_family != AF_UNSPEC)
conf_write(fp, " LVS mcast group %s", inet_sockaddrtos(&data->lvs_syncd.mcast_group));
if (data->lvs_syncd.mcast_port)
conf_write(fp, " LVS syncd mcast port = %d", data->lvs_syncd.mcast_port);
if (data->lvs_syncd.mcast_ttl)
conf_write(fp, " LVS syncd mcast ttl = %u", data->lvs_syncd.mcast_ttl);
#endif
}
#endif
conf_write(fp, " LVS flush = %s", data->lvs_flush ? "true" : "false");
#endif
if (data->notify_fifo.name) {
conf_write(fp, " Global notify fifo = %s", data->notify_fifo.name);
if (data->notify_fifo.script)
conf_write(fp, " Global notify fifo script = %s, uid:gid %d:%d",
cmd_str(data->notify_fifo.script),
data->notify_fifo.script->uid,
data->notify_fifo.script->gid);
}
#ifdef _WITH_VRRP_
if (data->vrrp_notify_fifo.name) {
conf_write(fp, " VRRP notify fifo = %s", data->vrrp_notify_fifo.name);
if (data->vrrp_notify_fifo.script)
conf_write(fp, " VRRP notify fifo script = %s, uid:gid %d:%d",
cmd_str(data->vrrp_notify_fifo.script),
data->vrrp_notify_fifo.script->uid,
data->vrrp_notify_fifo.script->gid);
}
#endif
#ifdef _WITH_LVS_
if (data->lvs_notify_fifo.name) {
conf_write(fp, " LVS notify fifo = %s", data->lvs_notify_fifo.name);
if (data->lvs_notify_fifo.script)
conf_write(fp, " LVS notify fifo script = %s, uid:gid %d:%d",
cmd_str(data->lvs_notify_fifo.script),
data->lvs_notify_fifo.script->uid,
data->lvs_notify_fifo.script->gid);
}
#endif
#ifdef _WITH_VRRP_
if (data->vrrp_mcast_group4.sin_family) {
conf_write(fp, " VRRP IPv4 mcast group = %s"
, inet_sockaddrtos((struct sockaddr_storage *)&data->vrrp_mcast_group4));
}
if (data->vrrp_mcast_group6.sin6_family) {
conf_write(fp, " VRRP IPv6 mcast group = %s"
, inet_sockaddrtos((struct sockaddr_storage *)&data->vrrp_mcast_group6));
}
conf_write(fp, " Gratuitous ARP delay = %u",
data->vrrp_garp_delay/TIMER_HZ);
conf_write(fp, " Gratuitous ARP repeat = %u", data->vrrp_garp_rep);
conf_write(fp, " Gratuitous ARP refresh timer = %lu",
data->vrrp_garp_refresh.tv_sec);
conf_write(fp, " Gratuitous ARP refresh repeat = %d", data->vrrp_garp_refresh_rep);
conf_write(fp, " Gratuitous ARP lower priority delay = %d", data->vrrp_garp_lower_prio_delay == PARAMETER_UNSET ? PARAMETER_UNSET : data->vrrp_garp_lower_prio_delay / TIMER_HZ);
conf_write(fp, " Gratuitous ARP lower priority repeat = %d", data->vrrp_garp_lower_prio_rep);
conf_write(fp, " Send advert after receive lower priority advert = %s", data->vrrp_lower_prio_no_advert ? "false" : "true");
conf_write(fp, " Send advert after receive higher priority advert = %s", data->vrrp_higher_prio_send_advert ? "true" : "false");
conf_write(fp, " Gratuitous ARP interval = %d", data->vrrp_garp_interval);
conf_write(fp, " Gratuitous NA interval = %d", data->vrrp_gna_interval);
conf_write(fp, " VRRP default protocol version = %d", data->vrrp_version);
if (data->vrrp_iptables_inchain[0])
conf_write(fp," Iptables input chain = %s", data->vrrp_iptables_inchain);
if (data->vrrp_iptables_outchain[0])
conf_write(fp," Iptables output chain = %s", data->vrrp_iptables_outchain);
#ifdef _HAVE_LIBIPSET_
conf_write(fp, " Using ipsets = %s", data->using_ipsets ? "true" : "false");
if (data->vrrp_ipset_address[0])
conf_write(fp," ipset IPv4 address set = %s", data->vrrp_ipset_address);
if (data->vrrp_ipset_address6[0])
conf_write(fp," ipset IPv6 address set = %s", data->vrrp_ipset_address6);
if (data->vrrp_ipset_address_iface6[0])
conf_write(fp," ipset IPv6 address,iface set = %s", data->vrrp_ipset_address_iface6);
#endif
conf_write(fp, " VRRP check unicast_src = %s", data->vrrp_check_unicast_src ? "true" : "false");
conf_write(fp, " VRRP skip check advert addresses = %s", data->vrrp_skip_check_adv_addr ? "true" : "false");
conf_write(fp, " VRRP strict mode = %s", data->vrrp_strict ? "true" : "false");
conf_write(fp, " VRRP process priority = %d", data->vrrp_process_priority);
conf_write(fp, " VRRP don't swap = %s", data->vrrp_no_swap ? "true" : "false");
#ifdef _HAVE_SCHED_RT_
conf_write(fp, " VRRP realtime priority = %u", data->vrrp_realtime_priority);
#if HAVE_DECL_RLIMIT_RTTIME
conf_write(fp, " VRRP realtime limit = %lu", data->vrrp_rlimit_rt);
#endif
#endif
#endif
#ifdef _WITH_LVS_
conf_write(fp, " Checker process priority = %d", data->checker_process_priority);
conf_write(fp, " Checker don't swap = %s", data->checker_no_swap ? "true" : "false");
#ifdef _HAVE_SCHED_RT_
conf_write(fp, " Checker realtime priority = %u", data->checker_realtime_priority);
#if HAVE_DECL_RLIMIT_RTTIME
conf_write(fp, " Checker realtime limit = %lu", data->checker_rlimit_rt);
#endif
#endif
#endif
#ifdef _WITH_BFD_
conf_write(fp, " BFD process priority = %d", data->bfd_process_priority);
conf_write(fp, " BFD don't swap = %s", data->bfd_no_swap ? "true" : "false");
#ifdef _HAVE_SCHED_RT_
conf_write(fp, " BFD realtime priority = %u", data->bfd_realtime_priority);
#if HAVE_DECL_RLIMIT_RTTIME
conf_write(fp, " BFD realtime limit = %lu", data->bfd_rlimit_rt);
#endif
#endif
#endif
#ifdef _WITH_SNMP_VRRP_
conf_write(fp, " SNMP vrrp %s", data->enable_snmp_vrrp ? "enabled" : "disabled");
#endif
#ifdef _WITH_SNMP_CHECKER_
conf_write(fp, " SNMP checker %s", data->enable_snmp_checker ? "enabled" : "disabled");
#endif
#ifdef _WITH_SNMP_RFCV2_
conf_write(fp, " SNMP RFCv2 %s", data->enable_snmp_rfcv2 ? "enabled" : "disabled");
#endif
#ifdef _WITH_SNMP_RFCV3_
conf_write(fp, " SNMP RFCv3 %s", data->enable_snmp_rfcv3 ? "enabled" : "disabled");
#endif
#ifdef _WITH_SNMP_
conf_write(fp, " SNMP traps %s", data->enable_traps ? "enabled" : "disabled");
conf_write(fp, " SNMP socket = %s", data->snmp_socket ? data->snmp_socket : "default (unix:/var/agentx/master)");
#endif
#ifdef _WITH_DBUS_
conf_write(fp, " DBus %s", data->enable_dbus ? "enabled" : "disabled");
conf_write(fp, " DBus service name = %s", data->dbus_service_name ? data->dbus_service_name : "");
#endif
conf_write(fp, " Script security %s", script_security ? "enabled" : "disabled");
conf_write(fp, " Default script uid:gid %d:%d", default_script_uid, default_script_gid);
#ifdef _WITH_VRRP_
conf_write(fp, " vrrp_netlink_cmd_rcv_bufs = %u", global_data->vrrp_netlink_cmd_rcv_bufs);
conf_write(fp, " vrrp_netlink_cmd_rcv_bufs_force = %u", global_data->vrrp_netlink_cmd_rcv_bufs_force);
conf_write(fp, " vrrp_netlink_monitor_rcv_bufs = %u", global_data->vrrp_netlink_monitor_rcv_bufs);
conf_write(fp, " vrrp_netlink_monitor_rcv_bufs_force = %u", global_data->vrrp_netlink_monitor_rcv_bufs_force);
#endif
#ifdef _WITH_LVS_
conf_write(fp, " lvs_netlink_cmd_rcv_bufs = %u", global_data->lvs_netlink_cmd_rcv_bufs);
conf_write(fp, " lvs_netlink_cmd_rcv_bufs_force = %u", global_data->lvs_netlink_cmd_rcv_bufs_force);
conf_write(fp, " lvs_netlink_monitor_rcv_bufs = %u", global_data->lvs_netlink_monitor_rcv_bufs);
conf_write(fp, " lvs_netlink_monitor_rcv_bufs_force = %u", global_data->lvs_netlink_monitor_rcv_bufs_force);
conf_write(fp, " rs_init_notifies = %u", global_data->rs_init_notifies);
conf_write(fp, " no_checker_emails = %u", global_data->no_checker_emails);
#endif
#ifdef _WITH_VRRP_
buf[0] = '\0';
if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU)
strcpy(buf, " rx_bufs_policy = MTU");
else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT)
strcpy(buf, " rx_bufs_policy = ADVERT");
else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE)
sprintf(buf, " rx_bufs_size = %lu", global_data->vrrp_rx_bufs_size);
if (buf[0])
conf_write(fp, "%s", buf);
conf_write(fp, " rx_bufs_multiples = %u", global_data->vrrp_rx_bufs_multiples);
conf_write(fp, " umask = 0%o", global_data->umask);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_438_3 |
crossvul-cpp_data_good_2559_0 | /******************************************************************************
*
* Back-end of the driver for virtual block devices. This portion of the
* driver exports a 'unified' block-device interface that can be accessed
* by any operating system that implements a compatible front end. A
* reference front-end implementation can be found in:
* drivers/block/xen-blkfront.c
*
* Copyright (c) 2003-2004, Keir Fraser & Steve Hand
* Copyright (c) 2005, Christopher Clark
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#define pr_fmt(fmt) "xen-blkback: " fmt
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <linux/bitmap.h>
#include <xen/events.h>
#include <xen/page.h>
#include <xen/xen.h>
#include <asm/xen/hypervisor.h>
#include <asm/xen/hypercall.h>
#include <xen/balloon.h>
#include <xen/grant_table.h>
#include "common.h"
/*
* Maximum number of unused free pages to keep in the internal buffer.
* Setting this to a value too low will reduce memory used in each backend,
* but can have a performance penalty.
*
* A sane value is xen_blkif_reqs * BLKIF_MAX_SEGMENTS_PER_REQUEST, but can
* be set to a lower value that might degrade performance on some intensive
* IO workloads.
*/
static int xen_blkif_max_buffer_pages = 1024;
module_param_named(max_buffer_pages, xen_blkif_max_buffer_pages, int, 0644);
MODULE_PARM_DESC(max_buffer_pages,
"Maximum number of free pages to keep in each block backend buffer");
/*
* Maximum number of grants to map persistently in blkback. For maximum
* performance this should be the total numbers of grants that can be used
* to fill the ring, but since this might become too high, specially with
* the use of indirect descriptors, we set it to a value that provides good
* performance without using too much memory.
*
* When the list of persistent grants is full we clean it up using a LRU
* algorithm.
*/
static int xen_blkif_max_pgrants = 1056;
module_param_named(max_persistent_grants, xen_blkif_max_pgrants, int, 0644);
MODULE_PARM_DESC(max_persistent_grants,
"Maximum number of grants to map persistently");
/*
* Maximum number of rings/queues blkback supports, allow as many queues as there
* are CPUs if user has not specified a value.
*/
unsigned int xenblk_max_queues;
module_param_named(max_queues, xenblk_max_queues, uint, 0644);
MODULE_PARM_DESC(max_queues,
"Maximum number of hardware queues per virtual disk." \
"By default it is the number of online CPUs.");
/*
* Maximum order of pages to be used for the shared ring between front and
* backend, 4KB page granularity is used.
*/
unsigned int xen_blkif_max_ring_order = XENBUS_MAX_RING_GRANT_ORDER;
module_param_named(max_ring_page_order, xen_blkif_max_ring_order, int, S_IRUGO);
MODULE_PARM_DESC(max_ring_page_order, "Maximum order of pages to be used for the shared ring");
/*
* The LRU mechanism to clean the lists of persistent grants needs to
* be executed periodically. The time interval between consecutive executions
* of the purge mechanism is set in ms.
*/
#define LRU_INTERVAL 100
/*
* When the persistent grants list is full we will remove unused grants
* from the list. The percent number of grants to be removed at each LRU
* execution.
*/
#define LRU_PERCENT_CLEAN 5
/* Run-time switchable: /sys/module/blkback/parameters/ */
static unsigned int log_stats;
module_param(log_stats, int, 0644);
#define BLKBACK_INVALID_HANDLE (~0)
/* Number of free pages to remove on each call to gnttab_free_pages */
#define NUM_BATCH_FREE_PAGES 10
static inline int get_free_page(struct xen_blkif_ring *ring, struct page **page)
{
unsigned long flags;
spin_lock_irqsave(&ring->free_pages_lock, flags);
if (list_empty(&ring->free_pages)) {
BUG_ON(ring->free_pages_num != 0);
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
return gnttab_alloc_pages(1, page);
}
BUG_ON(ring->free_pages_num == 0);
page[0] = list_first_entry(&ring->free_pages, struct page, lru);
list_del(&page[0]->lru);
ring->free_pages_num--;
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
return 0;
}
static inline void put_free_pages(struct xen_blkif_ring *ring, struct page **page,
int num)
{
unsigned long flags;
int i;
spin_lock_irqsave(&ring->free_pages_lock, flags);
for (i = 0; i < num; i++)
list_add(&page[i]->lru, &ring->free_pages);
ring->free_pages_num += num;
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
}
static inline void shrink_free_pagepool(struct xen_blkif_ring *ring, int num)
{
/* Remove requested pages in batches of NUM_BATCH_FREE_PAGES */
struct page *page[NUM_BATCH_FREE_PAGES];
unsigned int num_pages = 0;
unsigned long flags;
spin_lock_irqsave(&ring->free_pages_lock, flags);
while (ring->free_pages_num > num) {
BUG_ON(list_empty(&ring->free_pages));
page[num_pages] = list_first_entry(&ring->free_pages,
struct page, lru);
list_del(&page[num_pages]->lru);
ring->free_pages_num--;
if (++num_pages == NUM_BATCH_FREE_PAGES) {
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
gnttab_free_pages(num_pages, page);
spin_lock_irqsave(&ring->free_pages_lock, flags);
num_pages = 0;
}
}
spin_unlock_irqrestore(&ring->free_pages_lock, flags);
if (num_pages != 0)
gnttab_free_pages(num_pages, page);
}
#define vaddr(page) ((unsigned long)pfn_to_kaddr(page_to_pfn(page)))
static int do_block_io_op(struct xen_blkif_ring *ring);
static int dispatch_rw_block_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req);
static void make_response(struct xen_blkif_ring *ring, u64 id,
unsigned short op, int st);
#define foreach_grant_safe(pos, n, rbtree, node) \
for ((pos) = container_of(rb_first((rbtree)), typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL; \
&(pos)->node != NULL; \
(pos) = container_of(n, typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL)
/*
* We don't need locking around the persistent grant helpers
* because blkback uses a single-thread for each backend, so we
* can be sure that this functions will never be called recursively.
*
* The only exception to that is put_persistent_grant, that can be called
* from interrupt context (by xen_blkbk_unmap), so we have to use atomic
* bit operations to modify the flags of a persistent grant and to count
* the number of used grants.
*/
static int add_persistent_gnt(struct xen_blkif_ring *ring,
struct persistent_gnt *persistent_gnt)
{
struct rb_node **new = NULL, *parent = NULL;
struct persistent_gnt *this;
struct xen_blkif *blkif = ring->blkif;
if (ring->persistent_gnt_c >= xen_blkif_max_pgrants) {
if (!blkif->vbd.overflow_max_grants)
blkif->vbd.overflow_max_grants = 1;
return -EBUSY;
}
/* Figure out where to put new node */
new = &ring->persistent_gnts.rb_node;
while (*new) {
this = container_of(*new, struct persistent_gnt, node);
parent = *new;
if (persistent_gnt->gnt < this->gnt)
new = &((*new)->rb_left);
else if (persistent_gnt->gnt > this->gnt)
new = &((*new)->rb_right);
else {
pr_alert_ratelimited("trying to add a gref that's already in the tree\n");
return -EINVAL;
}
}
bitmap_zero(persistent_gnt->flags, PERSISTENT_GNT_FLAGS_SIZE);
set_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
/* Add new node and rebalance tree. */
rb_link_node(&(persistent_gnt->node), parent, new);
rb_insert_color(&(persistent_gnt->node), &ring->persistent_gnts);
ring->persistent_gnt_c++;
atomic_inc(&ring->persistent_gnt_in_use);
return 0;
}
static struct persistent_gnt *get_persistent_gnt(struct xen_blkif_ring *ring,
grant_ref_t gref)
{
struct persistent_gnt *data;
struct rb_node *node = NULL;
node = ring->persistent_gnts.rb_node;
while (node) {
data = container_of(node, struct persistent_gnt, node);
if (gref < data->gnt)
node = node->rb_left;
else if (gref > data->gnt)
node = node->rb_right;
else {
if(test_bit(PERSISTENT_GNT_ACTIVE, data->flags)) {
pr_alert_ratelimited("requesting a grant already in use\n");
return NULL;
}
set_bit(PERSISTENT_GNT_ACTIVE, data->flags);
atomic_inc(&ring->persistent_gnt_in_use);
return data;
}
}
return NULL;
}
static void put_persistent_gnt(struct xen_blkif_ring *ring,
struct persistent_gnt *persistent_gnt)
{
if(!test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
pr_alert_ratelimited("freeing a grant already unused\n");
set_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
clear_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
atomic_dec(&ring->persistent_gnt_in_use);
}
static void free_persistent_gnts(struct xen_blkif_ring *ring, struct rb_root *root,
unsigned int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
int segs_to_unmap = 0;
struct gntab_unmap_queue_data unmap_data;
unmap_data.pages = pages;
unmap_data.unmap_ops = unmap;
unmap_data.kunmap_ops = NULL;
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
(unsigned long) pfn_to_kaddr(page_to_pfn(
persistent_gnt->page)),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST ||
!rb_next(&persistent_gnt->node)) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
segs_to_unmap = 0;
}
rb_erase(&persistent_gnt->node, root);
kfree(persistent_gnt);
num--;
}
BUG_ON(num != 0);
}
void xen_blkbk_unmap_purged_grants(struct work_struct *work)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
int segs_to_unmap = 0;
struct xen_blkif_ring *ring = container_of(work, typeof(*ring), persistent_purge_work);
struct gntab_unmap_queue_data unmap_data;
unmap_data.pages = pages;
unmap_data.unmap_ops = unmap;
unmap_data.kunmap_ops = NULL;
while(!list_empty(&ring->persistent_purge_list)) {
persistent_gnt = list_first_entry(&ring->persistent_purge_list,
struct persistent_gnt,
remove_node);
list_del(&persistent_gnt->remove_node);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
vaddr(persistent_gnt->page),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
segs_to_unmap = 0;
}
kfree(persistent_gnt);
}
if (segs_to_unmap > 0) {
unmap_data.count = segs_to_unmap;
BUG_ON(gnttab_unmap_refs_sync(&unmap_data));
put_free_pages(ring, pages, segs_to_unmap);
}
}
static void purge_persistent_gnt(struct xen_blkif_ring *ring)
{
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
unsigned int num_clean, total;
bool scan_used = false, clean_used = false;
struct rb_root *root;
if (ring->persistent_gnt_c < xen_blkif_max_pgrants ||
(ring->persistent_gnt_c == xen_blkif_max_pgrants &&
!ring->blkif->vbd.overflow_max_grants)) {
goto out;
}
if (work_busy(&ring->persistent_purge_work)) {
pr_alert_ratelimited("Scheduled work from previous purge is still busy, cannot purge list\n");
goto out;
}
num_clean = (xen_blkif_max_pgrants / 100) * LRU_PERCENT_CLEAN;
num_clean = ring->persistent_gnt_c - xen_blkif_max_pgrants + num_clean;
num_clean = min(ring->persistent_gnt_c, num_clean);
if ((num_clean == 0) ||
(num_clean > (ring->persistent_gnt_c - atomic_read(&ring->persistent_gnt_in_use))))
goto out;
/*
* At this point, we can assure that there will be no calls
* to get_persistent_grant (because we are executing this code from
* xen_blkif_schedule), there can only be calls to put_persistent_gnt,
* which means that the number of currently used grants will go down,
* but never up, so we will always be able to remove the requested
* number of grants.
*/
total = num_clean;
pr_debug("Going to purge %u persistent grants\n", num_clean);
BUG_ON(!list_empty(&ring->persistent_purge_list));
root = &ring->persistent_gnts;
purge_list:
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
if (clean_used) {
clear_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
continue;
}
if (test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
continue;
if (!scan_used &&
(test_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags)))
continue;
rb_erase(&persistent_gnt->node, root);
list_add(&persistent_gnt->remove_node,
&ring->persistent_purge_list);
if (--num_clean == 0)
goto finished;
}
/*
* If we get here it means we also need to start cleaning
* grants that were used since last purge in order to cope
* with the requested num
*/
if (!scan_used && !clean_used) {
pr_debug("Still missing %u purged frames\n", num_clean);
scan_used = true;
goto purge_list;
}
finished:
if (!clean_used) {
pr_debug("Finished scanning for grants to clean, removing used flag\n");
clean_used = true;
goto purge_list;
}
ring->persistent_gnt_c -= (total - num_clean);
ring->blkif->vbd.overflow_max_grants = 0;
/* We can defer this work */
schedule_work(&ring->persistent_purge_work);
pr_debug("Purged %u/%u\n", (total - num_clean), total);
out:
return;
}
/*
* Retrieve from the 'pending_reqs' a free pending_req structure to be used.
*/
static struct pending_req *alloc_req(struct xen_blkif_ring *ring)
{
struct pending_req *req = NULL;
unsigned long flags;
spin_lock_irqsave(&ring->pending_free_lock, flags);
if (!list_empty(&ring->pending_free)) {
req = list_entry(ring->pending_free.next, struct pending_req,
free_list);
list_del(&req->free_list);
}
spin_unlock_irqrestore(&ring->pending_free_lock, flags);
return req;
}
/*
* Return the 'pending_req' structure back to the freepool. We also
* wake up the thread if it was waiting for a free page.
*/
static void free_req(struct xen_blkif_ring *ring, struct pending_req *req)
{
unsigned long flags;
int was_empty;
spin_lock_irqsave(&ring->pending_free_lock, flags);
was_empty = list_empty(&ring->pending_free);
list_add(&req->free_list, &ring->pending_free);
spin_unlock_irqrestore(&ring->pending_free_lock, flags);
if (was_empty)
wake_up(&ring->pending_free_wq);
}
/*
* Routines for managing virtual block devices (vbds).
*/
static int xen_vbd_translate(struct phys_req *req, struct xen_blkif *blkif,
int operation)
{
struct xen_vbd *vbd = &blkif->vbd;
int rc = -EACCES;
if ((operation != REQ_OP_READ) && vbd->readonly)
goto out;
if (likely(req->nr_sects)) {
blkif_sector_t end = req->sector_number + req->nr_sects;
if (unlikely(end < req->sector_number))
goto out;
if (unlikely(end > vbd_sz(vbd)))
goto out;
}
req->dev = vbd->pdevice;
req->bdev = vbd->bdev;
rc = 0;
out:
return rc;
}
static void xen_vbd_resize(struct xen_blkif *blkif)
{
struct xen_vbd *vbd = &blkif->vbd;
struct xenbus_transaction xbt;
int err;
struct xenbus_device *dev = xen_blkbk_xenbus(blkif->be);
unsigned long long new_size = vbd_sz(vbd);
pr_info("VBD Resize: Domid: %d, Device: (%d, %d)\n",
blkif->domid, MAJOR(vbd->pdevice), MINOR(vbd->pdevice));
pr_info("VBD Resize: new size %llu\n", new_size);
vbd->size = new_size;
again:
err = xenbus_transaction_start(&xbt);
if (err) {
pr_warn("Error starting transaction\n");
return;
}
err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
(unsigned long long)vbd_sz(vbd));
if (err) {
pr_warn("Error writing new size\n");
goto abort;
}
/*
* Write the current state; we will use this to synchronize
* the front-end. If the current state is "connected" the
* front-end will get the new size information online.
*/
err = xenbus_printf(xbt, dev->nodename, "state", "%d", dev->state);
if (err) {
pr_warn("Error writing the state\n");
goto abort;
}
err = xenbus_transaction_end(xbt, 0);
if (err == -EAGAIN)
goto again;
if (err)
pr_warn("Error ending transaction\n");
return;
abort:
xenbus_transaction_end(xbt, 1);
}
/*
* Notification from the guest OS.
*/
static void blkif_notify_work(struct xen_blkif_ring *ring)
{
ring->waiting_reqs = 1;
wake_up(&ring->wq);
}
irqreturn_t xen_blkif_be_int(int irq, void *dev_id)
{
blkif_notify_work(dev_id);
return IRQ_HANDLED;
}
/*
* SCHEDULER FUNCTIONS
*/
static void print_stats(struct xen_blkif_ring *ring)
{
pr_info("(%s): oo %3llu | rd %4llu | wr %4llu | f %4llu"
" | ds %4llu | pg: %4u/%4d\n",
current->comm, ring->st_oo_req,
ring->st_rd_req, ring->st_wr_req,
ring->st_f_req, ring->st_ds_req,
ring->persistent_gnt_c,
xen_blkif_max_pgrants);
ring->st_print = jiffies + msecs_to_jiffies(10 * 1000);
ring->st_rd_req = 0;
ring->st_wr_req = 0;
ring->st_oo_req = 0;
ring->st_ds_req = 0;
}
int xen_blkif_schedule(void *arg)
{
struct xen_blkif_ring *ring = arg;
struct xen_blkif *blkif = ring->blkif;
struct xen_vbd *vbd = &blkif->vbd;
unsigned long timeout;
int ret;
set_freezable();
while (!kthread_should_stop()) {
if (try_to_freeze())
continue;
if (unlikely(vbd->size != vbd_sz(vbd)))
xen_vbd_resize(blkif);
timeout = msecs_to_jiffies(LRU_INTERVAL);
timeout = wait_event_interruptible_timeout(
ring->wq,
ring->waiting_reqs || kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
timeout = wait_event_interruptible_timeout(
ring->pending_free_wq,
!list_empty(&ring->pending_free) ||
kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
ring->waiting_reqs = 0;
smp_mb(); /* clear flag *before* checking for work */
ret = do_block_io_op(ring);
if (ret > 0)
ring->waiting_reqs = 1;
if (ret == -EACCES)
wait_event_interruptible(ring->shutdown_wq,
kthread_should_stop());
purge_gnt_list:
if (blkif->vbd.feature_gnt_persistent &&
time_after(jiffies, ring->next_lru)) {
purge_persistent_gnt(ring);
ring->next_lru = jiffies + msecs_to_jiffies(LRU_INTERVAL);
}
/* Shrink if we have more than xen_blkif_max_buffer_pages */
shrink_free_pagepool(ring, xen_blkif_max_buffer_pages);
if (log_stats && time_after(jiffies, ring->st_print))
print_stats(ring);
}
/* Drain pending purge work */
flush_work(&ring->persistent_purge_work);
if (log_stats)
print_stats(ring);
ring->xenblkd = NULL;
return 0;
}
/*
* Remove persistent grants and empty the pool of free pages
*/
void xen_blkbk_free_caches(struct xen_blkif_ring *ring)
{
/* Free all persistent grant pages */
if (!RB_EMPTY_ROOT(&ring->persistent_gnts))
free_persistent_gnts(ring, &ring->persistent_gnts,
ring->persistent_gnt_c);
BUG_ON(!RB_EMPTY_ROOT(&ring->persistent_gnts));
ring->persistent_gnt_c = 0;
/* Since we are shutting down remove all pages from the buffer */
shrink_free_pagepool(ring, 0 /* All */);
}
static unsigned int xen_blkbk_unmap_prepare(
struct xen_blkif_ring *ring,
struct grant_page **pages,
unsigned int num,
struct gnttab_unmap_grant_ref *unmap_ops,
struct page **unmap_pages)
{
unsigned int i, invcount = 0;
for (i = 0; i < num; i++) {
if (pages[i]->persistent_gnt != NULL) {
put_persistent_gnt(ring, pages[i]->persistent_gnt);
continue;
}
if (pages[i]->handle == BLKBACK_INVALID_HANDLE)
continue;
unmap_pages[invcount] = pages[i]->page;
gnttab_set_unmap_op(&unmap_ops[invcount], vaddr(pages[i]->page),
GNTMAP_host_map, pages[i]->handle);
pages[i]->handle = BLKBACK_INVALID_HANDLE;
invcount++;
}
return invcount;
}
static void xen_blkbk_unmap_and_respond_callback(int result, struct gntab_unmap_queue_data *data)
{
struct pending_req *pending_req = (struct pending_req *)(data->data);
struct xen_blkif_ring *ring = pending_req->ring;
struct xen_blkif *blkif = ring->blkif;
/* BUG_ON used to reproduce existing behaviour,
but is this the best way to deal with this? */
BUG_ON(result);
put_free_pages(ring, data->pages, data->count);
make_response(ring, pending_req->id,
pending_req->operation, pending_req->status);
free_req(ring, pending_req);
/*
* Make sure the request is freed before releasing blkif,
* or there could be a race between free_req and the
* cleanup done in xen_blkif_free during shutdown.
*
* NB: The fact that we might try to wake up pending_free_wq
* before drain_complete (in case there's a drain going on)
* it's not a problem with our current implementation
* because we can assure there's no thread waiting on
* pending_free_wq if there's a drain going on, but it has
* to be taken into account if the current model is changed.
*/
if (atomic_dec_and_test(&ring->inflight) && atomic_read(&blkif->drain)) {
complete(&blkif->drain_complete);
}
xen_blkif_put(blkif);
}
static void xen_blkbk_unmap_and_respond(struct pending_req *req)
{
struct gntab_unmap_queue_data* work = &req->gnttab_unmap_data;
struct xen_blkif_ring *ring = req->ring;
struct grant_page **pages = req->segments;
unsigned int invcount;
invcount = xen_blkbk_unmap_prepare(ring, pages, req->nr_segs,
req->unmap, req->unmap_pages);
work->data = req;
work->done = xen_blkbk_unmap_and_respond_callback;
work->unmap_ops = req->unmap;
work->kunmap_ops = NULL;
work->pages = req->unmap_pages;
work->count = invcount;
gnttab_unmap_refs_async(&req->gnttab_unmap_data);
}
/*
* Unmap the grant references.
*
* This could accumulate ops up to the batch size to reduce the number
* of hypercalls, but since this is only used in error paths there's
* no real need.
*/
static void xen_blkbk_unmap(struct xen_blkif_ring *ring,
struct grant_page *pages[],
int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *unmap_pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
unsigned int invcount = 0;
int ret;
while (num) {
unsigned int batch = min(num, BLKIF_MAX_SEGMENTS_PER_REQUEST);
invcount = xen_blkbk_unmap_prepare(ring, pages, batch,
unmap, unmap_pages);
if (invcount) {
ret = gnttab_unmap_refs(unmap, NULL, unmap_pages, invcount);
BUG_ON(ret);
put_free_pages(ring, unmap_pages, invcount);
}
pages += batch;
num -= batch;
}
}
static int xen_blkbk_map(struct xen_blkif_ring *ring,
struct grant_page *pages[],
int num, bool ro)
{
struct gnttab_map_grant_ref map[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages_to_gnt[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt = NULL;
phys_addr_t addr = 0;
int i, seg_idx, new_map_idx;
int segs_to_map = 0;
int ret = 0;
int last_map = 0, map_until = 0;
int use_persistent_gnts;
struct xen_blkif *blkif = ring->blkif;
use_persistent_gnts = (blkif->vbd.feature_gnt_persistent);
/*
* Fill out preq.nr_sects with proper amount of sectors, and setup
* assign map[..] with the PFN of the page in our domain with the
* corresponding grant reference for each page.
*/
again:
for (i = map_until; i < num; i++) {
uint32_t flags;
if (use_persistent_gnts) {
persistent_gnt = get_persistent_gnt(
ring,
pages[i]->gref);
}
if (persistent_gnt) {
/*
* We are using persistent grants and
* the grant is already mapped
*/
pages[i]->page = persistent_gnt->page;
pages[i]->persistent_gnt = persistent_gnt;
} else {
if (get_free_page(ring, &pages[i]->page))
goto out_of_memory;
addr = vaddr(pages[i]->page);
pages_to_gnt[segs_to_map] = pages[i]->page;
pages[i]->persistent_gnt = NULL;
flags = GNTMAP_host_map;
if (!use_persistent_gnts && ro)
flags |= GNTMAP_readonly;
gnttab_set_map_op(&map[segs_to_map++], addr,
flags, pages[i]->gref,
blkif->domid);
}
map_until = i + 1;
if (segs_to_map == BLKIF_MAX_SEGMENTS_PER_REQUEST)
break;
}
if (segs_to_map) {
ret = gnttab_map_refs(map, NULL, pages_to_gnt, segs_to_map);
BUG_ON(ret);
}
/*
* Now swizzle the MFN in our domain with the MFN from the other domain
* so that when we access vaddr(pending_req,i) it has the contents of
* the page from the other domain.
*/
for (seg_idx = last_map, new_map_idx = 0; seg_idx < map_until; seg_idx++) {
if (!pages[seg_idx]->persistent_gnt) {
/* This is a newly mapped grant */
BUG_ON(new_map_idx >= segs_to_map);
if (unlikely(map[new_map_idx].status != 0)) {
pr_debug("invalid buffer -- could not remap it\n");
put_free_pages(ring, &pages[seg_idx]->page, 1);
pages[seg_idx]->handle = BLKBACK_INVALID_HANDLE;
ret |= 1;
goto next;
}
pages[seg_idx]->handle = map[new_map_idx].handle;
} else {
continue;
}
if (use_persistent_gnts &&
ring->persistent_gnt_c < xen_blkif_max_pgrants) {
/*
* We are using persistent grants, the grant is
* not mapped but we might have room for it.
*/
persistent_gnt = kmalloc(sizeof(struct persistent_gnt),
GFP_KERNEL);
if (!persistent_gnt) {
/*
* If we don't have enough memory to
* allocate the persistent_gnt struct
* map this grant non-persistenly
*/
goto next;
}
persistent_gnt->gnt = map[new_map_idx].ref;
persistent_gnt->handle = map[new_map_idx].handle;
persistent_gnt->page = pages[seg_idx]->page;
if (add_persistent_gnt(ring,
persistent_gnt)) {
kfree(persistent_gnt);
persistent_gnt = NULL;
goto next;
}
pages[seg_idx]->persistent_gnt = persistent_gnt;
pr_debug("grant %u added to the tree of persistent grants, using %u/%u\n",
persistent_gnt->gnt, ring->persistent_gnt_c,
xen_blkif_max_pgrants);
goto next;
}
if (use_persistent_gnts && !blkif->vbd.overflow_max_grants) {
blkif->vbd.overflow_max_grants = 1;
pr_debug("domain %u, device %#x is using maximum number of persistent grants\n",
blkif->domid, blkif->vbd.handle);
}
/*
* We could not map this grant persistently, so use it as
* a non-persistent grant.
*/
next:
new_map_idx++;
}
segs_to_map = 0;
last_map = map_until;
if (map_until != num)
goto again;
return ret;
out_of_memory:
pr_alert("%s: out of memory\n", __func__);
put_free_pages(ring, pages_to_gnt, segs_to_map);
return -ENOMEM;
}
static int xen_blkbk_map_seg(struct pending_req *pending_req)
{
int rc;
rc = xen_blkbk_map(pending_req->ring, pending_req->segments,
pending_req->nr_segs,
(pending_req->operation != BLKIF_OP_READ));
return rc;
}
static int xen_blkbk_parse_indirect(struct blkif_request *req,
struct pending_req *pending_req,
struct seg_buf seg[],
struct phys_req *preq)
{
struct grant_page **pages = pending_req->indirect_pages;
struct xen_blkif_ring *ring = pending_req->ring;
int indirect_grefs, rc, n, nseg, i;
struct blkif_request_segment *segments = NULL;
nseg = pending_req->nr_segs;
indirect_grefs = INDIRECT_PAGES(nseg);
BUG_ON(indirect_grefs > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
for (i = 0; i < indirect_grefs; i++)
pages[i]->gref = req->u.indirect.indirect_grefs[i];
rc = xen_blkbk_map(ring, pages, indirect_grefs, true);
if (rc)
goto unmap;
for (n = 0, i = 0; n < nseg; n++) {
uint8_t first_sect, last_sect;
if ((n % SEGS_PER_INDIRECT_FRAME) == 0) {
/* Map indirect segments */
if (segments)
kunmap_atomic(segments);
segments = kmap_atomic(pages[n/SEGS_PER_INDIRECT_FRAME]->page);
}
i = n % SEGS_PER_INDIRECT_FRAME;
pending_req->segments[n]->gref = segments[i].gref;
first_sect = READ_ONCE(segments[i].first_sect);
last_sect = READ_ONCE(segments[i].last_sect);
if (last_sect >= (XEN_PAGE_SIZE >> 9) || last_sect < first_sect) {
rc = -EINVAL;
goto unmap;
}
seg[n].nsec = last_sect - first_sect + 1;
seg[n].offset = first_sect << 9;
preq->nr_sects += seg[n].nsec;
}
unmap:
if (segments)
kunmap_atomic(segments);
xen_blkbk_unmap(ring, pages, indirect_grefs);
return rc;
}
static int dispatch_discard_io(struct xen_blkif_ring *ring,
struct blkif_request *req)
{
int err = 0;
int status = BLKIF_RSP_OKAY;
struct xen_blkif *blkif = ring->blkif;
struct block_device *bdev = blkif->vbd.bdev;
unsigned long secure;
struct phys_req preq;
xen_blkif_get(blkif);
preq.sector_number = req->u.discard.sector_number;
preq.nr_sects = req->u.discard.nr_sectors;
err = xen_vbd_translate(&preq, blkif, REQ_OP_WRITE);
if (err) {
pr_warn("access denied: DISCARD [%llu->%llu] on dev=%04x\n",
preq.sector_number,
preq.sector_number + preq.nr_sects, blkif->vbd.pdevice);
goto fail_response;
}
ring->st_ds_req++;
secure = (blkif->vbd.discard_secure &&
(req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?
BLKDEV_DISCARD_SECURE : 0;
err = blkdev_issue_discard(bdev, req->u.discard.sector_number,
req->u.discard.nr_sectors,
GFP_KERNEL, secure);
fail_response:
if (err == -EOPNOTSUPP) {
pr_debug("discard op failed, not supported\n");
status = BLKIF_RSP_EOPNOTSUPP;
} else if (err)
status = BLKIF_RSP_ERROR;
make_response(ring, req->u.discard.id, req->operation, status);
xen_blkif_put(blkif);
return err;
}
static int dispatch_other_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req)
{
free_req(ring, pending_req);
make_response(ring, req->u.other.id, req->operation,
BLKIF_RSP_EOPNOTSUPP);
return -EIO;
}
static void xen_blk_drain_io(struct xen_blkif_ring *ring)
{
struct xen_blkif *blkif = ring->blkif;
atomic_set(&blkif->drain, 1);
do {
if (atomic_read(&ring->inflight) == 0)
break;
wait_for_completion_interruptible_timeout(
&blkif->drain_complete, HZ);
if (!atomic_read(&blkif->drain))
break;
} while (!kthread_should_stop());
atomic_set(&blkif->drain, 0);
}
/*
* Completion callback on the bio's. Called as bh->b_end_io()
*/
static void __end_block_io_op(struct pending_req *pending_req, int error)
{
/* An error fails the entire request. */
if ((pending_req->operation == BLKIF_OP_FLUSH_DISKCACHE) &&
(error == -EOPNOTSUPP)) {
pr_debug("flush diskcache op failed, not supported\n");
xen_blkbk_flush_diskcache(XBT_NIL, pending_req->ring->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if ((pending_req->operation == BLKIF_OP_WRITE_BARRIER) &&
(error == -EOPNOTSUPP)) {
pr_debug("write barrier op failed, not supported\n");
xen_blkbk_barrier(XBT_NIL, pending_req->ring->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if (error) {
pr_debug("Buffer not up-to-date at end of operation,"
" error=%d\n", error);
pending_req->status = BLKIF_RSP_ERROR;
}
/*
* If all of the bio's have completed it is time to unmap
* the grant references associated with 'request' and provide
* the proper response on the ring.
*/
if (atomic_dec_and_test(&pending_req->pendcnt))
xen_blkbk_unmap_and_respond(pending_req);
}
/*
* bio callback.
*/
static void end_block_io_op(struct bio *bio)
{
__end_block_io_op(bio->bi_private, bio->bi_error);
bio_put(bio);
}
/*
* Function to copy the from the ring buffer the 'struct blkif_request'
* (which has the sectors we want, number of them, grant references, etc),
* and transmute it to the block API to hand it over to the proper block disk.
*/
static int
__do_block_io_op(struct xen_blkif_ring *ring)
{
union blkif_back_rings *blk_rings = &ring->blk_rings;
struct blkif_request req;
struct pending_req *pending_req;
RING_IDX rc, rp;
int more_to_do = 0;
rc = blk_rings->common.req_cons;
rp = blk_rings->common.sring->req_prod;
rmb(); /* Ensure we see queued requests up to 'rp'. */
if (RING_REQUEST_PROD_OVERFLOW(&blk_rings->common, rp)) {
rc = blk_rings->common.rsp_prod_pvt;
pr_warn("Frontend provided bogus ring requests (%d - %d = %d). Halting ring processing on dev=%04x\n",
rp, rc, rp - rc, ring->blkif->vbd.pdevice);
return -EACCES;
}
while (rc != rp) {
if (RING_REQUEST_CONS_OVERFLOW(&blk_rings->common, rc))
break;
if (kthread_should_stop()) {
more_to_do = 1;
break;
}
pending_req = alloc_req(ring);
if (NULL == pending_req) {
ring->st_oo_req++;
more_to_do = 1;
break;
}
switch (ring->blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(&req, RING_GET_REQUEST(&blk_rings->native, rc), sizeof(req));
break;
case BLKIF_PROTOCOL_X86_32:
blkif_get_x86_32_req(&req, RING_GET_REQUEST(&blk_rings->x86_32, rc));
break;
case BLKIF_PROTOCOL_X86_64:
blkif_get_x86_64_req(&req, RING_GET_REQUEST(&blk_rings->x86_64, rc));
break;
default:
BUG();
}
blk_rings->common.req_cons = ++rc; /* before make_response() */
/* Apply all sanity checks to /private copy/ of request. */
barrier();
switch (req.operation) {
case BLKIF_OP_READ:
case BLKIF_OP_WRITE:
case BLKIF_OP_WRITE_BARRIER:
case BLKIF_OP_FLUSH_DISKCACHE:
case BLKIF_OP_INDIRECT:
if (dispatch_rw_block_io(ring, &req, pending_req))
goto done;
break;
case BLKIF_OP_DISCARD:
free_req(ring, pending_req);
if (dispatch_discard_io(ring, &req))
goto done;
break;
default:
if (dispatch_other_io(ring, &req, pending_req))
goto done;
break;
}
/* Yield point for this unbounded loop. */
cond_resched();
}
done:
return more_to_do;
}
static int
do_block_io_op(struct xen_blkif_ring *ring)
{
union blkif_back_rings *blk_rings = &ring->blk_rings;
int more_to_do;
do {
more_to_do = __do_block_io_op(ring);
if (more_to_do)
break;
RING_FINAL_CHECK_FOR_REQUESTS(&blk_rings->common, more_to_do);
} while (more_to_do);
return more_to_do;
}
/*
* Transmutation of the 'struct blkif_request' to a proper 'struct bio'
* and call the 'submit_bio' to pass it to the underlying storage.
*/
static int dispatch_rw_block_io(struct xen_blkif_ring *ring,
struct blkif_request *req,
struct pending_req *pending_req)
{
struct phys_req preq;
struct seg_buf *seg = pending_req->seg;
unsigned int nseg;
struct bio *bio = NULL;
struct bio **biolist = pending_req->biolist;
int i, nbio = 0;
int operation;
int operation_flags = 0;
struct blk_plug plug;
bool drain = false;
struct grant_page **pages = pending_req->segments;
unsigned short req_operation;
req_operation = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.indirect_op : req->operation;
if ((req->operation == BLKIF_OP_INDIRECT) &&
(req_operation != BLKIF_OP_READ) &&
(req_operation != BLKIF_OP_WRITE)) {
pr_debug("Invalid indirect operation (%u)\n", req_operation);
goto fail_response;
}
switch (req_operation) {
case BLKIF_OP_READ:
ring->st_rd_req++;
operation = REQ_OP_READ;
break;
case BLKIF_OP_WRITE:
ring->st_wr_req++;
operation = REQ_OP_WRITE;
operation_flags = REQ_SYNC | REQ_IDLE;
break;
case BLKIF_OP_WRITE_BARRIER:
drain = true;
case BLKIF_OP_FLUSH_DISKCACHE:
ring->st_f_req++;
operation = REQ_OP_WRITE;
operation_flags = REQ_PREFLUSH;
break;
default:
operation = 0; /* make gcc happy */
goto fail_response;
break;
}
/* Check that the number of segments is sane. */
nseg = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.nr_segments : req->u.rw.nr_segments;
if (unlikely(nseg == 0 && operation_flags != REQ_PREFLUSH) ||
unlikely((req->operation != BLKIF_OP_INDIRECT) &&
(nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) ||
unlikely((req->operation == BLKIF_OP_INDIRECT) &&
(nseg > MAX_INDIRECT_SEGMENTS))) {
pr_debug("Bad number of segments in request (%d)\n", nseg);
/* Haven't submitted any bio's yet. */
goto fail_response;
}
preq.nr_sects = 0;
pending_req->ring = ring;
pending_req->id = req->u.rw.id;
pending_req->operation = req_operation;
pending_req->status = BLKIF_RSP_OKAY;
pending_req->nr_segs = nseg;
if (req->operation != BLKIF_OP_INDIRECT) {
preq.dev = req->u.rw.handle;
preq.sector_number = req->u.rw.sector_number;
for (i = 0; i < nseg; i++) {
pages[i]->gref = req->u.rw.seg[i].gref;
seg[i].nsec = req->u.rw.seg[i].last_sect -
req->u.rw.seg[i].first_sect + 1;
seg[i].offset = (req->u.rw.seg[i].first_sect << 9);
if ((req->u.rw.seg[i].last_sect >= (XEN_PAGE_SIZE >> 9)) ||
(req->u.rw.seg[i].last_sect <
req->u.rw.seg[i].first_sect))
goto fail_response;
preq.nr_sects += seg[i].nsec;
}
} else {
preq.dev = req->u.indirect.handle;
preq.sector_number = req->u.indirect.sector_number;
if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq))
goto fail_response;
}
if (xen_vbd_translate(&preq, ring->blkif, operation) != 0) {
pr_debug("access denied: %s of [%llu,%llu] on dev=%04x\n",
operation == REQ_OP_READ ? "read" : "write",
preq.sector_number,
preq.sector_number + preq.nr_sects,
ring->blkif->vbd.pdevice);
goto fail_response;
}
/*
* This check _MUST_ be done after xen_vbd_translate as the preq.bdev
* is set there.
*/
for (i = 0; i < nseg; i++) {
if (((int)preq.sector_number|(int)seg[i].nsec) &
((bdev_logical_block_size(preq.bdev) >> 9) - 1)) {
pr_debug("Misaligned I/O request from domain %d\n",
ring->blkif->domid);
goto fail_response;
}
}
/* Wait on all outstanding I/O's and once that has been completed
* issue the flush.
*/
if (drain)
xen_blk_drain_io(pending_req->ring);
/*
* If we have failed at this point, we need to undo the M2P override,
* set gnttab_set_unmap_op on all of the grant references and perform
* the hypercall to unmap the grants - that is all done in
* xen_blkbk_unmap.
*/
if (xen_blkbk_map_seg(pending_req))
goto fail_flush;
/*
* This corresponding xen_blkif_put is done in __end_block_io_op, or
* below (in "!bio") if we are handling a BLKIF_OP_DISCARD.
*/
xen_blkif_get(ring->blkif);
atomic_inc(&ring->inflight);
for (i = 0; i < nseg; i++) {
while ((bio == NULL) ||
(bio_add_page(bio,
pages[i]->page,
seg[i].nsec << 9,
seg[i].offset) == 0)) {
int nr_iovecs = min_t(int, (nseg-i), BIO_MAX_PAGES);
bio = bio_alloc(GFP_KERNEL, nr_iovecs);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
bio->bi_iter.bi_sector = preq.sector_number;
bio_set_op_attrs(bio, operation, operation_flags);
}
preq.sector_number += seg[i].nsec;
}
/* This will be hit if the operation was a flush or discard. */
if (!bio) {
BUG_ON(operation_flags != REQ_PREFLUSH);
bio = bio_alloc(GFP_KERNEL, 0);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
bio_set_op_attrs(bio, operation, operation_flags);
}
atomic_set(&pending_req->pendcnt, nbio);
blk_start_plug(&plug);
for (i = 0; i < nbio; i++)
submit_bio(biolist[i]);
/* Let the I/Os go.. */
blk_finish_plug(&plug);
if (operation == REQ_OP_READ)
ring->st_rd_sect += preq.nr_sects;
else if (operation == REQ_OP_WRITE)
ring->st_wr_sect += preq.nr_sects;
return 0;
fail_flush:
xen_blkbk_unmap(ring, pending_req->segments,
pending_req->nr_segs);
fail_response:
/* Haven't submitted any bio's yet. */
make_response(ring, req->u.rw.id, req_operation, BLKIF_RSP_ERROR);
free_req(ring, pending_req);
msleep(1); /* back off a bit */
return -EIO;
fail_put_bio:
for (i = 0; i < nbio; i++)
bio_put(biolist[i]);
atomic_set(&pending_req->pendcnt, 1);
__end_block_io_op(pending_req, -EINVAL);
msleep(1); /* back off a bit */
return -EIO;
}
/*
* Put a response on the ring on how the operation fared.
*/
static void make_response(struct xen_blkif_ring *ring, u64 id,
unsigned short op, int st)
{
struct blkif_response *resp;
unsigned long flags;
union blkif_back_rings *blk_rings;
int notify;
spin_lock_irqsave(&ring->blk_ring_lock, flags);
blk_rings = &ring->blk_rings;
/* Place on the response ring for the relevant domain. */
switch (ring->blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
resp = RING_GET_RESPONSE(&blk_rings->native,
blk_rings->native.rsp_prod_pvt);
break;
case BLKIF_PROTOCOL_X86_32:
resp = RING_GET_RESPONSE(&blk_rings->x86_32,
blk_rings->x86_32.rsp_prod_pvt);
break;
case BLKIF_PROTOCOL_X86_64:
resp = RING_GET_RESPONSE(&blk_rings->x86_64,
blk_rings->x86_64.rsp_prod_pvt);
break;
default:
BUG();
}
resp->id = id;
resp->operation = op;
resp->status = st;
blk_rings->common.rsp_prod_pvt++;
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blk_rings->common, notify);
spin_unlock_irqrestore(&ring->blk_ring_lock, flags);
if (notify)
notify_remote_via_irq(ring->irq);
}
static int __init xen_blkif_init(void)
{
int rc = 0;
if (!xen_domain())
return -ENODEV;
if (xen_blkif_max_ring_order > XENBUS_MAX_RING_GRANT_ORDER) {
pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
xen_blkif_max_ring_order, XENBUS_MAX_RING_GRANT_ORDER);
xen_blkif_max_ring_order = XENBUS_MAX_RING_GRANT_ORDER;
}
if (xenblk_max_queues == 0)
xenblk_max_queues = num_online_cpus();
rc = xen_blkif_interface_init();
if (rc)
goto failed_init;
rc = xen_blkif_xenbus_init();
if (rc)
goto failed_init;
failed_init:
return rc;
}
module_init(xen_blkif_init);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_ALIAS("xen-backend:vbd");
| ./CrossVul/dataset_final_sorted/CWE-200/c/good_2559_0 |
crossvul-cpp_data_bad_3837_0 | /*
RFCOMM implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* RFCOMM TTY.
*/
#include <linux/module.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/rfcomm.h>
#define RFCOMM_TTY_MAGIC 0x6d02 /* magic number for rfcomm struct */
#define RFCOMM_TTY_PORTS RFCOMM_MAX_DEV /* whole lotta rfcomm devices */
#define RFCOMM_TTY_MAJOR 216 /* device node major id of the usb/bluetooth.c driver */
#define RFCOMM_TTY_MINOR 0
static struct tty_driver *rfcomm_tty_driver;
struct rfcomm_dev {
struct tty_port port;
struct list_head list;
char name[12];
int id;
unsigned long flags;
int err;
bdaddr_t src;
bdaddr_t dst;
u8 channel;
uint modem_status;
struct rfcomm_dlc *dlc;
wait_queue_head_t wait;
struct device *tty_dev;
atomic_t wmem_alloc;
struct sk_buff_head pending;
};
static LIST_HEAD(rfcomm_dev_list);
static DEFINE_SPINLOCK(rfcomm_dev_lock);
static void rfcomm_dev_data_ready(struct rfcomm_dlc *dlc, struct sk_buff *skb);
static void rfcomm_dev_state_change(struct rfcomm_dlc *dlc, int err);
static void rfcomm_dev_modem_status(struct rfcomm_dlc *dlc, u8 v24_sig);
/* ---- Device functions ---- */
/*
* The reason this isn't actually a race, as you no doubt have a little voice
* screaming at you in your head, is that the refcount should never actually
* reach zero unless the device has already been taken off the list, in
* rfcomm_dev_del(). And if that's not true, we'll hit the BUG() in
* rfcomm_dev_destruct() anyway.
*/
static void rfcomm_dev_destruct(struct tty_port *port)
{
struct rfcomm_dev *dev = container_of(port, struct rfcomm_dev, port);
struct rfcomm_dlc *dlc = dev->dlc;
BT_DBG("dev %p dlc %p", dev, dlc);
/* Refcount should only hit zero when called from rfcomm_dev_del()
which will have taken us off the list. Everything else are
refcounting bugs. */
BUG_ON(!list_empty(&dev->list));
rfcomm_dlc_lock(dlc);
/* Detach DLC if it's owned by this dev */
if (dlc->owner == dev)
dlc->owner = NULL;
rfcomm_dlc_unlock(dlc);
rfcomm_dlc_put(dlc);
tty_unregister_device(rfcomm_tty_driver, dev->id);
kfree(dev);
/* It's safe to call module_put() here because socket still
holds reference to this module. */
module_put(THIS_MODULE);
}
static const struct tty_port_operations rfcomm_port_ops = {
.destruct = rfcomm_dev_destruct,
};
static struct rfcomm_dev *__rfcomm_dev_get(int id)
{
struct rfcomm_dev *dev;
list_for_each_entry(dev, &rfcomm_dev_list, list)
if (dev->id == id)
return dev;
return NULL;
}
static struct rfcomm_dev *rfcomm_dev_get(int id)
{
struct rfcomm_dev *dev;
spin_lock(&rfcomm_dev_lock);
dev = __rfcomm_dev_get(id);
if (dev) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
dev = NULL;
else
tty_port_get(&dev->port);
}
spin_unlock(&rfcomm_dev_lock);
return dev;
}
static struct device *rfcomm_get_device(struct rfcomm_dev *dev)
{
struct hci_dev *hdev;
struct hci_conn *conn;
hdev = hci_get_route(&dev->dst, &dev->src);
if (!hdev)
return NULL;
conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &dev->dst);
hci_dev_put(hdev);
return conn ? &conn->dev : NULL;
}
static ssize_t show_address(struct device *tty_dev, struct device_attribute *attr, char *buf)
{
struct rfcomm_dev *dev = dev_get_drvdata(tty_dev);
return sprintf(buf, "%s\n", batostr(&dev->dst));
}
static ssize_t show_channel(struct device *tty_dev, struct device_attribute *attr, char *buf)
{
struct rfcomm_dev *dev = dev_get_drvdata(tty_dev);
return sprintf(buf, "%d\n", dev->channel);
}
static DEVICE_ATTR(address, S_IRUGO, show_address, NULL);
static DEVICE_ATTR(channel, S_IRUGO, show_channel, NULL);
static int rfcomm_dev_add(struct rfcomm_dev_req *req, struct rfcomm_dlc *dlc)
{
struct rfcomm_dev *dev, *entry;
struct list_head *head = &rfcomm_dev_list;
int err = 0;
BT_DBG("id %d channel %d", req->dev_id, req->channel);
dev = kzalloc(sizeof(struct rfcomm_dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
spin_lock(&rfcomm_dev_lock);
if (req->dev_id < 0) {
dev->id = 0;
list_for_each_entry(entry, &rfcomm_dev_list, list) {
if (entry->id != dev->id)
break;
dev->id++;
head = &entry->list;
}
} else {
dev->id = req->dev_id;
list_for_each_entry(entry, &rfcomm_dev_list, list) {
if (entry->id == dev->id) {
err = -EADDRINUSE;
goto out;
}
if (entry->id > dev->id - 1)
break;
head = &entry->list;
}
}
if ((dev->id < 0) || (dev->id > RFCOMM_MAX_DEV - 1)) {
err = -ENFILE;
goto out;
}
sprintf(dev->name, "rfcomm%d", dev->id);
list_add(&dev->list, head);
bacpy(&dev->src, &req->src);
bacpy(&dev->dst, &req->dst);
dev->channel = req->channel;
dev->flags = req->flags &
((1 << RFCOMM_RELEASE_ONHUP) | (1 << RFCOMM_REUSE_DLC));
tty_port_init(&dev->port);
dev->port.ops = &rfcomm_port_ops;
init_waitqueue_head(&dev->wait);
skb_queue_head_init(&dev->pending);
rfcomm_dlc_lock(dlc);
if (req->flags & (1 << RFCOMM_REUSE_DLC)) {
struct sock *sk = dlc->owner;
struct sk_buff *skb;
BUG_ON(!sk);
rfcomm_dlc_throttle(dlc);
while ((skb = skb_dequeue(&sk->sk_receive_queue))) {
skb_orphan(skb);
skb_queue_tail(&dev->pending, skb);
atomic_sub(skb->len, &sk->sk_rmem_alloc);
}
}
dlc->data_ready = rfcomm_dev_data_ready;
dlc->state_change = rfcomm_dev_state_change;
dlc->modem_status = rfcomm_dev_modem_status;
dlc->owner = dev;
dev->dlc = dlc;
rfcomm_dev_modem_status(dlc, dlc->remote_v24_sig);
rfcomm_dlc_unlock(dlc);
/* It's safe to call __module_get() here because socket already
holds reference to this module. */
__module_get(THIS_MODULE);
out:
spin_unlock(&rfcomm_dev_lock);
if (err < 0)
goto free;
dev->tty_dev = tty_register_device(rfcomm_tty_driver, dev->id, NULL);
if (IS_ERR(dev->tty_dev)) {
err = PTR_ERR(dev->tty_dev);
list_del(&dev->list);
goto free;
}
dev_set_drvdata(dev->tty_dev, dev);
if (device_create_file(dev->tty_dev, &dev_attr_address) < 0)
BT_ERR("Failed to create address attribute");
if (device_create_file(dev->tty_dev, &dev_attr_channel) < 0)
BT_ERR("Failed to create channel attribute");
return dev->id;
free:
kfree(dev);
return err;
}
static void rfcomm_dev_del(struct rfcomm_dev *dev)
{
unsigned long flags;
BT_DBG("dev %p", dev);
BUG_ON(test_and_set_bit(RFCOMM_TTY_RELEASED, &dev->flags));
spin_lock_irqsave(&dev->port.lock, flags);
if (dev->port.count > 0) {
spin_unlock_irqrestore(&dev->port.lock, flags);
return;
}
spin_unlock_irqrestore(&dev->port.lock, flags);
spin_lock(&rfcomm_dev_lock);
list_del_init(&dev->list);
spin_unlock(&rfcomm_dev_lock);
tty_port_put(&dev->port);
}
/* ---- Send buffer ---- */
static inline unsigned int rfcomm_room(struct rfcomm_dlc *dlc)
{
/* We can't let it be zero, because we don't get a callback
when tx_credits becomes nonzero, hence we'd never wake up */
return dlc->mtu * (dlc->tx_credits?:1);
}
static void rfcomm_wfree(struct sk_buff *skb)
{
struct rfcomm_dev *dev = (void *) skb->sk;
struct tty_struct *tty = dev->port.tty;
atomic_sub(skb->truesize, &dev->wmem_alloc);
if (test_bit(RFCOMM_TTY_ATTACHED, &dev->flags) && tty)
tty_wakeup(tty);
tty_port_put(&dev->port);
}
static void rfcomm_set_owner_w(struct sk_buff *skb, struct rfcomm_dev *dev)
{
tty_port_get(&dev->port);
atomic_add(skb->truesize, &dev->wmem_alloc);
skb->sk = (void *) dev;
skb->destructor = rfcomm_wfree;
}
static struct sk_buff *rfcomm_wmalloc(struct rfcomm_dev *dev, unsigned long size, gfp_t priority)
{
if (atomic_read(&dev->wmem_alloc) < rfcomm_room(dev->dlc)) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
rfcomm_set_owner_w(skb, dev);
return skb;
}
}
return NULL;
}
/* ---- Device IOCTLs ---- */
#define NOCAP_FLAGS ((1 << RFCOMM_REUSE_DLC) | (1 << RFCOMM_RELEASE_ONHUP))
static int rfcomm_create_dev(struct sock *sk, void __user *arg)
{
struct rfcomm_dev_req req;
struct rfcomm_dlc *dlc;
int id;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
BT_DBG("sk %p dev_id %d flags 0x%x", sk, req.dev_id, req.flags);
if (req.flags != NOCAP_FLAGS && !capable(CAP_NET_ADMIN))
return -EPERM;
if (req.flags & (1 << RFCOMM_REUSE_DLC)) {
/* Socket must be connected */
if (sk->sk_state != BT_CONNECTED)
return -EBADFD;
dlc = rfcomm_pi(sk)->dlc;
rfcomm_dlc_hold(dlc);
} else {
dlc = rfcomm_dlc_alloc(GFP_KERNEL);
if (!dlc)
return -ENOMEM;
}
id = rfcomm_dev_add(&req, dlc);
if (id < 0) {
rfcomm_dlc_put(dlc);
return id;
}
if (req.flags & (1 << RFCOMM_REUSE_DLC)) {
/* DLC is now used by device.
* Socket must be disconnected */
sk->sk_state = BT_CLOSED;
}
return id;
}
static int rfcomm_release_dev(void __user *arg)
{
struct rfcomm_dev_req req;
struct rfcomm_dev *dev;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
BT_DBG("dev_id %d flags 0x%x", req.dev_id, req.flags);
dev = rfcomm_dev_get(req.dev_id);
if (!dev)
return -ENODEV;
if (dev->flags != NOCAP_FLAGS && !capable(CAP_NET_ADMIN)) {
tty_port_put(&dev->port);
return -EPERM;
}
if (req.flags & (1 << RFCOMM_HANGUP_NOW))
rfcomm_dlc_close(dev->dlc, 0);
/* Shut down TTY synchronously before freeing rfcomm_dev */
if (dev->port.tty)
tty_vhangup(dev->port.tty);
if (!test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags))
rfcomm_dev_del(dev);
tty_port_put(&dev->port);
return 0;
}
static int rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kmalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 0;
}
static int rfcomm_get_dev_info(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_info di;
int err = 0;
BT_DBG("");
if (copy_from_user(&di, arg, sizeof(di)))
return -EFAULT;
dev = rfcomm_dev_get(di.id);
if (!dev)
return -ENODEV;
di.flags = dev->flags;
di.channel = dev->channel;
di.state = dev->dlc->state;
bacpy(&di.src, &dev->src);
bacpy(&di.dst, &dev->dst);
if (copy_to_user(arg, &di, sizeof(di)))
err = -EFAULT;
tty_port_put(&dev->port);
return err;
}
int rfcomm_dev_ioctl(struct sock *sk, unsigned int cmd, void __user *arg)
{
BT_DBG("cmd %d arg %p", cmd, arg);
switch (cmd) {
case RFCOMMCREATEDEV:
return rfcomm_create_dev(sk, arg);
case RFCOMMRELEASEDEV:
return rfcomm_release_dev(arg);
case RFCOMMGETDEVLIST:
return rfcomm_get_dev_list(arg);
case RFCOMMGETDEVINFO:
return rfcomm_get_dev_info(arg);
}
return -EINVAL;
}
/* ---- DLC callbacks ---- */
static void rfcomm_dev_data_ready(struct rfcomm_dlc *dlc, struct sk_buff *skb)
{
struct rfcomm_dev *dev = dlc->owner;
struct tty_struct *tty;
if (!dev) {
kfree_skb(skb);
return;
}
tty = dev->port.tty;
if (!tty || !skb_queue_empty(&dev->pending)) {
skb_queue_tail(&dev->pending, skb);
return;
}
BT_DBG("dlc %p tty %p len %d", dlc, tty, skb->len);
tty_insert_flip_string(tty, skb->data, skb->len);
tty_flip_buffer_push(tty);
kfree_skb(skb);
}
static void rfcomm_dev_state_change(struct rfcomm_dlc *dlc, int err)
{
struct rfcomm_dev *dev = dlc->owner;
if (!dev)
return;
BT_DBG("dlc %p dev %p err %d", dlc, dev, err);
dev->err = err;
wake_up_interruptible(&dev->wait);
if (dlc->state == BT_CLOSED) {
if (!dev->port.tty) {
if (test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags)) {
/* Drop DLC lock here to avoid deadlock
* 1. rfcomm_dev_get will take rfcomm_dev_lock
* but in rfcomm_dev_add there's lock order:
* rfcomm_dev_lock -> dlc lock
* 2. tty_port_put will deadlock if it's
* the last reference
*/
rfcomm_dlc_unlock(dlc);
if (rfcomm_dev_get(dev->id) == NULL) {
rfcomm_dlc_lock(dlc);
return;
}
rfcomm_dev_del(dev);
tty_port_put(&dev->port);
rfcomm_dlc_lock(dlc);
}
} else
tty_hangup(dev->port.tty);
}
}
static void rfcomm_dev_modem_status(struct rfcomm_dlc *dlc, u8 v24_sig)
{
struct rfcomm_dev *dev = dlc->owner;
if (!dev)
return;
BT_DBG("dlc %p dev %p v24_sig 0x%02x", dlc, dev, v24_sig);
if ((dev->modem_status & TIOCM_CD) && !(v24_sig & RFCOMM_V24_DV)) {
if (dev->port.tty && !C_CLOCAL(dev->port.tty))
tty_hangup(dev->port.tty);
}
dev->modem_status =
((v24_sig & RFCOMM_V24_RTC) ? (TIOCM_DSR | TIOCM_DTR) : 0) |
((v24_sig & RFCOMM_V24_RTR) ? (TIOCM_RTS | TIOCM_CTS) : 0) |
((v24_sig & RFCOMM_V24_IC) ? TIOCM_RI : 0) |
((v24_sig & RFCOMM_V24_DV) ? TIOCM_CD : 0);
}
/* ---- TTY functions ---- */
static void rfcomm_tty_copy_pending(struct rfcomm_dev *dev)
{
struct tty_struct *tty = dev->port.tty;
struct sk_buff *skb;
int inserted = 0;
if (!tty)
return;
BT_DBG("dev %p tty %p", dev, tty);
rfcomm_dlc_lock(dev->dlc);
while ((skb = skb_dequeue(&dev->pending))) {
inserted += tty_insert_flip_string(tty, skb->data, skb->len);
kfree_skb(skb);
}
rfcomm_dlc_unlock(dev->dlc);
if (inserted > 0)
tty_flip_buffer_push(tty);
}
static int rfcomm_tty_open(struct tty_struct *tty, struct file *filp)
{
DECLARE_WAITQUEUE(wait, current);
struct rfcomm_dev *dev;
struct rfcomm_dlc *dlc;
unsigned long flags;
int err, id;
id = tty->index;
BT_DBG("tty %p id %d", tty, id);
/* We don't leak this refcount. For reasons which are not entirely
clear, the TTY layer will call our ->close() method even if the
open fails. We decrease the refcount there, and decreasing it
here too would cause breakage. */
dev = rfcomm_dev_get(id);
if (!dev)
return -ENODEV;
BT_DBG("dev %p dst %s channel %d opened %d", dev, batostr(&dev->dst),
dev->channel, dev->port.count);
spin_lock_irqsave(&dev->port.lock, flags);
if (++dev->port.count > 1) {
spin_unlock_irqrestore(&dev->port.lock, flags);
return 0;
}
spin_unlock_irqrestore(&dev->port.lock, flags);
dlc = dev->dlc;
/* Attach TTY and open DLC */
rfcomm_dlc_lock(dlc);
tty->driver_data = dev;
dev->port.tty = tty;
rfcomm_dlc_unlock(dlc);
set_bit(RFCOMM_TTY_ATTACHED, &dev->flags);
err = rfcomm_dlc_open(dlc, &dev->src, &dev->dst, dev->channel);
if (err < 0)
return err;
/* Wait for DLC to connect */
add_wait_queue(&dev->wait, &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (dlc->state == BT_CLOSED) {
err = -dev->err;
break;
}
if (dlc->state == BT_CONNECTED)
break;
if (signal_pending(current)) {
err = -EINTR;
break;
}
tty_unlock();
schedule();
tty_lock();
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&dev->wait, &wait);
if (err == 0)
device_move(dev->tty_dev, rfcomm_get_device(dev),
DPM_ORDER_DEV_AFTER_PARENT);
rfcomm_tty_copy_pending(dev);
rfcomm_dlc_unthrottle(dev->dlc);
return err;
}
static void rfcomm_tty_close(struct tty_struct *tty, struct file *filp)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
unsigned long flags;
if (!dev)
return;
BT_DBG("tty %p dev %p dlc %p opened %d", tty, dev, dev->dlc,
dev->port.count);
spin_lock_irqsave(&dev->port.lock, flags);
if (!--dev->port.count) {
spin_unlock_irqrestore(&dev->port.lock, flags);
if (dev->tty_dev->parent)
device_move(dev->tty_dev, NULL, DPM_ORDER_DEV_LAST);
/* Close DLC and dettach TTY */
rfcomm_dlc_close(dev->dlc, 0);
clear_bit(RFCOMM_TTY_ATTACHED, &dev->flags);
rfcomm_dlc_lock(dev->dlc);
tty->driver_data = NULL;
dev->port.tty = NULL;
rfcomm_dlc_unlock(dev->dlc);
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags)) {
spin_lock(&rfcomm_dev_lock);
list_del_init(&dev->list);
spin_unlock(&rfcomm_dev_lock);
tty_port_put(&dev->port);
}
} else
spin_unlock_irqrestore(&dev->port.lock, flags);
tty_port_put(&dev->port);
}
static int rfcomm_tty_write(struct tty_struct *tty, const unsigned char *buf, int count)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
struct rfcomm_dlc *dlc = dev->dlc;
struct sk_buff *skb;
int err = 0, sent = 0, size;
BT_DBG("tty %p count %d", tty, count);
while (count) {
size = min_t(uint, count, dlc->mtu);
skb = rfcomm_wmalloc(dev, size + RFCOMM_SKB_RESERVE, GFP_ATOMIC);
if (!skb)
break;
skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE);
memcpy(skb_put(skb, size), buf + sent, size);
err = rfcomm_dlc_send(dlc, skb);
if (err < 0) {
kfree_skb(skb);
break;
}
sent += size;
count -= size;
}
return sent ? sent : err;
}
static int rfcomm_tty_write_room(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
int room;
BT_DBG("tty %p", tty);
if (!dev || !dev->dlc)
return 0;
room = rfcomm_room(dev->dlc) - atomic_read(&dev->wmem_alloc);
if (room < 0)
room = 0;
return room;
}
static int rfcomm_tty_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
{
BT_DBG("tty %p cmd 0x%02x", tty, cmd);
switch (cmd) {
case TCGETS:
BT_DBG("TCGETS is not supported");
return -ENOIOCTLCMD;
case TCSETS:
BT_DBG("TCSETS is not supported");
return -ENOIOCTLCMD;
case TIOCMIWAIT:
BT_DBG("TIOCMIWAIT");
break;
case TIOCGSERIAL:
BT_ERR("TIOCGSERIAL is not supported");
return -ENOIOCTLCMD;
case TIOCSSERIAL:
BT_ERR("TIOCSSERIAL is not supported");
return -ENOIOCTLCMD;
case TIOCSERGSTRUCT:
BT_ERR("TIOCSERGSTRUCT is not supported");
return -ENOIOCTLCMD;
case TIOCSERGETLSR:
BT_ERR("TIOCSERGETLSR is not supported");
return -ENOIOCTLCMD;
case TIOCSERCONFIG:
BT_ERR("TIOCSERCONFIG is not supported");
return -ENOIOCTLCMD;
default:
return -ENOIOCTLCMD; /* ioctls which we must ignore */
}
return -ENOIOCTLCMD;
}
static void rfcomm_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct ktermios *new = tty->termios;
int old_baud_rate = tty_termios_baud_rate(old);
int new_baud_rate = tty_termios_baud_rate(new);
u8 baud, data_bits, stop_bits, parity, x_on, x_off;
u16 changes = 0;
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p termios %p", tty, old);
if (!dev || !dev->dlc || !dev->dlc->session)
return;
/* Handle turning off CRTSCTS */
if ((old->c_cflag & CRTSCTS) && !(new->c_cflag & CRTSCTS))
BT_DBG("Turning off CRTSCTS unsupported");
/* Parity on/off and when on, odd/even */
if (((old->c_cflag & PARENB) != (new->c_cflag & PARENB)) ||
((old->c_cflag & PARODD) != (new->c_cflag & PARODD))) {
changes |= RFCOMM_RPN_PM_PARITY;
BT_DBG("Parity change detected.");
}
/* Mark and space parity are not supported! */
if (new->c_cflag & PARENB) {
if (new->c_cflag & PARODD) {
BT_DBG("Parity is ODD");
parity = RFCOMM_RPN_PARITY_ODD;
} else {
BT_DBG("Parity is EVEN");
parity = RFCOMM_RPN_PARITY_EVEN;
}
} else {
BT_DBG("Parity is OFF");
parity = RFCOMM_RPN_PARITY_NONE;
}
/* Setting the x_on / x_off characters */
if (old->c_cc[VSTOP] != new->c_cc[VSTOP]) {
BT_DBG("XOFF custom");
x_on = new->c_cc[VSTOP];
changes |= RFCOMM_RPN_PM_XON;
} else {
BT_DBG("XOFF default");
x_on = RFCOMM_RPN_XON_CHAR;
}
if (old->c_cc[VSTART] != new->c_cc[VSTART]) {
BT_DBG("XON custom");
x_off = new->c_cc[VSTART];
changes |= RFCOMM_RPN_PM_XOFF;
} else {
BT_DBG("XON default");
x_off = RFCOMM_RPN_XOFF_CHAR;
}
/* Handle setting of stop bits */
if ((old->c_cflag & CSTOPB) != (new->c_cflag & CSTOPB))
changes |= RFCOMM_RPN_PM_STOP;
/* POSIX does not support 1.5 stop bits and RFCOMM does not
* support 2 stop bits. So a request for 2 stop bits gets
* translated to 1.5 stop bits */
if (new->c_cflag & CSTOPB)
stop_bits = RFCOMM_RPN_STOP_15;
else
stop_bits = RFCOMM_RPN_STOP_1;
/* Handle number of data bits [5-8] */
if ((old->c_cflag & CSIZE) != (new->c_cflag & CSIZE))
changes |= RFCOMM_RPN_PM_DATA;
switch (new->c_cflag & CSIZE) {
case CS5:
data_bits = RFCOMM_RPN_DATA_5;
break;
case CS6:
data_bits = RFCOMM_RPN_DATA_6;
break;
case CS7:
data_bits = RFCOMM_RPN_DATA_7;
break;
case CS8:
data_bits = RFCOMM_RPN_DATA_8;
break;
default:
data_bits = RFCOMM_RPN_DATA_8;
break;
}
/* Handle baudrate settings */
if (old_baud_rate != new_baud_rate)
changes |= RFCOMM_RPN_PM_BITRATE;
switch (new_baud_rate) {
case 2400:
baud = RFCOMM_RPN_BR_2400;
break;
case 4800:
baud = RFCOMM_RPN_BR_4800;
break;
case 7200:
baud = RFCOMM_RPN_BR_7200;
break;
case 9600:
baud = RFCOMM_RPN_BR_9600;
break;
case 19200:
baud = RFCOMM_RPN_BR_19200;
break;
case 38400:
baud = RFCOMM_RPN_BR_38400;
break;
case 57600:
baud = RFCOMM_RPN_BR_57600;
break;
case 115200:
baud = RFCOMM_RPN_BR_115200;
break;
case 230400:
baud = RFCOMM_RPN_BR_230400;
break;
default:
/* 9600 is standard accordinag to the RFCOMM specification */
baud = RFCOMM_RPN_BR_9600;
break;
}
if (changes)
rfcomm_send_rpn(dev->dlc->session, 1, dev->dlc->dlci, baud,
data_bits, stop_bits, parity,
RFCOMM_RPN_FLOW_NONE, x_on, x_off, changes);
}
static void rfcomm_tty_throttle(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
rfcomm_dlc_throttle(dev->dlc);
}
static void rfcomm_tty_unthrottle(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
rfcomm_dlc_unthrottle(dev->dlc);
}
static int rfcomm_tty_chars_in_buffer(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
if (!dev || !dev->dlc)
return 0;
if (!skb_queue_empty(&dev->dlc->tx_queue))
return dev->dlc->mtu;
return 0;
}
static void rfcomm_tty_flush_buffer(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
if (!dev || !dev->dlc)
return;
skb_queue_purge(&dev->dlc->tx_queue);
tty_wakeup(tty);
}
static void rfcomm_tty_send_xchar(struct tty_struct *tty, char ch)
{
BT_DBG("tty %p ch %c", tty, ch);
}
static void rfcomm_tty_wait_until_sent(struct tty_struct *tty, int timeout)
{
BT_DBG("tty %p timeout %d", tty, timeout);
}
static void rfcomm_tty_hangup(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
if (!dev)
return;
rfcomm_tty_flush_buffer(tty);
if (test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags)) {
if (rfcomm_dev_get(dev->id) == NULL)
return;
rfcomm_dev_del(dev);
tty_port_put(&dev->port);
}
}
static int rfcomm_tty_tiocmget(struct tty_struct *tty)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
BT_DBG("tty %p dev %p", tty, dev);
return dev->modem_status;
}
static int rfcomm_tty_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
{
struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data;
struct rfcomm_dlc *dlc = dev->dlc;
u8 v24_sig;
BT_DBG("tty %p dev %p set 0x%02x clear 0x%02x", tty, dev, set, clear);
rfcomm_dlc_get_modem_status(dlc, &v24_sig);
if (set & TIOCM_DSR || set & TIOCM_DTR)
v24_sig |= RFCOMM_V24_RTC;
if (set & TIOCM_RTS || set & TIOCM_CTS)
v24_sig |= RFCOMM_V24_RTR;
if (set & TIOCM_RI)
v24_sig |= RFCOMM_V24_IC;
if (set & TIOCM_CD)
v24_sig |= RFCOMM_V24_DV;
if (clear & TIOCM_DSR || clear & TIOCM_DTR)
v24_sig &= ~RFCOMM_V24_RTC;
if (clear & TIOCM_RTS || clear & TIOCM_CTS)
v24_sig &= ~RFCOMM_V24_RTR;
if (clear & TIOCM_RI)
v24_sig &= ~RFCOMM_V24_IC;
if (clear & TIOCM_CD)
v24_sig &= ~RFCOMM_V24_DV;
rfcomm_dlc_set_modem_status(dlc, v24_sig);
return 0;
}
/* ---- TTY structure ---- */
static const struct tty_operations rfcomm_ops = {
.open = rfcomm_tty_open,
.close = rfcomm_tty_close,
.write = rfcomm_tty_write,
.write_room = rfcomm_tty_write_room,
.chars_in_buffer = rfcomm_tty_chars_in_buffer,
.flush_buffer = rfcomm_tty_flush_buffer,
.ioctl = rfcomm_tty_ioctl,
.throttle = rfcomm_tty_throttle,
.unthrottle = rfcomm_tty_unthrottle,
.set_termios = rfcomm_tty_set_termios,
.send_xchar = rfcomm_tty_send_xchar,
.hangup = rfcomm_tty_hangup,
.wait_until_sent = rfcomm_tty_wait_until_sent,
.tiocmget = rfcomm_tty_tiocmget,
.tiocmset = rfcomm_tty_tiocmset,
};
int __init rfcomm_init_ttys(void)
{
int error;
rfcomm_tty_driver = alloc_tty_driver(RFCOMM_TTY_PORTS);
if (!rfcomm_tty_driver)
return -ENOMEM;
rfcomm_tty_driver->driver_name = "rfcomm";
rfcomm_tty_driver->name = "rfcomm";
rfcomm_tty_driver->major = RFCOMM_TTY_MAJOR;
rfcomm_tty_driver->minor_start = RFCOMM_TTY_MINOR;
rfcomm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
rfcomm_tty_driver->subtype = SERIAL_TYPE_NORMAL;
rfcomm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
rfcomm_tty_driver->init_termios = tty_std_termios;
rfcomm_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
rfcomm_tty_driver->init_termios.c_lflag &= ~ICANON;
tty_set_operations(rfcomm_tty_driver, &rfcomm_ops);
error = tty_register_driver(rfcomm_tty_driver);
if (error) {
BT_ERR("Can't register RFCOMM TTY driver");
put_tty_driver(rfcomm_tty_driver);
return error;
}
BT_INFO("RFCOMM TTY layer initialized");
return 0;
}
void rfcomm_cleanup_ttys(void)
{
tty_unregister_driver(rfcomm_tty_driver);
put_tty_driver(rfcomm_tty_driver);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3837_0 |
crossvul-cpp_data_bad_3836_0 | /*
RFCOMM implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* RFCOMM sockets.
*/
#include <linux/export.h>
#include <linux/debugfs.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
#include <net/bluetooth/rfcomm.h>
static const struct proto_ops rfcomm_sock_ops;
static struct bt_sock_list rfcomm_sk_list = {
.lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock)
};
static void rfcomm_sock_close(struct sock *sk);
static void rfcomm_sock_kill(struct sock *sk);
/* ---- DLC callbacks ----
*
* called under rfcomm_dlc_lock()
*/
static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb)
{
struct sock *sk = d->owner;
if (!sk)
return;
atomic_add(skb->len, &sk->sk_rmem_alloc);
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, skb->len);
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
rfcomm_dlc_throttle(d);
}
static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err)
{
struct sock *sk = d->owner, *parent;
unsigned long flags;
if (!sk)
return;
BT_DBG("dlc %p state %ld err %d", d, d->state, err);
local_irq_save(flags);
bh_lock_sock(sk);
if (err)
sk->sk_err = err;
sk->sk_state = d->state;
parent = bt_sk(sk)->parent;
if (parent) {
if (d->state == BT_CLOSED) {
sock_set_flag(sk, SOCK_ZAPPED);
bt_accept_unlink(sk);
}
parent->sk_data_ready(parent, 0);
} else {
if (d->state == BT_CONNECTED)
rfcomm_session_getaddr(d->session, &bt_sk(sk)->src, NULL);
sk->sk_state_change(sk);
}
bh_unlock_sock(sk);
local_irq_restore(flags);
if (parent && sock_flag(sk, SOCK_ZAPPED)) {
/* We have to drop DLC lock here, otherwise
* rfcomm_sock_destruct() will dead lock. */
rfcomm_dlc_unlock(d);
rfcomm_sock_kill(sk);
rfcomm_dlc_lock(d);
}
}
/* ---- Socket functions ---- */
static struct sock *__rfcomm_get_sock_by_addr(u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL;
struct hlist_node *node;
sk_for_each(sk, node, &rfcomm_sk_list.head) {
if (rfcomm_pi(sk)->channel == channel &&
!bacmp(&bt_sk(sk)->src, src))
break;
}
return node ? sk : NULL;
}
/* Find socket with channel and source bdaddr.
* Returns closest match.
*/
static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL, *sk1 = NULL;
struct hlist_node *node;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, node, &rfcomm_sk_list.head) {
if (state && sk->sk_state != state)
continue;
if (rfcomm_pi(sk)->channel == channel) {
/* Exact match. */
if (!bacmp(&bt_sk(sk)->src, src))
break;
/* Closest match */
if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY))
sk1 = sk;
}
}
read_unlock(&rfcomm_sk_list.lock);
return node ? sk : sk1;
}
static void rfcomm_sock_destruct(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p dlc %p", sk, d);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
rfcomm_dlc_lock(d);
rfcomm_pi(sk)->dlc = NULL;
/* Detach DLC if it's owned by this socket */
if (d->owner == sk)
d->owner = NULL;
rfcomm_dlc_unlock(d);
rfcomm_dlc_put(d);
}
static void rfcomm_sock_cleanup_listen(struct sock *parent)
{
struct sock *sk;
BT_DBG("parent %p", parent);
/* Close not yet accepted dlcs */
while ((sk = bt_accept_dequeue(parent, NULL))) {
rfcomm_sock_close(sk);
rfcomm_sock_kill(sk);
}
parent->sk_state = BT_CLOSED;
sock_set_flag(parent, SOCK_ZAPPED);
}
/* Kill socket (only if zapped and orphan)
* Must be called on unlocked socket.
*/
static void rfcomm_sock_kill(struct sock *sk)
{
if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket)
return;
BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt));
/* Kill poor orphan */
bt_sock_unlink(&rfcomm_sk_list, sk);
sock_set_flag(sk, SOCK_DEAD);
sock_put(sk);
}
static void __rfcomm_sock_close(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket);
switch (sk->sk_state) {
case BT_LISTEN:
rfcomm_sock_cleanup_listen(sk);
break;
case BT_CONNECT:
case BT_CONNECT2:
case BT_CONFIG:
case BT_CONNECTED:
rfcomm_dlc_close(d, 0);
default:
sock_set_flag(sk, SOCK_ZAPPED);
break;
}
}
/* Close socket.
* Must be called on unlocked socket.
*/
static void rfcomm_sock_close(struct sock *sk)
{
lock_sock(sk);
__rfcomm_sock_close(sk);
release_sock(sk);
}
static void rfcomm_sock_init(struct sock *sk, struct sock *parent)
{
struct rfcomm_pinfo *pi = rfcomm_pi(sk);
BT_DBG("sk %p", sk);
if (parent) {
sk->sk_type = parent->sk_type;
pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP,
&bt_sk(parent)->flags);
pi->sec_level = rfcomm_pi(parent)->sec_level;
pi->role_switch = rfcomm_pi(parent)->role_switch;
security_sk_clone(parent, sk);
} else {
pi->dlc->defer_setup = 0;
pi->sec_level = BT_SECURITY_LOW;
pi->role_switch = 0;
}
pi->dlc->sec_level = pi->sec_level;
pi->dlc->role_switch = pi->role_switch;
}
static struct proto rfcomm_proto = {
.name = "RFCOMM",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rfcomm_pinfo)
};
static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio)
{
struct rfcomm_dlc *d;
struct sock *sk;
sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto);
if (!sk)
return NULL;
sock_init_data(sock, sk);
INIT_LIST_HEAD(&bt_sk(sk)->accept_q);
d = rfcomm_dlc_alloc(prio);
if (!d) {
sk_free(sk);
return NULL;
}
d->data_ready = rfcomm_sk_data_ready;
d->state_change = rfcomm_sk_state_change;
rfcomm_pi(sk)->dlc = d;
d->owner = sk;
sk->sk_destruct = rfcomm_sock_destruct;
sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT;
sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = proto;
sk->sk_state = BT_OPEN;
bt_sock_link(&rfcomm_sk_list, sk);
BT_DBG("sk %p", sk);
return sk;
}
static int rfcomm_sock_create(struct net *net, struct socket *sock,
int protocol, int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sock->ops = &rfcomm_sock_ops;
sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC);
if (!sk)
return -ENOMEM;
rfcomm_sock_init(sk, NULL);
return 0;
}
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %s", sk, batostr(&sa->rc_bdaddr));
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa->rc_channel && __rfcomm_get_sock_by_addr(sa->rc_channel, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&bt_sk(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int err = 0;
BT_DBG("sk %p", sk);
if (alen < sizeof(struct sockaddr_rc) ||
addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
sk->sk_state = BT_CONNECT;
bacpy(&bt_sk(sk)->dst, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
d->sec_level = rfcomm_pi(sk)->sec_level;
d->role_switch = rfcomm_pi(sk)->role_switch;
err = rfcomm_dlc_open(d, &bt_sk(sk)->src, &sa->rc_bdaddr, sa->rc_channel);
if (!err)
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
if (!rfcomm_pi(sk)->channel) {
bdaddr_t *src = &bt_sk(sk)->src;
u8 channel;
err = -EINVAL;
write_lock(&rfcomm_sk_list.lock);
for (channel = 1; channel < 31; channel++)
if (!__rfcomm_get_sock_by_addr(channel, src)) {
rfcomm_pi(sk)->channel = channel;
err = 0;
break;
}
write_unlock(&rfcomm_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *nsk;
long timeo;
int err = 0;
lock_sock(sk);
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
nsk = bt_accept_dequeue(sk, newsock);
if (nsk)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", nsk);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
sa->rc_family = AF_BLUETOOTH;
sa->rc_channel = rfcomm_pi(sk)->channel;
if (peer)
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst);
else
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src);
*len = sizeof(struct sockaddr_rc);
return 0;
}
static int rfcomm_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
struct sk_buff *skb;
int sent = 0;
if (test_bit(RFCOMM_DEFER_SETUP, &d->flags))
return -ENOTCONN;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (sk->sk_shutdown & SEND_SHUTDOWN)
return -EPIPE;
BT_DBG("sock %p, sk %p", sock, sk);
lock_sock(sk);
while (len) {
size_t size = min_t(size_t, len, d->mtu);
int err;
skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE,
msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb) {
if (sent == 0)
sent = err;
break;
}
skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE);
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
skb->priority = sk->sk_priority;
err = rfcomm_dlc_send(d, skb);
if (err < 0) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
sent += size;
len -= size;
}
release_sock(sk);
return sent;
}
static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int err = 0;
u32 opt;
BT_DBG("sk %p", sk);
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt & RFCOMM_LM_AUTH)
rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW;
if (opt & RFCOMM_LM_ENCRYPT)
rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM;
if (opt & RFCOMM_LM_SECURE)
rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH;
rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int err = 0;
size_t len;
u32 opt;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = BT_SECURITY_LOW;
len = min_t(unsigned int, sizeof(sec), optlen);
if (copy_from_user((char *) &sec, optval, len)) {
err = -EFAULT;
break;
}
if (sec.level > BT_SECURITY_HIGH) {
err = -EINVAL;
break;
}
rfcomm_pi(sk)->sec_level = sec.level;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt)
set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
else
clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct rfcomm_conninfo cinfo;
struct l2cap_conn *conn = l2cap_pi(sk)->chan->conn;
int len, err = 0;
u32 opt;
BT_DBG("sk %p", sk);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
switch (rfcomm_pi(sk)->sec_level) {
case BT_SECURITY_LOW:
opt = RFCOMM_LM_AUTH;
break;
case BT_SECURITY_MEDIUM:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT;
break;
case BT_SECURITY_HIGH:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT |
RFCOMM_LM_SECURE;
break;
default:
opt = 0;
break;
}
if (rfcomm_pi(sk)->role_switch)
opt |= RFCOMM_LM_MASTER;
if (put_user(opt, (u32 __user *) optval))
err = -EFAULT;
break;
case RFCOMM_CONNINFO:
if (sk->sk_state != BT_CONNECTED &&
!rfcomm_pi(sk)->dlc->defer_setup) {
err = -ENOTCONN;
break;
}
memset(&cinfo, 0, sizeof(cinfo));
cinfo.hci_handle = conn->hcon->handle;
memcpy(cinfo.dev_class, conn->hcon->dev_class, 3);
len = min_t(unsigned int, len, sizeof(cinfo));
if (copy_to_user(optval, (char *) &cinfo, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int len, err = 0;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = rfcomm_pi(sk)->sec_level;
len = min_t(unsigned int, len, sizeof(sec));
if (copy_to_user(optval, (char *) &sec, len))
err = -EFAULT;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk __maybe_unused = sock->sk;
int err;
BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg);
err = bt_sock_ioctl(sock, cmd, arg);
if (err == -ENOIOCTLCMD) {
#ifdef CONFIG_BT_RFCOMM_TTY
lock_sock(sk);
err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg);
release_sock(sk);
#else
err = -EOPNOTSUPP;
#endif
}
return err;
}
static int rfcomm_sock_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
lock_sock(sk);
if (!sk->sk_shutdown) {
sk->sk_shutdown = SHUTDOWN_MASK;
__rfcomm_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime)
err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime);
}
release_sock(sk);
return err;
}
static int rfcomm_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
int err;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
err = rfcomm_sock_shutdown(sock, 2);
sock_orphan(sk);
rfcomm_sock_kill(sk);
return err;
}
/* ---- RFCOMM core layer callbacks ----
*
* called under rfcomm_lock()
*/
int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d)
{
struct sock *sk, *parent;
bdaddr_t src, dst;
int result = 0;
BT_DBG("session %p channel %d", s, channel);
rfcomm_session_getaddr(s, &src, &dst);
/* Check if we have socket listening on channel */
parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src);
if (!parent)
return 0;
bh_lock_sock(parent);
/* Check for backlog size */
if (sk_acceptq_is_full(parent)) {
BT_DBG("backlog full %d", parent->sk_ack_backlog);
goto done;
}
sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC);
if (!sk)
goto done;
bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM);
rfcomm_sock_init(sk, parent);
bacpy(&bt_sk(sk)->src, &src);
bacpy(&bt_sk(sk)->dst, &dst);
rfcomm_pi(sk)->channel = channel;
sk->sk_state = BT_CONFIG;
bt_accept_enqueue(parent, sk);
/* Accept connection and return socket DLC */
*d = rfcomm_pi(sk)->dlc;
result = 1;
done:
bh_unlock_sock(parent);
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags))
parent->sk_state_change(parent);
return result;
}
static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p)
{
struct sock *sk;
struct hlist_node *node;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, node, &rfcomm_sk_list.head) {
seq_printf(f, "%s %s %d %d\n",
batostr(&bt_sk(sk)->src),
batostr(&bt_sk(sk)->dst),
sk->sk_state, rfcomm_pi(sk)->channel);
}
read_unlock(&rfcomm_sk_list.lock);
return 0;
}
static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, rfcomm_sock_debugfs_show, inode->i_private);
}
static const struct file_operations rfcomm_sock_debugfs_fops = {
.open = rfcomm_sock_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *rfcomm_sock_debugfs;
static const struct proto_ops rfcomm_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = rfcomm_sock_release,
.bind = rfcomm_sock_bind,
.connect = rfcomm_sock_connect,
.listen = rfcomm_sock_listen,
.accept = rfcomm_sock_accept,
.getname = rfcomm_sock_getname,
.sendmsg = rfcomm_sock_sendmsg,
.recvmsg = rfcomm_sock_recvmsg,
.shutdown = rfcomm_sock_shutdown,
.setsockopt = rfcomm_sock_setsockopt,
.getsockopt = rfcomm_sock_getsockopt,
.ioctl = rfcomm_sock_ioctl,
.poll = bt_sock_poll,
.socketpair = sock_no_socketpair,
.mmap = sock_no_mmap
};
static const struct net_proto_family rfcomm_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = rfcomm_sock_create
};
int __init rfcomm_init_sockets(void)
{
int err;
err = proto_register(&rfcomm_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops);
if (err < 0)
goto error;
if (bt_debugfs) {
rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444,
bt_debugfs, NULL, &rfcomm_sock_debugfs_fops);
if (!rfcomm_sock_debugfs)
BT_ERR("Failed to create RFCOMM debug file");
}
BT_INFO("RFCOMM socket layer initialized");
return 0;
error:
BT_ERR("RFCOMM socket layer registration failed");
proto_unregister(&rfcomm_proto);
return err;
}
void __exit rfcomm_cleanup_sockets(void)
{
debugfs_remove(rfcomm_sock_debugfs);
if (bt_sock_unregister(BTPROTO_RFCOMM) < 0)
BT_ERR("RFCOMM socket layer unregistration failed");
proto_unregister(&rfcomm_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-200/c/bad_3836_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.