repo_name
string | path
string | copies
string | size
string | content
string | license
string |
---|---|---|---|---|---|
isj/sigmod | admin/winning_teams/mofumofu/code/impl/ref_impl/core.cpp | 1 | 26591 | /*
* core.cpp version 1.0
* Copyright (c) 2013 KAUST - InfoCloud Group (All Rights Reserved)
* Author: Amin Allam
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "../include/core.h"
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <nmmintrin.h>
#include <pthread.h>
#include <vector>
#include <algorithm>
#include "util.h"
#include "AlignmentAllocator.h"
#include "threadsafe_queue.h"
#include "popcount.h"
#include "word.h"
#include "timsort.hpp"
#include "doc_words_vec.h"
#if 0
#include <map>
#define my_map map
#else
#include "../cpp-btree-1.0.1/btree_map.h" //from http://code.google.com/p/cpp-btree/
#define my_map btree_map
using namespace btree;
#endif
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////
//queryの文字列情報だけを取り出したもの。
class QueryStrings
{
public:
Word_32 words[MAX_QUERY_WORDS];
unsigned int words_len;
QueryStrings(){}
QueryStrings(const char* query_str)
{
words_len =0;
const char* __restrict cp = query_str;
const __m128i ws = _mm_set1_epi8('a');
const __m128i zero = _mm_setzero_si128();
//const __m128i one = _mm_set1_epi8(255);
const __m128i num = _mm_set_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0);
while (true)
{
__m128i c = _mm_loadu_si128((const __m128i* __restrict)cp);
int mask = _mm_movemask_epi8(_mm_cmpgt_epi8(ws,c));
int len;
__m128i co2;
if(mask){//15文字以下の場合
len = bsf(mask);
__m128i sc = _mm_cmpgt_epi8(_mm_shuffle_epi8(_mm_cvtsi32_si128(len),zero),num);
c= _mm_and_si128(sc,c);
co2 = zero;
}else{//16文字以上の場合
__m128i c2 = _mm_loadu_si128((const __m128i* __restrict)(cp+16));
int mask2 = _mm_movemask_epi8(_mm_cmpgt_epi8(ws,c2));
int b = bsf(mask2);
co2 = _mm_and_si128(_mm_cmpgt_epi8(_mm_shuffle_epi8(_mm_cvtsi32_si128(b),zero),num) ,c2);
len = 16+ b;
}
_mm_store_si128(words[words_len].pack_sse + 0 , c);
_mm_store_si128(words[words_len].pack_sse + 1 , _mm_insert_epi8(co2,len,15));
words_len++;
if(!cp[len])break;
cp += len+1;
}
switch (words_len)
{
case 1:
break;
case 2:
if(Word_32_length_comp_R()(words[0],words[1])){
}else{
swap(words[0],words[1]);
}
break;
case 3:
if(Word_32_length_comp_R()(words[0],words[1])){
if(Word_32_length_comp_R()(words[1],words[2])){
}else if(Word_32_length_comp_R()(words[0] , words[2])){
Word_32 t=words[0];
words[0] = words[2];
words[2] = words[1];
words[1] = t;
}else{
// words[0] = ww[0];
swap(words[1],words[2]);
}
}else{
Word_32 t =words[0];
if(Word_32_length_comp_R()(words[2] , words[1])){
words[0] = words[2];
words[2] =t;
//words[1] = ww[1];
}else if(Word_32_length_comp_R()(words[2] , words[0])){
words[0] = words[1];
words[1] = words[2];
words[2] = t;
}else{
words[0] = words[1];
words[1] = t;
// words[2] = ww[2];
}
}
default:
sort(words,words+words_len,Word_32_length_comp_R());
break;
}
}
//謎ソート(逆順にする)
MY_INLINE bool operator<(const QueryStrings& right) const
{
if(words_len< right.words_len)return true;
else if(words_len > right.words_len)return false;
for(unsigned int i=0;i<words_len;i++){
if(words[i] == right.words[i])continue;
return words[i] < right.words[i];
}
return false;
}
MY_INLINE bool operator==(const QueryStrings& right) const
{
if(words_len != right.words_len)return false;
for(unsigned int i=0;i<words_len;i++){
if(words[i] == right.words[i])continue;
return false;
}
return true;
}
};
///////////////////////////////////////////////////////////////////////////////////////////////
struct CountAlphabetPair{
unsigned int Count;
//unsigned int Alphabet;
CountAlphabetPair(){}
CountAlphabetPair(unsigned int count):Count(count){}
//CountAlphabetPair(unsigned int count,unsigned int alphabet):Count(count),Alphabet(alphabet){}
};
//typedef unsigned int CountAlphabetPair;
class WordSet{
public:
//my_map<Word_32,CountAlphabetPair,Word_32_length_comp,AlignmentAllocator<pair<const Word_32,CountAlphabetPair> > > words;
my_map<Word_8,CountAlphabetPair,less<Word_8>,AlignmentAllocator<pair<const Word_8,CountAlphabetPair> > > words8;
my_map<Word_16,CountAlphabetPair,less<Word_16>,AlignmentAllocator<pair<const Word_16,CountAlphabetPair> > > words16;
my_map<Word_32,CountAlphabetPair,less<Word_32>,AlignmentAllocator<pair<const Word_32,CountAlphabetPair> > > words32;
vector<Word_8> vec_words8;
vector<Word_16> vec_words16;
vector<Word_32> vec_words32;
bool needUpdate;
size_t vec_words_offset[3];
WordSet():words8(),words16(),words32()
,vec_words8(),vec_words16(),vec_words32(),needUpdate(true)
{
vec_words_offset[0] =vec_words_offset[1]=vec_words_offset[2]=0;
}
void add(const Word_32 &w){
if(w.word.len<=8){
auto ww = Word_8(w);
auto p = words8.find(ww);
if(p==words8.end()){
needUpdate=true;
words8.insert(make_pair(ww,CountAlphabetPair(1)));
}
else{p->second.Count++;}
}else if(w.word.len<=16){
auto ww = Word_16(w);
auto p = words16.find(ww);
if(p==words16.end()){
needUpdate=true;
words16.insert(make_pair(ww,CountAlphabetPair(1)));
}
else{p->second.Count++;}
}else{
auto p = words32.find(w);
if(p==words32.end()){
needUpdate=true;
words32.insert(make_pair(w,CountAlphabetPair(1)));
}
else{p->second.Count++;}
}
}
void remove(const Word_32 &w){
if(w.word.len<=8){
auto p =words8.find(Word_8(w));
if(p->second.Count ==1){
needUpdate=true;
words8.erase(p);
}
else{p->second.Count--;}
}else if(w.word.len<=16){
auto p =words16.find(Word_16(w));
if(p->second.Count ==1){
needUpdate=true;
words16.erase(p);
}
else{p->second.Count--;}
}else{
auto p =words32.find(w);
if(p->second.Count ==1){
needUpdate=true;
words32.erase(p);
}
else{p->second.Count--;}
}
}
void update(){
if(!needUpdate)return;
needUpdate=false;
vec_words8.clear();
vec_words16.clear();
vec_words32.clear();
for(auto itr = words8.begin();itr!= words8.end();itr++){
const auto &w = itr->first;
vec_words8.push_back(w);
}
for(auto itr = words16.begin();itr!= words16.end();itr++){
const auto &w = itr->first;
vec_words16.push_back(w);
}
for(auto itr = words32.begin();itr!= words32.end();itr++){
const auto &w = itr->first;
vec_words32.push_back(w);
}
vec_words_offset[0] = vec_words8.size();
vec_words_offset[1] = vec_words8.size() + vec_words16.size();
vec_words_offset[2] = vec_words8.size() + vec_words16.size()+ vec_words32.size();
}
};
struct QueryIDSet{
vector<QueryID> QueryIDs;
unsigned int alphabet[MAX_QUERY_WORDS];
};
struct QueryStringsAndInfo{
QueryStrings strs;
vector<QueryID> *QueryIDs;
//vector<QueryID> QueryIDs;
unsigned int alphabet[MAX_QUERY_WORDS];
unsigned int wordIndex[MAX_QUERY_WORDS];
};
class QuerySet{
my_map<QueryID,QueryStrings,less<QueryID>,AlignmentAllocator<pair<const QueryID,QueryStrings> > > raw_queries;
my_map<QueryStrings,QueryIDSet,less<QueryStrings>,AlignmentAllocator<pair<const QueryStrings,QueryIDSet> > > Compressed_Querys; //圧縮状態のQuery
public:
bool isUseWordSet,needUpdate;
vector<QueryStringsAndInfo,AlignmentAllocator<QueryStringsAndInfo> > QueryVector;
//QuerySet():isDeleted(false), raw_queries(),addedQueries(),Compressed_Querys(){ }
QuerySet():raw_queries(),Compressed_Querys() ,isUseWordSet(false),needUpdate(true),QueryVector() { }
private:
MY_INLINE void innerAdd(const QueryStrings &str,QueryID id,WordSet *wordSet){
const auto itr = Compressed_Querys.find(str);
if(itr != Compressed_Querys.end()){
itr->second.QueryIDs.push_back(id);
}else{
QueryIDSet qas;
for(unsigned int i=0U;i<str.words_len;i++){
qas.alphabet[i] = GetAlphabetSet(str.words[i]);
}
qas.QueryIDs.push_back(id);
Compressed_Querys.insert(make_pair(str, qas));
needUpdate=true;
if(wordSet!=NULL){ //新しいときだけカウント
for(auto i=0U;i<str.words_len;i++){
wordSet->add(str.words[i]);
}
}
}
}
public:
void addQuery(QueryID query_id, const char* query_str,WordSet *wordSet ){
auto q =QueryStrings(query_str);
raw_queries.insert(make_pair(query_id,q ));
innerAdd(q,query_id,wordSet);
}
//処理されたかをチェック
bool removeQuery(QueryID query_id,WordSet *wordSet){
if(raw_queries.empty())return false;
const auto itr =raw_queries.find(query_id);
if(itr == raw_queries.end())return false;
const auto d = Compressed_Querys.find(itr->second);
if(d->second.QueryIDs.size()==1){
Compressed_Querys.erase(d);
needUpdate=true;
if(wordSet!=NULL){ //新しいときだけカウント
for(auto i=0U;i<itr->second.words_len;i++){
wordSet->remove(itr->second.words[i]);
}
}
}else{
auto &arr = d->second.QueryIDs;
if(arr.size()<=32){
unsigned int i=0;
for(;arr[i] != query_id;i++){assert(i<arr.size());}
arr.erase(arr.begin()+i);
//arr[i] = arr.back();
//arr.pop_back();
}else{
arr.erase(lower_bound(arr.begin(),arr.end(),query_id));
}
}
//isDeleted=true;
raw_queries.erase(itr);
return true;
}
MY_INLINE void updateForce(const WordSet &wordSet);
MY_INLINE void update(const WordSet &wordSet)
{
if(!needUpdate)return;
updateForce(wordSet);
}
MY_INLINE void updateForce();
MY_INLINE void update()
{
if(!needUpdate){return;}
updateForce();
}
};
MY_INLINE void QuerySet::updateForce()
{
needUpdate=false;
QueryVector.clear();
//QueryVector.reserve(Compressed_Querys.size());
QueryVector.resize(Compressed_Querys.size());
int i=0;
for(auto itr = Compressed_Querys.begin();itr != Compressed_Querys.end();itr++,i++){
const auto &quer = itr->first;
QueryStringsAndInfo &info = QueryVector[i];
info.QueryIDs = &( itr->second.QueryIDs);
//info.QueryIDs.assign(itr->second.QueryIDs.begin(),itr->second.QueryIDs.end());
info.strs = quer;
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
info.alphabet[j] = itr->second.alphabet[j];
}
}
}
MY_INLINE void QuerySet::updateForce(const WordSet &wordSet)
{
needUpdate=false;
QueryVector.clear();
//QueryVector.reserve(Compressed_Querys.size());
QueryVector.resize(Compressed_Querys.size());
int i=0;
for(auto itr = Compressed_Querys.begin();itr != Compressed_Querys.end();itr++,i++){
const auto &quer = itr->first;
QueryStringsAndInfo &info = QueryVector[i];
info.QueryIDs = &( itr->second.QueryIDs);
//info.QueryIDs.assign(itr->second.QueryIDs.begin(),itr->second.QueryIDs.end());
info.strs = quer;
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
info.alphabet[j] = itr->second.alphabet[j];
const Word_32 &w = quer.words[j];
const int len = w.word.len;
long long index;
if(len<=8){
const auto &ww = wordSet.vec_words8;
index = lower_bound(ww.begin(),ww.end(),Word_8(w)) -ww.begin();
}else if(len<=16){
const auto &ww = wordSet.vec_words16;
index = lower_bound(ww.begin(),ww.end(),Word_16(w)) -ww.begin()
+ wordSet.vec_words_offset[0];
}else{
const auto &ww = wordSet.vec_words32;
index = lower_bound(ww.begin(),ww.end(),w) -ww.begin()
+ wordSet.vec_words_offset[1];
}
assert(0<=index && index < (long long)wordSet.vec_words_offset[2]);
info.wordIndex[j]=(unsigned int) index;
}
}
}
class QuerySetSet{
public:
vector<QuerySet> queries;
WordSet wordSet;
bool isUseWordSet;
QuerySetSet():queries(),wordSet(),isUseWordSet(false){}
void addQuery(unsigned int dist,QueryID query_id, const char* query_str){
if(dist!=0)dist--;
queries[dist].addQuery( query_id,query_str,isUseWordSet?&wordSet:NULL );
}
//処理されたかをチェック
bool removeQuery(QueryID query_id){
for(auto i=0U;i<queries.size();i++){
if(queries[i].removeQuery(query_id,isUseWordSet?&wordSet:NULL ))return true;
}
return false;
}
MY_INLINE void update();
};
MY_INLINE void QuerySetSet::update()
{
if(!isUseWordSet){
queries[0].update();
return;
}
if(wordSet.needUpdate){
wordSet.update();
for(auto i=0U;i<queries.size();i++)queries[i].updateForce(wordSet);
}else{
for(auto i=0U;i<queries.size();i++)queries[i].update(wordSet);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Keeps all query ID results associated with a dcoument
struct Document
{
DocID doc_id;
unsigned int num_res;
QueryID* query_ids;
};
struct DocumentInput
{
DocID doc_id;
const char* str;
DocumentInput(DocID _doc_id,const char * _str):doc_id(_doc_id),str(_str){;}
};
///////////////////////////////////////////////////////////////////////////////////////////////
//static unsigned int MY_INLINE getQueryTypeIndex( MatchType match_type, unsigned int match_dist){
// return match_type*4+ match_dist;
//}
//static const int activeQueryTypeIndex[]={0,5,6,7,9,10,11};
// Keeps all currently active queries
static const unsigned int MAX_QUERY_SET = 3*4;
typedef vector<Word_32,AlignmentAllocator<Word_32> > doc_words_type;
class calc_class{
DocumentInput *di;
const vector<QuerySetSet> *queries;
vector<QueryID> query_ids;
doc_words_vec doc_words[MAX_WORD_LENGTH+1];
vector<signed char> wf;
static const char ED_YES_MATCH=1;
static const char ED_NO_MATCH=2;
MY_INLINE void getDocWordSet();
MY_INLINE void calcExact();
MY_INLINE void calcHamming();
MY_INLINE void calcED();
MY_INLINE Document returnDocument();
public:
calc_class():di(NULL),queries(NULL),query_ids(),doc_words(),wf()
{
for(int i=0;i<=MAX_WORD_LENGTH;i++){doc_words[i].setLen(i);}
}
MY_INLINE Document calc(const vector<QuerySetSet> &queries,DocumentInput & di);
};
MY_INLINE void calc_class::getDocWordSet()
{
const char* __restrict cp = &di->str[0];
const __m128i ws = _mm_set1_epi8('a');
const __m128i zero = _mm_setzero_si128();
const __m128i num = _mm_set_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0);
while (true)
{
__m128i c = _mm_loadu_si128((const __m128i* __restrict)cp);
int mask = _mm_movemask_epi8(_mm_cmpgt_epi8(ws,c));
int len;
if(mask){//15文字以下の場合
len = bsf(mask);
__m128i sc = _mm_cmpgt_epi8(_mm_shuffle_epi8(_mm_cvtsi32_si128(len),zero),num);
c= _mm_and_si128(sc,c);
Word_16 w;
w.pack_sse =c;
doc_words[len].addWordCnv8_16(w);
}else{//16文字以上の場合
__m128i c2 = _mm_loadu_si128((const __m128i* __restrict)(cp+16));
int mask2 = _mm_movemask_epi8(_mm_cmpgt_epi8(ws,c2));
int b = bsf(mask2);
__m128i co2 = _mm_and_si128(_mm_cmpgt_epi8(_mm_shuffle_epi8(_mm_cvtsi32_si128(b),zero),num) ,c2);
len = 16+ b;
Word_32 w;
w.pack_sse[0]= c;
w.pack_sse[1]= _mm_insert_epi8(co2,len,15);
doc_words[len].addWordCnv16_32(w);
}
//_mm_store_si128(w.pack_sse + 1 , co2);
if(!cp[len])break;
cp += len+1;
}
for(int i=MIN_WORD_LENGTH;i<=MAX_WORD_LENGTH;i++){doc_words[i].UniqeAndSetAlphabet();}
}
MY_INLINE void calc_class::calcExact()
{
auto const & mq = (*queries)[MT_EXACT_MATCH].queries[0];
for(auto vi =0U;vi<mq.QueryVector.size();vi++){
const auto &qq =mq.QueryVector[vi];
const auto &quer = qq.strs;
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
const Word_32 &w = quer.words[j];
if(!doc_words[w.word.len].ExactMatch(w))goto no_match_exact;
}
{
const auto &ids = *qq.QueryIDs;
query_ids.insert(query_ids.end(),ids.begin(),ids.end());
//for(unsigned int i =0;i<ids.size();i++){ query_ids.push_back(ids[i]); }
}
no_match_exact:;
}
}
MY_INLINE void calc_class::calcHamming()
{
auto const &qs = (*queries)[MT_HAMMING_DIST];
wf.assign(qs.wordSet.vec_words_offset[2],0);
for(int dist=3;dist>=1;dist--){
auto const & mq = qs.queries[dist-1];
if(mq.QueryVector.empty())continue;
for(auto vi =0U;vi<mq.QueryVector.size();vi++){
const auto &qq =mq.QueryVector[vi];
const auto &quer = qq.strs;
char state[5]={};
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
auto index = qq.wordIndex[j];
assert(0<=index && index < wf.size());
auto s = wf[index];
if(s<0)goto no_match_hamming;
state[j]=s;
}
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
assert(state[j] >=0);
if(state[j] == dist)continue;
const Word_32 &w = quer.words[j];
const int len = w.word.len;
const auto & dw = doc_words[len];
if(dw.size()>=64){ //一致文字列をまず検索
if(dw.ExactMatch(w))goto match_hamming_pre;
}
if(dist ==1){
if(dw.HammingMatch1(w,qq.alphabet[j]))goto match_hamming_pre;
}else{
if(dw.HammingMatch(w,qq.alphabet[j],dist))goto match_hamming_pre;
}
wf[qq.wordIndex[j]]=-1;
goto no_match_hamming;
match_hamming_pre:; //マッチした場合だけ処理
wf[qq.wordIndex[j]]=dist;
}
//マッチした
{
const auto &ids = *qq.QueryIDs;
query_ids.insert(query_ids.end(),ids.begin(),ids.end());
//for(unsigned int i =0;i<ids.size();i++){ query_ids.push_back(ids[i]); }
}
no_match_hamming:;
}
}
}
MY_INLINE void calc_class::calcED()
{
auto const &qs = (*queries)[MT_EDIT_DIST];
int max_word_len = MAX_WORD_LENGTH;
int min_word_len = MIN_WORD_LENGTH;
for(;doc_words[max_word_len].size()==0 && max_word_len>MIN_WORD_LENGTH;max_word_len--);
for(;doc_words[min_word_len].size()==0 && min_word_len<MAX_WORD_LENGTH;min_word_len++);
if(max_word_len < min_word_len)return; //マッチする可能性が無い
wf.assign(qs.wordSet.vec_words_offset[2],0);
for(int dist=1;dist<=3;dist++){
auto const & mq = qs.queries[dist-1];
if(mq.QueryVector.empty())continue;
for(auto vi =0U;vi<mq.QueryVector.size();vi++){
const auto &qq =mq.QueryVector[vi];
const auto &quer = qq.strs;
char state[5]={};
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
auto index = qq.wordIndex[j];
assert(0<=index && index < wf.size());
auto s = wf[index];
if(s<=-dist){goto no_match_edit;}
state[j]=s;
}
assert(quer.words_len>0);
for(unsigned int j=0;j<quer.words_len;j++){
assert(state[j]>-dist);
if(state[j] > 0){
//if(state[j]==dist)printf(".");
//else printf("#");
continue;
}
const Word_32 &w = quer.words[j];
const int len = w.word.len;
if( (len + dist >= min_word_len) &&
(len - dist <= max_word_len))
{
const unsigned int a = qq.alphabet[j];
if(true){ //一致文字列をまず検索
const auto & dw = doc_words[len];
if(dw.ExactMatch(w))goto match_edit_pre;
}
if(dist == 1){
if(doc_words[len].HammingMatch1(w,a))goto match_edit_pre;
if(len - 1 >=min_word_len){
if( doc_words[len-1].EditDistMatch1_1(w,a))goto match_edit_pre;
}
if(len+1<= max_word_len){
if( doc_words[len+1].EditDistMatch1_2(w,a))goto match_edit_pre;
}
}else{
const int s = max(min_word_len,len -(int) dist);
const int e = min(max_word_len,len +(int) dist);
assert(s<=e);
if(len <=16 && e <= 16){
const EditDistFast edf(w);
for(int r=s;r<=e;r++){
const auto & dw = doc_words[r];
if(dw.size()==0)continue;
const int d = dist*2- abs(len-r);
if(dw.EditDistMatch(edf,a,d,dist,len-r))goto match_edit_pre;
}
}else{
EditDist ed(w.word.str,len);
for(int r=s;r<=e;r++){
const auto & dw = doc_words[r];
if(dw.size()==0)continue;
const int d = dist*2- abs(len-r);
if(len<=16 && r<=16){
const EditDistFast edf(w);
if(dw.EditDistMatch(edf,a,d,dist,len-r))goto match_edit_pre;
}else{
if(dw.EditDistMatch(ed,a,d,dist))goto match_edit_pre;
}
}
}
}
}
wf[qq.wordIndex[j]]=-dist;
goto no_match_edit;
match_edit_pre:; //マッチした場合だけ処理
// wf[itr->second.wordIndex[j]]= dist;
wf[qq.wordIndex[j]]= 1;
}
//マッチした
{
const auto &ids = *qq.QueryIDs;
query_ids.insert(query_ids.end(),ids.begin(),ids.end());
//for(unsigned int i =0;i<ids.size();i++){ query_ids.push_back(ids[i]); }
}
no_match_edit:;
}
}
}
MY_INLINE Document calc_class::returnDocument()
{
Document doc;
doc.doc_id=di->doc_id;
doc.num_res = (unsigned int)query_ids.size();
doc.query_ids=NULL;
if(doc.num_res){
//gfx::timsort(query_ids.begin(),query_ids.end());
//sort(query_ids.begin(),query_ids.end());
doc.query_ids=(unsigned int*)malloc(doc.num_res*sizeof(unsigned int));
memcpy(doc.query_ids,&query_ids[0],sizeof(QueryID) * doc.num_res);
gfx::timsort(doc.query_ids,doc.query_ids+doc.num_res);
//sort(doc.query_ids,doc.query_ids+doc.num_res);
}
return doc;
}
MY_INLINE Document calc_class::calc(const vector<QuerySetSet> &queries,DocumentInput & di)
{
this->di=&di;
this->queries = &queries;
for(int i=MIN_WORD_LENGTH;i<=MAX_WORD_LENGTH;i++)doc_words[i].clear();
query_ids.clear();
getDocWordSet();
calcExact();
calcHamming();
calcED();
return returnDocument();
}
///////////////////////////////////////////////////////////////////////////////////////////////
void * work_func( void * arg );
class WorkerThread{
public:
static const int THREAD_MAX=24; //TODO :スレッド数の適正値を割り出し
pthread_t thread[THREAD_MAX];
ts_queue<DocumentInput> job_que;
ts_queue<Document> end_que;
void Create()
{
job_que = ts_queue<DocumentInput>();
end_que = ts_queue<Document>();
for(int i=0;i<THREAD_MAX;i++){
pthread_create( &thread[i], 0, work_func, this );
}
}
void Destruct()
{
for(int i=0;i<THREAD_MAX;i++){job_que.enqueue(DocumentInput(0,NULL));}
for(int i=0;i<THREAD_MAX;i++){pthread_join(thread[i],NULL);}
while(end_que.size()!=0){ //後始末
Document d = end_que.dequeue();
free(d.query_ids);
}
}
};
WorkerThread worker;
vector<QuerySetSet> g_queries;
int activeDocumentCount;
void * work_func( void * arg )
{
WorkerThread * wt = (WorkerThread *) arg;
calc_class cc;
while (true)
{
DocumentInput di = wt->job_que.dequeue();
if(di.str ==NULL) break;//スレッド終了用
Document d = cc.calc(g_queries,di);
free((char *)di.str);
wt->end_que.enqueue(d);
}
return 0;
}
ErrorCode InitializeIndex()
{
g_queries.resize(3);
g_queries[MT_EXACT_MATCH].queries.resize(1);
g_queries[MT_HAMMING_DIST].queries.resize(3);
g_queries[MT_EDIT_DIST].queries.resize(3);
g_queries[MT_EXACT_MATCH].isUseWordSet=false;
g_queries[MT_HAMMING_DIST].isUseWordSet=true;
g_queries[MT_EDIT_DIST].isUseWordSet=true;
worker.Create();
activeDocumentCount=0;
return EC_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////////////////////
ErrorCode DestroyIndex()
{
//色々開放する
worker.Destruct();
g_queries.clear();
return EC_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////////////////////
ErrorCode StartQuery(QueryID query_id, const char* query_str, MatchType match_type, unsigned int match_dist)
{
if(match_type == MT_EXACT_MATCH){match_dist = 0;}//念のため
if(match_dist == 0){match_type = MT_EXACT_MATCH;}//念のため
g_queries[match_type].addQuery(match_dist,query_id,query_str);
return EC_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////////////////////
ErrorCode EndQuery(QueryID query_id)
{
for(unsigned int i=0;i<MAX_QUERY_SET;i++){
if(g_queries[i].removeQuery(query_id)){return EC_SUCCESS;}
}
return EC_FAIL;
}
///////////////////////////////////////////////////////////////////////////////////////////////
ErrorCode MatchDocument(DocID doc_id, const char* doc_str)
{
g_queries[MT_EXACT_MATCH].update();
g_queries[MT_HAMMING_DIST].update();
g_queries[MT_EDIT_DIST].update();
char * buf = (char * )malloc(sizeof(char) * (MAX_DOC_LENGTH+32));
//アクセス範囲外にならないように多めに確保?
strcpy(buf,doc_str);
worker.job_que.enqueue(DocumentInput(doc_id,buf));
activeDocumentCount++;
return EC_SUCCESS;
}
ErrorCode GetNextAvailRes(DocID* p_doc_id, unsigned int* p_num_res, QueryID** p_query_ids)
{
*p_doc_id=0; *p_num_res=0; *p_query_ids=0;
if(activeDocumentCount==0)return EC_NO_AVAIL_RES;
Document d = worker.end_que.dequeue();
*p_doc_id = d.doc_id;*p_num_res = d.num_res;*p_query_ids = d.query_ids;
activeDocumentCount--;
return EC_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////////////////////
| bsd-2-clause |
PopCap/GameIdea | Engine/Source/Editor/UnrealEd/Private/StaticLightingSystem/StaticLightingExport.cpp | 1 | 4720 | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
StaticLightingExport.cpp: Static lighting export implementations.
=============================================================================*/
#include "UnrealEd.h"
#include "StaticMeshLight.h"
#include "ModelLight.h"
#include "StaticMeshResources.h"
#include "LandscapeLight.h"
#include "LandscapeComponent.h"
#include "Lightmass/Lightmass.h"
#include "Lightmass/LightmappedSurfaceCollection.h"
#include "Materials/MaterialInstanceConstant.h"
// Doxygen cannot parse these definitions correctly since the declaration is in a header from a different module
#if !UE_BUILD_DOCS
/**
* Export static lighting mapping instance data to an exporter
* @param Exporter - export interface to process static lighting data
**/
void FBSPSurfaceStaticLighting::ExportMapping(class FLightmassExporter* Exporter)
{
if (!Model.IsValid()) {return;}
Exporter->BSPSurfaceMappings.AddUnique(this);
// remember all the models used by all the BSP mappings
Exporter->Models.AddUnique(Model.Get());
// get all the materials used in the node group
for (int32 NodeIndex = 0; NodeIndex < NodeGroup->Nodes.Num(); NodeIndex++)
{
FBspSurf& Surf = Model->Surfs[Model->Nodes[NodeGroup->Nodes[NodeIndex]].iSurf];
UMaterialInterface* Material = Surf.Material;
if (Material)
{
Exporter->AddMaterial(Material);
}
}
for( int32 LightIdx=0; LightIdx < NodeGroup->RelevantLights.Num(); LightIdx++ )
{
ULightComponent* Light = NodeGroup->RelevantLights[LightIdx];
if( Light )
{
Exporter->AddLight(Light);
}
}
}
/**
* @return UOject* The object that is mapped by this mapping
*/
UObject* FBSPSurfaceStaticLighting::GetMappedObject() const
{
//@todo. THIS WILL SCREW UP IF CALLED MORE THAN ONE TIME!!!!
// Create a collection object to allow selection of the surfaces in this mapping
auto MappedObject = NewObject<ULightmappedSurfaceCollection>();
// Set the owner model
MappedObject->SourceModel = Model.Get();
// Fill in the surface index array
for (int32 NodeIndex = 0; NodeIndex < NodeGroup->Nodes.Num(); NodeIndex++)
{
MappedObject->Surfaces.Add(Model->Nodes[NodeGroup->Nodes[NodeIndex]].iSurf);
}
return MappedObject;
}
/**
* Export static lighting mesh instance data to an exporter
* @param Exporter - export interface to process static lighting data
**/
void FStaticMeshStaticLightingMesh::ExportMeshInstance(class FLightmassExporter* Exporter) const
{
Exporter->StaticMeshLightingMeshes.AddUnique(this);
for( int32 LightIdx=0; LightIdx < RelevantLights.Num(); LightIdx++ )
{
ULightComponent* Light = RelevantLights[LightIdx];
if( Light )
{
Exporter->AddLight(Light);
}
}
// Add the UStaticMesh and materials to the exporter...
if( StaticMesh && StaticMesh->RenderData )
{
Exporter->StaticMeshes.AddUnique(StaticMesh);
if( Primitive )
{
for( int32 ResourceIndex = 0; ResourceIndex < StaticMesh->RenderData->LODResources.Num(); ++ResourceIndex )
{
const FStaticMeshLODResources& LODResourceData = StaticMesh->RenderData->LODResources[ResourceIndex];
for( int32 SectionIndex = 0; SectionIndex < LODResourceData.Sections.Num(); ++SectionIndex )
{
const FStaticMeshSection& Section = LODResourceData.Sections[SectionIndex];
UMaterialInterface* Material = Primitive->GetMaterial(Section.MaterialIndex);
Exporter->AddMaterial(Material);
}
}
}
}
}
/**
* Export static lighting mapping instance data to an exporter
* @param Exporter - export interface to process static lighting data
**/
void FStaticMeshStaticLightingTextureMapping::ExportMapping(class FLightmassExporter* Exporter)
{
Exporter->StaticMeshTextureMappings.AddUnique(this);
}
//
// Landscape
//
/**
* Export static lighting mesh instance data to an exporter
* @param Exporter - export interface to process static lighting data
**/
void FLandscapeStaticLightingMesh::ExportMeshInstance(class FLightmassExporter* Exporter) const
{
Exporter->LandscapeLightingMeshes.AddUnique(this);
if (LandscapeComponent && LandscapeComponent->MaterialInstance)
{
Exporter->AddMaterial(LandscapeComponent->MaterialInstance, this);
}
for( int32 LightIdx=0; LightIdx < RelevantLights.Num(); LightIdx++ )
{
ULightComponent* Light = RelevantLights[LightIdx];
if( Light )
{
Exporter->AddLight(Light);
}
}
}
/**
* Export static lighting mapping instance data to an exporter
* @param Exporter - export interface to process static lighting data
**/
void FLandscapeStaticLightingTextureMapping::ExportMapping(class FLightmassExporter* Exporter)
{
Exporter->LandscapeTextureMappings.AddUnique(this);
}
#endif
| bsd-2-clause |
rajaditya-m/pbrt-realistic-camera | film/camerasensor.cpp | 1 | 3247 | //
// camerasensor.cpp
// pbrt
//
// Created by Rajaditya Mukherjee on 3/1/13.
//
//
#include "pbrt.h"
#include "imageio.h"
#include "camerasensor.h"
// CameraSensor Method Definitions
CameraSensor::CameraSensor(int xres, int yres) : pixels(xres, yres)
{
xPixelCount = xres;
yPixelCount = yres;
// Allocate film image storage
rgb = new float[3 * xPixelCount * yPixelCount];
alpha = new float[xPixelCount * yPixelCount];
}
// accumulates sample into one pixel of the sensor using nearest neighbor
// filtering
void CameraSensor::AddSample(int pixelx, int pixely, const Spectrum &L, const Spectrum& alpha) {
float weight = 1.0f;
Pixel &pixel = pixels(pixelx, pixely);
//pixel.L.AddWeighted(weight, L);
pixel.L += L;
pixel.alpha += alpha;
pixel.weightSum += weight;
}
// clears the image
void CameraSensor::ResetImage() {
for (int i=0; i<xPixelCount; i++)
for (int j=0; j<yPixelCount; j++) {
pixels(i,j).Reset();
}
}
// Return an array of floats representing the RGB image. Image pixels
// are returned in row major order. RGB values for a single pixel are
// consecutive elements in this array.
float* CameraSensor::ComputeImageRGB() {
int nPix = xPixelCount * yPixelCount;
int offset = 0;
for (int y = 0; y < yPixelCount; ++y) {
for (int x = 0; x < xPixelCount; ++x) {
// Convert pixel spectral radiance to RGB
float xyz[3];
float a[3];
pixels(x, y).L.ToXYZ(xyz);
const float
rWeight[3] = { 3.240479f, -1.537150f, -0.498535f };
const float
gWeight[3] = {-0.969256f, 1.875991f, 0.041556f };
const float
bWeight[3] = { 0.055648f, -0.204043f, 1.057311f };
rgb[3*offset ] = rWeight[0]*xyz[0] +
rWeight[1]*xyz[1] +
rWeight[2]*xyz[2];
rgb[3*offset+1] = gWeight[0]*xyz[0] +
gWeight[1]*xyz[1] +
gWeight[2]*xyz[2];
rgb[3*offset+2] = bWeight[0]*xyz[0] +
bWeight[1]*xyz[1] +
bWeight[2]*xyz[2];
pixels(x, y).alpha.ToRGB( a );
alpha[offset] = a[0];
// Normalize pixel with weight sum
float weightSum = pixels(x, y).weightSum;
if (weightSum != 0.f) {
float invWt = 1.f / weightSum;
rgb[3*offset ] =
Clamp(rgb[3*offset ] * invWt, 0.f, INFINITY);
rgb[3*offset+1] =
Clamp(rgb[3*offset+1] * invWt, 0.f, INFINITY);
rgb[3*offset+2] =
Clamp(rgb[3*offset+2] * invWt, 0.f, INFINITY);
alpha[offset] = Clamp(alpha[offset] * invWt, 0.f, 1.f);
}
// Compute premultiplied alpha color
rgb[3*offset ] *= alpha[offset];
rgb[3*offset+1] *= alpha[offset];
rgb[3*offset+2] *= alpha[offset];
++offset;
}
}
// UA: Uncomment the following lines when debugging to write
// the current state of the image to a unique file on disk.
// Potentially very useful.
/*
static int afCount = 0;
char filename[30];
// Write RGBA image to disk
sprintf(filename, "afzone%04d.exr", afCount);
printf("Writing image %s\n", filename);
WriteImage(filename, rgb, alpha,
xPixelCount, yPixelCount,
xPixelCount, yPixelCount,
0, 0);
afCount++;
*/
return rgb;
}
| bsd-2-clause |
pok-kernel/pok | examples/arinc653-threads/sample-ada/cpu/kernel/deployment.c | 1 | 2071 | #include <core/error.h>
#include <core/kernel.h>
#include <core/partition.h>
/*****************************************************/
/* This file was automatically generated by Ocarina */
/* Do NOT hand-modify this file, as your */
/* changes will be lost when you re-run Ocarina */
/*****************************************************/
/**************************/
/* pok_partition_error */
/*************************/
void pok_partition_error(uint8_t partition, uint32_t error) {
switch (partition) {
case 0: {
switch (error) {
case POK_ERROR_KIND_PARTITION_CONFIGURATION: {
pok_partition_set_mode(0, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_INIT: {
pok_partition_set_mode(0, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_HANDLER: {
pok_partition_set_mode(0, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_SCHEDULING: {
pok_partition_set_mode(0, POK_PARTITION_MODE_INIT_WARM);
break;
}
}
break;
}
case 1: {
switch (error) {
case POK_ERROR_KIND_PARTITION_CONFIGURATION: {
pok_partition_set_mode(1, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_INIT: {
pok_partition_set_mode(1, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_HANDLER: {
pok_partition_set_mode(1, POK_PARTITION_MODE_INIT_WARM);
break;
}
case POK_ERROR_KIND_PARTITION_SCHEDULING: {
pok_partition_set_mode(1, POK_PARTITION_MODE_INIT_WARM);
break;
}
}
break;
}
}
}
/***********************/
/* pok_kernel_error */
/**********************/
void pok_kernel_error(uint32_t error) {
switch (error) {
case POK_ERROR_KIND_KERNEL_CONFIG: {
pok_kernel_restart();
break;
}
case POK_ERROR_KIND_KERNEL_INIT: {
pok_kernel_restart();
break;
}
case POK_ERROR_KIND_KERNEL_SCHEDULING: {
pok_kernel_restart();
break;
}
}
}
| bsd-2-clause |
laureolus/rxTools | tools/toolsrc/xor/main.c | 4 | 3233 | /*
padxorer by xerpi
compile with:
gcc -O3 padxorer.c -o padxorer
usage:
padxorer <input file 1> <input file 2>
the output will be <input file 1>.out
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#define BUF_SIZE (8*1024*1024)
void print_usage();
int main(int argc, char *argv[])
{
int ret_val = EXIT_SUCCESS;
if (argc < 3) {
print_usage();
ret_val = EXIT_FAILURE;
goto exit_fail_1;
}
FILE *fd_in1, *fd_in2, *fd_out;
if (!(fd_in1 = fopen(argv[1], "rb"))) {
printf("Error opening input file 1\n");
ret_val = EXIT_FAILURE;
goto exit_fail_1;
}
if (!(fd_in2 = fopen(argv[2], "rb"))) {
printf("Error opening input file 2\n");
ret_val = EXIT_FAILURE;
goto exit_fail_2;
}
fseek(fd_in1, 0, SEEK_END);
unsigned int in_size1 = ftell(fd_in1);
fseek(fd_in1, 0, SEEK_SET);
fseek(fd_in2, 0, SEEK_END);
unsigned int in_size2 = ftell(fd_in2);
fseek(fd_in2, 0, SEEK_SET);
unsigned int min_size = (in_size1 < in_size2) ? in_size1 : in_size2;
char *out_name = malloc(strlen(argv[1]) + strlen(".out") + 1);
sprintf(out_name, "%s.out", argv[1]);
if (!(fd_out = fopen(out_name, "wb+"))) {
printf("Cannot create output file\n");
ret_val = EXIT_FAILURE;
goto exit_fail_3;
}
unsigned char *data_buf1 = (unsigned char *)malloc(BUF_SIZE);
unsigned char *data_buf2 = (unsigned char *)malloc(BUF_SIZE);
#define BAR_LEN 50
unsigned int step_bytes = min_size/100;
unsigned int temp_bytes = 0;
size_t bytes_read1, bytes_read2, total_read = 0, min_read;
while ((total_read < min_size) && (bytes_read1 = fread(data_buf1, 1, BUF_SIZE, fd_in1)) &&
(bytes_read2 = fread(data_buf2, 1, BUF_SIZE, fd_in2))) {
min_read = (bytes_read1 < bytes_read2) ? bytes_read1 : bytes_read2;
total_read += min_read;
temp_bytes += min_read;
size_t i;
for (i = 0; i < min_read; i++) {
data_buf1[i] ^= data_buf2[i];
}
fwrite(data_buf1, 1, min_read, fd_out);
if ((temp_bytes >= step_bytes) || (total_read == min_size)) {
temp_bytes = 0;
unsigned int percent = (unsigned int)(total_read*(100.0/min_size));
printf("%3i%% [", percent);
int j;
int bar_size = (BAR_LEN*percent)/100;
for (j = 0; j < BAR_LEN; j++) {
if (j < bar_size) printf("=");
else if (j == bar_size) printf(">");
else printf(" ");
}
printf("]\r");
fflush(stdout);
}
}
fflush(fd_out);
fclose(fd_out);
free(data_buf1);
free(data_buf2);
printf("\nFinished!\n");
exit_fail_3:
free(out_name);
fclose(fd_in2);
exit_fail_2:
fclose(fd_in1);
exit_fail_1:
return ret_val;
}
void print_usage()
{
printf("padxorer by xerpi\n"
"usage: padxorer <input file 1> <input file 2>\n"
"the output will be <input file 1>.out\n");
} | bsd-2-clause |
MattDevo/edk2 | EdkCompatibilityPkg/Foundation/Library/EdkIIGlueLib/Library/BaseLib/Ia32/RRotU64.c | 5 | 1077 | /**
64-bit right rotation for Ia32
Copyright (c) 2006 - 2007, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "BaseLibInternals.h"
UINT64
EFIAPI
InternalMathRRotU64 (
IN UINT64 Operand,
IN UINTN Count
)
{
_asm {
mov cl, byte ptr [Count]
mov eax, dword ptr [Operand + 0]
mov edx, dword ptr [Operand + 4]
shrd ebx, eax, cl
shrd eax, edx, cl
rol ebx, cl
shrd edx, ebx, cl
test cl, 32 // Count >= 32?
cmovnz ecx, eax
cmovnz eax, edx
cmovnz edx, ecx
}
}
| bsd-2-clause |
coverxiaoeye/nginx-openresty-windows | nginx/src/event/ngx_event_udp_recv.c | 7 | 7947 |
/*
* Copyright (C) Ngwsx
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
typedef struct {
ngx_event_t event;
ngx_pool_t *pool;
ngx_buf_t *buffer;
u_char sockaddr[NGX_SOCKADDRLEN];
socklen_t socklen;
} ngx_udp_recv_event_t;
#if (NGX_WIN32)
static ngx_int_t ngx_event_post_one_udp_recv(ngx_listening_t *ls,
ngx_udp_recv_event_t *event);
#endif
static void ngx_close_udp_connection(ngx_connection_t *c);
void
ngx_event_udp_recv(ngx_event_t *ev)
{
u_char *buf;
size_t size;
ssize_t n;
ngx_listening_t *ls;
ngx_connection_t *lc;
ngx_udp_recv_event_t event;
lc = ev->data;
ls = lc->listening;
ngx_memcpy(&event.event, ev, sizeof(ngx_event_t));
event.pool = ngx_create_pool(ls->pool_size, ngx_cycle->log);
if (event.pool == NULL) {
return;
}
event.buffer = ngx_create_temp_buf(event.pool, ls->udp_recv_buffer_size);
if (event.buffer == NULL) {
ngx_destroy_pool(event.pool);
return;
}
buf = event.buffer->last;
size = event.buffer->end - event.buffer->last;
event.socklen = NGX_SOCKADDRLEN;
#if (NGX_UDT)
n = ngx_recvfrom(lc->fd, (char *) buf, size, 0,
(struct sockaddr *) event.sockaddr, &event.socklen);
#else
n = recvfrom(lc->fd, (char *) buf, size, 0,
(struct sockaddr *) event.sockaddr, &event.socklen);
#endif
if (n == -1) {
#if (NGX_UDT)
ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno,
"ngx_recvfrom() failed");
#else
ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno,
"recvfrom() failed");
#endif
ngx_destroy_pool(event.pool);
return;
}
event.buffer->last += n;
ngx_event_udp_aio_recv((ngx_event_t *) &event);
}
void
ngx_event_udp_aio_recv(ngx_event_t *ev)
{
ngx_udp_recv_event_t *event = (ngx_udp_recv_event_t *) ev;
ngx_log_t *log;
ngx_event_t *rev, *wev;
ngx_listening_t *ls;
ngx_connection_t *c, *lc;
ev->ready = 0;
lc = ev->data;
ls = lc->listening;
if (ev->error) {
ngx_destroy_pool(event->pool);
goto post_udp_recv;
}
#if (NGX_STAT_STUB)
(void) ngx_atomic_fetch_add(ngx_stat_accepted, 1);
#endif
ev->log->data = &ls->addr_text;
c = ngx_get_connection(lc->fd, ev->log);
if (c == NULL) {
ngx_destroy_pool(event->pool);
goto post_udp_recv;
}
#if (NGX_STAT_STUB)
(void) ngx_atomic_fetch_add(ngx_stat_active, 1);
#endif
c->pool = event->pool;
c->buffer = event->buffer;
#if (NGX_WIN32) && (NGX_HAVE_IOCP)
if (ngx_event_flags & NGX_USE_IOCP_EVENT) {
c->buffer->last += ev->available;
ev->available = 0;
}
#endif
c->sockaddr = ngx_palloc(c->pool, event->socklen);
if (c->sockaddr == NULL) {
ngx_close_udp_connection(c);
goto post_udp_recv;
}
ngx_memcpy(c->sockaddr, event->sockaddr, event->socklen);
log = ngx_palloc(c->pool, sizeof(ngx_log_t));
if (log == NULL) {
ngx_close_udp_connection(c);
goto post_udp_recv;
}
*log = ls->log;
c->recv = ngx_recv;
c->send = ngx_send;
c->recv_chain = ngx_recv_chain;
c->send_chain = ngx_send_chain;
c->log = log;
c->pool->log = log;
c->socklen = event->socklen;
c->listening = ls;
c->local_sockaddr = ls->sockaddr;
c->unexpected_eof = 1;
#if (NGX_HAVE_UNIX_DOMAIN)
if (c->sockaddr->sa_family == AF_UNIX) {
c->tcp_nopush = NGX_TCP_NOPUSH_DISABLED;
c->tcp_nodelay = NGX_TCP_NODELAY_DISABLED;
}
#endif
rev = c->read;
wev = c->write;
wev->ready = 1;
if (ngx_event_flags & (NGX_USE_AIO_EVENT|NGX_USE_RTSIG_EVENT)) {
/* rtsig, aio, iocp */
rev->ready = 1;
}
if (ev->deferred_accept) {
rev->ready = 1;
}
rev->log = log;
wev->log = log;
/*
* TODO: MT: - ngx_atomic_fetch_add()
* or protection by critical section or light mutex
*
* TODO: MP: - allocated in a shared memory
* - ngx_atomic_fetch_add()
* or protection by critical section or light mutex
*/
c->number = ngx_atomic_fetch_add(ngx_connection_counter, 1);
#if (NGX_STAT_STUB)
(void) ngx_atomic_fetch_add(ngx_stat_handled, 1);
#endif
#if (NGX_THREADS)
rev->lock = &c->lock;
wev->lock = &c->lock;
rev->own_lock = &c->lock;
wev->own_lock = &c->lock;
#endif
if (ls->addr_ntop) {
c->addr_text.data = ngx_pnalloc(c->pool,
ls->addr_text_max_len + sizeof(":65535") - 1);
if (c->addr_text.data == NULL) {
ngx_close_udp_connection(c);
goto post_udp_recv;
}
c->addr_text.len = ngx_sock_ntop(c->sockaddr, c->addr_text.data,
ls->addr_text_max_len + sizeof(":65535") - 1, 1);
if (c->addr_text.len == 0) {
ngx_close_udp_connection(c);
goto post_udp_recv;
}
}
#if (NGX_DEBUG)
{
in_addr_t i;
ngx_event_conf_t *ecf;
ngx_event_debug_t *dc;
struct sockaddr_in *sin;
sin = (struct sockaddr_in *) c->sockaddr;
ecf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_core_module);
dc = ecf->debug_connection.elts;
for (i = 0; i < ecf->debug_connection.nelts; i++) {
if ((sin->sin_addr.s_addr & dc[i].mask) == dc[i].addr) {
log->log_level = NGX_LOG_DEBUG_CONNECTION|NGX_LOG_DEBUG_ALL;
break;
}
}
}
#endif
log->data = NULL;
log->handler = NULL;
ls->handler(c);
post_udp_recv:
#if (NGX_WIN32)
if (ngx_event_flags & NGX_USE_IOCP_EVENT) {
ngx_event_post_one_udp_recv(ls, event);
}
#endif
return;
}
#if (NGX_WIN32)
ngx_int_t
ngx_event_post_udp_recv(ngx_listening_t *ls, ngx_uint_t n)
{
ngx_uint_t i;
ngx_udp_recv_event_t *udp_events, *ev;
udp_events = ngx_alloc(sizeof(ngx_udp_recv_event_t) * n, ngx_cycle->log);
if (udp_events == NULL) {
return NGX_ERROR;
}
for (i = 0; i < n; i++) {
ev = &udp_events[i];
ngx_memcpy(&ev->event, ls->connection->read, sizeof(ngx_event_t));
ev->event.ovlp.event = &ev->event;
if (ngx_event_post_one_udp_recv(ls, ev) != NGX_OK) {
return NGX_ERROR;
}
}
return NGX_OK;
}
static ngx_int_t
ngx_event_post_one_udp_recv(ngx_listening_t *ls, ngx_udp_recv_event_t *event)
{
int rc;
DWORD flags;
WSABUF wsabuf;
ngx_err_t err;
event->pool = ngx_create_pool(ls->pool_size, ngx_cycle->log);
if (event->pool == NULL) {
return NGX_ERROR;
}
event->buffer = ngx_create_temp_buf(event->pool, ls->udp_recv_buffer_size);
if (event->buffer == NULL) {
ngx_destroy_pool(event->pool);
return NGX_ERROR;
}
wsabuf.buf = (CHAR *) event->buffer->last;
wsabuf.len = (DWORD) (event->buffer->end - event->buffer->last);
flags = 0;
event->socklen = NGX_SOCKADDRLEN;
rc = WSARecvFrom(ls->connection->fd, &wsabuf, 1, NULL, &flags,
(struct sockaddr *) event->sockaddr,
(LPINT) &event->socklen,
(LPWSAOVERLAPPED) &event->event.ovlp, NULL);
err = ngx_socket_errno;
if (rc == SOCKET_ERROR && err != WSA_IO_PENDING) {
ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, err,
"WSARecvFrom() failed");
return NGX_ERROR;
}
return NGX_OK;
}
#endif
static void
ngx_close_udp_connection(ngx_connection_t *c)
{
ngx_free_connection(c);
if (c->pool) {
ngx_destroy_pool(c->pool);
}
#if (NGX_STAT_STUB)
(void) ngx_atomic_fetch_add(ngx_stat_active, -1);
#endif
}
| bsd-2-clause |
fangeugene/trajopt | src/humanoids/hull2d.cpp | 8 | 2667 | #include "hull2d.hpp"
#include <algorithm>
#include <vector>
using namespace Eigen;
using namespace std;
// http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
namespace {
typedef float coord_t; // coordinate type
typedef float coord2_t; // must be big enough to hold 2*max(|coordinate|)^2
struct Point {
coord_t x, y;
Point() {}
Point(coord_t x, coord_t y) : x(x), y(y) {}
bool operator <(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
};
// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
// Returns a positive value, if OAB makes a counter-clockwise turn,
// negative for clockwise turn, and zero if the points are collinear.
coord2_t cross(const Point &O, const Point &A, const Point &B)
{
return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}
// Returns a list of points on the convex hull in counter-clockwise order.
// Note: the last point in the returned list is the same as the first one.
vector<Point> convex_hull(vector<Point> P)
{
int n = P.size(), k = 0;
vector<Point> H(2*n);
// Sort points lexicographically
sort(P.begin(), P.end());
// Build lower hull
for (int i = 0; i < n; i++) {
while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
// Build upper hull
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
H.resize(k);
return H;
}
}
Eigen::MatrixX2d hull2d(const Eigen::MatrixX2d& in) {
vector<Point> points(in.rows());
for (int i=0; i < in.rows(); ++i) points[i] = Point(in(i,0), in(i,1));
vector<Point> hull = convex_hull(points);
Eigen::MatrixX2d out(hull.size()-1,2);
for (int i=0; i < hull.size()-1; ++i) {
out(i,0) = hull[i].x;
out(i,1) = hull[i].y;
}
return out;
}
void PolygonToEquations(const MatrixX2d& pts, MatrixX2d& ab, VectorXd& c) {
// ax + by + c <= 0
// assume polygon is convex
ab.resize(pts.rows(),2);
c.resize(pts.rows());
// Vector2d p0 = pts.row(0);
for (int i=0; i < pts.rows(); ++i) {
int i1 = (i+1) % pts.rows();
double x0 = pts(i,0),
y0 = pts(i,1),
x1 = pts(i1,0),
y1 = pts(i1,1);
ab(i,0) = -(y1 - y0);
ab(i,1) = x1 - x0;
ab.row(i).normalize();
c(i) = -ab.row(i).dot(pts.row(i));
}
Vector2d centroid = pts.colwise().mean();
if (ab.row(0) * centroid + c(0) >= 0) {
ab *= -1;
c *= -1;
}
}
| bsd-2-clause |
hugewave/asn1c | libasn1parser/asn1p_y.c | 8 | 154577 | /* A Bison parser, made by GNU Bison 2.3. */
/* Skeleton implementation for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, 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. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "2.3"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Using locations. */
#define YYLSP_NEEDED 0
/* Substitute the variable and function names. */
#define yyparse asn1p_parse
#define yylex asn1p_lex
#define yyerror asn1p_error
#define yylval asn1p_lval
#define yychar asn1p_char
#define yydebug asn1p_debug
#define yynerrs asn1p_nerrs
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
TOK_PPEQ = 258,
TOK_VBracketLeft = 259,
TOK_VBracketRight = 260,
TOK_whitespace = 261,
TOK_opaque = 262,
TOK_bstring = 263,
TOK_cstring = 264,
TOK_hstring = 265,
TOK_identifier = 266,
TOK_number = 267,
TOK_number_negative = 268,
TOK_realnumber = 269,
TOK_tuple = 270,
TOK_quadruple = 271,
TOK_typereference = 272,
TOK_capitalreference = 273,
TOK_typefieldreference = 274,
TOK_valuefieldreference = 275,
TOK_Literal = 276,
TOK_ABSENT = 277,
TOK_ABSTRACT_SYNTAX = 278,
TOK_ALL = 279,
TOK_ANY = 280,
TOK_APPLICATION = 281,
TOK_AUTOMATIC = 282,
TOK_BEGIN = 283,
TOK_BIT = 284,
TOK_BMPString = 285,
TOK_BOOLEAN = 286,
TOK_BY = 287,
TOK_CHARACTER = 288,
TOK_CHOICE = 289,
TOK_CLASS = 290,
TOK_COMPONENT = 291,
TOK_COMPONENTS = 292,
TOK_CONSTRAINED = 293,
TOK_CONTAINING = 294,
TOK_DEFAULT = 295,
TOK_DEFINITIONS = 296,
TOK_DEFINED = 297,
TOK_EMBEDDED = 298,
TOK_ENCODED = 299,
TOK_ENCODING_CONTROL = 300,
TOK_END = 301,
TOK_ENUMERATED = 302,
TOK_EXPLICIT = 303,
TOK_EXPORTS = 304,
TOK_EXTENSIBILITY = 305,
TOK_EXTERNAL = 306,
TOK_FALSE = 307,
TOK_FROM = 308,
TOK_GeneralizedTime = 309,
TOK_GeneralString = 310,
TOK_GraphicString = 311,
TOK_IA5String = 312,
TOK_IDENTIFIER = 313,
TOK_IMPLICIT = 314,
TOK_IMPLIED = 315,
TOK_IMPORTS = 316,
TOK_INCLUDES = 317,
TOK_INSTANCE = 318,
TOK_INSTRUCTIONS = 319,
TOK_INTEGER = 320,
TOK_ISO646String = 321,
TOK_MAX = 322,
TOK_MIN = 323,
TOK_MINUS_INFINITY = 324,
TOK_NULL = 325,
TOK_NumericString = 326,
TOK_OBJECT = 327,
TOK_ObjectDescriptor = 328,
TOK_OCTET = 329,
TOK_OF = 330,
TOK_OPTIONAL = 331,
TOK_PATTERN = 332,
TOK_PDV = 333,
TOK_PLUS_INFINITY = 334,
TOK_PRESENT = 335,
TOK_PrintableString = 336,
TOK_PRIVATE = 337,
TOK_REAL = 338,
TOK_RELATIVE_OID = 339,
TOK_SEQUENCE = 340,
TOK_SET = 341,
TOK_SIZE = 342,
TOK_STRING = 343,
TOK_SYNTAX = 344,
TOK_T61String = 345,
TOK_TAGS = 346,
TOK_TeletexString = 347,
TOK_TRUE = 348,
TOK_TYPE_IDENTIFIER = 349,
TOK_UNIQUE = 350,
TOK_UNIVERSAL = 351,
TOK_UniversalString = 352,
TOK_UTCTime = 353,
TOK_UTF8String = 354,
TOK_VideotexString = 355,
TOK_VisibleString = 356,
TOK_WITH = 357,
TOK_EXCEPT = 358,
TOK_INTERSECTION = 359,
TOK_UNION = 360,
TOK_TwoDots = 361,
TOK_ThreeDots = 362
};
#endif
/* Tokens. */
#define TOK_PPEQ 258
#define TOK_VBracketLeft 259
#define TOK_VBracketRight 260
#define TOK_whitespace 261
#define TOK_opaque 262
#define TOK_bstring 263
#define TOK_cstring 264
#define TOK_hstring 265
#define TOK_identifier 266
#define TOK_number 267
#define TOK_number_negative 268
#define TOK_realnumber 269
#define TOK_tuple 270
#define TOK_quadruple 271
#define TOK_typereference 272
#define TOK_capitalreference 273
#define TOK_typefieldreference 274
#define TOK_valuefieldreference 275
#define TOK_Literal 276
#define TOK_ABSENT 277
#define TOK_ABSTRACT_SYNTAX 278
#define TOK_ALL 279
#define TOK_ANY 280
#define TOK_APPLICATION 281
#define TOK_AUTOMATIC 282
#define TOK_BEGIN 283
#define TOK_BIT 284
#define TOK_BMPString 285
#define TOK_BOOLEAN 286
#define TOK_BY 287
#define TOK_CHARACTER 288
#define TOK_CHOICE 289
#define TOK_CLASS 290
#define TOK_COMPONENT 291
#define TOK_COMPONENTS 292
#define TOK_CONSTRAINED 293
#define TOK_CONTAINING 294
#define TOK_DEFAULT 295
#define TOK_DEFINITIONS 296
#define TOK_DEFINED 297
#define TOK_EMBEDDED 298
#define TOK_ENCODED 299
#define TOK_ENCODING_CONTROL 300
#define TOK_END 301
#define TOK_ENUMERATED 302
#define TOK_EXPLICIT 303
#define TOK_EXPORTS 304
#define TOK_EXTENSIBILITY 305
#define TOK_EXTERNAL 306
#define TOK_FALSE 307
#define TOK_FROM 308
#define TOK_GeneralizedTime 309
#define TOK_GeneralString 310
#define TOK_GraphicString 311
#define TOK_IA5String 312
#define TOK_IDENTIFIER 313
#define TOK_IMPLICIT 314
#define TOK_IMPLIED 315
#define TOK_IMPORTS 316
#define TOK_INCLUDES 317
#define TOK_INSTANCE 318
#define TOK_INSTRUCTIONS 319
#define TOK_INTEGER 320
#define TOK_ISO646String 321
#define TOK_MAX 322
#define TOK_MIN 323
#define TOK_MINUS_INFINITY 324
#define TOK_NULL 325
#define TOK_NumericString 326
#define TOK_OBJECT 327
#define TOK_ObjectDescriptor 328
#define TOK_OCTET 329
#define TOK_OF 330
#define TOK_OPTIONAL 331
#define TOK_PATTERN 332
#define TOK_PDV 333
#define TOK_PLUS_INFINITY 334
#define TOK_PRESENT 335
#define TOK_PrintableString 336
#define TOK_PRIVATE 337
#define TOK_REAL 338
#define TOK_RELATIVE_OID 339
#define TOK_SEQUENCE 340
#define TOK_SET 341
#define TOK_SIZE 342
#define TOK_STRING 343
#define TOK_SYNTAX 344
#define TOK_T61String 345
#define TOK_TAGS 346
#define TOK_TeletexString 347
#define TOK_TRUE 348
#define TOK_TYPE_IDENTIFIER 349
#define TOK_UNIQUE 350
#define TOK_UNIVERSAL 351
#define TOK_UniversalString 352
#define TOK_UTCTime 353
#define TOK_UTF8String 354
#define TOK_VideotexString 355
#define TOK_VisibleString 356
#define TOK_WITH 357
#define TOK_EXCEPT 358
#define TOK_INTERSECTION 359
#define TOK_UNION 360
#define TOK_TwoDots 361
#define TOK_ThreeDots 362
/* Copy the first part of user declarations. */
#line 1 "asn1p_y.y"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include "asn1parser.h"
#define YYPARSE_PARAM param
#define YYPARSE_PARAM_TYPE void **
#define YYERROR_VERBOSE
int yylex(void);
int yyerror(const char *msg);
#ifdef YYBYACC
int yyparse(void **param); /* byacc does not produce a prototype */
#endif
void asn1p_lexer_hack_push_opaque_state(void);
void asn1p_lexer_hack_enable_with_syntax(void);
void asn1p_lexer_hack_push_encoding_control(void);
#define yylineno asn1p_lineno
extern int asn1p_lineno;
/*
* Process directives as <ASN1C:RepresentAsPointer>
*/
extern int asn1p_as_pointer;
/*
* This temporary variable is used to solve the shortcomings of 1-lookahead
* parser.
*/
static struct AssignedIdentifier *saved_aid;
static asn1p_value_t *_convert_bitstring2binary(char *str, int base);
static void _fixup_anonymous_identifier(asn1p_expr_t *expr);
static asn1p_module_t *currentModule;
#define NEW_EXPR() (asn1p_expr_new(yylineno, currentModule))
#define checkmem(ptr) do { \
if(!(ptr)) \
return yyerror("Memory failure"); \
} while(0)
#define CONSTRAINT_INSERT(root, constr_type, arg1, arg2) do { \
if(arg1->type != constr_type) { \
int __ret; \
root = asn1p_constraint_new(yylineno); \
checkmem(root); \
root->type = constr_type; \
__ret = asn1p_constraint_insert(root, \
arg1); \
checkmem(__ret == 0); \
} else { \
root = arg1; \
} \
if(arg2) { \
int __ret \
= asn1p_constraint_insert(root, arg2); \
checkmem(__ret == 0); \
} \
} while(0)
#ifdef AL_IMPORT
#error AL_IMPORT DEFINED ELSEWHERE!
#endif
#define AL_IMPORT(to,where,from,field) do { \
if(!(from)) break; \
while(TQ_FIRST(&((from)->where))) { \
TQ_ADD(&((to)->where), \
TQ_REMOVE(&((from)->where), field), \
field); \
} \
assert(TQ_FIRST(&((from)->where)) == 0); \
} while(0)
/* Enabling traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* Enabling the token table. */
#ifndef YYTOKEN_TABLE
# define YYTOKEN_TABLE 0
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
#line 88 "asn1p_y.y"
{
asn1p_t *a_grammar;
asn1p_module_flags_e a_module_flags;
asn1p_module_t *a_module;
asn1p_expr_type_e a_type; /* ASN.1 Type */
asn1p_expr_t *a_expr; /* Constructed collection */
asn1p_constraint_t *a_constr; /* Constraint */
enum asn1p_constraint_type_e a_ctype;/* Constraint type */
asn1p_xports_t *a_xports; /* IMports/EXports */
struct AssignedIdentifier a_aid; /* Assigned Identifier */
asn1p_oid_t *a_oid; /* Object Identifier */
asn1p_oid_arc_t a_oid_arc; /* Single OID's arc */
struct asn1p_type_tag_s a_tag; /* A tag */
asn1p_ref_t *a_ref; /* Reference to custom type */
asn1p_wsyntx_t *a_wsynt; /* WITH SYNTAX contents */
asn1p_wsyntx_chunk_t *a_wchunk; /* WITH SYNTAX chunk */
struct asn1p_ref_component_s a_refcomp; /* Component of a reference */
asn1p_value_t *a_value; /* Number, DefinedValue, etc */
struct asn1p_param_s a_parg; /* A parameter argument */
asn1p_paramlist_t *a_plist; /* A pargs list */
struct asn1p_expr_marker_s a_marker; /* OPTIONAL/DEFAULT */
enum asn1p_constr_pres_e a_pres; /* PRESENT/ABSENT/OPTIONAL */
asn1c_integer_t a_int;
double a_dbl;
char *tv_str;
struct {
char *buf;
int len;
} tv_opaque;
struct {
char *name;
struct asn1p_type_tag_s tag;
} tv_nametag;
}
/* Line 193 of yacc.c. */
#line 434 "y.tab.c"
YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
/* Copy the second part of user declarations. */
/* Line 216 of yacc.c. */
#line 447 "y.tab.c"
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#elif (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
typedef signed char yytype_int8;
#else
typedef short int yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(e) ((void) (e))
#else
# define YYUSE(e) /* empty */
#endif
/* Identity function, used to suppress warnings about constant conditions. */
#ifndef lint
# define YYID(n) (n)
#else
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static int
YYID (int i)
#else
static int
YYID (i)
int i;
#endif
{
return i;
}
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's `empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined _STDLIB_H \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss;
YYSTYPE yyvs;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
/* Copy COUNT objects from FROM to TO. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(To, From, Count) \
__builtin_memcpy (To, From, (Count) * sizeof (*(From)))
# else
# define YYCOPY(To, From, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(To)[yyi] = (From)[yyi]; \
} \
while (YYID (0))
# endif
# endif
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack, Stack, yysize); \
Stack = &yyptr->Stack; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (YYID (0))
#endif
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 7
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 793
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 123
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 122
/* YYNRULES -- Number of rules. */
#define YYNRULES 313
/* YYNRULES -- Number of states. */
#define YYNSTATES 473
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 362
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 119, 2, 2, 2, 2, 2, 2,
112, 113, 2, 2, 115, 2, 120, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 116, 114,
121, 2, 2, 2, 122, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 117, 2, 118, 104, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 110, 106, 111, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 105,
107, 108, 109
};
#if YYDEBUG
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
static const yytype_uint16 yyprhs[] =
{
0, 0, 3, 5, 7, 10, 11, 21, 22, 24,
28, 31, 33, 36, 38, 43, 45, 46, 48, 50,
53, 56, 59, 62, 65, 68, 69, 71, 75, 77,
80, 82, 84, 86, 87, 91, 93, 94, 96, 100,
103, 104, 106, 108, 111, 112, 114, 119, 121, 125,
127, 131, 133, 134, 136, 140, 144, 147, 149, 153,
155, 159, 161, 165, 170, 172, 174, 179, 183, 187,
194, 201, 203, 207, 209, 213, 217, 221, 225, 227,
231, 233, 235, 237, 239, 240, 242, 244, 248, 254,
258, 261, 265, 267, 269, 273, 276, 278, 280, 286,
287, 289, 291, 295, 298, 303, 307, 311, 315, 319,
323, 324, 326, 327, 334, 336, 339, 341, 343, 345,
349, 351, 355, 359, 363, 364, 367, 369, 374, 379,
384, 391, 398, 400, 405, 409, 411, 415, 419, 423,
425, 429, 431, 435, 437, 439, 441, 443, 447, 451,
453, 458, 460, 462, 466, 467, 471, 473, 475, 477,
479, 481, 483, 485, 487, 491, 493, 495, 497, 499,
502, 504, 506, 508, 510, 513, 516, 518, 520, 523,
526, 528, 530, 532, 534, 536, 539, 541, 544, 546,
548, 550, 552, 554, 556, 558, 560, 562, 564, 566,
568, 570, 572, 574, 576, 578, 580, 581, 583, 585,
587, 592, 596, 601, 603, 605, 609, 615, 617, 619,
623, 625, 629, 631, 635, 637, 641, 646, 650, 652,
654, 658, 662, 666, 670, 672, 674, 677, 680, 682,
684, 686, 688, 690, 692, 694, 696, 698, 700, 702,
706, 712, 714, 718, 720, 724, 725, 727, 729, 731,
733, 735, 737, 739, 740, 746, 749, 751, 754, 757,
761, 763, 765, 769, 774, 776, 780, 783, 787, 789,
793, 794, 796, 798, 801, 804, 808, 810, 814, 816,
821, 826, 828, 830, 832, 834, 836, 838, 839, 841,
844, 849, 850, 852, 854, 856, 857, 859, 861, 863,
865, 867, 868, 870
};
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
static const yytype_int16 yyrhs[] =
{
124, 0, -1, 125, -1, 126, -1, 125, 126, -1,
-1, 241, 127, 128, 41, 132, 3, 28, 135, 46,
-1, -1, 129, -1, 110, 130, 111, -1, 110, 111,
-1, 131, -1, 130, 131, -1, 244, -1, 244, 112,
12, 113, -1, 12, -1, -1, 133, -1, 134, -1,
133, 134, -1, 48, 91, -1, 59, 91, -1, 27,
91, -1, 50, 60, -1, 18, 64, -1, -1, 136,
-1, 148, 140, 137, -1, 138, -1, 137, 138, -1,
155, -1, 185, -1, 153, -1, -1, 45, 18, 139,
-1, 195, -1, -1, 141, -1, 61, 142, 114, -1,
61, 53, -1, -1, 143, -1, 145, -1, 143, 145,
-1, -1, 129, -1, 146, 53, 241, 144, -1, 147,
-1, 146, 115, 147, -1, 241, -1, 241, 110, 111,
-1, 244, -1, -1, 149, -1, 49, 150, 114, -1,
49, 24, 114, -1, 49, 114, -1, 151, -1, 150,
115, 151, -1, 241, -1, 241, 110, 111, -1, 244,
-1, 110, 202, 111, -1, 241, 154, 3, 152, -1,
194, -1, 179, -1, 179, 110, 158, 111, -1, 241,
3, 175, -1, 241, 3, 165, -1, 241, 110, 156,
111, 3, 175, -1, 241, 110, 156, 111, 3, 165,
-1, 157, -1, 156, 115, 157, -1, 241, -1, 241,
116, 244, -1, 241, 116, 241, -1, 192, 116, 244,
-1, 192, 116, 241, -1, 159, -1, 158, 115, 159,
-1, 175, -1, 188, -1, 244, -1, 152, -1, -1,
161, -1, 162, -1, 161, 115, 162, -1, 161, 115,
4, 161, 5, -1, 244, 175, 229, -1, 175, 229,
-1, 37, 75, 175, -1, 174, -1, 164, -1, 163,
115, 164, -1, 244, 175, -1, 174, -1, 175, -1,
35, 110, 167, 111, 169, -1, -1, 95, -1, 168,
-1, 167, 115, 168, -1, 19, 229, -1, 20, 175,
166, 229, -1, 20, 183, 229, -1, 20, 184, 229,
-1, 19, 183, 229, -1, 19, 175, 229, -1, 19,
184, 229, -1, -1, 170, -1, -1, 102, 89, 110,
171, 172, 111, -1, 173, -1, 172, 173, -1, 6,
-1, 21, -1, 182, -1, 117, 172, 118, -1, 109,
-1, 109, 119, 189, -1, 109, 119, 234, -1, 236,
177, 198, -1, -1, 176, 178, -1, 154, -1, 34,
110, 163, 111, -1, 85, 110, 160, 111, -1, 86,
110, 160, 111, -1, 85, 198, 75, 243, 236, 177,
-1, 86, 198, 75, 243, 236, 177, -1, 25, -1,
25, 42, 32, 244, -1, 63, 75, 179, -1, 17,
-1, 17, 120, 241, -1, 242, 120, 241, -1, 17,
120, 244, -1, 242, -1, 242, 120, 180, -1, 181,
-1, 180, 120, 181, -1, 182, -1, 19, -1, 20,
-1, 19, -1, 183, 120, 19, -1, 183, 120, 20,
-1, 18, -1, 244, 175, 3, 186, -1, 188, -1,
189, -1, 244, 116, 186, -1, -1, 110, 187, 191,
-1, 70, -1, 52, -1, 93, -1, 8, -1, 10,
-1, 190, -1, 234, -1, 244, -1, 241, 120, 244,
-1, 9, -1, 15, -1, 16, -1, 7, -1, 191,
7, -1, 31, -1, 70, -1, 83, -1, 193, -1,
74, 88, -1, 72, 58, -1, 84, -1, 51, -1,
43, 78, -1, 33, 88, -1, 98, -1, 54, -1,
195, -1, 65, -1, 47, -1, 29, 88, -1, 192,
-1, 193, 231, -1, 30, -1, 55, -1, 56, -1,
57, -1, 66, -1, 71, -1, 81, -1, 90, -1,
92, -1, 97, -1, 99, -1, 100, -1, 101, -1,
73, -1, 106, -1, 107, -1, 104, -1, 105, -1,
-1, 199, -1, 200, -1, 201, -1, 87, 112, 202,
113, -1, 112, 202, 113, -1, 201, 112, 202, 113,
-1, 109, -1, 203, -1, 203, 115, 109, -1, 203,
115, 109, 115, 203, -1, 218, -1, 204, -1, 24,
103, 207, -1, 205, -1, 204, 196, 205, -1, 206,
-1, 205, 197, 206, -1, 207, -1, 207, 103, 207,
-1, 209, 112, 202, 113, -1, 112, 202, 113, -1,
210, -1, 212, -1, 210, 222, 210, -1, 68, 222,
210, -1, 210, 222, 67, -1, 68, 222, 67, -1,
213, -1, 208, -1, 77, 9, -1, 77, 244, -1,
87, -1, 53, -1, 52, -1, 93, -1, 235, -1,
190, -1, 211, -1, 244, -1, 8, -1, 10, -1,
241, -1, 102, 36, 201, -1, 102, 37, 110, 214,
111, -1, 215, -1, 214, 115, 215, -1, 109, -1,
244, 198, 216, -1, -1, 217, -1, 80, -1, 22,
-1, 76, -1, 219, -1, 223, -1, 221, -1, -1,
38, 32, 110, 220, 191, -1, 39, 175, -1, 108,
-1, 108, 121, -1, 121, 108, -1, 121, 108, 121,
-1, 224, -1, 225, -1, 110, 241, 111, -1, 224,
110, 226, 111, -1, 227, -1, 226, 115, 227, -1,
122, 228, -1, 122, 120, 228, -1, 244, -1, 228,
120, 244, -1, -1, 230, -1, 76, -1, 40, 186,
-1, 110, 111, -1, 110, 232, 111, -1, 233, -1,
232, 115, 233, -1, 244, -1, 244, 112, 234, 113,
-1, 244, 112, 189, 113, -1, 234, -1, 109, -1,
12, -1, 13, -1, 234, -1, 14, -1, -1, 237,
-1, 238, 240, -1, 117, 239, 12, 118, -1, -1,
96, -1, 26, -1, 82, -1, -1, 59, -1, 48,
-1, 17, -1, 18, -1, 18, -1, -1, 244, -1,
11, -1
};
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 357, 357, 363, 368, 385, 385, 414, 415, 419,
422, 428, 434, 443, 447, 451, 461, 462, 471, 474,
483, 486, 489, 492, 496, 517, 518, 527, 536, 539,
555, 562, 575, 583, 582, 596, 609, 610, 613, 623,
629, 630, 633, 638, 645, 646, 650, 661, 666, 673,
679, 685, 695, 696, 708, 711, 714, 722, 727, 734,
740, 746, 755, 758, 768, 781, 791, 811, 817, 833,
839, 847, 856, 867, 871, 878, 885, 893, 904, 909,
916, 919, 927, 938, 961, 962, 965, 970, 974, 981,
988, 994, 1001, 1007, 1012, 1019, 1024, 1027, 1034, 1044,
1045, 1049, 1056, 1066, 1076, 1087, 1097, 1108, 1118, 1129,
1141, 1142, 1149, 1148, 1157, 1161, 1168, 1172, 1175, 1179,
1185, 1193, 1202, 1214, 1236, 1243, 1262, 1265, 1271, 1277,
1283, 1293, 1303, 1309, 1320, 1335, 1343, 1353, 1363, 1373,
1381, 1403, 1411, 1420, 1424, 1429, 1438, 1442, 1446, 1453,
1473, 1483, 1484, 1485, 1492, 1492, 1497, 1505, 1510, 1515,
1519, 1523, 1526, 1532, 1543, 1561, 1565, 1570, 1578, 1587,
1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611,
1612, 1613, 1614, 1621, 1622, 1623, 1627, 1633, 1646, 1647,
1651, 1655, 1656, 1657, 1658, 1659, 1663, 1664, 1665, 1666,
1670, 1671, 1678, 1678, 1679, 1679, 1682, 1683, 1689, 1693,
1696, 1706, 1709, 1715, 1719, 1722, 1728, 1736, 1742, 1743,
1749, 1750, 1756, 1757, 1764, 1765, 1771, 1779, 1787, 1793,
1799, 1806, 1814, 1822, 1831, 1834, 1840, 1845, 1856, 1859,
1865, 1870, 1875, 1876, 1877, 1878, 1892, 1896, 1903, 1917,
1920, 1926, 1929, 1935, 1941, 1955, 1956, 1960, 1963, 1966,
1974, 1975, 1976, 1981, 1980, 1992, 2000, 2001, 2002, 2003,
2006, 2009, 2018, 2033, 2039, 2045, 2059, 2070, 2086, 2089,
2107, 2111, 2115, 2119, 2142, 2146, 2152, 2157, 2164, 2171,
2179, 2187, 2194, 2205, 2209, 2216, 2217, 2248, 2249, 2253,
2260, 2266, 2267, 2268, 2269, 2273, 2274, 2275, 2279, 2283,
2291, 2298, 2299, 2305
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "TOK_PPEQ", "TOK_VBracketLeft",
"TOK_VBracketRight", "TOK_whitespace", "TOK_opaque", "TOK_bstring",
"TOK_cstring", "TOK_hstring", "TOK_identifier", "TOK_number",
"TOK_number_negative", "TOK_realnumber", "TOK_tuple", "TOK_quadruple",
"TOK_typereference", "TOK_capitalreference", "TOK_typefieldreference",
"TOK_valuefieldreference", "TOK_Literal", "TOK_ABSENT",
"TOK_ABSTRACT_SYNTAX", "TOK_ALL", "TOK_ANY", "TOK_APPLICATION",
"TOK_AUTOMATIC", "TOK_BEGIN", "TOK_BIT", "TOK_BMPString", "TOK_BOOLEAN",
"TOK_BY", "TOK_CHARACTER", "TOK_CHOICE", "TOK_CLASS", "TOK_COMPONENT",
"TOK_COMPONENTS", "TOK_CONSTRAINED", "TOK_CONTAINING", "TOK_DEFAULT",
"TOK_DEFINITIONS", "TOK_DEFINED", "TOK_EMBEDDED", "TOK_ENCODED",
"TOK_ENCODING_CONTROL", "TOK_END", "TOK_ENUMERATED", "TOK_EXPLICIT",
"TOK_EXPORTS", "TOK_EXTENSIBILITY", "TOK_EXTERNAL", "TOK_FALSE",
"TOK_FROM", "TOK_GeneralizedTime", "TOK_GeneralString",
"TOK_GraphicString", "TOK_IA5String", "TOK_IDENTIFIER", "TOK_IMPLICIT",
"TOK_IMPLIED", "TOK_IMPORTS", "TOK_INCLUDES", "TOK_INSTANCE",
"TOK_INSTRUCTIONS", "TOK_INTEGER", "TOK_ISO646String", "TOK_MAX",
"TOK_MIN", "TOK_MINUS_INFINITY", "TOK_NULL", "TOK_NumericString",
"TOK_OBJECT", "TOK_ObjectDescriptor", "TOK_OCTET", "TOK_OF",
"TOK_OPTIONAL", "TOK_PATTERN", "TOK_PDV", "TOK_PLUS_INFINITY",
"TOK_PRESENT", "TOK_PrintableString", "TOK_PRIVATE", "TOK_REAL",
"TOK_RELATIVE_OID", "TOK_SEQUENCE", "TOK_SET", "TOK_SIZE", "TOK_STRING",
"TOK_SYNTAX", "TOK_T61String", "TOK_TAGS", "TOK_TeletexString",
"TOK_TRUE", "TOK_TYPE_IDENTIFIER", "TOK_UNIQUE", "TOK_UNIVERSAL",
"TOK_UniversalString", "TOK_UTCTime", "TOK_UTF8String",
"TOK_VideotexString", "TOK_VisibleString", "TOK_WITH", "TOK_EXCEPT",
"'^'", "TOK_INTERSECTION", "'|'", "TOK_UNION", "TOK_TwoDots",
"TOK_ThreeDots", "'{'", "'}'", "'('", "')'", "';'", "','", "':'", "'['",
"']'", "'!'", "'.'", "'<'", "'@'", "$accept", "ParsedGrammar",
"ModuleList", "ModuleDefinition", "@1", "optObjectIdentifier",
"ObjectIdentifier", "ObjectIdentifierBody", "ObjectIdentifierElement",
"optModuleDefinitionFlags", "ModuleDefinitionFlags",
"ModuleDefinitionFlag", "optModuleBody", "ModuleBody", "AssignmentList",
"Assignment", "@2", "optImports", "ImportsDefinition",
"optImportsBundleSet", "ImportsBundleSet", "AssignedIdentifier",
"ImportsBundle", "ImportsList", "ImportsElement", "optExports",
"ExportsDefinition", "ExportsBody", "ExportsElement", "ValueSet",
"ValueSetTypeAssignment", "DefinedType", "DataTypeReference",
"ParameterArgumentList", "ParameterArgumentName", "ActualParameterList",
"ActualParameter", "optComponentTypeLists", "ComponentTypeLists",
"ComponentType", "AlternativeTypeLists", "AlternativeType",
"ObjectClass", "optUnique", "FieldSpec", "ClassField", "optWithSyntax",
"WithSyntax", "@3", "WithSyntaxList", "WithSyntaxToken",
"ExtensionAndException", "Type", "NSTD_IndirectMarker",
"TypeDeclaration", "TypeDeclarationSet", "ComplexTypeReference",
"ComplexTypeReferenceAmpList", "ComplexTypeReferenceElement",
"PrimitiveFieldReference", "FieldName", "DefinedObjectClass",
"ValueAssignment", "Value", "@4", "SimpleValue", "DefinedValue",
"RestrictedCharacterStringValue", "Opaque", "BasicTypeId",
"BasicTypeId_UniverationCompatible", "BasicType", "BasicString",
"UnionMark", "IntersectionMark", "optConstraints", "Constraint",
"SubtypeConstraint", "SetOfConstraints", "ElementSetSpecs",
"ElementSetSpec", "Unions", "Intersections", "IntersectionElements",
"ConstraintSubtypeElement", "PatternConstraint", "ConstraintSpec",
"SingleValue", "BitStringValue", "ContainedSubtype",
"InnerTypeConstraint", "WithComponentsList", "WithComponentsElement",
"optPresenceConstraint", "PresenceConstraint", "GeneralConstraint",
"UserDefinedConstraint", "@5", "ContentsConstraint",
"ConstraintRangeSpec", "TableConstraint", "SimpleTableConstraint",
"ComponentRelationConstraint", "AtNotationList", "AtNotationElement",
"ComponentIdList", "optMarker", "Marker", "UniverationDefinition",
"UniverationList", "UniverationElement", "SignedNumber", "RealValue",
"optTag", "Tag", "TagTypeValue", "TagClass", "TagPlicit", "TypeRefName",
"ObjectClassReference", "optIdentifier", "Identifier", 0
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
token YYLEX-NUM. */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354,
355, 356, 357, 358, 94, 359, 124, 360, 361, 362,
123, 125, 40, 41, 59, 44, 58, 91, 93, 33,
46, 60, 64
};
# endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 123, 124, 125, 125, 127, 126, 128, 128, 129,
129, 130, 130, 131, 131, 131, 132, 132, 133, 133,
134, 134, 134, 134, 134, 135, 135, 136, 137, 137,
138, 138, 138, 139, 138, 138, 140, 140, 141, 141,
142, 142, 143, 143, 144, 144, 145, 146, 146, 147,
147, 147, 148, 148, 149, 149, 149, 150, 150, 151,
151, 151, 152, 153, 154, 154, 154, 155, 155, 155,
155, 156, 156, 157, 157, 157, 157, 157, 158, 158,
159, 159, 159, 159, 160, 160, 161, 161, 161, 162,
162, 162, 162, 163, 163, 164, 164, 164, 165, 166,
166, 167, 167, 168, 168, 168, 168, 168, 168, 168,
169, 169, 171, 170, 172, 172, 173, 173, 173, 173,
174, 174, 174, 175, 176, 177, 178, 178, 178, 178,
178, 178, 178, 178, 178, 179, 179, 179, 179, 179,
179, 180, 180, 181, 182, 182, 183, 183, 183, 184,
185, 186, 186, 186, 187, 186, 186, 188, 188, 188,
188, 188, 188, 189, 189, 190, 190, 190, 191, 191,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 193, 193, 193, 194, 194, 195, 195,
195, 195, 195, 195, 195, 195, 195, 195, 195, 195,
195, 195, 196, 196, 197, 197, 198, 198, 199, 200,
200, 201, 201, 202, 202, 202, 202, 202, 203, 203,
204, 204, 205, 205, 206, 206, 207, 207, 207, 207,
207, 207, 207, 207, 207, 207, 208, 208, 209, 209,
210, 210, 210, 210, 210, 210, 211, 211, 212, 213,
213, 214, 214, 215, 215, 216, 216, 217, 217, 217,
218, 218, 218, 220, 219, 221, 222, 222, 222, 222,
223, 223, 224, 225, 226, 226, 227, 227, 228, 228,
229, 229, 230, 230, 231, 231, 232, 232, 233, 233,
233, 233, 233, 234, 234, 235, 235, 236, 236, 237,
238, 239, 239, 239, 239, 240, 240, 240, 241, 241,
242, 243, 243, 244
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 1, 1, 2, 0, 9, 0, 1, 3,
2, 1, 2, 1, 4, 1, 0, 1, 1, 2,
2, 2, 2, 2, 2, 0, 1, 3, 1, 2,
1, 1, 1, 0, 3, 1, 0, 1, 3, 2,
0, 1, 1, 2, 0, 1, 4, 1, 3, 1,
3, 1, 0, 1, 3, 3, 2, 1, 3, 1,
3, 1, 3, 4, 1, 1, 4, 3, 3, 6,
6, 1, 3, 1, 3, 3, 3, 3, 1, 3,
1, 1, 1, 1, 0, 1, 1, 3, 5, 3,
2, 3, 1, 1, 3, 2, 1, 1, 5, 0,
1, 1, 3, 2, 4, 3, 3, 3, 3, 3,
0, 1, 0, 6, 1, 2, 1, 1, 1, 3,
1, 3, 3, 3, 0, 2, 1, 4, 4, 4,
6, 6, 1, 4, 3, 1, 3, 3, 3, 1,
3, 1, 3, 1, 1, 1, 1, 3, 3, 1,
4, 1, 1, 3, 0, 3, 1, 1, 1, 1,
1, 1, 1, 1, 3, 1, 1, 1, 1, 2,
1, 1, 1, 1, 2, 2, 1, 1, 2, 2,
1, 1, 1, 1, 1, 2, 1, 2, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
4, 3, 4, 1, 1, 3, 5, 1, 1, 3,
1, 3, 1, 3, 1, 3, 4, 3, 1, 1,
3, 3, 3, 3, 1, 1, 2, 2, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
5, 1, 3, 1, 3, 0, 1, 1, 1, 1,
1, 1, 1, 0, 5, 2, 1, 2, 2, 3,
1, 1, 3, 4, 1, 3, 2, 3, 1, 3,
0, 1, 1, 2, 2, 3, 1, 3, 1, 4,
4, 1, 1, 1, 1, 1, 1, 0, 1, 2,
4, 0, 1, 1, 1, 0, 1, 1, 1, 1,
1, 0, 1, 1
};
/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
STATE-NUM when YYTABLE doesn't specify something else to do. Zero
means the default is an error. */
static const yytype_uint16 yydefact[] =
{
0, 308, 309, 0, 2, 3, 5, 1, 4, 7,
0, 0, 8, 313, 15, 10, 0, 11, 13, 16,
9, 12, 0, 0, 0, 0, 0, 0, 0, 17,
18, 0, 24, 22, 20, 23, 21, 0, 19, 14,
52, 0, 0, 26, 36, 53, 0, 56, 0, 57,
59, 61, 6, 40, 0, 37, 55, 54, 0, 0,
39, 0, 41, 42, 0, 47, 49, 51, 188, 0,
189, 190, 191, 192, 193, 201, 194, 195, 196, 197,
198, 199, 200, 27, 28, 32, 30, 31, 35, 0,
297, 58, 60, 38, 43, 0, 0, 0, 33, 29,
297, 135, 310, 0, 170, 0, 0, 184, 177, 181,
183, 171, 0, 0, 172, 176, 180, 0, 0, 65,
186, 173, 64, 182, 139, 301, 0, 124, 298, 305,
44, 48, 50, 34, 0, 68, 67, 0, 185, 179,
178, 175, 174, 0, 71, 0, 173, 73, 0, 297,
0, 187, 0, 303, 304, 302, 0, 0, 0, 206,
307, 306, 299, 45, 46, 0, 136, 138, 0, 0,
0, 0, 0, 63, 159, 165, 160, 293, 294, 166,
167, 157, 158, 83, 0, 78, 80, 81, 161, 162,
82, 292, 284, 0, 286, 291, 288, 144, 145, 140,
141, 143, 137, 0, 156, 154, 150, 151, 152, 0,
163, 132, 0, 0, 206, 206, 126, 125, 0, 0,
123, 207, 208, 209, 297, 297, 0, 101, 297, 72,
77, 76, 75, 74, 246, 247, 296, 0, 0, 297,
240, 239, 0, 0, 238, 241, 0, 213, 0, 0,
243, 0, 214, 218, 220, 222, 224, 235, 0, 228,
244, 229, 234, 217, 260, 262, 261, 270, 271, 295,
242, 248, 245, 66, 297, 285, 0, 0, 0, 300,
0, 0, 0, 0, 297, 0, 297, 0, 297, 0,
0, 0, 0, 149, 146, 0, 282, 280, 280, 280,
103, 281, 99, 280, 280, 110, 0, 70, 69, 0,
0, 265, 266, 0, 0, 236, 237, 0, 0, 0,
0, 62, 0, 202, 203, 0, 204, 205, 0, 0,
0, 0, 0, 79, 287, 0, 0, 163, 142, 168,
155, 164, 153, 0, 120, 0, 93, 96, 97, 297,
134, 0, 0, 85, 86, 92, 280, 297, 311, 0,
311, 0, 211, 0, 283, 108, 0, 107, 109, 100,
280, 105, 106, 0, 98, 111, 102, 219, 263, 267,
268, 233, 231, 249, 0, 272, 227, 215, 221, 223,
225, 0, 232, 230, 0, 0, 274, 290, 289, 169,
133, 0, 127, 297, 95, 297, 128, 297, 90, 280,
297, 312, 129, 297, 210, 212, 147, 148, 104, 0,
0, 269, 253, 0, 251, 206, 0, 226, 0, 276,
278, 273, 0, 121, 122, 94, 91, 297, 87, 89,
124, 124, 112, 264, 250, 0, 255, 216, 277, 0,
275, 0, 130, 131, 0, 252, 258, 259, 257, 254,
256, 279, 88, 116, 117, 0, 0, 114, 118, 0,
113, 115, 119
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 3, 4, 5, 9, 11, 12, 16, 17, 28,
29, 30, 42, 43, 83, 84, 133, 54, 55, 61,
62, 164, 63, 64, 65, 44, 45, 48, 49, 183,
85, 118, 86, 143, 144, 184, 185, 352, 353, 354,
345, 346, 135, 370, 226, 227, 374, 375, 454, 466,
467, 355, 356, 158, 159, 217, 119, 199, 200, 468,
298, 299, 87, 206, 280, 207, 208, 250, 340, 120,
121, 122, 123, 325, 328, 220, 221, 222, 223, 251,
252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
262, 423, 424, 459, 460, 263, 264, 420, 265, 314,
266, 267, 268, 395, 396, 429, 300, 301, 151, 193,
194, 269, 270, 127, 128, 129, 156, 162, 271, 124,
410, 272
};
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
#define YYPACT_NINF -276
static const yytype_int16 yypact[] =
{
223, -276, -276, 28, 223, -276, -276, -276, -276, -61,
13, 25, -276, -276, -276, -276, 42, -276, -56, 229,
-276, -276, 90, 54, 32, 64, 129, 79, 193, 229,
-276, 104, -276, -276, -276, -276, -276, 197, -276, -276,
133, 66, 185, -276, 191, -276, 144, -276, 154, -276,
176, -276, -276, 196, 524, -276, -276, -276, 237, 149,
-276, 177, 237, -276, -26, -276, 189, -276, -276, 291,
-276, -276, -276, -276, -276, -276, -276, -276, -276, -276,
-276, -276, -276, 524, -276, -276, -276, -276, -276, 272,
200, -276, -276, -276, -276, 223, 237, 209, -276, -276,
-18, 202, -276, 247, -276, 253, 269, -276, -276, -276,
-276, -276, 296, 261, -276, -276, -276, 692, 356, 255,
-276, 258, -276, -276, 243, 77, 372, -276, -276, 184,
-61, -276, -276, -276, 266, -276, -276, 237, -276, -276,
-276, -276, -276, -64, -276, 262, -276, 263, 267, 99,
84, -276, 294, -276, -276, -276, 368, 211, 616, -57,
-276, -276, -276, -276, -276, 288, -276, -276, 378, 692,
237, 237, 399, -276, -276, -276, -276, -276, -276, -276,
-276, -276, -276, -276, 150, -276, -276, -276, -276, -276,
-276, -276, -276, 169, -276, -276, 271, -276, -276, 265,
-276, -276, -276, 268, -276, -276, -276, -276, -276, 270,
273, 345, 278, 317, 78, 124, -276, -276, 282, 399,
-276, -276, -276, 283, 219, 46, 181, -276, -18, -276,
-276, -276, -276, -276, -276, -276, -276, 293, 366, 200,
-276, -276, 63, 199, -276, -276, 295, -276, 223, 399,
-276, 289, 284, 218, 235, -276, 298, -276, 290, 63,
-276, -276, -276, -276, -276, -276, -276, 309, -276, -276,
-276, -276, -276, -276, 99, -276, 69, 233, 332, -276,
396, 393, 211, 373, 49, 340, 8, 346, 8, 347,
399, 307, 399, -276, -276, 211, -276, -8, 110, -8,
-276, -276, 329, 110, -8, 323, 288, -276, -276, 550,
316, -276, 308, 320, 190, -276, -276, 318, 321, 322,
319, -276, 325, -276, -276, 550, -276, -276, 550, 550,
399, 432, 314, -276, -276, 336, 337, -276, -276, -276,
457, -276, -276, 393, 349, 182, -276, -276, -276, 200,
-276, 390, 355, 357, -276, -276, -8, 200, 393, 359,
393, 358, -276, 360, -276, -276, 341, -276, -276, -276,
-8, -276, -276, 385, -276, -276, -276, -276, -276, -276,
354, -276, -276, 283, 74, -276, -276, 362, 235, -276,
-276, 365, -276, -276, 0, 183, -276, -276, -276, -276,
-276, 233, -276, 49, -276, 200, -276, 4, -276, -8,
200, -276, -276, 200, -276, -276, -276, -276, -276, 369,
396, -276, -276, 195, -276, -57, 445, -276, 393, 361,
-276, -276, 314, -276, -276, -276, -276, 68, -276, -276,
-276, -276, -276, 457, -276, 74, 159, -276, 361, 393,
-276, 11, -276, -276, 55, -276, -276, -276, -276, -276,
-276, -276, -276, -276, -276, 55, 17, -276, -276, 51,
-276, -276, -276
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int16 yypgoto[] =
{
-276, -276, -276, 476, -276, -276, 352, -276, 467, -276,
-276, 456, -276, -276, -276, 404, -276, -276, -276, -276,
-276, -276, 426, -276, 394, -276, -276, -276, 431, 343,
-276, 335, -276, -276, 326, -276, 220, 208, 65, 93,
-276, 100, 276, -276, -276, 201, -276, -276, -276, 40,
-275, -270, -87, -276, -74, -276, 221, -276, 232, -148,
287, 292, -276, -166, -276, -142, -265, -139, 94, -91,
-75, -276, 15, -276, -276, -213, -276, -276, 198, -199,
92, -276, 194, 188, -165, -276, -276, -227, -276, -276,
-276, -276, 75, -276, -276, -276, -276, -276, -276, 264,
-276, -276, -276, -276, 89, 96, -264, -276, -276, -276,
250, -128, -276, -195, -276, -276, -276, -276, 5, -276,
167, -10
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If zero, do what YYDEFACT says.
If YYTABLE_NINF, syntax error. */
#define YYTABLE_NINF -281
static const yytype_int16 yytable[] =
{
18, 287, 289, 126, 201, 6, 18, 187, 437, 6,
188, 13, 335, 136, 347, 13, 462, 134, 188, 13,
291, 189, 195, 463, 13, 14, 145, 95, 7, 189,
218, 51, 295, 365, 367, 368, 197, 198, 464, 371,
372, 351, 146, 67, 90, 351, 50, 168, 51, 10,
320, 169, 67, 13, 14, 219, 22, 463, 66, 89,
13, 463, 186, 50, 293, 294, 19, 66, 296, 88,
197, 198, 464, 90, 197, 198, 464, 13, 145, 13,
13, 177, 178, 1, 2, 13, 67, 382, 89, 96,
46, 361, 408, 363, 146, 13, 177, 178, 88, 125,
130, 66, 31, 153, 393, 351, 418, 174, 175, 176,
13, 177, 178, 344, 179, 180, 342, 344, 32, -84,
428, 125, 147, 33, 15, 125, 407, 167, 470, 364,
201, 391, 187, 347, 465, 188, 433, 297, 302, 190,
196, 308, 166, 188, 377, 439, 189, 210, 195, 336,
295, 181, 311, 20, 189, 34, 188, 202, 344, 154,
231, 233, 209, 125, 390, 218, 125, 189, 465, 472,
36, 312, 465, 155, 147, 230, 232, 344, 191, -25,
47, 456, 41, 422, 313, 125, 296, 186, 286, 35,
219, 471, 182, 191, 471, 192, 37, 348, 234, 175,
235, 13, 177, 178, 236, 179, 180, 13, 315, 172,
13, 218, 446, 1, 2, 440, 125, 39, 441, 174,
175, 176, 13, 177, 178, 40, 179, 180, 1, 2,
366, 52, 160, 316, 288, 457, 219, 293, 294, 458,
1, 2, 240, 161, 13, 177, 178, 23, 13, 60,
1, 2, 53, 319, 1, 2, 24, 381, 56, 295,
92, 273, 404, 181, 190, 274, 196, 337, 57, 58,
409, 341, 210, 434, 349, 100, 357, 25, 357, 26,
275, 204, 209, 245, 276, 210, 59, 209, 27, 101,
102, 93, 305, 402, 431, 296, 306, 403, 432, 97,
209, 103, 68, 104, 182, 105, 444, 224, 225, 98,
445, 1, 2, 197, 198, 106, 348, 125, 436, 107,
132, 205, 137, 108, 323, 324, 109, 70, 71, 72,
-280, 317, 318, 400, -280, 138, 125, 110, 73, 326,
327, 139, 111, 74, 112, 75, 113, 140, 411, 142,
411, 197, 198, 76, 141, 114, 115, 101, 102, 148,
416, 417, 77, 152, 78, 149, 452, 453, 150, 79,
116, 80, 81, 82, 425, 157, 165, 172, 170, 171,
203, 228, 117, 277, 430, 278, 279, 283, 284, 282,
281, 337, 285, 349, 290, 292, 309, 357, 310, 322,
321, 329, 330, 339, 13, 343, 209, 234, 175, 235,
13, 177, 178, 236, 179, 180, 1, 2, 430, 332,
362, 358, 360, 237, 369, 373, 378, 357, 380, 379,
219, 384, 386, 385, 387, 425, 394, 238, 239, 461,
234, 175, 235, 13, 177, 178, 236, 179, 180, 397,
398, 240, 241, 234, 175, 235, 13, 177, 178, 236,
179, 180, 1, 2, 399, 405, 406, 242, 401, 237,
412, 414, 407, 415, 419, 421, 243, 426, 427, 442,
8, 449, 163, 21, 240, 38, 244, 99, 94, 91,
131, 173, 245, 216, 333, 229, 359, 240, 241, 392,
438, 246, 451, 435, 307, 469, 350, 376, 247, 248,
338, 249, 303, 242, 443, 383, 389, 304, 447, 388,
455, 450, 243, 331, 448, 245, 334, 413, 0, 0,
0, 0, 244, 0, 0, 13, 0, 0, 245, 0,
0, 1, 2, 0, 0, 0, 0, 246, 0, 0,
0, 0, 0, 0, 68, 0, 0, 249, 234, 175,
235, 13, 177, 178, 236, 179, 180, 1, 2, 69,
0, 0, 0, 0, 0, 0, 0, 0, 0, 70,
71, 72, 0, 0, 0, 0, 0, 0, 0, 0,
73, 0, 0, 0, 0, 74, 0, 75, 0, 0,
0, 0, 240, 241, 0, 76, 0, 0, 0, 0,
0, 0, 0, 0, 77, 0, 78, 0, 242, 0,
0, 79, 0, 80, 81, 82, 0, 243, 0, 0,
0, 0, 0, 101, 102, 0, 0, 244, 0, 0,
0, 211, 0, 245, 0, 103, 68, 104, 0, 105,
212, 0, 246, 0, 0, 0, 0, 0, 0, 106,
0, 0, 249, 107, 0, 0, 0, 108, 0, 0,
109, 70, 71, 72, 0, 0, 0, 0, 0, 213,
0, 110, 73, 0, 0, 0, 111, 74, 112, 75,
113, 0, 0, 0, 0, 0, 0, 76, 0, 114,
115, 214, 215, 0, 0, 0, 77, 0, 78, 1,
2, 0, 0, 79, 116, 80, 81, 82, 0, 0,
0, 103, 68, 104, 0, 105, 0, 0, 0, 0,
0, 0, 0, 0, 0, 106, 0, 0, 0, 107,
0, 0, 0, 108, 0, 0, 109, 70, 71, 72,
0, 0, 0, 0, 0, 0, 0, 110, 73, 0,
0, 0, 111, 74, 112, 75, 113, 0, 0, 0,
0, 0, 0, 76, 0, 114, 115, 0, 0, 0,
0, 0, 77, 0, 78, 0, 0, 0, 0, 79,
116, 80, 81, 82
};
static const yytype_int16 yycheck[] =
{
10, 214, 215, 90, 152, 0, 16, 149, 4, 4,
149, 11, 277, 100, 284, 11, 5, 35, 157, 11,
219, 149, 150, 6, 11, 12, 117, 53, 0, 157,
87, 41, 40, 297, 298, 299, 19, 20, 21, 303,
304, 37, 117, 53, 54, 37, 41, 111, 58, 110,
249, 115, 62, 11, 12, 112, 112, 6, 53, 54,
11, 6, 149, 58, 18, 19, 41, 62, 76, 54,
19, 20, 21, 83, 19, 20, 21, 11, 169, 11,
11, 12, 13, 17, 18, 11, 96, 314, 83, 115,
24, 290, 356, 292, 169, 11, 12, 13, 83, 117,
95, 96, 12, 26, 331, 37, 370, 8, 9, 10,
11, 12, 13, 109, 15, 16, 282, 109, 64, 111,
120, 117, 117, 91, 111, 117, 115, 137, 111, 295,
278, 330, 274, 403, 117, 274, 401, 224, 225, 149,
150, 228, 137, 282, 309, 409, 274, 157, 276, 277,
40, 52, 239, 111, 282, 91, 295, 152, 109, 82,
170, 171, 157, 117, 329, 87, 117, 295, 117, 118,
91, 108, 117, 96, 169, 170, 171, 109, 109, 46,
114, 22, 49, 109, 121, 117, 76, 274, 110, 60,
112, 466, 93, 109, 469, 111, 3, 284, 8, 9,
10, 11, 12, 13, 14, 15, 16, 11, 9, 110,
11, 87, 425, 17, 18, 410, 117, 113, 413, 8,
9, 10, 11, 12, 13, 28, 15, 16, 17, 18,
120, 46, 48, 243, 110, 76, 112, 18, 19, 80,
17, 18, 52, 59, 11, 12, 13, 18, 11, 53,
17, 18, 61, 248, 17, 18, 27, 67, 114, 40,
111, 111, 349, 52, 274, 115, 276, 277, 114, 115,
357, 281, 282, 401, 284, 3, 286, 48, 288, 50,
111, 70, 277, 93, 115, 295, 110, 282, 59, 17,
18, 114, 111, 111, 111, 76, 115, 115, 115, 110,
295, 29, 30, 31, 93, 33, 111, 19, 20, 18,
115, 17, 18, 19, 20, 43, 403, 117, 405, 47,
111, 110, 120, 51, 106, 107, 54, 55, 56, 57,
111, 36, 37, 343, 115, 88, 117, 65, 66, 104,
105, 88, 70, 71, 72, 73, 74, 78, 358, 88,
360, 19, 20, 81, 58, 83, 84, 17, 18, 3,
19, 20, 90, 120, 92, 110, 440, 441, 110, 97,
98, 99, 100, 101, 384, 3, 110, 110, 116, 116,
12, 3, 110, 112, 394, 120, 118, 42, 110, 116,
120, 401, 75, 403, 112, 112, 103, 407, 32, 115,
111, 103, 112, 7, 11, 32, 401, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 428, 110,
113, 75, 75, 24, 95, 102, 110, 437, 108, 121,
112, 110, 113, 111, 109, 445, 122, 38, 39, 449,
8, 9, 10, 11, 12, 13, 14, 15, 16, 113,
113, 52, 53, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 7, 75, 111, 68, 119, 24,
111, 113, 115, 113, 89, 121, 77, 115, 113, 110,
4, 120, 130, 16, 52, 29, 87, 83, 62, 58,
96, 148, 93, 158, 274, 169, 288, 52, 53, 67,
407, 102, 437, 403, 228, 465, 285, 306, 109, 110,
278, 112, 225, 68, 420, 317, 328, 225, 426, 325,
445, 432, 77, 259, 428, 93, 276, 360, -1, -1,
-1, -1, 87, -1, -1, 11, -1, -1, 93, -1,
-1, 17, 18, -1, -1, -1, -1, 102, -1, -1,
-1, -1, -1, -1, 30, -1, -1, 112, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 45,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 55,
56, 57, -1, -1, -1, -1, -1, -1, -1, -1,
66, -1, -1, -1, -1, 71, -1, 73, -1, -1,
-1, -1, 52, 53, -1, 81, -1, -1, -1, -1,
-1, -1, -1, -1, 90, -1, 92, -1, 68, -1,
-1, 97, -1, 99, 100, 101, -1, 77, -1, -1,
-1, -1, -1, 17, 18, -1, -1, 87, -1, -1,
-1, 25, -1, 93, -1, 29, 30, 31, -1, 33,
34, -1, 102, -1, -1, -1, -1, -1, -1, 43,
-1, -1, 112, 47, -1, -1, -1, 51, -1, -1,
54, 55, 56, 57, -1, -1, -1, -1, -1, 63,
-1, 65, 66, -1, -1, -1, 70, 71, 72, 73,
74, -1, -1, -1, -1, -1, -1, 81, -1, 83,
84, 85, 86, -1, -1, -1, 90, -1, 92, 17,
18, -1, -1, 97, 98, 99, 100, 101, -1, -1,
-1, 29, 30, 31, -1, 33, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 43, -1, -1, -1, 47,
-1, -1, -1, 51, -1, -1, 54, 55, 56, 57,
-1, -1, -1, -1, -1, -1, -1, 65, 66, -1,
-1, -1, 70, 71, 72, 73, 74, -1, -1, -1,
-1, -1, -1, 81, -1, 83, 84, -1, -1, -1,
-1, -1, 90, -1, 92, -1, -1, -1, -1, 97,
98, 99, 100, 101
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 17, 18, 124, 125, 126, 241, 0, 126, 127,
110, 128, 129, 11, 12, 111, 130, 131, 244, 41,
111, 131, 112, 18, 27, 48, 50, 59, 132, 133,
134, 12, 64, 91, 91, 60, 91, 3, 134, 113,
28, 49, 135, 136, 148, 149, 24, 114, 150, 151,
241, 244, 46, 61, 140, 141, 114, 114, 115, 110,
53, 142, 143, 145, 146, 147, 241, 244, 30, 45,
55, 56, 57, 66, 71, 73, 81, 90, 92, 97,
99, 100, 101, 137, 138, 153, 155, 185, 195, 241,
244, 151, 111, 114, 145, 53, 115, 110, 18, 138,
3, 17, 18, 29, 31, 33, 43, 47, 51, 54,
65, 70, 72, 74, 83, 84, 98, 110, 154, 179,
192, 193, 194, 195, 242, 117, 175, 236, 237, 238,
241, 147, 111, 139, 35, 165, 175, 120, 88, 88,
78, 58, 88, 156, 157, 192, 193, 241, 3, 110,
110, 231, 120, 26, 82, 96, 239, 3, 176, 177,
48, 59, 240, 129, 144, 110, 241, 244, 111, 115,
116, 116, 110, 152, 8, 9, 10, 12, 13, 15,
16, 52, 93, 152, 158, 159, 175, 188, 190, 234,
244, 109, 111, 232, 233, 234, 244, 19, 20, 180,
181, 182, 241, 12, 70, 110, 186, 188, 189, 241,
244, 25, 34, 63, 85, 86, 154, 178, 87, 112,
198, 199, 200, 201, 19, 20, 167, 168, 3, 157,
241, 244, 241, 244, 8, 10, 14, 24, 38, 39,
52, 53, 68, 77, 87, 93, 102, 109, 110, 112,
190, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 213, 218, 219, 221, 223, 224, 225, 234,
235, 241, 244, 111, 115, 111, 115, 112, 120, 118,
187, 120, 116, 42, 110, 75, 110, 198, 110, 198,
112, 202, 112, 18, 19, 40, 76, 175, 183, 184,
229, 230, 175, 183, 184, 111, 115, 165, 175, 103,
32, 175, 108, 121, 222, 9, 244, 36, 37, 241,
202, 111, 115, 106, 107, 196, 104, 105, 197, 103,
112, 222, 110, 159, 233, 189, 234, 244, 181, 7,
191, 244, 186, 32, 109, 163, 164, 174, 175, 244,
179, 37, 160, 161, 162, 174, 175, 244, 75, 160,
75, 202, 113, 202, 186, 229, 120, 229, 229, 95,
166, 229, 229, 102, 169, 170, 168, 207, 110, 121,
108, 67, 210, 201, 110, 111, 113, 109, 205, 206,
207, 202, 67, 210, 122, 226, 227, 113, 113, 7,
244, 119, 111, 115, 175, 75, 111, 115, 229, 175,
243, 244, 111, 243, 113, 113, 19, 20, 229, 89,
220, 121, 109, 214, 215, 244, 115, 113, 120, 228,
244, 111, 115, 189, 234, 164, 175, 4, 162, 229,
236, 236, 110, 191, 111, 115, 198, 203, 228, 120,
227, 161, 177, 177, 171, 215, 22, 76, 80, 216,
217, 244, 5, 6, 21, 117, 172, 173, 182, 172,
111, 173, 118
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
/* Like YYERROR except do call yyerror. This remains here temporarily
to ease the transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. */
#define YYFAIL goto yyerrlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ \
yychar = (Token); \
yylval = (Value); \
yytoken = YYTRANSLATE (yychar); \
YYPOPSTACK (1); \
goto yybackup; \
} \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (YYID (0))
#define YYTERROR 1
#define YYERRCODE 256
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (YYID (N)) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (YYID (0))
#endif
/* YY_LOCATION_PRINT -- Print the location on the stream.
This macro was not mandated originally: define only if we know
we won't break user code: when these are the locations we know. */
#ifndef YY_LOCATION_PRINT
# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
# define YY_LOCATION_PRINT(File, Loc) \
fprintf (File, "%d.%d-%d.%d", \
(Loc).first_line, (Loc).first_column, \
(Loc).last_line, (Loc).last_column)
# else
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
#endif
/* YYLEX -- calling `yylex' with the right arguments. */
#ifdef YYLEX_PARAM
# define YYLEX yylex (YYLEX_PARAM)
#else
# define YYLEX yylex ()
#endif
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (YYID (0))
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value); \
YYFPRINTF (stderr, "\n"); \
} \
} while (YYID (0))
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_value_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# else
YYUSE (yyoutput);
# endif
switch (yytype)
{
default:
break;
}
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (yytype < YYNTOKENS)
YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
else
YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
#else
static void
yy_stack_print (bottom, top)
yytype_int16 *bottom;
yytype_int16 *top;
#endif
{
YYFPRINTF (stderr, "Stack now");
for (; bottom <= top; ++bottom)
YYFPRINTF (stderr, " %d", *bottom);
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (YYID (0))
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
#else
static void
yy_reduce_print (yyvsp, yyrule)
YYSTYPE *yyvsp;
int yyrule;
#endif
{
int yynrhs = yyr2[yyrule];
int yyi;
unsigned long int yylno = yyrline[yyrule];
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
fprintf (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
&(yyvsp[(yyi + 1) - (yynrhs)])
);
fprintf (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyvsp, Rule); \
} while (YYID (0))
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
#else
static YYSIZE_T
yystrlen (yystr)
const char *yystr;
#endif
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
#else
static char *
yystpcpy (yydest, yysrc)
char *yydest;
const char *yysrc;
#endif
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into YYRESULT an error message about the unexpected token
YYCHAR while in state YYSTATE. Return the number of bytes copied,
including the terminating null byte. If YYRESULT is null, do not
copy anything; just return the number of bytes that would be
copied. As a special case, return 0 if an ordinary "syntax error"
message will do. Return YYSIZE_MAXIMUM if overflow occurs during
size calculation. */
static YYSIZE_T
yysyntax_error (char *yyresult, int yystate, int yychar)
{
int yyn = yypact[yystate];
if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
return 0;
else
{
int yytype = YYTRANSLATE (yychar);
YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
YYSIZE_T yysize = yysize0;
YYSIZE_T yysize1;
int yysize_overflow = 0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
int yyx;
# if 0
/* This is so xgettext sees the translatable formats that are
constructed on the fly. */
YY_("syntax error, unexpected %s");
YY_("syntax error, unexpected %s, expecting %s");
YY_("syntax error, unexpected %s, expecting %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
# endif
char *yyfmt;
char const *yyf;
static char const yyunexpected[] = "syntax error, unexpected %s";
static char const yyexpecting[] = ", expecting %s";
static char const yyor[] = " or %s";
char yyformat[sizeof yyunexpected
+ sizeof yyexpecting - 1
+ ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
* (sizeof yyor - 1))];
char const *yyprefix = yyexpecting;
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yycount = 1;
yyarg[0] = yytname[yytype];
yyfmt = yystpcpy (yyformat, yyunexpected);
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
yyformat[sizeof yyunexpected - 1] = '\0';
break;
}
yyarg[yycount++] = yytname[yyx];
yysize1 = yysize + yytnamerr (0, yytname[yyx]);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
yyfmt = yystpcpy (yyfmt, yyprefix);
yyprefix = yyor;
}
yyf = YY_(yyformat);
yysize1 = yysize + yystrlen (yyf);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
if (yysize_overflow)
return YYSIZE_MAXIMUM;
if (yyresult)
{
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
char *yyp = yyresult;
int yyi = 0;
while ((*yyp = *yyf) != '\0')
{
if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyf += 2;
}
else
{
yyp++;
yyf++;
}
}
}
return yysize;
}
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
#else
static void
yydestruct (yymsg, yytype, yyvaluep)
const char *yymsg;
int yytype;
YYSTYPE *yyvaluep;
#endif
{
YYUSE (yyvaluep);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
default:
break;
}
}
/* Prevent warnings from -Wmissing-prototypes. */
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (void);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */
/* The look-ahead symbol. */
int yychar;
/* The semantic value of the look-ahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*----------.
| yyparse. |
`----------*/
#ifdef YYPARSE_PARAM
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void *YYPARSE_PARAM)
#else
int
yyparse (YYPARSE_PARAM)
void *YYPARSE_PARAM;
#endif
#else /* ! YYPARSE_PARAM */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void)
#else
int
yyparse ()
#endif
#endif
{
int yystate;
int yyn;
int yyresult;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* Look-ahead token as an internal (translated) token number. */
int yytoken = 0;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
/* Three stacks and their tools:
`yyss': related to states,
`yyvs': related to semantic values,
`yyls': related to locations.
Refer to the stacks thru separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss = yyssa;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs = yyvsa;
YYSTYPE *yyvsp;
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
YYSIZE_T yystacksize = YYINITDEPTH;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss;
yyvsp = yyvs;
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss);
YYSTACK_RELOCATE (yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
look-ahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to look-ahead token. */
yyn = yypact[yystate];
if (yyn == YYPACT_NINF)
goto yydefault;
/* Not known => get a look-ahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = YYLEX;
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yyn == 0 || yyn == YYTABLE_NINF)
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
if (yyn == YYFINAL)
YYACCEPT;
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the look-ahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token unless it is eof. */
if (yychar != YYEOF)
yychar = YYEMPTY;
yystate = yyn;
*++yyvsp = yylval;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
#line 357 "asn1p_y.y"
{
*(void **)param = (yyvsp[(1) - (1)].a_grammar);
}
break;
case 3:
#line 363 "asn1p_y.y"
{
(yyval.a_grammar) = asn1p_new();
checkmem((yyval.a_grammar));
TQ_ADD(&((yyval.a_grammar)->modules), (yyvsp[(1) - (1)].a_module), mod_next);
}
break;
case 4:
#line 368 "asn1p_y.y"
{
(yyval.a_grammar) = (yyvsp[(1) - (2)].a_grammar);
TQ_ADD(&((yyval.a_grammar)->modules), (yyvsp[(2) - (2)].a_module), mod_next);
}
break;
case 5:
#line 385 "asn1p_y.y"
{ currentModule = asn1p_module_new(); }
break;
case 6:
#line 390 "asn1p_y.y"
{
(yyval.a_module) = currentModule;
if((yyvsp[(8) - (9)].a_module)) {
asn1p_module_t tmp = *((yyval.a_module));
*((yyval.a_module)) = *((yyvsp[(8) - (9)].a_module));
*((yyvsp[(8) - (9)].a_module)) = tmp;
asn1p_module_free((yyvsp[(8) - (9)].a_module));
} else {
/* There's a chance that a module is just plain empty */
}
(yyval.a_module)->ModuleName = (yyvsp[(1) - (9)].tv_str);
(yyval.a_module)->module_oid = (yyvsp[(3) - (9)].a_oid);
(yyval.a_module)->module_flags = (yyvsp[(5) - (9)].a_module_flags);
}
break;
case 7:
#line 414 "asn1p_y.y"
{ (yyval.a_oid) = 0; }
break;
case 8:
#line 415 "asn1p_y.y"
{ (yyval.a_oid) = (yyvsp[(1) - (1)].a_oid); }
break;
case 9:
#line 419 "asn1p_y.y"
{
(yyval.a_oid) = (yyvsp[(2) - (3)].a_oid);
}
break;
case 10:
#line 422 "asn1p_y.y"
{
(yyval.a_oid) = 0;
}
break;
case 11:
#line 428 "asn1p_y.y"
{
(yyval.a_oid) = asn1p_oid_new();
asn1p_oid_add_arc((yyval.a_oid), &(yyvsp[(1) - (1)].a_oid_arc));
if((yyvsp[(1) - (1)].a_oid_arc).name)
free((yyvsp[(1) - (1)].a_oid_arc).name);
}
break;
case 12:
#line 434 "asn1p_y.y"
{
(yyval.a_oid) = (yyvsp[(1) - (2)].a_oid);
asn1p_oid_add_arc((yyval.a_oid), &(yyvsp[(2) - (2)].a_oid_arc));
if((yyvsp[(2) - (2)].a_oid_arc).name)
free((yyvsp[(2) - (2)].a_oid_arc).name);
}
break;
case 13:
#line 443 "asn1p_y.y"
{ /* iso */
(yyval.a_oid_arc).name = (yyvsp[(1) - (1)].tv_str);
(yyval.a_oid_arc).number = -1;
}
break;
case 14:
#line 447 "asn1p_y.y"
{ /* iso(1) */
(yyval.a_oid_arc).name = (yyvsp[(1) - (4)].tv_str);
(yyval.a_oid_arc).number = (yyvsp[(3) - (4)].a_int);
}
break;
case 15:
#line 451 "asn1p_y.y"
{ /* 1 */
(yyval.a_oid_arc).name = 0;
(yyval.a_oid_arc).number = (yyvsp[(1) - (1)].a_int);
}
break;
case 16:
#line 461 "asn1p_y.y"
{ (yyval.a_module_flags) = MSF_NOFLAGS; }
break;
case 17:
#line 462 "asn1p_y.y"
{
(yyval.a_module_flags) = (yyvsp[(1) - (1)].a_module_flags);
}
break;
case 18:
#line 471 "asn1p_y.y"
{
(yyval.a_module_flags) = (yyvsp[(1) - (1)].a_module_flags);
}
break;
case 19:
#line 474 "asn1p_y.y"
{
(yyval.a_module_flags) = (yyvsp[(1) - (2)].a_module_flags) | (yyvsp[(2) - (2)].a_module_flags);
}
break;
case 20:
#line 483 "asn1p_y.y"
{
(yyval.a_module_flags) = MSF_EXPLICIT_TAGS;
}
break;
case 21:
#line 486 "asn1p_y.y"
{
(yyval.a_module_flags) = MSF_IMPLICIT_TAGS;
}
break;
case 22:
#line 489 "asn1p_y.y"
{
(yyval.a_module_flags) = MSF_AUTOMATIC_TAGS;
}
break;
case 23:
#line 492 "asn1p_y.y"
{
(yyval.a_module_flags) = MSF_EXTENSIBILITY_IMPLIED;
}
break;
case 24:
#line 496 "asn1p_y.y"
{
/* X.680Amd1 specifies TAG and XER */
if(strcmp((yyvsp[(1) - (2)].tv_str), "TAG") == 0) {
(yyval.a_module_flags) = MSF_TAG_INSTRUCTIONS;
} else if(strcmp((yyvsp[(1) - (2)].tv_str), "XER") == 0) {
(yyval.a_module_flags) = MSF_XER_INSTRUCTIONS;
} else {
fprintf(stderr,
"WARNING: %s INSTRUCTIONS at line %d: "
"Unrecognized encoding reference\n",
(yyvsp[(1) - (2)].tv_str), yylineno);
(yyval.a_module_flags) = MSF_unk_INSTRUCTIONS;
}
free((yyvsp[(1) - (2)].tv_str));
}
break;
case 25:
#line 517 "asn1p_y.y"
{ (yyval.a_module) = 0; }
break;
case 26:
#line 518 "asn1p_y.y"
{
(yyval.a_module) = (yyvsp[(1) - (1)].a_module);
}
break;
case 27:
#line 527 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
AL_IMPORT((yyval.a_module), exports, (yyvsp[(1) - (3)].a_module), xp_next);
AL_IMPORT((yyval.a_module), imports, (yyvsp[(2) - (3)].a_module), xp_next);
AL_IMPORT((yyval.a_module), members, (yyvsp[(3) - (3)].a_module), next);
}
break;
case 28:
#line 536 "asn1p_y.y"
{
(yyval.a_module) = (yyvsp[(1) - (1)].a_module);
}
break;
case 29:
#line 539 "asn1p_y.y"
{
if((yyvsp[(1) - (2)].a_module)) {
(yyval.a_module) = (yyvsp[(1) - (2)].a_module);
} else {
(yyval.a_module) = (yyvsp[(2) - (2)].a_module);
break;
}
AL_IMPORT((yyval.a_module), members, (yyvsp[(2) - (2)].a_module), next);
}
break;
case 30:
#line 555 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
checkmem((yyval.a_module));
assert((yyvsp[(1) - (1)].a_expr)->expr_type != A1TC_INVALID);
assert((yyvsp[(1) - (1)].a_expr)->meta_type != AMT_INVALID);
TQ_ADD(&((yyval.a_module)->members), (yyvsp[(1) - (1)].a_expr), next);
}
break;
case 31:
#line 562 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
checkmem((yyval.a_module));
assert((yyvsp[(1) - (1)].a_expr)->expr_type != A1TC_INVALID);
assert((yyvsp[(1) - (1)].a_expr)->meta_type != AMT_INVALID);
TQ_ADD(&((yyval.a_module)->members), (yyvsp[(1) - (1)].a_expr), next);
}
break;
case 32:
#line 575 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
checkmem((yyval.a_module));
assert((yyvsp[(1) - (1)].a_expr)->expr_type != A1TC_INVALID);
assert((yyvsp[(1) - (1)].a_expr)->meta_type != AMT_INVALID);
TQ_ADD(&((yyval.a_module)->members), (yyvsp[(1) - (1)].a_expr), next);
}
break;
case 33:
#line 583 "asn1p_y.y"
{ asn1p_lexer_hack_push_encoding_control(); }
break;
case 34:
#line 584 "asn1p_y.y"
{
fprintf(stderr,
"WARNING: ENCODING-CONTROL %s "
"specification at line %d ignored\n",
(yyvsp[(2) - (3)].tv_str), yylineno);
free((yyvsp[(2) - (3)].tv_str));
(yyval.a_module) = 0;
}
break;
case 35:
#line 596 "asn1p_y.y"
{
return yyerror(
"Attempt to redefine a standard basic string type, "
"please comment out or remove this type redefinition.");
}
break;
case 36:
#line 609 "asn1p_y.y"
{ (yyval.a_module) = 0; }
break;
case 38:
#line 613 "asn1p_y.y"
{
if(!saved_aid && 0)
return yyerror("Unterminated IMPORTS FROM, "
"expected semicolon ';'");
saved_aid = 0;
(yyval.a_module) = (yyvsp[(2) - (3)].a_module);
}
break;
case 39:
#line 623 "asn1p_y.y"
{
return yyerror("Empty IMPORTS list");
}
break;
case 40:
#line 629 "asn1p_y.y"
{ (yyval.a_module) = asn1p_module_new(); }
break;
case 42:
#line 633 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
checkmem((yyval.a_module));
TQ_ADD(&((yyval.a_module)->imports), (yyvsp[(1) - (1)].a_xports), xp_next);
}
break;
case 43:
#line 638 "asn1p_y.y"
{
(yyval.a_module) = (yyvsp[(1) - (2)].a_module);
TQ_ADD(&((yyval.a_module)->imports), (yyvsp[(2) - (2)].a_xports), xp_next);
}
break;
case 44:
#line 645 "asn1p_y.y"
{ memset(&(yyval.a_aid), 0, sizeof((yyval.a_aid))); }
break;
case 45:
#line 646 "asn1p_y.y"
{ (yyval.a_aid).oid = (yyvsp[(1) - (1)].a_oid); }
break;
case 46:
#line 650 "asn1p_y.y"
{
(yyval.a_xports) = (yyvsp[(1) - (4)].a_xports);
(yyval.a_xports)->fromModuleName = (yyvsp[(3) - (4)].tv_str);
(yyval.a_xports)->identifier = (yyvsp[(4) - (4)].a_aid);
/* This stupid thing is used for look-back hack. */
saved_aid = (yyval.a_xports)->identifier.oid ? 0 : &((yyval.a_xports)->identifier);
checkmem((yyval.a_xports));
}
break;
case 47:
#line 661 "asn1p_y.y"
{
(yyval.a_xports) = asn1p_xports_new();
checkmem((yyval.a_xports));
TQ_ADD(&((yyval.a_xports)->members), (yyvsp[(1) - (1)].a_expr), next);
}
break;
case 48:
#line 666 "asn1p_y.y"
{
(yyval.a_xports) = (yyvsp[(1) - (3)].a_xports);
TQ_ADD(&((yyval.a_xports)->members), (yyvsp[(3) - (3)].a_expr), next);
}
break;
case 49:
#line 673 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
}
break;
case 50:
#line 679 "asn1p_y.y"
{ /* Completely equivalent to above */
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
}
break;
case 51:
#line 685 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
}
break;
case 52:
#line 695 "asn1p_y.y"
{ (yyval.a_module) = 0; }
break;
case 53:
#line 696 "asn1p_y.y"
{
(yyval.a_module) = asn1p_module_new();
checkmem((yyval.a_module));
if((yyvsp[(1) - (1)].a_xports)) {
TQ_ADD(&((yyval.a_module)->exports), (yyvsp[(1) - (1)].a_xports), xp_next);
} else {
/* "EXPORTS ALL;" */
}
}
break;
case 54:
#line 708 "asn1p_y.y"
{
(yyval.a_xports) = (yyvsp[(2) - (3)].a_xports);
}
break;
case 55:
#line 711 "asn1p_y.y"
{
(yyval.a_xports) = 0;
}
break;
case 56:
#line 714 "asn1p_y.y"
{
/* Empty EXPORTS clause effectively prohibits export. */
(yyval.a_xports) = asn1p_xports_new();
checkmem((yyval.a_xports));
}
break;
case 57:
#line 722 "asn1p_y.y"
{
(yyval.a_xports) = asn1p_xports_new();
assert((yyval.a_xports));
TQ_ADD(&((yyval.a_xports)->members), (yyvsp[(1) - (1)].a_expr), next);
}
break;
case 58:
#line 727 "asn1p_y.y"
{
(yyval.a_xports) = (yyvsp[(1) - (3)].a_xports);
TQ_ADD(&((yyval.a_xports)->members), (yyvsp[(3) - (3)].a_expr), next);
}
break;
case 59:
#line 734 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
(yyval.a_expr)->expr_type = A1TC_EXPORTVAR;
}
break;
case 60:
#line 740 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->expr_type = A1TC_EXPORTVAR;
}
break;
case 61:
#line 746 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
(yyval.a_expr)->expr_type = A1TC_EXPORTVAR;
}
break;
case 62:
#line 755 "asn1p_y.y"
{ (yyval.a_constr) = (yyvsp[(2) - (3)].a_constr); }
break;
case 63:
#line 758 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (4)].a_expr);
assert((yyval.a_expr)->Identifier == 0);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (4)].tv_str);
(yyval.a_expr)->meta_type = AMT_VALUESET;
(yyval.a_expr)->constraints = (yyvsp[(4) - (4)].a_constr);
}
break;
case 64:
#line 768 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
}
break;
case 65:
#line 781 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->reference = (yyvsp[(1) - (1)].a_ref);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
(yyval.a_expr)->meta_type = AMT_TYPEREF;
}
break;
case 66:
#line 791 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->reference = (yyvsp[(1) - (4)].a_ref);
(yyval.a_expr)->rhs_pspecs = (yyvsp[(3) - (4)].a_expr);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
(yyval.a_expr)->meta_type = AMT_TYPEREF;
}
break;
case 67:
#line 811 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (3)].a_expr);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
assert((yyval.a_expr)->expr_type);
assert((yyval.a_expr)->meta_type);
}
break;
case 68:
#line 817 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (3)].a_expr);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
assert((yyval.a_expr)->expr_type == A1TC_CLASSDEF);
assert((yyval.a_expr)->meta_type == AMT_OBJECTCLASS);
}
break;
case 69:
#line 833 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(6) - (6)].a_expr);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (6)].tv_str);
(yyval.a_expr)->lhs_params = (yyvsp[(3) - (6)].a_plist);
}
break;
case 70:
#line 839 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(6) - (6)].a_expr);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (6)].tv_str);
(yyval.a_expr)->lhs_params = (yyvsp[(3) - (6)].a_plist);
}
break;
case 71:
#line 847 "asn1p_y.y"
{
int ret;
(yyval.a_plist) = asn1p_paramlist_new(yylineno);
checkmem((yyval.a_plist));
ret = asn1p_paramlist_add_param((yyval.a_plist), (yyvsp[(1) - (1)].a_parg).governor, (yyvsp[(1) - (1)].a_parg).argument);
checkmem(ret == 0);
if((yyvsp[(1) - (1)].a_parg).governor) asn1p_ref_free((yyvsp[(1) - (1)].a_parg).governor);
if((yyvsp[(1) - (1)].a_parg).argument) free((yyvsp[(1) - (1)].a_parg).argument);
}
break;
case 72:
#line 856 "asn1p_y.y"
{
int ret;
(yyval.a_plist) = (yyvsp[(1) - (3)].a_plist);
ret = asn1p_paramlist_add_param((yyval.a_plist), (yyvsp[(3) - (3)].a_parg).governor, (yyvsp[(3) - (3)].a_parg).argument);
checkmem(ret == 0);
if((yyvsp[(3) - (3)].a_parg).governor) asn1p_ref_free((yyvsp[(3) - (3)].a_parg).governor);
if((yyvsp[(3) - (3)].a_parg).argument) free((yyvsp[(3) - (3)].a_parg).argument);
}
break;
case 73:
#line 867 "asn1p_y.y"
{
(yyval.a_parg).governor = NULL;
(yyval.a_parg).argument = (yyvsp[(1) - (1)].tv_str);
}
break;
case 74:
#line 871 "asn1p_y.y"
{
int ret;
(yyval.a_parg).governor = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_parg).governor, (yyvsp[(1) - (3)].tv_str), 0);
checkmem(ret == 0);
(yyval.a_parg).argument = (yyvsp[(3) - (3)].tv_str);
}
break;
case 75:
#line 878 "asn1p_y.y"
{
int ret;
(yyval.a_parg).governor = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_parg).governor, (yyvsp[(1) - (3)].tv_str), 0);
checkmem(ret == 0);
(yyval.a_parg).argument = (yyvsp[(3) - (3)].tv_str);
}
break;
case 76:
#line 885 "asn1p_y.y"
{
int ret;
(yyval.a_parg).governor = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_parg).governor,
ASN_EXPR_TYPE2STR((yyvsp[(1) - (3)].a_type)), 1);
checkmem(ret == 0);
(yyval.a_parg).argument = (yyvsp[(3) - (3)].tv_str);
}
break;
case 77:
#line 893 "asn1p_y.y"
{
int ret;
(yyval.a_parg).governor = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_parg).governor,
ASN_EXPR_TYPE2STR((yyvsp[(1) - (3)].a_type)), 1);
checkmem(ret == 0);
(yyval.a_parg).argument = (yyvsp[(3) - (3)].tv_str);
}
break;
case 78:
#line 904 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
asn1p_expr_add((yyval.a_expr), (yyvsp[(1) - (1)].a_expr));
}
break;
case 79:
#line 909 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (3)].a_expr);
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 80:
#line 916 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
}
break;
case 81:
#line 919 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = "?";
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->value = (yyvsp[(1) - (1)].a_value);
}
break;
case 82:
#line 927 "asn1p_y.y"
{
asn1p_ref_t *ref;
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
(yyval.a_expr)->expr_type = A1TC_REFERENCE;
(yyval.a_expr)->meta_type = AMT_VALUE;
ref = asn1p_ref_new(yylineno);
asn1p_ref_add_component(ref, (yyvsp[(1) - (1)].tv_str), RLT_lowercase);
(yyval.a_expr)->value = asn1p_value_fromref(ref, 0);
}
break;
case 83:
#line 938 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
(yyval.a_expr)->expr_type = A1TC_VALUESET;
(yyval.a_expr)->meta_type = AMT_VALUESET;
(yyval.a_expr)->constraints = (yyvsp[(1) - (1)].a_constr);
}
break;
case 84:
#line 961 "asn1p_y.y"
{ (yyval.a_expr) = NEW_EXPR(); }
break;
case 85:
#line 962 "asn1p_y.y"
{ (yyval.a_expr) = (yyvsp[(1) - (1)].a_expr); }
break;
case 86:
#line 965 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
asn1p_expr_add((yyval.a_expr), (yyvsp[(1) - (1)].a_expr));
}
break;
case 87:
#line 970 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (3)].a_expr);
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 88:
#line 974 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (5)].a_expr);
asn1p_expr_add_many((yyval.a_expr), (yyvsp[(4) - (5)].a_expr));
}
break;
case 89:
#line 981 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (3)].a_expr);
assert((yyval.a_expr)->Identifier == 0);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyvsp[(3) - (3)].a_marker).flags |= (yyval.a_expr)->marker.flags;
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 90:
#line 988 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (2)].a_expr);
(yyvsp[(2) - (2)].a_marker).flags |= (yyval.a_expr)->marker.flags;
(yyval.a_expr)->marker = (yyvsp[(2) - (2)].a_marker);
_fixup_anonymous_identifier((yyval.a_expr));
}
break;
case 91:
#line 994 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->meta_type = (yyvsp[(3) - (3)].a_expr)->meta_type;
(yyval.a_expr)->expr_type = A1TC_COMPONENTS_OF;
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 92:
#line 1001 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
}
break;
case 93:
#line 1007 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
asn1p_expr_add((yyval.a_expr), (yyvsp[(1) - (1)].a_expr));
}
break;
case 94:
#line 1012 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (3)].a_expr);
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 95:
#line 1019 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (2)].a_expr);
assert((yyval.a_expr)->Identifier == 0);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (2)].tv_str);
}
break;
case 96:
#line 1024 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
}
break;
case 97:
#line 1027 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
_fixup_anonymous_identifier((yyval.a_expr));
}
break;
case 98:
#line 1034 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (5)].a_expr);
checkmem((yyval.a_expr));
(yyval.a_expr)->with_syntax = (yyvsp[(5) - (5)].a_wsynt);
assert((yyval.a_expr)->expr_type == A1TC_CLASSDEF);
assert((yyval.a_expr)->meta_type == AMT_OBJECTCLASS);
}
break;
case 99:
#line 1044 "asn1p_y.y"
{ (yyval.a_int) = 0; }
break;
case 100:
#line 1045 "asn1p_y.y"
{ (yyval.a_int) = 1; }
break;
case 101:
#line 1049 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = A1TC_CLASSDEF;
(yyval.a_expr)->meta_type = AMT_OBJECTCLASS;
asn1p_expr_add((yyval.a_expr), (yyvsp[(1) - (1)].a_expr));
}
break;
case 102:
#line 1056 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (3)].a_expr);
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 103:
#line 1066 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (2)].tv_str);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_TFS; /* TypeFieldSpec */
(yyval.a_expr)->marker = (yyvsp[(2) - (2)].a_marker);
}
break;
case 104:
#line 1076 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
(yyval.a_expr)->Identifier = (yyvsp[(1) - (4)].tv_str);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_FTVFS; /* FixedTypeValueFieldSpec */
(yyval.a_expr)->unique = (yyvsp[(3) - (4)].a_int);
(yyval.a_expr)->marker = (yyvsp[(4) - (4)].a_marker);
asn1p_expr_add((yyval.a_expr), (yyvsp[(2) - (4)].a_expr));
}
break;
case 105:
#line 1087 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_VTVFS;
(yyval.a_expr)->reference = (yyvsp[(2) - (3)].a_ref);
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 106:
#line 1097 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->reference = (yyvsp[(2) - (3)].a_ref);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_OFS;
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 107:
#line 1108 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_VTVSFS;
(yyval.a_expr)->reference = (yyvsp[(2) - (3)].a_ref);
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 108:
#line 1118 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_FTVSFS;
asn1p_expr_add((yyval.a_expr), (yyvsp[(2) - (3)].a_expr));
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 109:
#line 1129 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_expr)->reference = (yyvsp[(2) - (3)].a_ref);
(yyval.a_expr)->meta_type = AMT_OBJECTFIELD;
(yyval.a_expr)->expr_type = A1TC_CLASSFIELD_OSFS;
(yyval.a_expr)->marker = (yyvsp[(3) - (3)].a_marker);
}
break;
case 110:
#line 1141 "asn1p_y.y"
{ (yyval.a_wsynt) = 0; }
break;
case 111:
#line 1142 "asn1p_y.y"
{
(yyval.a_wsynt) = (yyvsp[(1) - (1)].a_wsynt);
}
break;
case 112:
#line 1149 "asn1p_y.y"
{ asn1p_lexer_hack_enable_with_syntax(); }
break;
case 113:
#line 1151 "asn1p_y.y"
{
(yyval.a_wsynt) = (yyvsp[(5) - (6)].a_wsynt);
}
break;
case 114:
#line 1157 "asn1p_y.y"
{
(yyval.a_wsynt) = asn1p_wsyntx_new();
TQ_ADD(&((yyval.a_wsynt)->chunks), (yyvsp[(1) - (1)].a_wchunk), next);
}
break;
case 115:
#line 1161 "asn1p_y.y"
{
(yyval.a_wsynt) = (yyvsp[(1) - (2)].a_wsynt);
TQ_ADD(&((yyval.a_wsynt)->chunks), (yyvsp[(2) - (2)].a_wchunk), next);
}
break;
case 116:
#line 1168 "asn1p_y.y"
{
(yyval.a_wchunk) = asn1p_wsyntx_chunk_fromstring((yyvsp[(1) - (1)].tv_opaque).buf, 0);
(yyval.a_wchunk)->type = WC_WHITESPACE;
}
break;
case 117:
#line 1172 "asn1p_y.y"
{
(yyval.a_wchunk) = asn1p_wsyntx_chunk_fromstring((yyvsp[(1) - (1)].tv_str), 0);
}
break;
case 118:
#line 1175 "asn1p_y.y"
{
(yyval.a_wchunk) = asn1p_wsyntx_chunk_fromstring((yyvsp[(1) - (1)].a_refcomp).name, 0);
(yyval.a_wchunk)->type = WC_FIELD;
}
break;
case 119:
#line 1179 "asn1p_y.y"
{
(yyval.a_wchunk) = asn1p_wsyntx_chunk_fromsyntax((yyvsp[(2) - (3)].a_wsynt));
}
break;
case 120:
#line 1185 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = strdup("...");
checkmem((yyval.a_expr)->Identifier);
(yyval.a_expr)->expr_type = A1TC_EXTENSIBLE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 121:
#line 1193 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = strdup("...");
checkmem((yyval.a_expr)->Identifier);
(yyval.a_expr)->value = (yyvsp[(3) - (3)].a_value);
(yyval.a_expr)->expr_type = A1TC_EXTENSIBLE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 122:
#line 1202 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = strdup("...");
(yyval.a_expr)->value = (yyvsp[(3) - (3)].a_value);
checkmem((yyval.a_expr)->Identifier);
(yyval.a_expr)->expr_type = A1TC_EXTENSIBLE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 123:
#line 1214 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (3)].a_expr);
(yyval.a_expr)->tag = (yyvsp[(1) - (3)].a_tag);
/*
* Outer constraint for SEQUENCE OF and SET OF applies
* to the inner type.
*/
if((yyval.a_expr)->expr_type == ASN_CONSTR_SEQUENCE_OF
|| (yyval.a_expr)->expr_type == ASN_CONSTR_SET_OF) {
assert(!TQ_FIRST(&((yyval.a_expr)->members))->constraints);
TQ_FIRST(&((yyval.a_expr)->members))->constraints = (yyvsp[(3) - (3)].a_constr);
} else {
if((yyval.a_expr)->constraints) {
assert(!(yyvsp[(2) - (3)].a_expr));
} else {
(yyval.a_expr)->constraints = (yyvsp[(3) - (3)].a_constr);
}
}
}
break;
case 124:
#line 1236 "asn1p_y.y"
{
(yyval.a_int) = asn1p_as_pointer ? EM_INDIRECT : 0;
asn1p_as_pointer = 0;
}
break;
case 125:
#line 1243 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (2)].a_expr);
(yyval.a_expr)->marker.flags |= (yyvsp[(1) - (2)].a_int);
if(((yyval.a_expr)->marker.flags & EM_INDIRECT)
&& ((yyval.a_expr)->marker.flags & EM_OPTIONAL) != EM_OPTIONAL) {
fprintf(stderr,
"INFO: Directive <ASN1C:RepresentAsPointer> "
"applied to %s at line %d\n",
ASN_EXPR_TYPE2STR((yyval.a_expr)->expr_type)
? ASN_EXPR_TYPE2STR((yyval.a_expr)->expr_type)
: "member",
(yyval.a_expr)->_lineno
);
}
}
break;
case 126:
#line 1262 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (1)].a_expr);
}
break;
case 127:
#line 1265 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (4)].a_expr);
assert((yyval.a_expr)->expr_type == A1TC_INVALID);
(yyval.a_expr)->expr_type = ASN_CONSTR_CHOICE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 128:
#line 1271 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (4)].a_expr);
assert((yyval.a_expr)->expr_type == A1TC_INVALID);
(yyval.a_expr)->expr_type = ASN_CONSTR_SEQUENCE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 129:
#line 1277 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(3) - (4)].a_expr);
assert((yyval.a_expr)->expr_type == A1TC_INVALID);
(yyval.a_expr)->expr_type = ASN_CONSTR_SET;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 130:
#line 1283 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->constraints = (yyvsp[(2) - (6)].a_constr);
(yyval.a_expr)->expr_type = ASN_CONSTR_SEQUENCE_OF;
(yyval.a_expr)->meta_type = AMT_TYPE;
(yyvsp[(6) - (6)].a_expr)->Identifier = (yyvsp[(4) - (6)].tv_str);
(yyvsp[(6) - (6)].a_expr)->tag = (yyvsp[(5) - (6)].a_tag);
asn1p_expr_add((yyval.a_expr), (yyvsp[(6) - (6)].a_expr));
}
break;
case 131:
#line 1293 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->constraints = (yyvsp[(2) - (6)].a_constr);
(yyval.a_expr)->expr_type = ASN_CONSTR_SET_OF;
(yyval.a_expr)->meta_type = AMT_TYPE;
(yyvsp[(6) - (6)].a_expr)->Identifier = (yyvsp[(4) - (6)].tv_str);
(yyvsp[(6) - (6)].a_expr)->tag = (yyvsp[(5) - (6)].a_tag);
asn1p_expr_add((yyval.a_expr), (yyvsp[(6) - (6)].a_expr));
}
break;
case 132:
#line 1303 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = ASN_TYPE_ANY;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 133:
#line 1309 "asn1p_y.y"
{
int ret;
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->reference = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_expr)->reference,
(yyvsp[(4) - (4)].tv_str), RLT_lowercase);
checkmem(ret == 0);
(yyval.a_expr)->expr_type = ASN_TYPE_ANY;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 134:
#line 1320 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->reference = (yyvsp[(3) - (3)].a_ref);
(yyval.a_expr)->expr_type = A1TC_INSTANCE;
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 135:
#line 1335 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (1)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
free((yyvsp[(1) - (1)].tv_str));
}
break;
case 136:
#line 1343 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
free((yyvsp[(1) - (3)].tv_str));
}
break;
case 137:
#line 1353 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
free((yyvsp[(1) - (3)].tv_str));
}
break;
case 138:
#line 1363 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].tv_str), RLT_lowercase);
checkmem(ret == 0);
free((yyvsp[(1) - (3)].tv_str));
}
break;
case 139:
#line 1373 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (1)].tv_str), RLT_CAPITALS);
free((yyvsp[(1) - (1)].tv_str));
checkmem(ret == 0);
}
break;
case 140:
#line 1381 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = (yyvsp[(3) - (3)].a_ref);
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (3)].tv_str), RLT_CAPITALS);
free((yyvsp[(1) - (3)].tv_str));
checkmem(ret == 0);
/*
* Move the last element infront.
*/
{
struct asn1p_ref_component_s tmp_comp;
tmp_comp = (yyval.a_ref)->components[(yyval.a_ref)->comp_count-1];
memmove(&(yyval.a_ref)->components[1],
&(yyval.a_ref)->components[0],
sizeof((yyval.a_ref)->components[0])
* ((yyval.a_ref)->comp_count - 1));
(yyval.a_ref)->components[0] = tmp_comp;
}
}
break;
case 141:
#line 1403 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = asn1p_ref_new(yylineno);
checkmem((yyval.a_ref));
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (1)].a_refcomp).name, (yyvsp[(1) - (1)].a_refcomp).lex_type);
free((yyvsp[(1) - (1)].a_refcomp).name);
checkmem(ret == 0);
}
break;
case 142:
#line 1411 "asn1p_y.y"
{
int ret;
(yyval.a_ref) = (yyvsp[(1) - (3)].a_ref);
ret = asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].a_refcomp).name, (yyvsp[(3) - (3)].a_refcomp).lex_type);
free((yyvsp[(3) - (3)].a_refcomp).name);
checkmem(ret == 0);
}
break;
case 144:
#line 1424 "asn1p_y.y"
{
(yyval.a_refcomp).lex_type = RLT_AmpUppercase;
(yyval.a_refcomp).name = (yyvsp[(1) - (1)].tv_str);
}
break;
case 145:
#line 1429 "asn1p_y.y"
{
(yyval.a_refcomp).lex_type = RLT_Amplowercase;
(yyval.a_refcomp).name = (yyvsp[(1) - (1)].tv_str);
}
break;
case 146:
#line 1438 "asn1p_y.y"
{
(yyval.a_ref) = asn1p_ref_new(yylineno);
asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (1)].tv_str), RLT_AmpUppercase);
}
break;
case 147:
#line 1442 "asn1p_y.y"
{
(yyval.a_ref) = (yyval.a_ref);
asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].tv_str), RLT_AmpUppercase);
}
break;
case 148:
#line 1446 "asn1p_y.y"
{
(yyval.a_ref) = (yyval.a_ref);
asn1p_ref_add_component((yyval.a_ref), (yyvsp[(3) - (3)].tv_str), RLT_Amplowercase);
}
break;
case 149:
#line 1453 "asn1p_y.y"
{
(yyval.a_ref) = asn1p_ref_new(yylineno);
asn1p_ref_add_component((yyval.a_ref), (yyvsp[(1) - (1)].tv_str), RLT_CAPITALS);
}
break;
case 150:
#line 1473 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (4)].a_expr);
assert((yyval.a_expr)->Identifier == NULL);
(yyval.a_expr)->Identifier = (yyvsp[(1) - (4)].tv_str);
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->value = (yyvsp[(4) - (4)].a_value);
}
break;
case 153:
#line 1485 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_CHOICE_IDENTIFIER;
(yyval.a_value)->value.choice_identifier.identifier = (yyvsp[(1) - (3)].tv_str);
(yyval.a_value)->value.choice_identifier.value = (yyvsp[(3) - (3)].a_value);
}
break;
case 154:
#line 1492 "asn1p_y.y"
{ asn1p_lexer_hack_push_opaque_state(); }
break;
case 155:
#line 1492 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_frombuf((yyvsp[(3) - (3)].tv_opaque).buf, (yyvsp[(3) - (3)].tv_opaque).len, 0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_UNPARSED;
}
break;
case 156:
#line 1497 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_NULL;
}
break;
case 157:
#line 1505 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_FALSE;
}
break;
case 158:
#line 1510 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_TRUE;
}
break;
case 159:
#line 1515 "asn1p_y.y"
{
(yyval.a_value) = _convert_bitstring2binary((yyvsp[(1) - (1)].tv_str), 'B');
checkmem((yyval.a_value));
}
break;
case 160:
#line 1519 "asn1p_y.y"
{
(yyval.a_value) = _convert_bitstring2binary((yyvsp[(1) - (1)].tv_str), 'H');
checkmem((yyval.a_value));
}
break;
case 161:
#line 1523 "asn1p_y.y"
{
(yyval.a_value) = (yyval.a_value);
}
break;
case 162:
#line 1526 "asn1p_y.y"
{
(yyval.a_value) = (yyvsp[(1) - (1)].a_value);
}
break;
case 163:
#line 1532 "asn1p_y.y"
{
asn1p_ref_t *ref;
int ret;
ref = asn1p_ref_new(yylineno);
checkmem(ref);
ret = asn1p_ref_add_component(ref, (yyvsp[(1) - (1)].tv_str), RLT_lowercase);
checkmem(ret == 0);
(yyval.a_value) = asn1p_value_fromref(ref, 0);
checkmem((yyval.a_value));
free((yyvsp[(1) - (1)].tv_str));
}
break;
case 164:
#line 1543 "asn1p_y.y"
{
asn1p_ref_t *ref;
int ret;
ref = asn1p_ref_new(yylineno);
checkmem(ref);
ret = asn1p_ref_add_component(ref, (yyvsp[(1) - (3)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
ret = asn1p_ref_add_component(ref, (yyvsp[(3) - (3)].tv_str), RLT_lowercase);
checkmem(ret == 0);
(yyval.a_value) = asn1p_value_fromref(ref, 0);
checkmem((yyval.a_value));
free((yyvsp[(1) - (3)].tv_str));
free((yyvsp[(3) - (3)].tv_str));
}
break;
case 165:
#line 1561 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_frombuf((yyvsp[(1) - (1)].tv_opaque).buf, (yyvsp[(1) - (1)].tv_opaque).len, 0);
checkmem((yyval.a_value));
}
break;
case 166:
#line 1565 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint((yyvsp[(1) - (1)].a_int));
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_TUPLE;
}
break;
case 167:
#line 1570 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint((yyvsp[(1) - (1)].a_int));
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_QUADRUPLE;
}
break;
case 168:
#line 1578 "asn1p_y.y"
{
(yyval.tv_opaque).len = (yyvsp[(1) - (1)].tv_opaque).len + 1;
(yyval.tv_opaque).buf = malloc((yyval.tv_opaque).len + 1);
checkmem((yyval.tv_opaque).buf);
(yyval.tv_opaque).buf[0] = '{';
memcpy((yyval.tv_opaque).buf + 1, (yyvsp[(1) - (1)].tv_opaque).buf, (yyvsp[(1) - (1)].tv_opaque).len);
(yyval.tv_opaque).buf[(yyval.tv_opaque).len] = '\0';
free((yyvsp[(1) - (1)].tv_opaque).buf);
}
break;
case 169:
#line 1587 "asn1p_y.y"
{
int newsize = (yyvsp[(1) - (2)].tv_opaque).len + (yyvsp[(2) - (2)].tv_opaque).len;
char *p = malloc(newsize + 1);
checkmem(p);
memcpy(p , (yyvsp[(1) - (2)].tv_opaque).buf, (yyvsp[(1) - (2)].tv_opaque).len);
memcpy(p + (yyvsp[(1) - (2)].tv_opaque).len, (yyvsp[(2) - (2)].tv_opaque).buf, (yyvsp[(2) - (2)].tv_opaque).len);
p[newsize] = '\0';
free((yyvsp[(1) - (2)].tv_opaque).buf);
free((yyvsp[(2) - (2)].tv_opaque).buf);
(yyval.tv_opaque).buf = p;
(yyval.tv_opaque).len = newsize;
}
break;
case 170:
#line 1602 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_BOOLEAN; }
break;
case 171:
#line 1603 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_NULL; }
break;
case 172:
#line 1604 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_REAL; }
break;
case 173:
#line 1605 "asn1p_y.y"
{ (yyval.a_type) = (yyvsp[(1) - (1)].a_type); }
break;
case 174:
#line 1606 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_OCTET_STRING; }
break;
case 175:
#line 1607 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_OBJECT_IDENTIFIER; }
break;
case 176:
#line 1608 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_RELATIVE_OID; }
break;
case 177:
#line 1609 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_EXTERNAL; }
break;
case 178:
#line 1610 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_EMBEDDED_PDV; }
break;
case 179:
#line 1611 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_CHARACTER_STRING; }
break;
case 180:
#line 1612 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_UTCTime; }
break;
case 181:
#line 1613 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_GeneralizedTime; }
break;
case 182:
#line 1614 "asn1p_y.y"
{ (yyval.a_type) = (yyvsp[(1) - (1)].a_type); }
break;
case 183:
#line 1621 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_INTEGER; }
break;
case 184:
#line 1622 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_ENUMERATED; }
break;
case 185:
#line 1623 "asn1p_y.y"
{ (yyval.a_type) = ASN_BASIC_BIT_STRING; }
break;
case 186:
#line 1627 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = (yyvsp[(1) - (1)].a_type);
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 187:
#line 1633 "asn1p_y.y"
{
if((yyvsp[(2) - (2)].a_expr)) {
(yyval.a_expr) = (yyvsp[(2) - (2)].a_expr);
} else {
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
}
(yyval.a_expr)->expr_type = (yyvsp[(1) - (2)].a_type);
(yyval.a_expr)->meta_type = AMT_TYPE;
}
break;
case 188:
#line 1646 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_BMPString; }
break;
case 189:
#line 1647 "asn1p_y.y"
{
(yyval.a_type) = ASN_STRING_GeneralString;
fprintf(stderr, "WARNING: GeneralString is not fully supported\n");
}
break;
case 190:
#line 1651 "asn1p_y.y"
{
(yyval.a_type) = ASN_STRING_GraphicString;
fprintf(stderr, "WARNING: GraphicString is not fully supported\n");
}
break;
case 191:
#line 1655 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_IA5String; }
break;
case 192:
#line 1656 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_ISO646String; }
break;
case 193:
#line 1657 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_NumericString; }
break;
case 194:
#line 1658 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_PrintableString; }
break;
case 195:
#line 1659 "asn1p_y.y"
{
(yyval.a_type) = ASN_STRING_T61String;
fprintf(stderr, "WARNING: T61String is not fully supported\n");
}
break;
case 196:
#line 1663 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_TeletexString; }
break;
case 197:
#line 1664 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_UniversalString; }
break;
case 198:
#line 1665 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_UTF8String; }
break;
case 199:
#line 1666 "asn1p_y.y"
{
(yyval.a_type) = ASN_STRING_VideotexString;
fprintf(stderr, "WARNING: VideotexString is not fully supported\n");
}
break;
case 200:
#line 1670 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_VisibleString; }
break;
case 201:
#line 1671 "asn1p_y.y"
{ (yyval.a_type) = ASN_STRING_ObjectDescriptor; }
break;
case 206:
#line 1682 "asn1p_y.y"
{ (yyval.a_constr) = 0; }
break;
case 207:
#line 1683 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 209:
#line 1693 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_SET, (yyvsp[(1) - (1)].a_constr), 0);
}
break;
case 210:
#line 1696 "asn1p_y.y"
{
/*
* This is a special case, for compatibility purposes.
* It goes without parentheses.
*/
CONSTRAINT_INSERT((yyval.a_constr), ACT_CT_SIZE, (yyvsp[(3) - (4)].a_constr), 0);
}
break;
case 211:
#line 1706 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(2) - (3)].a_constr);
}
break;
case 212:
#line 1709 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_SET, (yyvsp[(1) - (4)].a_constr), (yyvsp[(3) - (4)].a_constr));
}
break;
case 213:
#line 1715 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
(yyval.a_constr)->type = ACT_EL_EXT;
}
break;
case 214:
#line 1719 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 215:
#line 1722 "asn1p_y.y"
{
asn1p_constraint_t *ct;
ct = asn1p_constraint_new(yylineno);
ct->type = ACT_EL_EXT;
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CSV, (yyvsp[(1) - (3)].a_constr), ct);
}
break;
case 216:
#line 1728 "asn1p_y.y"
{
asn1p_constraint_t *ct;
ct = asn1p_constraint_new(yylineno);
ct->type = ACT_EL_EXT;
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CSV, (yyvsp[(1) - (5)].a_constr), ct);
ct = (yyval.a_constr);
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CSV, ct, (yyvsp[(5) - (5)].a_constr));
}
break;
case 217:
#line 1736 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 219:
#line 1743 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_AEX, (yyvsp[(3) - (3)].a_constr), 0);
}
break;
case 221:
#line 1750 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_UNI, (yyvsp[(1) - (3)].a_constr), (yyvsp[(3) - (3)].a_constr));
}
break;
case 223:
#line 1757 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_INT, (yyvsp[(1) - (3)].a_constr), (yyvsp[(3) - (3)].a_constr));
}
break;
case 225:
#line 1765 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_EXC, (yyvsp[(1) - (3)].a_constr), (yyvsp[(3) - (3)].a_constr));
}
break;
case 226:
#line 1771 "asn1p_y.y"
{
int ret;
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = (yyvsp[(1) - (4)].a_ctype);
ret = asn1p_constraint_insert((yyval.a_constr), (yyvsp[(3) - (4)].a_constr));
checkmem(ret == 0);
}
break;
case 227:
#line 1779 "asn1p_y.y"
{
int ret;
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_CA_SET;
ret = asn1p_constraint_insert((yyval.a_constr), (yyvsp[(2) - (3)].a_constr));
checkmem(ret == 0);
}
break;
case 228:
#line 1787 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_EL_VALUE;
(yyval.a_constr)->value = (yyvsp[(1) - (1)].a_value);
}
break;
case 229:
#line 1793 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_EL_TYPE;
(yyval.a_constr)->containedSubtype = (yyvsp[(1) - (1)].a_value);
}
break;
case 230:
#line 1799 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = (yyvsp[(2) - (3)].a_ctype);
(yyval.a_constr)->range_start = (yyvsp[(1) - (3)].a_value);
(yyval.a_constr)->range_stop = (yyvsp[(3) - (3)].a_value);
}
break;
case 231:
#line 1806 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = (yyvsp[(2) - (3)].a_ctype);
(yyval.a_constr)->range_start = asn1p_value_fromint(-123);
(yyval.a_constr)->range_stop = (yyvsp[(3) - (3)].a_value);
(yyval.a_constr)->range_start->type = ATV_MIN;
}
break;
case 232:
#line 1814 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = (yyvsp[(2) - (3)].a_ctype);
(yyval.a_constr)->range_start = (yyvsp[(1) - (3)].a_value);
(yyval.a_constr)->range_stop = asn1p_value_fromint(321);
(yyval.a_constr)->range_stop->type = ATV_MAX;
}
break;
case 233:
#line 1822 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = (yyvsp[(2) - (3)].a_ctype);
(yyval.a_constr)->range_start = asn1p_value_fromint(-123);
(yyval.a_constr)->range_stop = asn1p_value_fromint(321);
(yyval.a_constr)->range_start->type = ATV_MIN;
(yyval.a_constr)->range_stop->type = ATV_MAX;
}
break;
case 234:
#line 1831 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 235:
#line 1834 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 236:
#line 1840 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
(yyval.a_constr)->type = ACT_CT_PATTERN;
(yyval.a_constr)->value = asn1p_value_frombuf((yyvsp[(2) - (2)].tv_opaque).buf, (yyvsp[(2) - (2)].tv_opaque).len, 0);
}
break;
case 237:
#line 1845 "asn1p_y.y"
{
asn1p_ref_t *ref;
(yyval.a_constr) = asn1p_constraint_new(yylineno);
(yyval.a_constr)->type = ACT_CT_PATTERN;
ref = asn1p_ref_new(yylineno);
asn1p_ref_add_component(ref, (yyvsp[(2) - (2)].tv_str), RLT_lowercase);
(yyval.a_constr)->value = asn1p_value_fromref(ref, 0);
}
break;
case 238:
#line 1856 "asn1p_y.y"
{
(yyval.a_ctype) = ACT_CT_SIZE;
}
break;
case 239:
#line 1859 "asn1p_y.y"
{
(yyval.a_ctype) = ACT_CT_FROM;
}
break;
case 240:
#line 1865 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(0);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_FALSE;
}
break;
case 241:
#line 1870 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint(1);
checkmem((yyval.a_value));
(yyval.a_value)->type = ATV_TRUE;
}
break;
case 245:
#line 1878 "asn1p_y.y"
{
asn1p_ref_t *ref;
int ret;
ref = asn1p_ref_new(yylineno);
checkmem(ref);
ret = asn1p_ref_add_component(ref, (yyvsp[(1) - (1)].tv_str), RLT_lowercase);
checkmem(ret == 0);
(yyval.a_value) = asn1p_value_fromref(ref, 0);
checkmem((yyval.a_value));
free((yyvsp[(1) - (1)].tv_str));
}
break;
case 246:
#line 1892 "asn1p_y.y"
{
(yyval.a_value) = _convert_bitstring2binary((yyvsp[(1) - (1)].tv_str), 'B');
checkmem((yyval.a_value));
}
break;
case 247:
#line 1896 "asn1p_y.y"
{
(yyval.a_value) = _convert_bitstring2binary((yyvsp[(1) - (1)].tv_str), 'H');
checkmem((yyval.a_value));
}
break;
case 248:
#line 1903 "asn1p_y.y"
{
asn1p_ref_t *ref;
int ret;
ref = asn1p_ref_new(yylineno);
checkmem(ref);
ret = asn1p_ref_add_component(ref, (yyvsp[(1) - (1)].tv_str), RLT_UNKNOWN);
checkmem(ret == 0);
(yyval.a_value) = asn1p_value_fromref(ref, 0);
checkmem((yyval.a_value));
free((yyvsp[(1) - (1)].tv_str));
}
break;
case 249:
#line 1917 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CT_WCOMP, (yyvsp[(3) - (3)].a_constr), 0);
}
break;
case 250:
#line 1920 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CT_WCOMPS, (yyvsp[(4) - (5)].a_constr), 0);
}
break;
case 251:
#line 1926 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 252:
#line 1929 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CT_WCOMPS, (yyvsp[(1) - (3)].a_constr), (yyvsp[(3) - (3)].a_constr));
}
break;
case 253:
#line 1935 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_EL_EXT;
(yyval.a_constr)->value = asn1p_value_frombuf("...", 3, 1);
}
break;
case 254:
#line 1941 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_EL_VALUE;
(yyval.a_constr)->value = asn1p_value_frombuf((yyvsp[(1) - (3)].tv_str), strlen((yyvsp[(1) - (3)].tv_str)), 0);
(yyval.a_constr)->presence = (yyvsp[(3) - (3)].a_pres);
if((yyvsp[(2) - (3)].a_constr)) asn1p_constraint_insert((yyval.a_constr), (yyvsp[(2) - (3)].a_constr));
}
break;
case 255:
#line 1955 "asn1p_y.y"
{ (yyval.a_pres) = ACPRES_DEFAULT; }
break;
case 256:
#line 1956 "asn1p_y.y"
{ (yyval.a_pres) = (yyvsp[(1) - (1)].a_pres); }
break;
case 257:
#line 1960 "asn1p_y.y"
{
(yyval.a_pres) = ACPRES_PRESENT;
}
break;
case 258:
#line 1963 "asn1p_y.y"
{
(yyval.a_pres) = ACPRES_ABSENT;
}
break;
case 259:
#line 1966 "asn1p_y.y"
{
(yyval.a_pres) = ACPRES_OPTIONAL;
}
break;
case 263:
#line 1981 "asn1p_y.y"
{ asn1p_lexer_hack_push_opaque_state(); }
break;
case 264:
#line 1981 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_CT_CTDBY;
(yyval.a_constr)->value = asn1p_value_frombuf((yyvsp[(5) - (5)].tv_opaque).buf, (yyvsp[(5) - (5)].tv_opaque).len, 0);
checkmem((yyval.a_constr)->value);
(yyval.a_constr)->value->type = ATV_UNPARSED;
}
break;
case 265:
#line 1992 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
(yyval.a_constr)->type = ACT_CT_CTNG;
(yyval.a_constr)->value = asn1p_value_fromtype((yyvsp[(2) - (2)].a_expr));
}
break;
case 266:
#line 2000 "asn1p_y.y"
{ (yyval.a_ctype) = ACT_EL_RANGE; }
break;
case 267:
#line 2001 "asn1p_y.y"
{ (yyval.a_ctype) = ACT_EL_RLRANGE; }
break;
case 268:
#line 2002 "asn1p_y.y"
{ (yyval.a_ctype) = ACT_EL_LLRANGE; }
break;
case 269:
#line 2003 "asn1p_y.y"
{ (yyval.a_ctype) = ACT_EL_ULRANGE; }
break;
case 270:
#line 2006 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 271:
#line 2009 "asn1p_y.y"
{
(yyval.a_constr) = (yyvsp[(1) - (1)].a_constr);
}
break;
case 272:
#line 2018 "asn1p_y.y"
{
asn1p_ref_t *ref = asn1p_ref_new(yylineno);
asn1p_constraint_t *ct;
int ret;
ret = asn1p_ref_add_component(ref, (yyvsp[(2) - (3)].tv_str), 0);
checkmem(ret == 0);
ct = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
ct->type = ACT_EL_VALUE;
ct->value = asn1p_value_fromref(ref, 0);
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CRC, ct, 0);
}
break;
case 273:
#line 2033 "asn1p_y.y"
{
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CRC, (yyvsp[(1) - (4)].a_constr), (yyvsp[(3) - (4)].a_constr));
}
break;
case 274:
#line 2039 "asn1p_y.y"
{
(yyval.a_constr) = asn1p_constraint_new(yylineno);
checkmem((yyval.a_constr));
(yyval.a_constr)->type = ACT_EL_VALUE;
(yyval.a_constr)->value = asn1p_value_fromref((yyvsp[(1) - (1)].a_ref), 0);
}
break;
case 275:
#line 2045 "asn1p_y.y"
{
asn1p_constraint_t *ct;
ct = asn1p_constraint_new(yylineno);
checkmem(ct);
ct->type = ACT_EL_VALUE;
ct->value = asn1p_value_fromref((yyvsp[(3) - (3)].a_ref), 0);
CONSTRAINT_INSERT((yyval.a_constr), ACT_CA_CSV, (yyvsp[(1) - (3)].a_constr), ct);
}
break;
case 276:
#line 2059 "asn1p_y.y"
{
char *p = malloc(strlen((yyvsp[(2) - (2)].tv_str)) + 2);
int ret;
*p = '@';
strcpy(p + 1, (yyvsp[(2) - (2)].tv_str));
(yyval.a_ref) = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_ref), p, 0);
checkmem(ret == 0);
free(p);
free((yyvsp[(2) - (2)].tv_str));
}
break;
case 277:
#line 2070 "asn1p_y.y"
{
char *p = malloc(strlen((yyvsp[(3) - (3)].tv_str)) + 3);
int ret;
p[0] = '@';
p[1] = '.';
strcpy(p + 2, (yyvsp[(3) - (3)].tv_str));
(yyval.a_ref) = asn1p_ref_new(yylineno);
ret = asn1p_ref_add_component((yyval.a_ref), p, 0);
checkmem(ret == 0);
free(p);
free((yyvsp[(3) - (3)].tv_str));
}
break;
case 278:
#line 2086 "asn1p_y.y"
{
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
case 279:
#line 2089 "asn1p_y.y"
{
int l1 = strlen((yyvsp[(1) - (3)].tv_str));
int l3 = strlen((yyvsp[(3) - (3)].tv_str));
(yyval.tv_str) = malloc(l1 + 1 + l3 + 1);
memcpy((yyval.tv_str), (yyvsp[(1) - (3)].tv_str), l1);
(yyval.tv_str)[l1] = '.';
memcpy((yyval.tv_str) + l1 + 1, (yyvsp[(3) - (3)].tv_str), l3);
(yyval.tv_str)[l1 + 1 + l3] = '\0';
}
break;
case 280:
#line 2107 "asn1p_y.y"
{
(yyval.a_marker).flags = EM_NOMARK;
(yyval.a_marker).default_value = 0;
}
break;
case 281:
#line 2111 "asn1p_y.y"
{ (yyval.a_marker) = (yyvsp[(1) - (1)].a_marker); }
break;
case 282:
#line 2115 "asn1p_y.y"
{
(yyval.a_marker).flags = EM_OPTIONAL | EM_INDIRECT;
(yyval.a_marker).default_value = 0;
}
break;
case 283:
#line 2119 "asn1p_y.y"
{
(yyval.a_marker).flags = EM_DEFAULT;
(yyval.a_marker).default_value = (yyvsp[(2) - (2)].a_value);
}
break;
case 284:
#line 2142 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
}
break;
case 285:
#line 2146 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(2) - (3)].a_expr);
}
break;
case 286:
#line 2152 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
asn1p_expr_add((yyval.a_expr), (yyvsp[(1) - (1)].a_expr));
}
break;
case 287:
#line 2157 "asn1p_y.y"
{
(yyval.a_expr) = (yyvsp[(1) - (3)].a_expr);
asn1p_expr_add((yyval.a_expr), (yyvsp[(3) - (3)].a_expr));
}
break;
case 288:
#line 2164 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = A1TC_UNIVERVAL;
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->Identifier = (yyvsp[(1) - (1)].tv_str);
}
break;
case 289:
#line 2171 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = A1TC_UNIVERVAL;
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->Identifier = (yyvsp[(1) - (4)].tv_str);
(yyval.a_expr)->value = (yyvsp[(3) - (4)].a_value);
}
break;
case 290:
#line 2179 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = A1TC_UNIVERVAL;
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->Identifier = (yyvsp[(1) - (4)].tv_str);
(yyval.a_expr)->value = (yyvsp[(3) - (4)].a_value);
}
break;
case 291:
#line 2187 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->expr_type = A1TC_UNIVERVAL;
(yyval.a_expr)->meta_type = AMT_VALUE;
(yyval.a_expr)->value = (yyvsp[(1) - (1)].a_value);
}
break;
case 292:
#line 2194 "asn1p_y.y"
{
(yyval.a_expr) = NEW_EXPR();
checkmem((yyval.a_expr));
(yyval.a_expr)->Identifier = strdup("...");
checkmem((yyval.a_expr)->Identifier);
(yyval.a_expr)->expr_type = A1TC_EXTENSIBLE;
(yyval.a_expr)->meta_type = AMT_VALUE;
}
break;
case 293:
#line 2205 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint((yyvsp[(1) - (1)].a_int));
checkmem((yyval.a_value));
}
break;
case 294:
#line 2209 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromint((yyvsp[(1) - (1)].a_int));
checkmem((yyval.a_value));
}
break;
case 296:
#line 2217 "asn1p_y.y"
{
(yyval.a_value) = asn1p_value_fromdouble((yyvsp[(1) - (1)].a_dbl));
checkmem((yyval.a_value));
}
break;
case 297:
#line 2248 "asn1p_y.y"
{ memset(&(yyval.a_tag), 0, sizeof((yyval.a_tag))); }
break;
case 298:
#line 2249 "asn1p_y.y"
{ (yyval.a_tag) = (yyvsp[(1) - (1)].a_tag); }
break;
case 299:
#line 2253 "asn1p_y.y"
{
(yyval.a_tag) = (yyvsp[(1) - (2)].a_tag);
(yyval.a_tag).tag_mode = (yyvsp[(2) - (2)].a_tag).tag_mode;
}
break;
case 300:
#line 2260 "asn1p_y.y"
{
(yyval.a_tag) = (yyvsp[(2) - (4)].a_tag);
(yyval.a_tag).tag_value = (yyvsp[(3) - (4)].a_int);
}
break;
case 301:
#line 2266 "asn1p_y.y"
{ (yyval.a_tag).tag_class = TC_CONTEXT_SPECIFIC; }
break;
case 302:
#line 2267 "asn1p_y.y"
{ (yyval.a_tag).tag_class = TC_UNIVERSAL; }
break;
case 303:
#line 2268 "asn1p_y.y"
{ (yyval.a_tag).tag_class = TC_APPLICATION; }
break;
case 304:
#line 2269 "asn1p_y.y"
{ (yyval.a_tag).tag_class = TC_PRIVATE; }
break;
case 305:
#line 2273 "asn1p_y.y"
{ (yyval.a_tag).tag_mode = TM_DEFAULT; }
break;
case 306:
#line 2274 "asn1p_y.y"
{ (yyval.a_tag).tag_mode = TM_IMPLICIT; }
break;
case 307:
#line 2275 "asn1p_y.y"
{ (yyval.a_tag).tag_mode = TM_EXPLICIT; }
break;
case 308:
#line 2279 "asn1p_y.y"
{
checkmem((yyvsp[(1) - (1)].tv_str));
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
case 309:
#line 2283 "asn1p_y.y"
{
checkmem((yyvsp[(1) - (1)].tv_str));
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
case 310:
#line 2291 "asn1p_y.y"
{
checkmem((yyvsp[(1) - (1)].tv_str));
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
case 311:
#line 2298 "asn1p_y.y"
{ (yyval.tv_str) = 0; }
break;
case 312:
#line 2299 "asn1p_y.y"
{
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
case 313:
#line 2305 "asn1p_y.y"
{
checkmem((yyvsp[(1) - (1)].tv_str));
(yyval.tv_str) = (yyvsp[(1) - (1)].tv_str);
}
break;
/* Line 1267 of yacc.c. */
#line 4799 "y.tab.c"
default: break;
}
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now `shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (YY_("syntax error"));
#else
{
YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
{
YYSIZE_T yyalloc = 2 * yysize;
if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
yyalloc = YYSTACK_ALLOC_MAXIMUM;
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yyalloc);
if (yymsg)
yymsg_alloc = yyalloc;
else
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
}
}
if (0 < yysize && yysize <= yymsg_alloc)
{
(void) yysyntax_error (yymsg, yystate, yychar);
yyerror (yymsg);
}
else
{
yyerror (YY_("syntax error"));
if (yysize != 0)
goto yyexhaustedlab;
}
}
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse look-ahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval);
yychar = YYEMPTY;
}
}
/* Else will try to reuse look-ahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (yyn != YYPACT_NINF)
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
if (yyn == YYFINAL)
YYACCEPT;
*++yyvsp = yylval;
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#ifndef yyoverflow
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEOF && yychar != YYEMPTY)
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
/* Make sure YYID is used. */
return YYID (yyresult);
}
#line 2311 "asn1p_y.y"
/*
* Convert Xstring ('0101'B or '5'H) to the binary vector.
*/
static asn1p_value_t *
_convert_bitstring2binary(char *str, int base) {
asn1p_value_t *val;
int slen;
int memlen;
int baselen;
int bits;
uint8_t *binary_vector;
uint8_t *bv_ptr;
uint8_t cur_val;
assert(str);
assert(str[0] == '\'');
switch(base) {
case 'B':
baselen = 1;
break;
case 'H':
baselen = 4;
break;
default:
assert(base == 'B' || base == 'H');
errno = EINVAL;
return NULL;
}
slen = strlen(str);
assert(str[slen - 1] == base);
assert(str[slen - 2] == '\'');
memlen = slen / (8 / baselen); /* Conservative estimate */
bv_ptr = binary_vector = malloc(memlen + 1);
if(bv_ptr == NULL)
/* ENOMEM */
return NULL;
cur_val = 0;
bits = 0;
while(*(++str) != '\'') {
switch(baselen) {
case 1:
switch(*str) {
case '1':
cur_val |= 1 << (7 - (bits % 8));
case '0':
break;
default:
assert(!"_y UNREACH1");
case ' ': case '\r': case '\n':
continue;
}
break;
case 4:
switch(*str) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
cur_val |= (*str - '0') << (4 - (bits % 8));
break;
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
cur_val |= ((*str - 'A') + 10)
<< (4 - (bits % 8));
break;
default:
assert(!"_y UNREACH2");
case ' ': case '\r': case '\n':
continue;
}
break;
}
bits += baselen;
if((bits % 8) == 0) {
*bv_ptr++ = cur_val;
cur_val = 0;
}
}
*bv_ptr = cur_val;
assert((bv_ptr - binary_vector) <= memlen);
val = asn1p_value_frombits(binary_vector, bits, 0);
if(val == NULL) {
free(binary_vector);
}
return val;
}
/*
* For unnamed types (used in old X.208 compliant modules)
* generate some sort of interim names, to not to force human being to fix
* the specification's compliance to modern ASN.1 standards.
*/
static void
_fixup_anonymous_identifier(asn1p_expr_t *expr) {
char *p;
assert(expr->Identifier == 0);
/*
* Try to figure out the type name
* without going too much into details
*/
expr->Identifier = ASN_EXPR_TYPE2STR(expr->expr_type);
if(expr->reference && expr->reference->comp_count > 0)
expr->Identifier = expr->reference->components[0].name;
fprintf(stderr,
"WARNING: Line %d: expected lower-case member identifier, "
"found an unnamed %s.\n"
"WARNING: Obsolete X.208 syntax detected, "
"please give the member a name.\n",
yylineno, expr->Identifier ? expr->Identifier : "type");
if(!expr->Identifier)
expr->Identifier = "unnamed";
expr->Identifier = strdup(expr->Identifier);
assert(expr->Identifier);
/* Make a lowercase identifier from the type name */
for(p = expr->Identifier; *p; p++) {
switch(*p) {
case 'A' ... 'Z': *p += 32; break;
case ' ': *p = '_'; break;
case '-': *p = '_'; break;
}
}
fprintf(stderr, "NOTE: Assigning temporary identifier \"%s\". "
"Name clash may occur later.\n",
expr->Identifier);
}
int
yyerror(const char *msg) {
extern char *asn1p_text;
fprintf(stderr,
"ASN.1 grammar parse error "
"near line %d (token \"%s\"): %s\n",
yylineno, asn1p_text, msg);
return -1;
}
| bsd-2-clause |
pascal-brand-st-dev/optee_os | lib/libutils/isoc/arch/arm/softfloat/source/s_add128.c | 10 | 2152 | // SPDX-License-Identifier: BSD-3-Clause
/*============================================================================
This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3a, by John R. Hauser.
Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#include <stdint.h>
#include "platform.h"
#include "primitiveTypes.h"
#ifndef softfloat_add128
struct uint128
softfloat_add128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 )
{
struct uint128 z;
z.v0 = a0 + b0;
z.v64 = a64 + b64 + (z.v0 < a0);
return z;
}
#endif
| bsd-2-clause |
ah744/ScaffCC_RKQC | clang/test/CodeGenCXX/default-arguments.cpp | 11 | 1332 | // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
// PR5484
namespace PR5484 {
struct A { };
extern A a;
void f(const A & = a);
void g() {
f();
}
}
struct A1 {
A1();
~A1();
};
struct A2 {
A2();
~A2();
};
struct B {
B(const A1& = A1(), const A2& = A2());
};
// CHECK: define void @_Z2f1v()
void f1() {
// CHECK: call void @_ZN2A1C1Ev(
// CHECK: call void @_ZN2A2C1Ev(
// CHECK: call void @_ZN1BC1ERK2A1RK2A2(
// CHECK: call void @_ZN2A2D1Ev
// CHECK: call void @_ZN2A1D1Ev
B bs[2];
}
struct C {
B bs[2];
C();
};
// CHECK: define void @_ZN1CC1Ev(%struct.C* %this) unnamed_addr
// CHECK: call void @_ZN1CC2Ev(
// CHECK: define void @_ZN1CC2Ev(%struct.C* %this) unnamed_addr
// CHECK: call void @_ZN2A1C1Ev(
// CHECK: call void @_ZN2A2C1Ev(
// CHECK: call void @_ZN1BC1ERK2A1RK2A2(
// CHECK: call void @_ZN2A2D1Ev
// CHECK: call void @_ZN2A1D1Ev
C::C() { }
// CHECK: define void @_Z2f3v()
void f3() {
// CHECK: call void @_ZN2A1C1Ev(
// CHECK: call void @_ZN2A2C1Ev(
// CHECK: call void @_ZN1BC1ERK2A1RK2A2(
// CHECK: call void @_ZN2A2D1Ev
// CHECK: call void @_ZN2A1D1Ev
B *bs = new B[2];
delete bs;
}
void f4() {
void g4(int a, int b = 7);
{
void g4(int a, int b = 5);
}
void g4(int a = 5, int b);
// CHECK: call void @_Z2g4ii(i32 5, i32 7)
g4();
}
| bsd-2-clause |
mikedlowis-prototypes/albase | source/kernel/drivers/net/ethernet/smsc/smc91x.c | 19 | 64989 | /*
* smc91x.c
* This is a driver for SMSC's 91C9x/91C1xx single-chip Ethernet devices.
*
* Copyright (C) 1996 by Erik Stahlman
* Copyright (C) 2001 Standard Microsystems Corporation
* Developed by Simple Network Magic Corporation
* Copyright (C) 2003 Monta Vista Software, Inc.
* Unified SMC91x driver by Nicolas Pitre
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Arguments:
* io = for the base address
* irq = for the IRQ
* nowait = 0 for normal wait states, 1 eliminates additional wait states
*
* original author:
* Erik Stahlman <erik@vt.edu>
*
* hardware multicast code:
* Peter Cammaert <pc@denkart.be>
*
* contributors:
* Daris A Nevil <dnevil@snmc.com>
* Nicolas Pitre <nico@fluxnic.net>
* Russell King <rmk@arm.linux.org.uk>
*
* History:
* 08/20/00 Arnaldo Melo fix kfree(skb) in smc_hardware_send_packet
* 12/15/00 Christian Jullien fix "Warning: kfree_skb on hard IRQ"
* 03/16/01 Daris A Nevil modified smc9194.c for use with LAN91C111
* 08/22/01 Scott Anderson merge changes from smc9194 to smc91111
* 08/21/01 Pramod B Bhardwaj added support for RevB of LAN91C111
* 12/20/01 Jeff Sutherland initial port to Xscale PXA with DMA support
* 04/07/03 Nicolas Pitre unified SMC91x driver, killed irq races,
* more bus abstraction, big cleanup, etc.
* 29/09/03 Russell King - add driver model support
* - ethtool support
* - convert to use generic MII interface
* - add link up/down notification
* - don't try to handle full negotiation in
* smc_phy_configure
* - clean up (and fix stack overrun) in PHY
* MII read/write functions
* 22/09/04 Nicolas Pitre big update (see commit log for details)
*/
static const char version[] =
"smc91x.c: v1.1, sep 22 2004 by Nicolas Pitre <nico@fluxnic.net>";
/* Debugging level */
#ifndef SMC_DEBUG
#define SMC_DEBUG 0
#endif
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/crc32.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/workqueue.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include "smc91x.h"
#if defined(CONFIG_ASSABET_NEPONSET)
#include <mach/assabet.h>
#include <mach/neponset.h>
#endif
#ifndef SMC_NOWAIT
# define SMC_NOWAIT 0
#endif
static int nowait = SMC_NOWAIT;
module_param(nowait, int, 0400);
MODULE_PARM_DESC(nowait, "set to 1 for no wait state");
/*
* Transmit timeout, default 5 seconds.
*/
static int watchdog = 1000;
module_param(watchdog, int, 0400);
MODULE_PARM_DESC(watchdog, "transmit timeout in milliseconds");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:smc91x");
/*
* The internal workings of the driver. If you are changing anything
* here with the SMC stuff, you should have the datasheet and know
* what you are doing.
*/
#define CARDNAME "smc91x"
/*
* Use power-down feature of the chip
*/
#define POWER_DOWN 1
/*
* Wait time for memory to be free. This probably shouldn't be
* tuned that much, as waiting for this means nothing else happens
* in the system
*/
#define MEMORY_WAIT_TIME 16
/*
* The maximum number of processing loops allowed for each call to the
* IRQ handler.
*/
#define MAX_IRQ_LOOPS 8
/*
* This selects whether TX packets are sent one by one to the SMC91x internal
* memory and throttled until transmission completes. This may prevent
* RX overruns a litle by keeping much of the memory free for RX packets
* but to the expense of reduced TX throughput and increased IRQ overhead.
* Note this is not a cure for a too slow data bus or too high IRQ latency.
*/
#define THROTTLE_TX_PKTS 0
/*
* The MII clock high/low times. 2x this number gives the MII clock period
* in microseconds. (was 50, but this gives 6.4ms for each MII transaction!)
*/
#define MII_DELAY 1
#define DBG(n, dev, fmt, ...) \
do { \
if (SMC_DEBUG >= (n)) \
netdev_dbg(dev, fmt, ##__VA_ARGS__); \
} while (0)
#define PRINTK(dev, fmt, ...) \
do { \
if (SMC_DEBUG > 0) \
netdev_info(dev, fmt, ##__VA_ARGS__); \
else \
netdev_dbg(dev, fmt, ##__VA_ARGS__); \
} while (0)
#if SMC_DEBUG > 3
static void PRINT_PKT(u_char *buf, int length)
{
int i;
int remainder;
int lines;
lines = length / 16;
remainder = length % 16;
for (i = 0; i < lines ; i ++) {
int cur;
printk(KERN_DEBUG);
for (cur = 0; cur < 8; cur++) {
u_char a, b;
a = *buf++;
b = *buf++;
pr_cont("%02x%02x ", a, b);
}
pr_cont("\n");
}
printk(KERN_DEBUG);
for (i = 0; i < remainder/2 ; i++) {
u_char a, b;
a = *buf++;
b = *buf++;
pr_cont("%02x%02x ", a, b);
}
pr_cont("\n");
}
#else
static inline void PRINT_PKT(u_char *buf, int length) { }
#endif
/* this enables an interrupt in the interrupt mask register */
#define SMC_ENABLE_INT(lp, x) do { \
unsigned char mask; \
unsigned long smc_enable_flags; \
spin_lock_irqsave(&lp->lock, smc_enable_flags); \
mask = SMC_GET_INT_MASK(lp); \
mask |= (x); \
SMC_SET_INT_MASK(lp, mask); \
spin_unlock_irqrestore(&lp->lock, smc_enable_flags); \
} while (0)
/* this disables an interrupt from the interrupt mask register */
#define SMC_DISABLE_INT(lp, x) do { \
unsigned char mask; \
unsigned long smc_disable_flags; \
spin_lock_irqsave(&lp->lock, smc_disable_flags); \
mask = SMC_GET_INT_MASK(lp); \
mask &= ~(x); \
SMC_SET_INT_MASK(lp, mask); \
spin_unlock_irqrestore(&lp->lock, smc_disable_flags); \
} while (0)
/*
* Wait while MMU is busy. This is usually in the order of a few nanosecs
* if at all, but let's avoid deadlocking the system if the hardware
* decides to go south.
*/
#define SMC_WAIT_MMU_BUSY(lp) do { \
if (unlikely(SMC_GET_MMU_CMD(lp) & MC_BUSY)) { \
unsigned long timeout = jiffies + 2; \
while (SMC_GET_MMU_CMD(lp) & MC_BUSY) { \
if (time_after(jiffies, timeout)) { \
netdev_dbg(dev, "timeout %s line %d\n", \
__FILE__, __LINE__); \
break; \
} \
cpu_relax(); \
} \
} \
} while (0)
/*
* this does a soft reset on the device
*/
static void smc_reset(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int ctl, cfg;
struct sk_buff *pending_skb;
DBG(2, dev, "%s\n", __func__);
/* Disable all interrupts, block TX tasklet */
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, 0);
pending_skb = lp->pending_tx_skb;
lp->pending_tx_skb = NULL;
spin_unlock_irq(&lp->lock);
/* free any pending tx skb */
if (pending_skb) {
dev_kfree_skb(pending_skb);
dev->stats.tx_errors++;
dev->stats.tx_aborted_errors++;
}
/*
* This resets the registers mostly to defaults, but doesn't
* affect EEPROM. That seems unnecessary
*/
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_SOFTRST);
/*
* Setup the Configuration Register
* This is necessary because the CONFIG_REG is not affected
* by a soft reset
*/
SMC_SELECT_BANK(lp, 1);
cfg = CONFIG_DEFAULT;
/*
* Setup for fast accesses if requested. If the card/system
* can't handle it then there will be no recovery except for
* a hard reset or power cycle
*/
if (lp->cfg.flags & SMC91X_NOWAIT)
cfg |= CONFIG_NO_WAIT;
/*
* Release from possible power-down state
* Configuration register is not affected by Soft Reset
*/
cfg |= CONFIG_EPH_POWER_EN;
SMC_SET_CONFIG(lp, cfg);
/* this should pause enough for the chip to be happy */
/*
* elaborate? What does the chip _need_? --jgarzik
*
* This seems to be undocumented, but something the original
* driver(s) have always done. Suspect undocumented timing
* info/determined empirically. --rmk
*/
udelay(1);
/* Disable transmit and receive functionality */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_CLEAR);
SMC_SET_TCR(lp, TCR_CLEAR);
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp) | CTL_LE_ENABLE;
/*
* Set the control register to automatically release successfully
* transmitted packets, to make the best use out of our limited
* memory
*/
if(!THROTTLE_TX_PKTS)
ctl |= CTL_AUTO_RELEASE;
else
ctl &= ~CTL_AUTO_RELEASE;
SMC_SET_CTL(lp, ctl);
/* Reset the MMU */
SMC_SELECT_BANK(lp, 2);
SMC_SET_MMU_CMD(lp, MC_RESET);
SMC_WAIT_MMU_BUSY(lp);
}
/*
* Enable Interrupts, Receive, and Transmit
*/
static void smc_enable(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int mask;
DBG(2, dev, "%s\n", __func__);
/* see the header file for options in TCR/RCR DEFAULT */
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
SMC_SET_RCR(lp, lp->rcr_cur_mode);
SMC_SELECT_BANK(lp, 1);
SMC_SET_MAC_ADDR(lp, dev->dev_addr);
/* now, enable interrupts */
mask = IM_EPH_INT|IM_RX_OVRN_INT|IM_RCV_INT;
if (lp->version >= (CHIP_91100 << 4))
mask |= IM_MDINT;
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, mask);
/*
* From this point the register bank must _NOT_ be switched away
* to something else than bank 2 without proper locking against
* races with any tasklet or interrupt handlers until smc_shutdown()
* or smc_reset() is called.
*/
}
/*
* this puts the device in an inactive state
*/
static void smc_shutdown(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
struct sk_buff *pending_skb;
DBG(2, dev, "%s: %s\n", CARDNAME, __func__);
/* no more interrupts for me */
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, 0);
pending_skb = lp->pending_tx_skb;
lp->pending_tx_skb = NULL;
spin_unlock_irq(&lp->lock);
if (pending_skb)
dev_kfree_skb(pending_skb);
/* and tell the card to stay away from that nasty outside world */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_CLEAR);
SMC_SET_TCR(lp, TCR_CLEAR);
#ifdef POWER_DOWN
/* finally, shut the chip down */
SMC_SELECT_BANK(lp, 1);
SMC_SET_CONFIG(lp, SMC_GET_CONFIG(lp) & ~CONFIG_EPH_POWER_EN);
#endif
}
/*
* This is the procedure to handle the receipt of a packet.
*/
static inline void smc_rcv(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int packet_number, status, packet_len;
DBG(3, dev, "%s\n", __func__);
packet_number = SMC_GET_RXFIFO(lp);
if (unlikely(packet_number & RXFIFO_REMPTY)) {
PRINTK(dev, "smc_rcv with nothing on FIFO.\n");
return;
}
/* read from start of packet */
SMC_SET_PTR(lp, PTR_READ | PTR_RCV | PTR_AUTOINC);
/* First two words are status and packet length */
SMC_GET_PKT_HDR(lp, status, packet_len);
packet_len &= 0x07ff; /* mask off top bits */
DBG(2, dev, "RX PNR 0x%x STATUS 0x%04x LENGTH 0x%04x (%d)\n",
packet_number, status, packet_len, packet_len);
back:
if (unlikely(packet_len < 6 || status & RS_ERRORS)) {
if (status & RS_TOOLONG && packet_len <= (1514 + 4 + 6)) {
/* accept VLAN packets */
status &= ~RS_TOOLONG;
goto back;
}
if (packet_len < 6) {
/* bloody hardware */
netdev_err(dev, "fubar (rxlen %u status %x\n",
packet_len, status);
status |= RS_TOOSHORT;
}
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
dev->stats.rx_errors++;
if (status & RS_ALGNERR)
dev->stats.rx_frame_errors++;
if (status & (RS_TOOSHORT | RS_TOOLONG))
dev->stats.rx_length_errors++;
if (status & RS_BADCRC)
dev->stats.rx_crc_errors++;
} else {
struct sk_buff *skb;
unsigned char *data;
unsigned int data_len;
/* set multicast stats */
if (status & RS_MULTICAST)
dev->stats.multicast++;
/*
* Actual payload is packet_len - 6 (or 5 if odd byte).
* We want skb_reserve(2) and the final ctrl word
* (2 bytes, possibly containing the payload odd byte).
* Furthermore, we add 2 bytes to allow rounding up to
* multiple of 4 bytes on 32 bit buses.
* Hence packet_len - 6 + 2 + 2 + 2.
*/
skb = netdev_alloc_skb(dev, packet_len);
if (unlikely(skb == NULL)) {
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
dev->stats.rx_dropped++;
return;
}
/* Align IP header to 32 bits */
skb_reserve(skb, 2);
/* BUG: the LAN91C111 rev A never sets this bit. Force it. */
if (lp->version == 0x90)
status |= RS_ODDFRAME;
/*
* If odd length: packet_len - 5,
* otherwise packet_len - 6.
* With the trailing ctrl byte it's packet_len - 4.
*/
data_len = packet_len - ((status & RS_ODDFRAME) ? 5 : 6);
data = skb_put(skb, data_len);
SMC_PULL_DATA(lp, data, packet_len - 4);
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
PRINT_PKT(data, packet_len - 4);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += data_len;
}
}
#ifdef CONFIG_SMP
/*
* On SMP we have the following problem:
*
* A = smc_hardware_send_pkt()
* B = smc_hard_start_xmit()
* C = smc_interrupt()
*
* A and B can never be executed simultaneously. However, at least on UP,
* it is possible (and even desirable) for C to interrupt execution of
* A or B in order to have better RX reliability and avoid overruns.
* C, just like A and B, must have exclusive access to the chip and
* each of them must lock against any other concurrent access.
* Unfortunately this is not possible to have C suspend execution of A or
* B taking place on another CPU. On UP this is no an issue since A and B
* are run from softirq context and C from hard IRQ context, and there is
* no other CPU where concurrent access can happen.
* If ever there is a way to force at least B and C to always be executed
* on the same CPU then we could use read/write locks to protect against
* any other concurrent access and C would always interrupt B. But life
* isn't that easy in a SMP world...
*/
#define smc_special_trylock(lock, flags) \
({ \
int __ret; \
local_irq_save(flags); \
__ret = spin_trylock(lock); \
if (!__ret) \
local_irq_restore(flags); \
__ret; \
})
#define smc_special_lock(lock, flags) spin_lock_irqsave(lock, flags)
#define smc_special_unlock(lock, flags) spin_unlock_irqrestore(lock, flags)
#else
#define smc_special_trylock(lock, flags) (flags == flags)
#define smc_special_lock(lock, flags) do { flags = 0; } while (0)
#define smc_special_unlock(lock, flags) do { flags = 0; } while (0)
#endif
/*
* This is called to actually send a packet to the chip.
*/
static void smc_hardware_send_pkt(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
struct sk_buff *skb;
unsigned int packet_no, len;
unsigned char *buf;
unsigned long flags;
DBG(3, dev, "%s\n", __func__);
if (!smc_special_trylock(&lp->lock, flags)) {
netif_stop_queue(dev);
tasklet_schedule(&lp->tx_task);
return;
}
skb = lp->pending_tx_skb;
if (unlikely(!skb)) {
smc_special_unlock(&lp->lock, flags);
return;
}
lp->pending_tx_skb = NULL;
packet_no = SMC_GET_AR(lp);
if (unlikely(packet_no & AR_FAILED)) {
netdev_err(dev, "Memory allocation failed.\n");
dev->stats.tx_errors++;
dev->stats.tx_fifo_errors++;
smc_special_unlock(&lp->lock, flags);
goto done;
}
/* point to the beginning of the packet */
SMC_SET_PN(lp, packet_no);
SMC_SET_PTR(lp, PTR_AUTOINC);
buf = skb->data;
len = skb->len;
DBG(2, dev, "TX PNR 0x%x LENGTH 0x%04x (%d) BUF 0x%p\n",
packet_no, len, len, buf);
PRINT_PKT(buf, len);
/*
* Send the packet length (+6 for status words, length, and ctl.
* The card will pad to 64 bytes with zeroes if packet is too small.
*/
SMC_PUT_PKT_HDR(lp, 0, len + 6);
/* send the actual data */
SMC_PUSH_DATA(lp, buf, len & ~1);
/* Send final ctl word with the last byte if there is one */
SMC_outw(((len & 1) ? (0x2000 | buf[len-1]) : 0), ioaddr, DATA_REG(lp));
/*
* If THROTTLE_TX_PKTS is set, we stop the queue here. This will
* have the effect of having at most one packet queued for TX
* in the chip's memory at all time.
*
* If THROTTLE_TX_PKTS is not set then the queue is stopped only
* when memory allocation (MC_ALLOC) does not succeed right away.
*/
if (THROTTLE_TX_PKTS)
netif_stop_queue(dev);
/* queue the packet for TX */
SMC_SET_MMU_CMD(lp, MC_ENQUEUE);
smc_special_unlock(&lp->lock, flags);
dev->trans_start = jiffies;
dev->stats.tx_packets++;
dev->stats.tx_bytes += len;
SMC_ENABLE_INT(lp, IM_TX_INT | IM_TX_EMPTY_INT);
done: if (!THROTTLE_TX_PKTS)
netif_wake_queue(dev);
dev_consume_skb_any(skb);
}
/*
* Since I am not sure if I will have enough room in the chip's ram
* to store the packet, I call this routine which either sends it
* now, or set the card to generates an interrupt when ready
* for the packet.
*/
static int smc_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int numPages, poll_count, status;
unsigned long flags;
DBG(3, dev, "%s\n", __func__);
BUG_ON(lp->pending_tx_skb != NULL);
/*
* The MMU wants the number of pages to be the number of 256 bytes
* 'pages', minus 1 (since a packet can't ever have 0 pages :))
*
* The 91C111 ignores the size bits, but earlier models don't.
*
* Pkt size for allocating is data length +6 (for additional status
* words, length and ctl)
*
* If odd size then last byte is included in ctl word.
*/
numPages = ((skb->len & ~1) + (6 - 1)) >> 8;
if (unlikely(numPages > 7)) {
netdev_warn(dev, "Far too big packet error.\n");
dev->stats.tx_errors++;
dev->stats.tx_dropped++;
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
smc_special_lock(&lp->lock, flags);
/* now, try to allocate the memory */
SMC_SET_MMU_CMD(lp, MC_ALLOC | numPages);
/*
* Poll the chip for a short amount of time in case the
* allocation succeeds quickly.
*/
poll_count = MEMORY_WAIT_TIME;
do {
status = SMC_GET_INT(lp);
if (status & IM_ALLOC_INT) {
SMC_ACK_INT(lp, IM_ALLOC_INT);
break;
}
} while (--poll_count);
smc_special_unlock(&lp->lock, flags);
lp->pending_tx_skb = skb;
if (!poll_count) {
/* oh well, wait until the chip finds memory later */
netif_stop_queue(dev);
DBG(2, dev, "TX memory allocation deferred.\n");
SMC_ENABLE_INT(lp, IM_ALLOC_INT);
} else {
/*
* Allocation succeeded: push packet to the chip's own memory
* immediately.
*/
smc_hardware_send_pkt((unsigned long)dev);
}
return NETDEV_TX_OK;
}
/*
* This handles a TX interrupt, which is only called when:
* - a TX error occurred, or
* - CTL_AUTO_RELEASE is not set and TX of a packet completed.
*/
static void smc_tx(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int saved_packet, packet_no, tx_status, pkt_len;
DBG(3, dev, "%s\n", __func__);
/* If the TX FIFO is empty then nothing to do */
packet_no = SMC_GET_TXFIFO(lp);
if (unlikely(packet_no & TXFIFO_TEMPTY)) {
PRINTK(dev, "smc_tx with nothing on FIFO.\n");
return;
}
/* select packet to read from */
saved_packet = SMC_GET_PN(lp);
SMC_SET_PN(lp, packet_no);
/* read the first word (status word) from this packet */
SMC_SET_PTR(lp, PTR_AUTOINC | PTR_READ);
SMC_GET_PKT_HDR(lp, tx_status, pkt_len);
DBG(2, dev, "TX STATUS 0x%04x PNR 0x%02x\n",
tx_status, packet_no);
if (!(tx_status & ES_TX_SUC))
dev->stats.tx_errors++;
if (tx_status & ES_LOSTCARR)
dev->stats.tx_carrier_errors++;
if (tx_status & (ES_LATCOL | ES_16COL)) {
PRINTK(dev, "%s occurred on last xmit\n",
(tx_status & ES_LATCOL) ?
"late collision" : "too many collisions");
dev->stats.tx_window_errors++;
if (!(dev->stats.tx_window_errors & 63) && net_ratelimit()) {
netdev_info(dev, "unexpectedly large number of bad collisions. Please check duplex setting.\n");
}
}
/* kill the packet */
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_FREEPKT);
/* Don't restore Packet Number Reg until busy bit is cleared */
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_PN(lp, saved_packet);
/* re-enable transmit */
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
SMC_SELECT_BANK(lp, 2);
}
/*---PHY CONTROL AND CONFIGURATION-----------------------------------------*/
static void smc_mii_out(struct net_device *dev, unsigned int val, int bits)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int mii_reg, mask;
mii_reg = SMC_GET_MII(lp) & ~(MII_MCLK | MII_MDOE | MII_MDO);
mii_reg |= MII_MDOE;
for (mask = 1 << (bits - 1); mask; mask >>= 1) {
if (val & mask)
mii_reg |= MII_MDO;
else
mii_reg &= ~MII_MDO;
SMC_SET_MII(lp, mii_reg);
udelay(MII_DELAY);
SMC_SET_MII(lp, mii_reg | MII_MCLK);
udelay(MII_DELAY);
}
}
static unsigned int smc_mii_in(struct net_device *dev, int bits)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int mii_reg, mask, val;
mii_reg = SMC_GET_MII(lp) & ~(MII_MCLK | MII_MDOE | MII_MDO);
SMC_SET_MII(lp, mii_reg);
for (mask = 1 << (bits - 1), val = 0; mask; mask >>= 1) {
if (SMC_GET_MII(lp) & MII_MDI)
val |= mask;
SMC_SET_MII(lp, mii_reg);
udelay(MII_DELAY);
SMC_SET_MII(lp, mii_reg | MII_MCLK);
udelay(MII_DELAY);
}
return val;
}
/*
* Reads a register from the MII Management serial interface
*/
static int smc_phy_read(struct net_device *dev, int phyaddr, int phyreg)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int phydata;
SMC_SELECT_BANK(lp, 3);
/* Idle - 32 ones */
smc_mii_out(dev, 0xffffffff, 32);
/* Start code (01) + read (10) + phyaddr + phyreg */
smc_mii_out(dev, 6 << 10 | phyaddr << 5 | phyreg, 14);
/* Turnaround (2bits) + phydata */
phydata = smc_mii_in(dev, 18);
/* Return to idle state */
SMC_SET_MII(lp, SMC_GET_MII(lp) & ~(MII_MCLK|MII_MDOE|MII_MDO));
DBG(3, dev, "%s: phyaddr=0x%x, phyreg=0x%x, phydata=0x%x\n",
__func__, phyaddr, phyreg, phydata);
SMC_SELECT_BANK(lp, 2);
return phydata;
}
/*
* Writes a register to the MII Management serial interface
*/
static void smc_phy_write(struct net_device *dev, int phyaddr, int phyreg,
int phydata)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
SMC_SELECT_BANK(lp, 3);
/* Idle - 32 ones */
smc_mii_out(dev, 0xffffffff, 32);
/* Start code (01) + write (01) + phyaddr + phyreg + turnaround + phydata */
smc_mii_out(dev, 5 << 28 | phyaddr << 23 | phyreg << 18 | 2 << 16 | phydata, 32);
/* Return to idle state */
SMC_SET_MII(lp, SMC_GET_MII(lp) & ~(MII_MCLK|MII_MDOE|MII_MDO));
DBG(3, dev, "%s: phyaddr=0x%x, phyreg=0x%x, phydata=0x%x\n",
__func__, phyaddr, phyreg, phydata);
SMC_SELECT_BANK(lp, 2);
}
/*
* Finds and reports the PHY address
*/
static void smc_phy_detect(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int phyaddr;
DBG(2, dev, "%s\n", __func__);
lp->phy_type = 0;
/*
* Scan all 32 PHY addresses if necessary, starting at
* PHY#1 to PHY#31, and then PHY#0 last.
*/
for (phyaddr = 1; phyaddr < 33; ++phyaddr) {
unsigned int id1, id2;
/* Read the PHY identifiers */
id1 = smc_phy_read(dev, phyaddr & 31, MII_PHYSID1);
id2 = smc_phy_read(dev, phyaddr & 31, MII_PHYSID2);
DBG(3, dev, "phy_id1=0x%x, phy_id2=0x%x\n",
id1, id2);
/* Make sure it is a valid identifier */
if (id1 != 0x0000 && id1 != 0xffff && id1 != 0x8000 &&
id2 != 0x0000 && id2 != 0xffff && id2 != 0x8000) {
/* Save the PHY's address */
lp->mii.phy_id = phyaddr & 31;
lp->phy_type = id1 << 16 | id2;
break;
}
}
}
/*
* Sets the PHY to a configuration as determined by the user
*/
static int smc_phy_fixed(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int phyaddr = lp->mii.phy_id;
int bmcr, cfg1;
DBG(3, dev, "%s\n", __func__);
/* Enter Link Disable state */
cfg1 = smc_phy_read(dev, phyaddr, PHY_CFG1_REG);
cfg1 |= PHY_CFG1_LNKDIS;
smc_phy_write(dev, phyaddr, PHY_CFG1_REG, cfg1);
/*
* Set our fixed capabilities
* Disable auto-negotiation
*/
bmcr = 0;
if (lp->ctl_rfduplx)
bmcr |= BMCR_FULLDPLX;
if (lp->ctl_rspeed == 100)
bmcr |= BMCR_SPEED100;
/* Write our capabilities to the phy control register */
smc_phy_write(dev, phyaddr, MII_BMCR, bmcr);
/* Re-Configure the Receive/Phy Control register */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RPC(lp, lp->rpc_cur_mode);
SMC_SELECT_BANK(lp, 2);
return 1;
}
/**
* smc_phy_reset - reset the phy
* @dev: net device
* @phy: phy address
*
* Issue a software reset for the specified PHY and
* wait up to 100ms for the reset to complete. We should
* not access the PHY for 50ms after issuing the reset.
*
* The time to wait appears to be dependent on the PHY.
*
* Must be called with lp->lock locked.
*/
static int smc_phy_reset(struct net_device *dev, int phy)
{
struct smc_local *lp = netdev_priv(dev);
unsigned int bmcr;
int timeout;
smc_phy_write(dev, phy, MII_BMCR, BMCR_RESET);
for (timeout = 2; timeout; timeout--) {
spin_unlock_irq(&lp->lock);
msleep(50);
spin_lock_irq(&lp->lock);
bmcr = smc_phy_read(dev, phy, MII_BMCR);
if (!(bmcr & BMCR_RESET))
break;
}
return bmcr & BMCR_RESET;
}
/**
* smc_phy_powerdown - powerdown phy
* @dev: net device
*
* Power down the specified PHY
*/
static void smc_phy_powerdown(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
unsigned int bmcr;
int phy = lp->mii.phy_id;
if (lp->phy_type == 0)
return;
/* We need to ensure that no calls to smc_phy_configure are
pending.
*/
cancel_work_sync(&lp->phy_configure);
bmcr = smc_phy_read(dev, phy, MII_BMCR);
smc_phy_write(dev, phy, MII_BMCR, bmcr | BMCR_PDOWN);
}
/**
* smc_phy_check_media - check the media status and adjust TCR
* @dev: net device
* @init: set true for initialisation
*
* Select duplex mode depending on negotiation state. This
* also updates our carrier state.
*/
static void smc_phy_check_media(struct net_device *dev, int init)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
if (mii_check_media(&lp->mii, netif_msg_link(lp), init)) {
/* duplex state has changed */
if (lp->mii.full_duplex) {
lp->tcr_cur_mode |= TCR_SWFDUP;
} else {
lp->tcr_cur_mode &= ~TCR_SWFDUP;
}
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
}
}
/*
* Configures the specified PHY through the MII management interface
* using Autonegotiation.
* Calls smc_phy_fixed() if the user has requested a certain config.
* If RPC ANEG bit is set, the media selection is dependent purely on
* the selection by the MII (either in the MII BMCR reg or the result
* of autonegotiation.) If the RPC ANEG bit is cleared, the selection
* is controlled by the RPC SPEED and RPC DPLX bits.
*/
static void smc_phy_configure(struct work_struct *work)
{
struct smc_local *lp =
container_of(work, struct smc_local, phy_configure);
struct net_device *dev = lp->dev;
void __iomem *ioaddr = lp->base;
int phyaddr = lp->mii.phy_id;
int my_phy_caps; /* My PHY capabilities */
int my_ad_caps; /* My Advertised capabilities */
int status;
DBG(3, dev, "smc_program_phy()\n");
spin_lock_irq(&lp->lock);
/*
* We should not be called if phy_type is zero.
*/
if (lp->phy_type == 0)
goto smc_phy_configure_exit;
if (smc_phy_reset(dev, phyaddr)) {
netdev_info(dev, "PHY reset timed out\n");
goto smc_phy_configure_exit;
}
/*
* Enable PHY Interrupts (for register 18)
* Interrupts listed here are disabled
*/
smc_phy_write(dev, phyaddr, PHY_MASK_REG,
PHY_INT_LOSSSYNC | PHY_INT_CWRD | PHY_INT_SSD |
PHY_INT_ESD | PHY_INT_RPOL | PHY_INT_JAB |
PHY_INT_SPDDET | PHY_INT_DPLXDET);
/* Configure the Receive/Phy Control register */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RPC(lp, lp->rpc_cur_mode);
/* If the user requested no auto neg, then go set his request */
if (lp->mii.force_media) {
smc_phy_fixed(dev);
goto smc_phy_configure_exit;
}
/* Copy our capabilities from MII_BMSR to MII_ADVERTISE */
my_phy_caps = smc_phy_read(dev, phyaddr, MII_BMSR);
if (!(my_phy_caps & BMSR_ANEGCAPABLE)) {
netdev_info(dev, "Auto negotiation NOT supported\n");
smc_phy_fixed(dev);
goto smc_phy_configure_exit;
}
my_ad_caps = ADVERTISE_CSMA; /* I am CSMA capable */
if (my_phy_caps & BMSR_100BASE4)
my_ad_caps |= ADVERTISE_100BASE4;
if (my_phy_caps & BMSR_100FULL)
my_ad_caps |= ADVERTISE_100FULL;
if (my_phy_caps & BMSR_100HALF)
my_ad_caps |= ADVERTISE_100HALF;
if (my_phy_caps & BMSR_10FULL)
my_ad_caps |= ADVERTISE_10FULL;
if (my_phy_caps & BMSR_10HALF)
my_ad_caps |= ADVERTISE_10HALF;
/* Disable capabilities not selected by our user */
if (lp->ctl_rspeed != 100)
my_ad_caps &= ~(ADVERTISE_100BASE4|ADVERTISE_100FULL|ADVERTISE_100HALF);
if (!lp->ctl_rfduplx)
my_ad_caps &= ~(ADVERTISE_100FULL|ADVERTISE_10FULL);
/* Update our Auto-Neg Advertisement Register */
smc_phy_write(dev, phyaddr, MII_ADVERTISE, my_ad_caps);
lp->mii.advertising = my_ad_caps;
/*
* Read the register back. Without this, it appears that when
* auto-negotiation is restarted, sometimes it isn't ready and
* the link does not come up.
*/
status = smc_phy_read(dev, phyaddr, MII_ADVERTISE);
DBG(2, dev, "phy caps=%x\n", my_phy_caps);
DBG(2, dev, "phy advertised caps=%x\n", my_ad_caps);
/* Restart auto-negotiation process in order to advertise my caps */
smc_phy_write(dev, phyaddr, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART);
smc_phy_check_media(dev, 1);
smc_phy_configure_exit:
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
}
/*
* smc_phy_interrupt
*
* Purpose: Handle interrupts relating to PHY register 18. This is
* called from the "hard" interrupt handler under our private spinlock.
*/
static void smc_phy_interrupt(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int phyaddr = lp->mii.phy_id;
int phy18;
DBG(2, dev, "%s\n", __func__);
if (lp->phy_type == 0)
return;
for(;;) {
smc_phy_check_media(dev, 0);
/* Read PHY Register 18, Status Output */
phy18 = smc_phy_read(dev, phyaddr, PHY_INT_REG);
if ((phy18 & PHY_INT_INT) == 0)
break;
}
}
/*--- END PHY CONTROL AND CONFIGURATION-------------------------------------*/
static void smc_10bt_check_media(struct net_device *dev, int init)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int old_carrier, new_carrier;
old_carrier = netif_carrier_ok(dev) ? 1 : 0;
SMC_SELECT_BANK(lp, 0);
new_carrier = (SMC_GET_EPH_STATUS(lp) & ES_LINK_OK) ? 1 : 0;
SMC_SELECT_BANK(lp, 2);
if (init || (old_carrier != new_carrier)) {
if (!new_carrier) {
netif_carrier_off(dev);
} else {
netif_carrier_on(dev);
}
if (netif_msg_link(lp))
netdev_info(dev, "link %s\n",
new_carrier ? "up" : "down");
}
}
static void smc_eph_interrupt(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int ctl;
smc_10bt_check_media(dev, 0);
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl & ~CTL_LE_ENABLE);
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
}
/*
* This is the main routine of the driver, to handle the device when
* it needs some attention.
*/
static irqreturn_t smc_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int status, mask, timeout, card_stats;
int saved_pointer;
DBG(3, dev, "%s\n", __func__);
spin_lock(&lp->lock);
/* A preamble may be used when there is a potential race
* between the interruptible transmit functions and this
* ISR. */
SMC_INTERRUPT_PREAMBLE;
saved_pointer = SMC_GET_PTR(lp);
mask = SMC_GET_INT_MASK(lp);
SMC_SET_INT_MASK(lp, 0);
/* set a timeout value, so I don't stay here forever */
timeout = MAX_IRQ_LOOPS;
do {
status = SMC_GET_INT(lp);
DBG(2, dev, "INT 0x%02x MASK 0x%02x MEM 0x%04x FIFO 0x%04x\n",
status, mask,
({ int meminfo; SMC_SELECT_BANK(lp, 0);
meminfo = SMC_GET_MIR(lp);
SMC_SELECT_BANK(lp, 2); meminfo; }),
SMC_GET_FIFO(lp));
status &= mask;
if (!status)
break;
if (status & IM_TX_INT) {
/* do this before RX as it will free memory quickly */
DBG(3, dev, "TX int\n");
smc_tx(dev);
SMC_ACK_INT(lp, IM_TX_INT);
if (THROTTLE_TX_PKTS)
netif_wake_queue(dev);
} else if (status & IM_RCV_INT) {
DBG(3, dev, "RX irq\n");
smc_rcv(dev);
} else if (status & IM_ALLOC_INT) {
DBG(3, dev, "Allocation irq\n");
tasklet_hi_schedule(&lp->tx_task);
mask &= ~IM_ALLOC_INT;
} else if (status & IM_TX_EMPTY_INT) {
DBG(3, dev, "TX empty\n");
mask &= ~IM_TX_EMPTY_INT;
/* update stats */
SMC_SELECT_BANK(lp, 0);
card_stats = SMC_GET_COUNTER(lp);
SMC_SELECT_BANK(lp, 2);
/* single collisions */
dev->stats.collisions += card_stats & 0xF;
card_stats >>= 4;
/* multiple collisions */
dev->stats.collisions += card_stats & 0xF;
} else if (status & IM_RX_OVRN_INT) {
DBG(1, dev, "RX overrun (EPH_ST 0x%04x)\n",
({ int eph_st; SMC_SELECT_BANK(lp, 0);
eph_st = SMC_GET_EPH_STATUS(lp);
SMC_SELECT_BANK(lp, 2); eph_st; }));
SMC_ACK_INT(lp, IM_RX_OVRN_INT);
dev->stats.rx_errors++;
dev->stats.rx_fifo_errors++;
} else if (status & IM_EPH_INT) {
smc_eph_interrupt(dev);
} else if (status & IM_MDINT) {
SMC_ACK_INT(lp, IM_MDINT);
smc_phy_interrupt(dev);
} else if (status & IM_ERCV_INT) {
SMC_ACK_INT(lp, IM_ERCV_INT);
PRINTK(dev, "UNSUPPORTED: ERCV INTERRUPT\n");
}
} while (--timeout);
/* restore register states */
SMC_SET_PTR(lp, saved_pointer);
SMC_SET_INT_MASK(lp, mask);
spin_unlock(&lp->lock);
#ifndef CONFIG_NET_POLL_CONTROLLER
if (timeout == MAX_IRQ_LOOPS)
PRINTK(dev, "spurious interrupt (mask = 0x%02x)\n",
mask);
#endif
DBG(3, dev, "Interrupt done (%d loops)\n",
MAX_IRQ_LOOPS - timeout);
/*
* We return IRQ_HANDLED unconditionally here even if there was
* nothing to do. There is a possibility that a packet might
* get enqueued into the chip right after TX_EMPTY_INT is raised
* but just before the CPU acknowledges the IRQ.
* Better take an unneeded IRQ in some occasions than complexifying
* the code for all cases.
*/
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling receive - used by netconsole and other diagnostic tools
* to allow network i/o with interrupts disabled.
*/
static void smc_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
smc_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
/* Our watchdog timed out. Called by the networking layer */
static void smc_timeout(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int status, mask, eph_st, meminfo, fifo;
DBG(2, dev, "%s\n", __func__);
spin_lock_irq(&lp->lock);
status = SMC_GET_INT(lp);
mask = SMC_GET_INT_MASK(lp);
fifo = SMC_GET_FIFO(lp);
SMC_SELECT_BANK(lp, 0);
eph_st = SMC_GET_EPH_STATUS(lp);
meminfo = SMC_GET_MIR(lp);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
PRINTK(dev, "TX timeout (INT 0x%02x INTMASK 0x%02x MEM 0x%04x FIFO 0x%04x EPH_ST 0x%04x)\n",
status, mask, meminfo, fifo, eph_st);
smc_reset(dev);
smc_enable(dev);
/*
* Reconfiguring the PHY doesn't seem like a bad idea here, but
* smc_phy_configure() calls msleep() which calls schedule_timeout()
* which calls schedule(). Hence we use a work queue.
*/
if (lp->phy_type != 0)
schedule_work(&lp->phy_configure);
/* We can accept TX packets again */
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
/*
* This routine will, depending on the values passed to it,
* either make it accept multicast packets, go into
* promiscuous mode (for TCPDUMP and cousins) or accept
* a select set of multicast packets
*/
static void smc_set_multicast_list(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned char multicast_table[8];
int update_multicast = 0;
DBG(2, dev, "%s\n", __func__);
if (dev->flags & IFF_PROMISC) {
DBG(2, dev, "RCR_PRMS\n");
lp->rcr_cur_mode |= RCR_PRMS;
}
/* BUG? I never disable promiscuous mode if multicasting was turned on.
Now, I turn off promiscuous mode, but I don't do anything to multicasting
when promiscuous mode is turned on.
*/
/*
* Here, I am setting this to accept all multicast packets.
* I don't need to zero the multicast table, because the flag is
* checked before the table is
*/
else if (dev->flags & IFF_ALLMULTI || netdev_mc_count(dev) > 16) {
DBG(2, dev, "RCR_ALMUL\n");
lp->rcr_cur_mode |= RCR_ALMUL;
}
/*
* This sets the internal hardware table to filter out unwanted
* multicast packets before they take up memory.
*
* The SMC chip uses a hash table where the high 6 bits of the CRC of
* address are the offset into the table. If that bit is 1, then the
* multicast packet is accepted. Otherwise, it's dropped silently.
*
* To use the 6 bits as an offset into the table, the high 3 bits are
* the number of the 8 bit register, while the low 3 bits are the bit
* within that register.
*/
else if (!netdev_mc_empty(dev)) {
struct netdev_hw_addr *ha;
/* table for flipping the order of 3 bits */
static const unsigned char invert3[] = {0, 4, 2, 6, 1, 5, 3, 7};
/* start with a table of all zeros: reject all */
memset(multicast_table, 0, sizeof(multicast_table));
netdev_for_each_mc_addr(ha, dev) {
int position;
/* only use the low order bits */
position = crc32_le(~0, ha->addr, 6) & 0x3f;
/* do some messy swapping to put the bit in the right spot */
multicast_table[invert3[position&7]] |=
(1<<invert3[(position>>3)&7]);
}
/* be sure I get rid of flags I might have set */
lp->rcr_cur_mode &= ~(RCR_PRMS | RCR_ALMUL);
/* now, the table can be loaded into the chipset */
update_multicast = 1;
} else {
DBG(2, dev, "~(RCR_PRMS|RCR_ALMUL)\n");
lp->rcr_cur_mode &= ~(RCR_PRMS | RCR_ALMUL);
/*
* since I'm disabling all multicast entirely, I need to
* clear the multicast list
*/
memset(multicast_table, 0, sizeof(multicast_table));
update_multicast = 1;
}
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, lp->rcr_cur_mode);
if (update_multicast) {
SMC_SELECT_BANK(lp, 3);
SMC_SET_MCAST(lp, multicast_table);
}
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
}
/*
* Open and Initialize the board
*
* Set up everything, reset the card, etc..
*/
static int
smc_open(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
DBG(2, dev, "%s\n", __func__);
/* Setup the default Register Modes */
lp->tcr_cur_mode = TCR_DEFAULT;
lp->rcr_cur_mode = RCR_DEFAULT;
lp->rpc_cur_mode = RPC_DEFAULT |
lp->cfg.leda << RPC_LSXA_SHFT |
lp->cfg.ledb << RPC_LSXB_SHFT;
/*
* If we are not using a MII interface, we need to
* monitor our own carrier signal to detect faults.
*/
if (lp->phy_type == 0)
lp->tcr_cur_mode |= TCR_MON_CSN;
/* reset the hardware */
smc_reset(dev);
smc_enable(dev);
/* Configure the PHY, initialize the link state */
if (lp->phy_type != 0)
smc_phy_configure(&lp->phy_configure);
else {
spin_lock_irq(&lp->lock);
smc_10bt_check_media(dev, 1);
spin_unlock_irq(&lp->lock);
}
netif_start_queue(dev);
return 0;
}
/*
* smc_close
*
* this makes the board clean up everything that it can
* and not talk to the outside world. Caused by
* an 'ifconfig ethX down'
*/
static int smc_close(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
DBG(2, dev, "%s\n", __func__);
netif_stop_queue(dev);
netif_carrier_off(dev);
/* clear everything */
smc_shutdown(dev);
tasklet_kill(&lp->tx_task);
smc_phy_powerdown(dev);
return 0;
}
/*
* Ethtool support
*/
static int
smc_ethtool_getsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smc_local *lp = netdev_priv(dev);
int ret;
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_ethtool_gset(&lp->mii, cmd);
spin_unlock_irq(&lp->lock);
} else {
cmd->supported = SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_TP | SUPPORTED_AUI;
if (lp->ctl_rspeed == 10)
ethtool_cmd_speed_set(cmd, SPEED_10);
else if (lp->ctl_rspeed == 100)
ethtool_cmd_speed_set(cmd, SPEED_100);
cmd->autoneg = AUTONEG_DISABLE;
cmd->transceiver = XCVR_INTERNAL;
cmd->port = 0;
cmd->duplex = lp->tcr_cur_mode & TCR_SWFDUP ? DUPLEX_FULL : DUPLEX_HALF;
ret = 0;
}
return ret;
}
static int
smc_ethtool_setsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smc_local *lp = netdev_priv(dev);
int ret;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_ethtool_sset(&lp->mii, cmd);
spin_unlock_irq(&lp->lock);
} else {
if (cmd->autoneg != AUTONEG_DISABLE ||
cmd->speed != SPEED_10 ||
(cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL) ||
(cmd->port != PORT_TP && cmd->port != PORT_AUI))
return -EINVAL;
// lp->port = cmd->port;
lp->ctl_rfduplx = cmd->duplex == DUPLEX_FULL;
// if (netif_running(dev))
// smc_set_port(dev);
ret = 0;
}
return ret;
}
static void
smc_ethtool_getdrvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strlcpy(info->driver, CARDNAME, sizeof(info->driver));
strlcpy(info->version, version, sizeof(info->version));
strlcpy(info->bus_info, dev_name(dev->dev.parent),
sizeof(info->bus_info));
}
static int smc_ethtool_nwayreset(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int ret = -EINVAL;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_nway_restart(&lp->mii);
spin_unlock_irq(&lp->lock);
}
return ret;
}
static u32 smc_ethtool_getmsglevel(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
return lp->msg_enable;
}
static void smc_ethtool_setmsglevel(struct net_device *dev, u32 level)
{
struct smc_local *lp = netdev_priv(dev);
lp->msg_enable = level;
}
static int smc_write_eeprom_word(struct net_device *dev, u16 addr, u16 word)
{
u16 ctl;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
spin_lock_irq(&lp->lock);
/* load word into GP register */
SMC_SELECT_BANK(lp, 1);
SMC_SET_GP(lp, word);
/* set the address to put the data in EEPROM */
SMC_SELECT_BANK(lp, 2);
SMC_SET_PTR(lp, addr);
/* tell it to write */
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl | (CTL_EEPROM_SELECT | CTL_STORE));
/* wait for it to finish */
do {
udelay(1);
} while (SMC_GET_CTL(lp) & CTL_STORE);
/* clean up */
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
return 0;
}
static int smc_read_eeprom_word(struct net_device *dev, u16 addr, u16 *word)
{
u16 ctl;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
spin_lock_irq(&lp->lock);
/* set the EEPROM address to get the data from */
SMC_SELECT_BANK(lp, 2);
SMC_SET_PTR(lp, addr | PTR_READ);
/* tell it to load */
SMC_SELECT_BANK(lp, 1);
SMC_SET_GP(lp, 0xffff); /* init to known */
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl | (CTL_EEPROM_SELECT | CTL_RELOAD));
/* wait for it to finish */
do {
udelay(1);
} while (SMC_GET_CTL(lp) & CTL_RELOAD);
/* read word from GP register */
*word = SMC_GET_GP(lp);
/* clean up */
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
return 0;
}
static int smc_ethtool_geteeprom_len(struct net_device *dev)
{
return 0x23 * 2;
}
static int smc_ethtool_geteeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int i;
int imax;
DBG(1, dev, "Reading %d bytes at %d(0x%x)\n",
eeprom->len, eeprom->offset, eeprom->offset);
imax = smc_ethtool_geteeprom_len(dev);
for (i = 0; i < eeprom->len; i += 2) {
int ret;
u16 wbuf;
int offset = i + eeprom->offset;
if (offset > imax)
break;
ret = smc_read_eeprom_word(dev, offset >> 1, &wbuf);
if (ret != 0)
return ret;
DBG(2, dev, "Read 0x%x from 0x%x\n", wbuf, offset >> 1);
data[i] = (wbuf >> 8) & 0xff;
data[i+1] = wbuf & 0xff;
}
return 0;
}
static int smc_ethtool_seteeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int i;
int imax;
DBG(1, dev, "Writing %d bytes to %d(0x%x)\n",
eeprom->len, eeprom->offset, eeprom->offset);
imax = smc_ethtool_geteeprom_len(dev);
for (i = 0; i < eeprom->len; i += 2) {
int ret;
u16 wbuf;
int offset = i + eeprom->offset;
if (offset > imax)
break;
wbuf = (data[i] << 8) | data[i + 1];
DBG(2, dev, "Writing 0x%x to 0x%x\n", wbuf, offset >> 1);
ret = smc_write_eeprom_word(dev, offset >> 1, wbuf);
if (ret != 0)
return ret;
}
return 0;
}
static const struct ethtool_ops smc_ethtool_ops = {
.get_settings = smc_ethtool_getsettings,
.set_settings = smc_ethtool_setsettings,
.get_drvinfo = smc_ethtool_getdrvinfo,
.get_msglevel = smc_ethtool_getmsglevel,
.set_msglevel = smc_ethtool_setmsglevel,
.nway_reset = smc_ethtool_nwayreset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = smc_ethtool_geteeprom_len,
.get_eeprom = smc_ethtool_geteeprom,
.set_eeprom = smc_ethtool_seteeprom,
};
static const struct net_device_ops smc_netdev_ops = {
.ndo_open = smc_open,
.ndo_stop = smc_close,
.ndo_start_xmit = smc_hard_start_xmit,
.ndo_tx_timeout = smc_timeout,
.ndo_set_rx_mode = smc_set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = smc_poll_controller,
#endif
};
/*
* smc_findirq
*
* This routine has a simple purpose -- make the SMC chip generate an
* interrupt, so an auto-detect routine can detect it, and find the IRQ,
*/
/*
* does this still work?
*
* I just deleted auto_irq.c, since it was never built...
* --jgarzik
*/
static int smc_findirq(struct smc_local *lp)
{
void __iomem *ioaddr = lp->base;
int timeout = 20;
unsigned long cookie;
DBG(2, lp->dev, "%s: %s\n", CARDNAME, __func__);
cookie = probe_irq_on();
/*
* What I try to do here is trigger an ALLOC_INT. This is done
* by allocating a small chunk of memory, which will give an interrupt
* when done.
*/
/* enable ALLOCation interrupts ONLY */
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, IM_ALLOC_INT);
/*
* Allocate 512 bytes of memory. Note that the chip was just
* reset so all the memory is available
*/
SMC_SET_MMU_CMD(lp, MC_ALLOC | 1);
/*
* Wait until positive that the interrupt has been generated
*/
do {
int int_status;
udelay(10);
int_status = SMC_GET_INT(lp);
if (int_status & IM_ALLOC_INT)
break; /* got the interrupt */
} while (--timeout);
/*
* there is really nothing that I can do here if timeout fails,
* as autoirq_report will return a 0 anyway, which is what I
* want in this case. Plus, the clean up is needed in both
* cases.
*/
/* and disable all interrupts again */
SMC_SET_INT_MASK(lp, 0);
/* and return what I found */
return probe_irq_off(cookie);
}
/*
* Function: smc_probe(unsigned long ioaddr)
*
* Purpose:
* Tests to see if a given ioaddr points to an SMC91x chip.
* Returns a 0 on success
*
* Algorithm:
* (1) see if the high byte of BANK_SELECT is 0x33
* (2) compare the ioaddr with the base register's address
* (3) see if I recognize the chip ID in the appropriate register
*
* Here I do typical initialization tasks.
*
* o Initialize the structure if needed
* o print out my vanity message if not done so already
* o print out what type of hardware is detected
* o print out the ethernet address
* o find the IRQ
* o set up my private data
* o configure the dev structure with my subroutines
* o actually GRAB the irq.
* o GRAB the region
*/
static int smc_probe(struct net_device *dev, void __iomem *ioaddr,
unsigned long irq_flags)
{
struct smc_local *lp = netdev_priv(dev);
int retval;
unsigned int val, revision_register;
const char *version_string;
DBG(2, dev, "%s: %s\n", CARDNAME, __func__);
/* First, see if the high byte is 0x33 */
val = SMC_CURRENT_BANK(lp);
DBG(2, dev, "%s: bank signature probe returned 0x%04x\n",
CARDNAME, val);
if ((val & 0xFF00) != 0x3300) {
if ((val & 0xFF) == 0x33) {
netdev_warn(dev,
"%s: Detected possible byte-swapped interface at IOADDR %p\n",
CARDNAME, ioaddr);
}
retval = -ENODEV;
goto err_out;
}
/*
* The above MIGHT indicate a device, but I need to write to
* further test this.
*/
SMC_SELECT_BANK(lp, 0);
val = SMC_CURRENT_BANK(lp);
if ((val & 0xFF00) != 0x3300) {
retval = -ENODEV;
goto err_out;
}
/*
* well, we've already written once, so hopefully another
* time won't hurt. This time, I need to switch the bank
* register to bank 1, so I can access the base address
* register
*/
SMC_SELECT_BANK(lp, 1);
val = SMC_GET_BASE(lp);
val = ((val & 0x1F00) >> 3) << SMC_IO_SHIFT;
if (((unsigned long)ioaddr & (0x3e0 << SMC_IO_SHIFT)) != val) {
netdev_warn(dev, "%s: IOADDR %p doesn't match configuration (%x).\n",
CARDNAME, ioaddr, val);
}
/*
* check if the revision register is something that I
* recognize. These might need to be added to later,
* as future revisions could be added.
*/
SMC_SELECT_BANK(lp, 3);
revision_register = SMC_GET_REV(lp);
DBG(2, dev, "%s: revision = 0x%04x\n", CARDNAME, revision_register);
version_string = chip_ids[ (revision_register >> 4) & 0xF];
if (!version_string || (revision_register & 0xff00) != 0x3300) {
/* I don't recognize this chip, so... */
netdev_warn(dev, "%s: IO %p: Unrecognized revision register 0x%04x, Contact author.\n",
CARDNAME, ioaddr, revision_register);
retval = -ENODEV;
goto err_out;
}
/* At this point I'll assume that the chip is an SMC91x. */
pr_info_once("%s\n", version);
/* fill in some of the fields */
dev->base_addr = (unsigned long)ioaddr;
lp->base = ioaddr;
lp->version = revision_register & 0xff;
spin_lock_init(&lp->lock);
/* Get the MAC address */
SMC_SELECT_BANK(lp, 1);
SMC_GET_MAC_ADDR(lp, dev->dev_addr);
/* now, reset the chip, and put it into a known state */
smc_reset(dev);
/*
* If dev->irq is 0, then the device has to be banged on to see
* what the IRQ is.
*
* This banging doesn't always detect the IRQ, for unknown reasons.
* a workaround is to reset the chip and try again.
*
* Interestingly, the DOS packet driver *SETS* the IRQ on the card to
* be what is requested on the command line. I don't do that, mostly
* because the card that I have uses a non-standard method of accessing
* the IRQs, and because this _should_ work in most configurations.
*
* Specifying an IRQ is done with the assumption that the user knows
* what (s)he is doing. No checking is done!!!!
*/
if (dev->irq < 1) {
int trials;
trials = 3;
while (trials--) {
dev->irq = smc_findirq(lp);
if (dev->irq)
break;
/* kick the card and try again */
smc_reset(dev);
}
}
if (dev->irq == 0) {
netdev_warn(dev, "Couldn't autodetect your IRQ. Use irq=xx.\n");
retval = -ENODEV;
goto err_out;
}
dev->irq = irq_canonicalize(dev->irq);
dev->watchdog_timeo = msecs_to_jiffies(watchdog);
dev->netdev_ops = &smc_netdev_ops;
dev->ethtool_ops = &smc_ethtool_ops;
tasklet_init(&lp->tx_task, smc_hardware_send_pkt, (unsigned long)dev);
INIT_WORK(&lp->phy_configure, smc_phy_configure);
lp->dev = dev;
lp->mii.phy_id_mask = 0x1f;
lp->mii.reg_num_mask = 0x1f;
lp->mii.force_media = 0;
lp->mii.full_duplex = 0;
lp->mii.dev = dev;
lp->mii.mdio_read = smc_phy_read;
lp->mii.mdio_write = smc_phy_write;
/*
* Locate the phy, if any.
*/
if (lp->version >= (CHIP_91100 << 4))
smc_phy_detect(dev);
/* then shut everything down to save power */
smc_shutdown(dev);
smc_phy_powerdown(dev);
/* Set default parameters */
lp->msg_enable = NETIF_MSG_LINK;
lp->ctl_rfduplx = 0;
lp->ctl_rspeed = 10;
if (lp->version >= (CHIP_91100 << 4)) {
lp->ctl_rfduplx = 1;
lp->ctl_rspeed = 100;
}
/* Grab the IRQ */
retval = request_irq(dev->irq, smc_interrupt, irq_flags, dev->name, dev);
if (retval)
goto err_out;
#ifdef CONFIG_ARCH_PXA
# ifdef SMC_USE_PXA_DMA
lp->cfg.flags |= SMC91X_USE_DMA;
# endif
if (lp->cfg.flags & SMC91X_USE_DMA) {
dma_cap_mask_t mask;
struct pxad_param param;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
param.prio = PXAD_PRIO_LOWEST;
param.drcmr = -1UL;
lp->dma_chan =
dma_request_slave_channel_compat(mask, pxad_filter_fn,
¶m, &dev->dev,
"data");
}
#endif
retval = register_netdev(dev);
if (retval == 0) {
/* now, print out the card info, in a short format.. */
netdev_info(dev, "%s (rev %d) at %p IRQ %d",
version_string, revision_register & 0x0f,
lp->base, dev->irq);
if (lp->dma_chan)
pr_cont(" DMA %p", lp->dma_chan);
pr_cont("%s%s\n",
lp->cfg.flags & SMC91X_NOWAIT ? " [nowait]" : "",
THROTTLE_TX_PKTS ? " [throttle_tx]" : "");
if (!is_valid_ether_addr(dev->dev_addr)) {
netdev_warn(dev, "Invalid ethernet MAC address. Please set using ifconfig\n");
} else {
/* Print the Ethernet address */
netdev_info(dev, "Ethernet addr: %pM\n",
dev->dev_addr);
}
if (lp->phy_type == 0) {
PRINTK(dev, "No PHY found\n");
} else if ((lp->phy_type & 0xfffffff0) == 0x0016f840) {
PRINTK(dev, "PHY LAN83C183 (LAN91C111 Internal)\n");
} else if ((lp->phy_type & 0xfffffff0) == 0x02821c50) {
PRINTK(dev, "PHY LAN83C180\n");
}
}
err_out:
#ifdef CONFIG_ARCH_PXA
if (retval && lp->dma_chan)
dma_release_channel(lp->dma_chan);
#endif
return retval;
}
static int smc_enable_device(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smc_local *lp = netdev_priv(ndev);
unsigned long flags;
unsigned char ecor, ecsr;
void __iomem *addr;
struct resource * res;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
if (!res)
return 0;
/*
* Map the attribute space. This is overkill, but clean.
*/
addr = ioremap(res->start, ATTRIB_SIZE);
if (!addr)
return -ENOMEM;
/*
* Reset the device. We must disable IRQs around this
* since a reset causes the IRQ line become active.
*/
local_irq_save(flags);
ecor = readb(addr + (ECOR << SMC_IO_SHIFT)) & ~ECOR_RESET;
writeb(ecor | ECOR_RESET, addr + (ECOR << SMC_IO_SHIFT));
readb(addr + (ECOR << SMC_IO_SHIFT));
/*
* Wait 100us for the chip to reset.
*/
udelay(100);
/*
* The device will ignore all writes to the enable bit while
* reset is asserted, even if the reset bit is cleared in the
* same write. Must clear reset first, then enable the device.
*/
writeb(ecor, addr + (ECOR << SMC_IO_SHIFT));
writeb(ecor | ECOR_ENABLE, addr + (ECOR << SMC_IO_SHIFT));
/*
* Set the appropriate byte/word mode.
*/
ecsr = readb(addr + (ECSR << SMC_IO_SHIFT)) & ~ECSR_IOIS8;
if (!SMC_16BIT(lp))
ecsr |= ECSR_IOIS8;
writeb(ecsr, addr + (ECSR << SMC_IO_SHIFT));
local_irq_restore(flags);
iounmap(addr);
/*
* Wait for the chip to wake up. We could poll the control
* register in the main register space, but that isn't mapped
* yet. We know this is going to take 750us.
*/
msleep(1);
return 0;
}
static int smc_request_attrib(struct platform_device *pdev,
struct net_device *ndev)
{
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
struct smc_local *lp __maybe_unused = netdev_priv(ndev);
if (!res)
return 0;
if (!request_mem_region(res->start, ATTRIB_SIZE, CARDNAME))
return -EBUSY;
return 0;
}
static void smc_release_attrib(struct platform_device *pdev,
struct net_device *ndev)
{
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
struct smc_local *lp __maybe_unused = netdev_priv(ndev);
if (res)
release_mem_region(res->start, ATTRIB_SIZE);
}
static inline void smc_request_datacs(struct platform_device *pdev, struct net_device *ndev)
{
if (SMC_CAN_USE_DATACS) {
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-data32");
struct smc_local *lp = netdev_priv(ndev);
if (!res)
return;
if(!request_mem_region(res->start, SMC_DATA_EXTENT, CARDNAME)) {
netdev_info(ndev, "%s: failed to request datacs memory region.\n",
CARDNAME);
return;
}
lp->datacs = ioremap(res->start, SMC_DATA_EXTENT);
}
}
static void smc_release_datacs(struct platform_device *pdev, struct net_device *ndev)
{
if (SMC_CAN_USE_DATACS) {
struct smc_local *lp = netdev_priv(ndev);
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-data32");
if (lp->datacs)
iounmap(lp->datacs);
lp->datacs = NULL;
if (res)
release_mem_region(res->start, SMC_DATA_EXTENT);
}
}
#if IS_BUILTIN(CONFIG_OF)
static const struct of_device_id smc91x_match[] = {
{ .compatible = "smsc,lan91c94", },
{ .compatible = "smsc,lan91c111", },
{},
};
MODULE_DEVICE_TABLE(of, smc91x_match);
/**
* of_try_set_control_gpio - configure a gpio if it exists
*/
static int try_toggle_control_gpio(struct device *dev,
struct gpio_desc **desc,
const char *name, int index,
int value, unsigned int nsdelay)
{
struct gpio_desc *gpio = *desc;
enum gpiod_flags flags = value ? GPIOD_OUT_LOW : GPIOD_OUT_HIGH;
gpio = devm_gpiod_get_index_optional(dev, name, index, flags);
if (IS_ERR(gpio))
return PTR_ERR(gpio);
if (gpio) {
if (nsdelay)
usleep_range(nsdelay, 2 * nsdelay);
gpiod_set_value_cansleep(gpio, value);
}
*desc = gpio;
return 0;
}
#endif
/*
* smc_init(void)
* Input parameters:
* dev->base_addr == 0, try to find all possible locations
* dev->base_addr > 0x1ff, this is the address to check
* dev->base_addr == <anything else>, return failure code
*
* Output:
* 0 --> there is a device
* anything else, error
*/
static int smc_drv_probe(struct platform_device *pdev)
{
struct smc91x_platdata *pd = dev_get_platdata(&pdev->dev);
const struct of_device_id *match = NULL;
struct smc_local *lp;
struct net_device *ndev;
struct resource *res;
unsigned int __iomem *addr;
unsigned long irq_flags = SMC_IRQ_FLAGS;
unsigned long irq_resflags;
int ret;
ndev = alloc_etherdev(sizeof(struct smc_local));
if (!ndev) {
ret = -ENOMEM;
goto out;
}
SET_NETDEV_DEV(ndev, &pdev->dev);
/* get configuration from platform data, only allow use of
* bus width if both SMC_CAN_USE_xxx and SMC91X_USE_xxx are set.
*/
lp = netdev_priv(ndev);
lp->cfg.flags = 0;
if (pd) {
memcpy(&lp->cfg, pd, sizeof(lp->cfg));
lp->io_shift = SMC91X_IO_SHIFT(lp->cfg.flags);
}
#if IS_BUILTIN(CONFIG_OF)
match = of_match_device(of_match_ptr(smc91x_match), &pdev->dev);
if (match) {
struct device_node *np = pdev->dev.of_node;
u32 val;
/* Optional pwrdwn GPIO configured? */
ret = try_toggle_control_gpio(&pdev->dev, &lp->power_gpio,
"power", 0, 0, 100);
if (ret)
return ret;
/*
* Optional reset GPIO configured? Minimum 100 ns reset needed
* according to LAN91C96 datasheet page 14.
*/
ret = try_toggle_control_gpio(&pdev->dev, &lp->reset_gpio,
"reset", 0, 0, 100);
if (ret)
return ret;
/*
* Need to wait for optional EEPROM to load, max 750 us according
* to LAN91C96 datasheet page 55.
*/
if (lp->reset_gpio)
usleep_range(750, 1000);
/* Combination of IO widths supported, default to 16-bit */
if (!of_property_read_u32(np, "reg-io-width", &val)) {
if (val & 1)
lp->cfg.flags |= SMC91X_USE_8BIT;
if ((val == 0) || (val & 2))
lp->cfg.flags |= SMC91X_USE_16BIT;
if (val & 4)
lp->cfg.flags |= SMC91X_USE_32BIT;
} else {
lp->cfg.flags |= SMC91X_USE_16BIT;
}
}
#endif
if (!pd && !match) {
lp->cfg.flags |= (SMC_CAN_USE_8BIT) ? SMC91X_USE_8BIT : 0;
lp->cfg.flags |= (SMC_CAN_USE_16BIT) ? SMC91X_USE_16BIT : 0;
lp->cfg.flags |= (SMC_CAN_USE_32BIT) ? SMC91X_USE_32BIT : 0;
lp->cfg.flags |= (nowait) ? SMC91X_NOWAIT : 0;
}
if (!lp->cfg.leda && !lp->cfg.ledb) {
lp->cfg.leda = RPC_LSA_DEFAULT;
lp->cfg.ledb = RPC_LSB_DEFAULT;
}
ndev->dma = (unsigned char)-1;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-regs");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto out_free_netdev;
}
if (!request_mem_region(res->start, SMC_IO_EXTENT, CARDNAME)) {
ret = -EBUSY;
goto out_free_netdev;
}
ndev->irq = platform_get_irq(pdev, 0);
if (ndev->irq < 0) {
ret = ndev->irq;
goto out_release_io;
}
/*
* If this platform does not specify any special irqflags, or if
* the resource supplies a trigger, override the irqflags with
* the trigger flags from the resource.
*/
irq_resflags = irqd_get_trigger_type(irq_get_irq_data(ndev->irq));
if (irq_flags == -1 || irq_resflags & IRQF_TRIGGER_MASK)
irq_flags = irq_resflags & IRQF_TRIGGER_MASK;
ret = smc_request_attrib(pdev, ndev);
if (ret)
goto out_release_io;
#if defined(CONFIG_ASSABET_NEPONSET)
if (machine_is_assabet() && machine_has_neponset())
neponset_ncr_set(NCR_ENET_OSC_EN);
#endif
platform_set_drvdata(pdev, ndev);
ret = smc_enable_device(pdev);
if (ret)
goto out_release_attrib;
addr = ioremap(res->start, SMC_IO_EXTENT);
if (!addr) {
ret = -ENOMEM;
goto out_release_attrib;
}
#ifdef CONFIG_ARCH_PXA
{
struct smc_local *lp = netdev_priv(ndev);
lp->device = &pdev->dev;
lp->physaddr = res->start;
}
#endif
ret = smc_probe(ndev, addr, irq_flags);
if (ret != 0)
goto out_iounmap;
smc_request_datacs(pdev, ndev);
return 0;
out_iounmap:
iounmap(addr);
out_release_attrib:
smc_release_attrib(pdev, ndev);
out_release_io:
release_mem_region(res->start, SMC_IO_EXTENT);
out_free_netdev:
free_netdev(ndev);
out:
pr_info("%s: not found (%d).\n", CARDNAME, ret);
return ret;
}
static int smc_drv_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smc_local *lp = netdev_priv(ndev);
struct resource *res;
unregister_netdev(ndev);
free_irq(ndev->irq, ndev);
#ifdef CONFIG_ARCH_PXA
if (lp->dma_chan)
dma_release_channel(lp->dma_chan);
#endif
iounmap(lp->base);
smc_release_datacs(pdev,ndev);
smc_release_attrib(pdev,ndev);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-regs");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, SMC_IO_EXTENT);
free_netdev(ndev);
return 0;
}
static int smc_drv_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
if (ndev) {
if (netif_running(ndev)) {
netif_device_detach(ndev);
smc_shutdown(ndev);
smc_phy_powerdown(ndev);
}
}
return 0;
}
static int smc_drv_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
if (ndev) {
struct smc_local *lp = netdev_priv(ndev);
smc_enable_device(pdev);
if (netif_running(ndev)) {
smc_reset(ndev);
smc_enable(ndev);
if (lp->phy_type != 0)
smc_phy_configure(&lp->phy_configure);
netif_device_attach(ndev);
}
}
return 0;
}
static struct dev_pm_ops smc_drv_pm_ops = {
.suspend = smc_drv_suspend,
.resume = smc_drv_resume,
};
static struct platform_driver smc_driver = {
.probe = smc_drv_probe,
.remove = smc_drv_remove,
.driver = {
.name = CARDNAME,
.pm = &smc_drv_pm_ops,
.of_match_table = of_match_ptr(smc91x_match),
},
};
module_platform_driver(smc_driver);
| bsd-2-clause |
bureau14/qdb-benchmark | thirdparty/boost/libs/serialization/test/test_check.cpp | 57 | 4561 | // (C) Copyright 2009 Robert Ramey
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version including documentation.
// note: this is a compile only test.
#include <sstream>
#include <boost/config.hpp> // BOOST_STATIC_CONST
#include <boost/serialization/static_warning.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
// track_selectivly with class information in the archive
// is unsafe when used with a pointer and should trigger a warning
struct check1 {
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
check1(){}
};
BOOST_CLASS_IMPLEMENTATION(check1, boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(check1, boost::serialization::track_selectively)
// the combination of versioning + no class information
// should trigger a warning
struct check2 {
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
check2(){}
};
BOOST_CLASS_IMPLEMENTATION(check2, boost::serialization::object_serializable)
BOOST_CLASS_VERSION(check2, 1)
// use track always to turn off warning tested above
BOOST_CLASS_TRACKING(check2, boost::serialization::track_always)
// serializing a type marked as "track_never" through a pointer
// is likely an error
struct check3 {
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
check3(){}
};
BOOST_CLASS_TRACKING(check3, boost::serialization::track_never)
template<class T>
int f(){
BOOST_STATIC_WARNING(T::value);
BOOST_STATIC_ASSERT(T::value);
return 0;
}
/////////////////////////////////////////////////////////////////////////
// compilation of this program should show a total of 10 warning messages
int main(int /* argc */, char * /* argv */[]){
std::stringstream s;
{
boost::archive::text_oarchive oa(s);
check1 const c1_out;
oa << c1_out;
check1 c1_non_const_out;
oa << c1_non_const_out; // warn check_object_tracking
check1 * const c1_ptr_out = 0;
oa << c1_ptr_out; // warn check_pointer_level
check2 const * c2_ptr_out;
oa << c2_ptr_out; // error check_object_versioning
check3 * const c3_ptr_out = 0;
oa << c3_ptr_out; // warning check_pointer_tracking
check2 const c2_out;
oa << c2_out; // error check_object_versioning
}
{
boost::archive::text_iarchive ia(s);
check1 const c1_in;
ia >> c1_in; // check_const_loading
check1 * c1_ptr_in = 0;
ia >> c1_ptr_in; // warn check_pointer_level
check2 * c2_ptr_in;
ia >> c2_ptr_in; // error check_object_versioning
check3 * c3_ptr_in = 0;
ia >> c3_ptr_in; // warning check_pointer_tracking
check2 c2_in;
ia >> c2_in; // error check_object_versioning
}
{
boost::archive::text_oarchive oa(s);
check1 const c1_out;
oa << BOOST_SERIALIZATION_NVP(c1_out);
check1 c1_non_const_out;
oa << BOOST_SERIALIZATION_NVP(c1_non_const_out); // warn check_object_tracking
check1 * const c1_ptr_out = 0;
oa << BOOST_SERIALIZATION_NVP(c1_ptr_out); // warn check_pointer_level
check2 const * c2_ptr_out;
oa << BOOST_SERIALIZATION_NVP(c2_ptr_out); // error check_object_versioning
check3 * const c3_ptr_out = 0;
oa << BOOST_SERIALIZATION_NVP(c3_ptr_out); // warning check_pointer_tracking
check2 const c2_out;
oa << BOOST_SERIALIZATION_NVP(c2_out); // error check_object_versioning
}
{
boost::archive::text_iarchive ia(s);
check1 const c1_in;
ia >> BOOST_SERIALIZATION_NVP(c1_in); // check_const_loading
check1 * c1_ptr_in = 0;
ia >> BOOST_SERIALIZATION_NVP(c1_ptr_in); // warn check_pointer_level
check2 * c2_ptr_in;
ia >> BOOST_SERIALIZATION_NVP(c2_ptr_in); // error check_object_versioning
check3 * c3_ptr_in = 0;
ia >> BOOST_SERIALIZATION_NVP(c3_ptr_in); // warning check_pointer_tracking
check2 c2_in;
ia >> BOOST_SERIALIZATION_NVP(c2_in); // error check_object_versioning
}
return 0;
}
| bsd-2-clause |
andrewjylee/omniplay | linux-lts-quantal-3.5.0/arch/arm/mach-msm/devices-msm7x00.c | 1354 | 9887 | /* linux/arch/arm/mach-msm/devices.c
*
* Copyright (C) 2008 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/clkdev.h>
#include <mach/irqs.h>
#include <mach/msm_iomap.h>
#include "devices.h"
#include <asm/mach/flash.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include "clock.h"
#include "clock-pcom.h"
#include <mach/mmc.h>
static struct resource resources_uart1[] = {
{
.start = INT_UART1,
.end = INT_UART1,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART1_PHYS,
.end = MSM_UART1_PHYS + MSM_UART1_SIZE - 1,
.flags = IORESOURCE_MEM,
.name = "uart_resource"
},
};
static struct resource resources_uart2[] = {
{
.start = INT_UART2,
.end = INT_UART2,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART2_PHYS,
.end = MSM_UART2_PHYS + MSM_UART2_SIZE - 1,
.flags = IORESOURCE_MEM,
.name = "uart_resource"
},
};
static struct resource resources_uart3[] = {
{
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART3_PHYS,
.end = MSM_UART3_PHYS + MSM_UART3_SIZE - 1,
.flags = IORESOURCE_MEM,
.name = "uart_resource"
},
};
struct platform_device msm_device_uart1 = {
.name = "msm_serial",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart1),
.resource = resources_uart1,
};
struct platform_device msm_device_uart2 = {
.name = "msm_serial",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart2),
.resource = resources_uart2,
};
struct platform_device msm_device_uart3 = {
.name = "msm_serial",
.id = 2,
.num_resources = ARRAY_SIZE(resources_uart3),
.resource = resources_uart3,
};
static struct resource resources_i2c[] = {
{
.start = MSM_I2C_PHYS,
.end = MSM_I2C_PHYS + MSM_I2C_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_PWB_I2C,
.end = INT_PWB_I2C,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_i2c = {
.name = "msm_i2c",
.id = 0,
.num_resources = ARRAY_SIZE(resources_i2c),
.resource = resources_i2c,
};
static struct resource resources_hsusb[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + MSM_HSUSB_SIZE,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_hsusb = {
.name = "msm_hsusb",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb),
.resource = resources_hsusb,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct flash_platform_data msm_nand_data = {
.parts = NULL,
.nr_parts = 0,
};
static struct resource resources_nand[] = {
[0] = {
.start = 7,
.end = 7,
.flags = IORESOURCE_DMA,
},
};
struct platform_device msm_device_nand = {
.name = "msm_nand",
.id = -1,
.num_resources = ARRAY_SIZE(resources_nand),
.resource = resources_nand,
.dev = {
.platform_data = &msm_nand_data,
},
};
struct platform_device msm_device_smd = {
.name = "msm_smd",
.id = -1,
};
static struct resource resources_sdc1[] = {
{
.start = MSM_SDC1_PHYS,
.end = MSM_SDC1_PHYS + MSM_SDC1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC1_0,
.end = INT_SDC1_0,
.flags = IORESOURCE_IRQ,
.name = "cmd_irq",
},
{
.flags = IORESOURCE_IRQ | IORESOURCE_DISABLED,
.name = "status_irq"
},
{
.start = 8,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
static struct resource resources_sdc2[] = {
{
.start = MSM_SDC2_PHYS,
.end = MSM_SDC2_PHYS + MSM_SDC2_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC2_0,
.end = INT_SDC2_0,
.flags = IORESOURCE_IRQ,
.name = "cmd_irq",
},
{
.flags = IORESOURCE_IRQ | IORESOURCE_DISABLED,
.name = "status_irq"
},
{
.start = 8,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
static struct resource resources_sdc3[] = {
{
.start = MSM_SDC3_PHYS,
.end = MSM_SDC3_PHYS + MSM_SDC3_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC3_0,
.end = INT_SDC3_0,
.flags = IORESOURCE_IRQ,
.name = "cmd_irq",
},
{
.flags = IORESOURCE_IRQ | IORESOURCE_DISABLED,
.name = "status_irq"
},
{
.start = 8,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
static struct resource resources_sdc4[] = {
{
.start = MSM_SDC4_PHYS,
.end = MSM_SDC4_PHYS + MSM_SDC4_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC4_0,
.end = INT_SDC4_0,
.flags = IORESOURCE_IRQ,
.name = "cmd_irq",
},
{
.flags = IORESOURCE_IRQ | IORESOURCE_DISABLED,
.name = "status_irq"
},
{
.start = 8,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
struct platform_device msm_device_sdc1 = {
.name = "msm_sdcc",
.id = 1,
.num_resources = ARRAY_SIZE(resources_sdc1),
.resource = resources_sdc1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc2 = {
.name = "msm_sdcc",
.id = 2,
.num_resources = ARRAY_SIZE(resources_sdc2),
.resource = resources_sdc2,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc3 = {
.name = "msm_sdcc",
.id = 3,
.num_resources = ARRAY_SIZE(resources_sdc3),
.resource = resources_sdc3,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc4 = {
.name = "msm_sdcc",
.id = 4,
.num_resources = ARRAY_SIZE(resources_sdc4),
.resource = resources_sdc4,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct platform_device *msm_sdcc_devices[] __initdata = {
&msm_device_sdc1,
&msm_device_sdc2,
&msm_device_sdc3,
&msm_device_sdc4,
};
int __init msm_add_sdcc(unsigned int controller,
struct msm_mmc_platform_data *plat,
unsigned int stat_irq, unsigned long stat_irq_flags)
{
struct platform_device *pdev;
struct resource *res;
if (controller < 1 || controller > 4)
return -EINVAL;
pdev = msm_sdcc_devices[controller-1];
pdev->dev.platform_data = plat;
res = platform_get_resource_byname(pdev, IORESOURCE_IRQ, "status_irq");
if (!res)
return -EINVAL;
else if (stat_irq) {
res->start = res->end = stat_irq;
res->flags &= ~IORESOURCE_DISABLED;
res->flags |= stat_irq_flags;
}
return platform_device_register(pdev);
}
static struct resource resources_mddi0[] = {
{
.start = MSM_PMDH_PHYS,
.end = MSM_PMDH_PHYS + MSM_PMDH_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_MDDI_PRI,
.end = INT_MDDI_PRI,
.flags = IORESOURCE_IRQ,
},
};
static struct resource resources_mddi1[] = {
{
.start = MSM_EMDH_PHYS,
.end = MSM_EMDH_PHYS + MSM_EMDH_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_MDDI_EXT,
.end = INT_MDDI_EXT,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_mddi0 = {
.name = "msm_mddi",
.id = 0,
.num_resources = ARRAY_SIZE(resources_mddi0),
.resource = resources_mddi0,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_mddi1 = {
.name = "msm_mddi",
.id = 1,
.num_resources = ARRAY_SIZE(resources_mddi1),
.resource = resources_mddi1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_mdp[] = {
{
.start = MSM_MDP_PHYS,
.end = MSM_MDP_PHYS + MSM_MDP_SIZE - 1,
.name = "mdp",
.flags = IORESOURCE_MEM
},
{
.start = INT_MDP,
.end = INT_MDP,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_mdp = {
.name = "msm_mdp",
.id = 0,
.num_resources = ARRAY_SIZE(resources_mdp),
.resource = resources_mdp,
};
struct clk_lookup msm_clocks_7x01a[] = {
CLK_PCOM("adm_clk", ADM_CLK, NULL, 0),
CLK_PCOM("adsp_clk", ADSP_CLK, NULL, 0),
CLK_PCOM("ebi1_clk", EBI1_CLK, NULL, 0),
CLK_PCOM("ebi2_clk", EBI2_CLK, NULL, 0),
CLK_PCOM("ecodec_clk", ECODEC_CLK, NULL, 0),
CLK_PCOM("emdh_clk", EMDH_CLK, NULL, OFF),
CLK_PCOM("gp_clk", GP_CLK, NULL, 0),
CLK_PCOM("grp_clk", GRP_3D_CLK, NULL, OFF),
CLK_PCOM("i2c_clk", I2C_CLK, "msm_i2c.0", 0),
CLK_PCOM("icodec_rx_clk", ICODEC_RX_CLK, NULL, 0),
CLK_PCOM("icodec_tx_clk", ICODEC_TX_CLK, NULL, 0),
CLK_PCOM("imem_clk", IMEM_CLK, NULL, OFF),
CLK_PCOM("mdc_clk", MDC_CLK, NULL, 0),
CLK_PCOM("mdp_clk", MDP_CLK, NULL, OFF),
CLK_PCOM("pbus_clk", PBUS_CLK, NULL, 0),
CLK_PCOM("pcm_clk", PCM_CLK, NULL, 0),
CLK_PCOM("mddi_clk", PMDH_CLK, NULL, OFF | CLK_MINMAX),
CLK_PCOM("sdac_clk", SDAC_CLK, NULL, OFF),
CLK_PCOM("sdc_clk", SDC1_CLK, "msm_sdcc.1", OFF),
CLK_PCOM("sdc_pclk", SDC1_P_CLK, "msm_sdcc.1", OFF),
CLK_PCOM("sdc_clk", SDC2_CLK, "msm_sdcc.2", OFF),
CLK_PCOM("sdc_pclk", SDC2_P_CLK, "msm_sdcc.2", OFF),
CLK_PCOM("sdc_clk", SDC3_CLK, "msm_sdcc.3", OFF),
CLK_PCOM("sdc_pclk", SDC3_P_CLK, "msm_sdcc.3", OFF),
CLK_PCOM("sdc_clk", SDC4_CLK, "msm_sdcc.4", OFF),
CLK_PCOM("sdc_pclk", SDC4_P_CLK, "msm_sdcc.4", OFF),
CLK_PCOM("tsif_clk", TSIF_CLK, NULL, 0),
CLK_PCOM("tsif_ref_clk", TSIF_REF_CLK, NULL, 0),
CLK_PCOM("tv_dac_clk", TV_DAC_CLK, NULL, 0),
CLK_PCOM("tv_enc_clk", TV_ENC_CLK, NULL, 0),
CLK_PCOM("uart_clk", UART1_CLK, "msm_serial.0", OFF),
CLK_PCOM("uart_clk", UART2_CLK, "msm_serial.1", 0),
CLK_PCOM("uart_clk", UART3_CLK, "msm_serial.2", OFF),
CLK_PCOM("uart1dm_clk", UART1DM_CLK, NULL, OFF),
CLK_PCOM("uart2dm_clk", UART2DM_CLK, NULL, 0),
CLK_PCOM("usb_hs_clk", USB_HS_CLK, "msm_hsusb", OFF),
CLK_PCOM("usb_hs_pclk", USB_HS_P_CLK, "msm_hsusb", OFF),
CLK_PCOM("usb_otg_clk", USB_OTG_CLK, NULL, 0),
CLK_PCOM("vdc_clk", VDC_CLK, NULL, OFF ),
CLK_PCOM("vfe_clk", VFE_CLK, NULL, OFF),
CLK_PCOM("vfe_mdc_clk", VFE_MDC_CLK, NULL, OFF),
};
unsigned msm_num_clocks_7x01a = ARRAY_SIZE(msm_clocks_7x01a);
| bsd-2-clause |
coverxiaoeye/nginx-openresty-windows | nginx/objs/lib_x64/openssl-1.0.1p/crypto/asn1/x_nx509.c | 187 | 3099 | /* x_nx509.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2005.
*/
/* ====================================================================
* Copyright (c) 2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stddef.h>
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
/* Old netscape certificate wrapper format */
ASN1_SEQUENCE(NETSCAPE_X509) = {
ASN1_SIMPLE(NETSCAPE_X509, header, ASN1_OCTET_STRING),
ASN1_OPT(NETSCAPE_X509, cert, X509)
} ASN1_SEQUENCE_END(NETSCAPE_X509)
IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_X509)
| bsd-2-clause |
rubenvb/skia | src/sksl/SkSLLexer.cpp | 1 | 86014 | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*****************************************************************************************
******************** This file was generated by sksllex. Do not edit. *******************
*****************************************************************************************/
#include "SkSLLexer.h"
namespace SkSL {
static const uint8_t INVALID_CHAR = 18;
static int8_t mappings[127] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 4, 3, 5, 6, 7, 8, 3, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26,
26, 26, 26, 27, 26, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 28, 6, 6, 6,
29, 6, 6, 30, 3, 31, 32, 33, 3, 34, 35, 36, 37, 38, 39, 6, 40, 41, 6, 42, 43, 44,
45, 46, 47, 6, 48, 49, 50, 51, 52, 53, 54, 55, 6, 56, 57, 58, 59};
static int16_t transitions[60][304] = {
{
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, 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, 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, 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, 0, 0, 0, 0,
},
{
0, 2, 3, 3, 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, 35, 35, 0, 38, 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, 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, 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, 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, 3, 3, 3, 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, 35, 35, 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, 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, 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, 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, 4, 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, 35, 35, 0, 38, 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, 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, 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, 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, 5, 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, 35, 35, 0, 38, 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, 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, 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, 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, 7, 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, 35, 35, 0, 38, 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, 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, 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, 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, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 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, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 11, 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, 35, 35, 0, 38, 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, 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, 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, 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, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 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, 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, 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, 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, 17, 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, 35, 35, 0, 38, 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, 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, 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, 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, 18, 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, 35, 35, 0, 38, 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, 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, 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, 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, 19, 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, 35, 36, 35, 0, 38, 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, 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, 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, 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, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0,
0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 35, 35, 0, 38, 0, 0, 0, 0, 44, 0, 0, 47, 0,
0, 0, 51, 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, 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, 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, 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, 24, 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, 35, 35, 0, 38, 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, 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, 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, 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, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 26, 0, 0, 0, 0, 0, 32, 0, 0, 0, 35, 35, 0, 38, 0, 0, 0, 0, 44, 0, 0, 47, 0,
0, 0, 51, 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, 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, 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, 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, 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, 35, 35, 0, 38, 0, 41, 0, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0,
0, 0, 0, 41, 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, 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, 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, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 34, 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, 38, 35, 37, 0, 38, 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, 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, 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, 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, 40, 0, 0, 0, 0, 0, 0, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 33, 33, 33, 0, 35, 35, 0, 38, 0, 49, 42,
42, 45, 45, 45, 48, 48, 48, 49, 52, 52, 52, 54, 54, 49, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 55, 0, 0, 0, 0, 0, 0, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 33, 33, 33, 0, 35, 35, 0, 38, 0, 49, 42,
42, 45, 45, 45, 48, 48, 48, 49, 52, 52, 52, 54, 54, 49, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 56, 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, 35, 35, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 57, 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, 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, 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, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 58, 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, 35, 35, 0, 38, 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, 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, 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, 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, 59, 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, 35, 35, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 60, 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, 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, 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, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 63, 0, 0, 0, 6, 0, 0, 0, 0, 0, 12, 0, 16, 15, 0, 0, 0, 0, 20, 0, 23, 0, 0,
0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 39, 35, 35, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 61, 0, 0, 64, 0, 66, 0, 68, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 0, 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, 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, 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, 299, 0, 301, 0, 0, 0,
},
{
0, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28,
0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 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, 67, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 69, 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, 35, 35, 0, 38, 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, 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, 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, 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, 70, 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, 35, 35, 0, 38, 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, 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, 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, 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, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 35, 35, 0,
38, 0, 50, 46, 43, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 54, 54, 50, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 99, 10, 10, 10, 10, 10, 105, 10, 10, 10, 10, 10, 111, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 101, 10, 10, 10, 10, 10, 107, 10, 10, 10, 10, 10, 113, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 100, 10, 10, 10, 10, 10, 106, 10, 10, 10, 10, 10, 112, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 80, 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, 35, 35, 0, 38, 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, 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, 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, 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, 81, 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, 35, 35, 0, 38, 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, 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, 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, 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, 82, 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, 35, 35, 0, 38, 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, 84, 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, 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, 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, 86, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 87, 10, 10, 10, 10, 10, 93, 10, 10,
10, 10, 10, 102, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 238, 10, 10, 10, 242, 10, 10, 10, 10, 247,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 97, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 117, 10, 10, 10, 10, 10, 10, 10, 125, 10, 10, 10, 129, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 150, 10, 10,
10, 10, 10, 10, 157, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 169, 10, 10,
10, 10, 174, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 185, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 220, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 240, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 279, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 114, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 124, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71,
71, 78, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
96, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 156, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 198, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 212, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 230, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 252, 10, 10, 10, 10, 10, 258, 10, 10, 10, 10, 263, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 147, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 159, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 221, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 245, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 161, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 35,
35, 0, 38, 0, 50, 46, 43, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 54,
54, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71,
71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10,
91, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 116, 10, 10, 10, 10, 10, 122, 10, 10, 10, 10,
127, 10, 10, 10, 10, 10, 10, 134, 10, 136, 10, 10, 10, 10, 10, 10, 10, 10,
10, 146, 10, 148, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 164, 10, 10, 10, 10, 10, 10, 10, 172, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 193, 10, 10, 10, 197, 10,
10, 10, 10, 202, 10, 10, 10, 10, 10, 10, 10, 10, 211, 10, 10, 10, 10, 10,
10, 10, 219, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 246, 10, 248, 10, 10, 251, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 268, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 283, 10, 10, 10, 10, 288,
10, 10, 10, 292, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 168, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 54, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 71, 73, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 120, 121, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 149, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 179, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 249, 250, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 272, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 79, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 133,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 239, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 264, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 285,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 178, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35,
35, 0, 38, 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, 72, 71,
71, 71, 71, 76, 71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 89, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 103, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 143, 10,
10, 10, 10, 154, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 200, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 213, 10, 215, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 229, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 244, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 261, 10, 10, 10, 10, 10, 10, 10, 10, 10,
271, 10, 10, 10, 10, 10, 10, 10, 10, 10, 281, 10, 10, 10, 10, 286, 10, 10,
10, 290, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 118, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 237, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 184, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35,
35, 0, 38, 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, 71, 71,
71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10,
10, 92, 10, 94, 10, 10, 10, 98, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 128, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 152, 10, 10, 10, 10, 10, 10, 10, 10, 10, 162,
10, 10, 10, 10, 10, 10, 173, 170, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 204, 205, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 224, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 278, 10, 10, 10, 282, 10, 10, 10, 10, 287, 10,
10, 10, 10, 10, 10, 10, 295, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 167, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 275, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 190, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 104, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 139,
10, 10, 10, 137, 10, 10, 10, 10, 10, 10, 144, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 165, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 180, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 217, 10, 10, 10, 10, 10, 223, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 235, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 270, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 294, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 206, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35,
35, 0, 38, 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, 71, 71,
71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10,
10, 10, 10, 10, 95, 10, 10, 10, 10, 10, 10, 10, 108, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 132, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 160, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 176, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
181, 10, 10, 10, 10, 10, 187, 10, 10, 10, 191, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 216,
10, 10, 10, 10, 10, 222, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 273, 10, 10, 10, 277, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 293, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 209, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 88, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 192, 10, 10, 10, 196, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 218, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
115, 10, 10, 10, 10, 10, 10, 10, 123, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 135, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 158, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 177, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 194, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
210, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 228,
10, 10, 10, 10, 10, 234, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 256, 10, 10, 10, 10, 10, 10, 10, 10, 10, 266,
10, 10, 10, 10, 10, 10, 10, 274, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 289,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 236, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35,
35, 0, 38, 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, 74, 71,
71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 126,
10, 10, 10, 130, 131, 10, 10, 10, 10, 10, 10, 10, 10, 140, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 155, 10, 10, 10, 10, 10, 10, 10,
163, 10, 10, 10, 10, 10, 10, 10, 171, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 195, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 214, 10, 10,
10, 10, 10, 226, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 241, 10, 243, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 254, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 265, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35,
35, 0, 38, 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, 71, 71,
71, 71, 71, 71, 77, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 110, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 138, 10, 142, 141, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 153, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 175, 10, 10, 10, 10, 10,
10, 10, 183, 10, 10, 10, 10, 10, 189, 10, 10, 10, 10, 10, 10, 10, 10, 10,
199, 10, 10, 10, 10, 10, 10, 10, 10, 208, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 232, 10, 10, 10, 10, 10, 10, 227, 10, 10, 10, 231, 10, 10, 10,
10, 10, 255, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
253, 10, 10, 10, 10, 10, 259, 10, 10, 262, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 280, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 291, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 269, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 109, 10, 10, 10, 10, 10,
119, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 145, 10, 10, 10, 10, 10, 151, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 166, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 182, 10, 10, 10, 10, 10, 188, 10, 10,
203, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 207, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 233, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 257, 10, 10, 10, 10, 10, 10, 10, 10, 10,
267, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 276, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 201, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 284, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 75, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 260, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0, 38, 0, 53, 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, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 0, 0, 0, 0,
0, 0, 10, 10, 10, 90, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 9, 0, 0, 0, 0, 0, 8, 8, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 0,
38, 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, 71, 71, 71, 71, 71, 71,
71, 71, 71, 71, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 186, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 225, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 296, 10, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 297, 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, 35, 35, 0, 38, 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, 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, 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, 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, 298, 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, 35, 35, 0, 38, 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, 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, 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, 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, 300, 0, 0, 0, 0, 0,
},
{
0, 302, 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, 35, 35, 0, 38, 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, 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, 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, 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, 303, 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, 35, 35, 0, 38, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
};
static int8_t accepts[304] = {
-1, -1, 95, 95, 98, 69, 75, 98, 43, 42, 42, 59, 84, 64, 68, 92, 89, 45, 46, 57, 82, 55,
53, 80, 52, 56, 54, 81, 94, 51, 1, -1, -1, 1, 58, -1, -1, 97, 96, 83, 2, 1, 1, -1,
-1, 1, -1, -1, 1, 2, -1, -1, 1, -1, 2, 2, 72, 71, 93, 77, 60, 85, 79, 73, 74, 76,
78, 61, 86, 70, 98, 44, 44, 6, 44, 44, 44, 44, 44, 12, 49, 50, 63, 88, 67, 91, 42, 42,
42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 34, 42, 42, 42, 42, 42, 35, 42, 42,
42, 42, 42, 36, 42, 42, 42, 42, 15, 42, 42, 42, 42, 32, 42, 42, 42, 13, 42, 42, 42, 41,
42, 42, 42, 42, 42, 42, 29, 42, 42, 24, 42, 42, 42, 42, 16, 42, 42, 42, 42, 42, 42, 14,
42, 42, 42, 42, 42, 17, 10, 42, 42, 42, 7, 42, 42, 40, 42, 42, 42, 42, 4, 42, 42, 25,
42, 8, 42, 5, 20, 42, 42, 22, 42, 42, 42, 42, 42, 38, 42, 42, 42, 42, 42, 42, 42, 42,
42, 42, 42, 42, 26, 42, 42, 19, 42, 42, 21, 42, 42, 42, 42, 42, 42, 42, 42, 39, 42, 42,
42, 42, 42, 42, 42, 27, 42, 42, 42, 42, 42, 31, 42, 42, 42, 18, 42, 42, 42, 42, 42, 42,
42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 33, 42, 42, 42, 42, 37, 42, 42, 42, 42,
11, 42, 42, 42, 3, 42, 42, 42, 42, 42, 42, 23, 42, 42, 42, 42, 42, 42, 42, 30, 42, 42,
42, 42, 9, 42, 42, 42, 42, 42, 42, 42, 28, 47, 62, 87, 66, 90, 48, 65,
};
Token Lexer::next() {
// note that we cheat here: normally a lexer needs to worry about the case
// where a token has a prefix which is not itself a valid token - for instance,
// maybe we have a valid token 'while', but 'w', 'wh', etc. are not valid
// tokens. Our grammar doesn't have this property, so we can simplify the logic
// a bit.
int32_t startOffset = fOffset;
if (startOffset == fLength) {
return Token(Token::END_OF_FILE, startOffset, 0);
}
int16_t state = 1;
for (;;) {
if (fOffset >= fLength) {
if (accepts[state] == -1) {
return Token(Token::END_OF_FILE, startOffset, 0);
}
break;
}
uint8_t c = (uint8_t)fText[fOffset];
if (c <= 8 || c >= 127) {
c = INVALID_CHAR;
}
int16_t newState = transitions[mappings[c]][state];
if (!newState) {
break;
}
state = newState;
++fOffset;
}
Token::Kind kind = (Token::Kind)accepts[state];
return Token(kind, startOffset, fOffset - startOffset);
}
} // namespace SkSL
| bsd-3-clause |
pridolfi/uPOSIX | external/target/lpc1769/lpc_chip_175x_6x/src/clock_17xx_40xx.c | 1 | 13827 | /*
* @brief LPC17xx/40xx System and Control driver
*
* @note
* Copyright(C) NXP Semiconductors, 2014
* All rights reserved.
*
* @par
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licensor disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* @par
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#include "chip.h"
/*****************************************************************************
* Private types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Public types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Private functions
****************************************************************************/
/*****************************************************************************
* Public functions
****************************************************************************/
/* Enables or connects a PLL */
void Chip_Clock_EnablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags) {
uint32_t temp;
temp = LPC_SYSCTL->PLL[PLLNum].PLLCON;
temp |= flags;
LPC_SYSCTL->PLL[PLLNum].PLLCON = temp;
Chip_Clock_FeedPLL(PLLNum);
}
/* Disables or disconnects a PLL */
void Chip_Clock_DisablePLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t flags) {
uint32_t temp;
temp = LPC_SYSCTL->PLL[PLLNum].PLLCON;
temp &= ~flags;
LPC_SYSCTL->PLL[PLLNum].PLLCON = temp;
Chip_Clock_FeedPLL(PLLNum);
}
/* Sets up a PLL */
void Chip_Clock_SetupPLL(CHIP_SYSCTL_PLL_T PLLNum, uint32_t msel, uint32_t psel) {
uint32_t PLLcfg;
#if defined(CHIP_LPC175X_6X)
/* PLL0 and PLL1 are slightly different */
if (PLLNum == SYSCTL_MAIN_PLL) {
PLLcfg = (msel) | (psel << 16);
}
else {
PLLcfg = (msel) | (psel << 5);
}
#else
PLLcfg = (msel) | (psel << 5);
#endif
LPC_SYSCTL->PLL[PLLNum].PLLCFG = PLLcfg;
LPC_SYSCTL->PLL[PLLNum].PLLCON = 0x1;
Chip_Clock_FeedPLL(PLLNum);
}
/* Enables power and clocking for a peripheral */
void Chip_Clock_EnablePeriphClock(CHIP_SYSCTL_CLOCK_T clk) {
uint32_t bs = (uint32_t) clk;
#if defined(CHIP_LPC40XX)
if (bs >= 32) {
LPC_SYSCTL->PCONP1 |= (1 << (bs - 32));
}
else {
LPC_SYSCTL->PCONP |= (1 << bs);
}
#else
LPC_SYSCTL->PCONP |= (1 << bs);
#endif
}
/* Disables power and clocking for a peripheral */
void Chip_Clock_DisablePeriphClock(CHIP_SYSCTL_CLOCK_T clk) {
uint32_t bs = (uint32_t) clk;
#if defined(CHIP_LPC40XX)
if (bs >= 32) {
LPC_SYSCTL->PCONP1 &= ~(1 << (bs - 32));
}
else {
LPC_SYSCTL->PCONP |= ~(1 << bs);
}
#else
LPC_SYSCTL->PCONP |= ~(1 << bs);
#endif
}
/* Returns power enables state for a peripheral */
bool Chip_Clock_IsPeripheralClockEnabled(CHIP_SYSCTL_CLOCK_T clk)
{
uint32_t bs = (uint32_t) clk;
#if defined(CHIP_LPC40XX)
if (bs >= 32) {
bs = LPC_SYSCTL->PCONP1 & (1 << (bs - 32));
}
else {
bs = LPC_SYSCTL->PCONP & (1 << bs);
}
#else
bs = LPC_SYSCTL->PCONP & (1 << bs);
#endif
return (bool) (bs != 0);
}
/* Sets the current CPU clock source */
void Chip_Clock_SetCPUClockSource(CHIP_SYSCTL_CCLKSRC_T src)
{
#if defined(CHIP_LPC175X_6X)
/* LPC175x/6x CPU clock source is based on PLL connect status */
if (src == SYSCTL_CCLKSRC_MAINPLL) {
/* Connect PLL0 */
Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT);
}
else {
Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT);
}
#else
/* LPC177x/8x and 407x/8x CPU clock source is based on CCLKSEL */
if (src == SYSCTL_CCLKSRC_MAINPLL) {
/* Connect PLL0 */
LPC_SYSCTL->CCLKSEL |= (1 << 8);
}
else {
LPC_SYSCTL->CCLKSEL &= ~(1 << 8);
}
#endif
}
/* Returns the current CPU clock source */
CHIP_SYSCTL_CCLKSRC_T Chip_Clock_GetCPUClockSource(void)
{
CHIP_SYSCTL_CCLKSRC_T src;
#if defined(CHIP_LPC175X_6X)
/* LPC175x/6x CPU clock source is based on PLL connect status */
if (Chip_Clock_IsMainPLLConnected()) {
src = SYSCTL_CCLKSRC_MAINPLL;
}
else {
src = SYSCTL_CCLKSRC_SYSCLK;
}
#else
/* LPC177x/8x and 407x/8x CPU clock source is based on CCLKSEL */
if (LPC_SYSCTL->CCLKSEL & (1 << 8)) {
src = SYSCTL_CCLKSRC_MAINPLL;
}
else {
src = SYSCTL_CCLKSRC_SYSCLK;
}
#endif
return src;
}
/* Selects the CPU clock divider */
void Chip_Clock_SetCPUClockDiv(uint32_t div)
{
#if defined(CHIP_LPC175X_6X)
LPC_SYSCTL->CCLKSEL = div;
#else
uint32_t temp;
/* Save state of CPU clock source bit */
temp = LPC_SYSCTL->CCLKSEL & (1 << 8);
LPC_SYSCTL->CCLKSEL = temp | div;
#endif
}
/* Gets the CPU clock divider */
uint32_t Chip_Clock_GetCPUClockDiv(void)
{
#if defined(CHIP_LPC175X_6X)
return (LPC_SYSCTL->CCLKSEL & 0xFF) + 1;
#else
return LPC_SYSCTL->CCLKSEL & 0x1F;
#endif
}
#if !defined(CHIP_LPC175X_6X)
/* Selects the USB clock divider source */
void Chip_Clock_SetUSBClockSource(CHIP_SYSCTL_USBCLKSRC_T src)
{
uint32_t temp;
/* Mask out current source, but keep divider */
temp = LPC_SYSCTL->USBCLKSEL & ~(0x3 << 8);
LPC_SYSCTL->USBCLKSEL = temp | (((uint32_t) src) << 8);
}
#endif
/* Sets the USB clock divider */
void Chip_Clock_SetUSBClockDiv(uint32_t div)
{
uint32_t temp;
/* Mask out current divider */
#if defined(CHIP_LPC175X_6X)
temp = LPC_SYSCTL->USBCLKSEL & ~(0xF);
#else
temp = LPC_SYSCTL->USBCLKSEL & ~(0x1F);
#endif
LPC_SYSCTL->USBCLKSEL = temp | div;
}
/* Gets the USB clock divider */
uint32_t Chip_Clock_GetUSBClockDiv(void)
{
#if defined(CHIP_LPC175X_6X)
return (LPC_SYSCTL->USBCLKSEL & 0xF) + 1;
#else
return (LPC_SYSCTL->USBCLKSEL & 0x1F) + 1;
#endif
}
#if defined(CHIP_LPC175X_6X)
/* Selects a clock divider for a peripheral */
void Chip_Clock_SetPCLKDiv(CHIP_SYSCTL_PCLK_T clk, CHIP_SYSCTL_CLKDIV_T div)
{
uint32_t temp, bitIndex, regIndex = (uint32_t) clk;
/* Get register array index and clock index into the register */
bitIndex = ((regIndex % 16) * 2);
regIndex = regIndex / 16;
/* Mask and update register */
temp = LPC_SYSCTL->PCLKSEL[regIndex] & ~(0x3 << bitIndex);
temp |= (((uint32_t) div) << bitIndex);
LPC_SYSCTL->PCLKSEL[regIndex] = temp;
}
/* Gets a clock divider for a peripheral */
uint32_t Chip_Clock_GetPCLKDiv(CHIP_SYSCTL_PCLK_T clk)
{
uint32_t div = 1, bitIndex, regIndex = ((uint32_t) clk) * 2;
/* Get register array index and clock index into the register */
bitIndex = regIndex % 32;
regIndex = regIndex / 32;
/* Mask and update register */
div = LPC_SYSCTL->PCLKSEL[regIndex];
div = (div >> bitIndex) & 0x3;
if (div == SYSCTL_CLKDIV_4) {
div = 4;
}
else if (div == SYSCTL_CLKDIV_1) {
div = 1;
}
else if (div == SYSCTL_CLKDIV_2) {
div = 2;
}
else {
/* Special case for CAN clock divider */
if ((clk == SYSCTL_PCLK_CAN1) || (clk == SYSCTL_PCLK_CAN2) || (clk == SYSCTL_PCLK_ACF)) {
div = 6;
}
else {
div = 8;
}
}
return div;
}
#endif
/* Selects a source clock and divider rate for the CLKOUT pin */
void Chip_Clock_SetCLKOUTSource(CHIP_SYSCTL_CLKOUTSRC_T src,
uint32_t div)
{
uint32_t temp;
temp = LPC_SYSCTL->CLKOUTCFG & ~0x1FF;
temp |= ((uint32_t) src) | ((div - 1) << 4);
LPC_SYSCTL->CLKOUTCFG = temp;
}
/* Returns the current SYSCLK clock rate */
uint32_t Chip_Clock_GetSYSCLKRate(void)
{
/* Determine clock input rate to SYSCLK based on input selection */
switch (Chip_Clock_GetMainPLLSource()) {
case (uint32_t) SYSCTL_PLLCLKSRC_IRC:
return Chip_Clock_GetIntOscRate();
case (uint32_t) SYSCTL_PLLCLKSRC_MAINOSC:
return Chip_Clock_GetMainOscRate();
#if defined(CHIP_LPC175X_6X)
case (uint32_t) SYSCTL_PLLCLKSRC_RTC:
return Chip_Clock_GetRTCOscRate();
#endif
case SYSCTL_PLLCLKSRC_RESERVED2: /* only to avoid warning */
break;
}
return 0;
}
/* Returns the main PLL output clock rate */
uint32_t Chip_Clock_GetMainPLLOutClockRate(void)
{
uint32_t clkhr = 0;
#if defined(CHIP_LPC175X_6X)
/* Only valid if enabled */
if (Chip_Clock_IsMainPLLEnabled()) {
uint32_t msel, nsel;
/* PLL0 rate is (FIN * 2 * MSEL) / NSEL, get MSEL and NSEL */
msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG & 0x7FFF);
nsel = 1 + ((LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG >> 16) & 0xFF);
clkhr = (Chip_Clock_GetMainPLLInClockRate() * 2 * msel) / nsel;
}
#else
if (Chip_Clock_IsMainPLLEnabled()) {
uint32_t msel;
/* PLL0 rate is (FIN * MSEL) */
msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_MAIN_PLL].PLLCFG & 0x1F);
clkhr = (Chip_Clock_GetMainPLLInClockRate() * msel);
}
#endif
return (uint32_t) clkhr;
}
/* Get USB output clock rate */
uint32_t Chip_Clock_GetUSBPLLOutClockRate(void)
{
uint32_t clkhr = 0;
/* Only valid if enabled */
if (Chip_Clock_IsUSBPLLEnabled()) {
uint32_t msel;
/* PLL1 input clock (FIN) is always main oscillator */
/* PLL1 rate is (FIN * MSEL) */
msel = 1 + (LPC_SYSCTL->PLL[SYSCTL_USB_PLL].PLLCFG & 0x1F);
clkhr = (Chip_Clock_GetUSBPLLInClockRate() * msel);
}
return (uint32_t) clkhr;
}
/* Get the main clock rate */
/* On 175x/6x devices, this is the input clock to the CPU divider.
Additionally, on 177x/8x and 407x/8x devices, this is also the
input clock to the peripheral divider. */
uint32_t Chip_Clock_GetMainClockRate(void)
{
switch (Chip_Clock_GetCPUClockSource()) {
case SYSCTL_CCLKSRC_MAINPLL:
return Chip_Clock_GetMainPLLOutClockRate();
case SYSCTL_CCLKSRC_SYSCLK:
return Chip_Clock_GetSYSCLKRate();
default:
return 0;
}
}
/* Get CCLK rate */
uint32_t Chip_Clock_GetSystemClockRate(void)
{
return Chip_Clock_GetMainClockRate() / Chip_Clock_GetCPUClockDiv();
}
/* Returns the USB clock (USB_CLK) rate */
uint32_t Chip_Clock_GetUSBClockRate(void)
{
uint32_t div, clkrate;
#if defined(CHIP_LPC175X_6X)
/* The USB clock rate is derived from PLL1 or PLL0 */
if (Chip_Clock_IsUSBPLLConnected()) {
/* Use PLL1 clock for USB source with divider of 1 */
clkrate = Chip_Clock_GetUSBPLLOutClockRate();
div = 1;
}
else {
clkrate = Chip_Clock_GetMainClockRate();
div = Chip_Clock_GetUSBClockDiv();
}
#else
/* Get clock from source drving USB */
switch (Chip_Clock_GetUSBClockSource()) {
case SYSCTL_USBCLKSRC_SYSCLK:
default:
clkrate = Chip_Clock_GetSYSCLKRate();
break;
case SYSCTL_USBCLKSRC_MAINPLL:
clkrate = Chip_Clock_GetMainPLLOutClockRate();
break;
case SYSCTL_USBCLKSRC_USBPLL:
clkrate = Chip_Clock_GetUSBPLLOutClockRate();
break;
}
div = Chip_Clock_GetUSBClockDiv();
#endif
return clkrate / div;
}
#if !defined(CHIP_LPC175X_6X)
/* Selects the SPIFI clock divider source */
void Chip_Clock_SetSPIFIClockSource(CHIP_SYSCTL_SPIFICLKSRC_T src)
{
uint32_t temp;
/* Mask out current source, but keep divider */
temp = LPC_SYSCTL->SPIFICLKSEL & ~(0x3 << 8);
LPC_SYSCTL->SPIFICLKSEL = temp | (((uint32_t) src) << 8);
}
/* Sets the SPIFI clock divider */
void Chip_Clock_SetSPIFIClockDiv(uint32_t div)
{
uint32_t temp;
/* Mask out current divider */
temp = LPC_SYSCTL->SPIFICLKSEL & ~(0x1F);
LPC_SYSCTL->SPIFICLKSEL = temp | div;
}
/* Returns the SPIFI clock rate */
uint32_t Chip_Clock_GetSPIFIClockRate(void)
{
uint32_t div, clkrate;
/* Get clock from source drving USB */
switch (Chip_Clock_GetSPIFIClockSource()) {
case SYSCTL_SPIFICLKSRC_SYSCLK:
default:
clkrate = Chip_Clock_GetSYSCLKRate();
break;
case SYSCTL_SPIFICLKSRC_MAINPLL:
clkrate = Chip_Clock_GetMainPLLOutClockRate();
break;
case SYSCTL_SPIFICLKSRC_USBPLL:
clkrate = Chip_Clock_GetUSBPLLOutClockRate();
break;
}
div = Chip_Clock_GetSPIFIClockDiv();
return clkrate / div;
}
#endif
#if defined(CHIP_LPC175X_6X)
/* Returns the clock rate for a peripheral */
uint32_t Chip_Clock_GetPeripheralClockRate(CHIP_SYSCTL_PCLK_T clk) {
/* 175x/6x clock is derived from CPU clock with CPU divider */
return Chip_Clock_GetSystemClockRate() / Chip_Clock_GetPCLKDiv(clk);
}
#else
/* Returns the clock rate for all peripherals */
uint32_t Chip_Clock_GetPeripheralClockRate(void)
{
uint32_t clkrate = 0, div;
/* Get divider, a divider of 0 means the clock is disabled */
div = Chip_Clock_GetPCLKDiv();
if (div != 0) {
/* Derived from periperhal clock input and peripheral clock divider */
clkrate = Chip_Clock_GetMainClockRate() / div;
}
return clkrate;
}
#endif
| bsd-3-clause |
kylelutz/chemkit | tests/auto/plugins/gasteiger/gasteigertest.cpp | 1 | 6115 | /******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE 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 "gasteigertest.h"
#include <boost/range/algorithm.hpp>
#include <chemkit/molecule.h>
#include <chemkit/partialchargemodel.h>
void GasteigerTest::initTestCase()
{
// verify that the gasteiger plugin registered itself correctly
QVERIFY(boost::count(chemkit::PartialChargeModel::models(), "gasteiger") == 1);
}
void GasteigerTest::name()
{
chemkit::PartialChargeModel *model = chemkit::PartialChargeModel::create("gasteiger");
QVERIFY(model != 0);
QCOMPARE(model->name(), std::string("gasteiger"));
delete model;
}
void GasteigerTest::methane()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *H2 = molecule.addAtom("H");
chemkit::Atom *H3 = molecule.addAtom("H");
chemkit::Atom *H4 = molecule.addAtom("H");
chemkit::Atom *H5 = molecule.addAtom("H");
molecule.addBond(C1, H2);
molecule.addBond(C1, H3);
molecule.addBond(C1, H4);
molecule.addBond(C1, H5);
QCOMPARE(molecule.formula(), std::string("CH4"));
chemkit::PartialChargeModel *model = chemkit::PartialChargeModel::create("gasteiger");
QVERIFY(model != 0);
model->setMolecule(&molecule);
QCOMPARE(qRound(model->partialCharge(C1) * 1e3), -78);
delete model;
}
void GasteigerTest::fluoromethane()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *F2 = molecule.addAtom("F");
chemkit::Atom *H3 = molecule.addAtom("H");
chemkit::Atom *H4 = molecule.addAtom("H");
chemkit::Atom *H5 = molecule.addAtom("H");
molecule.addBond(C1, F2);
molecule.addBond(C1, H3);
molecule.addBond(C1, H4);
molecule.addBond(C1, H5);
QCOMPARE(molecule.formula(), std::string("CH3F"));
chemkit::PartialChargeModel *model = chemkit::PartialChargeModel::create("gasteiger");
QVERIFY(model != 0);
model->setMolecule(&molecule);
QCOMPARE(qRound(model->partialCharge(C1) * 1e3), 79);
QCOMPARE(qRound(model->partialCharge(F2) * 1e3), -253);
QCOMPARE(qRound(model->partialCharge(H3) * 1e3), 58);
QCOMPARE(qRound(model->partialCharge(H4) * 1e3), 58);
QCOMPARE(qRound(model->partialCharge(H5) * 1e3), 58);
delete model;
}
void GasteigerTest::ethane()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *H2 = molecule.addAtom("H");
chemkit::Atom *H3 = molecule.addAtom("H");
chemkit::Atom *H4 = molecule.addAtom("H");
chemkit::Atom *C5 = molecule.addAtom("C");
chemkit::Atom *H6 = molecule.addAtom("H");
chemkit::Atom *H7 = molecule.addAtom("H");
chemkit::Atom *H8 = molecule.addAtom("H");
molecule.addBond(C1, H2);
molecule.addBond(C1, H3);
molecule.addBond(C1, H4);
molecule.addBond(C1, C5);
molecule.addBond(C5, H6);
molecule.addBond(C5, H7);
molecule.addBond(C5, H8);
QCOMPARE(molecule.formula(), std::string("C2H6"));
chemkit::PartialChargeModel *model = chemkit::PartialChargeModel::create("gasteiger");
QVERIFY(model != 0);
model->setMolecule(&molecule);
QCOMPARE(qRound(model->partialCharge(C1) * 1e3), -68);
QCOMPARE(qRound(model->partialCharge(C5) * 1e3), -68);
delete model;
}
void GasteigerTest::fluoroethane()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *H2 = molecule.addAtom("H");
chemkit::Atom *H3 = molecule.addAtom("H");
chemkit::Atom *H4 = molecule.addAtom("H");
chemkit::Atom *C5 = molecule.addAtom("C");
chemkit::Atom *F6 = molecule.addAtom("F");
chemkit::Atom *H7 = molecule.addAtom("H");
chemkit::Atom *H8 = molecule.addAtom("H");
molecule.addBond(C1, H2);
molecule.addBond(C1, H3);
molecule.addBond(C1, H4);
molecule.addBond(C1, C5);
molecule.addBond(C5, F6);
molecule.addBond(C5, H7);
molecule.addBond(C5, H8);
QCOMPARE(molecule.formula(), std::string("C2H5F"));
chemkit::PartialChargeModel *model = chemkit::PartialChargeModel::create("gasteiger");
QVERIFY(model != 0);
model->setMolecule(&molecule);
QCOMPARE(qRound(model->partialCharge(C1) * 1e3), -37);
QCOMPARE(qRound(model->partialCharge(C5) * 1e3), 87);
delete model;
}
QTEST_APPLESS_MAIN(GasteigerTest)
| bsd-3-clause |
teoliphant/numpy-refactor | numpy/core/blasdot/_dotblas.c | 1 | 44301 | static char module_doc[] = "This module provides a BLAS \
optimized\nmatrix multiply, inner product and dot for numpy arrays";
#include "Python.h"
#include "npy_api.h"
#include "npy_descriptor.h"
#include "numpy/ndarrayobject.h"
#include "numpy/ndarraytypes.h"
#ifndef CBLAS_HEADER
#define CBLAS_HEADER "cblas.h"
#endif
#include CBLAS_HEADER
#include <stdio.h>
#if (PY_VERSION_HEX < 0x02060000)
#define Py_TYPE(o) (((PyObject*)(o))->ob_type)
#define Py_REFCNT(o) (((PyObject*)(o))->ob_refcnt)
#define Py_SIZE(o) (((PyVarObject*)(o))->ob_size)
#endif
static PyArray_DotFunc *oldFunctions[PyArray_NTYPES];
static void
FLOAT_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res,
npy_intp n, void *tmp)
{
register npy_intp na = stridea / sizeof(float);
register npy_intp nb = strideb / sizeof(float);
if ((sizeof(float) * na == (size_t)stridea) &&
(sizeof(float) * nb == (size_t)strideb) &&
(na >= 0) && (nb >= 0))
*((float *)res) = cblas_sdot((int)n, (float *)a, na, (float *)b, nb);
else
oldFunctions[PyArray_FLOAT](a, stridea, b, strideb, res, n, tmp);
}
static void
DOUBLE_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res,
npy_intp n, void *tmp)
{
register int na = stridea / sizeof(double);
register int nb = strideb / sizeof(double);
if ((sizeof(double) * na == (size_t)stridea) &&
(sizeof(double) * nb == (size_t)strideb) &&
(na >= 0) && (nb >= 0))
*((double *)res) = cblas_ddot((int)n, (double *)a, na, (double *)b, nb);
else
oldFunctions[PyArray_DOUBLE](a, stridea, b, strideb, res, n, tmp);
}
static void
CFLOAT_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res,
npy_intp n, void *tmp)
{
register int na = stridea / sizeof(npy_cfloat);
register int nb = strideb / sizeof(npy_cfloat);
if ((sizeof(npy_cfloat) * na == (size_t)stridea) &&
(sizeof(npy_cfloat) * nb == (size_t)strideb) &&
(na >= 0) && (nb >= 0))
cblas_cdotu_sub((int)n, (float *)a, na, (float *)b, nb, (float *)res);
else
oldFunctions[PyArray_CFLOAT](a, stridea, b, strideb, res, n, tmp);
}
static void
CDOUBLE_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res,
npy_intp n, void *tmp)
{
register int na = stridea / sizeof(npy_cdouble);
register int nb = strideb / sizeof(npy_cdouble);
if ((sizeof(npy_cdouble) * na == (size_t)stridea) &&
(sizeof(npy_cdouble) * nb == (size_t)strideb) &&
(na >= 0) && (nb >= 0))
cblas_zdotu_sub((int)n, (double *)a, na, (double *)b, nb, (double *)res);
else
oldFunctions[PyArray_CDOUBLE](a, stridea, b, strideb, res, n, tmp);
}
static npy_bool altered=NPY_FALSE;
/*
* alterdot() changes all dot functions to use blas.
*/
static PyObject *
dotblas_alterdot(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
NpyArray_Descr *descr;
if (!PyArg_ParseTuple(args, "")) return NULL;
/* Replace the dot functions to the ones using blas */
if (!altered) {
descr = NpyArray_DescrFromType(PyArray_FLOAT);
oldFunctions[PyArray_FLOAT] = descr->f->dotfunc;
descr->f->dotfunc = (PyArray_DotFunc *)FLOAT_dot;
/* TODO: Isn't think leaking descr? */
descr = NpyArray_DescrFromType(PyArray_DOUBLE);
oldFunctions[PyArray_DOUBLE] = descr->f->dotfunc;
descr->f->dotfunc = (PyArray_DotFunc *)DOUBLE_dot;
descr = NpyArray_DescrFromType(PyArray_CFLOAT);
oldFunctions[PyArray_CFLOAT] = descr->f->dotfunc;
descr->f->dotfunc = (PyArray_DotFunc *)CFLOAT_dot;
descr = NpyArray_DescrFromType(PyArray_CDOUBLE);
oldFunctions[PyArray_CDOUBLE] = descr->f->dotfunc;
descr->f->dotfunc = (PyArray_DotFunc *)CDOUBLE_dot;
altered = NPY_TRUE;
}
Py_INCREF(Py_None);
return Py_None;
}
/*
* restoredot() restores dots to defaults.
*/
static PyObject *
dotblas_restoredot(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
NpyArray_Descr *descr;
if (!PyArg_ParseTuple(args, "")) return NULL;
if (altered) {
descr = NpyArray_DescrFromType(PyArray_FLOAT);
descr->f->dotfunc = oldFunctions[PyArray_FLOAT];
oldFunctions[PyArray_FLOAT] = NULL;
Npy_XDECREF(descr);
descr = NpyArray_DescrFromType(PyArray_DOUBLE);
descr->f->dotfunc = oldFunctions[PyArray_DOUBLE];
oldFunctions[PyArray_DOUBLE] = NULL;
Npy_XDECREF(descr);
descr = NpyArray_DescrFromType(PyArray_CFLOAT);
descr->f->dotfunc = oldFunctions[PyArray_CFLOAT];
oldFunctions[PyArray_CFLOAT] = NULL;
Npy_XDECREF(descr);
descr = NpyArray_DescrFromType(PyArray_CDOUBLE);
descr->f->dotfunc = oldFunctions[PyArray_CDOUBLE];
oldFunctions[PyArray_CDOUBLE] = NULL;
Npy_XDECREF(descr);
altered = NPY_FALSE;
}
Py_INCREF(Py_None);
return Py_None;
}
typedef enum {_scalar, _column, _row, _matrix} MatrixShape;
static MatrixShape
_select_matrix_shape(PyArrayObject *array)
{
switch (PyArray_NDIM(array)) {
case 0:
return _scalar;
case 1:
if (PyArray_DIM(array, 0) > 1)
return _column;
return _scalar;
case 2:
if (PyArray_DIM(array, 0) > 1) {
if (PyArray_DIM(array, 1) == 1)
return _column;
else
return _matrix;
}
if (PyArray_DIM(array, 1) == 1)
return _scalar;
return _row;
}
return _matrix;
}
/* This also makes sure that the data segment is aligned with
an itemsize address as well by returning one if not true.
*/
static int
_bad_strides(PyArrayObject *ap)
{
register int itemsize = PyArray_ITEMSIZE(ap);
register int i, N=PyArray_NDIM(ap);
register npy_intp *strides = PyArray_STRIDES(ap);
if (((npy_intp)(PyArray_BYTES(ap)) % itemsize) != 0)
return 1;
for (i=0; i<N; i++) {
if ((strides[i] < 0) || (strides[i] % itemsize) != 0)
return 1;
}
return 0;
}
/*
* dot(a,b)
* Returns the dot product of a and b for arrays of floating point types.
* Like the generic numpy equivalent the product sum is over
* the last dimension of a and the second-to-last dimension of b.
* NB: The first argument is not conjugated.;
*/
static PyObject *
dotblas_matrixproduct(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
PyObject *op1, *op2;
PyArrayObject *ap1 = NULL, *ap2 = NULL, *ret = NULL;
int j, l, lda, ldb, ldc;
int typenum, nd;
npy_intp ap1stride = 0;
npy_intp dimensions[NPY_MAXDIMS];
npy_intp numbytes;
static const float oneF[2] = {1.0, 0.0};
static const float zeroF[2] = {0.0, 0.0};
static const double oneD[2] = {1.0, 0.0};
static const double zeroD[2] = {0.0, 0.0};
double prior1, prior2;
PyTypeObject *subtype;
PyArray_Descr *dtype;
MatrixShape ap1shape, ap2shape;
if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) {
return NULL;
}
/*
* "Matrix product" using the BLAS.
* Only works for float double and complex types.
*/
typenum = PyArray_ObjectType(op1, 0);
typenum = PyArray_ObjectType(op2, typenum);
/* This function doesn't handle other types */
if ((typenum != PyArray_DOUBLE && typenum != PyArray_CDOUBLE &&
typenum != PyArray_FLOAT && typenum != PyArray_CFLOAT)) {
return PyArray_Return((PyArrayObject *)PyArray_MatrixProduct(op1, op2));
}
dtype = PyArray_DescrFromType(typenum);
if (dtype == NULL) {
return NULL;
}
Py_INCREF(dtype);
ap1 = (PyArrayObject *)PyArray_FromAny(op1, dtype, 0, 0, NPY_ALIGNED, NULL);
if (ap1 == NULL) {
Py_DECREF(dtype);
return NULL;
}
ap2 = (PyArrayObject *)PyArray_FromAny(op2, dtype, 0, 0, NPY_ALIGNED, NULL);
if (ap2 == NULL) {
Py_DECREF(ap1);
return NULL;
}
if ((PyArray_NDIM(ap1) > 2) || (PyArray_NDIM(ap2) > 2)) {
/*
* This function doesn't handle dimensions greater than 2
* (or negative striding) -- other
* than to ensure the dot function is altered
*/
if (!altered) {
/* need to alter dot product */
PyObject *tmp1, *tmp2;
tmp1 = PyTuple_New(0);
tmp2 = dotblas_alterdot(NULL, tmp1);
Py_DECREF(tmp1);
Py_DECREF(tmp2);
}
ret = (PyArrayObject *)PyArray_MatrixProduct((PyObject *)ap1,
(PyObject *)ap2);
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
}
if (_bad_strides(ap1)) {
op1 = PyArray_NewCopy(ap1, PyArray_ANYORDER);
Py_DECREF(ap1);
ap1 = (PyArrayObject *)op1;
if (ap1 == NULL) {
goto fail;
}
}
if (_bad_strides(ap2)) {
op2 = PyArray_NewCopy(ap2, PyArray_ANYORDER);
Py_DECREF(ap2);
ap2 = (PyArrayObject *)op2;
if (ap2 == NULL) {
goto fail;
}
}
ap1shape = _select_matrix_shape(ap1);
ap2shape = _select_matrix_shape(ap2);
if (ap1shape == _scalar || ap2shape == _scalar) {
PyArrayObject *oap1, *oap2;
oap1 = ap1; oap2 = ap2;
/* One of ap1 or ap2 is a scalar */
if (ap1shape == _scalar) { /* Make ap2 the scalar */
PyArrayObject *t = ap1;
ap1 = ap2;
ap2 = t;
ap1shape = ap2shape;
ap2shape = _scalar;
}
if (ap1shape == _row) {
ap1stride = PyArray_STRIDE(ap1, 1);
}
else if (PyArray_NDIM(ap1) > 0) {
ap1stride = PyArray_STRIDE(ap1, 0);
}
if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) {
npy_intp *thisdims;
if (PyArray_NDIM(ap1) == 0) {
nd = PyArray_NDIM(ap2);
thisdims = PyArray_DIMS(ap2);
}
else {
nd = PyArray_NDIM(ap1);
thisdims = PyArray_DIMS(ap1);
}
l = 1;
for (j = 0; j < nd; j++) {
dimensions[j] = thisdims[j];
l *= dimensions[j];
}
}
else {
l = PyArray_DIM(oap1, PyArray_NDIM(oap1) - 1);
if (PyArray_DIM(oap2, 0) != l) {
PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
goto fail;
}
nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2;
/*
* nd = 0 or 1 or 2. If nd == 0 do nothing ...
*/
if (nd == 1) {
/*
* Either PyArray_NDIM(ap1) is 1 dim or PyArray_NDIM(ap2) is 1 dim
* and the other is 2-dim
*/
dimensions[0] = (PyArray_NDIM(oap1) == 2) ? PyArray_DIM(oap1, 0) : PyArray_DIM(oap2, 1);
l = dimensions[0];
/*
* Fix it so that dot(shape=(N,1), shape=(1,))
* and dot(shape=(1,), shape=(1,N)) both return
* an (N,) array (but use the fast scalar code)
*/
}
else if (nd == 2) {
dimensions[0] = PyArray_DIM(oap1, 0);
dimensions[1] = PyArray_DIM(oap2, 1);
/*
* We need to make sure that dot(shape=(1,1), shape=(1,N))
* and dot(shape=(N,1),shape=(1,1)) uses
* scalar multiplication appropriately
*/
if (ap1shape == _row) {
l = dimensions[1];
}
else {
l = dimensions[0];
}
}
/* Check if the summation dimension is 0-sized */
if (PyArray_DIM(oap1, PyArray_NDIM(oap1) - 1) == 0) {
l = 0;
}
}
}
else {
/*
* (PyArray_NDIM(ap1) <= 2 && PyArray_NDIM(ap2) <= 2)
* Both ap1 and ap2 are vectors or matrices
*/
l = PyArray_DIM(ap1, PyArray_NDIM(ap1) - 1);
if (PyArray_DIM(ap2, 0) != l) {
PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
goto fail;
}
nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2;
if (nd == 1)
dimensions[0] = (PyArray_NDIM(ap1) == 2) ? PyArray_DIM(ap1, 0) : PyArray_DIM(ap2, 1);
else if (nd == 2) {
dimensions[0] = PyArray_DIM(ap1, 0);
dimensions[1] = PyArray_DIM(ap2, 1);
}
}
/* Choose which subtype to return */
if (Py_TYPE(ap1) != Py_TYPE(ap2)) {
prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0);
prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0);
subtype = (prior2 > prior1 ? Py_TYPE(ap2) : Py_TYPE(ap1));
}
else {
prior1 = prior2 = 0.0;
subtype = Py_TYPE(ap1);
}
ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions,
typenum, NULL, NULL, 0, 0,
(PyObject *)
(prior2 > prior1 ? ap2 : ap1));
if (ret == NULL) {
goto fail;
}
numbytes = PyArray_NBYTES(ret);
memset(PyArray_BYTES(ret), 0, numbytes);
if (numbytes==0 || l == 0) {
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
}
if (ap2shape == _scalar) {
/*
* Multiplication by a scalar -- Level 1 BLAS
* if ap1shape is a matrix and we are not contiguous, then we can't
* just blast through the entire array using a single striding factor
*/
NPY_BEGIN_ALLOW_THREADS;
if (typenum == PyArray_DOUBLE) {
if (l == 1) {
*((double *)PyArray_BYTES(ret)) = *((double *)PyArray_BYTES(ap2)) *
*((double *)PyArray_BYTES(ap1));
}
else if (ap1shape != _matrix) {
cblas_daxpy(l, *((double *)PyArray_BYTES(ap2)), (double *)PyArray_BYTES(ap1),
ap1stride/sizeof(double), (double *)PyArray_BYTES(ret), 1);
}
else {
int maxind, oind, i, a1s, rets;
char *ptr, *rptr;
double val;
maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1);
oind = 1-maxind;
ptr = PyArray_BYTES(ap1);
rptr = PyArray_BYTES(ret);
l = PyArray_DIM(ap1, maxind);
val = *((double *)PyArray_BYTES(ap2));
a1s = PyArray_STRIDE(ap1, maxind) / sizeof(double);
rets = PyArray_STRIDE(ret, maxind) / sizeof(double);
for (i = 0; i < PyArray_DIM(ap1, oind); i++) {
cblas_daxpy(l, val, (double *)ptr, a1s,
(double *)rptr, rets);
ptr += PyArray_STRIDE(ap1, oind);
rptr += PyArray_STRIDE(ret, oind);
}
}
}
else if (typenum == PyArray_CDOUBLE) {
if (l == 1) {
npy_cdouble *ptr1, *ptr2, *res;
ptr1 = (npy_cdouble *)PyArray_BYTES(ap2);
ptr2 = (npy_cdouble *)PyArray_BYTES(ap1);
res = (npy_cdouble *)PyArray_BYTES(ret);
res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag;
res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real;
}
else if (ap1shape != _matrix) {
cblas_zaxpy(l, (double *)PyArray_BYTES(ap2), (double *)PyArray_BYTES(ap1),
ap1stride/sizeof(npy_cdouble), (double *)PyArray_BYTES(ret), 1);
}
else {
int maxind, oind, i, a1s, rets;
char *ptr, *rptr;
double *pval;
maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1);
oind = 1-maxind;
ptr = PyArray_BYTES(ap1);
rptr = PyArray_BYTES(ret);
l = PyArray_DIM(ap1, maxind);
pval = (double *)PyArray_BYTES(ap2);
a1s = PyArray_STRIDE(ap1, maxind) / sizeof(npy_cdouble);
rets = PyArray_STRIDE(ret, maxind) / sizeof(npy_cdouble);
for (i = 0; i < PyArray_DIM(ap1, oind); i++) {
cblas_zaxpy(l, pval, (double *)ptr, a1s,
(double *)rptr, rets);
ptr += PyArray_STRIDE(ap1, oind);
rptr += PyArray_STRIDE(ret, oind);
}
}
}
else if (typenum == PyArray_FLOAT) {
if (l == 1) {
*((float *)PyArray_BYTES(ret)) = *((float *)PyArray_BYTES(ap2)) *
*((float *)PyArray_BYTES(ap1));
}
else if (ap1shape != _matrix) {
cblas_saxpy(l, *((float *)PyArray_BYTES(ap2)), (float *)PyArray_BYTES(ap1),
ap1stride/sizeof(float), (float *)PyArray_BYTES(ret), 1);
}
else {
int maxind, oind, i, a1s, rets;
char *ptr, *rptr;
float val;
maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1);
oind = 1-maxind;
ptr = PyArray_BYTES(ap1);
rptr = PyArray_BYTES(ret);
l = PyArray_DIM(ap1, maxind);
val = *((float *)PyArray_BYTES(ap2));
a1s = PyArray_STRIDE(ap1, maxind) / sizeof(float);
rets = PyArray_STRIDE(ret, maxind) / sizeof(float);
for (i = 0; i < PyArray_DIM(ap1, oind); i++) {
cblas_saxpy(l, val, (float *)ptr, a1s,
(float *)rptr, rets);
ptr += PyArray_STRIDE(ap1, oind);
rptr += PyArray_STRIDE(ret, oind);
}
}
}
else if (typenum == PyArray_CFLOAT) {
if (l == 1) {
npy_cfloat *ptr1, *ptr2, *res;
ptr1 = (npy_cfloat *)PyArray_BYTES(ap2);
ptr2 = (npy_cfloat *)PyArray_BYTES(ap1);
res = (npy_cfloat *)PyArray_BYTES(ret);
res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag;
res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real;
}
else if (ap1shape != _matrix) {
cblas_caxpy(l, (float *)PyArray_BYTES(ap2), (float *)PyArray_BYTES(ap1),
ap1stride/sizeof(npy_cfloat), (float *)PyArray_BYTES(ret), 1);
}
else {
int maxind, oind, i, a1s, rets;
char *ptr, *rptr;
float *pval;
maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1);
oind = 1-maxind;
ptr = PyArray_BYTES(ap1);
rptr = PyArray_BYTES(ret);
l = PyArray_DIM(ap1, maxind);
pval = (float *)PyArray_BYTES(ap2);
a1s = PyArray_STRIDE(ap1, maxind) / sizeof(npy_cfloat);
rets = PyArray_STRIDE(ret, maxind) / sizeof(npy_cfloat);
for (i = 0; i < PyArray_DIM(ap1, oind); i++) {
cblas_caxpy(l, pval, (float *)ptr, a1s,
(float *)rptr, rets);
ptr += PyArray_STRIDE(ap1, oind);
rptr += PyArray_STRIDE(ret, oind);
}
}
}
NPY_END_ALLOW_THREADS;
}
else if ((ap2shape == _column) && (ap1shape != _matrix)) {
int ap1s, ap2s;
NPY_BEGIN_ALLOW_THREADS;
ap2s = PyArray_STRIDE(ap2, 0) / PyArray_ITEMSIZE(ap2);
if (ap1shape == _row) {
ap1s = PyArray_STRIDE(ap1, 1) / PyArray_ITEMSIZE(ap1);
}
else {
ap1s = PyArray_STRIDE(ap1, 0) / PyArray_ITEMSIZE(ap1);
}
/* Dot product between two vectors -- Level 1 BLAS */
if (typenum == PyArray_DOUBLE) {
double result = cblas_ddot(l, (double *)PyArray_BYTES(ap1), ap1s,
(double *)PyArray_BYTES(ap2), ap2s);
*((double *)PyArray_BYTES(ret)) = result;
}
else if (typenum == PyArray_FLOAT) {
float result = cblas_sdot(l, (float *)PyArray_BYTES(ap1), ap1s,
(float *)PyArray_BYTES(ap2), ap2s);
*((float *)PyArray_BYTES(ret)) = result;
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zdotu_sub(l, (double *)PyArray_BYTES(ap1), ap1s,
(double *)PyArray_BYTES(ap2), ap2s, (double *)PyArray_BYTES(ret));
}
else if (typenum == PyArray_CFLOAT) {
cblas_cdotu_sub(l, (float *)PyArray_BYTES(ap1), ap1s,
(float *)PyArray_BYTES(ap2), ap2s, (float *)PyArray_BYTES(ret));
}
NPY_END_ALLOW_THREADS;
}
else if (ap1shape == _matrix && ap2shape != _matrix) {
/* Matrix vector multiplication -- Level 2 BLAS */
/* lda must be MAX(M,1) */
enum CBLAS_ORDER Order;
int ap2s;
if (!PyArray_ISONESEGMENT(ap1)) {
PyObject *new;
new = PyArray_Copy(ap1);
Py_DECREF(ap1);
ap1 = (PyArrayObject *)new;
if (new == NULL) {
goto fail;
}
}
NPY_BEGIN_ALLOW_THREADS
if (PyArray_ISCONTIGUOUS(ap1)) {
Order = CblasRowMajor;
lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1);
}
else {
Order = CblasColMajor;
lda = (PyArray_DIM(ap1, 0) > 1 ? PyArray_DIM(ap1, 0) : 1);
}
ap2s = PyArray_STRIDE(ap2, 0) / PyArray_ITEMSIZE(ap2);
if (typenum == PyArray_DOUBLE) {
cblas_dgemv(Order, CblasNoTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
1.0, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ap2s, 0.0, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemv(Order, CblasNoTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
1.0, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ap2s, 0.0, (float *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemv(Order,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
oneD, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ap2s, zeroD,
(double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemv(Order,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
oneF, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ap2s, zeroF,
(float *)PyArray_BYTES(ret), 1);
}
NPY_END_ALLOW_THREADS;
}
else if (ap1shape != _matrix && ap2shape == _matrix) {
/* Vector matrix multiplication -- Level 2 BLAS */
enum CBLAS_ORDER Order;
int ap1s;
if (!PyArray_ISONESEGMENT(ap2)) {
PyObject *new;
new = PyArray_Copy(ap2);
Py_DECREF(ap2);
ap2 = (PyArrayObject *)new;
if (new == NULL) {
goto fail;
}
}
NPY_BEGIN_ALLOW_THREADS
if (PyArray_ISCONTIGUOUS(ap2)) {
Order = CblasRowMajor;
lda = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1);
}
else {
Order = CblasColMajor;
lda = (PyArray_DIM(ap2, 0) > 1 ? PyArray_DIM(ap2, 0) : 1);
}
if (ap1shape == _row) {
ap1s = PyArray_STRIDE(ap1, 1) / PyArray_ITEMSIZE(ap1);
}
else {
ap1s = PyArray_STRIDE(ap1, 0) / PyArray_ITEMSIZE(ap1);
}
if (typenum == PyArray_DOUBLE) {
cblas_dgemv(Order,
CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
1.0, (double *)PyArray_BYTES(ap2), lda,
(double *)PyArray_BYTES(ap1), ap1s, 0.0, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemv(Order,
CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
1.0, (float *)PyArray_BYTES(ap2), lda,
(float *)PyArray_BYTES(ap1), ap1s, 0.0, (float *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemv(Order,
CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
oneD, (double *)PyArray_BYTES(ap2), lda,
(double *)PyArray_BYTES(ap1), ap1s, zeroD, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemv(Order,
CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
oneF, (float *)PyArray_BYTES(ap2), lda,
(float *)PyArray_BYTES(ap1), ap1s, zeroF, (float *)PyArray_BYTES(ret), 1);
}
NPY_END_ALLOW_THREADS;
}
else {
/*
* (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 2)
* Matrix matrix multiplication -- Level 3 BLAS
* L x M multiplied by M x N
*/
enum CBLAS_ORDER Order;
enum CBLAS_TRANSPOSE Trans1, Trans2;
int M, N, L;
/* Optimization possible: */
/*
* We may be able to handle single-segment arrays here
* using appropriate values of Order, Trans1, and Trans2.
*/
if (!PyArray_ISCONTIGUOUS(ap2)) {
PyObject *new = PyArray_Copy(ap2);
Py_DECREF(ap2);
ap2 = (PyArrayObject *)new;
if (new == NULL) {
goto fail;
}
}
if (!PyArray_ISCONTIGUOUS(ap1)) {
PyObject *new = PyArray_Copy(ap1);
Py_DECREF(ap1);
ap1 = (PyArrayObject *)new;
if (new == NULL) {
goto fail;
}
}
NPY_BEGIN_ALLOW_THREADS;
Order = CblasRowMajor;
Trans1 = CblasNoTrans;
Trans2 = CblasNoTrans;
L = PyArray_DIM(ap1, 0);
N = PyArray_DIM(ap2, 1);
M = PyArray_DIM(ap2, 0);
lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1);
ldb = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1);
ldc = (PyArray_DIM(ret, 1) > 1 ? PyArray_DIM(ret, 1) : 1);
if (typenum == PyArray_DOUBLE) {
cblas_dgemm(Order, Trans1, Trans2,
L, N, M,
1.0, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ldb,
0.0, (double *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemm(Order, Trans1, Trans2,
L, N, M,
1.0, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ldb,
0.0, (float *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemm(Order, Trans1, Trans2,
L, N, M,
oneD, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ldb,
zeroD, (double *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemm(Order, Trans1, Trans2,
L, N, M,
oneF, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ldb,
zeroF, (float *)PyArray_BYTES(ret), ldc);
}
NPY_END_ALLOW_THREADS;
}
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
fail:
Py_XDECREF(ap1);
Py_XDECREF(ap2);
Py_XDECREF(ret);
return NULL;
}
/*
* innerproduct(a,b)
*
* Returns the inner product of a and b for arrays of
* floating point types. Like the generic NumPy equivalent the product
* sum is over the last dimension of a and b.
* NB: The first argument is not conjugated.
*/
static PyObject *
dotblas_innerproduct(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
PyObject *op1, *op2;
PyArrayObject *ap1, *ap2, *ret;
int j, l, lda, ldb, ldc;
int typenum, nd;
npy_intp dimensions[NPY_MAXDIMS];
static const float oneF[2] = {1.0, 0.0};
static const float zeroF[2] = {0.0, 0.0};
static const double oneD[2] = {1.0, 0.0};
static const double zeroD[2] = {0.0, 0.0};
PyTypeObject *subtype;
double prior1, prior2;
if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) return NULL;
/*
* Inner product using the BLAS. The product sum is taken along the last
* dimensions of the two arrays.
* Only speeds things up for float double and complex types.
*/
typenum = PyArray_ObjectType(op1, 0);
typenum = PyArray_ObjectType(op2, typenum);
/* This function doesn't handle other types */
if ((typenum != PyArray_DOUBLE && typenum != PyArray_CDOUBLE &&
typenum != PyArray_FLOAT && typenum != PyArray_CFLOAT)) {
return PyArray_Return((PyArrayObject *)PyArray_InnerProduct(op1, op2));
}
ret = NULL;
ap1 = (PyArrayObject *)PyArray_ContiguousFromObject(op1, typenum, 0, 0);
if (ap1 == NULL) return NULL;
ap2 = (PyArrayObject *)PyArray_ContiguousFromObject(op2, typenum, 0, 0);
if (ap2 == NULL) goto fail;
if ((PyArray_NDIM(ap1) > 2) || (PyArray_NDIM(ap2) > 2)) {
/* This function doesn't handle dimensions greater than 2 -- other
than to ensure the dot function is altered
*/
if (!altered) {
/* need to alter dot product */
PyObject *tmp1, *tmp2;
tmp1 = PyTuple_New(0);
tmp2 = dotblas_alterdot(NULL, tmp1);
Py_DECREF(tmp1);
Py_DECREF(tmp2);
}
ret = (PyArrayObject *)PyArray_InnerProduct((PyObject *)ap1,
(PyObject *)ap2);
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
}
if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) {
/* One of ap1 or ap2 is a scalar */
if (PyArray_NDIM(ap1) == 0) { /* Make ap2 the scalar */
PyArrayObject *t = ap1;
ap1 = ap2;
ap2 = t;
}
for (l = 1, j = 0; j < PyArray_NDIM(ap1); j++) {
dimensions[j] = PyArray_DIM(ap1, j);
l *= dimensions[j];
}
nd = PyArray_NDIM(ap1);
}
else { /* (PyArray_NDIM(ap1) <= 2 && PyArray_NDIM(ap2) <= 2) */
/* Both ap1 and ap2 are vectors or matrices */
l = PyArray_DIM(ap1, PyArray_NDIM(ap1)-1);
if (PyArray_DIM(ap2, PyArray_NDIM(ap2)-1) != l) {
PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
goto fail;
}
nd = PyArray_NDIM(ap1)+PyArray_NDIM(ap2)-2;
if (nd == 1)
dimensions[0] = (PyArray_NDIM(ap1) == 2) ? PyArray_DIM(ap1, 0) : PyArray_DIM(ap2, 0);
else if (nd == 2) {
dimensions[0] = PyArray_DIM(ap1, 0);
dimensions[1] = PyArray_DIM(ap2, 0);
}
}
/* Choose which subtype to return */
prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0);
prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0);
subtype = (prior2 > prior1 ? Py_TYPE(ap2) : Py_TYPE(ap1));
ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions,
typenum, NULL, NULL, 0, 0,
(PyObject *)\
(prior2 > prior1 ? ap2 : ap1));
if (ret == NULL) goto fail;
NPY_BEGIN_ALLOW_THREADS
memset(PyArray_BYTES(ret), 0, PyArray_NBYTES(ret));
if (PyArray_NDIM(ap2) == 0) {
/* Multiplication by a scalar -- Level 1 BLAS */
if (typenum == PyArray_DOUBLE) {
cblas_daxpy(l, *((double *)PyArray_BYTES(ap2)), (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zaxpy(l, (double *)PyArray_BYTES(ap2), (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_FLOAT) {
cblas_saxpy(l, *((float *)PyArray_BYTES(ap2)), (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CFLOAT) {
cblas_caxpy(l, (float *)PyArray_BYTES(ap2), (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ret), 1);
}
}
else if (PyArray_NDIM(ap1) == 1 && PyArray_NDIM(ap2) == 1) {
/* Dot product between two vectors -- Level 1 BLAS */
if (typenum == PyArray_DOUBLE) {
double result = cblas_ddot(l, (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ap2), 1);
*((double *)PyArray_BYTES(ret)) = result;
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zdotu_sub(l, (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ap2), 1, (double *)PyArray_BYTES(ret));
}
else if (typenum == PyArray_FLOAT) {
float result = cblas_sdot(l, (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ap2), 1);
*((float *)PyArray_BYTES(ret)) = result;
}
else if (typenum == PyArray_CFLOAT) {
cblas_cdotu_sub(l, (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ap2), 1, (float *)PyArray_BYTES(ret));
}
}
else if (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 1) {
/* Matrix-vector multiplication -- Level 2 BLAS */
lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1);
if (typenum == PyArray_DOUBLE) {
cblas_dgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
1.0, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), 1, 0.0, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
oneD, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), 1, zeroD, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
1.0, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), 1, 0.0, (float *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1),
oneF, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), 1, zeroF, (float *)PyArray_BYTES(ret), 1);
}
}
else if (PyArray_NDIM(ap1) == 1 && PyArray_NDIM(ap2) == 2) {
/* Vector matrix multiplication -- Level 2 BLAS */
lda = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1);
if (typenum == PyArray_DOUBLE) {
cblas_dgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
1.0, (double *)PyArray_BYTES(ap2), lda,
(double *)PyArray_BYTES(ap1), 1, 0.0, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
oneD, (double *)PyArray_BYTES(ap2), lda,
(double *)PyArray_BYTES(ap1), 1, zeroD, (double *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
1.0, (float *)PyArray_BYTES(ap2), lda,
(float *)PyArray_BYTES(ap1), 1, 0.0, (float *)PyArray_BYTES(ret), 1);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemv(CblasRowMajor,
CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1),
oneF, (float *)PyArray_BYTES(ap2), lda,
(float *)PyArray_BYTES(ap1), 1, zeroF, (float *)PyArray_BYTES(ret), 1);
}
}
else { /* (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 2) */
/* Matrix matrix multiplication -- Level 3 BLAS */
lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1);
ldb = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1);
ldc = (PyArray_DIM(ret, 1) > 1 ? PyArray_DIM(ret, 1) : 1);
if (typenum == PyArray_DOUBLE) {
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1),
1.0, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ldb,
0.0, (double *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_FLOAT) {
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1),
1.0, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ldb,
0.0, (float *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1),
oneD, (double *)PyArray_BYTES(ap1), lda,
(double *)PyArray_BYTES(ap2), ldb,
zeroD, (double *)PyArray_BYTES(ret), ldc);
}
else if (typenum == PyArray_CFLOAT) {
cblas_cgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1),
oneF, (float *)PyArray_BYTES(ap1), lda,
(float *)PyArray_BYTES(ap2), ldb,
zeroF, (float *)PyArray_BYTES(ret), ldc);
}
}
NPY_END_ALLOW_THREADS
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
fail:
Py_XDECREF(ap1);
Py_XDECREF(ap2);
Py_XDECREF(ret);
return NULL;
}
/*
* vdot(a,b)
*
* Returns the dot product of a and b for scalars and vectors of
* floating point and complex types. The first argument, a, is conjugated.
*/
static PyObject *dotblas_vdot(PyObject *NPY_UNUSED(dummy), PyObject *args) {
PyObject *op1, *op2;
PyArrayObject *ap1=NULL, *ap2=NULL, *ret=NULL;
int l;
int typenum;
npy_intp dimensions[NPY_MAXDIMS];
PyArray_Descr *type;
if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) return NULL;
/*
* Conjugating dot product using the BLAS for vectors.
* Multiplies op1 and op2, each of which must be vector.
*/
typenum = PyArray_ObjectType(op1, 0);
typenum = PyArray_ObjectType(op2, typenum);
type = PyArray_DescrFromType(typenum);
Py_INCREF(type);
ap1 = (PyArrayObject *)PyArray_FromAny(op1, type, 0, 0, 0, NULL);
if (ap1==NULL) {Py_DECREF(type); goto fail;}
op1 = PyArray_Flatten(ap1, 0);
if (op1==NULL) {Py_DECREF(type); goto fail;}
Py_DECREF(ap1);
ap1 = (PyArrayObject *)op1;
ap2 = (PyArrayObject *)PyArray_FromAny(op2, type, 0, 0, 0, NULL);
if (ap2==NULL) goto fail;
op2 = PyArray_Flatten(ap2, 0);
if (op2 == NULL) goto fail;
Py_DECREF(ap2);
ap2 = (PyArrayObject *)op2;
if (typenum != PyArray_FLOAT && typenum != PyArray_DOUBLE &&
typenum != PyArray_CFLOAT && typenum != PyArray_CDOUBLE) {
if (!altered) {
/* need to alter dot product */
PyObject *tmp1, *tmp2;
tmp1 = PyTuple_New(0);
tmp2 = dotblas_alterdot(NULL, tmp1);
Py_DECREF(tmp1);
Py_DECREF(tmp2);
}
if (NpyTypeNum_ISCOMPLEX(typenum)) {
op1 = PyArray_Conjugate(ap1, NULL);
if (op1==NULL) goto fail;
Py_DECREF(ap1);
ap1 = (PyArrayObject *)op1;
}
ret = (PyArrayObject *)PyArray_InnerProduct((PyObject *)ap1,
(PyObject *)ap2);
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
}
if (PyArray_DIM(ap2, 0) != PyArray_DIM(ap1, PyArray_NDIM(ap1)-1)) {
PyErr_SetString(PyExc_ValueError, "vectors have different lengths");
goto fail;
}
l = PyArray_DIM(ap1, PyArray_NDIM(ap1)-1);
ret = (PyArrayObject *)PyArray_SimpleNew(0, dimensions, typenum);
if (ret == NULL) goto fail;
NPY_BEGIN_ALLOW_THREADS
/* Dot product between two vectors -- Level 1 BLAS */
if (typenum == PyArray_DOUBLE) {
*((double *)PyArray_BYTES(ret)) = cblas_ddot(l, (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ap2), 1);
}
else if (typenum == PyArray_FLOAT) {
*((float *)PyArray_BYTES(ret)) = cblas_sdot(l, (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ap2), 1);
}
else if (typenum == PyArray_CDOUBLE) {
cblas_zdotc_sub(l, (double *)PyArray_BYTES(ap1), 1,
(double *)PyArray_BYTES(ap2), 1, (double *)PyArray_BYTES(ret));
}
else if (typenum == PyArray_CFLOAT) {
cblas_cdotc_sub(l, (float *)PyArray_BYTES(ap1), 1,
(float *)PyArray_BYTES(ap2), 1, (float *)PyArray_BYTES(ret));
}
NPY_END_ALLOW_THREADS
Py_DECREF(ap1);
Py_DECREF(ap2);
return PyArray_Return(ret);
fail:
Py_XDECREF(ap1);
Py_XDECREF(ap2);
Py_XDECREF(ret);
return NULL;
}
static struct PyMethodDef dotblas_module_methods[] = {
{"dot", (PyCFunction)dotblas_matrixproduct, 1, NULL},
{"inner", (PyCFunction)dotblas_innerproduct, 1, NULL},
{"vdot", (PyCFunction)dotblas_vdot, 1, NULL},
{"alterdot", (PyCFunction)dotblas_alterdot, 1, NULL},
{"restoredot", (PyCFunction)dotblas_restoredot, 1, NULL},
{NULL, NULL, 0, NULL} /* sentinel */
};
/* Initialization function for the module */
PyMODINIT_FUNC init_dotblas(void) {
int i;
PyObject *d, *s;
/* Create the module and add the functions */
Py_InitModule3("_dotblas", dotblas_module_methods, module_doc);
/* Import the array object */
import_array();
/* Initialise the array of dot functions */
for (i = 0; i < PyArray_NTYPES; i++)
oldFunctions[i] = NULL;
/* alterdot at load */
d = PyTuple_New(0);
s = dotblas_alterdot(NULL, d);
Py_DECREF(d);
Py_DECREF(s);
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE195_Signed_to_Unsigned_Conversion_Error/s01/CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68b.c | 1 | 3189 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68b.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-68b.tmpl.c
*/
/*
* @description
* CWE: 195 Signed to Unsigned Conversion Error
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Positive integer
* Sink: malloc
* BadSink : Allocate memory using malloc() with the size of data
* Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
extern int CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68_badData;
extern int CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68_goodG2BData;
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68b_badSink()
{
int data = CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68_badData;
/* Assume we want to allocate a relatively small buffer */
if (data < 100)
{
/* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
* the conversion will cause malloc() to allocate a very large amount of data or fail */
char * dataBuffer = (char *)malloc(data);
if (dataBuffer == NULL) {exit(-1);}
/* Do something with dataBuffer */
memset(dataBuffer, 'A', data-1);
dataBuffer[data-1] = '\0';
printLine(dataBuffer);
free(dataBuffer);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68b_goodG2BSink()
{
int data = CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_68_goodG2BData;
/* Assume we want to allocate a relatively small buffer */
if (data < 100)
{
/* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
* the conversion will cause malloc() to allocate a very large amount of data or fail */
char * dataBuffer = (char *)malloc(data);
if (dataBuffer == NULL) {exit(-1);}
/* Do something with dataBuffer */
memset(dataBuffer, 'A', data-1);
dataBuffer[data-1] = '\0';
printLine(dataBuffer);
free(dataBuffer);
}
}
#endif /* OMITGOOD */
| bsd-3-clause |
chshu/openthread | examples/platforms/simulation/virtual_time/platform-sim.c | 2 | 8138 | /*
* Copyright (c) 2018, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file includes the platform-specific initializers.
*/
#include "platform-simulation.h"
#if OPENTHREAD_SIMULATION_VIRTUAL_TIME
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <libgen.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <openthread/tasklet.h>
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/uart.h>
uint32_t gNodeId = 1;
extern bool gPlatformPseudoResetWasRequested;
static volatile bool gTerminate = false;
int gArgumentsCount = 0;
char **gArguments = NULL;
uint64_t sNow = 0; // microseconds
int sSockFd;
uint16_t sPortOffset;
static void handleSignal(int aSignal)
{
OT_UNUSED_VARIABLE(aSignal);
gTerminate = true;
}
void otSimSendEvent(const struct Event *aEvent)
{
ssize_t rval;
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &sockaddr.sin_addr);
sockaddr.sin_port = htons(9000 + sPortOffset);
rval = sendto(sSockFd, aEvent, offsetof(struct Event, mData) + aEvent->mDataLength, 0, (struct sockaddr *)&sockaddr,
sizeof(sockaddr));
if (rval < 0)
{
perror("sendto");
exit(EXIT_FAILURE);
}
}
static void receiveEvent(otInstance *aInstance)
{
struct Event event;
ssize_t rval = recvfrom(sSockFd, (char *)&event, sizeof(event), 0, NULL, NULL);
if (rval < 0 || (uint16_t)rval < offsetof(struct Event, mData))
{
perror("recvfrom");
exit(EXIT_FAILURE);
}
platformAlarmAdvanceNow(event.mDelay);
switch (event.mEvent)
{
case OT_SIM_EVENT_ALARM_FIRED:
break;
case OT_SIM_EVENT_RADIO_RECEIVED:
platformRadioReceive(aInstance, event.mData, event.mDataLength);
break;
case OT_SIM_EVENT_UART_WRITE:
otPlatUartReceived(event.mData, event.mDataLength);
break;
default:
assert(false);
}
}
static void platformSendSleepEvent(void)
{
struct Event event;
assert(platformAlarmGetNext() > 0);
event.mDelay = (uint64_t)platformAlarmGetNext();
event.mEvent = OT_SIM_EVENT_ALARM_FIRED;
event.mDataLength = 0;
otSimSendEvent(&event);
}
#if OPENTHREAD_SIMULATION_VIRTUAL_TIME_UART
void platformUartRestore(void)
{
}
otError otPlatUartEnable(void)
{
return OT_ERROR_NONE;
}
otError otPlatUartDisable(void)
{
return OT_ERROR_NONE;
}
otError otPlatUartSend(const uint8_t *aData, uint16_t aLength)
{
otError error = OT_ERROR_NONE;
struct Event event;
event.mDelay = 0;
event.mEvent = OT_SIM_EVENT_UART_WRITE;
event.mDataLength = aLength;
memcpy(event.mData, aData, aLength);
otSimSendEvent(&event);
otPlatUartSendDone();
return error;
}
otError otPlatUartFlush(void)
{
return OT_ERROR_NOT_IMPLEMENTED;
}
#endif // OPENTHREAD_SIMULATION_VIRTUAL_TIME_UART
static void socket_init(void)
{
struct sockaddr_in sockaddr;
char * offset;
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
offset = getenv("PORT_OFFSET");
if (offset)
{
char *endptr;
sPortOffset = (uint16_t)strtol(offset, &endptr, 0);
if (*endptr != '\0')
{
fprintf(stderr, "Invalid PORT_OFFSET: %s\n", offset);
exit(EXIT_FAILURE);
}
sPortOffset *= (MAX_NETWORK_SIZE + 1);
}
sockaddr.sin_port = htons((uint16_t)(9000 + sPortOffset + gNodeId));
sockaddr.sin_addr.s_addr = INADDR_ANY;
sSockFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sSockFd == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
if (bind(sSockFd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == -1)
{
perror("bind");
exit(EXIT_FAILURE);
}
}
void otSysInit(int argc, char *argv[])
{
char *endptr;
if (gPlatformPseudoResetWasRequested)
{
gPlatformPseudoResetWasRequested = false;
return;
}
if (argc != 2)
{
exit(EXIT_FAILURE);
}
openlog(basename(argv[0]), LOG_PID, LOG_USER);
setlogmask(setlogmask(0) & LOG_UPTO(LOG_NOTICE));
gArgumentsCount = argc;
gArguments = argv;
gNodeId = (uint32_t)strtol(argv[1], &endptr, 0);
if (*endptr != '\0' || gNodeId < 1 || gNodeId > MAX_NETWORK_SIZE)
{
fprintf(stderr, "Invalid NodeId: %s\n", argv[1]);
exit(EXIT_FAILURE);
}
socket_init();
platformAlarmInit(1);
platformRadioInit();
platformRandomInit();
signal(SIGTERM, &handleSignal);
signal(SIGHUP, &handleSignal);
}
bool otSysPseudoResetWasRequested(void)
{
return gPlatformPseudoResetWasRequested;
}
void otSysDeinit(void)
{
close(sSockFd);
}
void otSysProcessDrivers(otInstance *aInstance)
{
fd_set read_fds;
fd_set write_fds;
fd_set error_fds;
int max_fd = -1;
int rval;
if (gTerminate)
{
exit(0);
}
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_ZERO(&error_fds);
FD_SET(sSockFd, &read_fds);
max_fd = sSockFd;
#if OPENTHREAD_SIMULATION_VIRTUAL_TIME_UART == 0
platformUartUpdateFdSet(&read_fds, &write_fds, &error_fds, &max_fd);
#endif
if (!otTaskletsArePending(aInstance) && platformAlarmGetNext() > 0 && !platformRadioIsTransmitPending())
{
platformSendSleepEvent();
rval = select(max_fd + 1, &read_fds, &write_fds, &error_fds, NULL);
if ((rval < 0) && (errno != EINTR))
{
perror("select");
exit(EXIT_FAILURE);
}
if (rval > 0 && FD_ISSET(sSockFd, &read_fds))
{
receiveEvent(aInstance);
}
}
platformAlarmProcess(aInstance);
platformRadioProcess(aInstance, &read_fds, &write_fds);
#if OPENTHREAD_SIMULATION_VIRTUAL_TIME_UART == 0
platformUartProcess();
#endif
}
#if OPENTHREAD_CONFIG_OTNS_ENABLE
void otPlatOtnsStatus(const char *aStatus)
{
struct Event event;
uint16_t statusLength = (uint16_t)strlen(aStatus);
assert(statusLength < sizeof(event.mData));
memcpy(event.mData, aStatus, statusLength);
event.mDataLength = statusLength;
event.mDelay = 0;
event.mEvent = OT_SIM_EVENT_OTNS_STATUS_PUSH;
otSimSendEvent(&event);
}
#endif // OPENTHREAD_CONFIG_OTNS_ENABLE
#endif // OPENTHREAD_SIMULATION_VIRTUAL_TIME
| bsd-3-clause |
shengren/magma-1.6.1 | testing/testing_zgeqrf_gpu.cpp | 2 | 13437 | /*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@precisions normal z -> c d s
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "flops.h"
#include "magma.h"
#include "magma_lapack.h"
#include "testings.h"
/* ////////////////////////////////////////////////////////////////////////////
-- Testing zgeqrf
*/
int main( int argc, char** argv)
{
TESTING_INIT();
const double d_neg_one = MAGMA_D_NEG_ONE;
const double d_one = MAGMA_D_ONE;
const magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
const magmaDoubleComplex c_one = MAGMA_Z_ONE;
const magmaDoubleComplex c_zero = MAGMA_Z_ZERO;
const magma_int_t ione = 1;
real_Double_t gflops, gpu_perf, gpu_time, cpu_perf=0, cpu_time=0;
double Anorm, error=0, error2=0;
magmaDoubleComplex *h_A, *h_R, *tau, *h_work, tmp[1];
magmaDoubleComplex_ptr d_A, dT;
magma_int_t M, N, n2, lda, ldda, lwork, info, min_mn, nb, size;
magma_int_t ISEED[4] = {0,0,0,1};
magma_opts opts;
parse_opts( argc, argv, &opts );
magma_int_t status = 0;
double tol = opts.tolerance * lapackf77_dlamch("E");
printf( "version %d\n", (int) opts.version );
if ( opts.version == 2 ) {
printf(" M N CPU GFlop/s (sec) GPU GFlop/s (sec) |R - Q^H*A| |I - Q^H*Q|\n");
printf("===============================================================================\n");
}
else {
printf(" M N CPU GFlop/s (sec) GPU GFlop/s (sec) |b - A*x|\n");
printf("================================================================\n");
}
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
M = opts.msize[itest];
N = opts.nsize[itest];
min_mn = min(M, N);
lda = M;
n2 = lda*N;
ldda = ((M+31)/32)*32;
gflops = FLOPS_ZGEQRF( M, N ) / 1e9;
// query for workspace size
lwork = -1;
lapackf77_zgeqrf(&M, &N, NULL, &M, NULL, tmp, &lwork, &info);
lwork = (magma_int_t)MAGMA_Z_REAL( tmp[0] );
TESTING_MALLOC_CPU( tau, magmaDoubleComplex, min_mn );
TESTING_MALLOC_CPU( h_A, magmaDoubleComplex, n2 );
TESTING_MALLOC_CPU( h_work, magmaDoubleComplex, lwork );
TESTING_MALLOC_PIN( h_R, magmaDoubleComplex, n2 );
TESTING_MALLOC_DEV( d_A, magmaDoubleComplex, ldda*N );
/* Initialize the matrix */
lapackf77_zlarnv( &ione, ISEED, &n2, h_A );
lapackf77_zlacpy( MagmaUpperLowerStr, &M, &N, h_A, &lda, h_R, &lda );
magma_zsetmatrix( M, N, h_R, lda, d_A, ldda );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
gpu_time = magma_wtime();
if ( opts.version == 2 ) {
// LAPACK complaint arguments
magma_zgeqrf2_gpu( M, N, d_A, ldda, tau, &info );
}
else {
nb = magma_get_zgeqrf_nb( M );
size = (2*min(M, N) + (N+31)/32*32 )*nb;
TESTING_MALLOC_DEV( dT, magmaDoubleComplex, size );
if ( opts.version == 1 ) {
// stores dT, V blocks have zeros, R blocks inverted & stored in dT
magma_zgeqrf_gpu( M, N, d_A, ldda, tau, dT, &info );
}
#ifdef HAVE_CUBLAS
else if ( opts.version == 3 ) {
// stores dT, V blocks have zeros, R blocks stored in dT
magma_zgeqrf3_gpu( M, N, d_A, ldda, tau, dT, &info );
}
#endif
else {
printf( "Unknown version %d\n", (int) opts.version );
exit(1);
}
}
gpu_time = magma_wtime() - gpu_time;
gpu_perf = gflops / gpu_time;
if (info != 0)
printf("magma_zgeqrf returned error %d: %s.\n",
(int) info, magma_strerror( info ));
if ( opts.check && opts.version == 2 ) {
/* =====================================================================
Check the result, following zqrt01 except using the reduced Q.
This works for any M,N (square, tall, wide).
Only for version 2, which has LAPACK complaint output.
=================================================================== */
magma_zgetmatrix( M, N, d_A, ldda, h_R, lda );
magma_int_t ldq = M;
magma_int_t ldr = min_mn;
magmaDoubleComplex *Q, *R;
double *work;
TESTING_MALLOC_CPU( Q, magmaDoubleComplex, ldq*min_mn ); // M by K
TESTING_MALLOC_CPU( R, magmaDoubleComplex, ldr*N ); // K by N
TESTING_MALLOC_CPU( work, double, min_mn );
// generate M by K matrix Q, where K = min(M,N)
lapackf77_zlacpy( "Lower", &M, &min_mn, h_R, &lda, Q, &ldq );
lapackf77_zungqr( &M, &min_mn, &min_mn, Q, &ldq, tau, h_work, &lwork, &info );
assert( info == 0 );
// copy K by N matrix R
lapackf77_zlaset( "Lower", &min_mn, &N, &c_zero, &c_zero, R, &ldr );
lapackf77_zlacpy( "Upper", &min_mn, &N, h_R, &lda, R, &ldr );
// error = || R - Q^H*A || / (N * ||A||)
blasf77_zgemm( "Conj", "NoTrans", &min_mn, &N, &M,
&c_neg_one, Q, &ldq, h_A, &lda, &c_one, R, &ldr );
Anorm = lapackf77_zlange( "1", &M, &N, h_A, &lda, work );
error = lapackf77_zlange( "1", &min_mn, &N, R, &ldr, work );
if ( N > 0 && Anorm > 0 )
error /= (N*Anorm);
// set R = I (K by K identity), then R = I - Q^H*Q
// error = || I - Q^H*Q || / N
lapackf77_zlaset( "Upper", &min_mn, &min_mn, &c_zero, &c_one, R, &ldr );
blasf77_zherk( "Upper", "Conj", &min_mn, &M, &d_neg_one, Q, &ldq, &d_one, R, &ldr );
error2 = lapackf77_zlanhe( "1", "Upper", &min_mn, R, &ldr, work );
if ( N > 0 )
error2 /= N;
TESTING_FREE_CPU( Q ); Q = NULL;
TESTING_FREE_CPU( R ); R = NULL;
TESTING_FREE_CPU( work ); work = NULL;
}
else if ( opts.check && M >= N ) {
/* =====================================================================
Check the result by solving consistent linear system, A*x = b.
Only for versions 1 & 3 with M >= N.
=================================================================== */
magma_int_t lwork;
magmaDoubleComplex *x, *b, *hwork;
magmaDoubleComplex_ptr d_B;
const magmaDoubleComplex c_zero = MAGMA_Z_ZERO;
const magmaDoubleComplex c_one = MAGMA_Z_ONE;
const magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
const magma_int_t ione = 1;
// initialize RHS, b = A*random
TESTING_MALLOC_CPU( x, magmaDoubleComplex, N );
TESTING_MALLOC_CPU( b, magmaDoubleComplex, M );
lapackf77_zlarnv( &ione, ISEED, &N, x );
blasf77_zgemv( "Notrans", &M, &N, &c_one, h_A, &lda, x, &ione, &c_zero, b, &ione );
// copy to GPU
TESTING_MALLOC_DEV( d_B, magmaDoubleComplex, M );
magma_zsetvector( M, b, 1, d_B, 1 );
if ( opts.version == 1 ) {
// allocate hwork
magma_zgeqrs_gpu( M, N, 1,
d_A, ldda, tau, dT,
d_B, M, tmp, -1, &info );
lwork = (magma_int_t)MAGMA_Z_REAL( tmp[0] );
TESTING_MALLOC_CPU( hwork, magmaDoubleComplex, lwork );
// solve linear system
magma_zgeqrs_gpu( M, N, 1,
d_A, ldda, tau, dT,
d_B, M, hwork, lwork, &info );
if (info != 0)
printf("magma_zgeqrs returned error %d: %s.\n",
(int) info, magma_strerror( info ));
TESTING_FREE_CPU( hwork );
}
#ifdef HAVE_CUBLAS
else if ( opts.version == 3 ) {
// allocate hwork
magma_zgeqrs3_gpu( M, N, 1,
d_A, ldda, tau, dT,
d_B, M, tmp, -1, &info );
lwork = (magma_int_t)MAGMA_Z_REAL( tmp[0] );
TESTING_MALLOC_CPU( hwork, magmaDoubleComplex, lwork );
// solve linear system
magma_zgeqrs3_gpu( M, N, 1,
d_A, ldda, tau, dT,
d_B, M, hwork, lwork, &info );
if (info != 0)
printf("magma_zgeqrs3 returned error %d: %s.\n",
(int) info, magma_strerror( info ));
TESTING_FREE_CPU( hwork );
}
#endif
else {
printf( "Unknown version %d\n", (int) opts.version );
exit(1);
}
magma_zgetvector( N, d_B, 1, x, 1 );
// compute r = Ax - b, saved in b
blasf77_zgemv( "Notrans", &M, &N, &c_one, h_A, &lda, x, &ione, &c_neg_one, b, &ione );
// compute residual |Ax - b| / (n*|A|*|x|)
double norm_x, norm_A, norm_r, work[1];
norm_A = lapackf77_zlange( "F", &M, &N, h_A, &lda, work );
norm_r = lapackf77_zlange( "F", &M, &ione, b, &M, work );
norm_x = lapackf77_zlange( "F", &N, &ione, x, &N, work );
TESTING_FREE_CPU( x );
TESTING_FREE_CPU( b );
TESTING_FREE_DEV( d_B );
error = norm_r / (N * norm_A * norm_x);
}
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
if ( opts.lapack ) {
cpu_time = magma_wtime();
lapackf77_zgeqrf(&M, &N, h_A, &lda, tau, h_work, &lwork, &info);
cpu_time = magma_wtime() - cpu_time;
cpu_perf = gflops / cpu_time;
if (info != 0)
printf("lapackf77_zgeqrf returned error %d: %s.\n",
(int) info, magma_strerror( info ));
}
/* =====================================================================
Print performance and error.
=================================================================== */
printf("%5d %5d ", (int) M, (int) N );
if ( opts.lapack ) {
printf( "%7.2f (%7.2f)", cpu_perf, cpu_time );
}
else {
printf(" --- ( --- )" );
}
printf( " %7.2f (%7.2f) ", gpu_perf, gpu_time );
if ( opts.check ) {
if ( opts.version == 2 ) {
bool okay = (error < tol && error2 < tol);
status += ! okay;
printf( "%11.2e %11.2e %s\n", error, error2, (okay ? "ok" : "failed") );
}
else if ( M >= N ) {
bool okay = (error < tol);
status += ! okay;
printf( "%10.2e %s\n", error, (okay ? "ok" : "failed") );
}
else {
printf( "(error check only for M >= N)\n" );
}
}
else {
printf( " ---\n" );
}
TESTING_FREE_CPU( tau );
TESTING_FREE_CPU( h_A );
TESTING_FREE_CPU( h_work );
TESTING_FREE_PIN( h_R );
TESTING_FREE_DEV( d_A );
if ( opts.version != 2 )
TESTING_FREE_DEV( dT );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
TESTING_FINALIZE();
return status;
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE134_Uncontrolled_Format_String/s04/CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64a.c | 2 | 4780 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64a.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-64a.tmpl.c
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: console Read input from the console
* GoodSource: Copy a fixed string into data
* Sinks: fprintf
* GoodSink: fwprintf with "%s" as the second argument and data as the third
* BadSink : fwprintf with data as the second argument
* Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifndef OMITBAD
/* bad function declaration */
void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_badSink(void * dataVoidPtr);
void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = wcslen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgetws() */
dataLen = wcslen(data);
if (dataLen > 0 && data[dataLen-1] == L'\n')
{
data[dataLen-1] = L'\0';
}
}
else
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
}
}
CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_badSink(&data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_goodG2BSink(void * dataVoidPtr);
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
wcscpy(data, L"fixedstringtest");
CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_goodG2BSink(&data);
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_goodB2GSink(void * dataVoidPtr);
static void goodB2G()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = wcslen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgetws() */
dataLen = wcslen(data);
if (dataLen > 0 && data[dataLen-1] == L'\n')
{
data[dataLen-1] = L'\0';
}
}
else
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
}
}
CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64b_goodB2GSink(&data);
}
void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64_good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_64_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
youtube/cobalt | third_party/angle/src/tests/gl_tests/LinkAndRelinkTest.cpp | 2 | 13520 | //
// Copyright 2017 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// LinkAndRelinkFailureTest:
// Link and relink failure tests for rendering pipeline and compute pipeline.
#include <vector>
#include "test_utils/ANGLETest.h"
#include "test_utils/gl_raii.h"
using namespace angle;
namespace
{
class LinkAndRelinkTest : public ANGLETest
{
protected:
LinkAndRelinkTest() {}
};
class LinkAndRelinkTestES31 : public ANGLETest
{
protected:
LinkAndRelinkTestES31() {}
};
// When a program link or relink fails, if you try to install the unsuccessfully
// linked program (via UseProgram) and start rendering or dispatch compute,
// We can not always report INVALID_OPERATION for rendering/compute pipeline.
// The result depends on the previous state: Whether a valid program is
// installed in current GL state before the link.
// If a program successfully relinks when it is in use, the program might
// change from a rendering program to a compute program in theory,
// or vice versa.
// When program link fails and no valid rendering program is installed in the GL
// state before the link, it should report an error for UseProgram and
// DrawArrays/DrawElements.
TEST_P(LinkAndRelinkTest, RenderingProgramFailsWithoutProgramInstalled)
{
glUseProgram(0);
GLuint program = glCreateProgram();
glLinkProgram(program);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
glUseProgram(program);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
// When program link or relink fails and a valid rendering program is installed
// in the GL state before the link, using the failed program via UseProgram
// should report an error, but starting rendering should succeed.
// However, dispatching compute always fails.
TEST_P(LinkAndRelinkTest, RenderingProgramFailsWithProgramInstalled)
{
// Install a render program in current GL state via UseProgram, then render.
// It should succeed.
constexpr char kVS[] = "void main() {}";
constexpr char kFS[] = "void main() {}";
GLuint program = glCreateProgram();
GLuint vs = CompileShader(GL_VERTEX_SHADER, kVS);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, kFS);
EXPECT_NE(0u, vs);
EXPECT_NE(0u, fs);
glAttachShader(program, vs);
glDeleteShader(vs);
glAttachShader(program, fs);
glDeleteShader(fs);
glLinkProgram(program);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glUseProgram(program);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Link failure, and a valid program has been installed in the GL state.
GLuint programNull = glCreateProgram();
glLinkProgram(programNull);
glGetProgramiv(programNull, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
// Starting rendering should succeed.
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully linked program should report an error.
glUseProgram(programNull);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully linked program, that program should not
// replace the program binary residing in the GL state. It will not make
// the installed program invalid either, like what UseProgram(0) can do.
// So, starting rendering should succeed.
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// We try to relink the installed program, but make it fail.
// No vertex shader, relink fails.
glDetachShader(program, vs);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
EXPECT_GL_NO_ERROR();
// Starting rendering should succeed.
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully relinked program should report an error.
glUseProgram(program);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully relinked program, that program should not
// replace the program binary residing in the GL state. It will not make
// the installed program invalid either, like what UseProgram(0) can do.
// So, starting rendering should succeed.
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
// Tests uniform default values.
TEST_P(LinkAndRelinkTest, UniformDefaultValues)
{
// TODO(anglebug.com/3969): Understand why rectangle texture CLs made this fail.
ANGLE_SKIP_TEST_IF(IsOzone() && IsIntel());
constexpr char kFS[] = R"(precision mediump float;
uniform vec4 u_uniform;
bool isZero(vec4 value) {
return value == vec4(0,0,0,0);
}
void main()
{
gl_FragColor = isZero(u_uniform) ? vec4(0, 1, 0, 1) : vec4(1, 0, 0, 1);
})";
ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Simple(), kFS);
glUseProgram(program);
drawQuad(program, essl1_shaders::PositionAttrib(), 0.5f, 1.0f, true);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);
GLint loc = glGetUniformLocation(program, "u_uniform");
ASSERT_NE(-1, loc);
glUniform4f(loc, 0.1f, 0.2f, 0.3f, 0.4f);
drawQuad(program, essl1_shaders::PositionAttrib(), 0.5f, 1.0f, true);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);
glLinkProgram(program);
ASSERT_GL_NO_ERROR();
drawQuad(program, essl1_shaders::PositionAttrib(), 0.5f, 1.0f, true);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);
}
// When program link fails and no valid compute program is installed in the GL
// state before the link, it should report an error for UseProgram and
// DispatchCompute.
TEST_P(LinkAndRelinkTestES31, ComputeProgramFailsWithoutProgramInstalled)
{
glUseProgram(0);
GLuint program = glCreateProgram();
glLinkProgram(program);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
glUseProgram(program);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
// When program link or relink fails and a valid compute program is installed in
// the GL state before the link, using the failed program via UseProgram should
// report an error, but dispatching compute should succeed.
// However, starting rendering always fails.
TEST_P(LinkAndRelinkTestES31, ComputeProgramFailsWithProgramInstalled)
{
// Install a compute program in the GL state via UseProgram, then dispatch
// compute. It should succeed.
constexpr char kCS[] =
R"(#version 310 es
layout(local_size_x=1) in;
void main()
{
})";
GLuint program = glCreateProgram();
GLuint cs = CompileShader(GL_COMPUTE_SHADER, kCS);
EXPECT_NE(0u, cs);
glAttachShader(program, cs);
glDeleteShader(cs);
glLinkProgram(program);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glUseProgram(program);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Link failure, and a valid program has been installed in the GL state.
GLuint programNull = glCreateProgram();
glLinkProgram(programNull);
glGetProgramiv(programNull, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
// Dispatching compute should succeed.
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully linked program should report an error.
glUseProgram(programNull);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully linked program, that program should not
// replace the program binary residing in the GL state. It will not make
// the installed program invalid either, like what UseProgram(0) can do.
// So, dispatching compute should succeed.
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// We try to relink the installed program, but make it fail.
// No compute shader, relink fails.
glDetachShader(program, cs);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_FALSE(linkStatus);
EXPECT_GL_NO_ERROR();
// Dispatching compute should succeed.
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully relinked program should report an error.
glUseProgram(program);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
// Using the unsuccessfully relinked program, that program should not
// replace the program binary residing in the GL state. It will not make
// the installed program invalid either, like what UseProgram(0) can do.
// So, dispatching compute should succeed.
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
// If you compile and link a compute program successfully and use the program,
// then dispatching compute can succeed, while starting rendering will fail.
// If you relink the compute program to a rendering program when it is in use,
// then dispatching compute will fail, but starting rendering can succeed.
TEST_P(LinkAndRelinkTestES31, RelinkProgramSucceedsFromComputeToRendering)
{
constexpr char kCS[] = R"(#version 310 es
layout(local_size_x=1) in;
void main()
{
})";
GLuint program = glCreateProgram();
GLuint cs = CompileShader(GL_COMPUTE_SHADER, kCS);
EXPECT_NE(0u, cs);
glAttachShader(program, cs);
glDeleteShader(cs);
glLinkProgram(program);
glDetachShader(program, cs);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glUseProgram(program);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
constexpr char kVS[] = "void main() {}";
constexpr char kFS[] = "void main() {}";
GLuint vs = CompileShader(GL_VERTEX_SHADER, kVS);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, kFS);
EXPECT_NE(0u, vs);
EXPECT_NE(0u, fs);
glAttachShader(program, vs);
glDeleteShader(vs);
glAttachShader(program, fs);
glDeleteShader(fs);
glLinkProgram(program);
glDetachShader(program, vs);
glDetachShader(program, fs);
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
// If you compile and link a rendering program successfully and use the program,
// then starting rendering can succeed, while dispatching compute will fail.
// If you relink the rendering program to a compute program when it is in use,
// then starting rendering will fail, but dispatching compute can succeed.
TEST_P(LinkAndRelinkTestES31, RelinkProgramSucceedsFromRenderingToCompute)
{
constexpr char kVS[] = "void main() {}";
constexpr char kFS[] = "void main() {}";
GLuint program = glCreateProgram();
GLuint vs = CompileShader(GL_VERTEX_SHADER, kVS);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, kFS);
EXPECT_NE(0u, vs);
EXPECT_NE(0u, fs);
glAttachShader(program, vs);
glDeleteShader(vs);
glAttachShader(program, fs);
glDeleteShader(fs);
glLinkProgram(program);
glDetachShader(program, vs);
glDetachShader(program, fs);
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glUseProgram(program);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
constexpr char kCS[] = R"(#version 310 es
layout(local_size_x=1) in;
void main()
{
})";
GLuint cs = CompileShader(GL_COMPUTE_SHADER, kCS);
EXPECT_NE(0u, cs);
glAttachShader(program, cs);
glDeleteShader(cs);
glLinkProgram(program);
glDetachShader(program, cs);
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_GL_TRUE(linkStatus);
EXPECT_GL_NO_ERROR();
glDispatchCompute(8, 4, 2);
EXPECT_GL_NO_ERROR();
glDrawArrays(GL_POINTS, 0, 1);
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
ANGLE_INSTANTIATE_TEST_ES2_AND_ES3(LinkAndRelinkTest);
ANGLE_INSTANTIATE_TEST_ES31(LinkAndRelinkTestES31);
} // namespace
| bsd-3-clause |
youtube/cobalt_sandbox | third_party/skia/modules/skottie/src/layers/ShapeLayer.cpp | 2 | 28504 | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skottie/src/SkottiePriv.h"
#include "include/core/SkPath.h"
#include "modules/skottie/src/SkottieAdapter.h"
#include "modules/skottie/src/SkottieJson.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGDraw.h"
#include "modules/sksg/include/SkSGGeometryTransform.h"
#include "modules/sksg/include/SkSGGradient.h"
#include "modules/sksg/include/SkSGGroup.h"
#include "modules/sksg/include/SkSGMerge.h"
#include "modules/sksg/include/SkSGPaint.h"
#include "modules/sksg/include/SkSGPath.h"
#include "modules/sksg/include/SkSGRect.h"
#include "modules/sksg/include/SkSGRenderEffect.h"
#include "modules/sksg/include/SkSGRoundEffect.h"
#include "modules/sksg/include/SkSGTransform.h"
#include "modules/sksg/include/SkSGTrimEffect.h"
#include "src/utils/SkJSON.h"
#include <algorithm>
#include <iterator>
namespace skottie {
namespace internal {
namespace {
sk_sp<sksg::GeometryNode> AttachPathGeometry(const skjson::ObjectValue& jpath,
const AnimationBuilder* abuilder) {
return abuilder->attachPath(jpath["ks"]);
}
sk_sp<sksg::GeometryNode> AttachRRectGeometry(const skjson::ObjectValue& jrect,
const AnimationBuilder* abuilder) {
auto rect_node = sksg::RRect::Make();
rect_node->setDirection(ParseDefault(jrect["d"], -1) == 3 ? SkPath::kCCW_Direction
: SkPath::kCW_Direction);
rect_node->setInitialPointIndex(2); // starting point: (Right, Top - radius.y)
auto adapter = sk_make_sp<RRectAdapter>(rect_node);
auto p_attached = abuilder->bindProperty<VectorValue>(jrect["p"],
[adapter](const VectorValue& p) {
adapter->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
});
auto s_attached = abuilder->bindProperty<VectorValue>(jrect["s"],
[adapter](const VectorValue& s) {
adapter->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
});
auto r_attached = abuilder->bindProperty<ScalarValue>(jrect["r"],
[adapter](const ScalarValue& r) {
adapter->setRadius(SkSize::Make(r, r));
});
if (!p_attached && !s_attached && !r_attached) {
return nullptr;
}
return rect_node;
}
sk_sp<sksg::GeometryNode> AttachEllipseGeometry(const skjson::ObjectValue& jellipse,
const AnimationBuilder* abuilder) {
auto rect_node = sksg::RRect::Make();
rect_node->setDirection(ParseDefault(jellipse["d"], -1) == 3 ? SkPath::kCCW_Direction
: SkPath::kCW_Direction);
rect_node->setInitialPointIndex(1); // starting point: (Center, Top)
auto adapter = sk_make_sp<RRectAdapter>(rect_node);
auto p_attached = abuilder->bindProperty<VectorValue>(jellipse["p"],
[adapter](const VectorValue& p) {
adapter->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
});
auto s_attached = abuilder->bindProperty<VectorValue>(jellipse["s"],
[adapter](const VectorValue& s) {
const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
adapter->setSize(sz);
adapter->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
});
if (!p_attached && !s_attached) {
return nullptr;
}
return rect_node;
}
sk_sp<sksg::GeometryNode> AttachPolystarGeometry(const skjson::ObjectValue& jstar,
const AnimationBuilder* abuilder) {
static constexpr PolyStarAdapter::Type gTypes[] = {
PolyStarAdapter::Type::kStar, // "sy": 1
PolyStarAdapter::Type::kPoly, // "sy": 2
};
const auto type = ParseDefault<size_t>(jstar["sy"], 0) - 1;
if (type >= SK_ARRAY_COUNT(gTypes)) {
abuilder->log(Logger::Level::kError, &jstar, "Unknown polystar type.");
return nullptr;
}
auto path_node = sksg::Path::Make();
auto adapter = sk_make_sp<PolyStarAdapter>(path_node, gTypes[type]);
abuilder->bindProperty<VectorValue>(jstar["p"],
[adapter](const VectorValue& p) {
adapter->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
});
abuilder->bindProperty<ScalarValue>(jstar["pt"],
[adapter](const ScalarValue& pt) {
adapter->setPointCount(pt);
});
abuilder->bindProperty<ScalarValue>(jstar["ir"],
[adapter](const ScalarValue& ir) {
adapter->setInnerRadius(ir);
});
abuilder->bindProperty<ScalarValue>(jstar["or"],
[adapter](const ScalarValue& otr) {
adapter->setOuterRadius(otr);
});
abuilder->bindProperty<ScalarValue>(jstar["is"],
[adapter](const ScalarValue& is) {
adapter->setInnerRoundness(is);
});
abuilder->bindProperty<ScalarValue>(jstar["os"],
[adapter](const ScalarValue& os) {
adapter->setOuterRoundness(os);
});
abuilder->bindProperty<ScalarValue>(jstar["r"],
[adapter](const ScalarValue& r) {
adapter->setRotation(r);
});
return path_node;
}
sk_sp<sksg::ShaderPaint> AttachGradient(const skjson::ObjectValue& jgrad,
const AnimationBuilder* abuilder) {
const skjson::ObjectValue* stops = jgrad["g"];
if (!stops)
return nullptr;
const auto stopCount = ParseDefault<int>((*stops)["p"], -1);
if (stopCount < 0)
return nullptr;
sk_sp<sksg::Gradient> gradient_node;
sk_sp<GradientAdapter> adapter;
if (ParseDefault<int>(jgrad["t"], 1) == 1) {
auto linear_node = sksg::LinearGradient::Make();
adapter = sk_make_sp<LinearGradientAdapter>(linear_node, stopCount);
gradient_node = std::move(linear_node);
} else {
auto radial_node = sksg::RadialGradient::Make();
adapter = sk_make_sp<RadialGradientAdapter>(radial_node, stopCount);
// TODO: highlight, angle
gradient_node = std::move(radial_node);
}
abuilder->bindProperty<VectorValue>(
(*stops)["k"], [adapter](const VectorValue& stops) { adapter->setStops(stops); });
abuilder->bindProperty<VectorValue>(jgrad["s"],
[adapter](const VectorValue& s) {
adapter->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
});
abuilder->bindProperty<VectorValue>(jgrad["e"],
[adapter](const VectorValue& e) {
adapter->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
});
return sksg::ShaderPaint::Make(std::move(gradient_node));
}
sk_sp<sksg::PaintNode> AttachPaint(const skjson::ObjectValue& jpaint,
const AnimationBuilder* abuilder,
sk_sp<sksg::PaintNode> paint_node) {
if (paint_node) {
paint_node->setAntiAlias(true);
abuilder->bindProperty<ScalarValue>(jpaint["o"],
[paint_node](const ScalarValue& o) {
// BM opacity is [0..100]
paint_node->setOpacity(o * 0.01f);
});
}
return paint_node;
}
sk_sp<sksg::PaintNode> AttachStroke(const skjson::ObjectValue& jstroke,
const AnimationBuilder* abuilder,
sk_sp<sksg::PaintNode> stroke_node) {
if (!stroke_node)
return nullptr;
stroke_node->setStyle(SkPaint::kStroke_Style);
abuilder->bindProperty<ScalarValue>(jstroke["w"],
[stroke_node](const ScalarValue& w) {
stroke_node->setStrokeWidth(w);
});
stroke_node->setStrokeMiter(ParseDefault<SkScalar>(jstroke["ml"], 4.0f));
static constexpr SkPaint::Join gJoins[] = {
SkPaint::kMiter_Join,
SkPaint::kRound_Join,
SkPaint::kBevel_Join,
};
stroke_node->setStrokeJoin(gJoins[SkTMin<size_t>(ParseDefault<size_t>(jstroke["lj"], 1) - 1,
SK_ARRAY_COUNT(gJoins) - 1)]);
static constexpr SkPaint::Cap gCaps[] = {
SkPaint::kButt_Cap,
SkPaint::kRound_Cap,
SkPaint::kSquare_Cap,
};
stroke_node->setStrokeCap(gCaps[SkTMin<size_t>(ParseDefault<size_t>(jstroke["lc"], 1) - 1,
SK_ARRAY_COUNT(gCaps) - 1)]);
return stroke_node;
}
sk_sp<sksg::PaintNode> AttachColorFill(const skjson::ObjectValue& jfill,
const AnimationBuilder* abuilder) {
return AttachPaint(jfill, abuilder, abuilder->attachColor(jfill, "c"));
}
sk_sp<sksg::PaintNode> AttachGradientFill(const skjson::ObjectValue& jfill,
const AnimationBuilder* abuilder) {
return AttachPaint(jfill, abuilder, AttachGradient(jfill, abuilder));
}
sk_sp<sksg::PaintNode> AttachColorStroke(const skjson::ObjectValue& jstroke,
const AnimationBuilder* abuilder) {
return AttachStroke(jstroke, abuilder, AttachPaint(jstroke, abuilder,
abuilder->attachColor(jstroke, "c")));
}
sk_sp<sksg::PaintNode> AttachGradientStroke(const skjson::ObjectValue& jstroke,
const AnimationBuilder* abuilder) {
return AttachStroke(jstroke, abuilder, AttachPaint(jstroke, abuilder,
AttachGradient(jstroke, abuilder)));
}
sk_sp<sksg::Merge> Merge(std::vector<sk_sp<sksg::GeometryNode>>&& geos, sksg::Merge::Mode mode) {
std::vector<sksg::Merge::Rec> merge_recs;
merge_recs.reserve(geos.size());
for (auto& geo : geos) {
merge_recs.push_back(
{std::move(geo), merge_recs.empty() ? sksg::Merge::Mode::kMerge : mode});
}
return sksg::Merge::Make(std::move(merge_recs));
}
std::vector<sk_sp<sksg::GeometryNode>> AttachMergeGeometryEffect(
const skjson::ObjectValue& jmerge, const AnimationBuilder*,
std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
static constexpr sksg::Merge::Mode gModes[] = {
sksg::Merge::Mode::kMerge, // "mm": 1
sksg::Merge::Mode::kUnion, // "mm": 2
sksg::Merge::Mode::kDifference, // "mm": 3
sksg::Merge::Mode::kIntersect, // "mm": 4
sksg::Merge::Mode::kXOR , // "mm": 5
};
const auto mode = gModes[SkTMin<size_t>(ParseDefault<size_t>(jmerge["mm"], 1) - 1,
SK_ARRAY_COUNT(gModes) - 1)];
std::vector<sk_sp<sksg::GeometryNode>> merged;
merged.push_back(Merge(std::move(geos), mode));
return merged;
}
std::vector<sk_sp<sksg::GeometryNode>> AttachTrimGeometryEffect(
const skjson::ObjectValue& jtrim, const AnimationBuilder* abuilder,
std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
enum class Mode {
kParallel, // "m": 1 (Trim Multiple Shapes: Simultaneously)
kSerial, // "m": 2 (Trim Multiple Shapes: Individually)
} gModes[] = {Mode::kParallel, Mode::kSerial};
const auto mode = gModes[SkTMin<size_t>(ParseDefault<size_t>(jtrim["m"], 1) - 1,
SK_ARRAY_COUNT(gModes) - 1)];
std::vector<sk_sp<sksg::GeometryNode>> inputs;
if (mode == Mode::kSerial) {
inputs.push_back(Merge(std::move(geos), sksg::Merge::Mode::kMerge));
} else {
inputs = std::move(geos);
}
std::vector<sk_sp<sksg::GeometryNode>> trimmed;
trimmed.reserve(inputs.size());
for (const auto& i : inputs) {
auto trimEffect = sksg::TrimEffect::Make(i);
trimmed.push_back(trimEffect);
const auto adapter = sk_make_sp<TrimEffectAdapter>(std::move(trimEffect));
abuilder->bindProperty<ScalarValue>(jtrim["s"],
[adapter](const ScalarValue& s) {
adapter->setStart(s);
});
abuilder->bindProperty<ScalarValue>(jtrim["e"],
[adapter](const ScalarValue& e) {
adapter->setEnd(e);
});
abuilder->bindProperty<ScalarValue>(jtrim["o"],
[adapter](const ScalarValue& o) {
adapter->setOffset(o);
});
}
return trimmed;
}
std::vector<sk_sp<sksg::GeometryNode>> AttachRoundGeometryEffect(
const skjson::ObjectValue& jtrim, const AnimationBuilder* abuilder,
std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
std::vector<sk_sp<sksg::GeometryNode>> rounded;
rounded.reserve(geos.size());
for (auto& g : geos) {
const auto roundEffect = sksg::RoundEffect::Make(std::move(g));
rounded.push_back(roundEffect);
abuilder->bindProperty<ScalarValue>(jtrim["r"],
[roundEffect](const ScalarValue& r) {
roundEffect->setRadius(r);
});
}
return rounded;
}
std::vector<sk_sp<sksg::RenderNode>> AttachRepeaterDrawEffect(
const skjson::ObjectValue& jrepeater,
const AnimationBuilder* abuilder,
std::vector<sk_sp<sksg::RenderNode>>&& draws) {
std::vector<sk_sp<sksg::RenderNode>> repeater_draws;
if (const skjson::ObjectValue* jtransform = jrepeater["tr"]) {
sk_sp<sksg::RenderNode> repeater_node;
if (draws.size() > 1) {
repeater_node = sksg::Group::Make(std::move(draws));
} else {
repeater_node = std::move(draws[0]);
}
const auto repeater_composite = (ParseDefault(jrepeater["m"], 1) == 1)
? RepeaterAdapter::Composite::kAbove
: RepeaterAdapter::Composite::kBelow;
auto adapter = sk_make_sp<RepeaterAdapter>(std::move(repeater_node),
repeater_composite);
abuilder->bindProperty<ScalarValue>(jrepeater["c"],
[adapter](const ScalarValue& c) {
adapter->setCount(c);
});
abuilder->bindProperty<ScalarValue>(jrepeater["o"],
[adapter](const ScalarValue& o) {
adapter->setOffset(o);
});
abuilder->bindProperty<VectorValue>((*jtransform)["a"],
[adapter](const VectorValue& a) {
adapter->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
});
abuilder->bindProperty<VectorValue>((*jtransform)["p"],
[adapter](const VectorValue& p) {
adapter->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
});
abuilder->bindProperty<VectorValue>((*jtransform)["s"],
[adapter](const VectorValue& s) {
adapter->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
});
abuilder->bindProperty<ScalarValue>((*jtransform)["r"],
[adapter](const ScalarValue& r) {
adapter->setRotation(r);
});
abuilder->bindProperty<ScalarValue>((*jtransform)["so"],
[adapter](const ScalarValue& so) {
adapter->setStartOpacity(so);
});
abuilder->bindProperty<ScalarValue>((*jtransform)["eo"],
[adapter](const ScalarValue& eo) {
adapter->setEndOpacity(eo);
});
repeater_draws.reserve(1);
repeater_draws.push_back(adapter->root());
} else {
repeater_draws = std::move(draws);
}
return repeater_draws;
}
using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const skjson::ObjectValue&,
const AnimationBuilder*);
static constexpr GeometryAttacherT gGeometryAttachers[] = {
AttachPathGeometry,
AttachRRectGeometry,
AttachEllipseGeometry,
AttachPolystarGeometry,
};
using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const skjson::ObjectValue&,
const AnimationBuilder*);
static constexpr PaintAttacherT gPaintAttachers[] = {
AttachColorFill,
AttachColorStroke,
AttachGradientFill,
AttachGradientStroke,
};
using GeometryEffectAttacherT =
std::vector<sk_sp<sksg::GeometryNode>> (*)(const skjson::ObjectValue&,
const AnimationBuilder*,
std::vector<sk_sp<sksg::GeometryNode>>&&);
static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
AttachMergeGeometryEffect,
AttachTrimGeometryEffect,
AttachRoundGeometryEffect,
};
using DrawEffectAttacherT =
std::vector<sk_sp<sksg::RenderNode>> (*)(const skjson::ObjectValue&,
const AnimationBuilder*,
std::vector<sk_sp<sksg::RenderNode>>&&);
static constexpr DrawEffectAttacherT gDrawEffectAttachers[] = {
AttachRepeaterDrawEffect,
};
enum class ShapeType {
kGeometry,
kGeometryEffect,
kPaint,
kGroup,
kTransform,
kDrawEffect,
};
struct ShapeInfo {
const char* fTypeString;
ShapeType fShapeType;
uint32_t fAttacherIndex; // index into respective attacher tables
};
const ShapeInfo* FindShapeInfo(const skjson::ObjectValue& jshape) {
static constexpr ShapeInfo gShapeInfo[] = {
{ "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
{ "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
{ "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
{ "gr", ShapeType::kGroup , 0 }, // group -> Inline handler
{ "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
{ "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
{ "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
{ "rd", ShapeType::kGeometryEffect, 2 }, // round -> AttachRoundGeometryEffect
{ "rp", ShapeType::kDrawEffect , 0 }, // repeater -> AttachRepeaterDrawEffect
{ "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
{ "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
{ "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
{ "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
{ "tr", ShapeType::kTransform , 0 }, // transform -> Inline handler
};
const skjson::StringValue* type = jshape["ty"];
if (!type) {
return nullptr;
}
const auto* info = bsearch(type->begin(),
gShapeInfo,
SK_ARRAY_COUNT(gShapeInfo),
sizeof(ShapeInfo),
[](const void* key, const void* info) {
return strcmp(static_cast<const char*>(key),
static_cast<const ShapeInfo*>(info)->fTypeString);
});
return static_cast<const ShapeInfo*>(info);
}
struct GeometryEffectRec {
const skjson::ObjectValue& fJson;
GeometryEffectAttacherT fAttach;
};
} // namespace
struct AnimationBuilder::AttachShapeContext {
AttachShapeContext(std::vector<sk_sp<sksg::GeometryNode>>* geos,
std::vector<GeometryEffectRec>* effects,
size_t committedAnimators)
: fGeometryStack(geos)
, fGeometryEffectStack(effects)
, fCommittedAnimators(committedAnimators) {}
std::vector<sk_sp<sksg::GeometryNode>>* fGeometryStack;
std::vector<GeometryEffectRec>* fGeometryEffectStack;
size_t fCommittedAnimators;
};
sk_sp<sksg::RenderNode> AnimationBuilder::attachShape(const skjson::ArrayValue* jshape,
AttachShapeContext* ctx) const {
if (!jshape)
return nullptr;
SkDEBUGCODE(const auto initialGeometryEffects = ctx->fGeometryEffectStack->size();)
const skjson::ObjectValue* jtransform = nullptr;
struct ShapeRec {
const skjson::ObjectValue& fJson;
const ShapeInfo& fInfo;
};
// First pass (bottom->top):
//
// * pick up the group transform and opacity
// * push local geometry effects onto the stack
// * store recs for next pass
//
std::vector<ShapeRec> recs;
for (size_t i = 0; i < jshape->size(); ++i) {
const skjson::ObjectValue* shape = (*jshape)[jshape->size() - 1 - i];
if (!shape) continue;
const auto* info = FindShapeInfo(*shape);
if (!info) {
this->log(Logger::Level::kError, &(*shape)["ty"], "Unknown shape.");
continue;
}
if (ParseDefault<bool>((*shape)["hd"], false)) {
// Ignore hidden shapes.
continue;
}
recs.push_back({ *shape, *info });
switch (info->fShapeType) {
case ShapeType::kTransform:
// Just track the transform property for now -- we'll deal with it later.
jtransform = shape;
break;
case ShapeType::kGeometryEffect:
SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
ctx->fGeometryEffectStack->push_back(
{ *shape, gGeometryEffectAttachers[info->fAttacherIndex] });
break;
default:
break;
}
}
// Second pass (top -> bottom, after 2x reverse):
//
// * track local geometry
// * emit local paints
//
std::vector<sk_sp<sksg::GeometryNode>> geos;
std::vector<sk_sp<sksg::RenderNode >> draws;
const auto add_draw = [this, &draws](sk_sp<sksg::RenderNode> draw, const ShapeRec& rec) {
// All draws can have an optional blend mode.
draws.push_back(this->attachBlendMode(rec.fJson, std::move(draw)));
};
for (auto rec = recs.rbegin(); rec != recs.rend(); ++rec) {
const AutoPropertyTracker apt(this, rec->fJson);
switch (rec->fInfo.fShapeType) {
case ShapeType::kGeometry: {
SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
if (auto geo = gGeometryAttachers[rec->fInfo.fAttacherIndex](rec->fJson, this)) {
geos.push_back(std::move(geo));
}
} break;
case ShapeType::kGeometryEffect: {
// Apply the current effect and pop from the stack.
SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
if (!geos.empty()) {
geos = gGeometryEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
this,
std::move(geos));
}
SkASSERT(&ctx->fGeometryEffectStack->back().fJson == &rec->fJson);
SkASSERT(ctx->fGeometryEffectStack->back().fAttach ==
gGeometryEffectAttachers[rec->fInfo.fAttacherIndex]);
ctx->fGeometryEffectStack->pop_back();
} break;
case ShapeType::kGroup: {
AttachShapeContext groupShapeCtx(&geos,
ctx->fGeometryEffectStack,
ctx->fCommittedAnimators);
if (auto subgroup = this->attachShape(rec->fJson["it"], &groupShapeCtx)) {
add_draw(std::move(subgroup), *rec);
SkASSERT(groupShapeCtx.fCommittedAnimators >= ctx->fCommittedAnimators);
ctx->fCommittedAnimators = groupShapeCtx.fCommittedAnimators;
}
} break;
case ShapeType::kPaint: {
SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
auto paint = gPaintAttachers[rec->fInfo.fAttacherIndex](rec->fJson, this);
if (!paint || geos.empty())
break;
auto drawGeos = geos;
// Apply all pending effects from the stack.
for (auto it = ctx->fGeometryEffectStack->rbegin();
it != ctx->fGeometryEffectStack->rend(); ++it) {
drawGeos = it->fAttach(it->fJson, this, std::move(drawGeos));
}
// If we still have multiple geos, reduce using 'merge'.
auto geo = drawGeos.size() > 1
? Merge(std::move(drawGeos), sksg::Merge::Mode::kMerge)
: drawGeos[0];
SkASSERT(geo);
add_draw(sksg::Draw::Make(std::move(geo), std::move(paint)), *rec);
ctx->fCommittedAnimators = fCurrentAnimatorScope->size();
} break;
case ShapeType::kDrawEffect: {
SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gDrawEffectAttachers));
if (!draws.empty()) {
draws = gDrawEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
this,
std::move(draws));
ctx->fCommittedAnimators = fCurrentAnimatorScope->size();
}
} break;
default:
break;
}
}
// By now we should have popped all local geometry effects.
SkASSERT(ctx->fGeometryEffectStack->size() == initialGeometryEffects);
sk_sp<sksg::RenderNode> shape_wrapper;
if (draws.size() == 1) {
// For a single draw, we don't need a group.
shape_wrapper = std::move(draws.front());
} else if (!draws.empty()) {
// Emit local draws reversed (bottom->top, per spec).
std::reverse(draws.begin(), draws.end());
draws.shrink_to_fit();
// We need a group to dispatch multiple draws.
shape_wrapper = sksg::Group::Make(std::move(draws));
}
sk_sp<sksg::Transform> shape_transform;
if (jtransform) {
const AutoPropertyTracker apt(this, *jtransform);
// This is tricky due to the interaction with ctx->fCommittedAnimators: we want any
// animators related to tranform/opacity to be committed => they must be inserted in front
// of the dangling/uncommitted ones.
AutoScope ascope(this);
if ((shape_transform = this->attachMatrix2D(*jtransform, nullptr))) {
shape_wrapper = sksg::TransformEffect::Make(std::move(shape_wrapper), shape_transform);
}
shape_wrapper = this->attachOpacity(*jtransform, std::move(shape_wrapper));
auto local_scope = ascope.release();
fCurrentAnimatorScope->insert(fCurrentAnimatorScope->begin() + ctx->fCommittedAnimators,
std::make_move_iterator(local_scope.begin()),
std::make_move_iterator(local_scope.end()));
ctx->fCommittedAnimators += local_scope.size();
}
// Push transformed local geometries to parent list, for subsequent paints.
for (auto& geo : geos) {
ctx->fGeometryStack->push_back(shape_transform
? sksg::GeometryTransform::Make(std::move(geo), shape_transform)
: std::move(geo));
}
return shape_wrapper;
}
sk_sp<sksg::RenderNode> AnimationBuilder::attachShapeLayer(const skjson::ObjectValue& layer,
LayerInfo*) const {
std::vector<sk_sp<sksg::GeometryNode>> geometryStack;
std::vector<GeometryEffectRec> geometryEffectStack;
AttachShapeContext shapeCtx(&geometryStack, &geometryEffectStack,
fCurrentAnimatorScope->size());
auto shapeNode = this->attachShape(layer["shapes"], &shapeCtx);
// Trim uncommitted animators: AttachShape consumes effects on the fly, and greedily attaches
// geometries => at the end, we can end up with unused geometries, which are nevertheless alive
// due to attached animators. To avoid this, we track committed animators and discard the
// orphans here.
SkASSERT(shapeCtx.fCommittedAnimators <= fCurrentAnimatorScope->size());
fCurrentAnimatorScope->resize(shapeCtx.fCommittedAnimators);
return shapeNode;
}
} // namespace internal
} // namespace skottie
| bsd-3-clause |
malcolmreynolds/GTSAM | wrap/tests/testSpirit.cpp | 2 | 5276 | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testSpirit.cpp
* @brief Unit test for Boost's awesome Spirit parser
* @author Frank Dellaert
**/
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_push_back_actor.hpp>
#include <CppUnitLite/TestHarness.h>
#include <wrap/utilities.h>
using namespace std;
using namespace BOOST_SPIRIT_CLASSIC_NS;
typedef rule<BOOST_SPIRIT_CLASSIC_NS::phrase_scanner_t> Rule;
/* ************************************************************************* */
// lexeme_d turns off white space skipping
// http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/doc/directives.html
Rule name_p = lexeme_d[alpha_p >> *(alnum_p | '_')];
Rule className_p = lexeme_d[upper_p >> *(alnum_p | '_')];
Rule methodName_p = lexeme_d[lower_p >> *(alnum_p | '_')];
Rule basisType_p = (str_p("string") | "bool" | "size_t" | "int" | "double" | "Vector" | "Matrix");
/* ************************************************************************* */
TEST( spirit, real ) {
// check if we can parse 8.99 as a real
EXPECT(parse("8.99", real_p, space_p).full);
// make sure parsing fails on this one
EXPECT(!parse("zztop", real_p, space_p).full);
}
/* ************************************************************************* */
TEST( spirit, string ) {
// check if we can parse a string
EXPECT(parse("double", str_p("double"), space_p).full);
}
/* ************************************************************************* */
TEST( spirit, sequence ) {
// check that we skip white space
EXPECT(parse("int int", str_p("int") >> *str_p("int"), space_p).full);
EXPECT(parse("int --- - -- -", str_p("int") >> *ch_p('-'), space_p).full);
EXPECT(parse("const \t string", str_p("const") >> str_p("string"), space_p).full);
// note that (see spirit FAQ) the vanilla rule<> does not deal with whitespace
rule<>vanilla_p = str_p("const") >> str_p("string");
EXPECT(!parse("const \t string", vanilla_p, space_p).full);
// to fix it, we need to use <phrase_scanner_t>
rule<phrase_scanner_t>phrase_level_p = str_p("const") >> str_p("string");
EXPECT(parse("const \t string", phrase_level_p, space_p).full);
}
/* ************************************************************************* */
// parser for interface files
// const string reference reference
Rule constStringRef_p =
str_p("const") >> "string" >> '&';
// class reference
Rule classRef_p = className_p >> '&';
// const class reference
Rule constClassRef_p = str_p("const") >> classRef_p;
// method parsers
Rule constMethod_p = basisType_p >> methodName_p >> '(' >> ')' >> "const" >> ';';
/* ************************************************************************* */
TEST( spirit, basisType_p ) {
EXPECT(!parse("Point3", basisType_p, space_p).full);
EXPECT(parse("string", basisType_p, space_p).full);
}
/* ************************************************************************* */
TEST( spirit, className_p ) {
EXPECT(parse("Point3", className_p, space_p).full);
}
/* ************************************************************************* */
TEST( spirit, classRef_p ) {
EXPECT(parse("Point3 &", classRef_p, space_p).full);
EXPECT(parse("Point3&", classRef_p, space_p).full);
}
/* ************************************************************************* */
TEST( spirit, constMethod_p ) {
EXPECT(parse("double norm() const;", constMethod_p, space_p).full);
}
/* ************************************************************************* */
TEST( spirit, return_value_p ) {
bool isEigen = true;
string actual_return_type;
string actual_function_name;
Rule basisType_p =
(str_p("string") | "bool" | "size_t" | "int" | "double");
Rule eigenType_p =
(str_p("Vector") | "Matrix");
Rule className_p = lexeme_d[upper_p >> *(alnum_p | '_')] - eigenType_p - basisType_p;
Rule funcName_p = lexeme_d[lower_p >> *(alnum_p | '_')];
Rule returnType_p =
(basisType_p[assign_a(actual_return_type)][assign_a(isEigen, true)]) |
(className_p[assign_a(actual_return_type)][assign_a(isEigen,false)]) |
(eigenType_p[assign_a(actual_return_type)][assign_a(isEigen, true)]);
Rule testFunc_p = returnType_p >> funcName_p[assign_a(actual_function_name)] >> str_p("();");
EXPECT(parse("VectorNotEigen doesNotReturnAnEigenVector();", testFunc_p, space_p).full);
EXPECT(!isEigen);
EXPECT(actual_return_type == "VectorNotEigen");
EXPECT(actual_function_name == "doesNotReturnAnEigenVector");
EXPECT(parse("Vector actuallyAVector();", testFunc_p, space_p).full);
EXPECT(isEigen);
EXPECT(actual_return_type == "Vector");
EXPECT(actual_function_name == "actuallyAVector");
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
/* ************************************************************************* */
| bsd-3-clause |
Sevalecan/paintown | src/paintown-engine/network/chat_client.cpp | 3 | 18242 | #ifdef HAVE_NETWORKING
#include "util/graphics/bitmap.h"
#include "../network/network.h"
#include "util/events.h"
#include "chat_client.h"
#include "chat.h"
#include "util/init.h"
#include "util/version.h"
#include "util/input/keyboard.h"
#include "util/input/input-source.h"
#include "util/font.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/gui/lineedit.h"
#include "util/resource.h"
#include "util/input/input-manager.h"
#include "util/input/input-map.h"
#include "util/sound/sound.h"
/* FIXME: only for title screen */
#include "globals.h"
using namespace std;
static std::ostream & debug( int level ){
Global::debug( level ) << "[chat-client] ";
return Global::debug( level );
}
static void * serverInput( void * client_ ){
ChatClient * client = (ChatClient *) client_;
bool done = false;
while ( ! done ){
try{
debug(1) << "Waiting to receive a message" << endl;
Network::Message message(client->getSocket());
int x;
ChatType kind;
message >> x;
kind = (ChatType) x;
debug( 1 ) << "Received message type " << kind << endl;
switch ( kind ){
case HELLO : {
debug(0) << "Client should not see a HELLO message!" << endl;
break;
}
case ADD_MESSAGE : {
client->addMessage( message.path, 0 );
break;
}
case CHANGE_NAME : {
int id;
string name;
message >> id;
name = message.path;
client->changeName( id, name );
break;
}
case REMOVE_BUDDY : {
int id;
message >> id;
client->removeBuddy( id );
break;
}
case OK_TO_START : {
break;
}
case START_THE_GAME : {
/* shut down threads and prepare to play */
done = true;
client->finish();
break;
}
case ADD_BUDDY : {
int id;
string name;
message >> id;
name = message.path;
client->addBuddy( id, name );
break;
}
}
} catch ( const Network::NetworkException & e ){
debug( 0 ) << "Input thread died" << endl;
done = true;
}
}
return NULL;
}
void ChatClient::enter_pressed(void * self){
ChatClient * chat = (ChatClient*) self;
if (chat->lineEdit->getText().size() > 0){
chat->addMessage("You: " + chat->lineEdit->getText(), 0);
chat->toSend.push(chat->lineEdit->getText());
chat->lineEdit->clear();
chat->needUpdate();
}
}
ChatClient::ChatClient( Network::Socket socket, const string & name ):
need_update(true),
messages( 400, 300 ),
socket(socket),
focus(INPUT_BOX),
finished(false),
enterPressed( false ){
background = new Graphics::Bitmap(Global::titleScreen().path());
Util::Thread::initializeLock(&lock);
Util::Thread::createThread(&inputThread, NULL, (Util::Thread::ThreadFunction) serverInput, this);
try{
Network::Message nameMessage;
nameMessage.path = name;
nameMessage << HELLO;
nameMessage << Network::MagicId;
nameMessage << Version::getVersion();
nameMessage.send(socket);
} catch (const Network::NetworkException & n){
debug( 0 ) << "Could not send username: " << n.getMessage() << endl;
}
lineEdit = new Gui::LineEdit();
lineEdit->location.setPosition(Gui::AbsolutePoint(20, 20 + messages.getHeight() + 5));
lineEdit->location.setDimensions(400, 30);
lineEdit->transforms.setRadius(5);
lineEdit->colors.body = Graphics::makeColor(0, 0, 0);
lineEdit->colors.bodyAlpha = 128;
lineEdit->colors.border = Graphics::makeColor(255, 255, 0);
lineEdit->setTextColor(Graphics::makeColor(255, 255, 255));
lineEdit->setText("Hi!");
//lineEdit->setFont(& Font::getDefaultFont(20, 20));
lineEdit->addHook(Keyboard::Key_ENTER, enter_pressed, this);
lineEdit->addHook(Keyboard::Key_TAB, next_focus, this);
lineEdit->setFocused(true);
editCounter = 0;
}
bool ChatClient::needToDraw(){
return need_update;
}
Focus ChatClient::nextFocus(Focus f){
switch (f){
case INPUT_BOX: return QUIT;
case QUIT: return INPUT_BOX;
default: return INPUT_BOX;
}
}
void ChatClient::addBuddy( int id, const std::string & s ){
Buddy b;
b.id = id;
b.name = s;
Util::Thread::acquireLock( &lock );
buddies.push_back(b);
needUpdate();
Util::Thread::releaseLock( &lock );
Resource::getSound(Filesystem::RelativePath("menu/sounds/chip-in.wav"))->play();
}
void ChatClient::changeName( int id, const std::string & s ){
Util::Thread::acquireLock( &lock );
for ( vector< Buddy >::iterator it = buddies.begin(); it != buddies.end(); it++ ){
Buddy & buddy = *it;
if (buddy.id == id){
buddy.name = s;
}
}
needUpdate();
Util::Thread::releaseLock( &lock );
}
void ChatClient::removeBuddy( int id ){
Util::Thread::acquireLock( &lock );
for ( vector< Buddy >::iterator it = buddies.begin(); it != buddies.end(); ){
const Buddy & b = *it;
if ( b.id == id ){
it = buddies.erase( it );
} else {
it ++;
}
}
needUpdate();
Util::Thread::releaseLock( &lock );
Resource::getSound(Filesystem::RelativePath("menu/sounds/chip-out.wav"))->play();
}
void ChatClient::addMessage( const string & s, unsigned int id ){
Util::Thread::acquireLock( &lock );
messages.addMessage( s );
needUpdate();
Util::Thread::releaseLock( &lock );
}
/*
static char lowerCase( const char * x ){
if ( x[0] >= 'A' && x[0] <= 'Z' ){
return x[0] - 'A' + 'a';
}
return x[0];
}
*/
bool ChatClient::sendMessage( const string & message ){
try{
Network::Message net;
net << ADD_MESSAGE;
net.path = message;
net.send( socket );
return true;
} catch ( const Network::NetworkException & e ){
debug( 0 ) << "Client could not send message" << endl;
}
return false;
}
void ChatClient::popup(const Graphics::Bitmap & work, const std::string & str ){
const Font & font = Font::getDefaultFont(20, 20 );
int length = font.textLength( str.c_str() ) + 20;
int height = font.getHeight() * 2;
Graphics::Bitmap area( work, work.getWidth() / 2 - length / 2, work.getHeight() / 2, length, height );
area.translucent().rectangleFill( 0, 0, area.getWidth(), area.getHeight(), Graphics::makeColor( 64, 0, 0 ) );
Graphics::Color color = Graphics::makeColor( 255, 255, 255 );
area.rectangle( 0, 0, area.getWidth() - 1, area.getHeight() - 1, color );
font.printf( 10, area.getHeight() / 3, Graphics::makeColor( 255, 255, 255 ), area, str, 0 );
work.BlitToScreen();
/*
key.wait();
key.readKey();
*/
}
#if 0
void ChatClient::handleInput( Keyboard & keyboard ){
/*
vector< int > keys;
keyboard.readKeys( keys );
for ( vector< int >::iterator it = keys.begin(); it != keys.end(); it++ ){
int key = *it;
if ( key == Keyboard::Key_BACKSPACE ){
if ( input != "" ){
input = input.substr( 0, input.length() - 1 );
needUpdate();
}
} else if ( Keyboard::isAlpha( key ) ){
input += lowerCase( Keyboard::keyToName( key ) );
needUpdate();
} else if ( key == Keyboard::Key_SPACE ){
input += " ";
needUpdate();
} else if ( key == Keyboard::Key_ENTER ){
addMessage( "You: " + input, 0 );
if ( ! sendMessage( input ) ){
popup( keyboard, "Could not send message" );
}
input = "";
needUpdate();
}
}
*/
const Font & font = Font::getDefaultFont(20, 20 );
lineEdit->act(font);
if ( lineEdit->didChanged( editCounter ) ){
needUpdate();
}
if ( enterPressed && lineEdit->getText().length() > 0 ){
// enterPressed = false;
addMessage( "You: " + lineEdit->getText(), 0 );
toSend.push(lineEdit->getText());
lineEdit->clearText();
needUpdate();
}
}
#endif
void ChatClient::needUpdate(){
need_update = true;
}
void ChatClient::next_focus(void * self){
ChatClient * chat = (ChatClient*) self;
chat->focus = chat->nextFocus(chat->focus);
chat->lineEdit->setFocused(chat->focus == INPUT_BOX);
if (chat->focus == INPUT_BOX){
chat->lineEdit->colors.border = Graphics::makeColor(255,255,0);
} else {
chat->lineEdit->colors.border = Graphics::makeColor(255,255,255);
}
chat->needUpdate();
}
bool ChatClient::logic(){
const Font & font = Font::getDefaultFont(20, 20);
lineEdit->act(font);
if (lineEdit->didChanged(editCounter)){
needUpdate();
}
return false;
/*
if ( keyboard[ Keyboard::Key_TAB ] ){
focus = nextFocus( focus );
debug(1) << "Focus is " << focus << endl;
needUpdate();
}
lineEdit->setFocused(false);
switch ( focus ){
case INPUT_BOX : {
lineEdit->setFocused(true);
lineEdit->colors.border = Bitmap::makeColor(255,255,0);
handleInput( keyboard );
return false;
}
case QUIT : {
lineEdit->colors.border = Bitmap::makeColor(255,255,255);
if ( keyboard[ Keyboard::Key_ENTER ] ){
return true;
}
break;
}
}
return false;
*/
}
void ChatClient::drawInputBox( int x, int y, const Graphics::Bitmap & work ){
const Font & font = Font::getDefaultFont(20, 20 );
Graphics::Bitmap::transBlender( 0, 0, 0, 128 );
work.translucent().rectangleFill( x, y, x + messages.getWidth(), y + font.getHeight() + 1, Graphics::makeColor( 0, 0, 0 ) );
Graphics::Color color = Graphics::makeColor( 255, 255, 255 );
if ( focus == INPUT_BOX ){
color = Graphics::makeColor( 255, 255, 0 );
}
work.rectangle( x, y, x + messages.getWidth(), y + font.getHeight(), color );
Graphics::Bitmap input_box( work, x + 1, y, messages.getWidth(), font.getHeight() );
// font.printf( x + 1, y, Bitmap::makeColor( 255, 255, 255 ), work, input, 0 );
font.printf( 0, 0, Graphics::makeColor( 255, 255, 255 ), input_box, input, 0 );
}
void ChatClient::drawBuddies( const Graphics::Bitmap & area, int x, int y, const Font & font ){
Graphics::Bitmap buddyList( area, x, y, area.getWidth() - x - 5, 200 );
// buddyList.drawingMode( Graphics::Bitmap::MODE_TRANS );
Graphics::Bitmap::transBlender( 0, 0, 0, 128 );
buddyList.translucent().rectangleFill( 0, 0, buddyList.getWidth(), buddyList.getHeight(), Graphics::makeColor( 0, 0, 0 ) );
// buddyList.drawingMode( Bitmap::MODE_SOLID );
buddyList.rectangle( 0, 0, buddyList.getWidth() -1, buddyList.getHeight() - 1, Graphics::makeColor( 255, 255, 255 ) );
int fy = 1;
for ( vector< Buddy >::iterator it = buddies.begin(); it != buddies.end(); it++ ){
Buddy & buddy = *it;
const string & name = buddy.name;
font.printf( 1, fy, Graphics::makeColor( 255, 255, 255 ), buddyList, name, 0 );
fy += font.getHeight();
}
}
void ChatClient::draw( const Graphics::Bitmap & work ){
int start_x = 20;
int start_y = 20;
const Font & font = Font::getDefaultFont(20, 20 );
background->Blit( work );
messages.draw( start_x, start_y, work, font );
// drawInputBox( start_x, start_y + messages.getHeight() + 5, work );
lineEdit->draw(Font::getDefaultFont(20, 20), work);
drawBuddies( work, start_x + messages.getWidth() + 10, start_y, font );
Graphics::Color color = Graphics::makeColor( 255, 255, 255 );
if (focus == QUIT){
color = Graphics::makeColor( 255, 255, 0 );
}
font.printf( start_x, start_y + messages.getHeight() + 5 + font.getHeight() + 20, color, work, "Back", 0 );
need_update = false;
}
bool ChatClient::isFinished(){
bool b;
Util::Thread::acquireLock( &lock );
b = finished;
Util::Thread::releaseLock( &lock );
return b;
}
void ChatClient::finish(){
Util::Thread::acquireLock( &lock );
finished = true;
Util::Thread::releaseLock( &lock );
}
void ChatClient::killInputThread(){
debug(0) << "Killing input socket" << endl;
Network::close(getSocket());
debug(0) << "Waiting for input thread to die" << endl;
Util::Thread::joinThread(inputThread);
debug(0) << "Input thread killed" << endl;
}
static void set_to_true(void * b){
bool * what = (bool*) b;
*what = true;
}
void ChatClient::run(){
// Global::speed_counter2 = 0;
class Logic: public Util::Logic {
public:
Logic(bool & kill, ChatClient & client):
is_done(false),
kill(kill),
client(client),
forceQuit(false){
input.set(Keyboard::Key_TAB, 0, true, 0);
input.set(Keyboard::Key_ENTER, 0, true, 1);
input.set(Keyboard::Key_ESC, 0, true, 2);
client.lineEdit->addHook(Keyboard::Key_ESC, set_to_true, &forceQuit);
}
InputMap<int> input;
bool is_done;
bool & kill;
ChatClient & client;
bool forceQuit;
double ticks(double system){
return system;
}
bool done(){
return is_done;
}
void run(){
vector<InputMap<int>::InputEvent> events = InputManager::getEvents(input, InputSource(true));
bool hasInputFocus = client.focus == INPUT_BOX;
bool next = false;
bool select = false;
bool quit = false;
for (vector<InputMap<int>::InputEvent>::iterator it = events.begin(); it != events.end(); it++){
const InputMap<int>::InputEvent & event = *it;
if (!event.enabled){
continue;
}
next = next || event[0];
select = select || event[1];
quit = quit || event[2];
}
if (client.logic() || forceQuit || quit){
kill = true;
is_done = true;
return;
}
if (next && !hasInputFocus){
next_focus(&client);
}
if (quit || (select && client.focus == QUIT)){
Global::debug(0) << "Quit!" << endl;
kill = true;
is_done = true;
}
while (! client.toSend.empty()){
if (! client.sendMessage(client.toSend.front())){
popup(*Graphics::screenParameter.current(), "Could not send message" );
}
client.toSend.pop();
}
is_done = is_done || client.isFinished();
}
};
class Draw: public Util::Draw {
public:
Draw(ChatClient & client):
client(client){
}
ChatClient & client;
void draw(const Graphics::Bitmap & buffer){
Graphics::StretchedBitmap work(640, 480, buffer);
work.start();
work.clear();
client.draw(work);
work.finish();
}
};
bool kill = false;
Logic logic(kill, *this);
Draw draw(*this);
Util::standardLoop(logic, draw);
#if 0
InputMap<int> input;
input.set(Keyboard::Key_TAB, 0, true, 0);
input.set(Keyboard::Key_ENTER, 0, true, 1);
input.set(Keyboard::Key_ESC, 0, true, 2);
bool forceQuit = false;
bool done = false;
lineEdit->hookKey(Keyboard::Key_ESC, set_to_true, &forceQuit);
while (! done){
int think = Global::speed_counter2;
Global::speed_counter2 = 0;
while (think > 0){
InputManager::poll();
vector<InputMap<int>::InputEvent> events = InputManager::getEvents(input);
bool hasInputFocus = focus == INPUT_BOX;
bool next = false;
bool select = false;
bool quit = false;
for (vector<InputMap<int>::InputEvent>::iterator it = events.begin(); it != events.end(); it++){
const InputMap<int>::InputEvent & event = *it;
if (!event.enabled){
continue;
}
next = next || event[0];
select = select || event[1];
quit = quit || event[2];
}
if (logic() || forceQuit || quit){
kill = true;
done = true;
break;
}
if (next && !hasInputFocus){
next_focus(this);
}
if (quit || (select && focus == QUIT)){
Global::debug(0) << "Quit!" << endl;
kill = true;
done = true;
}
while (! toSend.empty()){
if (! sendMessage( toSend.front() )){
popup(work, "Could not send message" );
}
toSend.pop();
}
think -= 1;
done = done || isFinished();
/*
if ( keyboard[ Keyboard::Key_ESC ] ){
kill = true;
done = true;
break;
}
*/
}
if (needToDraw()){
draw(work);
work.BlitToScreen();
work.clear();
}
while (Global::speed_counter2 == 0){
Util::rest(1);
}
}
#endif
lineEdit->setFocused(false);
if (kill){
killInputThread();
} else {
/* when OK_TO_START is sent there are guaranteed to be no other
* packets in front of it to confuse the server
*/
Network::Message message;
message << OK_TO_START;
message.send(getSocket());
}
}
ChatClient::~ChatClient(){
delete background;
delete lineEdit;
}
#endif
| bsd-3-clause |
alishakiba/libflame | src/map/lapack2flamec/f2c/c/slarz.c | 3 | 7532 | /* ../netlib/slarz.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* Table of constant values */
static integer c__1 = 1;
static real c_b5 = 1.f;
/* > \brief \b SLARZ applies an elementary reflector (as returned by stzrzf) to a general matrix. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download SLARZ + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slarz.f "> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slarz.f "> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slarz.f "> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE SLARZ( SIDE, M, N, L, V, INCV, TAU, C, LDC, WORK ) */
/* .. Scalar Arguments .. */
/* CHARACTER SIDE */
/* INTEGER INCV, L, LDC, M, N */
/* REAL TAU */
/* .. */
/* .. Array Arguments .. */
/* REAL C( LDC, * ), V( * ), WORK( * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > SLARZ applies a real elementary reflector H to a real M-by-N */
/* > matrix C, from either the left or the right. H is represented in the */
/* > form */
/* > */
/* > H = I - tau * v * v**T */
/* > */
/* > where tau is a real scalar and v is a real vector. */
/* > */
/* > If tau = 0, then H is taken to be the unit matrix. */
/* > */
/* > */
/* > H is a product of k elementary reflectors as returned by STZRZF. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] SIDE */
/* > \verbatim */
/* > SIDE is CHARACTER*1 */
/* > = 'L': form H * C */
/* > = 'R': form C * H */
/* > \endverbatim */
/* > */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix C. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix C. */
/* > \endverbatim */
/* > */
/* > \param[in] L */
/* > \verbatim */
/* > L is INTEGER */
/* > The number of entries of the vector V containing */
/* > the meaningful part of the Householder vectors. */
/* > If SIDE = 'L', M >= L >= 0, if SIDE = 'R', N >= L >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] V */
/* > \verbatim */
/* > V is REAL array, dimension (1+(L-1)*abs(INCV)) */
/* > The vector v in the representation of H as returned by */
/* > STZRZF. V is not used if TAU = 0. */
/* > \endverbatim */
/* > */
/* > \param[in] INCV */
/* > \verbatim */
/* > INCV is INTEGER */
/* > The increment between elements of v. INCV <> 0. */
/* > \endverbatim */
/* > */
/* > \param[in] TAU */
/* > \verbatim */
/* > TAU is REAL */
/* > The value tau in the representation of H. */
/* > \endverbatim */
/* > */
/* > \param[in,out] C */
/* > \verbatim */
/* > C is REAL array, dimension (LDC,N) */
/* > On entry, the M-by-N matrix C. */
/* > On exit, C is overwritten by the matrix H * C if SIDE = 'L', */
/* > or C * H if SIDE = 'R'. */
/* > \endverbatim */
/* > */
/* > \param[in] LDC */
/* > \verbatim */
/* > LDC is INTEGER */
/* > The leading dimension of the array C. LDC >= max(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is REAL array, dimension */
/* > (N) if SIDE = 'L' */
/* > or (M) if SIDE = 'R' */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date September 2012 */
/* > \ingroup realOTHERcomputational */
/* > \par Contributors: */
/* ================== */
/* > */
/* > A. Petitet, Computer Science Dept., Univ. of Tenn., Knoxville, USA */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */
int slarz_(char *side, integer *m, integer *n, integer *l, real *v, integer *incv, real *tau, real *c__, integer *ldc, real * work)
{
/* System generated locals */
integer c_dim1, c_offset;
real r__1;
/* Local variables */
extern /* Subroutine */
int sger_(integer *, integer *, real *, real *, integer *, real *, integer *, real *, integer *);
extern logical lsame_(char *, char *);
extern /* Subroutine */
int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer *), saxpy_(integer *, real *, real *, integer *, real *, integer *);
/* -- LAPACK computational routine (version 3.4.2) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* September 2012 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
--v;
c_dim1 = *ldc;
c_offset = 1 + c_dim1;
c__ -= c_offset;
--work;
/* Function Body */
if (lsame_(side, "L"))
{
/* Form H * C */
if (*tau != 0.f)
{
/* w( 1:n ) = C( 1, 1:n ) */
scopy_(n, &c__[c_offset], ldc, &work[1], &c__1);
/* w( 1:n ) = w( 1:n ) + C( m-l+1:m, 1:n )**T * v( 1:l ) */
sgemv_("Transpose", l, n, &c_b5, &c__[*m - *l + 1 + c_dim1], ldc, &v[1], incv, &c_b5, &work[1], &c__1);
/* C( 1, 1:n ) = C( 1, 1:n ) - tau * w( 1:n ) */
r__1 = -(*tau);
saxpy_(n, &r__1, &work[1], &c__1, &c__[c_offset], ldc);
/* C( m-l+1:m, 1:n ) = C( m-l+1:m, 1:n ) - ... */
/* tau * v( 1:l ) * w( 1:n )**T */
r__1 = -(*tau);
sger_(l, n, &r__1, &v[1], incv, &work[1], &c__1, &c__[*m - *l + 1 + c_dim1], ldc);
}
}
else
{
/* Form C * H */
if (*tau != 0.f)
{
/* w( 1:m ) = C( 1:m, 1 ) */
scopy_(m, &c__[c_offset], &c__1, &work[1], &c__1);
/* w( 1:m ) = w( 1:m ) + C( 1:m, n-l+1:n, 1:n ) * v( 1:l ) */
sgemv_("No transpose", m, l, &c_b5, &c__[(*n - *l + 1) * c_dim1 + 1], ldc, &v[1], incv, &c_b5, &work[1], &c__1);
/* C( 1:m, 1 ) = C( 1:m, 1 ) - tau * w( 1:m ) */
r__1 = -(*tau);
saxpy_(m, &r__1, &work[1], &c__1, &c__[c_offset], &c__1);
/* C( 1:m, n-l+1:n ) = C( 1:m, n-l+1:n ) - ... */
/* tau * w( 1:m ) * v( 1:l )**T */
r__1 = -(*tau);
sger_(m, l, &r__1, &work[1], &c__1, &v[1], incv, &c__[(*n - *l + 1) * c_dim1 + 1], ldc);
}
}
return 0;
/* End of SLARZ */
}
/* slarz_ */
| bsd-3-clause |
ayenter/CS411SampleCode | libnova/src/nutation.c | 3 | 7898 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU 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.
*
* Copyright (C) 2000 - 2005 Liam Girdwood
*/
#include <math.h>
#include <libnova/nutation.h>
#include <libnova/dynamical_time.h>
#include <libnova/utility.h>
#define TERMS 63
#define LN_NUTATION_EPOCH_THRESHOLD 0.1
struct nutation_arguments
{
double D;
double M;
double MM;
double F;
double O;
};
struct nutation_coefficients
{
double longitude1;
double longitude2;
double obliquity1;
double obliquity2;
};
/* arguments and coefficients taken from table 21A on page 133 */
const static struct nutation_arguments arguments[TERMS] = {
{0.0, 0.0, 0.0, 0.0, 1.0},
{-2.0, 0.0, 0.0, 2.0, 2.0},
{0.0, 0.0, 0.0, 2.0, 2.0},
{0.0, 0.0, 0.0, 0.0, 2.0},
{0.0, 1.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0, 0.0},
{-2.0, 1.0, 0.0, 2.0, 2.0},
{0.0, 0.0, 0.0, 2.0, 1.0},
{0.0, 0.0, 1.0, 2.0, 2.0},
{-2.0, -1.0, 0.0, 2.0, 2.0},
{-2.0, 0.0, 1.0, 0.0, 0.0},
{-2.0, 0.0, 0.0, 2.0, 1.0},
{0.0, 0.0, -1.0, 2.0, 2.0},
{2.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0, 1.0},
{2.0, 0.0, -1.0, 2.0, 2.0},
{0.0, 0.0, -1.0, 0.0, 1.0},
{0.0, 0.0, 1.0, 2.0, 1.0},
{-2.0, 0.0, 2.0, 0.0, 0.0},
{0.0, 0.0, -2.0, 2.0, 1.0},
{2.0, 0.0, 0.0, 2.0, 2.0},
{0.0, 0.0, 2.0, 2.0, 2.0},
{0.0, 0.0, 2.0, 0.0, 0.0},
{-2.0, 0.0, 1.0, 2.0, 2.0},
{0.0, 0.0, 0.0, 2.0, 0.0},
{-2.0, 0.0, 0.0, 2.0, 0.0},
{0.0, 0.0, -1.0, 2.0, 1.0},
{0.0, 2.0, 0.0, 0.0, 0.0},
{2.0, 0.0, -1.0, 0.0, 1.0},
{-2.0, 2.0, 0.0, 2.0, 2.0},
{0.0, 1.0, 0.0, 0.0, 1.0},
{-2.0, 0.0, 1.0, 0.0, 1.0},
{0.0, -1.0, 0.0, 0.0, 1.0},
{0.0, 0.0, 2.0, -2.0, 0.0},
{2.0, 0.0, -1.0, 2.0, 1.0},
{2.0, 0.0, 1.0, 2.0, 2.0},
{0.0, 1.0, 0.0, 2.0, 2.0},
{-2.0, 1.0, 1.0, 0.0, 0.0},
{0.0, -1.0, 0.0, 2.0, 2.0},
{2.0, 0.0, 0.0, 2.0, 1.0},
{2.0, 0.0, 1.0, 0.0, 0.0},
{-2.0, 0.0, 2.0, 2.0, 2.0},
{-2.0, 0.0, 1.0, 2.0, 1.0},
{2.0, 0.0, -2.0, 0.0, 1.0},
{2.0, 0.0, 0.0, 0.0, 1.0},
{0.0, -1.0, 1.0, 0.0, 0.0},
{-2.0, -1.0, 0.0, 2.0, 1.0},
{-2.0, 0.0, 0.0, 0.0, 1.0},
{0.0, 0.0, 2.0, 2.0, 1.0},
{-2.0, 0.0, 2.0, 0.0, 1.0},
{-2.0, 1.0, 0.0, 2.0, 1.0},
{0.0, 0.0, 1.0, -2.0, 0.0},
{-1.0, 0.0, 1.0, 0.0, 0.0},
{-2.0, 1.0, 0.0, 0.0, 0.0},
{1.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 2.0, 0.0},
{0.0, 0.0, -2.0, 2.0, 2.0},
{-1.0, -1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0},
{0.0, -1.0, 1.0, 2.0, 2.0},
{2.0, -1.0, -1.0, 2.0, 2.0},
{0.0, 0.0, 3.0, 2.0, 2.0},
{2.0, -1.0, 0.0, 2.0, 2.0}};
const static struct nutation_coefficients coefficients[TERMS] = {
{-171996.0, -174.2, 92025.0,8.9},
{-13187.0, -1.6, 5736.0, -3.1},
{-2274.0, -0.2, 977.0, -0.5},
{2062.0, 0.2, -895.0, 0.5},
{1426.0, -3.4, 54.0, -0.1},
{712.0, 0.1, -7.0, 0.0},
{-517.0, 1.2, 224.0, -0.6},
{-386.0, -0.4, 200.0, 0.0},
{-301.0, 0.0, 129.0, -0.1},
{217.0, -0.5, -95.0, 0.3},
{-158.0, 0.0, 0.0, 0.0},
{129.0, 0.1, -70.0, 0.0},
{123.0, 0.0, -53.0, 0.0},
{63.0, 0.0, 0.0, 0.0},
{63.0, 0.1, -33.0, 0.0},
{-59.0, 0.0, 26.0, 0.0},
{-58.0, -0.1, 32.0, 0.0},
{-51.0, 0.0, 27.0, 0.0},
{48.0, 0.0, 0.0, 0.0},
{46.0, 0.0, -24.0, 0.0},
{-38.0, 0.0, 16.0, 0.0},
{-31.0, 0.0, 13.0, 0.0},
{29.0, 0.0, 0.0, 0.0},
{29.0, 0.0, -12.0, 0.0},
{26.0, 0.0, 0.0, 0.0},
{-22.0, 0.0, 0.0, 0.0},
{21.0, 0.0, -10.0, 0.0},
{17.0, -0.1, 0.0, 0.0},
{16.0, 0.0, -8.0, 0.0},
{-16.0, 0.1, 7.0, 0.0},
{-15.0, 0.0, 9.0, 0.0},
{-13.0, 0.0, 7.0, 0.0},
{-12.0, 0.0, 6.0, 0.0},
{11.0, 0.0, 0.0, 0.0},
{-10.0, 0.0, 5.0, 0.0},
{-8.0, 0.0, 3.0, 0.0},
{7.0, 0.0, -3.0, 0.0},
{-7.0, 0.0, 0.0, 0.0},
{-7.0, 0.0, 3.0, 0.0},
{-7.0, 0.0, 3.0, 0.0},
{6.0, 0.0, 0.0, 0.0},
{6.0, 0.0, -3.0, 0.0},
{6.0, 0.0, -3.0, 0.0},
{-6.0, 0.0, 3.0, 0.0},
{-6.0, 0.0, 3.0, 0.0},
{5.0, 0.0, 0.0, 0.0},
{-5.0, 0.0, 3.0, 0.0},
{-5.0, 0.0, 3.0, 0.0},
{-5.0, 0.0, 3.0, 0.0},
{4.0, 0.0, 0.0, 0.0},
{4.0, 0.0, 0.0, 0.0},
{4.0, 0.0, 0.0, 0.0},
{-4.0, 0.0, 0.0, 0.0},
{-4.0, 0.0, 0.0, 0.0},
{-4.0, 0.0, 0.0, 0.0},
{3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0},
{-3.0, 0.0, 0.0, 0.0}};
/* cache values */
static long double c_JD = 0.0, c_longitude = 0.0, c_obliquity = 0.0, c_ecliptic = 0.0;
/*! \fn void ln_get_nutation (double JD, struct ln_nutation * nutation)
* \param JD Julian Day.
* \param nutation Pointer to store nutation
*
* Calculate nutation of longitude and obliquity in degrees from Julian Ephemeris Day
*/
/* Chapter 21 pg 131-134 Using Table 21A
*/
void ln_get_nutation (double JD, struct ln_nutation * nutation)
{
long double D,M,MM,F,O,T,T2,T3,JDE;
long double coeff_sine, coeff_cos;
long double argument;
int i;
/* should we bother recalculating nutation */
if (fabs(JD - c_JD) > LN_NUTATION_EPOCH_THRESHOLD) {
/* set the new epoch */
c_JD = JD;
/* get julian ephemeris day */
JDE = ln_get_jde (JD);
/* calc T */
T = (JDE - 2451545.0)/36525;
T2 = T * T;
T3 = T2 * T;
/* calculate D,M,M',F and Omega */
D = 297.85036 + 445267.111480 * T - 0.0019142 * T2 + T3 / 189474.0;
M = 357.52772 + 35999.050340 * T - 0.0001603 * T2 - T3 / 300000.0;
MM = 134.96298 + 477198.867398 * T + 0.0086972 * T2 + T3 / 56250.0;
F = 93.2719100 + 483202.017538 * T - 0.0036825 * T2 + T3 / 327270.0;
O = 125.04452 - 1934.136261 * T + 0.0020708 * T2 + T3 / 450000.0;
/* convert to radians */
D = ln_deg_to_rad (D);
M = ln_deg_to_rad (M);
MM = ln_deg_to_rad (MM);
F = ln_deg_to_rad (F);
O = ln_deg_to_rad (O);
/* calc sum of terms in table 21A */
for (i=0; i< TERMS; i++) {
/* calc coefficients of sine and cosine */
coeff_sine = (coefficients[i].longitude1 + (coefficients[i].longitude2 * T));
coeff_cos = (coefficients[i].obliquity1 + (coefficients[i].obliquity2 * T));
argument = arguments[i].D * D
+ arguments[i].M * M
+ arguments[i].MM * MM
+ arguments[i].F * F
+ arguments[i].O * O;
c_longitude += coeff_sine * sin(argument);
c_obliquity += coeff_cos * cos(argument);
}
/* change to arcsecs */
c_longitude /= 10000;
c_obliquity /= 10000;
/* change to degrees */
c_longitude /= (60 * 60);
c_obliquity /= (60 * 60);
/* calculate mean ecliptic - Meeus 2nd edition, eq. 22.2 */
c_ecliptic = 23.0 + 26.0 / 60.0 + 21.448 / 3600.0
- 46.8150/3600 * T
- 0.00059/3600 * T2
+ 0.001813/3600 * T3;
/* c_ecliptic += c_obliquity; * Uncomment this if function should
return true obliquity rather than
mean obliquity */
}
/* return results */
nutation->longitude = c_longitude;
nutation->obliquity = c_obliquity;
nutation->ecliptic = c_ecliptic;
}
| bsd-3-clause |
marado/netkit-telnet | netkit-telnet-0.17/telnetd/setproctitle.c | 3 | 4154 | /*
* setproctitle implementation for linux.
* Stolen from sendmail 8.7.4 and bashed around by David A. Holland
*/
/*
* Copyright (c) 1983, 1995 Eric P. Allman
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* From: @(#)conf.c 8.243 (Berkeley) 11/20/95
*/
char setproctitle_rcsid[] =
"$Id: setproctitle.c,v 1.3 1999/12/10 23:06:39 bryce Exp $";
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
#include "setproctitle.h"
/*
** SETPROCTITLE -- set process title for ps
**
** Parameters:
** fmt -- a printf style format string.
** a, b, c -- possible parameters to fmt.
**
** Returns:
** none.
**
** Side Effects:
** Clobbers argv of our main procedure so ps(1) will
** display the title.
*/
/*
** Pointers for setproctitle.
** This allows "ps" listings to give more useful information.
*/
static char **Argv = NULL; /* pointer to argument vector */
static char *LastArgv = NULL; /* end of argv */
static char Argv0[128]; /* program name */
void
initsetproctitle(int argc, char **argv, char **envp)
{
register int i;
char *tmp;
/*
** Move the environment so setproctitle can use the space at
** the top of memory.
*/
for (i = 0; envp[i] != NULL; i++)
continue;
__environ = (char **) malloc(sizeof (char *) * (i + 1));
for (i = 0; envp[i] != NULL; i++)
__environ[i] = strdup(envp[i]);
__environ[i] = NULL;
/*
** Save start and extent of argv for setproctitle.
*/
Argv = argv;
if (i > 0)
LastArgv = envp[i - 1] + strlen(envp[i - 1]);
else
LastArgv = argv[argc - 1] + strlen(argv[argc - 1]);
tmp = strrchr(argv[0], '/');
if (!tmp) tmp = argv[0];
else tmp++;
strncpy(Argv0, tmp, sizeof(Argv0));
Argv0[sizeof(Argv0)-1] = 0;
}
void
setproctitle(const char *fmt, ...)
{
register char *p;
register int i=0;
static char buf[2048];
va_list ap;
p = buf;
/* print progname: heading for grep */
/* This can't overflow buf due to the relative size of Argv0. */
(void) strcpy(p, Argv0);
(void) strcat(p, ": ");
p += strlen(p);
/* print the argument string */
va_start(ap, fmt);
(void) vsnprintf(p, sizeof(buf) - (p - buf), fmt, ap);
va_end(ap);
i = strlen(buf);
if (i > LastArgv - Argv[0] - 2)
{
i = LastArgv - Argv[0] - 2;
buf[i] = '\0';
}
(void) strcpy(Argv[0], buf);
p = &Argv[0][i];
while (p < LastArgv)
*p++ = '\0';
Argv[1] = NULL;
}
| bsd-3-clause |
bebo/usrsctp | usrsctplib/netinet/sctp_auth.c | 3 | 61644 | /*-
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_auth.c 287717 2015-09-12 17:08:51Z tuexen $");
#endif
#include <netinet/sctp_os.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctputil.h>
#include <netinet/sctp_indata.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_auth.h>
#ifdef SCTP_DEBUG
#define SCTP_AUTH_DEBUG (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH1)
#define SCTP_AUTH_DEBUG2 (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH2)
#endif /* SCTP_DEBUG */
void
sctp_clear_chunklist(sctp_auth_chklist_t *chklist)
{
bzero(chklist, sizeof(*chklist));
/* chklist->num_chunks = 0; */
}
sctp_auth_chklist_t *
sctp_alloc_chunklist(void)
{
sctp_auth_chklist_t *chklist;
SCTP_MALLOC(chklist, sctp_auth_chklist_t *, sizeof(*chklist),
SCTP_M_AUTH_CL);
if (chklist == NULL) {
SCTPDBG(SCTP_DEBUG_AUTH1, "sctp_alloc_chunklist: failed to get memory!\n");
} else {
sctp_clear_chunklist(chklist);
}
return (chklist);
}
void
sctp_free_chunklist(sctp_auth_chklist_t *list)
{
if (list != NULL)
SCTP_FREE(list, SCTP_M_AUTH_CL);
}
sctp_auth_chklist_t *
sctp_copy_chunklist(sctp_auth_chklist_t *list)
{
sctp_auth_chklist_t *new_list;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_chunklist();
if (new_list == NULL)
return (NULL);
/* copy it */
bcopy(list, new_list, sizeof(*new_list));
return (new_list);
}
/*
* add a chunk to the required chunks list
*/
int
sctp_auth_add_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
/* is chunk restricted? */
if ((chunk == SCTP_INITIATION) ||
(chunk == SCTP_INITIATION_ACK) ||
(chunk == SCTP_SHUTDOWN_COMPLETE) ||
(chunk == SCTP_AUTHENTICATION)) {
return (-1);
}
if (list->chunks[chunk] == 0) {
list->chunks[chunk] = 1;
list->num_chunks++;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: added chunk %u (0x%02x) to Auth list\n",
chunk, chunk);
}
return (0);
}
/*
* delete a chunk from the required chunks list
*/
int
sctp_auth_delete_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
if (list->chunks[chunk] == 1) {
list->chunks[chunk] = 0;
list->num_chunks--;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: deleted chunk %u (0x%02x) from Auth list\n",
chunk, chunk);
}
return (0);
}
size_t
sctp_auth_get_chklist_size(const sctp_auth_chklist_t *list)
{
if (list == NULL)
return (0);
else
return (list->num_chunks);
}
/*
* return the current number and list of required chunks caller must
* guarantee ptr has space for up to 256 bytes
*/
int
sctp_serialize_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, count = 0;
if (list == NULL)
return (0);
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
count++;
}
}
return (count);
}
int
sctp_pack_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, size = 0;
if (list == NULL)
return (0);
if (list->num_chunks <= 32) {
/* just list them, one byte each */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
size++;
}
}
} else {
int index, offset;
/* pack into a 32 byte bitfield */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
index = i / 8;
offset = i % 8;
ptr[index] |= (1 << offset);
}
}
size = 32;
}
return (size);
}
int
sctp_unpack_auth_chunks(const uint8_t *ptr, uint8_t num_chunks,
sctp_auth_chklist_t *list)
{
int i;
int size;
if (list == NULL)
return (0);
if (num_chunks <= 32) {
/* just pull them, one byte each */
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(*ptr++, list);
}
size = num_chunks;
} else {
int index, offset;
/* unpack from a 32 byte bitfield */
for (index = 0; index < 32; index++) {
for (offset = 0; offset < 8; offset++) {
if (ptr[index] & (1 << offset)) {
(void)sctp_auth_add_chunk((index * 8) + offset, list);
}
}
}
size = 32;
}
return (size);
}
/*
* allocate structure space for a key of length keylen
*/
sctp_key_t *
sctp_alloc_key(uint32_t keylen)
{
sctp_key_t *new_key;
SCTP_MALLOC(new_key, sctp_key_t *, sizeof(*new_key) + keylen,
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
return (new_key);
}
void
sctp_free_key(sctp_key_t *key)
{
if (key != NULL)
SCTP_FREE(key,SCTP_M_AUTH_KY);
}
void
sctp_print_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
void
sctp_show_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
static uint32_t
sctp_get_keylen(sctp_key_t *key)
{
if (key != NULL)
return (key->keylen);
else
return (0);
}
/*
* generate a new random key of length 'keylen'
*/
sctp_key_t *
sctp_generate_random_key(uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
SCTP_READ_RANDOM(new_key->key, keylen);
new_key->keylen = keylen;
return (new_key);
}
sctp_key_t *
sctp_set_key(uint8_t *key, uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
bcopy(key, new_key->key, keylen);
return (new_key);
}
/*-
* given two keys of variable size, compute which key is "larger/smaller"
* returns: 1 if key1 > key2
* -1 if key1 < key2
* 0 if key1 = key2
*/
static int
sctp_compare_key(sctp_key_t *key1, sctp_key_t *key2)
{
uint32_t maxlen;
uint32_t i;
uint32_t key1len, key2len;
uint8_t *key_1, *key_2;
uint8_t val1, val2;
/* sanity/length check */
key1len = sctp_get_keylen(key1);
key2len = sctp_get_keylen(key2);
if ((key1len == 0) && (key2len == 0))
return (0);
else if (key1len == 0)
return (-1);
else if (key2len == 0)
return (1);
if (key1len < key2len) {
maxlen = key2len;
} else {
maxlen = key1len;
}
key_1 = key1->key;
key_2 = key2->key;
/* check for numeric equality */
for (i = 0; i < maxlen; i++) {
/* left-pad with zeros */
val1 = (i < (maxlen - key1len)) ? 0 : *(key_1++);
val2 = (i < (maxlen - key2len)) ? 0 : *(key_2++);
if (val1 > val2) {
return (1);
} else if (val1 < val2) {
return (-1);
}
}
/* keys are equal value, so check lengths */
if (key1len == key2len)
return (0);
else if (key1len < key2len)
return (-1);
else
return (1);
}
/*
* generate the concatenated keying material based on the two keys and the
* shared key (if available). draft-ietf-tsvwg-auth specifies the specific
* order for concatenation
*/
sctp_key_t *
sctp_compute_hashkey(sctp_key_t *key1, sctp_key_t *key2, sctp_key_t *shared)
{
uint32_t keylen;
sctp_key_t *new_key;
uint8_t *key_ptr;
keylen = sctp_get_keylen(key1) + sctp_get_keylen(key2) +
sctp_get_keylen(shared);
if (keylen > 0) {
/* get space for the new key */
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
key_ptr = new_key->key;
} else {
/* all keys empty/null?! */
return (NULL);
}
/* concatenate the keys */
if (sctp_compare_key(key1, key2) <= 0) {
/* key is shared + key1 + key2 */
if (sctp_get_keylen(shared)) {
bcopy(shared->key, key_ptr, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key1)) {
bcopy(key1->key, key_ptr, key1->keylen);
key_ptr += key1->keylen;
}
if (sctp_get_keylen(key2)) {
bcopy(key2->key, key_ptr, key2->keylen);
}
} else {
/* key is shared + key2 + key1 */
if (sctp_get_keylen(shared)) {
bcopy(shared->key, key_ptr, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key2)) {
bcopy(key2->key, key_ptr, key2->keylen);
key_ptr += key2->keylen;
}
if (sctp_get_keylen(key1)) {
bcopy(key1->key, key_ptr, key1->keylen);
}
}
return (new_key);
}
sctp_sharedkey_t *
sctp_alloc_sharedkey(void)
{
sctp_sharedkey_t *new_key;
SCTP_MALLOC(new_key, sctp_sharedkey_t *, sizeof(*new_key),
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keyid = 0;
new_key->key = NULL;
new_key->refcount = 1;
new_key->deactivated = 0;
return (new_key);
}
void
sctp_free_sharedkey(sctp_sharedkey_t *skey)
{
if (skey == NULL)
return;
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&skey->refcount)) {
if (skey->key != NULL)
sctp_free_key(skey->key);
SCTP_FREE(skey, SCTP_M_AUTH_KY);
}
}
sctp_sharedkey_t *
sctp_find_sharedkey(struct sctp_keyhead *shared_keys, uint16_t key_id)
{
sctp_sharedkey_t *skey;
LIST_FOREACH(skey, shared_keys, next) {
if (skey->keyid == key_id)
return (skey);
}
return (NULL);
}
int
sctp_insert_sharedkey(struct sctp_keyhead *shared_keys,
sctp_sharedkey_t *new_skey)
{
sctp_sharedkey_t *skey;
if ((shared_keys == NULL) || (new_skey == NULL))
return (EINVAL);
/* insert into an empty list? */
if (LIST_EMPTY(shared_keys)) {
LIST_INSERT_HEAD(shared_keys, new_skey, next);
return (0);
}
/* insert into the existing list, ordered by key id */
LIST_FOREACH(skey, shared_keys, next) {
if (new_skey->keyid < skey->keyid) {
/* insert it before here */
LIST_INSERT_BEFORE(skey, new_skey, next);
return (0);
} else if (new_skey->keyid == skey->keyid) {
/* replace the existing key */
/* verify this key *can* be replaced */
if ((skey->deactivated) && (skey->refcount > 1)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"can't replace shared key id %u\n",
new_skey->keyid);
return (EBUSY);
}
SCTPDBG(SCTP_DEBUG_AUTH1,
"replacing shared key id %u\n",
new_skey->keyid);
LIST_INSERT_BEFORE(skey, new_skey, next);
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey);
return (0);
}
if (LIST_NEXT(skey, next) == NULL) {
/* belongs at the end of the list */
LIST_INSERT_AFTER(skey, new_skey, next);
return (0);
}
}
/* shouldn't reach here */
return (0);
}
void
sctp_auth_key_acquire(struct sctp_tcb *stcb, uint16_t key_id)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* bump the ref count */
if (skey) {
atomic_add_int(&skey->refcount, 1);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount acquire to %d\n",
__FUNCTION__, (void *)stcb, key_id, skey->refcount);
}
}
void
sctp_auth_key_release(struct sctp_tcb *stcb, uint16_t key_id, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* decrement the ref count */
if (skey) {
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount release to %d\n",
__FUNCTION__, (void *)stcb, key_id, skey->refcount);
/* see if a notification should be generated */
if ((skey->refcount <= 2) && (skey->deactivated)) {
/* notify ULP that key is no longer used */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb,
key_id, 0, so_locked);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u no longer used, %d\n",
__FUNCTION__, (void *)stcb, key_id, skey->refcount);
}
sctp_free_sharedkey(skey);
}
}
static sctp_sharedkey_t *
sctp_copy_sharedkey(const sctp_sharedkey_t *skey)
{
sctp_sharedkey_t *new_skey;
if (skey == NULL)
return (NULL);
new_skey = sctp_alloc_sharedkey();
if (new_skey == NULL)
return (NULL);
if (skey->key != NULL)
new_skey->key = sctp_set_key(skey->key->key, skey->key->keylen);
else
new_skey->key = NULL;
new_skey->keyid = skey->keyid;
return (new_skey);
}
int
sctp_copy_skeylist(const struct sctp_keyhead *src, struct sctp_keyhead *dest)
{
sctp_sharedkey_t *skey, *new_skey;
int count = 0;
if ((src == NULL) || (dest == NULL))
return (0);
LIST_FOREACH(skey, src, next) {
new_skey = sctp_copy_sharedkey(skey);
if (new_skey != NULL) {
(void)sctp_insert_sharedkey(dest, new_skey);
count++;
}
}
return (count);
}
sctp_hmaclist_t *
sctp_alloc_hmaclist(uint16_t num_hmacs)
{
sctp_hmaclist_t *new_list;
int alloc_size;
alloc_size = sizeof(*new_list) + num_hmacs * sizeof(new_list->hmac[0]);
SCTP_MALLOC(new_list, sctp_hmaclist_t *, alloc_size,
SCTP_M_AUTH_HL);
if (new_list == NULL) {
/* out of memory */
return (NULL);
}
new_list->max_algo = num_hmacs;
new_list->num_algo = 0;
return (new_list);
}
void
sctp_free_hmaclist(sctp_hmaclist_t *list)
{
if (list != NULL) {
SCTP_FREE(list,SCTP_M_AUTH_HL);
list = NULL;
}
}
int
sctp_auth_add_hmacid(sctp_hmaclist_t *list, uint16_t hmac_id)
{
int i;
if (list == NULL)
return (-1);
if (list->num_algo == list->max_algo) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: HMAC id list full, ignoring add %u\n", hmac_id);
return (-1);
}
#if defined(SCTP_SUPPORT_HMAC_SHA256)
if ((hmac_id != SCTP_AUTH_HMAC_ID_SHA1) &&
(hmac_id != SCTP_AUTH_HMAC_ID_SHA256)) {
#else
if (hmac_id != SCTP_AUTH_HMAC_ID_SHA1) {
#endif
return (-1);
}
/* Now is it already in the list */
for (i = 0; i < list->num_algo; i++) {
if (list->hmac[i] == hmac_id) {
/* already in list */
return (-1);
}
}
SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: add HMAC id %u to list\n", hmac_id);
list->hmac[list->num_algo++] = hmac_id;
return (0);
}
sctp_hmaclist_t *
sctp_copy_hmaclist(sctp_hmaclist_t *list)
{
sctp_hmaclist_t *new_list;
int i;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_hmaclist(list->max_algo);
if (new_list == NULL)
return (NULL);
/* copy it */
new_list->max_algo = list->max_algo;
new_list->num_algo = list->num_algo;
for (i = 0; i < list->num_algo; i++)
new_list->hmac[i] = list->hmac[i];
return (new_list);
}
sctp_hmaclist_t *
sctp_default_supported_hmaclist(void)
{
sctp_hmaclist_t *new_list;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
new_list = sctp_alloc_hmaclist(2);
#else
new_list = sctp_alloc_hmaclist(1);
#endif
if (new_list == NULL)
return (NULL);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
/* We prefer SHA256, so list it first */
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA256);
#endif
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA1);
return (new_list);
}
/*-
* HMAC algos are listed in priority/preference order
* find the best HMAC id to use for the peer based on local support
*/
uint16_t
sctp_negotiate_hmacid(sctp_hmaclist_t *peer, sctp_hmaclist_t *local)
{
int i, j;
if ((local == NULL) || (peer == NULL))
return (SCTP_AUTH_HMAC_ID_RSVD);
for (i = 0; i < peer->num_algo; i++) {
for (j = 0; j < local->num_algo; j++) {
if (peer->hmac[i] == local->hmac[j]) {
/* found the "best" one */
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: negotiated peer HMAC id %u\n",
peer->hmac[i]);
return (peer->hmac[i]);
}
}
}
/* didn't find one! */
return (SCTP_AUTH_HMAC_ID_RSVD);
}
/*-
* serialize the HMAC algo list and return space used
* caller must guarantee ptr has appropriate space
*/
int
sctp_serialize_hmaclist(sctp_hmaclist_t *list, uint8_t *ptr)
{
int i;
uint16_t hmac_id;
if (list == NULL)
return (0);
for (i = 0; i < list->num_algo; i++) {
hmac_id = htons(list->hmac[i]);
bcopy(&hmac_id, ptr, sizeof(hmac_id));
ptr += sizeof(hmac_id);
}
return (list->num_algo * sizeof(hmac_id));
}
int
sctp_verify_hmac_param (struct sctp_auth_hmac_algo *hmacs, uint32_t num_hmacs)
{
uint32_t i;
for (i = 0; i < num_hmacs; i++) {
if (ntohs(hmacs->hmac_ids[i]) == SCTP_AUTH_HMAC_ID_SHA1) {
return (0);
}
}
return (-1);
}
sctp_authinfo_t *
sctp_alloc_authinfo(void)
{
sctp_authinfo_t *new_authinfo;
SCTP_MALLOC(new_authinfo, sctp_authinfo_t *, sizeof(*new_authinfo),
SCTP_M_AUTH_IF);
if (new_authinfo == NULL) {
/* out of memory */
return (NULL);
}
bzero(new_authinfo, sizeof(*new_authinfo));
return (new_authinfo);
}
void
sctp_free_authinfo(sctp_authinfo_t *authinfo)
{
if (authinfo == NULL)
return;
if (authinfo->random != NULL)
sctp_free_key(authinfo->random);
if (authinfo->peer_random != NULL)
sctp_free_key(authinfo->peer_random);
if (authinfo->assoc_key != NULL)
sctp_free_key(authinfo->assoc_key);
if (authinfo->recv_key != NULL)
sctp_free_key(authinfo->recv_key);
/* We are NOT dynamically allocating authinfo's right now... */
/* SCTP_FREE(authinfo, SCTP_M_AUTH_??); */
}
uint32_t
sctp_get_auth_chunk_len(uint16_t hmac_algo)
{
int size;
size = sizeof(struct sctp_auth_chunk) + sctp_get_hmac_digest_len(hmac_algo);
return (SCTP_SIZE32(size));
}
uint32_t
sctp_get_hmac_digest_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (SCTP_AUTH_DIGEST_LEN_SHA1);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (SCTP_AUTH_DIGEST_LEN_SHA256);
#endif
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
static inline int
sctp_get_hmac_block_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (64);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (64);
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
#if defined(__Userspace__)
/* __Userspace__ SHA1_Init is defined in libcrypto.a (libssl-dev on Ubuntu) */
#endif
static void
sctp_hmac_init(uint16_t hmac_algo, sctp_hash_context_t *ctx)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_INIT(&ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_INIT(&ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_update(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *text, uint32_t textlen)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_UPDATE(&ctx->sha1, text, textlen);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_UPDATE(&ctx->sha256, text, textlen);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_final(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *digest)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_FINAL(digest, &ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_FINAL(digest, &ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
/*-
* Keyed-Hashing for Message Authentication: FIPS 198 (RFC 2104)
*
* Compute the HMAC digest using the desired hash key, text, and HMAC
* algorithm. Resulting digest is placed in 'digest' and digest length
* is returned, if the HMAC was performed.
*
* WARNING: it is up to the caller to supply sufficient space to hold the
* resultant digest.
*/
uint32_t
sctp_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
uint8_t *text, uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (text == NULL) ||
(textlen == 0) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
bzero(ipad, blocklen);
bzero(opad, blocklen);
bcopy(key, ipad, keylen);
bcopy(key, opad, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, text, textlen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/* mbuf version */
uint32_t
sctp_hmac_m(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
struct mbuf *m, uint32_t m_offset, uint8_t *digest, uint32_t trailer)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
struct mbuf *m_tmp;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
bzero(ipad, blocklen);
bzero(opad, blocklen);
bcopy(key, ipad, keylen);
bcopy(key, opad, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
/* find the correct starting mbuf and offset (get start of text) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain for the text */
while (m_tmp != NULL) {
if ((SCTP_BUF_NEXT(m_tmp) == NULL) && trailer) {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - (trailer+m_offset));
} else {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - m_offset);
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/*-
* verify the HMAC digest using the desired hash key, text, and HMAC
* algorithm.
* Returns -1 on error, 0 on success.
*/
int
sctp_verify_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
uint8_t *text, uint32_t textlen,
uint8_t *digest, uint32_t digestlen)
{
uint32_t len;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) ||
(text == NULL) || (textlen == 0) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest */
return (-1);
}
len = sctp_get_hmac_digest_len(hmac_algo);
if ((len == 0) || (digestlen != len))
return (-1);
/* compute the expected hash */
if (sctp_hmac(hmac_algo, key, keylen, text, textlen, temp) != len)
return (-1);
if (memcmp(digest, temp, digestlen) != 0)
return (-1);
else
return (0);
}
/*
* computes the requested HMAC using a key struct (which may be modified if
* the keylen exceeds the HMAC block len).
*/
uint32_t
sctp_compute_hmac(uint16_t hmac_algo, sctp_key_t *key, uint8_t *text,
uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (text == NULL) || (textlen == 0) ||
(digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
bcopy(temp, key->key, key->keylen);
}
return (sctp_hmac(hmac_algo, key->key, key->keylen, text, textlen,
digest));
}
/* mbuf version */
uint32_t
sctp_compute_hmac_m(uint16_t hmac_algo, sctp_key_t *key, struct mbuf *m,
uint32_t m_offset, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
bcopy(temp, key->key, key->keylen);
}
return (sctp_hmac_m(hmac_algo, key->key, key->keylen, m, m_offset, digest, 0));
}
int
sctp_auth_is_supported_hmac(sctp_hmaclist_t *list, uint16_t id)
{
int i;
if ((list == NULL) || (id == SCTP_AUTH_HMAC_ID_RSVD))
return (0);
for (i = 0; i < list->num_algo; i++)
if (list->hmac[i] == id)
return (1);
/* not in the list */
return (0);
}
/*-
* clear any cached key(s) if they match the given key id on an association.
* the cached key(s) will be recomputed and re-cached at next use.
* ASSUMES TCB_LOCK is already held
*/
void
sctp_clear_cachedkeys(struct sctp_tcb *stcb, uint16_t keyid)
{
if (stcb == NULL)
return;
if (keyid == stcb->asoc.authinfo.assoc_keyid) {
sctp_free_key(stcb->asoc.authinfo.assoc_key);
stcb->asoc.authinfo.assoc_key = NULL;
}
if (keyid == stcb->asoc.authinfo.recv_keyid) {
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key = NULL;
}
}
/*-
* clear any cached key(s) if they match the given key id for all assocs on
* an endpoint.
* ASSUMES INP_WLOCK is already held
*/
void
sctp_clear_cachedkeys_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
struct sctp_tcb *stcb;
if (inp == NULL)
return;
/* clear the cached keys on all assocs on this instance */
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
SCTP_TCB_LOCK(stcb);
sctp_clear_cachedkeys(stcb, keyid);
SCTP_TCB_UNLOCK(stcb);
}
}
/*-
* delete a shared key from an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_delete_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount > 1)
return (-1);
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys(stcb, keyid);
return (0);
}
/*-
* deletes a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_delete_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys_ep(inp, keyid);
return (0);
}
/*-
* set the active key on an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_auth_setactivekey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey = NULL;
/* find the key on the assoc */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
if ((skey->deactivated) && (skey->refcount > 1)) {
/* can't reactivate a deactivated key with other refcounts */
return (-1);
}
/* set the (new) active key */
stcb->asoc.authinfo.active_keyid = keyid;
/* reset the deactivated flag */
skey->deactivated = 0;
return (0);
}
/*-
* set the active key on an endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_auth_setactivekey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
/* find the key */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
inp->sctp_ep.default_keyid = keyid;
return (0);
}
/*-
* deactivates a shared key from the association
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount == 1) {
/* no other users, send a notification for this key */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb, keyid, 0,
SCTP_SO_LOCKED);
}
/* mark the key as deactivated */
skey->deactivated = 1;
return (0);
}
/*-
* deactivates a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
return (0);
}
/*
* get local authentication parameters from cookie (from INIT-ACK)
*/
void
sctp_auth_get_cookie_params(struct sctp_tcb *stcb, struct mbuf *m,
uint32_t offset, uint32_t length)
{
struct sctp_paramhdr *phdr, tmp_param;
uint16_t plen, ptype;
uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_random *p_random = NULL;
uint16_t random_len = 0;
uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs = NULL;
uint16_t hmacs_len = 0;
uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_chunk_list *chunks = NULL;
uint16_t num_chunks = 0;
sctp_key_t *new_key;
uint32_t keylen;
/* convert to upper bound */
length += offset;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset,
sizeof(struct sctp_paramhdr), (uint8_t *)&tmp_param);
while (phdr != NULL) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if ((plen == 0) || (offset + plen > length))
break;
if (ptype == SCTP_RANDOM) {
if (plen > sizeof(random_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)random_store, min(plen, sizeof(random_store)));
if (phdr == NULL)
return;
/* save the random and length for the key */
p_random = (struct sctp_auth_random *)phdr;
random_len = plen - sizeof(*p_random);
} else if (ptype == SCTP_HMAC_LIST) {
uint16_t num_hmacs;
uint16_t i;
if (plen > sizeof(hmacs_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)hmacs_store, min(plen,sizeof(hmacs_store)));
if (phdr == NULL)
return;
/* save the hmacs list and num for the key */
hmacs = (struct sctp_auth_hmac_algo *)phdr;
hmacs_len = plen - sizeof(*hmacs);
num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
if (stcb->asoc.local_hmacs != NULL)
sctp_free_hmaclist(stcb->asoc.local_hmacs);
stcb->asoc.local_hmacs = sctp_alloc_hmaclist(num_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
for (i = 0; i < num_hmacs; i++) {
(void)sctp_auth_add_hmacid(stcb->asoc.local_hmacs,
ntohs(hmacs->hmac_ids[i]));
}
}
} else if (ptype == SCTP_CHUNK_LIST) {
int i;
if (plen > sizeof(chunks_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store, min(plen,sizeof(chunks_store)));
if (phdr == NULL)
return;
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
/* save chunks list and num for the key */
if (stcb->asoc.local_auth_chunks != NULL)
sctp_clear_chunklist(stcb->asoc.local_auth_chunks);
else
stcb->asoc.local_auth_chunks = sctp_alloc_chunklist();
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(chunks->chunk_types[i],
stcb->asoc.local_auth_chunks);
}
}
/* get next parameter */
offset += SCTP_SIZE32(plen);
if (offset + sizeof(struct sctp_paramhdr) > length)
break;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, sizeof(struct sctp_paramhdr),
(uint8_t *)&tmp_param);
}
/* concatenate the full random key */
keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
if (chunks != NULL) {
keylen += sizeof(*chunks) + num_chunks;
}
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
/* copy in the RANDOM */
if (p_random != NULL) {
keylen = sizeof(*p_random) + random_len;
bcopy(p_random, new_key->key, keylen);
}
/* append in the AUTH chunks */
if (chunks != NULL) {
bcopy(chunks, new_key->key + keylen,
sizeof(*chunks) + num_chunks);
keylen += sizeof(*chunks) + num_chunks;
}
/* append in the HMACs */
if (hmacs != NULL) {
bcopy(hmacs, new_key->key + keylen,
sizeof(*hmacs) + hmacs_len);
}
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
/* negotiate what HMAC to use for the peer */
stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
stcb->asoc.local_hmacs);
/* copy defaults from the endpoint */
/* FIX ME: put in cookie? */
stcb->asoc.authinfo.active_keyid = stcb->sctp_ep->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&stcb->sctp_ep->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
}
/*
* compute and fill in the HMAC digest for a packet
*/
void
sctp_fill_hmac_digest_m(struct mbuf *m, uint32_t auth_offset,
struct sctp_auth_chunk *auth, struct sctp_tcb *stcb, uint16_t keyid)
{
uint32_t digestlen;
sctp_sharedkey_t *skey;
sctp_key_t *key;
if ((stcb == NULL) || (auth == NULL))
return;
/* zero the digest + chunk padding */
digestlen = sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
bzero(auth->hmac, SCTP_SIZE32(digestlen));
/* is the desired key cached? */
if ((keyid != stcb->asoc.authinfo.assoc_keyid) ||
(stcb->asoc.authinfo.assoc_key == NULL)) {
if (stcb->asoc.authinfo.assoc_key != NULL) {
/* free the old cached key */
sctp_free_key(stcb->asoc.authinfo.assoc_key);
}
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
/* the only way skey is NULL is if null key id 0 is used */
if (skey != NULL)
key = skey->key;
else
key = NULL;
/* compute a new assoc key and cache it */
stcb->asoc.authinfo.assoc_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, key);
stcb->asoc.authinfo.assoc_keyid = keyid;
SCTPDBG(SCTP_DEBUG_AUTH1, "caching key id %u\n",
stcb->asoc.authinfo.assoc_keyid);
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.assoc_key,
"Assoc Key");
#endif
}
/* set in the active key id */
auth->shared_key_id = htons(keyid);
/* compute and fill in the digest */
(void)sctp_compute_hmac_m(stcb->asoc.peer_hmac_id, stcb->asoc.authinfo.assoc_key,
m, auth_offset, auth->hmac);
}
static void
sctp_bzero_m(struct mbuf *m, uint32_t m_offset, uint32_t size)
{
struct mbuf *m_tmp;
uint8_t *data;
/* sanity check */
if (m == NULL)
return;
/* find the correct starting mbuf and offset (get start position) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain */
while ((m_tmp != NULL) && (size > 0)) {
data = mtod(m_tmp, uint8_t *) + m_offset;
if (size > (uint32_t) SCTP_BUF_LEN(m_tmp)) {
bzero(data, SCTP_BUF_LEN(m_tmp));
size -= SCTP_BUF_LEN(m_tmp);
} else {
bzero(data, size);
size = 0;
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
}
/*-
* process the incoming Authentication chunk
* return codes:
* -1 on any authentication error
* 0 on authentication verification
*/
int
sctp_handle_auth(struct sctp_tcb *stcb, struct sctp_auth_chunk *auth,
struct mbuf *m, uint32_t offset)
{
uint16_t chunklen;
uint16_t shared_key_id;
uint16_t hmac_id;
sctp_sharedkey_t *skey;
uint32_t digestlen;
uint8_t digest[SCTP_AUTH_DIGEST_LEN_MAX];
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
/* auth is checked for NULL by caller */
chunklen = ntohs(auth->ch.chunk_length);
if (chunklen < sizeof(*auth)) {
SCTP_STAT_INCR(sctps_recvauthfailed);
return (-1);
}
SCTP_STAT_INCR(sctps_recvauth);
/* get the auth params */
shared_key_id = ntohs(auth->shared_key_id);
hmac_id = ntohs(auth->hmac_id);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP AUTH Chunk: shared key %u, HMAC id %u\n",
shared_key_id, hmac_id);
/* is the indicated HMAC supported? */
if (!sctp_auth_is_supported_hmac(stcb->asoc.local_hmacs, hmac_id)) {
struct mbuf *op_err;
struct sctp_error_auth_invalid_hmac *cause;
SCTP_STAT_INCR(sctps_recvivalhmacid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unsupported HMAC id %u\n",
hmac_id);
/*
* report this in an Error Chunk: Unsupported HMAC
* Identifier
*/
op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_error_auth_invalid_hmac),
0, M_NOWAIT, 1, MT_HEADER);
if (op_err != NULL) {
/* pre-reserve some space */
SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
/* fill in the error */
cause = mtod(op_err, struct sctp_error_auth_invalid_hmac *);
cause->cause.code = htons(SCTP_CAUSE_UNSUPPORTED_HMACID);
cause->cause.length = htons(sizeof(struct sctp_error_auth_invalid_hmac));
cause->hmac_id = ntohs(hmac_id);
SCTP_BUF_LEN(op_err) = sizeof(struct sctp_error_auth_invalid_hmac);
/* queue it */
sctp_queue_op_err(stcb, op_err);
}
return (-1);
}
/* get the indicated shared key, if available */
if ((stcb->asoc.authinfo.recv_key == NULL) ||
(stcb->asoc.authinfo.recv_keyid != shared_key_id)) {
/* find the shared key on the assoc first */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys,
shared_key_id);
/* if the shared key isn't found, discard the chunk */
if (skey == NULL) {
SCTP_STAT_INCR(sctps_recvivalkeyid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unknown key id %u\n",
shared_key_id);
return (-1);
}
/* generate a notification if this is a new key id */
if (stcb->asoc.authinfo.recv_keyid != shared_key_id)
/*
* sctp_ulp_notify(SCTP_NOTIFY_AUTH_NEW_KEY, stcb,
* shared_key_id, (void
* *)stcb->asoc.authinfo.recv_keyid);
*/
sctp_notify_authentication(stcb, SCTP_AUTH_NEW_KEY,
shared_key_id, stcb->asoc.authinfo.recv_keyid,
SCTP_SO_NOT_LOCKED);
/* compute a new recv assoc key and cache it */
if (stcb->asoc.authinfo.recv_key != NULL)
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, skey->key);
stcb->asoc.authinfo.recv_keyid = shared_key_id;
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.recv_key, "Recv Key");
#endif
}
/* validate the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_id);
if (chunklen < (sizeof(*auth) + digestlen)) {
/* invalid digest length */
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: chunk too short for HMAC\n");
return (-1);
}
/* save a copy of the digest, zero the pseudo header, and validate */
bcopy(auth->hmac, digest, digestlen);
sctp_bzero_m(m, offset + sizeof(*auth), SCTP_SIZE32(digestlen));
(void)sctp_compute_hmac_m(hmac_id, stcb->asoc.authinfo.recv_key,
m, offset, computed_digest);
/* compare the computed digest with the one in the AUTH chunk */
if (memcmp(digest, computed_digest, digestlen) != 0) {
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: HMAC digest check failed\n");
return (-1);
}
return (0);
}
/*
* Generate NOTIFICATION
*/
void
sctp_notify_authentication(struct sctp_tcb *stcb, uint32_t indication,
uint16_t keyid, uint16_t alt_keyid, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
struct mbuf *m_notify;
struct sctp_authkey_event *auth;
struct sctp_queued_to_read *control;
if ((stcb == NULL) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)
) {
/* If the socket is gone we are out of here */
return;
}
if (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_AUTHEVNT))
/* event not enabled */
return;
m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_authkey_event),
0, M_NOWAIT, 1, MT_HEADER);
if (m_notify == NULL)
/* no space left */
return;
SCTP_BUF_LEN(m_notify) = 0;
auth = mtod(m_notify, struct sctp_authkey_event *);
memset(auth, 0, sizeof(struct sctp_authkey_event));
auth->auth_type = SCTP_AUTHENTICATION_EVENT;
auth->auth_flags = 0;
auth->auth_length = sizeof(*auth);
auth->auth_keynumber = keyid;
auth->auth_altkeynumber = alt_keyid;
auth->auth_indication = indication;
auth->auth_assoc_id = sctp_get_associd(stcb);
SCTP_BUF_LEN(m_notify) = sizeof(*auth);
SCTP_BUF_NEXT(m_notify) = NULL;
/* append to socket */
control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
0, 0, stcb->asoc.context, 0, 0, 0, m_notify);
if (control == NULL) {
/* no memory */
sctp_m_freem(m_notify);
return;
}
control->spec_flags = M_NOTIFICATION;
control->length = SCTP_BUF_LEN(m_notify);
/* not that we need this */
control->tail_mbuf = m_notify;
sctp_add_to_readq(stcb->sctp_ep, stcb, control,
&stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
}
/*-
* validates the AUTHentication related parameters in an INIT/INIT-ACK
* Note: currently only used for INIT as INIT-ACK is handled inline
* with sctp_load_addresses_from_init()
*/
int
sctp_validate_init_auth_params(struct mbuf *m, int offset, int limit)
{
struct sctp_paramhdr *phdr, parm_buf;
uint16_t ptype, plen;
int peer_supports_asconf = 0;
int peer_supports_auth = 0;
int got_random = 0, got_hmacs = 0, got_chklist = 0;
uint8_t saw_asconf = 0;
uint8_t saw_asconf_ack = 0;
/* go through each of the params. */
phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
while (phdr) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if (offset + plen > limit) {
break;
}
if (plen < sizeof(struct sctp_paramhdr)) {
break;
}
if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
/* A supported extension chunk */
struct sctp_supported_chunk_types_param *pr_supported;
uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
int num_ent, i;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&local_store, min(plen,sizeof(local_store)));
if (phdr == NULL) {
return (-1);
}
pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
num_ent = plen - sizeof(struct sctp_paramhdr);
for (i = 0; i < num_ent; i++) {
switch (pr_supported->chunk_types[i]) {
case SCTP_ASCONF:
case SCTP_ASCONF_ACK:
peer_supports_asconf = 1;
break;
default:
/* one we don't care about */
break;
}
}
} else if (ptype == SCTP_RANDOM) {
got_random = 1;
/* enforce the random length */
if (plen != (sizeof(struct sctp_auth_random) +
SCTP_AUTH_RANDOM_SIZE_REQUIRED)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid RANDOM len\n");
return (-1);
}
} else if (ptype == SCTP_HMAC_LIST) {
uint8_t store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs;
int num_hmacs;
if (plen > sizeof(store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)store, min(plen,sizeof(store)));
if (phdr == NULL)
return (-1);
hmacs = (struct sctp_auth_hmac_algo *)phdr;
num_hmacs = (plen - sizeof(*hmacs)) /
sizeof(hmacs->hmac_ids[0]);
/* validate the hmac list */
if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid HMAC param\n");
return (-1);
}
got_hmacs = 1;
} else if (ptype == SCTP_CHUNK_LIST) {
int i, num_chunks;
uint8_t chunks_store[SCTP_SMALL_CHUNK_STORE];
/* did the peer send a non-empty chunk list? */
struct sctp_auth_chunk_list *chunks = NULL;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store,
min(plen,sizeof(chunks_store)));
if (phdr == NULL)
return (-1);
/*-
* Flip through the list and mark that the
* peer supports asconf/asconf_ack.
*/
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
for (i = 0; i < num_chunks; i++) {
/* record asconf/asconf-ack if listed */
if (chunks->chunk_types[i] == SCTP_ASCONF)
saw_asconf = 1;
if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
saw_asconf_ack = 1;
}
if (num_chunks)
got_chklist = 1;
}
offset += SCTP_SIZE32(plen);
if (offset >= limit) {
break;
}
phdr = sctp_get_next_param(m, offset, &parm_buf,
sizeof(parm_buf));
}
/* validate authentication required parameters */
if (got_random && got_hmacs) {
peer_supports_auth = 1;
} else {
peer_supports_auth = 0;
}
if (!peer_supports_auth && got_chklist) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer sent chunk list w/o AUTH\n");
return (-1);
}
if (peer_supports_asconf && !peer_supports_auth) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer supports ASCONF but not AUTH\n");
return (-1);
} else if ((peer_supports_asconf) && (peer_supports_auth) &&
((saw_asconf == 0) || (saw_asconf_ack == 0))) {
return (-2);
}
return (0);
}
void
sctp_initialize_auth_params(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
uint16_t chunks_len = 0;
uint16_t hmacs_len = 0;
uint16_t random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
sctp_key_t *new_key;
uint16_t keylen;
/* initialize hmac list from endpoint */
stcb->asoc.local_hmacs = sctp_copy_hmaclist(inp->sctp_ep.local_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
hmacs_len = stcb->asoc.local_hmacs->num_algo *
sizeof(stcb->asoc.local_hmacs->hmac[0]);
}
/* initialize auth chunks list from endpoint */
stcb->asoc.local_auth_chunks =
sctp_copy_chunklist(inp->sctp_ep.local_auth_chunks);
if (stcb->asoc.local_auth_chunks != NULL) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
chunks_len++;
}
}
/* copy defaults from the endpoint */
stcb->asoc.authinfo.active_keyid = inp->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&inp->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
/* now set the concatenated key (random + chunks + hmacs) */
/* key includes parameter headers */
keylen = (3 * sizeof(struct sctp_paramhdr)) + random_len + chunks_len +
hmacs_len;
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
struct sctp_paramhdr *ph;
int plen;
/* generate and copy in the RANDOM */
ph = (struct sctp_paramhdr *)new_key->key;
ph->param_type = htons(SCTP_RANDOM);
plen = sizeof(*ph) + random_len;
ph->param_length = htons(plen);
SCTP_READ_RANDOM(new_key->key + sizeof(*ph), random_len);
keylen = plen;
/* append in the AUTH chunks */
/* NOTE: currently we always have chunks to list */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_CHUNK_LIST);
plen = sizeof(*ph) + chunks_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
if (stcb->asoc.local_auth_chunks) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
new_key->key[keylen++] = i;
}
}
/* append in the HMACs */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_HMAC_LIST);
plen = sizeof(*ph) + hmacs_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
(void)sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
new_key->key + keylen);
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
}
#ifdef SCTP_HMAC_TEST
/*
* HMAC and key concatenation tests
*/
static void
sctp_print_digest(uint8_t *digest, uint32_t digestlen, const char *str)
{
uint32_t i;
SCTP_PRINTF("\n%s: 0x", str);
if (digest == NULL)
return;
for (i = 0; i < digestlen; i++)
SCTP_PRINTF("%02x", digest[i]);
}
static int
sctp_test_hmac(const char *str, uint16_t hmac_id, uint8_t *key,
uint32_t keylen, uint8_t *text, uint32_t textlen,
uint8_t *digest, uint32_t digestlen)
{
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
SCTP_PRINTF("\n%s:", str);
sctp_hmac(hmac_id, key, keylen, text, textlen, computed_digest);
sctp_print_digest(digest, digestlen, "Expected digest");
sctp_print_digest(computed_digest, digestlen, "Computed digest");
if (memcmp(digest, computed_digest, digestlen) != 0) {
SCTP_PRINTF("\nFAILED");
return (-1);
} else {
SCTP_PRINTF("\nPASSED");
return (0);
}
}
/*
* RFC 2202: HMAC-SHA1 test cases
*/
void
sctp_test_hmac_sha1(void)
{
uint8_t *digest;
uint8_t key[128];
uint32_t keylen;
uint8_t text[128];
uint32_t textlen;
uint32_t digestlen = 20;
int failed = 0;
/*-
* test_case = 1
* key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
* key_len = 20
* data = "Hi There"
* data_len = 8
* digest = 0xb617318655057264e28bc0b6fb378c8ef146be00
*/
keylen = 20;
memset(key, 0x0b, keylen);
textlen = 8;
strcpy(text, "Hi There");
digest = "\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00";
if (sctp_test_hmac("SHA1 test case 1", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 2
* key = "Jefe"
* key_len = 4
* data = "what do ya want for nothing?"
* data_len = 28
* digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
*/
keylen = 4;
strcpy(key, "Jefe");
textlen = 28;
strcpy(text, "what do ya want for nothing?");
digest = "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79";
if (sctp_test_hmac("SHA1 test case 2", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 3
* key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
* key_len = 20
* data = 0xdd repeated 50 times
* data_len = 50
* digest = 0x125d7342b9ac11cd91a39af48aa17b4f63f175d3
*/
keylen = 20;
memset(key, 0xaa, keylen);
textlen = 50;
memset(text, 0xdd, textlen);
digest = "\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3";
if (sctp_test_hmac("SHA1 test case 3", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 4
* key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
* key_len = 25
* data = 0xcd repeated 50 times
* data_len = 50
* digest = 0x4c9007f4026250c6bc8414f9bf50c86c2d7235da
*/
keylen = 25;
memcpy(key, "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", keylen);
textlen = 50;
memset(text, 0xcd, textlen);
digest = "\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda";
if (sctp_test_hmac("SHA1 test case 4", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 5
* key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
* key_len = 20
* data = "Test With Truncation"
* data_len = 20
* digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
* digest-96 = 0x4c1a03424b55e07fe7f27be1
*/
keylen = 20;
memset(key, 0x0c, keylen);
textlen = 20;
strcpy(text, "Test With Truncation");
digest = "\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04";
if (sctp_test_hmac("SHA1 test case 5", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 6
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key - Hash Key First"
* data_len = 54
* digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 54;
strcpy(text, "Test Using Larger Than Block-Size Key - Hash Key First");
digest = "\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12";
if (sctp_test_hmac("SHA1 test case 6", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 7
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
* data_len = 73
* digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 73;
strcpy(text, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
digest = "\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91";
if (sctp_test_hmac("SHA1 test case 7", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nSHA1 test results: %d cases failed", failed);
else
SCTP_PRINTF("\nSHA1 test results: all test cases passed");
}
/*
* test assoc key concatenation
*/
static int
sctp_test_key_concatenation(sctp_key_t *key1, sctp_key_t *key2,
sctp_key_t *expected_key)
{
sctp_key_t *key;
int ret_val;
sctp_show_key(key1, "\nkey1");
sctp_show_key(key2, "\nkey2");
key = sctp_compute_hashkey(key1, key2, NULL);
sctp_show_key(expected_key, "\nExpected");
sctp_show_key(key, "\nComputed");
if (memcmp(key, expected_key, expected_key->keylen) != 0) {
SCTP_PRINTF("\nFAILED");
ret_val = -1;
} else {
SCTP_PRINTF("\nPASSED");
ret_val = 0;
}
sctp_free_key(key1);
sctp_free_key(key2);
sctp_free_key(expected_key);
sctp_free_key(key);
return (ret_val);
}
void
sctp_test_authkey(void)
{
sctp_key_t *key1, *key2, *expected_key;
int failed = 0;
/* test case 1 */
key1 = sctp_set_key("\x01\x01\x01\x01", 4);
key2 = sctp_set_key("\x01\x02\x03\x04", 4);
expected_key = sctp_set_key("\x01\x01\x01\x01\x01\x02\x03\x04", 8);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 2 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x02", 1);
expected_key = sctp_set_key("\x00\x00\x00\x01\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 3 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x02", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 4 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x01", 1);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 5 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x01", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 6 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 7 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nKey concatenation test results: %d cases failed", failed);
else
SCTP_PRINTF("\nKey concatenation test results: all test cases passed");
}
#if defined(STANDALONE_HMAC_TEST)
int
main(void)
{
sctp_test_hmac_sha1();
sctp_test_authkey();
}
#endif /* STANDALONE_HMAC_TEST */
#endif /* SCTP_HMAC_TEST */
| bsd-3-clause |
youtube/cobalt | third_party/libjpeg-turbo/rdswitch.c | 4 | 13195 | /*
* rdswitch.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1996, Thomas G. Lane.
* libjpeg-turbo Modifications:
* Copyright (C) 2010, 2018, 2022, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains routines to process some of cjpeg's more complicated
* command-line switches. Switches processed here are:
* -qtables file Read quantization tables from text file
* -scans file Read scan script from text file
* -quality N[,N,...] Set quality ratings
* -qslots N[,N,...] Set component quantization table selectors
* -sample HxV[,HxV,...] Set component sampling factors
*/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include <ctype.h> /* to declare isdigit(), isspace() */
LOCAL(int)
text_getc(FILE *file)
/* Read next char, skipping over any comments (# to end of line) */
/* A comment/newline sequence is returned as a newline */
{
register int ch;
ch = getc(file);
if (ch == '#') {
do {
ch = getc(file);
} while (ch != '\n' && ch != EOF);
}
return ch;
}
LOCAL(boolean)
read_text_integer(FILE *file, long *result, int *termchar)
/* Read an unsigned decimal integer from a file, store it in result */
/* Reads one trailing character after the integer; returns it in termchar */
{
register int ch;
register long val;
/* Skip any leading whitespace, detect EOF */
do {
ch = text_getc(file);
if (ch == EOF) {
*termchar = ch;
return FALSE;
}
} while (isspace(ch));
if (!isdigit(ch)) {
*termchar = ch;
return FALSE;
}
val = ch - '0';
while ((ch = text_getc(file)) != EOF) {
if (!isdigit(ch))
break;
val *= 10;
val += ch - '0';
}
*result = val;
*termchar = ch;
return TRUE;
}
#if JPEG_LIB_VERSION < 70
static int q_scale_factor[NUM_QUANT_TBLS] = { 100, 100, 100, 100 };
#endif
GLOBAL(boolean)
read_quant_tables(j_compress_ptr cinfo, char *filename, boolean force_baseline)
/* Read a set of quantization tables from the specified file.
* The file is plain ASCII text: decimal numbers with whitespace between.
* Comments preceded by '#' may be included in the file.
* There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
* The tables are implicitly numbered 0,1,etc.
* NOTE: does not affect the qslots mapping, which will default to selecting
* table 0 for luminance (or primary) components, 1 for chrominance components.
* You must use -qslots if you want a different component->table mapping.
*/
{
FILE *fp;
int tblno, i, termchar;
long val;
unsigned int table[DCTSIZE2];
if ((fp = fopen(filename, "r")) == NULL) {
fprintf(stderr, "Can't open table file %s\n", filename);
return FALSE;
}
tblno = 0;
while (read_text_integer(fp, &val, &termchar)) { /* read 1st element of table */
if (tblno >= NUM_QUANT_TBLS) {
fprintf(stderr, "Too many tables in file %s\n", filename);
fclose(fp);
return FALSE;
}
table[0] = (unsigned int)val;
for (i = 1; i < DCTSIZE2; i++) {
if (!read_text_integer(fp, &val, &termchar)) {
fprintf(stderr, "Invalid table data in file %s\n", filename);
fclose(fp);
return FALSE;
}
table[i] = (unsigned int)val;
}
#if JPEG_LIB_VERSION >= 70
jpeg_add_quant_table(cinfo, tblno, table, cinfo->q_scale_factor[tblno],
force_baseline);
#else
jpeg_add_quant_table(cinfo, tblno, table, q_scale_factor[tblno],
force_baseline);
#endif
tblno++;
}
if (termchar != EOF) {
fprintf(stderr, "Non-numeric data in file %s\n", filename);
fclose(fp);
return FALSE;
}
fclose(fp);
return TRUE;
}
#ifdef C_MULTISCAN_FILES_SUPPORTED
LOCAL(boolean)
read_scan_integer(FILE *file, long *result, int *termchar)
/* Variant of read_text_integer that always looks for a non-space termchar;
* this simplifies parsing of punctuation in scan scripts.
*/
{
register int ch;
if (!read_text_integer(file, result, termchar))
return FALSE;
ch = *termchar;
while (ch != EOF && isspace(ch))
ch = text_getc(file);
if (isdigit(ch)) { /* oops, put it back */
if (ungetc(ch, file) == EOF)
return FALSE;
ch = ' ';
} else {
/* Any separators other than ';' and ':' are ignored;
* this allows user to insert commas, etc, if desired.
*/
if (ch != EOF && ch != ';' && ch != ':')
ch = ' ';
}
*termchar = ch;
return TRUE;
}
GLOBAL(boolean)
read_scan_script(j_compress_ptr cinfo, char *filename)
/* Read a scan script from the specified text file.
* Each entry in the file defines one scan to be emitted.
* Entries are separated by semicolons ';'.
* An entry contains one to four component indexes,
* optionally followed by a colon ':' and four progressive-JPEG parameters.
* The component indexes denote which component(s) are to be transmitted
* in the current scan. The first component has index 0.
* Sequential JPEG is used if the progressive-JPEG parameters are omitted.
* The file is free format text: any whitespace may appear between numbers
* and the ':' and ';' punctuation marks. Also, other punctuation (such
* as commas or dashes) can be placed between numbers if desired.
* Comments preceded by '#' may be included in the file.
* Note: we do very little validity checking here;
* jcmaster.c will validate the script parameters.
*/
{
FILE *fp;
int scanno, ncomps, termchar;
long val;
jpeg_scan_info *scanptr;
#define MAX_SCANS 100 /* quite arbitrary limit */
jpeg_scan_info scans[MAX_SCANS];
if ((fp = fopen(filename, "r")) == NULL) {
fprintf(stderr, "Can't open scan definition file %s\n", filename);
return FALSE;
}
scanptr = scans;
scanno = 0;
while (read_scan_integer(fp, &val, &termchar)) {
if (scanno >= MAX_SCANS) {
fprintf(stderr, "Too many scans defined in file %s\n", filename);
fclose(fp);
return FALSE;
}
scanptr->component_index[0] = (int)val;
ncomps = 1;
while (termchar == ' ') {
if (ncomps >= MAX_COMPS_IN_SCAN) {
fprintf(stderr, "Too many components in one scan in file %s\n",
filename);
fclose(fp);
return FALSE;
}
if (!read_scan_integer(fp, &val, &termchar))
goto bogus;
scanptr->component_index[ncomps] = (int)val;
ncomps++;
}
scanptr->comps_in_scan = ncomps;
if (termchar == ':') {
if (!read_scan_integer(fp, &val, &termchar) || termchar != ' ')
goto bogus;
scanptr->Ss = (int)val;
if (!read_scan_integer(fp, &val, &termchar) || termchar != ' ')
goto bogus;
scanptr->Se = (int)val;
if (!read_scan_integer(fp, &val, &termchar) || termchar != ' ')
goto bogus;
scanptr->Ah = (int)val;
if (!read_scan_integer(fp, &val, &termchar))
goto bogus;
scanptr->Al = (int)val;
} else {
/* set non-progressive parameters */
scanptr->Ss = 0;
scanptr->Se = DCTSIZE2 - 1;
scanptr->Ah = 0;
scanptr->Al = 0;
}
if (termchar != ';' && termchar != EOF) {
bogus:
fprintf(stderr, "Invalid scan entry format in file %s\n", filename);
fclose(fp);
return FALSE;
}
scanptr++, scanno++;
}
if (termchar != EOF) {
fprintf(stderr, "Non-numeric data in file %s\n", filename);
fclose(fp);
return FALSE;
}
if (scanno > 0) {
/* Stash completed scan list in cinfo structure.
* NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data,
* but if you want to compress multiple images you'd want JPOOL_PERMANENT.
*/
scanptr = (jpeg_scan_info *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
scanno * sizeof(jpeg_scan_info));
memcpy(scanptr, scans, scanno * sizeof(jpeg_scan_info));
cinfo->scan_info = scanptr;
cinfo->num_scans = scanno;
}
fclose(fp);
return TRUE;
}
#endif /* C_MULTISCAN_FILES_SUPPORTED */
#if JPEG_LIB_VERSION < 70
/* These are the sample quantization tables given in Annex K (Clause K.1) of
* Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
* The spec says that the values given produce "good" quality, and
* when divided by 2, "very good" quality.
*/
static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
};
static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
LOCAL(void)
jpeg_default_qtables(j_compress_ptr cinfo, boolean force_baseline)
{
jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl, q_scale_factor[0],
force_baseline);
jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl, q_scale_factor[1],
force_baseline);
}
#endif
GLOBAL(boolean)
set_quality_ratings(j_compress_ptr cinfo, char *arg, boolean force_baseline)
/* Process a quality-ratings parameter string, of the form
* N[,N,...]
* If there are more q-table slots than parameters, the last value is replicated.
*/
{
int val = 75; /* default value */
int tblno;
char ch;
for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
if (*arg) {
ch = ','; /* if not set by sscanf, will be ',' */
if (sscanf(arg, "%d%c", &val, &ch) < 1)
return FALSE;
if (ch != ',') /* syntax check */
return FALSE;
/* Convert user 0-100 rating to percentage scaling */
#if JPEG_LIB_VERSION >= 70
cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val);
#else
q_scale_factor[tblno] = jpeg_quality_scaling(val);
#endif
while (*arg && *arg++ != ','); /* advance to next segment of arg
string */
} else {
/* reached end of parameter, set remaining factors to last value */
#if JPEG_LIB_VERSION >= 70
cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val);
#else
q_scale_factor[tblno] = jpeg_quality_scaling(val);
#endif
}
}
jpeg_default_qtables(cinfo, force_baseline);
return TRUE;
}
GLOBAL(boolean)
set_quant_slots(j_compress_ptr cinfo, char *arg)
/* Process a quantization-table-selectors parameter string, of the form
* N[,N,...]
* If there are more components than parameters, the last value is replicated.
*/
{
int val = 0; /* default table # */
int ci;
char ch;
for (ci = 0; ci < MAX_COMPONENTS; ci++) {
if (*arg) {
ch = ','; /* if not set by sscanf, will be ',' */
if (sscanf(arg, "%d%c", &val, &ch) < 1)
return FALSE;
if (ch != ',') /* syntax check */
return FALSE;
if (val < 0 || val >= NUM_QUANT_TBLS) {
fprintf(stderr, "JPEG quantization tables are numbered 0..%d\n",
NUM_QUANT_TBLS - 1);
return FALSE;
}
cinfo->comp_info[ci].quant_tbl_no = val;
while (*arg && *arg++ != ','); /* advance to next segment of arg
string */
} else {
/* reached end of parameter, set remaining components to last table */
cinfo->comp_info[ci].quant_tbl_no = val;
}
}
return TRUE;
}
GLOBAL(boolean)
set_sample_factors(j_compress_ptr cinfo, char *arg)
/* Process a sample-factors parameter string, of the form
* HxV[,HxV,...]
* If there are more components than parameters, "1x1" is assumed for the rest.
*/
{
int ci, val1, val2;
char ch1, ch2;
for (ci = 0; ci < MAX_COMPONENTS; ci++) {
if (*arg) {
ch2 = ','; /* if not set by sscanf, will be ',' */
if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
return FALSE;
if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
return FALSE;
if (val1 <= 0 || val1 > 4 || val2 <= 0 || val2 > 4) {
fprintf(stderr, "JPEG sampling factors must be 1..4\n");
return FALSE;
}
cinfo->comp_info[ci].h_samp_factor = val1;
cinfo->comp_info[ci].v_samp_factor = val2;
while (*arg && *arg++ != ','); /* advance to next segment of arg
string */
} else {
/* reached end of parameter, set remaining components to 1x1 sampling */
cinfo->comp_info[ci].h_samp_factor = 1;
cinfo->comp_info[ci].v_samp_factor = 1;
}
}
return TRUE;
}
| bsd-3-clause |
siraj/newos | boot/sparc/libkern/bzero.c | 4 | 2355 | /* $OpenBSD: bzero.c,v 1.3 1997/11/07 15:56:38 niklas Exp $ */
/*
* Copyright (c) 1987 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
/*static char *sccsid = "from: @(#)bzero.c 5.7 (Berkeley) 2/24/91";*/
static char *rcsid = "$OpenBSD: bzero.c,v 1.3 1997/11/07 15:56:38 niklas Exp $";
#endif /* LIBC_SCCS and not lint */
#ifndef _KERNEL
#include <string.h>
#else
#include <libkern/libkern.h>
#endif
/*
* bzero -- vax movc5 instruction
*/
void
bzero(b, length)
void *b;
register size_t length;
{
register char *p;
for (p = b; length--;)
*p++ = '\0';
}
| bsd-3-clause |
iPlantCollaborativeOpenSource/irods-3.3.1-iplant | server/api/src/rsSendXmsg.c | 5 | 2625 | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* sendXmsg.c
*/
#include "sendXmsg.h"
#include "xmsgLib.h"
extern ticketHashQue_t XmsgHashQue[];
extern xmsgQue_t XmsgQue;
int
rsSendXmsg (rsComm_t *rsComm, sendXmsgInp_t *sendXmsgInp)
{
int status, i;
ticketMsgStruct_t *ticketMsgStruct = NULL;
irodsXmsg_t *irodsXmsg;
char *miscInfo;
status = getTicketMsgStructByTicket (sendXmsgInp->ticket.rcvTicket,
&ticketMsgStruct);
if (status < 0) {
clearSendXmsgInfo (&sendXmsgInp->sendXmsgInfo);
return status;
}
/* match sendTicket */
if (ticketMsgStruct->ticket.sendTicket != sendXmsgInp->ticket.sendTicket) {
/* unmatched sendTicket */
rodsLog (LOG_ERROR,
"rsSendXmsg: sendTicket mismatch, input %d, in cache %d",
sendXmsgInp->ticket.sendTicket, ticketMsgStruct->ticket.sendTicket);
return (SYS_UNMATCHED_XMSG_TICKET);
}
/* added by Raja Jun 30, 2010 for dropping and clearing a messageStream */
miscInfo = sendXmsgInp->sendXmsgInfo.miscInfo;
if (miscInfo != NULL && strlen(miscInfo) > 0) {
if(!strcmp(miscInfo,"CLEAR_STREAM")) {
i = clearAllXMessages(ticketMsgStruct);
return(i);
}
else if (!strcmp(miscInfo,"DROP_STREAM")) {
if(sendXmsgInp->ticket.rcvTicket > 5) {
i = clearAllXMessages(ticketMsgStruct);
if (i < 0) return (i);
i = rmTicketMsgStructFromHQue (ticketMsgStruct,
(ticketHashQue_t *) ticketMsgStruct->ticketHashQue);
return(i);
}
}
else if (!strcmp(miscInfo,"ERASE_MESSAGE")) {
/* msgNumber actually is the sequence Number in the queue*/
i = clearOneXMessage(ticketMsgStruct, sendXmsgInp->sendXmsgInfo.msgNumber);
return(i);
}
}
/* create a irodsXmsg_t */
irodsXmsg = (irodsXmsg_t*)calloc (1, sizeof (irodsXmsg_t));
irodsXmsg->sendXmsgInfo = (sendXmsgInfo_t*)calloc (1, sizeof (sendXmsgInfo_t));
*irodsXmsg->sendXmsgInfo = sendXmsgInp->sendXmsgInfo;
irodsXmsg->sendTime = time (0);
/* rstrcpy (irodsXmsg->sendUserName, rsComm->clientUser.userName, NAME_LEN);*/
snprintf(irodsXmsg->sendUserName,NAME_LEN,"%s@%s",rsComm->clientUser.userName,rsComm->clientUser.rodsZone);
rstrcpy (irodsXmsg->sendAddr,sendXmsgInp->sendAddr, NAME_LEN);
/*** moved to xmsgLib.c RAJA Nov 29 2010 ***
addXmsgToXmsgQue (irodsXmsg, &XmsgQue);
status = addXmsgToTicketMsgStruct (irodsXmsg, ticketMsgStruct);
*** moved to xmsgLib.c RAJA Nov 29 2010 ***/
status = addXmsgToQues(irodsXmsg, ticketMsgStruct);
return (status);
}
| bsd-3-clause |
leighpauls/k2cro4 | breakpad/src/third_party/libdisasm/ia32_invariant.c | 262 | 8391 | #include <stdlib.h>
#include <string.h>
#include "ia32_invariant.h"
#include "ia32_insn.h"
#include "ia32_settings.h"
extern ia32_table_desc_t *ia32_tables;
extern ia32_settings_t ia32_settings;
extern size_t ia32_table_lookup( unsigned char *buf, size_t buf_len,
unsigned int table, ia32_insn_t **raw_insn,
unsigned int *prefixes );
/* -------------------------------- ModR/M, SIB */
/* Convenience flags */
#define MODRM_EA 1 /* ModR/M is an effective addr */
#define MODRM_reg 2 /* ModR/M is a register */
/* ModR/M flags */
#define MODRM_RM_SIB 0x04 /* R/M == 100 */
#define MODRM_RM_NOREG 0x05 /* R/B == 101 */
/* if (MODRM.MOD_NODISP && MODRM.RM_NOREG) then just disp32 */
#define MODRM_MOD_NODISP 0x00 /* mod == 00 */
#define MODRM_MOD_DISP8 0x01 /* mod == 01 */
#define MODRM_MOD_DISP32 0x02 /* mod == 10 */
#define MODRM_MOD_NOEA 0x03 /* mod == 11 */
/* 16-bit modrm flags */
#define MOD16_MOD_NODISP 0
#define MOD16_MOD_DISP8 1
#define MOD16_MOD_DISP16 2
#define MOD16_MOD_REG 3
#define MOD16_RM_BXSI 0
#define MOD16_RM_BXDI 1
#define MOD16_RM_BPSI 2
#define MOD16_RM_BPDI 3
#define MOD16_RM_SI 4
#define MOD16_RM_DI 5
#define MOD16_RM_BP 6
#define MOD16_RM_BX 7
/* SIB flags */
#define SIB_INDEX_NONE 0x04
#define SIB_BASE_EBP 0x05
#define SIB_SCALE_NOBASE 0x00
/* Convenience struct for modR/M bitfield */
struct modRM_byte {
unsigned int mod : 2;
unsigned int reg : 3;
unsigned int rm : 3;
};
/* Convenience struct for SIB bitfield */
struct SIB_byte {
unsigned int scale : 2;
unsigned int index : 3;
unsigned int base : 3;
};
#ifdef WIN32
static void byte_decode(unsigned char b, struct modRM_byte *modrm) {
#else
static inline void byte_decode(unsigned char b, struct modRM_byte *modrm) {
#endif
/* generic bitfield-packing routine */
modrm->mod = b >> 6; /* top 2 bits */
modrm->reg = (b & 56) >> 3; /* middle 3 bits */
modrm->rm = b & 7; /* bottom 3 bits */
}
static int ia32_invariant_modrm( unsigned char *in, unsigned char *out,
unsigned int mode_16, x86_invariant_op_t *op) {
struct modRM_byte modrm;
struct SIB_byte sib;
unsigned char *c, *cin;
unsigned short *s;
unsigned int *i;
int size = 0; /* modrm byte is already counted */
byte_decode(*in, &modrm); /* get bitfields */
out[0] = in[0]; /* save modrm byte */
cin = &in[1];
c = &out[1];
s = (unsigned short *)&out[1];
i = (unsigned int *)&out[1];
op->type = op_expression;
op->flags |= op_pointer;
if ( ! mode_16 && modrm.rm == MODRM_RM_SIB &&
modrm.mod != MODRM_MOD_NOEA ) {
size ++;
byte_decode(*cin, (struct modRM_byte *)(void*)&sib);
out[1] = in[1]; /* save sib byte */
cin = &in[2];
c = &out[2];
s = (unsigned short *)&out[2];
i = (unsigned int *)&out[2];
if ( sib.base == SIB_BASE_EBP && ! modrm.mod ) {
/* disp 32 is variant! */
memset( i, X86_WILDCARD_BYTE, 4 );
size += 4;
}
}
if (! modrm.mod && modrm.rm == 101) {
if ( mode_16 ) { /* straight RVA in disp */
memset( s, X86_WILDCARD_BYTE, 2 );
size += 2;
} else {
memset( i, X86_WILDCARD_BYTE, 2 );
size += 4;
}
} else if (modrm.mod && modrm.mod < 3) {
if (modrm.mod == MODRM_MOD_DISP8) { /* offset in disp */
*c = *cin;
size += 1;
} else if ( mode_16 ) {
*s = (* ((unsigned short *) cin));
size += 2;
} else {
*i = (*((unsigned int *) cin));
size += 4;
}
} else if ( modrm.mod == 3 ) {
op->type = op_register;
op->flags &= ~op_pointer;
}
return (size);
}
static int ia32_decode_invariant( unsigned char *buf, size_t buf_len,
ia32_insn_t *t, unsigned char *out,
unsigned int prefixes, x86_invariant_t *inv) {
unsigned int addr_size, op_size, mode_16;
unsigned int op_flags[3] = { t->dest_flag, t->src_flag, t->aux_flag };
int x, type, bytes = 0, size = 0, modrm = 0;
/* set addressing mode */
if (ia32_settings.options & opt_16_bit) {
op_size = ( prefixes & PREFIX_OP_SIZE ) ? 4 : 2;
addr_size = ( prefixes & PREFIX_ADDR_SIZE ) ? 4 : 2;
mode_16 = ( prefixes & PREFIX_ADDR_SIZE ) ? 0 : 1;
} else {
op_size = ( prefixes & PREFIX_OP_SIZE ) ? 2 : 4;
addr_size = ( prefixes & PREFIX_ADDR_SIZE ) ? 2 : 4;
mode_16 = ( prefixes & PREFIX_ADDR_SIZE ) ? 1 : 0;
}
for (x = 0; x < 3; x++) {
inv->operands[x].access = (enum x86_op_access)
OP_PERM(op_flags[x]);
inv->operands[x].flags = (enum x86_op_flags)
(OP_FLAGS(op_flags[x]) >> 12);
switch (op_flags[x] & OPTYPE_MASK) {
case OPTYPE_c:
size = (op_size == 4) ? 2 : 1;
break;
case OPTYPE_a: case OPTYPE_v:
size = (op_size == 4) ? 4 : 2;
break;
case OPTYPE_p:
size = (op_size == 4) ? 6 : 4;
break;
case OPTYPE_b:
size = 1;
break;
case OPTYPE_w:
size = 2;
break;
case OPTYPE_d: case OPTYPE_fs: case OPTYPE_fd:
case OPTYPE_fe: case OPTYPE_fb: case OPTYPE_fv:
case OPTYPE_si: case OPTYPE_fx:
size = 4;
break;
case OPTYPE_s:
size = 6;
break;
case OPTYPE_q: case OPTYPE_pi:
size = 8;
break;
case OPTYPE_dq: case OPTYPE_ps: case OPTYPE_ss:
case OPTYPE_pd: case OPTYPE_sd:
size = 16;
break;
case OPTYPE_m:
size = (addr_size == 4) ? 4 : 2;
break;
default:
break;
}
type = op_flags[x] & ADDRMETH_MASK;
switch (type) {
case ADDRMETH_E: case ADDRMETH_M: case ADDRMETH_Q:
case ADDRMETH_R: case ADDRMETH_W:
modrm = 1;
bytes += ia32_invariant_modrm( buf, out,
mode_16, &inv->operands[x]);
break;
case ADDRMETH_C: case ADDRMETH_D: case ADDRMETH_G:
case ADDRMETH_P: case ADDRMETH_S: case ADDRMETH_T:
case ADDRMETH_V:
inv->operands[x].type = op_register;
modrm = 1;
break;
case ADDRMETH_A: case ADDRMETH_O:
/* pad with xF4's */
memset( &out[bytes + modrm], X86_WILDCARD_BYTE,
size );
bytes += size;
inv->operands[x].type = op_offset;
if ( type == ADDRMETH_O ) {
inv->operands[x].flags |= op_signed |
op_pointer;
}
break;
case ADDRMETH_I: case ADDRMETH_J:
/* grab imm value */
if ((op_flags[x] & OPTYPE_MASK) == OPTYPE_v) {
/* assume this is an address */
memset( &out[bytes + modrm],
X86_WILDCARD_BYTE, size );
} else {
memcpy( &out[bytes + modrm],
&buf[bytes + modrm], size );
}
bytes += size;
if ( type == ADDRMETH_J ) {
if ( size == 1 ) {
inv->operands[x].type =
op_relative_near;
} else {
inv->operands[x].type =
op_relative_far;
}
inv->operands[x].flags |= op_signed;
} else {
inv->operands[x].type = op_immediate;
}
break;
case ADDRMETH_F:
inv->operands[x].type = op_register;
break;
case ADDRMETH_X:
inv->operands[x].flags |= op_signed |
op_pointer | op_ds_seg | op_string;
break;
case ADDRMETH_Y:
inv->operands[x].flags |= op_signed |
op_pointer | op_es_seg | op_string;
break;
case ADDRMETH_RR:
inv->operands[x].type = op_register;
break;
case ADDRMETH_II:
inv->operands[x].type = op_immediate;
break;
default:
inv->operands[x].type = op_unused;
break;
}
}
return (bytes + modrm);
}
size_t ia32_disasm_invariant( unsigned char * buf, size_t buf_len,
x86_invariant_t *inv ) {
ia32_insn_t *raw_insn = NULL;
unsigned int prefixes;
unsigned int type;
size_t size;
/* Perform recursive table lookup starting with main table (0) */
size = ia32_table_lookup( buf, buf_len, 0, &raw_insn, &prefixes );
if ( size == INVALID_INSN || size > buf_len ) {
/* TODO: set errno */
return 0;
}
/* copy opcode bytes to buffer */
memcpy( inv->bytes, buf, size );
/* set mnemonic type and group */
type = raw_insn->mnem_flag & ~INS_FLAG_MASK;
inv->group = (enum x86_insn_group) (INS_GROUP(type)) >> 12;
inv->type = (enum x86_insn_type) INS_TYPE(type);
/* handle operands */
size += ia32_decode_invariant( buf + size, buf_len - size, raw_insn,
&buf[size - 1], prefixes, inv );
inv->size = size;
return size; /* return size of instruction in bytes */
}
size_t ia32_disasm_size( unsigned char *buf, size_t buf_len ) {
x86_invariant_t inv = { {0} };
return( ia32_disasm_invariant( buf, buf_len, &inv ) );
}
| bsd-3-clause |
MohamedSeliem/contiki | platform/openmote-cc2538/dev/antenna.c | 7 | 3339 | /*
* Copyright (c) 2014, Thingsquare, http://www.thingsquare.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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*
*/
/*---------------------------------------------------------------------------*/
/**
* \addtogroup openmote-antenna
* @{
*
* Driver for the OpenMote-CC2538 RF switch.
* INT is the internal antenna (chip) configured through ANT1_SEL (V1)
* EXT is the external antenna (connector) configured through ANT2_SEL (V2)
* @{
*
* \file
* Driver implementation for the OpenMote-CC2538 antenna switch
*/
/*---------------------------------------------------------------------------*/
#include "contiki-conf.h"
#include "dev/gpio.h"
#include "dev/antenna.h"
/*---------------------------------------------------------------------------*/
#define BSP_RADIO_BASE GPIO_PORT_TO_BASE(GPIO_D_NUM)
#define BSP_RADIO_INT GPIO_PIN_MASK(5)
#define BSP_RADIO_EXT GPIO_PIN_MASK(4)
/*---------------------------------------------------------------------------*/
void
antenna_init(void)
{
/* Configure the ANT1 and ANT2 GPIO as output */
GPIO_SET_OUTPUT(BSP_RADIO_BASE, BSP_RADIO_INT);
GPIO_SET_OUTPUT(BSP_RADIO_BASE, BSP_RADIO_EXT);
/* Select external antenna by default. */
antenna_external();
}
/*---------------------------------------------------------------------------*/
void
antenna_external(void)
{
GPIO_WRITE_PIN(BSP_RADIO_BASE, BSP_RADIO_INT, 0);
GPIO_WRITE_PIN(BSP_RADIO_BASE, BSP_RADIO_EXT, 1);
}
/*---------------------------------------------------------------------------*/
void
antenna_internal(void)
{
GPIO_WRITE_PIN(BSP_RADIO_BASE, BSP_RADIO_EXT, 0);
GPIO_WRITE_PIN(BSP_RADIO_BASE, BSP_RADIO_INT, 1);
}
/*---------------------------------------------------------------------------*/
/**
* @}
* @}
*/
| bsd-3-clause |
joone/chromium-crosswalk | third_party/WebKit/Source/modules/bluetooth/NavigatorBluetooth.cpp | 9 | 1220 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/bluetooth/NavigatorBluetooth.h"
#include "core/frame/Navigator.h"
#include "modules/bluetooth/Bluetooth.h"
namespace blink {
NavigatorBluetooth& NavigatorBluetooth::from(Navigator& navigator)
{
NavigatorBluetooth* supplement = static_cast<NavigatorBluetooth*>(HeapSupplement<Navigator>::from(navigator, supplementName()));
if (!supplement) {
supplement = new NavigatorBluetooth();
provideTo(navigator, supplementName(), supplement);
}
return *supplement;
}
Bluetooth* NavigatorBluetooth::bluetooth(Navigator& navigator)
{
return NavigatorBluetooth::from(navigator).bluetooth();
}
Bluetooth* NavigatorBluetooth::bluetooth()
{
if (!m_bluetooth)
m_bluetooth = Bluetooth::create();
return m_bluetooth.get();
}
DEFINE_TRACE(NavigatorBluetooth)
{
visitor->trace(m_bluetooth);
HeapSupplement<Navigator>::trace(visitor);
}
NavigatorBluetooth::NavigatorBluetooth()
{
}
const char* NavigatorBluetooth::supplementName()
{
return "NavigatorBluetooth";
}
} // namespace blink
| bsd-3-clause |
sgraham/nope | third_party/mesa/src/src/mesa/drivers/common/driverfuncs.c | 12 | 12129 | /*
* Mesa 3-D graphics library
* Version: 7.1
*
* Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL 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 "main/glheader.h"
#include "main/imports.h"
#include "main/accum.h"
#include "main/arrayobj.h"
#include "main/context.h"
#include "main/framebuffer.h"
#include "main/mipmap.h"
#include "main/queryobj.h"
#include "main/readpix.h"
#include "main/renderbuffer.h"
#include "main/shaderobj.h"
#include "main/texcompress.h"
#include "main/texformat.h"
#include "main/texgetimage.h"
#include "main/teximage.h"
#include "main/texobj.h"
#include "main/texstore.h"
#include "main/bufferobj.h"
#include "main/fbobject.h"
#include "main/samplerobj.h"
#include "main/syncobj.h"
#include "main/texturebarrier.h"
#include "main/transformfeedback.h"
#include "program/program.h"
#include "tnl/tnl.h"
#include "swrast/swrast.h"
#include "swrast/s_renderbuffer.h"
#include "driverfuncs.h"
#include "meta.h"
/**
* Plug in default functions for all pointers in the dd_function_table
* structure.
* Device drivers should call this function and then plug in any
* functions which it wants to override.
* Some functions (pointers) MUST be implemented by all drivers (REQUIRED).
*
* \param table the dd_function_table to initialize
*/
void
_mesa_init_driver_functions(struct dd_function_table *driver)
{
memset(driver, 0, sizeof(*driver));
driver->GetString = NULL; /* REQUIRED! */
driver->UpdateState = NULL; /* REQUIRED! */
driver->GetBufferSize = NULL; /* REQUIRED! */
driver->ResizeBuffers = _mesa_resize_framebuffer;
driver->Error = NULL;
driver->Finish = NULL;
driver->Flush = NULL;
/* framebuffer/image functions */
driver->Clear = _swrast_Clear;
driver->Accum = _mesa_accum;
driver->RasterPos = _tnl_RasterPos;
driver->DrawPixels = _swrast_DrawPixels;
driver->ReadPixels = _mesa_readpixels;
driver->CopyPixels = _swrast_CopyPixels;
driver->Bitmap = _swrast_Bitmap;
/* Texture functions */
driver->ChooseTextureFormat = _mesa_choose_tex_format;
driver->TexImage = _mesa_store_teximage;
driver->TexSubImage = _mesa_store_texsubimage;
driver->GetTexImage = _mesa_meta_GetTexImage;
driver->CopyTexSubImage = _mesa_meta_CopyTexSubImage;
driver->GenerateMipmap = _mesa_meta_GenerateMipmap;
driver->TestProxyTexImage = _mesa_test_proxy_teximage;
driver->CompressedTexImage = _mesa_store_compressed_teximage;
driver->CompressedTexSubImage = _mesa_store_compressed_texsubimage;
driver->GetCompressedTexImage = _mesa_get_compressed_teximage;
driver->BindTexture = NULL;
driver->NewTextureObject = _mesa_new_texture_object;
driver->DeleteTexture = _mesa_delete_texture_object;
driver->NewTextureImage = _swrast_new_texture_image;
driver->DeleteTextureImage = _swrast_delete_texture_image;
driver->AllocTextureImageBuffer = _swrast_alloc_texture_image_buffer;
driver->FreeTextureImageBuffer = _swrast_free_texture_image_buffer;
driver->MapTextureImage = _swrast_map_teximage;
driver->UnmapTextureImage = _swrast_unmap_teximage;
driver->DrawTex = _mesa_meta_DrawTex;
/* Vertex/fragment programs */
driver->BindProgram = NULL;
driver->NewProgram = _mesa_new_program;
driver->DeleteProgram = _mesa_delete_program;
/* simple state commands */
driver->AlphaFunc = NULL;
driver->BlendColor = NULL;
driver->BlendEquationSeparate = NULL;
driver->BlendFuncSeparate = NULL;
driver->ClipPlane = NULL;
driver->ColorMask = NULL;
driver->ColorMaterial = NULL;
driver->CullFace = NULL;
driver->DrawBuffer = NULL;
driver->DrawBuffers = NULL;
driver->FrontFace = NULL;
driver->DepthFunc = NULL;
driver->DepthMask = NULL;
driver->DepthRange = NULL;
driver->Enable = NULL;
driver->Fogfv = NULL;
driver->Hint = NULL;
driver->Lightfv = NULL;
driver->LightModelfv = NULL;
driver->LineStipple = NULL;
driver->LineWidth = NULL;
driver->LogicOpcode = NULL;
driver->PointParameterfv = NULL;
driver->PointSize = NULL;
driver->PolygonMode = NULL;
driver->PolygonOffset = NULL;
driver->PolygonStipple = NULL;
driver->ReadBuffer = NULL;
driver->RenderMode = NULL;
driver->Scissor = NULL;
driver->ShadeModel = NULL;
driver->StencilFuncSeparate = NULL;
driver->StencilOpSeparate = NULL;
driver->StencilMaskSeparate = NULL;
driver->TexGen = NULL;
driver->TexEnv = NULL;
driver->TexParameter = NULL;
driver->Viewport = NULL;
/* buffer objects */
_mesa_init_buffer_object_functions(driver);
/* query objects */
_mesa_init_query_object_functions(driver);
_mesa_init_sync_object_functions(driver);
driver->NewFramebuffer = _mesa_new_framebuffer;
driver->NewRenderbuffer = _swrast_new_soft_renderbuffer;
driver->MapRenderbuffer = _swrast_map_soft_renderbuffer;
driver->UnmapRenderbuffer = _swrast_unmap_soft_renderbuffer;
driver->RenderTexture = _swrast_render_texture;
driver->FinishRenderTexture = _swrast_finish_render_texture;
driver->FramebufferRenderbuffer = _mesa_framebuffer_renderbuffer;
driver->ValidateFramebuffer = _mesa_validate_framebuffer;
driver->BlitFramebuffer = _swrast_BlitFramebuffer;
_mesa_init_texture_barrier_functions(driver);
/* APPLE_vertex_array_object */
driver->NewArrayObject = _mesa_new_array_object;
driver->DeleteArrayObject = _mesa_delete_array_object;
driver->BindArrayObject = NULL;
_mesa_init_shader_object_functions(driver);
_mesa_init_transform_feedback_functions(driver);
_mesa_init_sampler_object_functions(driver);
/* T&L stuff */
driver->CurrentExecPrimitive = 0;
driver->CurrentSavePrimitive = 0;
driver->NeedFlush = 0;
driver->SaveNeedFlush = 0;
driver->ProgramStringNotify = _tnl_program_string;
driver->FlushVertices = NULL;
driver->SaveFlushVertices = NULL;
driver->PrepareExecBegin = NULL;
driver->NotifySaveBegin = NULL;
driver->LightingSpaceChange = NULL;
/* display list */
driver->NewList = NULL;
driver->EndList = NULL;
driver->BeginCallList = NULL;
driver->EndCallList = NULL;
/* GL_ARB_texture_storage */
driver->AllocTextureStorage = _swrast_AllocTextureStorage;
}
/**
* Call the ctx->Driver.* state functions with current values to initialize
* driver state.
* Only the Intel drivers use this so far.
*/
void
_mesa_init_driver_state(struct gl_context *ctx)
{
ctx->Driver.AlphaFunc(ctx, ctx->Color.AlphaFunc, ctx->Color.AlphaRef);
ctx->Driver.BlendColor(ctx, ctx->Color.BlendColor);
ctx->Driver.BlendEquationSeparate(ctx,
ctx->Color.Blend[0].EquationRGB,
ctx->Color.Blend[0].EquationA);
ctx->Driver.BlendFuncSeparate(ctx,
ctx->Color.Blend[0].SrcRGB,
ctx->Color.Blend[0].DstRGB,
ctx->Color.Blend[0].SrcA,
ctx->Color.Blend[0].DstA);
if (ctx->Driver.ColorMaskIndexed) {
GLuint i;
for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
ctx->Driver.ColorMaskIndexed(ctx, i,
ctx->Color.ColorMask[i][RCOMP],
ctx->Color.ColorMask[i][GCOMP],
ctx->Color.ColorMask[i][BCOMP],
ctx->Color.ColorMask[i][ACOMP]);
}
}
else {
ctx->Driver.ColorMask(ctx,
ctx->Color.ColorMask[0][RCOMP],
ctx->Color.ColorMask[0][GCOMP],
ctx->Color.ColorMask[0][BCOMP],
ctx->Color.ColorMask[0][ACOMP]);
}
ctx->Driver.CullFace(ctx, ctx->Polygon.CullFaceMode);
ctx->Driver.DepthFunc(ctx, ctx->Depth.Func);
ctx->Driver.DepthMask(ctx, ctx->Depth.Mask);
ctx->Driver.Enable(ctx, GL_ALPHA_TEST, ctx->Color.AlphaEnabled);
ctx->Driver.Enable(ctx, GL_BLEND, ctx->Color.BlendEnabled);
ctx->Driver.Enable(ctx, GL_COLOR_LOGIC_OP, ctx->Color.ColorLogicOpEnabled);
ctx->Driver.Enable(ctx, GL_COLOR_SUM, ctx->Fog.ColorSumEnabled);
ctx->Driver.Enable(ctx, GL_CULL_FACE, ctx->Polygon.CullFlag);
ctx->Driver.Enable(ctx, GL_DEPTH_TEST, ctx->Depth.Test);
ctx->Driver.Enable(ctx, GL_DITHER, ctx->Color.DitherFlag);
ctx->Driver.Enable(ctx, GL_FOG, ctx->Fog.Enabled);
ctx->Driver.Enable(ctx, GL_LIGHTING, ctx->Light.Enabled);
ctx->Driver.Enable(ctx, GL_LINE_SMOOTH, ctx->Line.SmoothFlag);
ctx->Driver.Enable(ctx, GL_POLYGON_STIPPLE, ctx->Polygon.StippleFlag);
ctx->Driver.Enable(ctx, GL_SCISSOR_TEST, ctx->Scissor.Enabled);
ctx->Driver.Enable(ctx, GL_STENCIL_TEST, ctx->Stencil._Enabled);
ctx->Driver.Enable(ctx, GL_TEXTURE_1D, GL_FALSE);
ctx->Driver.Enable(ctx, GL_TEXTURE_2D, GL_FALSE);
ctx->Driver.Enable(ctx, GL_TEXTURE_RECTANGLE_NV, GL_FALSE);
ctx->Driver.Enable(ctx, GL_TEXTURE_3D, GL_FALSE);
ctx->Driver.Enable(ctx, GL_TEXTURE_CUBE_MAP, GL_FALSE);
ctx->Driver.Fogfv(ctx, GL_FOG_COLOR, ctx->Fog.Color);
{
GLfloat mode = (GLfloat) ctx->Fog.Mode;
ctx->Driver.Fogfv(ctx, GL_FOG_MODE, &mode);
}
ctx->Driver.Fogfv(ctx, GL_FOG_DENSITY, &ctx->Fog.Density);
ctx->Driver.Fogfv(ctx, GL_FOG_START, &ctx->Fog.Start);
ctx->Driver.Fogfv(ctx, GL_FOG_END, &ctx->Fog.End);
ctx->Driver.FrontFace(ctx, ctx->Polygon.FrontFace);
{
GLfloat f = (GLfloat) ctx->Light.Model.ColorControl;
ctx->Driver.LightModelfv(ctx, GL_LIGHT_MODEL_COLOR_CONTROL, &f);
}
ctx->Driver.LineWidth(ctx, ctx->Line.Width);
ctx->Driver.LogicOpcode(ctx, ctx->Color.LogicOp);
ctx->Driver.PointSize(ctx, ctx->Point.Size);
ctx->Driver.PolygonStipple(ctx, (const GLubyte *) ctx->PolygonStipple);
ctx->Driver.Scissor(ctx, ctx->Scissor.X, ctx->Scissor.Y,
ctx->Scissor.Width, ctx->Scissor.Height);
ctx->Driver.ShadeModel(ctx, ctx->Light.ShadeModel);
ctx->Driver.StencilFuncSeparate(ctx, GL_FRONT,
ctx->Stencil.Function[0],
ctx->Stencil.Ref[0],
ctx->Stencil.ValueMask[0]);
ctx->Driver.StencilFuncSeparate(ctx, GL_BACK,
ctx->Stencil.Function[1],
ctx->Stencil.Ref[1],
ctx->Stencil.ValueMask[1]);
ctx->Driver.StencilMaskSeparate(ctx, GL_FRONT, ctx->Stencil.WriteMask[0]);
ctx->Driver.StencilMaskSeparate(ctx, GL_BACK, ctx->Stencil.WriteMask[1]);
ctx->Driver.StencilOpSeparate(ctx, GL_FRONT,
ctx->Stencil.FailFunc[0],
ctx->Stencil.ZFailFunc[0],
ctx->Stencil.ZPassFunc[0]);
ctx->Driver.StencilOpSeparate(ctx, GL_BACK,
ctx->Stencil.FailFunc[1],
ctx->Stencil.ZFailFunc[1],
ctx->Stencil.ZPassFunc[1]);
ctx->Driver.DrawBuffer(ctx, ctx->Color.DrawBuffer[0]);
}
| bsd-3-clause |
gem5/gem5 | ext/systemc/src/sysc/kernel/sc_attribute.cpp | 13 | 4764 | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
sc_attribute.cpp -- Attribute classes.
Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21
CHANGE LOG APPEARS AT THE END OF THE FILE
*****************************************************************************/
#include "sysc/kernel/sc_attribute.h"
namespace sc_core {
// ----------------------------------------------------------------------------
// CLASS : sc_attr_base
//
// Attribute base class.
// ----------------------------------------------------------------------------
// constructors
sc_attr_base::sc_attr_base( const std::string& name_ )
: m_name( name_ )
{}
sc_attr_base::sc_attr_base( const sc_attr_base& a )
: m_name( a.m_name )
{}
// destructor (does nothing)
sc_attr_base::~sc_attr_base()
{}
// get the name
const std::string&
sc_attr_base::name() const
{
return m_name;
}
// ----------------------------------------------------------------------------
// CLASS : sc_attr_cltn
//
// Attribute collection class. Stores pointers to attributes.
// Note: iterate over the collection by using iterators.
// ----------------------------------------------------------------------------
// constructors
sc_attr_cltn::sc_attr_cltn() : m_cltn()
{}
sc_attr_cltn::sc_attr_cltn( const sc_attr_cltn& a )
: m_cltn( a.m_cltn )
{}
// destructor
sc_attr_cltn::~sc_attr_cltn()
{
remove_all();
}
// add attribute to the collection.
// returns 'true' if the name of the attribute is unique,
// returns 'false' otherwise (attribute is not added).
bool
sc_attr_cltn::push_back( sc_attr_base* attribute_ )
{
if( attribute_ == 0 ) {
return false;
}
for( int i = m_cltn.size() - 1; i >= 0; -- i ) {
if( attribute_->name() == m_cltn[i]->name() ) {
return false;
}
}
m_cltn.push_back( attribute_ );
return true;
}
// get attribute by name.
// returns pointer to attribute, or 0 if name does not exist.
sc_attr_base*
sc_attr_cltn::operator [] ( const std::string& name_ )
{
for( int i = m_cltn.size() - 1; i >= 0; -- i ) {
if( name_ == m_cltn[i]->name() ) {
return m_cltn[i];
}
}
return 0;
}
const sc_attr_base*
sc_attr_cltn::operator [] ( const std::string& name_ ) const
{
for( int i = m_cltn.size() - 1; i >= 0; -- i ) {
if( name_ == m_cltn[i]->name() ) {
return m_cltn[i];
}
}
return 0;
}
// remove attribute by name.
// returns pointer to attribute, or 0 if name does not exist.
sc_attr_base*
sc_attr_cltn::remove( const std::string& name_ )
{
for( int i = m_cltn.size() - 1; i >= 0; -- i ) {
if( name_ == m_cltn[i]->name() ) {
sc_attr_base* attribute = m_cltn[i];
std::swap( m_cltn[i], m_cltn.back() );
m_cltn.pop_back();
return attribute;
}
}
return 0;
}
// remove all attributes
void
sc_attr_cltn::remove_all()
{
m_cltn.clear();
}
} // namespace sc_core
// $Log: sc_attribute.cpp,v $
// Revision 1.7 2011/08/26 20:46:08 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
// Revision 1.6 2011/08/24 22:05:50 acg
// Torsten Maehne: initialization changes to remove warnings.
//
// Revision 1.5 2011/02/18 20:27:14 acg
// Andy Goodrich: Updated Copyrights.
//
// Revision 1.4 2011/02/13 21:47:37 acg
// Andy Goodrich: update copyright notice.
//
// Revision 1.3 2010/07/22 20:02:33 acg
// Andy Goodrich: bug fixes.
//
// Revision 1.2 2008/05/22 17:06:24 acg
// Andy Goodrich: updated copyright notice to include 2008.
//
// Revision 1.1.1.1 2006/12/15 20:20:05 acg
// SystemC 2.3
//
// Revision 1.4 2006/01/16 22:27:08 acg
// Test of $Log comment.
//
// Revision 1.3 2006/01/13 18:44:29 acg
// Added $Log to record CVS changes into the source.
// Taf!
| bsd-3-clause |
crosswalk-project/blink-crosswalk | Source/platform/text/StringTruncator.cpp | 13 | 7317 | /*
* Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/text/StringTruncator.h"
#include "platform/fonts/Font.h"
#include "platform/text/TextBreakIterator.h"
#include "platform/text/TextRun.h"
#include "wtf/Assertions.h"
#include "wtf/text/CharacterNames.h"
namespace blink {
#define STRING_BUFFER_SIZE 2048
typedef unsigned TruncationFunction(const String&, unsigned length, unsigned keepCount, UChar* buffer);
static inline int textBreakAtOrPreceding(const NonSharedCharacterBreakIterator& it, int offset)
{
if (it.isBreak(offset))
return offset;
int result = it.preceding(offset);
return result == TextBreakDone ? 0 : result;
}
static inline int boundedTextBreakFollowing(const NonSharedCharacterBreakIterator& it, int offset, int length)
{
int result = it.following(offset);
return result == TextBreakDone ? length : result;
}
static unsigned centerTruncateToBuffer(const String& string, unsigned length, unsigned keepCount, UChar* buffer)
{
ASSERT(keepCount < length);
ASSERT(keepCount < STRING_BUFFER_SIZE);
unsigned omitStart = (keepCount + 1) / 2;
NonSharedCharacterBreakIterator it(string);
unsigned omitEnd = boundedTextBreakFollowing(it, omitStart + (length - keepCount) - 1, length);
omitStart = textBreakAtOrPreceding(it, omitStart);
unsigned truncatedLength = omitStart + 1 + (length - omitEnd);
ASSERT(truncatedLength <= length);
string.copyTo(buffer, 0, omitStart);
buffer[omitStart] = horizontalEllipsisCharacter;
string.copyTo(&buffer[omitStart + 1], omitEnd, length - omitEnd);
return truncatedLength;
}
static unsigned rightTruncateToBuffer(const String& string, unsigned length, unsigned keepCount, UChar* buffer)
{
ASSERT(keepCount < length);
ASSERT(keepCount < STRING_BUFFER_SIZE);
NonSharedCharacterBreakIterator it(string);
unsigned keepLength = textBreakAtOrPreceding(it, keepCount);
unsigned truncatedLength = keepLength + 1;
string.copyTo(buffer, 0, keepLength);
buffer[keepLength] = horizontalEllipsisCharacter;
return truncatedLength;
}
static float stringWidth(const Font& renderer, const String& string)
{
TextRun run(string);
return renderer.width(run);
}
static float stringWidth(const Font& renderer, const UChar* characters, unsigned length)
{
TextRun run(characters, length);
return renderer.width(run);
}
static String truncateString(const String& string, float maxWidth, const Font& font, TruncationFunction truncateToBuffer)
{
if (string.isEmpty())
return string;
ASSERT(maxWidth >= 0);
float currentEllipsisWidth = stringWidth(font, &horizontalEllipsisCharacter, 1);
UChar stringBuffer[STRING_BUFFER_SIZE];
unsigned truncatedLength;
unsigned keepCount;
unsigned length = string.length();
if (length > STRING_BUFFER_SIZE) {
keepCount = STRING_BUFFER_SIZE - 1; // need 1 character for the ellipsis
truncatedLength = centerTruncateToBuffer(string, length, keepCount, stringBuffer);
} else {
keepCount = length;
string.copyTo(stringBuffer, 0, length);
truncatedLength = length;
}
float width = stringWidth(font, stringBuffer, truncatedLength);
if (width <= maxWidth)
return string;
unsigned keepCountForLargestKnownToFit = 0;
float widthForLargestKnownToFit = currentEllipsisWidth;
unsigned keepCountForSmallestKnownToNotFit = keepCount;
float widthForSmallestKnownToNotFit = width;
if (currentEllipsisWidth >= maxWidth) {
keepCountForLargestKnownToFit = 1;
keepCountForSmallestKnownToNotFit = 2;
}
while (keepCountForLargestKnownToFit + 1 < keepCountForSmallestKnownToNotFit) {
ASSERT(widthForLargestKnownToFit <= maxWidth);
ASSERT(widthForSmallestKnownToNotFit > maxWidth);
float ratio = (keepCountForSmallestKnownToNotFit - keepCountForLargestKnownToFit)
/ (widthForSmallestKnownToNotFit - widthForLargestKnownToFit);
keepCount = static_cast<unsigned>(maxWidth * ratio);
if (keepCount <= keepCountForLargestKnownToFit) {
keepCount = keepCountForLargestKnownToFit + 1;
} else if (keepCount >= keepCountForSmallestKnownToNotFit) {
keepCount = keepCountForSmallestKnownToNotFit - 1;
}
ASSERT(keepCount < length);
ASSERT(keepCount > 0);
ASSERT(keepCount < keepCountForSmallestKnownToNotFit);
ASSERT(keepCount > keepCountForLargestKnownToFit);
truncatedLength = truncateToBuffer(string, length, keepCount, stringBuffer);
width = stringWidth(font, stringBuffer, truncatedLength);
if (width <= maxWidth) {
keepCountForLargestKnownToFit = keepCount;
widthForLargestKnownToFit = width;
} else {
keepCountForSmallestKnownToNotFit = keepCount;
widthForSmallestKnownToNotFit = width;
}
}
if (!keepCountForLargestKnownToFit)
keepCountForLargestKnownToFit = 1;
if (keepCount != keepCountForLargestKnownToFit) {
keepCount = keepCountForLargestKnownToFit;
truncatedLength = truncateToBuffer(string, length, keepCount, stringBuffer);
}
return String(stringBuffer, truncatedLength);
}
String StringTruncator::centerTruncate(const String& string, float maxWidth, const Font& font)
{
return truncateString(string, maxWidth, font, centerTruncateToBuffer);
}
String StringTruncator::rightTruncate(const String& string, float maxWidth, const Font& font)
{
return truncateString(string, maxWidth, font, rightTruncateToBuffer);
}
float StringTruncator::width(const String& string, const Font& font)
{
return stringWidth(font, string);
}
} // namespace blink
| bsd-3-clause |
anasazi/POP-REU-Project | pkgs/apps/ferret/src/src/bench.c | 14 | 4094 | /* AUTORIGHTS
Copyright (C) 2007 Princeton University
This file is part of Ferret Toolkit.
Ferret Toolkit is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <cass.h>
#include <cass_bench.h>
extern size_t D, N;
/* extern float *weight; */
extern float **points;
int
benchT_read(benchT *bench, const char *fname, int Q)
{
int i, j;
FILE *fp = fopen(fname, "r");
queryT *query;
if (fp == NULL) return -1;
bench->qrys = (queryT *)calloc(Q, sizeof(queryT));
for (i=0; i<Q; i++) {
query = &bench->qrys[i];
if (fscanf(fp, "%d", &(query->qry)) != 1) break;
fscanf(fp, "%d", &(query->knn));
query->nabors = (int *)calloc(query->knn, sizeof(int));
query->dist = (float *)calloc(query->knn, sizeof(float));
/*
query->dists = (float *)calloc(query->knn, sizeof(float));
*/
for (j=0; j<query->knn; j++) {
fscanf(fp, "%d", &(query->nabors[j]));
fscanf(fp, "%g", &(query->dist[j]));
/*
query->dists[j] = dist_l2(D, points[query->qry], points[query->nabors[j]], weight);
*/
}
}
fclose(fp);
bench->Q = Q;
bench->score = NULL;
return 0;
}
void
benchT_free(benchT *bench)
{
int i;
for (i=0; i<bench->Q; i++) {
free(bench->qrys[i].nabors);
free(bench->qrys[i].dist);
}
free(bench->qrys);
}
int
benchT_qry(benchT *bench, int x)
{
if (x < bench->Q)
return bench->qrys[x].qry;
else
return -1;
}
int *
benchT_nabors(benchT *bench, int x)
{
if (x < bench->Q)
return bench->qrys[x].nabors;
else
return NULL;
}
void
benchT_print(benchT *bench, int x)
{
int i;
queryT *query = &bench->qrys[x];
printf("qry %d:\n", query->qry);
for (i=0; i<query->knn; i++)
printf(" %d", query->nabors[i]);
printf("\n");
}
float
benchT_score_topk(benchT *bench, int x, int K, int cnt, cass_list_entry_t *results)
{
int i, j;
int matched = 0;
float recall;
queryT *query = &bench->qrys[x];
// benchT_print(bench, x);
for (i=0; i<K; i++) {
j = 0;
while ((j < cnt) && (results[j].id != query->nabors[i]))
j++;
if (j < cnt) {
matched++;
if (matched == K)
break;
}
}
recall = (float)matched / K;
return recall;
}
float
benchT_prec_topk(benchT *bench, int x, int K, int cnt, ftopk_t *results, float *prec)
{
int i, j;
float p;
queryT *query = &bench->qrys[x];
// benchT_print(bench, x);
p = 0;
for (i=0; i<K; i++) {
j = 0;
while ((j < cnt) && (results[j].index != query->nabors[i]))
j++;
if (j < cnt) {
prec[i] = (float) (i + 1) / (float) (j + 1);
}
else
{
prec[i] = 0.0;
}
p += prec[i];
}
p /= K;
return p;
}
float
benchT_score(benchT *bench, int x, int K, int cnt, int *results)
{
int i, j;
int matched = 0;
float recall;
queryT *query = &bench->qrys[x];
// benchT_print(bench, x);
for (i=0; i<K; i++) {
j = 0;
while ((j < cnt) && (results[j] != query->nabors[i]))
j++;
if (j < cnt) {
matched++;
if (matched == K)
break;
}
}
recall = (float)matched / K;
return recall;
}
/*
float
benchT_score_dist(benchT *bench, int x, int K, int cnt, float *dists)
{
int i;
float error;
queryT *query = &bench->qrys[x];
error = 0.0;
for (i=0; i<cnt; i++) {
if (query->dists[i] > 0)
error += dists[i] / query->dists[i];
else if (dists[i] == 0)
error += 1.0;
else
printf("ERROR:\t%d\t%.3f\t%.3f\n", i, dists[i], query->dists[i]);
//printf("%d\t%.3f\t%.3f\t%.3f\n", i, dists[i], query->dists[i], error);
}
return error/cnt;
}
*/
| bsd-3-clause |
xlsdg/phantomjs-linux-armv6l | src/qt/src/gui/styles/qstyle.cpp | 15 | 109382 | /****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qstyle.h"
#include "qapplication.h"
#include "qpainter.h"
#include "qwidget.h"
#include "qbitmap.h"
#include "qpixmapcache.h"
#include "qstyleoption.h"
#include "private/qstyle_p.h"
#include "private/qapplication_p.h"
#ifndef QT_NO_DEBUG
#include "qdebug.h"
#endif
#ifdef Q_WS_X11
#include <qx11info_x11.h>
#endif
#include <limits.h>
QT_BEGIN_NAMESPACE
static const int MaxBits = 8 * sizeof(QSizePolicy::ControlType);
static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::ControlType *array)
{
if (!controls)
return 0;
// optimization: exactly one bit is set
if ((controls & (controls - 1)) == 0) {
array[0] = QSizePolicy::ControlType(uint(controls));
return 1;
}
int count = 0;
for (int i = 0; i < MaxBits; ++i) {
if (uint bit = (controls & (0x1 << i)))
array[count++] = QSizePolicy::ControlType(bit);
}
return count;
}
/*!
\class QStyle
\brief The QStyle class is an abstract base class that encapsulates the look and feel of a GUI.
\ingroup appearance
Qt contains a set of QStyle subclasses that emulate the styles of
the different platforms supported by Qt (QWindowsStyle,
QMacStyle, QMotifStyle, etc.). By default, these styles are built
into the QtGui library. Styles can also be made available as
plugins.
Qt's built-in widgets use QStyle to perform nearly all of their
drawing, ensuring that they look exactly like the equivalent
native widgets. The diagram below shows a QComboBox in eight
different styles.
\img qstyle-comboboxes.png Eight combo boxes
Topics:
\tableofcontents
\section1 Setting a Style
The style of the entire application can be set using the
QApplication::setStyle() function. It can also be specified by the
user of the application, using the \c -style command-line option:
\snippet doc/src/snippets/code/src_gui_styles_qstyle.cpp 0
If no style is specified, Qt will choose the most appropriate
style for the user's platform or desktop environment.
A style can also be set on an individual widget using the
QWidget::setStyle() function.
\section1 Developing Style-Aware Custom Widgets
If you are developing custom widgets and want them to look good on
all platforms, you can use QStyle functions to perform parts of
the widget drawing, such as drawItemText(), drawItemPixmap(),
drawPrimitive(), drawControl(), and drawComplexControl().
Most QStyle draw functions take four arguments:
\list
\o an enum value specifying which graphical element to draw
\o a QStyleOption specifying how and where to render that element
\o a QPainter that should be used to draw the element
\o a QWidget on which the drawing is performed (optional)
\endlist
For example, if you want to draw a focus rectangle on your
widget, you can write:
\snippet doc/src/snippets/styles/styles.cpp 1
QStyle gets all the information it needs to render the graphical
element from QStyleOption. The widget is passed as the last
argument in case the style needs it to perform special effects
(such as animated default buttons on Mac OS X), but it isn't
mandatory. In fact, you can use QStyle to draw on any paint
device, not just widgets, by setting the QPainter properly.
QStyleOption has various subclasses for the various types of
graphical elements that can be drawn. For example,
PE_FrameFocusRect expects a QStyleOptionFocusRect argument.
To ensure that drawing operations are as fast as possible,
QStyleOption and its subclasses have public data members. See the
QStyleOption class documentation for details on how to use it.
For convenience, Qt provides the QStylePainter class, which
combines a QStyle, a QPainter, and a QWidget. This makes it
possible to write
\snippet doc/src/snippets/styles/styles.cpp 5
\dots
\snippet doc/src/snippets/styles/styles.cpp 7
instead of
\snippet doc/src/snippets/styles/styles.cpp 2
\dots
\snippet doc/src/snippets/styles/styles.cpp 3
\section1 Creating a Custom Style
You can create a custom look and feel for your application by
creating a custom style. There are two approaches to creating a
custom style. In the static approach, you either choose an
existing QStyle class, subclass it, and reimplement virtual
functions to provide the custom behavior, or you create an entire
QStyle class from scratch. In the dynamic approach, you modify the
behavior of your system style at runtime. The static approach is
described below. The dynamic approach is described in QProxyStyle.
The first step in the static approach is to pick one of the styles
provided by Qt from which you will build your custom style. Your
choice of QStyle class will depend on which style resembles your
desired style the most. The most general class that you can use as
a base is QCommonStyle (not QStyle). This is because Qt requires
its styles to be \l{QCommonStyle}s.
Depending on which parts of the base style you want to change,
you must reimplement the functions that are used to draw those
parts of the interface. To illustrate this, we will modify the
look of the spin box arrows drawn by QWindowsStyle. The arrows
are \e{primitive elements} that are drawn by the drawPrimitive()
function, so we need to reimplement that function. We need the
following class declaration:
\snippet doc/src/snippets/customstyle/customstyle.h 0
To draw its up and down arrows, QSpinBox uses the
PE_IndicatorSpinUp and PE_IndicatorSpinDown primitive elements.
Here's how to reimplement the drawPrimitive() function to draw
them differently:
\snippet doc/src/snippets/customstyle/customstyle.cpp 2
\snippet doc/src/snippets/customstyle/customstyle.cpp 3
\snippet doc/src/snippets/customstyle/customstyle.cpp 4
Notice that we don't use the \c widget argument, except to pass it
on to the QWindowStyle::drawPrimitive() function. As mentioned
earlier, the information about what is to be drawn and how it
should be drawn is specified by a QStyleOption object, so there is
no need to ask the widget.
If you need to use the \c widget argument to obtain additional
information, be careful to ensure that it isn't 0 and that it is
of the correct type before using it. For example:
\snippet doc/src/snippets/customstyle/customstyle.cpp 0
\dots
\snippet doc/src/snippets/customstyle/customstyle.cpp 1
When implementing a custom style, you cannot assume that the
widget is a QSpinBox just because the enum value is called
PE_IndicatorSpinUp or PE_IndicatorSpinDown.
The documentation for the \l{widgets/styles}{Styles} example
covers this topic in more detail.
\warning Qt style sheets are currently not supported for custom QStyle
subclasses. We plan to address this in some future release.
\section1 Using a Custom Style
There are several ways of using a custom style in a Qt
application. The simplest way is to pass the custom style to the
QApplication::setStyle() static function before creating the
QApplication object:
\snippet snippets/customstyle/main.cpp using a custom style
You can call QApplication::setStyle() at any time, but by calling
it before the constructor, you ensure that the user's preference,
set using the \c -style command-line option, is respected.
You may want to make your custom style available for use in other
applications, which may not be yours and hence not available for
you to recompile. The Qt Plugin system makes it possible to create
styles as plugins. Styles created as plugins are loaded as shared
objects at runtime by Qt itself. Please refer to the \link
plugins-howto.html Qt Plugin\endlink documentation for more
information on how to go about creating a style plugin.
Compile your plugin and put it into Qt's \c plugins/styles
directory. We now have a pluggable style that Qt can load
automatically. To use your new style with existing applications,
simply start the application with the following argument:
\snippet doc/src/snippets/code/src_gui_styles_qstyle.cpp 1
The application will use the look and feel from the custom style you
implemented.
\section1 Right-to-Left Desktops
Languages written from right to left (such as Arabic and Hebrew)
usually also mirror the whole layout of widgets, and require the
light to come from the screen's top-right corner instead of
top-left.
If you create a custom style, you should take special care when
drawing asymmetric elements to make sure that they also look
correct in a mirrored layout. An easy way to test your styles is
to run applications with the \c -reverse command-line option or
to call QApplication::setLayoutDirection() in your \c main()
function.
Here are some things to keep in mind when making a style work well in a
right-to-left environment:
\list
\o subControlRect() and subElementRect() return rectangles in screen coordinates
\o QStyleOption::direction indicates in which direction the item should be drawn in
\o If a style is not right-to-left aware it will display items as if it were left-to-right
\o visualRect(), visualPos(), and visualAlignment() are helpful functions that will
translate from logical to screen representations.
\o alignedRect() will return a logical rect aligned for the current direction
\endlist
\section1 Styles in Item Views
The painting of items in views is performed by a delegate. Qt's
default delegate, QStyledItemDelegate, is also used for for calculating bounding
rectangles of items, and their sub-elements for the various kind
of item \l{Qt::ItemDataRole}{data roles}
QStyledItemDelegate supports. See the QStyledItemDelegate class
description to find out which datatypes and roles are supported. You
can read more about item data roles in \l{Model/View Programming}.
When QStyledItemDelegate paints its items, it draws
CE_ItemViewItem, and calculates their size with CT_ItemViewItem.
Note also that it uses SE_ItemViewItemText to set the size of
editors. When implementing a style to customize drawing of item
views, you need to check the implementation of QCommonStyle (and
any other subclasses from which your style
inherits). This way, you find out which and how
other style elements are painted, and you can then reimplement the
painting of elements that should be drawn differently.
We include a small example where we customize the drawing of item
backgrounds.
\snippet doc/src/snippets/customviewstyle.cpp 0
The primitive element PE_PanelItemViewItem is responsible for
painting the background of items, and is called from
\l{QCommonStyle}'s implementation of CE_ItemViewItem.
To add support for drawing of new datatypes and item data roles,
it is necessary to create a custom delegate. But if you only
need to support the datatypes implemented by the default
delegate, a custom style does not need an accompanying
delegate. The QStyledItemDelegate class description gives more
information on custom delegates.
The drawing of item view headers is also done by the style, giving
control over size of header items and row and column sizes.
\sa QStyleOption, QStylePainter, {Styles Example},
{Styles and Style Aware Widgets}, QStyledItemDelegate
*/
/*!
Constructs a style object.
*/
QStyle::QStyle()
: QObject(*new QStylePrivate)
{
Q_D(QStyle);
d->proxyStyle = this;
}
/*!
\internal
Constructs a style object.
*/
QStyle::QStyle(QStylePrivate &dd)
: QObject(dd)
{
Q_D(QStyle);
d->proxyStyle = this;
}
/*!
Destroys the style object.
*/
QStyle::~QStyle()
{
}
/*!
Initializes the appearance of the given \a widget.
This function is called for every widget at some point after it
has been fully created but just \e before it is shown for the very
first time.
Note that the default implementation does nothing. Reasonable
actions in this function might be to call the
QWidget::setBackgroundMode() function for the widget. Do not use
the function to set, for example, the geometry. Reimplementing
this function provides a back-door through which the appearance
of a widget can be changed, but with Qt's style engine it is
rarely necessary to implement this function; reimplement
drawItemPixmap(), drawItemText(), drawPrimitive(), etc. instead.
The QWidget::inherits() function may provide enough information to
allow class-specific customizations. But because new QStyle
subclasses are expected to work reasonably with all current and \e
future widgets, limited use of hard-coded customization is
recommended.
\sa unpolish()
*/
void QStyle::polish(QWidget * /* widget */)
{
}
/*!
Uninitialize the given \a{widget}'s appearance.
This function is the counterpart to polish(). It is called for
every polished widget whenever the style is dynamically changed;
the former style has to unpolish its settings before the new style
can polish them again.
Note that unpolish() will only be called if the widget is
destroyed. This can cause problems in some cases, e.g, if you
remove a widget from the UI, cache it, and then reinsert it after
the style has changed; some of Qt's classes cache their widgets.
\sa polish()
*/
void QStyle::unpolish(QWidget * /* widget */)
{
}
/*!
\fn void QStyle::polish(QApplication * application)
\overload
Late initialization of the given \a application object.
*/
void QStyle::polish(QApplication * /* app */)
{
}
/*!
\fn void QStyle::unpolish(QApplication * application)
\overload
Uninitialize the given \a application.
*/
void QStyle::unpolish(QApplication * /* app */)
{
}
/*!
\fn void QStyle::polish(QPalette & palette)
\overload
Changes the \a palette according to style specific requirements
for color palettes (if any).
\sa QPalette, QApplication::setPalette()
*/
void QStyle::polish(QPalette & /* pal */)
{
}
/*!
\fn QRect QStyle::itemTextRect(const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const
Returns the area within the given \a rectangle in which to draw
the provided \a text according to the specified font \a metrics
and \a alignment. The \a enabled parameter indicates whether or
not the associated item is enabled.
If the given \a rectangle is larger than the area needed to render
the \a text, the rectangle that is returned will be offset within
\a rectangle according to the specified \a alignment. For
example, if \a alignment is Qt::AlignCenter, the returned
rectangle will be centered within \a rectangle. If the given \a
rectangle is smaller than the area needed, the returned rectangle
will be the smallest rectangle large enough to render the \a text.
\sa Qt::Alignment
*/
QRect QStyle::itemTextRect(const QFontMetrics &metrics, const QRect &rect, int alignment, bool enabled,
const QString &text) const
{
QRect result;
int x, y, w, h;
rect.getRect(&x, &y, &w, &h);
if (!text.isEmpty()) {
result = metrics.boundingRect(x, y, w, h, alignment, text);
if (!enabled && proxy()->styleHint(SH_EtchDisabledText)) {
result.setWidth(result.width()+1);
result.setHeight(result.height()+1);
}
} else {
result = QRect(x, y, w, h);
}
return result;
}
/*!
\fn QRect QStyle::itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const
Returns the area within the given \a rectangle in which to draw
the specified \a pixmap according to the defined \a alignment.
*/
QRect QStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const
{
QRect result;
int x, y, w, h;
rect.getRect(&x, &y, &w, &h);
if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
y += h/2 - pixmap.height()/2;
else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
y += h - pixmap.height();
if ((alignment & Qt::AlignRight) == Qt::AlignRight)
x += w - pixmap.width();
else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
x += w/2 - pixmap.width()/2;
else if ((alignment & Qt::AlignLeft) != Qt::AlignLeft && QApplication::isRightToLeft())
x += w - pixmap.width();
result = QRect(x, y, pixmap.width(), pixmap.height());
return result;
}
/*!
\fn void QStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString& text, QPalette::ColorRole textRole) const
Draws the given \a text in the specified \a rectangle using the
provided \a painter and \a palette.
The text is drawn using the painter's pen, and aligned and wrapped
according to the specified \a alignment. If an explicit \a
textRole is specified, the text is drawn using the \a palette's
color for the given role. The \a enabled parameter indicates
whether or not the item is enabled; when reimplementing this
function, the \a enabled parameter should influence how the item is
drawn.
\sa Qt::Alignment, drawItemPixmap()
*/
void QStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
bool enabled, const QString& text, QPalette::ColorRole textRole) const
{
if (text.isEmpty())
return;
QPen savedPen;
if (textRole != QPalette::NoRole) {
savedPen = painter->pen();
painter->setPen(QPen(pal.brush(textRole), savedPen.widthF()));
}
if (!enabled) {
if (proxy()->styleHint(SH_DitherDisabledText)) {
QRect br;
painter->drawText(rect, alignment, text, &br);
painter->fillRect(br, QBrush(painter->background().color(), Qt::Dense5Pattern));
return;
} else if (proxy()->styleHint(SH_EtchDisabledText)) {
QPen pen = painter->pen();
painter->setPen(pal.light().color());
painter->drawText(rect.adjusted(1, 1, 1, 1), alignment, text);
painter->setPen(pen);
}
}
painter->drawText(rect, alignment, text);
if (textRole != QPalette::NoRole)
painter->setPen(savedPen);
}
/*!
\fn void QStyle::drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment,
const QPixmap &pixmap) const
Draws the given \a pixmap in the specified \a rectangle, according
to the specified \a alignment, using the provided \a painter.
\sa drawItemText()
*/
void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
const QPixmap &pixmap) const
{
QRect aligned = alignedRect(QApplication::layoutDirection(), QFlag(alignment), pixmap.size(), rect);
QRect inter = aligned.intersected(rect);
painter->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), inter.width(), inter.height());
}
/*!
\enum QStyle::PrimitiveElement
This enum describes the various primitive elements. A
primitive element is a common GUI element, such as a checkbox
indicator or button bevel.
\omitvalue PE_IndicatorViewItemCheck
\value PE_FrameStatusBar Frame
\value PE_PanelButtonCommand Button used to initiate an action, for
example, a QPushButton.
\value PE_FrameDefaultButton This frame around a default button, e.g. in a dialog.
\value PE_PanelButtonBevel Generic panel with a button bevel.
\value PE_PanelButtonTool Panel for a Tool button, used with QToolButton.
\value PE_PanelLineEdit Panel for a QLineEdit.
\value PE_IndicatorButtonDropDown Indicator for a drop down button, for example, a tool
button that displays a menu.
\value PE_FrameFocusRect Generic focus indicator.
\value PE_IndicatorArrowUp Generic Up arrow.
\value PE_IndicatorArrowDown Generic Down arrow.
\value PE_IndicatorArrowRight Generic Right arrow.
\value PE_IndicatorArrowLeft Generic Left arrow.
\value PE_IndicatorSpinUp Up symbol for a spin widget, for example a QSpinBox.
\value PE_IndicatorSpinDown Down symbol for a spin widget.
\value PE_IndicatorSpinPlus Increase symbol for a spin widget.
\value PE_IndicatorSpinMinus Decrease symbol for a spin widget.
\value PE_IndicatorItemViewItemCheck On/off indicator for a view item.
\value PE_IndicatorCheckBox On/off indicator, for example, a QCheckBox.
\value PE_IndicatorRadioButton Exclusive on/off indicator, for example, a QRadioButton.
\value PE_Q3DockWindowSeparator Item separator for Qt 3 compatible dock window
and toolbar contents.
\value PE_IndicatorDockWidgetResizeHandle Resize handle for dock windows.
\value PE_Frame Generic frame
\value PE_FrameMenu Frame for popup windows/menus; see also QMenu.
\value PE_PanelMenuBar Panel for menu bars.
\value PE_PanelScrollAreaCorner Panel at the bottom-right (or
bottom-left) corner of a scroll area.
\value PE_FrameDockWidget Panel frame for dock windows and toolbars.
\value PE_FrameTabWidget Frame for tab widgets.
\value PE_FrameLineEdit Panel frame for line edits.
\value PE_FrameGroupBox Panel frame around group boxes.
\value PE_FrameButtonBevel Panel frame for a button bevel.
\value PE_FrameButtonTool Panel frame for a tool button.
\value PE_IndicatorHeaderArrow Arrow used to indicate sorting on a list or table
header.
\value PE_FrameStatusBarItem Frame for an item of a status bar; see also QStatusBar.
\value PE_FrameWindow Frame around a MDI window or a docking window.
\value PE_Q3Separator Qt 3 compatible generic separator.
\value PE_IndicatorMenuCheckMark Check mark used in a menu.
\value PE_IndicatorProgressChunk Section of a progress bar indicator; see also QProgressBar.
\value PE_Q3CheckListController Qt 3 compatible controller part of a list view item.
\value PE_Q3CheckListIndicator Qt 3 compatible checkbox part of a list view item.
\value PE_Q3CheckListExclusiveIndicator Qt 3 compatible radio button part of a list view item.
\value PE_IndicatorBranch Lines used to represent the branch of a tree in a tree view.
\value PE_IndicatorToolBarHandle The handle of a toolbar.
\value PE_IndicatorToolBarSeparator The separator in a toolbar.
\value PE_PanelToolBar The panel for a toolbar.
\value PE_PanelTipLabel The panel for a tip label.
\value PE_FrameTabBarBase The frame that is drawn for a tab bar, ususally drawn for a tab bar that isn't part of a tab widget.
\value PE_IndicatorTabTear An indicator that a tab is partially scrolled out of the visible tab bar when there are many tabs.
\value PE_IndicatorColumnViewArrow An arrow in a QColumnView.
\value PE_Widget A plain QWidget.
\value PE_CustomBase Base value for custom primitive elements.
All values above this are reserved for custom use. Custom values
must be greater than this value.
\value PE_IndicatorItemViewItemDrop An indicator that is drawn to show where an item in an item view is about to be dropped
during a drag-and-drop operation in an item view.
\value PE_PanelItemViewItem The background for an item in an item view.
\value PE_PanelItemViewRow The background of a row in an item view.
\value PE_PanelStatusBar The panel for a status bar.
\value PE_IndicatorTabClose The close button on a tab bar.
\value PE_PanelMenu The panel for a menu.
\sa drawPrimitive()
*/
/*!
\typedef QStyle::SFlags
\internal
*/
/*!
\typedef QStyle::SCFlags
\internal
*/
/*!
\enum QStyle::StateFlag
This enum describes flags that are used when drawing primitive
elements.
Note that not all primitives use all of these flags, and that the
flags may mean different things to different items.
\value State_None Indicates that the widget does not have a state.
\value State_Active Indicates that the widget is active.
\value State_AutoRaise Used to indicate if auto-raise appearance should be usd on a tool button.
\value State_Children Used to indicate if an item view branch has children.
\value State_DownArrow Used to indicate if a down arrow should be visible on the widget.
\value State_Editing Used to indicate if an editor is opened on the widget.
\value State_Enabled Used to indicate if the widget is enabled.
\value State_HasEditFocus Used to indicate if the widget currently has edit focus.
\value State_HasFocus Used to indicate if the widget has focus.
\value State_Horizontal Used to indicate if the widget is laid out horizontally, for example. a tool bar.
\value State_KeyboardFocusChange Used to indicate if the focus was changed with the keyboard, e.g., tab, backtab or shortcut.
\value State_MouseOver Used to indicate if the widget is under the mouse.
\value State_NoChange Used to indicate a tri-state checkbox.
\value State_Off Used to indicate if the widget is not checked.
\value State_On Used to indicate if the widget is checked.
\value State_Raised Used to indicate if a button is raised.
\value State_ReadOnly Used to indicate if a widget is read-only.
\value State_Selected Used to indicate if a widget is selected.
\value State_Item Used by item views to indicate if a horizontal branch should be drawn.
\value State_Open Used by item views to indicate if the tree branch is open.
\value State_Sibling Used by item views to indicate if a vertical line needs to be drawn (for siblings).
\value State_Sunken Used to indicate if the widget is sunken or pressed.
\value State_UpArrow Used to indicate if an up arrow should be visible on the widget.
\value State_Mini Used to indicate a mini style Mac widget or button.
\value State_Small Used to indicate a small style Mac widget or button.
\omitvalue State_Window
\omitvalue State_Bottom
\omitvalue State_Default
\omitvalue State_FocusAtBorder
\omitvalue State_Top
\sa drawPrimitive()
*/
/*!
\fn void QStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, \
QPainter *painter, const QWidget *widget) const
Draws the given primitive \a element with the provided \a painter using the style
options specified by \a option.
The \a widget argument is optional and may contain a widget that may
aid in drawing the primitive element.
The table below is listing the primitive elements and their
associated style option subclasses. The style options contain all
the parameters required to draw the elements, including
QStyleOption::state which holds the style flags that are used when
drawing. The table also describes which flags that are set when
casting the given option to the appropriate subclass.
Note that if a primitive element is not listed here, it is because
it uses a plain QStyleOption object.
\table
\header \o Primitive Element \o QStyleOption Subclass \o Style Flag \o Remark
\row \o \l PE_FrameFocusRect \o \l QStyleOptionFocusRect
\o \l State_FocusAtBorder
\o Whether the focus is is at the border or inside the widget.
\row \o{1,2} \l PE_IndicatorCheckBox \o{1,2} \l QStyleOptionButton
\o \l State_NoChange \o Indicates a "tri-state" checkbox.
\row \o \l State_On \o Indicates the indicator is checked.
\row \o \l PE_IndicatorRadioButton \o \l QStyleOptionButton
\o \l State_On \o Indicates that a radio button is selected.
\row \o{1,3} \l PE_Q3CheckListExclusiveIndicator, \l PE_Q3CheckListIndicator
\o{1,3} \l QStyleOptionQ3ListView \o \l State_On
\o Indicates whether or not the controller is selected.
\row \o \l State_NoChange \o Indicates a "tri-state" controller.
\row \o \l State_Enabled \o Indicates the controller is enabled.
\row \o{1,4} \l PE_IndicatorBranch \o{1,4} \l QStyleOption
\o \l State_Children \o Indicates that the control for expanding the tree to show child items, should be drawn.
\row \o \l State_Item \o Indicates that a horizontal branch (to show a child item), should be drawn.
\row \o \l State_Open \o Indicates that the tree branch is expanded.
\row \o \l State_Sibling \o Indicates that a vertical line (to show a sibling item), should be drawn.
\row \o \l PE_IndicatorHeaderArrow \o \l QStyleOptionHeader
\o \l State_UpArrow \o Indicates that the arrow should be drawn up;
otherwise it should be down.
\row \o \l PE_FrameGroupBox, \l PE_Frame, \l PE_FrameLineEdit,
\l PE_FrameMenu, \l PE_FrameDockWidget, \l PE_FrameWindow
\o \l QStyleOptionFrame \o \l State_Sunken
\o Indicates that the Frame should be sunken.
\row \o \l PE_IndicatorToolBarHandle \o \l QStyleOption
\o \l State_Horizontal \o Indicates that the window handle is horizontal
instead of vertical.
\row \o \l PE_Q3DockWindowSeparator \o \l QStyleOption
\o \l State_Horizontal \o Indicates that the separator is horizontal
instead of vertical.
\row \o \l PE_IndicatorSpinPlus, \l PE_IndicatorSpinMinus, \l PE_IndicatorSpinUp,
\l PE_IndicatorSpinDown,
\o \l QStyleOptionSpinBox
\o \l State_Sunken \o Indicates that the button is pressed.
\row \o{1,5} \l PE_PanelButtonCommand
\o{1,5} \l QStyleOptionButton
\o \l State_Enabled \o Set if the button is enabled.
\row \o \l State_HasFocus \o Set if the button has input focus.
\row \o \l State_Raised \o Set if the button is not down, not on and not flat.
\row \o \l State_On \o Set if the button is a toggle button and is toggled on.
\row \o \l State_Sunken
\o Set if the button is down (i.e., the mouse button or the
space bar is pressed on the button).
\endtable
\sa drawComplexControl(), drawControl()
*/
/*!
\enum QStyle::ControlElement
This enum represents a control element. A control element is a
part of a widget that performs some action or displays information
to the user.
\value CE_PushButton A QPushButton, draws CE_PushButtonBevel, CE_PushButtonLabel and PE_FrameFocusRect.
\value CE_PushButtonBevel The bevel and default indicator of a QPushButton.
\value CE_PushButtonLabel The label (an icon with text or pixmap) of a QPushButton.
\value CE_DockWidgetTitle Dock window title.
\value CE_Splitter Splitter handle; see also QSplitter.
\value CE_CheckBox A QCheckBox, draws a PE_IndicatorCheckBox, a CE_CheckBoxLabel and a PE_FrameFocusRect.
\value CE_CheckBoxLabel The label (text or pixmap) of a QCheckBox.
\value CE_RadioButton A QRadioButton, draws a PE_IndicatorRadioButton, a CE_RadioButtonLabel and a PE_FrameFocusRect.
\value CE_RadioButtonLabel The label (text or pixmap) of a QRadioButton.
\value CE_TabBarTab The tab and label within a QTabBar.
\value CE_TabBarTabShape The tab shape within a tab bar.
\value CE_TabBarTabLabel The label within a tab.
\value CE_ProgressBar A QProgressBar, draws CE_ProgressBarGroove, CE_ProgressBarContents and CE_ProgressBarLabel.
\value CE_ProgressBarGroove The groove where the progress
indicator is drawn in a QProgressBar.
\value CE_ProgressBarContents The progress indicator of a QProgressBar.
\value CE_ProgressBarLabel The text label of a QProgressBar.
\value CE_ToolButtonLabel A tool button's label.
\value CE_MenuBarItem A menu item in a QMenuBar.
\value CE_MenuBarEmptyArea The empty area of a QMenuBar.
\value CE_MenuItem A menu item in a QMenu.
\value CE_MenuScroller Scrolling areas in a QMenu when the
style supports scrolling.
\value CE_MenuTearoff A menu item representing the tear off section of
a QMenu.
\value CE_MenuEmptyArea The area in a menu without menu items.
\value CE_MenuHMargin The horizontal extra space on the left/right of a menu.
\value CE_MenuVMargin The vertical extra space on the top/bottom of a menu.
\value CE_Q3DockWindowEmptyArea The empty area of a QDockWidget.
\value CE_ToolBoxTab The toolbox's tab and label within a QToolBox.
\value CE_SizeGrip Window resize handle; see also QSizeGrip.
\value CE_Header A header.
\value CE_HeaderSection A header section.
\value CE_HeaderLabel The header's label.
\value CE_ScrollBarAddLine Scroll bar line increase indicator.
(i.e., scroll down); see also QScrollBar.
\value CE_ScrollBarSubLine Scroll bar line decrease indicator (i.e., scroll up).
\value CE_ScrollBarAddPage Scolllbar page increase indicator (i.e., page down).
\value CE_ScrollBarSubPage Scroll bar page decrease indicator (i.e., page up).
\value CE_ScrollBarSlider Scroll bar slider.
\value CE_ScrollBarFirst Scroll bar first line indicator (i.e., home).
\value CE_ScrollBarLast Scroll bar last line indicator (i.e., end).
\value CE_RubberBand Rubber band used in for example an icon view.
\value CE_FocusFrame Focus frame that is style controlled.
\value CE_ItemViewItem An item inside an item view.
\value CE_CustomBase Base value for custom control elements;
custom values must be greater than this value.
\value CE_ComboBoxLabel The label of a non-editable QComboBox.
\value CE_ToolBar A toolbar like QToolBar.
\value CE_ToolBoxTabShape The toolbox's tab shape.
\value CE_ToolBoxTabLabel The toolbox's tab label.
\value CE_HeaderEmptyArea The area of a header view where there are no header sections.
\value CE_ShapedFrame The frame with the shape specified in the QStyleOptionFrameV3; see QFrame.
\omitvalue CE_ColumnViewGrip
\sa drawControl()
*/
/*!
\fn void QStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
Draws the given \a element with the provided \a painter with the
style options specified by \a option.
The \a widget argument is optional and can be used as aid in
drawing the control. The \a option parameter is a pointer to a
QStyleOption object that can be cast to the correct subclass
using the qstyleoption_cast() function.
The table below is listing the control elements and their
associated style option subclass. The style options contain all
the parameters required to draw the controls, including
QStyleOption::state which holds the style flags that are used when
drawing. The table also describes which flags that are set when
casting the given option to the appropriate subclass.
Note that if a control element is not listed here, it is because
it uses a plain QStyleOption object.
\table
\header \o Control Element \o QStyleOption Subclass \o Style Flag \o Remark
\row \o{1,5} \l CE_MenuItem, \l CE_MenuBarItem
\o{1,5} \l QStyleOptionMenuItem
\o \l State_Selected \o The menu item is currently selected item.
\row \o \l State_Enabled \o The item is enabled.
\row \o \l State_DownArrow \o Indicates that a scroll down arrow should be drawn.
\row \o \l State_UpArrow \o Indicates that a scroll up arrow should be drawn
\row \o \l State_HasFocus \o Set if the menu bar has input focus.
\row \o{1,5} \l CE_PushButton, \l CE_PushButtonBevel, \l CE_PushButtonLabel
\o{1,5} \l QStyleOptionButton
\o \l State_Enabled \o Set if the button is enabled.
\row \o \l State_HasFocus \o Set if the button has input focus.
\row \o \l State_Raised \o Set if the button is not down, not on and not flat.
\row \o \l State_On \o Set if the button is a toggle button and is toggled on.
\row \o \l State_Sunken
\o Set if the button is down (i.e., the mouse button or the
space bar is pressed on the button).
\row \o{1,6} \l CE_RadioButton, \l CE_RadioButtonLabel,
\l CE_CheckBox, \l CE_CheckBoxLabel
\o{1,6} \l QStyleOptionButton
\o \l State_Enabled \o Set if the button is enabled.
\row \o \l State_HasFocus \o Set if the button has input focus.
\row \o \l State_On \o Set if the button is checked.
\row \o \l State_Off \o Set if the button is not checked.
\row \o \l State_NoChange \o Set if the button is in the NoChange state.
\row \o \l State_Sunken
\o Set if the button is down (i.e., the mouse button or
the space bar is pressed on the button).
\row \o{1,2} \l CE_ProgressBarContents, \l CE_ProgressBarLabel,
\l CE_ProgressBarGroove
\o{1,2} \l QStyleOptionProgressBar
\o \l State_Enabled \o Set if the progress bar is enabled.
\row \o \l State_HasFocus \o Set if the progress bar has input focus.
\row \o \l CE_Header, \l CE_HeaderSection, \l CE_HeaderLabel \o \l QStyleOptionHeader \o \o
\row \o{1,3} \l CE_TabBarTab, CE_TabBarTabShape, CE_TabBarTabLabel
\o{1,3} \l QStyleOptionTab
\o \l State_Enabled \o Set if the tab bar is enabled.
\row \o \l State_Selected \o The tab bar is the currently selected tab bar.
\row \o \l State_HasFocus \o Set if the tab bar tab has input focus.
\row \o{1,7} \l CE_ToolButtonLabel
\o{1,7} \l QStyleOptionToolButton
\o \l State_Enabled \o Set if the tool button is enabled.
\row \o \l State_HasFocus \o Set if the tool button has input focus.
\row \o \l State_Sunken
\o Set if the tool button is down (i.e., a mouse button or
the space bar is pressed).
\row \o \l State_On \o Set if the tool button is a toggle button and is toggled on.
\row \o \l State_AutoRaise \o Set if the tool button has auto-raise enabled.
\row \o \l State_MouseOver \o Set if the mouse pointer is over the tool button.
\row \o \l State_Raised \o Set if the button is not down and is not on.
\row \o \l CE_ToolBoxTab \o \l QStyleOptionToolBox
\o \l State_Selected \o The tab is the currently selected tab.
\row \o{1,3} \l CE_HeaderSection \o{1,3} \l QStyleOptionHeader
\o \l State_Sunken \o Indicates that the section is pressed.
\row \o \l State_UpArrow \o Indicates that the sort indicator should be pointing up.
\row \o \l State_DownArrow \o Indicates that the sort indicator should be pointing down.
\endtable
\sa drawPrimitive(), drawComplexControl()
*/
/*!
\enum QStyle::SubElement
This enum represents a sub-area of a widget. Style implementations
use these areas to draw the different parts of a widget.
\value SE_PushButtonContents Area containing the label (icon
with text or pixmap).
\value SE_PushButtonFocusRect Area for the focus rect (usually
larger than the contents rect).
\value SE_PushButtonLayoutItem Area that counts for the parent layout.
\value SE_CheckBoxIndicator Area for the state indicator (e.g., check mark).
\value SE_CheckBoxContents Area for the label (text or pixmap).
\value SE_CheckBoxFocusRect Area for the focus indicator.
\value SE_CheckBoxClickRect Clickable area, defaults to SE_CheckBoxFocusRect.
\value SE_CheckBoxLayoutItem Area that counts for the parent layout.
\value SE_DateTimeEditLayoutItem Area that counts for the parent layout.
\value SE_RadioButtonIndicator Area for the state indicator.
\value SE_RadioButtonContents Area for the label.
\value SE_RadioButtonFocusRect Area for the focus indicator.
\value SE_RadioButtonClickRect Clickable area, defaults to SE_RadioButtonFocusRect.
\value SE_RadioButtonLayoutItem Area that counts for the parent layout.
\value SE_ComboBoxFocusRect Area for the focus indicator.
\value SE_SliderFocusRect Area for the focus indicator.
\value SE_SliderLayoutItem Area that counts for the parent layout.
\value SE_SpinBoxLayoutItem Area that counts for the parent layout.
\value SE_Q3DockWindowHandleRect Area for the tear-off handle.
\value SE_ProgressBarGroove Area for the groove.
\value SE_ProgressBarContents Area for the progress indicator.
\value SE_ProgressBarLabel Area for the text label.
\value SE_ProgressBarLayoutItem Area that counts for the parent layout.
\omitvalue SE_DialogButtonAccept
\omitvalue SE_DialogButtonReject
\omitvalue SE_DialogButtonApply
\omitvalue SE_DialogButtonHelp
\omitvalue SE_DialogButtonAll
\omitvalue SE_DialogButtonRetry
\omitvalue SE_DialogButtonAbort
\omitvalue SE_DialogButtonIgnore
\omitvalue SE_DialogButtonCustom
\omitvalue SE_ViewItemCheckIndicator
\value SE_FrameContents Area for a frame's contents.
\value SE_ShapedFrameContents Area for a frame's contents using the shape in QStyleOptionFrameV3; see QFrame
\value SE_FrameLayoutItem Area that counts for the parent layout.
\value SE_HeaderArrow Area for the sort indicator for a header.
\value SE_HeaderLabel Area for the label in a header.
\value SE_LabelLayoutItem Area that counts for the parent layout.
\value SE_LineEditContents Area for a line edit's contents.
\value SE_TabWidgetLeftCorner Area for the left corner widget in a tab widget.
\value SE_TabWidgetRightCorner Area for the right corner widget in a tab widget.
\value SE_TabWidgetTabBar Area for the tab bar widget in a tab widget.
\value SE_TabWidgetTabContents Area for the contents of the tab widget.
\value SE_TabWidgetTabPane Area for the pane of a tab widget.
\value SE_TabWidgetLayoutItem Area that counts for the parent layout.
\value SE_ToolBoxTabContents Area for a toolbox tab's icon and label.
\value SE_ToolButtonLayoutItem Area that counts for the parent layout.
\value SE_ItemViewItemCheckIndicator Area for a view item's check mark.
\value SE_TabBarTearIndicator Area for the tear indicator on a tab bar with scroll arrows.
\value SE_TreeViewDisclosureItem Area for the actual disclosure item in a tree branch.
\value SE_DialogButtonBoxLayoutItem Area that counts for the parent layout.
\value SE_GroupBoxLayoutItem Area that counts for the parent layout.
\value SE_CustomBase Base value for custom sub-elements.
Custom values must be greater than this value.
\value SE_DockWidgetFloatButton The float button of a dock
widget.
\value SE_DockWidgetTitleBarText The text bounds of the dock
widgets title.
\value SE_DockWidgetCloseButton The close button of a dock
widget.
\value SE_DockWidgetIcon The icon of a dock widget.
\value SE_ComboBoxLayoutItem Area that counts for the parent layout.
\value SE_ItemViewItemDecoration Area for a view item's decoration (icon).
\value SE_ItemViewItemText Area for a view item's text.
\value SE_ItemViewItemFocusRect Area for a view item's focus rect.
\value SE_TabBarTabLeftButton Area for a widget on the left side of a tab in a tab bar.
\value SE_TabBarTabRightButton Area for a widget on the right side of a tab in a tab bar.
\value SE_TabBarTabText Area for the text on a tab in a tab bar.
\value SE_ToolBarHandle Area for the handle of a tool bar.
\sa subElementRect()
*/
/*!
\fn QRect QStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
Returns the sub-area for the given \a element as described in the
provided style \a option. The returned rectangle is defined in
screen coordinates.
The \a widget argument is optional and can be used to aid
determining the area. The QStyleOption object can be cast to the
appropriate type using the qstyleoption_cast() function. See the
table below for the appropriate \a option casts:
\table
\header \o Sub Element \o QStyleOption Subclass
\row \o \l SE_PushButtonContents \o \l QStyleOptionButton
\row \o \l SE_PushButtonFocusRect \o \l QStyleOptionButton
\row \o \l SE_CheckBoxIndicator \o \l QStyleOptionButton
\row \o \l SE_CheckBoxContents \o \l QStyleOptionButton
\row \o \l SE_CheckBoxFocusRect \o \l QStyleOptionButton
\row \o \l SE_RadioButtonIndicator \o \l QStyleOptionButton
\row \o \l SE_RadioButtonContents \o \l QStyleOptionButton
\row \o \l SE_RadioButtonFocusRect \o \l QStyleOptionButton
\row \o \l SE_ComboBoxFocusRect \o \l QStyleOptionComboBox
\row \o \l SE_Q3DockWindowHandleRect \o \l QStyleOptionQ3DockWindow
\row \o \l SE_ProgressBarGroove \o \l QStyleOptionProgressBar
\row \o \l SE_ProgressBarContents \o \l QStyleOptionProgressBar
\row \o \l SE_ProgressBarLabel \o \l QStyleOptionProgressBar
\endtable
*/
/*!
\enum QStyle::ComplexControl
This enum describes the available complex controls. Complex
controls have different behavior depending upon where the user
clicks on them or which keys are pressed.
\value CC_SpinBox A spinbox, like QSpinBox.
\value CC_ComboBox A combobox, like QComboBox.
\value CC_ScrollBar A scroll bar, like QScrollBar.
\value CC_Slider A slider, like QSlider.
\value CC_ToolButton A tool button, like QToolButton.
\value CC_TitleBar A Title bar, like those used in QMdiSubWindow.
\value CC_Q3ListView Used for drawing the Q3ListView class.
\value CC_GroupBox A group box, like QGroupBox.
\value CC_Dial A dial, like QDial.
\value CC_MdiControls The minimize, close, and normal
button in the menu bar for a
maximized MDI subwindow.
\value CC_CustomBase Base value for custom complex controls. Custom
values must be greater than this value.
\sa SubControl drawComplexControl()
*/
/*!
\enum QStyle::SubControl
This enum describes the available sub controls. A subcontrol is a
control element within a complex control (ComplexControl).
\value SC_None Special value that matches no other sub control.
\value SC_ScrollBarAddLine Scroll bar add line (i.e., down/right
arrow); see also QScrollBar.
\value SC_ScrollBarSubLine Scroll bar sub line (i.e., up/left arrow).
\value SC_ScrollBarAddPage Scroll bar add page (i.e., page down).
\value SC_ScrollBarSubPage Scroll bar sub page (i.e., page up).
\value SC_ScrollBarFirst Scroll bar first line (i.e., home).
\value SC_ScrollBarLast Scroll bar last line (i.e., end).
\value SC_ScrollBarSlider Scroll bar slider handle.
\value SC_ScrollBarGroove Special sub-control which contains the
area in which the slider handle may move.
\value SC_SpinBoxUp Spin widget up/increase; see also QSpinBox.
\value SC_SpinBoxDown Spin widget down/decrease.
\value SC_SpinBoxFrame Spin widget frame.
\value SC_SpinBoxEditField Spin widget edit field.
\value SC_ComboBoxEditField Combobox edit field; see also QComboBox.
\value SC_ComboBoxArrow Combobox arrow button.
\value SC_ComboBoxFrame Combobox frame.
\value SC_ComboBoxListBoxPopup The reference rectangle for the combobox popup.
Used to calculate the position of the popup.
\value SC_SliderGroove Special sub-control which contains the area
in which the slider handle may move.
\value SC_SliderHandle Slider handle.
\value SC_SliderTickmarks Slider tickmarks.
\value SC_ToolButton Tool button (see also QToolButton).
\value SC_ToolButtonMenu Sub-control for opening a popup menu in a
tool button; see also Q3PopupMenu.
\value SC_TitleBarSysMenu System menu button (i.e., restore, close, etc.).
\value SC_TitleBarMinButton Minimize button.
\value SC_TitleBarMaxButton Maximize button.
\value SC_TitleBarCloseButton Close button.
\value SC_TitleBarLabel Window title label.
\value SC_TitleBarNormalButton Normal (restore) button.
\value SC_TitleBarShadeButton Shade button.
\value SC_TitleBarUnshadeButton Unshade button.
\value SC_TitleBarContextHelpButton Context Help button.
\value SC_Q3ListView The list view area.
\value SC_Q3ListViewExpand Expand item (i.e., show/hide child items).
\value SC_DialHandle The handle of the dial (i.e. what you use to control the dial).
\value SC_DialGroove The groove for the dial.
\value SC_DialTickmarks The tickmarks for the dial.
\value SC_GroupBoxFrame The frame of a group box.
\value SC_GroupBoxLabel The title of a group box.
\value SC_GroupBoxCheckBox The optional check box of a group box.
\value SC_GroupBoxContents The group box contents.
\value SC_MdiNormalButton The normal button for a MDI
subwindow in the menu bar.
\value SC_MdiMinButton The minimize button for a MDI
subwindow in the menu bar.
\value SC_MdiCloseButton The close button for a MDI subwindow
in the menu bar.
\value SC_All Special value that matches all sub-controls.
\omitvalue SC_Q3ListViewBranch
\omitvalue SC_CustomBase
\sa ComplexControl
*/
/*!
\fn void QStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
Draws the given \a control using the provided \a painter with the
style options specified by \a option.
The \a widget argument is optional and can be used as aid in
drawing the control.
The \a option parameter is a pointer to a QStyleOptionComplex
object that can be cast to the correct subclass using the
qstyleoption_cast() function. Note that the \c rect member of the
specified \a option must be in logical
coordinates. Reimplementations of this function should use
visualRect() to change the logical coordinates into screen
coordinates before calling the drawPrimitive() or drawControl()
function.
The table below is listing the complex control elements and their
associated style option subclass. The style options contain all
the parameters required to draw the controls, including
QStyleOption::state which holds the \l {QStyle::StateFlag}{style
flags} that are used when drawing. The table also describes which
flags that are set when casting the given \a option to the
appropriate subclass.
\table
\header \o Complex Control \o QStyleOptionComplex Subclass \o Style Flag \o Remark
\row \o{1,2} \l{CC_SpinBox} \o{1,2} \l QStyleOptionSpinBox
\o \l State_Enabled \o Set if the spin box is enabled.
\row \o \l State_HasFocus \o Set if the spin box has input focus.
\row \o{1,2} \l {CC_ComboBox} \o{1,2} \l QStyleOptionComboBox
\o \l State_Enabled \o Set if the combobox is enabled.
\row \o \l State_HasFocus \o Set if the combobox has input focus.
\row \o{1,2} \l {CC_ScrollBar} \o{1,2} \l QStyleOptionSlider
\o \l State_Enabled \o Set if the scroll bar is enabled.
\row \o \l State_HasFocus \o Set if the scroll bar has input focus.
\row \o{1,2} \l {CC_Slider} \o{1,2} \l QStyleOptionSlider
\o \l State_Enabled \o Set if the slider is enabled.
\row \o \l State_HasFocus \o Set if the slider has input focus.
\row \o{1,2} \l {CC_Dial} \o{1,2} \l QStyleOptionSlider
\o \l State_Enabled \o Set if the dial is enabled.
\row \o \l State_HasFocus \o Set if the dial has input focus.
\row \o{1,6} \l {CC_ToolButton} \o{1,6} \l QStyleOptionToolButton
\o \l State_Enabled \o Set if the tool button is enabled.
\row \o \l State_HasFocus \o Set if the tool button has input focus.
\row \o \l State_DownArrow \o Set if the tool button is down (i.e., a mouse
button or the space bar is pressed).
\row \o \l State_On \o Set if the tool button is a toggle button
and is toggled on.
\row \o \l State_AutoRaise \o Set if the tool button has auto-raise enabled.
\row \o \l State_Raised \o Set if the button is not down, not on, and doesn't
contain the mouse when auto-raise is enabled.
\row \o \l{CC_TitleBar} \o \l QStyleOptionTitleBar
\o \l State_Enabled \o Set if the title bar is enabled.
\row \o \l{CC_Q3ListView} \o \l QStyleOptionQ3ListView
\o \l State_Enabled \o Set if the list view is enabled.
\endtable
\sa drawPrimitive(), drawControl()
*/
/*!
\fn QRect QStyle::subControlRect(ComplexControl control,
const QStyleOptionComplex *option, SubControl subControl,
const QWidget *widget) const = 0
Returns the rectangle containing the specified \a subControl of
the given complex \a control (with the style specified by \a
option). The rectangle is defined in screen coordinates.
The \a option argument is a pointer to QStyleOptionComplex or
one of its subclasses, and can be cast to the appropriate type
using the qstyleoption_cast() function. See drawComplexControl()
for details. The \a widget is optional and can contain additional
information for the function.
\sa drawComplexControl()
*/
/*!
\fn QStyle::SubControl QStyle::hitTestComplexControl(ComplexControl control,
const QStyleOptionComplex *option, const QPoint &position,
const QWidget *widget) const = 0
Returns the sub control at the given \a position in the given
complex \a control (with the style options specified by \a
option).
Note that the \a position is expressed in screen coordinates.
The \a option argument is a pointer to a QStyleOptionComplex
object (or one of its subclasses). The object can be cast to the
appropriate type using the qstyleoption_cast() function. See
drawComplexControl() for details. The \a widget argument is
optional and can contain additional information for the function.
\sa drawComplexControl(), subControlRect()
*/
/*!
\enum QStyle::PixelMetric
This enum describes the various available pixel metrics. A pixel
metric is a style dependent size represented by a single pixel
value.
\value PM_ButtonMargin Amount of whitespace between push button
labels and the frame.
\value PM_DockWidgetTitleBarButtonMargin Amount of whitespace between dock widget's
title bar button labels and the frame.
\value PM_ButtonDefaultIndicator Width of the default-button indicator frame.
\value PM_MenuButtonIndicator Width of the menu button indicator
proportional to the widget height.
\value PM_ButtonShiftHorizontal Horizontal contents shift of a
button when the button is down.
\value PM_ButtonShiftVertical Vertical contents shift of a button when the
button is down.
\value PM_DefaultFrameWidth Default frame width (usually 2).
\value PM_SpinBoxFrameWidth Frame width of a spin box, defaults to PM_DefaultFrameWidth.
\value PM_ComboBoxFrameWidth Frame width of a combo box, defaults to PM_DefaultFrameWidth.
\value PM_MDIFrameWidth Obsolete. Use PM_MdiSubWindowFrameWidth instead.
\value PM_MdiSubWindowFrameWidth Frame width of an MDI window.
\value PM_MDIMinimizedWidth Obsolete. Use PM_MdiSubWindowMinimizedWidth instead.
\value PM_MdiSubWindowMinimizedWidth Width of a minimized MDI window.
\value PM_LayoutLeftMargin Default \l{QLayout::setContentsMargins()}{left margin} for a
QLayout.
\value PM_LayoutTopMargin Default \l{QLayout::setContentsMargins()}{top margin} for a QLayout.
\value PM_LayoutRightMargin Default \l{QLayout::setContentsMargins()}{right margin} for a
QLayout.
\value PM_LayoutBottomMargin Default \l{QLayout::setContentsMargins()}{bottom margin} for a
QLayout.
\value PM_LayoutHorizontalSpacing Default \l{QLayout::spacing}{horizontal spacing} for a
QLayout.
\value PM_LayoutVerticalSpacing Default \l{QLayout::spacing}{vertical spacing} for a QLayout.
\value PM_MaximumDragDistance The maximum allowed distance between
the mouse and a scrollbar when dragging. Exceeding the specified
distance will cause the slider to jump back to the original
position; a value of -1 disables this behavior.
\value PM_ScrollBarExtent Width of a vertical scroll bar and the
height of a horizontal scroll bar.
\value PM_ScrollBarSliderMin The minimum height of a vertical
scroll bar's slider and the minimum width of a horizontal
scroll bar's slider.
\value PM_SliderThickness Total slider thickness.
\value PM_SliderControlThickness Thickness of the slider handle.
\value PM_SliderLength Length of the slider.
\value PM_SliderTickmarkOffset The offset between the tickmarks
and the slider.
\value PM_SliderSpaceAvailable The available space for the slider to move.
\value PM_DockWidgetSeparatorExtent Width of a separator in a
horizontal dock window and the height of a separator in a
vertical dock window.
\value PM_DockWidgetHandleExtent Width of the handle in a
horizontal dock window and the height of the handle in a
vertical dock window.
\value PM_DockWidgetFrameWidth Frame width of a dock window.
\value PM_DockWidgetTitleMargin Margin of the dock window title.
\value PM_MenuBarPanelWidth Frame width of a menu bar, defaults to PM_DefaultFrameWidth.
\value PM_MenuBarItemSpacing Spacing between menu bar items.
\value PM_MenuBarHMargin Spacing between menu bar items and left/right of bar.
\value PM_MenuBarVMargin Spacing between menu bar items and top/bottom of bar.
\value PM_ToolBarFrameWidth Width of the frame around toolbars.
\value PM_ToolBarHandleExtent Width of a toolbar handle in a
horizontal toolbar and the height of the handle in a vertical toolbar.
\value PM_ToolBarItemMargin Spacing between the toolbar frame and the items.
\value PM_ToolBarItemSpacing Spacing between toolbar items.
\value PM_ToolBarSeparatorExtent Width of a toolbar separator in a
horizontal toolbar and the height of a separator in a vertical toolbar.
\value PM_ToolBarExtensionExtent Width of a toolbar extension
button in a horizontal toolbar and the height of the button in a
vertical toolbar.
\value PM_TabBarTabOverlap Number of pixels the tabs should overlap.
(Currently only used in styles, not inside of QTabBar)
\value PM_TabBarTabHSpace Extra space added to the tab width.
\value PM_TabBarTabVSpace Extra space added to the tab height.
\value PM_TabBarBaseHeight Height of the area between the tab bar
and the tab pages.
\value PM_TabBarBaseOverlap Number of pixels the tab bar overlaps
the tab bar base.
\value PM_TabBarScrollButtonWidth
\value PM_TabBarTabShiftHorizontal Horizontal pixel shift when a
tab is selected.
\value PM_TabBarTabShiftVertical Vertical pixel shift when a
tab is selected.
\value PM_ProgressBarChunkWidth Width of a chunk in a progress bar indicator.
\value PM_SplitterWidth Width of a splitter.
\value PM_TitleBarHeight Height of the title bar.
\value PM_IndicatorWidth Width of a check box indicator.
\value PM_IndicatorHeight Height of a checkbox indicator.
\value PM_ExclusiveIndicatorWidth Width of a radio button indicator.
\value PM_ExclusiveIndicatorHeight Height of a radio button indicator.
\value PM_MenuPanelWidth Border width (applied on all sides) for a QMenu.
\value PM_MenuHMargin Additional border (used on left and right) for a QMenu.
\value PM_MenuVMargin Additional border (used for bottom and top) for a QMenu.
\value PM_MenuScrollerHeight Height of the scroller area in a QMenu.
\value PM_MenuTearoffHeight Height of a tear off area in a QMenu.
\value PM_MenuDesktopFrameWidth The frame width for the menu on the desktop.
\value PM_CheckListButtonSize Area (width/height) of the
checkbox/radio button in a Q3CheckListItem.
\value PM_CheckListControllerSize Area (width/height) of the
controller in a Q3CheckListItem.
\omitvalue PM_DialogButtonsSeparator
\omitvalue PM_DialogButtonsButtonWidth
\omitvalue PM_DialogButtonsButtonHeight
\value PM_HeaderMarkSize The size of the sort indicator in a header.
\value PM_HeaderGripMargin The size of the resize grip in a header.
\value PM_HeaderMargin The size of the margin between the sort indicator and the text.
\value PM_SpinBoxSliderHeight The height of the optional spin box slider.
\value PM_ToolBarIconSize Default tool bar icon size
\value PM_SmallIconSize Default small icon size
\value PM_LargeIconSize Default large icon size
\value PM_FocusFrameHMargin Horizontal margin that the focus frame will outset the widget by.
\value PM_FocusFrameVMargin Vertical margin that the focus frame will outset the widget by.
\value PM_IconViewIconSize The default size for icons in an icon view.
\value PM_ListViewIconSize The default size for icons in a list view.
\value PM_ToolTipLabelFrameWidth The frame width for a tool tip label.
\value PM_CheckBoxLabelSpacing The spacing between a check box indicator and its label.
\value PM_RadioButtonLabelSpacing The spacing between a radio button indicator and its label.
\value PM_TabBarIconSize The default icon size for a tab bar.
\value PM_SizeGripSize The size of a size grip.
\value PM_MessageBoxIconSize The size of the standard icons in a message box
\value PM_ButtonIconSize The default size of button icons
\value PM_TextCursorWidth The width of the cursor in a line edit or text edit
\value PM_TabBar_ScrollButtonOverlap The distance between the left and right buttons in a tab bar.
\value PM_TabCloseIndicatorWidth The default width of a close button on a tab in a tab bar.
\value PM_TabCloseIndicatorHeight The default height of a close button on a tab in a tab bar.
\value PM_CustomBase Base value for custom pixel metrics. Custom
values must be greater than this value.
The following values are obsolete:
\value PM_DefaultTopLevelMargin Use PM_LayoutLeftMargin,
PM_LayoutTopMargin,
PM_LayoutRightMargin, and
PM_LayoutBottomMargin instead.
\value PM_DefaultChildMargin Use PM_LayoutLeftMargin,
PM_LayoutTopMargin,
PM_LayoutRightMargin, and
PM_LayoutBottomMargin instead.
\value PM_DefaultLayoutSpacing Use PM_LayoutHorizontalSpacing
and PM_LayoutVerticalSpacing
instead.
\value PM_ScrollView_ScrollBarSpacing Distance between frame and scrollbar
with SH_ScrollView_FrameOnlyAroundContents set.
\value PM_SubMenuOverlap The horizontal overlap between a submenu and its parent.
\sa pixelMetric()
*/
/*!
\fn int QStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const;
Returns the value of the given pixel \a metric.
The specified \a option and \a widget can be used for calculating
the metric. In general, the \a widget argument is not used. The \a
option can be cast to the appropriate type using the
qstyleoption_cast() function. Note that the \a option may be zero
even for PixelMetrics that can make use of it. See the table below
for the appropriate \a option casts:
\table
\header \o Pixel Metric \o QStyleOption Subclass
\row \o \l PM_SliderControlThickness \o \l QStyleOptionSlider
\row \o \l PM_SliderLength \o \l QStyleOptionSlider
\row \o \l PM_SliderTickmarkOffset \o \l QStyleOptionSlider
\row \o \l PM_SliderSpaceAvailable \o \l QStyleOptionSlider
\row \o \l PM_ScrollBarExtent \o \l QStyleOptionSlider
\row \o \l PM_TabBarTabOverlap \o \l QStyleOptionTab
\row \o \l PM_TabBarTabHSpace \o \l QStyleOptionTab
\row \o \l PM_TabBarTabVSpace \o \l QStyleOptionTab
\row \o \l PM_TabBarBaseHeight \o \l QStyleOptionTab
\row \o \l PM_TabBarBaseOverlap \o \l QStyleOptionTab
\endtable
Some pixel metrics are called from widgets and some are only called
internally by the style. If the metric is not called by a widget, it is the
discretion of the style author to make use of it. For some styles, this
may not be appropriate.
*/
/*!
\enum QStyle::ContentsType
This enum describes the available contents types. These are used to
calculate sizes for the contents of various widgets.
\value CT_CheckBox A check box, like QCheckBox.
\value CT_ComboBox A combo box, like QComboBox.
\omitvalue CT_DialogButtons
\value CT_Q3DockWindow A Q3DockWindow.
\value CT_HeaderSection A header section, like QHeader.
\value CT_LineEdit A line edit, like QLineEdit.
\value CT_Menu A menu, like QMenu.
\value CT_Q3Header A Qt 3 header section, like Q3Header.
\value CT_MenuBar A menu bar, like QMenuBar.
\value CT_MenuBarItem A menu bar item, like the buttons in a QMenuBar.
\value CT_MenuItem A menu item, like QMenuItem.
\value CT_ProgressBar A progress bar, like QProgressBar.
\value CT_PushButton A push button, like QPushButton.
\value CT_RadioButton A radio button, like QRadioButton.
\value CT_SizeGrip A size grip, like QSizeGrip.
\value CT_Slider A slider, like QSlider.
\value CT_ScrollBar A scroll bar, like QScrollBar.
\value CT_SpinBox A spin box, like QSpinBox.
\value CT_Splitter A splitter, like QSplitter.
\value CT_TabBarTab A tab on a tab bar, like QTabBar.
\value CT_TabWidget A tab widget, like QTabWidget.
\value CT_ToolButton A tool button, like QToolButton.
\value CT_GroupBox A group box, like QGroupBox.
\value CT_ItemViewItem An item inside an item view.
\value CT_CustomBase Base value for custom contents types.
Custom values must be greater than this value.
\value CT_MdiControls The minimize, normal, and close button
in the menu bar for a maximized MDI
subwindow.
\sa sizeFromContents()
*/
/*!
\fn QSize QStyle::sizeFromContents(ContentsType type, const QStyleOption *option, \
const QSize &contentsSize, const QWidget *widget) const
Returns the size of the element described by the specified
\a option and \a type, based on the provided \a contentsSize.
The \a option argument is a pointer to a QStyleOption or one of
its subclasses. The \a option can be cast to the appropriate type
using the qstyleoption_cast() function. The \a widget is an
optional argument and can contain extra information used for
calculating the size.
See the table below for the appropriate \a option casts:
\table
\header \o Contents Type \o QStyleOption Subclass
\row \o \l CT_PushButton \o \l QStyleOptionButton
\row \o \l CT_CheckBox \o \l QStyleOptionButton
\row \o \l CT_RadioButton \o \l QStyleOptionButton
\row \o \l CT_ToolButton \o \l QStyleOptionToolButton
\row \o \l CT_ComboBox \o \l QStyleOptionComboBox
\row \o \l CT_Splitter \o \l QStyleOption
\row \o \l CT_Q3DockWindow \o \l QStyleOptionQ3DockWindow
\row \o \l CT_ProgressBar \o \l QStyleOptionProgressBar
\row \o \l CT_MenuItem \o \l QStyleOptionMenuItem
\endtable
\sa ContentsType QStyleOption
*/
/*!
\enum QStyle::RequestSoftwareInputPanel
This enum describes under what circumstances a software input panel will be
requested by input capable widgets.
\value RSIP_OnMouseClickAndAlreadyFocused Requests an input panel if the user
clicks on the widget, but only if it is already focused.
\value RSIP_OnMouseClick Requests an input panel if the user clicks on the
widget.
\sa QEvent::RequestSoftwareInputPanel, QInputContext
*/
/*!
\enum QStyle::StyleHint
This enum describes the available style hints. A style hint is a general look
and/or feel hint.
\value SH_EtchDisabledText Disabled text is "etched" as it is on Windows.
\value SH_DitherDisabledText Disabled text is dithered as it is on Motif.
\value SH_GUIStyle The GUI style to use.
\value SH_ScrollBar_ContextMenu Whether or not a scroll bar has a context menu.
\value SH_ScrollBar_MiddleClickAbsolutePosition A boolean value.
If true, middle clicking on a scroll bar causes the slider to
jump to that position. If false, middle clicking is
ignored.
\value SH_ScrollBar_LeftClickAbsolutePosition A boolean value.
If true, left clicking on a scroll bar causes the slider to
jump to that position. If false, left clicking will
behave as appropriate for each control.
\value SH_ScrollBar_ScrollWhenPointerLeavesControl A boolean
value. If true, when clicking a scroll bar SubControl, holding
the mouse button down and moving the pointer outside the
SubControl, the scroll bar continues to scroll. If false, the
scollbar stops scrolling when the pointer leaves the
SubControl.
\value SH_ScrollBar_RollBetweenButtons A boolean value.
If true, when clicking a scroll bar button (SC_ScrollBarAddLine or
SC_ScrollBarSubLine) and dragging over to the opposite button (rolling)
will press the new button and release the old one. When it is false, the
original button is released and nothing happens (like a push button).
\value SH_TabBar_Alignment The alignment for tabs in a
QTabWidget. Possible values are Qt::AlignLeft,
Qt::AlignCenter and Qt::AlignRight.
\value SH_Header_ArrowAlignment The placement of the sorting
indicator may appear in list or table headers. Possible values
are Qt::Left or Qt::Right.
\value SH_Slider_SnapToValue Sliders snap to values while moving,
as they do on Windows.
\value SH_Slider_SloppyKeyEvents Key presses handled in a sloppy
manner, i.e., left on a vertical slider subtracts a line.
\value SH_ProgressDialog_CenterCancelButton Center button on
progress dialogs, like Motif, otherwise right aligned.
\value SH_ProgressDialog_TextLabelAlignment The alignment for text
labels in progress dialogs; Qt::AlignCenter on Windows,
Qt::AlignVCenter otherwise.
\value SH_PrintDialog_RightAlignButtons Right align buttons in
the print dialog, as done on Windows.
\value SH_MainWindow_SpaceBelowMenuBar One or two pixel space between
the menu bar and the dockarea, as done on Windows.
\value SH_FontDialog_SelectAssociatedText Select the text in the
line edit, or when selecting an item from the listbox, or when
the line edit receives focus, as done on Windows.
\value SH_Menu_KeyboardSearch Typing causes a menu to be search
for relevant items, otherwise only mnemnonic is considered.
\value SH_Menu_AllowActiveAndDisabled Allows disabled menu
items to be active.
\value SH_Menu_SpaceActivatesItem Pressing the space bar activates
the item, as done on Motif.
\value SH_Menu_SubMenuPopupDelay The number of milliseconds
to wait before opening a submenu (256 on Windows, 96 on Motif).
\value SH_Menu_Scrollable Whether popup menus must support scrolling.
\value SH_Menu_SloppySubMenus Whether popupmenu's must support
sloppy submenu; as implemented on Mac OS.
\value SH_ScrollView_FrameOnlyAroundContents Whether scrollviews
draw their frame only around contents (like Motif), or around
contents, scroll bars and corner widgets (like Windows).
\value SH_MenuBar_AltKeyNavigation Menu bars items are navigable
by pressing Alt, followed by using the arrow keys to select
the desired item.
\value SH_ComboBox_ListMouseTracking Mouse tracking in combobox
drop-down lists.
\value SH_Menu_MouseTracking Mouse tracking in popup menus.
\value SH_MenuBar_MouseTracking Mouse tracking in menu bars.
\value SH_Menu_FillScreenWithScroll Whether scrolling popups
should fill the screen as they are scrolled.
\value SH_Menu_SelectionWrap Whether popups should allow the selections
to wrap, that is when selection should the next item be the first item.
\value SH_ItemView_ChangeHighlightOnFocus Gray out selected items
when losing focus.
\value SH_Widget_ShareActivation Turn on sharing activation with
floating modeless dialogs.
\value SH_TabBar_SelectMouseType Which type of mouse event should
cause a tab to be selected.
\value SH_Q3ListViewExpand_SelectMouseType Which type of mouse event should
cause a list view expansion to be selected.
\value SH_TabBar_PreferNoArrows Whether a tab bar should suggest a size
to prevent scoll arrows.
\value SH_ComboBox_Popup Allows popups as a combobox drop-down
menu.
\value SH_Workspace_FillSpaceOnMaximize The workspace should
maximize the client area.
\value SH_TitleBar_NoBorder The title bar has no border.
\value SH_ScrollBar_StopMouseOverSlider Obsolete. Use
SH_Slider_StopMouseOverSlider instead.
\value SH_Slider_StopMouseOverSlider Stops auto-repeat when
the slider reaches the mouse position.
\value SH_BlinkCursorWhenTextSelected Whether cursor should blink
when text is selected.
\value SH_RichText_FullWidthSelection Whether richtext selections
should extend to the full width of the document.
\value SH_GroupBox_TextLabelVerticalAlignment How to vertically align a
group box's text label.
\value SH_GroupBox_TextLabelColor How to paint a group box's text label.
\value SH_DialogButtons_DefaultButton Which button gets the
default status in a dialog's button widget.
\value SH_ToolBox_SelectedPageTitleBold Boldness of the selected
page title in a QToolBox.
\value SH_LineEdit_PasswordCharacter The Unicode character to be
used for passwords.
\value SH_Table_GridLineColor The RGB value of the grid for a table.
\value SH_UnderlineShortcut Whether shortcuts are underlined.
\value SH_SpellCheckUnderlineStyle A
QTextCharFormat::UnderlineStyle value that specifies the way
misspelled words should be underlined.
\value SH_SpinBox_AnimateButton Animate a click when up or down is
pressed in a spin box.
\value SH_SpinBox_KeyPressAutoRepeatRate Auto-repeat interval for
spinbox key presses.
\value SH_SpinBox_ClickAutoRepeatRate Auto-repeat interval for
spinbox mouse clicks.
\value SH_SpinBox_ClickAutoRepeatThreshold Auto-repeat threshold for
spinbox mouse clicks.
\value SH_ToolTipLabel_Opacity An integer indicating the opacity for
the tip label, 0 is completely transparent, 255 is completely
opaque.
\value SH_DrawMenuBarSeparator Indicates whether or not the menu bar draws separators.
\value SH_TitleBar_ModifyNotification Indicates if the title bar should show
a '*' for windows that are modified.
\value SH_Button_FocusPolicy The default focus policy for buttons.
\value SH_CustomBase Base value for custom style hints.
Custom values must be greater than this value.
\value SH_MenuBar_DismissOnSecondClick A boolean indicating if a menu in
the menu bar should be dismissed when it is clicked on a second time. (Example:
Clicking and releasing on the File Menu in a menu bar and then
immediately clicking on the File Menu again.)
\value SH_MessageBox_UseBorderForButtonSpacing A boolean indicating what the to
use the border of the buttons (computed as half the button height) for the spacing
of the button in a message box.
\value SH_MessageBox_CenterButtons A boolean indicating whether the buttons in the
message box should be centered or not (see QDialogButtonBox::setCentered()).
\value SH_MessageBox_TextInteractionFlags A boolean indicating if
the text in a message box should allow user interfactions (e.g.
selection) or not.
\value SH_TitleBar_AutoRaise A boolean indicating whether
controls on a title bar ought to update when the mouse is over them.
\value SH_ToolButton_PopupDelay An int indicating the popup delay in milliseconds
for menus attached to tool buttons.
\value SH_FocusFrame_Mask The mask of the focus frame.
\value SH_RubberBand_Mask The mask of the rubber band.
\value SH_WindowFrame_Mask The mask of the window frame.
\value SH_SpinControls_DisableOnBounds Determines if the spin controls will shown
as disabled when reaching the spin range boundary.
\value SH_Dial_BackgroundRole Defines the style's preferred
background role (as QPalette::ColorRole) for a dial widget.
\value SH_ScrollBar_BackgroundMode The background mode for a scroll bar.
\value SH_ComboBox_LayoutDirection The layout direction for the
combo box. By default it should be the same as indicated by the
QStyleOption::direction variable.
\value SH_ItemView_EllipsisLocation The location where ellipses should be
added for item text that is too long to fit in an view item.
\value SH_ItemView_ShowDecorationSelected When an item in an item
view is selected, also highlight the branch or other decoration.
\value SH_ItemView_ActivateItemOnSingleClick Emit the activated signal
when the user single clicks on an item in an item in an item view.
Otherwise the signal is emitted when the user double clicks on an item.
\value SH_Slider_AbsoluteSetButtons Which mouse buttons cause a slider
to set the value to the position clicked on.
\value SH_Slider_PageSetButtons Which mouse buttons cause a slider
to page step the value.
\value SH_TabBar_ElideMode The default eliding style for a tab bar.
\value SH_DialogButtonLayout Controls how buttons are laid out in a QDialogButtonBox, returns a QDialogButtonBox::ButtonLayout enum.
\value SH_WizardStyle Controls the look and feel of a QWizard. Returns a QWizard::WizardStyle enum.
\value SH_FormLayoutWrapPolicy Provides a default for how rows are wrapped in a QFormLayout. Returns a QFormLayout::RowWrapPolicy enum.
\value SH_FormLayoutFieldGrowthPolicy Provides a default for how fields can grow in a QFormLayout. Returns a QFormLayout::FieldGrowthPolicy enum.
\value SH_FormLayoutFormAlignment Provides a default for how a QFormLayout aligns its contents within the available space. Returns a Qt::Alignment enum.
\value SH_FormLayoutLabelAlignment Provides a default for how a QFormLayout aligns labels within the available space. Returns a Qt::Alignment enum.
\value SH_ItemView_ArrowKeysNavigateIntoChildren Controls whether the tree view will select the first child when it is exapanded and the right arrow key is pressed.
\value SH_ComboBox_PopupFrameStyle The frame style used when drawing a combobox popup menu.
\value SH_DialogButtonBox_ButtonsHaveIcons Indicates whether or not StandardButtons in QDialogButtonBox should have icons or not.
\value SH_ItemView_MovementWithoutUpdatingSelection The item view is able to indicate a current item without changing the selection.
\value SH_ToolTip_Mask The mask of a tool tip.
\value SH_FocusFrame_AboveWidget The FocusFrame is stacked above the widget that it is "focusing on".
\value SH_TextControl_FocusIndicatorTextCharFormat Specifies the text format used to highlight focused anchors in rich text
documents displayed for example in QTextBrowser. The format has to be a QTextCharFormat returned in the variant of the
QStyleHintReturnVariant return value. The QTextFormat::OutlinePen property is used for the outline and QTextFormat::BackgroundBrush
for the background of the highlighted area.
\value SH_Menu_FlashTriggeredItem Flash triggered item.
\value SH_Menu_FadeOutOnHide Fade out the menu instead of hiding it immediately.
\value SH_TabWidget_DefaultTabPosition Default position of the tab bar in a tab widget.
\value SH_ToolBar_Movable Determines if the tool bar is movable by default.
\value SH_ItemView_PaintAlternatingRowColorsForEmptyArea Whether QTreeView paints alternating row colors for the area that does not have any items.
\value SH_Menu_Mask The mask for a popup menu.
\value SH_ItemView_DrawDelegateFrame Determines if there should be a frame for a delegate widget.
\value SH_TabBar_CloseButtonPosition Determines the position of the close button on a tab in a tab bar.
\value SH_DockWidget_ButtonsHaveFrame Determines if dockwidget buttons should have frames. Default is true.
\value SH_ToolButtonStyle Determines the default system style for tool buttons that uses Qt::ToolButtonFollowStyle.
\value SH_RequestSoftwareInputPanel Determines when a software input panel should
be requested by input widgets. Returns an enum of type QStyle::RequestSoftwareInputPanel.
\omitvalue SH_UnderlineAccelerator
\sa styleHint()
*/
/*!
\fn int QStyle::styleHint(StyleHint hint, const QStyleOption *option, \
const QWidget *widget, QStyleHintReturn *returnData) const
Returns an integer representing the specified style \a hint for
the given \a widget described by the provided style \a option.
\a returnData is used when the querying widget needs more detailed data than
the integer that styleHint() returns. See the QStyleHintReturn class
description for details.
*/
/*!
\enum QStyle::StandardPixmap
This enum describes the available standard pixmaps. A standard pixmap is a pixmap that
can follow some existing GUI style or guideline.
\value SP_TitleBarMinButton Minimize button on title bars (e.g.,
in QMdiSubWindow).
\value SP_TitleBarMenuButton Menu button on a title bar.
\value SP_TitleBarMaxButton Maximize button on title bars.
\value SP_TitleBarCloseButton Close button on title bars.
\value SP_TitleBarNormalButton Normal (restore) button on title bars.
\value SP_TitleBarShadeButton Shade button on title bars.
\value SP_TitleBarUnshadeButton Unshade button on title bars.
\value SP_TitleBarContextHelpButton The Context help button on title bars.
\value SP_MessageBoxInformation The "information" icon.
\value SP_MessageBoxWarning The "warning" icon.
\value SP_MessageBoxCritical The "critical" icon.
\value SP_MessageBoxQuestion The "question" icon.
\value SP_DesktopIcon The "desktop" icon.
\value SP_TrashIcon The "trash" icon.
\value SP_ComputerIcon The "My computer" icon.
\value SP_DriveFDIcon The floppy icon.
\value SP_DriveHDIcon The harddrive icon.
\value SP_DriveCDIcon The CD icon.
\value SP_DriveDVDIcon The DVD icon.
\value SP_DriveNetIcon The network icon.
\value SP_DirHomeIcon The home directory icon.
\value SP_DirOpenIcon The open directory icon.
\value SP_DirClosedIcon The closed directory icon.
\value SP_DirIcon The directory icon.
\value SP_DirLinkIcon The link to directory icon.
\value SP_FileIcon The file icon.
\value SP_FileLinkIcon The link to file icon.
\value SP_FileDialogStart The "start" icon in a file dialog.
\value SP_FileDialogEnd The "end" icon in a file dialog.
\value SP_FileDialogToParent The "parent directory" icon in a file dialog.
\value SP_FileDialogNewFolder The "create new folder" icon in a file dialog.
\value SP_FileDialogDetailedView The detailed view icon in a file dialog.
\value SP_FileDialogInfoView The file info icon in a file dialog.
\value SP_FileDialogContentsView The contents view icon in a file dialog.
\value SP_FileDialogListView The list view icon in a file dialog.
\value SP_FileDialogBack The back arrow in a file dialog.
\value SP_DockWidgetCloseButton Close button on dock windows (see also QDockWidget).
\value SP_ToolBarHorizontalExtensionButton Extension button for horizontal toolbars.
\value SP_ToolBarVerticalExtensionButton Extension button for vertical toolbars.
\value SP_DialogOkButton Icon for a standard OK button in a QDialogButtonBox.
\value SP_DialogCancelButton Icon for a standard Cancel button in a QDialogButtonBox.
\value SP_DialogHelpButton Icon for a standard Help button in a QDialogButtonBox.
\value SP_DialogOpenButton Icon for a standard Open button in a QDialogButtonBox.
\value SP_DialogSaveButton Icon for a standard Save button in a QDialogButtonBox.
\value SP_DialogCloseButton Icon for a standard Close button in a QDialogButtonBox.
\value SP_DialogApplyButton Icon for a standard Apply button in a QDialogButtonBox.
\value SP_DialogResetButton Icon for a standard Reset button in a QDialogButtonBox.
\value SP_DialogDiscardButton Icon for a standard Discard button in a QDialogButtonBox.
\value SP_DialogYesButton Icon for a standard Yes button in a QDialogButtonBox.
\value SP_DialogNoButton Icon for a standard No button in a QDialogButtonBox.
\value SP_ArrowUp Icon arrow pointing up.
\value SP_ArrowDown Icon arrow pointing down.
\value SP_ArrowLeft Icon arrow pointing left.
\value SP_ArrowRight Icon arrow pointing right.
\value SP_ArrowBack Equivalent to SP_ArrowLeft when the current layout direction is Qt::LeftToRight, otherwise SP_ArrowRight.
\value SP_ArrowForward Equivalent to SP_ArrowRight when the current layout direction is Qt::LeftToRight, otherwise SP_ArrowLeft.
\value SP_CommandLink Icon used to indicate a Vista style command link glyph.
\value SP_VistaShield Icon used to indicate UAC prompts on Windows Vista. This will return a null pixmap or icon on all other platforms.
\value SP_BrowserReload Icon indicating that the current page should be reloaded.
\value SP_BrowserStop Icon indicating that the page loading should stop.
\value SP_MediaPlay Icon indicating that media should begin playback.
\value SP_MediaStop Icon indicating that media should stop playback.
\value SP_MediaPause Icon indicating that media should pause playback.
\value SP_MediaSkipForward Icon indicating that media should skip forward.
\value SP_MediaSkipBackward Icon indicating that media should skip backward.
\value SP_MediaSeekForward Icon indicating that media should seek forward.
\value SP_MediaSeekBackward Icon indicating that media should seek backward.
\value SP_MediaVolume Icon indicating a volume control.
\value SP_MediaVolumeMuted Icon indicating a muted volume control.
\value SP_CustomBase Base value for custom standard pixmaps;
custom values must be greater than this value.
\sa standardIcon()
*/
/*!
\fn QPixmap QStyle::generatedIconPixmap(QIcon::Mode iconMode,
const QPixmap &pixmap, const QStyleOption *option) const
Returns a copy of the given \a pixmap, styled to conform to the
specified \a iconMode and taking into account the palette
specified by \a option.
The \a option parameter can pass extra information, but
it must contain a palette.
Note that not all pixmaps will conform, in which case the returned
pixmap is a plain copy.
\sa QIcon
*/
/*!
\fn QPixmap QStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option, \
const QWidget *widget) const
\obsolete
Returns a pixmap for the given \a standardPixmap.
A standard pixmap is a pixmap that can follow some existing GUI
style or guideline. The \a option argument can be used to pass
extra information required when defining the appropriate
pixmap. The \a widget argument is optional and can also be used to
aid the determination of the pixmap.
Developers calling standardPixmap() should instead call standardIcon()
Developers who re-implemented standardPixmap() should instead re-implement
the slot standardIconImplementation().
\sa standardIcon()
*/
/*!
\fn QRect QStyle::visualRect(Qt::LayoutDirection direction, const QRect &boundingRectangle, const QRect &logicalRectangle)
Returns the given \a logicalRectangle converted to screen
coordinates based on the specified \a direction. The \a
boundingRectangle is used when performing the translation.
This function is provided to support right-to-left desktops, and
is typically used in implementations of the subControlRect()
function.
\sa QWidget::layoutDirection
*/
QRect QStyle::visualRect(Qt::LayoutDirection direction, const QRect &boundingRect, const QRect &logicalRect)
{
if (direction == Qt::LeftToRight)
return logicalRect;
QRect rect = logicalRect;
rect.translate(2 * (boundingRect.right() - logicalRect.right()) +
logicalRect.width() - boundingRect.width(), 0);
return rect;
}
/*!
\fn QPoint QStyle::visualPos(Qt::LayoutDirection direction, const QRect &boundingRectangle, const QPoint &logicalPosition)
Returns the given \a logicalPosition converted to screen
coordinates based on the specified \a direction. The \a
boundingRectangle is used when performing the translation.
\sa QWidget::layoutDirection
*/
QPoint QStyle::visualPos(Qt::LayoutDirection direction, const QRect &boundingRect, const QPoint &logicalPos)
{
if (direction == Qt::LeftToRight)
return logicalPos;
return QPoint(boundingRect.right() - logicalPos.x(), logicalPos.y());
}
/*!
Returns a new rectangle of the specified \a size that is aligned to the given \a
rectangle according to the specified \a alignment and \a direction.
*/
QRect QStyle::alignedRect(Qt::LayoutDirection direction, Qt::Alignment alignment, const QSize &size, const QRect &rectangle)
{
alignment = visualAlignment(direction, alignment);
int x = rectangle.x();
int y = rectangle.y();
int w = size.width();
int h = size.height();
if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
y += rectangle.size().height()/2 - h/2;
else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
y += rectangle.size().height() - h;
if ((alignment & Qt::AlignRight) == Qt::AlignRight)
x += rectangle.size().width() - w;
else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
x += rectangle.size().width()/2 - w/2;
return QRect(x, y, w, h);
}
/*!
Transforms an \a alignment of Qt::AlignLeft or Qt::AlignRight
without Qt::AlignAbsolute into Qt::AlignLeft or Qt::AlignRight with
Qt::AlignAbsolute according to the layout \a direction. The other
alignment flags are left untouched.
If no horizontal alignment was specified, the function returns the
default alignment for the given layout \a direction.
QWidget::layoutDirection
*/
Qt::Alignment QStyle::visualAlignment(Qt::LayoutDirection direction, Qt::Alignment alignment)
{
if (!(alignment & Qt::AlignHorizontal_Mask))
alignment |= Qt::AlignLeft;
if ((alignment & Qt::AlignAbsolute) == 0 && (alignment & (Qt::AlignLeft | Qt::AlignRight))) {
if (direction == Qt::RightToLeft)
alignment ^= (Qt::AlignLeft | Qt::AlignRight);
alignment |= Qt::AlignAbsolute;
}
return alignment;
}
/*!
Converts the given \a logicalValue to a pixel position. The \a min
parameter maps to 0, \a max maps to \a span and other values are
distributed evenly in-between.
This function can handle the entire integer range without
overflow, providing that \a span is less than 4096.
By default, this function assumes that the maximum value is on the
right for horizontal items and on the bottom for vertical items.
Set the \a upsideDown parameter to true to reverse this behavior.
\sa sliderValueFromPosition()
*/
int QStyle::sliderPositionFromValue(int min, int max, int logicalValue, int span, bool upsideDown)
{
if (span <= 0 || logicalValue < min || max <= min)
return 0;
if (logicalValue > max)
return upsideDown ? span : min;
uint range = max - min;
uint p = upsideDown ? max - logicalValue : logicalValue - min;
if (range > (uint)INT_MAX/4096) {
double dpos = (double(p))/(double(range)/span);
return int(dpos);
} else if (range > (uint)span) {
return (2 * p * span + range) / (2*range);
} else {
uint div = span / range;
uint mod = span % range;
return p * div + (2 * p * mod + range) / (2 * range);
}
// equiv. to (p * span) / range + 0.5
// no overflow because of this implicit assumption:
// span <= 4096
}
/*!
\fn int QStyle::sliderValueFromPosition(int min, int max, int position, int span, bool upsideDown)
Converts the given pixel \a position to a logical value. 0 maps to
the \a min parameter, \a span maps to \a max and other values are
distributed evenly in-between.
This function can handle the entire integer range without
overflow.
By default, this function assumes that the maximum value is on the
right for horizontal items and on the bottom for vertical
items. Set the \a upsideDown parameter to true to reverse this
behavior.
\sa sliderPositionFromValue()
*/
int QStyle::sliderValueFromPosition(int min, int max, int pos, int span, bool upsideDown)
{
if (span <= 0 || pos <= 0)
return upsideDown ? max : min;
if (pos >= span)
return upsideDown ? min : max;
uint range = max - min;
if ((uint)span > range) {
int tmp = (2 * pos * range + span) / (2 * span);
return upsideDown ? max - tmp : tmp + min;
} else {
uint div = range / span;
uint mod = range % span;
int tmp = pos * div + (2 * pos * mod + span) / (2 * span);
return upsideDown ? max - tmp : tmp + min;
}
// equiv. to min + (pos*range)/span + 0.5
// no overflow because of this implicit assumption:
// pos <= span < sqrt(INT_MAX+0.0625)+0.25 ~ sqrt(INT_MAX)
}
/*### \fn void QStyle::drawItem(QPainter *p, const QRect &r,
int flags, const QColorGroup &colorgroup, bool enabled,
const QString &text, int len = -1,
const QColor *penColor = 0) const
Use one of the drawItem() overloads that takes a QPalette instead
of a QColorGroup.
*/
/*### \fn void QStyle::drawItem(QPainter *p, const QRect &r,
int flags, const QColorGroup colorgroup, bool enabled,
const QPixmap &pixmap,
const QColor *penColor = 0) const
Use one of the drawItem() overloads that takes a QPalette instead
of a QColorGroup.
*/
/*### \fn void QStyle::drawItem(QPainter *p, const QRect &r,
int flags, const QColorGroup colorgroup, bool enabled,
const QPixmap *pixmap,
const QString &text, int len = -1,
const QColor *penColor = 0) const
Use one of the drawItem() overloads that takes a QPalette instead
of a QColorGroup.
*/
/*!
Returns the style's standard palette.
Note that on systems that support system colors, the style's
standard palette is not used. In particular, the Windows XP,
Vista, and Mac styles do not use the standard palette, but make
use of native theme engines. With these styles, you should not set
the palette with QApplication::setStandardPalette().
*/
QPalette QStyle::standardPalette() const
{
#ifdef Q_WS_X11
QColor background;
if (!qt_is_gui_used || QX11Info::appDepth() > 8)
background = QColor(0xd4, 0xd0, 0xc8); // win 2000 grey
else
background = QColor(192, 192, 192);
#else
QColor background(0xd4, 0xd0, 0xc8); // win 2000 grey
#endif
QColor light(background.lighter());
QColor dark(background.darker());
QColor mid(Qt::gray);
QPalette palette(Qt::black, background, light, dark, mid, Qt::black, Qt::white);
palette.setBrush(QPalette::Disabled, QPalette::WindowText, dark);
palette.setBrush(QPalette::Disabled, QPalette::Text, dark);
palette.setBrush(QPalette::Disabled, QPalette::ButtonText, dark);
palette.setBrush(QPalette::Disabled, QPalette::Base, background);
return palette;
}
/*!
\since 4.1
Returns an icon for the given \a standardIcon.
The \a standardIcon is a standard pixmap which can follow some
existing GUI style or guideline. The \a option argument can be
used to pass extra information required when defining the
appropriate icon. The \a widget argument is optional and can also
be used to aid the determination of the icon.
\warning Because of binary compatibility constraints, this
function is not virtual. If you want to provide your own icons in
a QStyle subclass, reimplement the standardIconImplementation()
slot in your subclass instead. The standardIcon() function will
dynamically detect the slot and call it.
\sa standardIconImplementation()
*/
QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
const QWidget *widget) const
{
QIcon result;
// ### Qt 4.1: invokeMethod should accept const functions, to avoid this dirty cast
QMetaObject::invokeMethod(const_cast<QStyle*>(this),
"standardIconImplementation", Qt::DirectConnection,
Q_RETURN_ARG(QIcon, result),
Q_ARG(StandardPixmap, standardIcon),
Q_ARG(const QStyleOption*, option),
Q_ARG(const QWidget*, widget));
return result;
}
/*!
\since 4.1
Returns an icon for the given \a standardIcon.
Reimplement this slot to provide your own icons in a QStyle
subclass; because of binary compatibility constraints, the
standardIcon() function (introduced in Qt 4.1) is not
virtual. Instead, standardIcon() will dynamically detect and call
\e this slot.
The \a standardIcon is a standard pixmap which can follow some
existing GUI style or guideline. The \a option argument can be
used to pass extra information required when defining the
appropriate icon. The \a widget argument is optional and can also
be used to aid the determination of the icon.
\sa standardIcon()
*/
QIcon QStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
const QWidget *widget) const
{
return QIcon(standardPixmap(standardIcon, option, widget));
}
/*!
\since 4.3
Returns the spacing that should be used between \a control1 and
\a control2 in a layout. \a orientation specifies whether the
controls are laid out side by side or stacked vertically. The \a
option parameter can be used to pass extra information about the
parent widget. The \a widget parameter is optional and can also
be used if \a option is 0.
This function is called by the layout system. It is used only if
PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
negative value.
For binary compatibility reasons, this function is not virtual.
If you want to specify custom layout spacings in a QStyle
subclass, implement a slot called layoutSpacingImplementation().
QStyle will discover the slot at run-time (using Qt's
\l{meta-object system}) and direct all calls to layoutSpacing()
to layoutSpacingImplementation().
\sa combinedLayoutSpacing(), layoutSpacingImplementation()
*/
int QStyle::layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
Qt::Orientation orientation, const QStyleOption *option,
const QWidget *widget) const
{
Q_D(const QStyle);
if (d->layoutSpacingIndex == -1) {
d->layoutSpacingIndex = metaObject()->indexOfMethod(
"layoutSpacingImplementation(QSizePolicy::ControlType,QSizePolicy::ControlType,"
"Qt::Orientation,const QStyleOption*,const QWidget*)"
);
}
if (d->layoutSpacingIndex < 0)
return -1;
int result = -1;
void *param[] = {&result, &control1, &control2, &orientation, &option, &widget};
const_cast<QStyle *>(this)->qt_metacall(QMetaObject::InvokeMetaMethod,
d->layoutSpacingIndex, param);
return result;
}
/*!
\since 4.3
Returns the spacing that should be used between \a controls1 and
\a controls2 in a layout. \a orientation specifies whether the
controls are laid out side by side or stacked vertically. The \a
option parameter can be used to pass extra information about the
parent widget. The \a widget parameter is optional and can also
be used if \a option is 0.
\a controls1 and \a controls2 are OR-combination of zero or more
\l{QSizePolicy::ControlTypes}{control types}.
This function is called by the layout system. It is used only if
PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
negative value.
\sa layoutSpacing(), layoutSpacingImplementation()
*/
int QStyle::combinedLayoutSpacing(QSizePolicy::ControlTypes controls1,
QSizePolicy::ControlTypes controls2, Qt::Orientation orientation,
QStyleOption *option, QWidget *widget) const
{
QSizePolicy::ControlType array1[MaxBits];
QSizePolicy::ControlType array2[MaxBits];
int count1 = unpackControlTypes(controls1, array1);
int count2 = unpackControlTypes(controls2, array2);
int result = -1;
for (int i = 0; i < count1; ++i) {
for (int j = 0; j < count2; ++j) {
int spacing = layoutSpacing(array1[i], array2[j], orientation, option, widget);
result = qMax(spacing, result);
}
}
return result;
}
/*!
\since 4.3
This slot is called by layoutSpacing() to determine the spacing
that should be used between \a control1 and \a control2 in a
layout. \a orientation specifies whether the controls are laid
out side by side or stacked vertically. The \a option parameter
can be used to pass extra information about the parent widget.
The \a widget parameter is optional and can also be used if \a
option is 0.
If you want to provide custom layout spacings in a QStyle
subclass, implement a slot called layoutSpacingImplementation()
in your subclass. Be aware that this slot will only be called if
PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
negative value.
The default implementation returns -1.
\sa layoutSpacing(), combinedLayoutSpacing()
*/
int QStyle::layoutSpacingImplementation(QSizePolicy::ControlType /* control1 */,
QSizePolicy::ControlType /* control2 */,
Qt::Orientation /*orientation*/,
const QStyleOption * /* option */,
const QWidget * /* widget */) const
{
return -1;
}
QT_BEGIN_INCLUDE_NAMESPACE
#include <QDebug>
QT_END_INCLUDE_NAMESPACE
#if !defined(QT_NO_DEBUG_STREAM)
QDebug operator<<(QDebug debug, QStyle::State state)
{
#if !defined(QT_NO_DEBUG)
debug << "QStyle::State(";
QStringList states;
if (state & QStyle::State_Active) states << QLatin1String("Active");
if (state & QStyle::State_AutoRaise) states << QLatin1String("AutoRaise");
if (state & QStyle::State_Bottom) states << QLatin1String("Bottom");
if (state & QStyle::State_Children) states << QLatin1String("Children");
if (state & QStyle::State_DownArrow) states << QLatin1String("DownArrow");
if (state & QStyle::State_Editing) states << QLatin1String("Editing");
if (state & QStyle::State_Enabled) states << QLatin1String("Enabled");
if (state & QStyle::State_FocusAtBorder) states << QLatin1String("FocusAtBorder");
if (state & QStyle::State_HasFocus) states << QLatin1String("HasFocus");
if (state & QStyle::State_Horizontal) states << QLatin1String("Horizontal");
if (state & QStyle::State_Item) states << QLatin1String("Item");
if (state & QStyle::State_KeyboardFocusChange) states << QLatin1String("KeyboardFocusChange");
if (state & QStyle::State_MouseOver) states << QLatin1String("MouseOver");
if (state & QStyle::State_NoChange) states << QLatin1String("NoChange");
if (state & QStyle::State_Off) states << QLatin1String("Off");
if (state & QStyle::State_On) states << QLatin1String("On");
if (state & QStyle::State_Open) states << QLatin1String("Open");
if (state & QStyle::State_Raised) states << QLatin1String("Raised");
if (state & QStyle::State_ReadOnly) states << QLatin1String("ReadOnly");
if (state & QStyle::State_Selected) states << QLatin1String("Selected");
if (state & QStyle::State_Sibling) states << QLatin1String("Sibling");
if (state & QStyle::State_Sunken) states << QLatin1String("Sunken");
if (state & QStyle::State_Top) states << QLatin1String("Top");
if (state & QStyle::State_UpArrow) states << QLatin1String("UpArrow");
qSort(states);
debug << states.join(QLatin1String(" | "));
debug << ')';
#else
Q_UNUSED(state);
#endif
return debug;
}
#endif
/*!
\since 4.6
\fn const QStyle *QStyle::proxy() const
This function returns the current proxy for this style.
By default most styles will return themselves. However
when a proxy style is in use, it will allow the style to
call back into its proxy.
*/
const QStyle * QStyle::proxy() const
{
Q_D(const QStyle);
return d->proxyStyle;
}
/* \internal
This function sets the base style that style calls will be
redirected to. Note that ownership is not transferred.
*/
void QStyle::setProxy(QStyle *style)
{
Q_D(QStyle);
d->proxyStyle = style;
}
QT_END_NAMESPACE
| bsd-3-clause |
HackLinux/goblin-core | llvm/3.4.2/llvm-3.4.2.src/lib/Target/Hexagon/HexagonRemoveSZExtArgs.cpp | 16 | 2725 | //===- HexagonRemoveExtendArgs.cpp - Remove unnecessary argument sign extends //
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Pass that removes sign extends for function parameters. These parameters
// are already sign extended by the caller per Hexagon's ABI
//
//===----------------------------------------------------------------------===//
#include "Hexagon.h"
#include "HexagonTargetMachine.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
namespace llvm {
void initializeHexagonRemoveExtendArgsPass(PassRegistry&);
}
namespace {
struct HexagonRemoveExtendArgs : public FunctionPass {
public:
static char ID;
HexagonRemoveExtendArgs() : FunctionPass(ID) {
initializeHexagonRemoveExtendArgsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &F);
const char *getPassName() const {
return "Remove sign extends";
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<MachineFunctionAnalysis>();
AU.addPreserved<MachineFunctionAnalysis>();
FunctionPass::getAnalysisUsage(AU);
}
};
}
char HexagonRemoveExtendArgs::ID = 0;
INITIALIZE_PASS(HexagonRemoveExtendArgs, "reargs",
"Remove Sign and Zero Extends for Args", false, false)
bool HexagonRemoveExtendArgs::runOnFunction(Function &F) {
unsigned Idx = 1;
for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
++AI, ++Idx) {
if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) {
Argument* Arg = AI;
if (!isa<PointerType>(Arg->getType())) {
for (Instruction::use_iterator UI = Arg->use_begin();
UI != Arg->use_end();) {
if (isa<SExtInst>(*UI)) {
Instruction* Use = cast<Instruction>(*UI);
SExtInst* SI = new SExtInst(Arg, Use->getType());
assert (EVT::getEVT(SI->getType()) ==
(EVT::getEVT(Use->getType())));
++UI;
Use->replaceAllUsesWith(SI);
Instruction* First = F.getEntryBlock().begin();
SI->insertBefore(First);
Use->eraseFromParent();
} else {
++UI;
}
}
}
}
}
return true;
}
FunctionPass*
llvm::createHexagonRemoveExtendArgs(const HexagonTargetMachine &TM) {
return new HexagonRemoveExtendArgs();
}
| bsd-3-clause |
zhmz90/OpenBLAS | lapack-netlib/lapacke/src/lapacke_sgbsv.c | 18 | 2747 | /*****************************************************************************
Copyright (c) 2011, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function sgbsv
* Author: Intel Corporation
* Generated November, 2011
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_sgbsv( int matrix_order, lapack_int n, lapack_int kl,
lapack_int ku, lapack_int nrhs, float* ab,
lapack_int ldab, lapack_int* ipiv, float* b,
lapack_int ldb )
{
if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_sgbsv", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_sgb_nancheck( matrix_order, n, n, kl, kl+ku, ab, ldab ) ) {
return -6;
}
if( LAPACKE_sge_nancheck( matrix_order, n, nrhs, b, ldb ) ) {
return -9;
}
#endif
return LAPACKE_sgbsv_work( matrix_order, n, kl, ku, nrhs, ab, ldab, ipiv, b,
ldb );
}
| bsd-3-clause |
MjAbuz/OpenBLAS | lapack-netlib/lapacke/src/lapacke_zhseqr_work.c | 18 | 5369 | /*****************************************************************************
Copyright (c) 2011, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native middle-level C interface to LAPACK function zhseqr
* Author: Intel Corporation
* Generated November, 2011
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_zhseqr_work( int matrix_order, char job, char compz,
lapack_int n, lapack_int ilo, lapack_int ihi,
lapack_complex_double* h, lapack_int ldh,
lapack_complex_double* w,
lapack_complex_double* z, lapack_int ldz,
lapack_complex_double* work, lapack_int lwork )
{
lapack_int info = 0;
if( matrix_order == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_zhseqr( &job, &compz, &n, &ilo, &ihi, h, &ldh, w, z, &ldz, work,
&lwork, &info );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_order == LAPACK_ROW_MAJOR ) {
lapack_int ldh_t = MAX(1,n);
lapack_int ldz_t = MAX(1,n);
lapack_complex_double* h_t = NULL;
lapack_complex_double* z_t = NULL;
/* Check leading dimension(s) */
if( ldh < n ) {
info = -8;
LAPACKE_xerbla( "LAPACKE_zhseqr_work", info );
return info;
}
if( ldz < n ) {
info = -11;
LAPACKE_xerbla( "LAPACKE_zhseqr_work", info );
return info;
}
/* Query optimal working array(s) size if requested */
if( lwork == -1 ) {
LAPACK_zhseqr( &job, &compz, &n, &ilo, &ihi, h, &ldh_t, w, z,
&ldz_t, work, &lwork, &info );
return (info < 0) ? (info - 1) : info;
}
/* Allocate memory for temporary array(s) */
h_t = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) * ldh_t * MAX(1,n) );
if( h_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) {
z_t = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) *
ldz_t * MAX(1,n) );
if( z_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_1;
}
}
/* Transpose input matrices */
LAPACKE_zge_trans( matrix_order, n, n, h, ldh, h_t, ldh_t );
if( LAPACKE_lsame( compz, 'v' ) ) {
LAPACKE_zge_trans( matrix_order, n, n, z, ldz, z_t, ldz_t );
}
/* Call LAPACK function and adjust info */
LAPACK_zhseqr( &job, &compz, &n, &ilo, &ihi, h_t, &ldh_t, w, z_t,
&ldz_t, work, &lwork, &info );
if( info < 0 ) {
info = info - 1;
}
/* Transpose output matrices */
LAPACKE_zge_trans( LAPACK_COL_MAJOR, n, n, h_t, ldh_t, h, ldh );
if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) {
LAPACKE_zge_trans( LAPACK_COL_MAJOR, n, n, z_t, ldz_t, z, ldz );
}
/* Release memory and exit */
if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) {
LAPACKE_free( z_t );
}
exit_level_1:
LAPACKE_free( h_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_zhseqr_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_zhseqr_work", info );
}
return info;
}
| bsd-3-clause |
dylanede/blaze-lib | blazetest/src/mathtest/smatsmatmult/LCaUCb.cpp | 18 | 5084 | //=================================================================================================
/*!
// \file src/mathtest/smatsmatmult/LCaUCb.cpp
// \brief Source file for the LCaUCb sparse matrix/sparse matrix multiplication math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatsmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'LCaUCb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::LowerMatrix< blaze::CompressedMatrix<TypeA> > LCa;
typedef blaze::UpperMatrix< blaze::CompressedMatrix<TypeB> > UCb;
// Creator type definitions
typedef blazetest::Creator<LCa> CLCa;
typedef blazetest::Creator<UCb> CUCb;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0UL ), CUCb( i, 0UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0UL ), CUCb( i, 0.2*i*i ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0UL ), CUCb( i, 0.5*i*i ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.2*i*i ), CUCb( i, 0UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.2*i*i ), CUCb( i, 0.2*i*i ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.2*i*i ), CUCb( i, 0.5*i*i ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.5*i*i ), CUCb( i, 0UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.5*i*i ), CUCb( i, 0.2*i*i ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( i, 0.5*i*i ), CUCb( i, 0.5*i*i ) );
}
// Running tests with large matrices
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 15UL, 7UL ), CUCb( 15UL, 7UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 37UL, 7UL ), CUCb( 37UL, 7UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 63UL, 13UL ), CUCb( 63UL, 13UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 16UL, 8UL ), CUCb( 16UL, 8UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 32UL, 8UL ), CUCb( 32UL, 8UL ) );
RUN_SMATSMATMULT_OPERATION_TEST( CLCa( 64UL, 16UL ), CUCb( 64UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| bsd-3-clause |
wsavoie/blaze-lib | blazemark/src/boost/TDMatDVecMult.cpp | 19 | 4554 | //=================================================================================================
/*!
// \file src/boost/TDMatDVecMult.cpp
// \brief Source file for the Boost transpose dense matrix/dense vector multiplication kernel
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <blaze/util/Timing.h>
#include <blazemark/boost/init/Matrix.h>
#include <blazemark/boost/init/Vector.h>
#include <blazemark/boost/TDMatDVecMult.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace boost {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Boost uBLAS transpose dense matrix/dense vector multiplication kernel.
//
// \param N The number of rows and columns of the matrix and the size of the vector.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the transpose dense matrix/dense vector multiplication by
// means of the Boost uBLAS functionality.
*/
double tdmatdvecmult( size_t N, size_t steps )
{
using ::blazemark::element_t;
using ::boost::numeric::ublas::column_major;
::blaze::setSeed( seed );
::boost::numeric::ublas::matrix<element_t,column_major> A( N, N );
::boost::numeric::ublas::vector<element_t> a( N ), b( N );
::blaze::timing::WcTimer timer;
init( A );
init( a );
noalias( b ) = prod( A, a );
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
noalias( b ) = prod( A, a );
}
timer.end();
if( b.size() != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " Boost uBLAS kernel 'tdmatdvecmult': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace boost
} // namespace blazemark
| bsd-3-clause |
tianzhihen/phantomjs | src/qt/src/gui/widgets/qabstractbutton.cpp | 19 | 39365 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qabstractbutton.h"
#include "qabstractitemview.h"
#include "qbuttongroup.h"
#include "qabstractbutton_p.h"
#include "qevent.h"
#include "qpainter.h"
#include "qapplication.h"
#include "qstyle.h"
#include "qaction.h"
#ifndef QT_NO_ACCESSIBILITY
#include "qaccessible.h"
#endif
QT_BEGIN_NAMESPACE
#define AUTO_REPEAT_DELAY 300
#define AUTO_REPEAT_INTERVAL 100
Q_GUI_EXPORT extern bool qt_tab_all_widgets;
/*!
\class QAbstractButton
\brief The QAbstractButton class is the abstract base class of
button widgets, providing functionality common to buttons.
\ingroup abstractwidgets
This class implements an \e abstract button.
Subclasses of this class handle user actions, and specify how the button
is drawn.
QAbstractButton provides support for both push buttons and checkable
(toggle) buttons. Checkable buttons are implemented in the QRadioButton
and QCheckBox classes. Push buttons are implemented in the
QPushButton and QToolButton classes; these also provide toggle
behavior if required.
Any button can display a label containing text and an icon. setText()
sets the text; setIcon() sets the icon. If a button is disabled, its label
is changed to give the button a "disabled" appearance.
If the button is a text button with a string containing an
ampersand ('&'), QAbstractButton automatically creates a shortcut
key. For example:
\snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 0
The \key Alt+C shortcut is assigned to the button, i.e., when the
user presses \key Alt+C the button will call animateClick(). See
the \l {QShortcut#mnemonic}{QShortcut} documentation for details
(to display an actual ampersand, use '&&').
You can also set a custom shortcut key using the setShortcut()
function. This is useful mostly for buttons that do not have any
text, because they have no automatic shortcut.
\snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 1
All of the buttons provided by Qt (QPushButton, QToolButton,
QCheckBox, and QRadioButton) can display both \l text and \l{icon}{icons}.
A button can be made the default button in a dialog are provided by
QPushButton::setDefault() and QPushButton::setAutoDefault().
QAbstractButton provides most of the states used for buttons:
\list
\o isDown() indicates whether the button is \e pressed down.
\o isChecked() indicates whether the button is \e checked. Only
checkable buttons can be checked and unchecked (see below).
\o isEnabled() indicates whether the button can be pressed by the
user. \note As opposed to other widgets, buttons derived from
QAbstractButton accepts mouse and context menu events
when disabled.
\o setAutoRepeat() sets whether the button will auto-repeat if the
user holds it down. \l autoRepeatDelay and \l autoRepeatInterval
define how auto-repetition is done.
\o setCheckable() sets whether the button is a toggle button or not.
\endlist
The difference between isDown() and isChecked() is as follows.
When the user clicks a toggle button to check it, the button is first
\e pressed then released into the \e checked state. When the user
clicks it again (to uncheck it), the button moves first to the
\e pressed state, then to the \e unchecked state (isChecked() and
isDown() are both false).
QAbstractButton provides four signals:
\list 1
\o pressed() is emitted when the left mouse button is pressed while
the mouse cursor is inside the button.
\o released() is emitted when the left mouse button is released.
\o clicked() is emitted when the button is first pressed and then
released, when the shortcut key is typed, or when click() or
animateClick() is called.
\o toggled() is emitted when the state of a toggle button changes.
\endlist
To subclass QAbstractButton, you must reimplement at least
paintEvent() to draw the button's outline and its text or pixmap. It
is generally advisable to reimplement sizeHint() as well, and
sometimes hitButton() (to determine whether a button press is within
the button). For buttons with more than two states (like tri-state
buttons), you will also have to reimplement checkStateSet() and
nextCheckState().
\sa QButtonGroup
*/
QAbstractButtonPrivate::QAbstractButtonPrivate(QSizePolicy::ControlType type)
:
#ifndef QT_NO_SHORTCUT
shortcutId(0),
#endif
checkable(false), checked(false), autoRepeat(false), autoExclusive(false),
down(false), blockRefresh(false), pressed(false),
#ifndef QT_NO_BUTTONGROUP
group(0),
#endif
autoRepeatDelay(AUTO_REPEAT_DELAY),
autoRepeatInterval(AUTO_REPEAT_INTERVAL),
controlType(type)
{}
#ifndef QT_NO_BUTTONGROUP
class QButtonGroupPrivate: public QObjectPrivate
{
Q_DECLARE_PUBLIC(QButtonGroup)
public:
QButtonGroupPrivate():exclusive(true){}
QList<QAbstractButton *> buttonList;
QPointer<QAbstractButton> checkedButton;
void detectCheckedButton();
void notifyChecked(QAbstractButton *button);
bool exclusive;
QMap<QAbstractButton*, int> mapping;
};
QButtonGroup::QButtonGroup(QObject *parent)
: QObject(*new QButtonGroupPrivate, parent)
{
}
QButtonGroup::~QButtonGroup()
{
Q_D(QButtonGroup);
for (int i = 0; i < d->buttonList.count(); ++i)
d->buttonList.at(i)->d_func()->group = 0;
}
bool QButtonGroup::exclusive() const
{
Q_D(const QButtonGroup);
return d->exclusive;
}
void QButtonGroup::setExclusive(bool exclusive)
{
Q_D(QButtonGroup);
d->exclusive = exclusive;
}
// TODO: Qt 5: Merge with addButton(QAbstractButton *button, int id)
void QButtonGroup::addButton(QAbstractButton *button)
{
addButton(button, -1);
}
void QButtonGroup::addButton(QAbstractButton *button, int id)
{
Q_D(QButtonGroup);
if (QButtonGroup *previous = button->d_func()->group)
previous->removeButton(button);
button->d_func()->group = this;
d->buttonList.append(button);
if (id == -1) {
QList<int> ids = d->mapping.values();
if (ids.isEmpty())
d->mapping[button] = -2;
else {
qSort(ids);
d->mapping[button] = ids.first()-1;
}
} else {
d->mapping[button] = id;
}
if (d->exclusive && button->isChecked())
button->d_func()->notifyChecked();
}
void QButtonGroup::removeButton(QAbstractButton *button)
{
Q_D(QButtonGroup);
if (d->checkedButton == button) {
d->detectCheckedButton();
}
if (button->d_func()->group == this) {
button->d_func()->group = 0;
d->buttonList.removeAll(button);
d->mapping.remove(button);
}
}
QList<QAbstractButton*> QButtonGroup::buttons() const
{
Q_D(const QButtonGroup);
return d->buttonList;
}
QAbstractButton *QButtonGroup::checkedButton() const
{
Q_D(const QButtonGroup);
return d->checkedButton;
}
QAbstractButton *QButtonGroup::button(int id) const
{
Q_D(const QButtonGroup);
return d->mapping.key(id);
}
void QButtonGroup::setId(QAbstractButton *button, int id)
{
Q_D(QButtonGroup);
if (button && id != -1)
d->mapping[button] = id;
}
int QButtonGroup::id(QAbstractButton *button) const
{
Q_D(const QButtonGroup);
return d->mapping.value(button, -1);
}
int QButtonGroup::checkedId() const
{
Q_D(const QButtonGroup);
return d->mapping.value(d->checkedButton, -1);
}
// detect a checked button other than the current one
void QButtonGroupPrivate::detectCheckedButton()
{
QAbstractButton *previous = checkedButton;
checkedButton = 0;
if (exclusive)
return;
for (int i = 0; i < buttonList.count(); i++) {
if (buttonList.at(i) != previous && buttonList.at(i)->isChecked()) {
checkedButton = buttonList.at(i);
return;
}
}
}
#endif // QT_NO_BUTTONGROUP
QList<QAbstractButton *>QAbstractButtonPrivate::queryButtonList() const
{
#ifndef QT_NO_BUTTONGROUP
if (group)
return group->d_func()->buttonList;
#endif
QList<QAbstractButton*>candidates = parent->findChildren<QAbstractButton *>();
if (autoExclusive) {
for (int i = candidates.count() - 1; i >= 0; --i) {
QAbstractButton *candidate = candidates.at(i);
if (!candidate->autoExclusive()
#ifndef QT_NO_BUTTONGROUP
|| candidate->group()
#endif
)
candidates.removeAt(i);
}
}
return candidates;
}
QAbstractButton *QAbstractButtonPrivate::queryCheckedButton() const
{
#ifndef QT_NO_BUTTONGROUP
if (group)
return group->d_func()->checkedButton;
#endif
Q_Q(const QAbstractButton);
QList<QAbstractButton *> buttonList = queryButtonList();
if (!autoExclusive || buttonList.count() == 1) // no group
return 0;
for (int i = 0; i < buttonList.count(); ++i) {
QAbstractButton *b = buttonList.at(i);
if (b->d_func()->checked && b != q)
return b;
}
return checked ? const_cast<QAbstractButton *>(q) : 0;
}
void QAbstractButtonPrivate::notifyChecked()
{
#ifndef QT_NO_BUTTONGROUP
Q_Q(QAbstractButton);
if (group) {
QAbstractButton *previous = group->d_func()->checkedButton;
group->d_func()->checkedButton = q;
if (group->d_func()->exclusive && previous && previous != q)
previous->nextCheckState();
} else
#endif
if (autoExclusive) {
if (QAbstractButton *b = queryCheckedButton())
b->setChecked(false);
}
}
void QAbstractButtonPrivate::moveFocus(int key)
{
QList<QAbstractButton *> buttonList = queryButtonList();;
#ifndef QT_NO_BUTTONGROUP
bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
#else
bool exclusive = autoExclusive;
#endif
QWidget *f = QApplication::focusWidget();
QAbstractButton *fb = qobject_cast<QAbstractButton *>(f);
if (!fb || !buttonList.contains(fb))
return;
QAbstractButton *candidate = 0;
int bestScore = -1;
QRect target = f->rect().translated(f->mapToGlobal(QPoint(0,0)));
QPoint goal = target.center();
uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
for (int i = 0; i < buttonList.count(); ++i) {
QAbstractButton *button = buttonList.at(i);
if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() &&
(autoExclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0)));
QPoint p = buttonRect.center();
//Priority to widgets that overlap on the same coordinate.
//In that case, the distance in the direction will be used as significant score,
//take also in account orthogonal distance in case two widget are in the same distance.
int score;
if ((buttonRect.x() < target.right() && target.x() < buttonRect.right())
&& (key == Qt::Key_Up || key == Qt::Key_Down)) {
//one item's is at the vertical of the other
score = (qAbs(p.y() - goal.y()) << 16) + qAbs(p.x() - goal.x());
} else if ((buttonRect.y() < target.bottom() && target.y() < buttonRect.bottom())
&& (key == Qt::Key_Left || key == Qt::Key_Right) ) {
//one item's is at the horizontal of the other
score = (qAbs(p.x() - goal.x()) << 16) + qAbs(p.y() - goal.y());
} else {
score = (1 << 30) + (p.y() - goal.y()) * (p.y() - goal.y()) + (p.x() - goal.x()) * (p.x() - goal.x());
}
if (score > bestScore && candidate)
continue;
switch(key) {
case Qt::Key_Up:
if (p.y() < goal.y()) {
candidate = button;
bestScore = score;
}
break;
case Qt::Key_Down:
if (p.y() > goal.y()) {
candidate = button;
bestScore = score;
}
break;
case Qt::Key_Left:
if (p.x() < goal.x()) {
candidate = button;
bestScore = score;
}
break;
case Qt::Key_Right:
if (p.x() > goal.x()) {
candidate = button;
bestScore = score;
}
break;
}
}
}
if (exclusive
#ifdef QT_KEYPAD_NAVIGATION
&& !QApplication::keypadNavigationEnabled()
#endif
&& candidate
&& fb->d_func()->checked
&& candidate->d_func()->checkable)
candidate->click();
if (candidate) {
if (key == Qt::Key_Up || key == Qt::Key_Left)
candidate->setFocus(Qt::BacktabFocusReason);
else
candidate->setFocus(Qt::TabFocusReason);
}
}
void QAbstractButtonPrivate::fixFocusPolicy()
{
Q_Q(QAbstractButton);
#ifndef QT_NO_BUTTONGROUP
if (!group && !autoExclusive)
#else
if (!autoExclusive)
#endif
return;
QList<QAbstractButton *> buttonList = queryButtonList();
for (int i = 0; i < buttonList.count(); ++i) {
QAbstractButton *b = buttonList.at(i);
if (!b->isCheckable())
continue;
b->setFocusPolicy((Qt::FocusPolicy) ((b == q || !q->isCheckable())
? (b->focusPolicy() | Qt::TabFocus)
: (b->focusPolicy() & ~Qt::TabFocus)));
}
}
void QAbstractButtonPrivate::init()
{
Q_Q(QAbstractButton);
q->setFocusPolicy(Qt::FocusPolicy(q->style()->styleHint(QStyle::SH_Button_FocusPolicy)));
q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, controlType));
q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
q->setForegroundRole(QPalette::ButtonText);
q->setBackgroundRole(QPalette::Button);
}
void QAbstractButtonPrivate::refresh()
{
Q_Q(QAbstractButton);
if (blockRefresh)
return;
q->update();
#ifndef QT_NO_ACCESSIBILITY
QAccessible::updateAccessibility(q, 0, QAccessible::StateChanged);
#endif
}
void QAbstractButtonPrivate::click()
{
Q_Q(QAbstractButton);
down = false;
blockRefresh = true;
bool changeState = true;
if (checked && queryCheckedButton() == q) {
// the checked button of an exclusive or autoexclusive group cannot be unchecked
#ifndef QT_NO_BUTTONGROUP
if (group ? group->d_func()->exclusive : autoExclusive)
#else
if (autoExclusive)
#endif
changeState = false;
}
QPointer<QAbstractButton> guard(q);
if (changeState) {
q->nextCheckState();
if (!guard)
return;
}
blockRefresh = false;
refresh();
q->repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
if (guard)
emitReleased();
if (guard)
emitClicked();
}
void QAbstractButtonPrivate::emitClicked()
{
Q_Q(QAbstractButton);
QPointer<QAbstractButton> guard(q);
emit q->clicked(checked);
#ifndef QT_NO_BUTTONGROUP
if (guard && group) {
emit group->buttonClicked(group->id(q));
if (guard && group)
emit group->buttonClicked(q);
}
#endif
}
void QAbstractButtonPrivate::emitPressed()
{
Q_Q(QAbstractButton);
QPointer<QAbstractButton> guard(q);
emit q->pressed();
#ifndef QT_NO_BUTTONGROUP
if (guard && group) {
emit group->buttonPressed(group->id(q));
if (guard && group)
emit group->buttonPressed(q);
}
#endif
}
void QAbstractButtonPrivate::emitReleased()
{
Q_Q(QAbstractButton);
QPointer<QAbstractButton> guard(q);
emit q->released();
#ifndef QT_NO_BUTTONGROUP
if (guard && group) {
emit group->buttonReleased(group->id(q));
if (guard && group)
emit group->buttonReleased(q);
}
#endif
}
/*!
Constructs an abstract button with a \a parent.
*/
QAbstractButton::QAbstractButton(QWidget *parent)
: QWidget(*new QAbstractButtonPrivate, parent, 0)
{
Q_D(QAbstractButton);
d->init();
}
/*!
Destroys the button.
*/
QAbstractButton::~QAbstractButton()
{
#ifndef QT_NO_BUTTONGROUP
Q_D(QAbstractButton);
if (d->group)
d->group->removeButton(this);
#endif
}
/*! \internal
*/
QAbstractButton::QAbstractButton(QAbstractButtonPrivate &dd, QWidget *parent)
: QWidget(dd, parent, 0)
{
Q_D(QAbstractButton);
d->init();
}
/*!
\property QAbstractButton::text
\brief the text shown on the button
If the button has no text, the text() function will return a an empty
string.
If the text contains an ampersand character ('&'), a shortcut is
automatically created for it. The character that follows the '&' will
be used as the shortcut key. Any previous shortcut will be
overwritten, or cleared if no shortcut is defined by the text. See the
\l {QShortcut#mnemonic}{QShortcut} documentation for details (to
display an actual ampersand, use '&&').
There is no default text.
*/
void QAbstractButton::setText(const QString &text)
{
Q_D(QAbstractButton);
if (d->text == text)
return;
d->text = text;
#ifndef QT_NO_SHORTCUT
QKeySequence newMnemonic = QKeySequence::mnemonic(text);
setShortcut(newMnemonic);
#endif
d->sizeHint = QSize();
update();
updateGeometry();
#ifndef QT_NO_ACCESSIBILITY
QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
#endif
}
QString QAbstractButton::text() const
{
Q_D(const QAbstractButton);
return d->text;
}
/*!
\property QAbstractButton::icon
\brief the icon shown on the button
The icon's default size is defined by the GUI style, but can be
adjusted by setting the \l iconSize property.
*/
void QAbstractButton::setIcon(const QIcon &icon)
{
Q_D(QAbstractButton);
d->icon = icon;
d->sizeHint = QSize();
update();
updateGeometry();
}
QIcon QAbstractButton::icon() const
{
Q_D(const QAbstractButton);
return d->icon;
}
#ifndef QT_NO_SHORTCUT
/*!
\property QAbstractButton::shortcut
\brief the mnemonic associated with the button
*/
void QAbstractButton::setShortcut(const QKeySequence &key)
{
Q_D(QAbstractButton);
if (d->shortcutId != 0)
releaseShortcut(d->shortcutId);
d->shortcut = key;
d->shortcutId = grabShortcut(key);
}
QKeySequence QAbstractButton::shortcut() const
{
Q_D(const QAbstractButton);
return d->shortcut;
}
#endif // QT_NO_SHORTCUT
/*!
\property QAbstractButton::checkable
\brief whether the button is checkable
By default, the button is not checkable.
\sa checked
*/
void QAbstractButton::setCheckable(bool checkable)
{
Q_D(QAbstractButton);
if (d->checkable == checkable)
return;
d->checkable = checkable;
d->checked = false;
}
bool QAbstractButton::isCheckable() const
{
Q_D(const QAbstractButton);
return d->checkable;
}
/*!
\property QAbstractButton::checked
\brief whether the button is checked
Only checkable buttons can be checked. By default, the button is unchecked.
\sa checkable
*/
void QAbstractButton::setChecked(bool checked)
{
Q_D(QAbstractButton);
if (!d->checkable || d->checked == checked) {
if (!d->blockRefresh)
checkStateSet();
return;
}
if (!checked && d->queryCheckedButton() == this) {
// the checked button of an exclusive or autoexclusive group cannot be unchecked
#ifndef QT_NO_BUTTONGROUP
if (d->group ? d->group->d_func()->exclusive : d->autoExclusive)
return;
if (d->group)
d->group->d_func()->detectCheckedButton();
#else
if (d->autoExclusive)
return;
#endif
}
QPointer<QAbstractButton> guard(this);
d->checked = checked;
if (!d->blockRefresh)
checkStateSet();
d->refresh();
if (guard && checked)
d->notifyChecked();
if (guard)
emit toggled(checked);
}
bool QAbstractButton::isChecked() const
{
Q_D(const QAbstractButton);
return d->checked;
}
/*!
\property QAbstractButton::down
\brief whether the button is pressed down
If this property is true, the button is pressed down. The signals
pressed() and clicked() are not emitted if you set this property
to true. The default is false.
*/
void QAbstractButton::setDown(bool down)
{
Q_D(QAbstractButton);
if (d->down == down)
return;
d->down = down;
d->refresh();
if (d->autoRepeat && d->down)
d->repeatTimer.start(d->autoRepeatDelay, this);
else
d->repeatTimer.stop();
}
bool QAbstractButton::isDown() const
{
Q_D(const QAbstractButton);
return d->down;
}
/*!
\property QAbstractButton::autoRepeat
\brief whether autoRepeat is enabled
If autoRepeat is enabled, then the pressed(), released(), and clicked() signals are emitted at
regular intervals when the button is down. autoRepeat is off by default.
The initial delay and the repetition interval are defined in milliseconds by \l
autoRepeatDelay and \l autoRepeatInterval.
Note: If a button is pressed down by a shortcut key, then auto-repeat is enabled and timed by the
system and not by this class. The pressed(), released(), and clicked() signals will be emitted
like in the normal case.
*/
void QAbstractButton::setAutoRepeat(bool autoRepeat)
{
Q_D(QAbstractButton);
if (d->autoRepeat == autoRepeat)
return;
d->autoRepeat = autoRepeat;
if (d->autoRepeat && d->down)
d->repeatTimer.start(d->autoRepeatDelay, this);
else
d->repeatTimer.stop();
}
bool QAbstractButton::autoRepeat() const
{
Q_D(const QAbstractButton);
return d->autoRepeat;
}
/*!
\property QAbstractButton::autoRepeatDelay
\brief the initial delay of auto-repetition
\since 4.2
If \l autoRepeat is enabled, then autoRepeatDelay defines the initial
delay in milliseconds before auto-repetition kicks in.
\sa autoRepeat, autoRepeatInterval
*/
void QAbstractButton::setAutoRepeatDelay(int autoRepeatDelay)
{
Q_D(QAbstractButton);
d->autoRepeatDelay = autoRepeatDelay;
}
int QAbstractButton::autoRepeatDelay() const
{
Q_D(const QAbstractButton);
return d->autoRepeatDelay;
}
/*!
\property QAbstractButton::autoRepeatInterval
\brief the interval of auto-repetition
\since 4.2
If \l autoRepeat is enabled, then autoRepeatInterval defines the
length of the auto-repetition interval in millisecons.
\sa autoRepeat, autoRepeatDelay
*/
void QAbstractButton::setAutoRepeatInterval(int autoRepeatInterval)
{
Q_D(QAbstractButton);
d->autoRepeatInterval = autoRepeatInterval;
}
int QAbstractButton::autoRepeatInterval() const
{
Q_D(const QAbstractButton);
return d->autoRepeatInterval;
}
/*!
\property QAbstractButton::autoExclusive
\brief whether auto-exclusivity is enabled
If auto-exclusivity is enabled, checkable buttons that belong to the
same parent widget behave as if they were part of the same
exclusive button group. In an exclusive button group, only one button
can be checked at any time; checking another button automatically
unchecks the previously checked one.
The property has no effect on buttons that belong to a button
group.
autoExclusive is off by default, except for radio buttons.
\sa QRadioButton
*/
void QAbstractButton::setAutoExclusive(bool autoExclusive)
{
Q_D(QAbstractButton);
d->autoExclusive = autoExclusive;
}
bool QAbstractButton::autoExclusive() const
{
Q_D(const QAbstractButton);
return d->autoExclusive;
}
#ifndef QT_NO_BUTTONGROUP
/*!
Returns the group that this button belongs to.
If the button is not a member of any QButtonGroup, this function
returns 0.
\sa QButtonGroup
*/
QButtonGroup *QAbstractButton::group() const
{
Q_D(const QAbstractButton);
return d->group;
}
#endif // QT_NO_BUTTONGROUP
/*!
Performs an animated click: the button is pressed immediately, and
released \a msec milliseconds later (the default is 100 ms).
Calling this function again before the button was released will reset
the release timer.
All signals associated with a click are emitted as appropriate.
This function does nothing if the button is \link setEnabled()
disabled. \endlink
\sa click()
*/
void QAbstractButton::animateClick(int msec)
{
if (!isEnabled())
return;
Q_D(QAbstractButton);
if (d->checkable && focusPolicy() & Qt::ClickFocus)
setFocus();
setDown(true);
repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
if (!d->animateTimer.isActive())
d->emitPressed();
d->animateTimer.start(msec, this);
}
/*!
Performs a click.
All the usual signals associated with a click are emitted as
appropriate. If the button is checkable, the state of the button is
toggled.
This function does nothing if the button is \link setEnabled()
disabled. \endlink
\sa animateClick()
*/
void QAbstractButton::click()
{
if (!isEnabled())
return;
Q_D(QAbstractButton);
QPointer<QAbstractButton> guard(this);
d->down = true;
d->emitPressed();
if (guard) {
d->down = false;
nextCheckState();
if (guard)
d->emitReleased();
if (guard)
d->emitClicked();
}
}
/*! \fn void QAbstractButton::toggle()
Toggles the state of a checkable button.
\sa checked
*/
void QAbstractButton::toggle()
{
Q_D(QAbstractButton);
setChecked(!d->checked);
}
/*! This virtual handler is called when setChecked() was called,
unless it was called from within nextCheckState(). It allows
subclasses to reset their intermediate button states.
\sa nextCheckState()
*/
void QAbstractButton::checkStateSet()
{
}
/*! This virtual handler is called when a button is clicked. The
default implementation calls setChecked(!isChecked()) if the button
isCheckable(). It allows subclasses to implement intermediate button
states.
\sa checkStateSet()
*/
void QAbstractButton::nextCheckState()
{
if (isCheckable())
setChecked(!isChecked());
}
/*!
Returns true if \a pos is inside the clickable button rectangle;
otherwise returns false.
By default, the clickable area is the entire widget. Subclasses
may reimplement this function to provide support for clickable
areas of different shapes and sizes.
*/
bool QAbstractButton::hitButton(const QPoint &pos) const
{
return rect().contains(pos);
}
/*! \reimp */
bool QAbstractButton::event(QEvent *e)
{
// as opposed to other widgets, disabled buttons accept mouse
// events. This avoids surprising click-through scenarios
if (!isEnabled()) {
switch(e->type()) {
case QEvent::TabletPress:
case QEvent::TabletRelease:
case QEvent::TabletMove:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
case QEvent::HoverMove:
case QEvent::HoverEnter:
case QEvent::HoverLeave:
case QEvent::ContextMenu:
#ifndef QT_NO_WHEELEVENT
case QEvent::Wheel:
#endif
return true;
default:
break;
}
}
#ifndef QT_NO_SHORTCUT
if (e->type() == QEvent::Shortcut) {
Q_D(QAbstractButton);
QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
if (d->shortcutId != se->shortcutId())
return false;
if (!se->isAmbiguous()) {
if (!d->animateTimer.isActive())
animateClick();
} else {
if (focusPolicy() != Qt::NoFocus)
setFocus(Qt::ShortcutFocusReason);
window()->setAttribute(Qt::WA_KeyboardFocusChange);
}
return true;
}
#endif
return QWidget::event(e);
}
/*! \reimp */
void QAbstractButton::mousePressEvent(QMouseEvent *e)
{
Q_D(QAbstractButton);
if (e->button() != Qt::LeftButton) {
e->ignore();
return;
}
if (hitButton(e->pos())) {
setDown(true);
d->pressed = true;
repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
d->emitPressed();
e->accept();
} else {
e->ignore();
}
}
/*! \reimp */
void QAbstractButton::mouseReleaseEvent(QMouseEvent *e)
{
Q_D(QAbstractButton);
d->pressed = false;
if (e->button() != Qt::LeftButton) {
e->ignore();
return;
}
if (!d->down) {
e->ignore();
return;
}
if (hitButton(e->pos())) {
d->repeatTimer.stop();
d->click();
e->accept();
} else {
setDown(false);
e->ignore();
}
}
/*! \reimp */
void QAbstractButton::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QAbstractButton);
if (!(e->buttons() & Qt::LeftButton) || !d->pressed) {
e->ignore();
return;
}
if (hitButton(e->pos()) != d->down) {
setDown(!d->down);
repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
if (d->down)
d->emitPressed();
else
d->emitReleased();
e->accept();
} else if (!hitButton(e->pos())) {
e->ignore();
}
}
/*! \reimp */
void QAbstractButton::keyPressEvent(QKeyEvent *e)
{
Q_D(QAbstractButton);
bool next = true;
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
e->ignore();
break;
case Qt::Key_Select:
case Qt::Key_Space:
if (!e->isAutoRepeat()) {
setDown(true);
repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
d->emitPressed();
}
break;
case Qt::Key_Up:
case Qt::Key_Left:
next = false;
// fall through
case Qt::Key_Right:
case Qt::Key_Down:
#ifdef QT_KEYPAD_NAVIGATION
if ((QApplication::keypadNavigationEnabled()
&& (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
|| (!QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
|| (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down))) {
e->ignore();
return;
}
#endif
QWidget *pw;
if (d->autoExclusive
#ifndef QT_NO_BUTTONGROUP
|| d->group
#endif
#ifndef QT_NO_ITEMVIEWS
|| ((pw = parentWidget()) && qobject_cast<QAbstractItemView *>(pw->parentWidget()))
#endif
) {
// ### Using qobject_cast to check if the parent is a viewport of
// QAbstractItemView is a crude hack, and should be revisited and
// cleaned up when fixing task 194373. It's here to ensure that we
// keep compatibility outside QAbstractItemView.
d->moveFocus(e->key());
if (hasFocus()) // nothing happend, propagate
e->ignore();
} else {
focusNextPrevChild(next);
}
break;
case Qt::Key_Escape:
if (d->down) {
setDown(false);
repaint(); //flush paint event before invoking potentially expensive operation
QApplication::flush();
d->emitReleased();
break;
}
// fall through
default:
e->ignore();
}
}
/*! \reimp */
void QAbstractButton::keyReleaseEvent(QKeyEvent *e)
{
Q_D(QAbstractButton);
if (!e->isAutoRepeat())
d->repeatTimer.stop();
switch (e->key()) {
case Qt::Key_Select:
case Qt::Key_Space:
if (!e->isAutoRepeat() && d->down)
d->click();
break;
default:
e->ignore();
}
}
/*!\reimp
*/
void QAbstractButton::timerEvent(QTimerEvent *e)
{
Q_D(QAbstractButton);
if (e->timerId() == d->repeatTimer.timerId()) {
d->repeatTimer.start(d->autoRepeatInterval, this);
if (d->down) {
QPointer<QAbstractButton> guard(this);
nextCheckState();
if (guard)
d->emitReleased();
if (guard)
d->emitClicked();
if (guard)
d->emitPressed();
}
} else if (e->timerId() == d->animateTimer.timerId()) {
d->animateTimer.stop();
d->click();
}
}
/*! \reimp */
void QAbstractButton::focusInEvent(QFocusEvent *e)
{
Q_D(QAbstractButton);
#ifdef QT_KEYPAD_NAVIGATION
if (!QApplication::keypadNavigationEnabled())
#endif
d->fixFocusPolicy();
QWidget::focusInEvent(e);
}
/*! \reimp */
void QAbstractButton::focusOutEvent(QFocusEvent *e)
{
Q_D(QAbstractButton);
if (e->reason() != Qt::PopupFocusReason)
d->down = false;
QWidget::focusOutEvent(e);
}
/*! \reimp */
void QAbstractButton::changeEvent(QEvent *e)
{
Q_D(QAbstractButton);
switch (e->type()) {
case QEvent::EnabledChange:
if (!isEnabled())
setDown(false);
break;
default:
d->sizeHint = QSize();
break;
}
QWidget::changeEvent(e);
}
/*!
\fn void QAbstractButton::paintEvent(QPaintEvent *e)
\reimp
*/
/*!
\fn void QAbstractButton::pressed()
This signal is emitted when the button is pressed down.
\sa released(), clicked()
*/
/*!
\fn void QAbstractButton::released()
This signal is emitted when the button is released.
\sa pressed(), clicked(), toggled()
*/
/*!
\fn void QAbstractButton::clicked(bool checked)
This signal is emitted when the button is activated (i.e. pressed down
then released while the mouse cursor is inside the button), when the
shortcut key is typed, or when click() or animateClick() is called.
Notably, this signal is \e not emitted if you call setDown(),
setChecked() or toggle().
If the button is checkable, \a checked is true if the button is
checked, or false if the button is unchecked.
\sa pressed(), released(), toggled()
*/
/*!
\fn void QAbstractButton::toggled(bool checked)
This signal is emitted whenever a checkable button changes its state.
\a checked is true if the button is checked, or false if the button is
unchecked.
This may be the result of a user action, click() slot activation,
or because setChecked() was called.
The states of buttons in exclusive button groups are updated before this
signal is emitted. This means that slots can act on either the "off"
signal or the "on" signal emitted by the buttons in the group whose
states have changed.
For example, a slot that reacts to signals emitted by newly checked
buttons but which ignores signals from buttons that have been unchecked
can be implemented using the following pattern:
\snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 2
Button groups can be created using the QButtonGroup class, and
updates to the button states monitored with the
\l{QButtonGroup::buttonClicked()} signal.
\sa checked, clicked()
*/
/*!
\property QAbstractButton::iconSize
\brief the icon size used for this button.
The default size is defined by the GUI style. This is a maximum
size for the icons. Smaller icons will not be scaled up.
*/
QSize QAbstractButton::iconSize() const
{
Q_D(const QAbstractButton);
if (d->iconSize.isValid())
return d->iconSize;
int e = style()->pixelMetric(QStyle::PM_ButtonIconSize, 0, this);
return QSize(e, e);
}
void QAbstractButton::setIconSize(const QSize &size)
{
Q_D(QAbstractButton);
if (d->iconSize == size)
return;
d->iconSize = size;
d->sizeHint = QSize();
updateGeometry();
if (isVisible()) {
update();
}
}
#ifdef QT3_SUPPORT
/*!
Use icon() instead.
*/
QIcon *QAbstractButton::iconSet() const
{
Q_D(const QAbstractButton);
if (!d->icon.isNull())
return const_cast<QIcon *>(&d->icon);
return 0;
}
/*!
Use QAbstractButton(QWidget *) instead.
Call setObjectName() if you want to specify an object name, and
setParent() if you want to set the window flags.
*/
QAbstractButton::QAbstractButton(QWidget *parent, const char *name, Qt::WindowFlags f)
: QWidget(*new QAbstractButtonPrivate, parent, f)
{
Q_D(QAbstractButton);
setObjectName(QString::fromAscii(name));
d->init();
}
/*! \fn bool QAbstractButton::isOn() const
Use isChecked() instead.
*/
/*!
\fn QPixmap *QAbstractButton::pixmap() const
This compatibility function always returns 0.
Use icon() instead.
*/
/*! \fn void QAbstractButton::setPixmap(const QPixmap &p)
Use setIcon() instead.
*/
/*! \fn void QAbstractButton::setIconSet(const QIcon &icon)
Use setIcon() instead.
*/
/*! \fn void QAbstractButton::setOn(bool b)
Use setChecked() instead.
*/
/*! \fn bool QAbstractButton::isToggleButton() const
Use isCheckable() instead.
*/
/*!
\fn void QAbstractButton::setToggleButton(bool b)
Use setCheckable() instead.
*/
/*! \fn void QAbstractButton::setAccel(const QKeySequence &key)
Use setShortcut() instead.
*/
/*! \fn QKeySequence QAbstractButton::accel() const
Use shortcut() instead.
*/
#endif
QT_END_NAMESPACE
| bsd-3-clause |
castoryan/OpenBLAS | lapack-netlib/SRC/sla_lin_berr.f | 24 | 4466 | *> \brief \b SLA_LIN_BERR computes a component-wise relative backward error.
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download SLA_LIN_BERR + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sla_lin_berr.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sla_lin_berr.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sla_lin_berr.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE SLA_LIN_BERR ( N, NZ, NRHS, RES, AYB, BERR )
*
* .. Scalar Arguments ..
* INTEGER N, NZ, NRHS
* ..
* .. Array Arguments ..
* REAL AYB( N, NRHS ), BERR( NRHS )
* REAL RES( N, NRHS )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> SLA_LIN_BERR computes componentwise relative backward error from
*> the formula
*> max(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
*> where abs(Z) is the componentwise absolute value of the matrix
*> or vector Z.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The number of linear equations, i.e., the order of the
*> matrix A. N >= 0.
*> \endverbatim
*>
*> \param[in] NZ
*> \verbatim
*> NZ is INTEGER
*> We add (NZ+1)*SLAMCH( 'Safe minimum' ) to R(i) in the numerator to
*> guard against spuriously zero residuals. Default value is N.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*> NRHS is INTEGER
*> The number of right hand sides, i.e., the number of columns
*> of the matrices AYB, RES, and BERR. NRHS >= 0.
*> \endverbatim
*>
*> \param[in] RES
*> \verbatim
*> RES is REAL array, dimension (N,NRHS)
*> The residual matrix, i.e., the matrix R in the relative backward
*> error formula above.
*> \endverbatim
*>
*> \param[in] AYB
*> \verbatim
*> AYB is REAL array, dimension (N, NRHS)
*> The denominator in the relative backward error formula above, i.e.,
*> the matrix abs(op(A_s))*abs(Y) + abs(B_s). The matrices A, Y, and B
*> are from iterative refinement (see sla_gerfsx_extended.f).
*> \endverbatim
*>
*> \param[out] BERR
*> \verbatim
*> BERR is REAL array, dimension (NRHS)
*> The componentwise relative backward error from the formula above.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date September 2012
*
*> \ingroup realOTHERcomputational
*
* =====================================================================
SUBROUTINE SLA_LIN_BERR ( N, NZ, NRHS, RES, AYB, BERR )
*
* -- LAPACK computational routine (version 3.4.2) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* September 2012
*
* .. Scalar Arguments ..
INTEGER N, NZ, NRHS
* ..
* .. Array Arguments ..
REAL AYB( N, NRHS ), BERR( NRHS )
REAL RES( N, NRHS )
* ..
*
* =====================================================================
*
* .. Local Scalars ..
REAL TMP
INTEGER I, J
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, MAX
* ..
* .. External Functions ..
EXTERNAL SLAMCH
REAL SLAMCH
REAL SAFE1
* ..
* .. Executable Statements ..
*
* Adding SAFE1 to the numerator guards against spuriously zero
* residuals. A similar safeguard is in the SLA_yyAMV routine used
* to compute AYB.
*
SAFE1 = SLAMCH( 'Safe minimum' )
SAFE1 = (NZ+1)*SAFE1
DO J = 1, NRHS
BERR(J) = 0.0
DO I = 1, N
IF (AYB(I,J) .NE. 0.0) THEN
TMP = (SAFE1+ABS(RES(I,J)))/AYB(I,J)
BERR(J) = MAX( BERR(J), TMP )
END IF
*
* If AYB is exactly 0.0 (and if computed by SLA_yyAMV), then we know
* the true residual also must be exactly 0.0.
*
END DO
END DO
END
| bsd-3-clause |
bitfusionio/OpenBLAS | lapack-netlib/SRC/clarf.f | 24 | 6362 | *> \brief \b CLARF applies an elementary reflector to a general rectangular matrix.
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download CLARF + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/clarf.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/clarf.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/clarf.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE CLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK )
*
* .. Scalar Arguments ..
* CHARACTER SIDE
* INTEGER INCV, LDC, M, N
* COMPLEX TAU
* ..
* .. Array Arguments ..
* COMPLEX C( LDC, * ), V( * ), WORK( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> CLARF applies a complex elementary reflector H to a complex M-by-N
*> matrix C, from either the left or the right. H is represented in the
*> form
*>
*> H = I - tau * v * v**H
*>
*> where tau is a complex scalar and v is a complex vector.
*>
*> If tau = 0, then H is taken to be the unit matrix.
*>
*> To apply H**H (the conjugate transpose of H), supply conjg(tau) instead
*> tau.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] SIDE
*> \verbatim
*> SIDE is CHARACTER*1
*> = 'L': form H * C
*> = 'R': form C * H
*> \endverbatim
*>
*> \param[in] M
*> \verbatim
*> M is INTEGER
*> The number of rows of the matrix C.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The number of columns of the matrix C.
*> \endverbatim
*>
*> \param[in] V
*> \verbatim
*> V is COMPLEX array, dimension
*> (1 + (M-1)*abs(INCV)) if SIDE = 'L'
*> or (1 + (N-1)*abs(INCV)) if SIDE = 'R'
*> The vector v in the representation of H. V is not used if
*> TAU = 0.
*> \endverbatim
*>
*> \param[in] INCV
*> \verbatim
*> INCV is INTEGER
*> The increment between elements of v. INCV <> 0.
*> \endverbatim
*>
*> \param[in] TAU
*> \verbatim
*> TAU is COMPLEX
*> The value tau in the representation of H.
*> \endverbatim
*>
*> \param[in,out] C
*> \verbatim
*> C is COMPLEX array, dimension (LDC,N)
*> On entry, the M-by-N matrix C.
*> On exit, C is overwritten by the matrix H * C if SIDE = 'L',
*> or C * H if SIDE = 'R'.
*> \endverbatim
*>
*> \param[in] LDC
*> \verbatim
*> LDC is INTEGER
*> The leading dimension of the array C. LDC >= max(1,M).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is COMPLEX array, dimension
*> (N) if SIDE = 'L'
*> or (M) if SIDE = 'R'
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date September 2012
*
*> \ingroup complexOTHERauxiliary
*
* =====================================================================
SUBROUTINE CLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK )
*
* -- LAPACK auxiliary routine (version 3.4.2) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* September 2012
*
* .. Scalar Arguments ..
CHARACTER SIDE
INTEGER INCV, LDC, M, N
COMPLEX TAU
* ..
* .. Array Arguments ..
COMPLEX C( LDC, * ), V( * ), WORK( * )
* ..
*
* =====================================================================
*
* .. Parameters ..
COMPLEX ONE, ZERO
PARAMETER ( ONE = ( 1.0E+0, 0.0E+0 ),
$ ZERO = ( 0.0E+0, 0.0E+0 ) )
* ..
* .. Local Scalars ..
LOGICAL APPLYLEFT
INTEGER I, LASTV, LASTC
* ..
* .. External Subroutines ..
EXTERNAL CGEMV, CGERC
* ..
* .. External Functions ..
LOGICAL LSAME
INTEGER ILACLR, ILACLC
EXTERNAL LSAME, ILACLR, ILACLC
* ..
* .. Executable Statements ..
*
APPLYLEFT = LSAME( SIDE, 'L' )
LASTV = 0
LASTC = 0
IF( TAU.NE.ZERO ) THEN
! Set up variables for scanning V. LASTV begins pointing to the end
! of V.
IF( APPLYLEFT ) THEN
LASTV = M
ELSE
LASTV = N
END IF
IF( INCV.GT.0 ) THEN
I = 1 + (LASTV-1) * INCV
ELSE
I = 1
END IF
! Look for the last non-zero row in V.
DO WHILE( LASTV.GT.0 .AND. V( I ).EQ.ZERO )
LASTV = LASTV - 1
I = I - INCV
END DO
IF( APPLYLEFT ) THEN
! Scan for the last non-zero column in C(1:lastv,:).
LASTC = ILACLC(LASTV, N, C, LDC)
ELSE
! Scan for the last non-zero row in C(:,1:lastv).
LASTC = ILACLR(M, LASTV, C, LDC)
END IF
END IF
! Note that lastc.eq.0 renders the BLAS operations null; no special
! case is needed at this level.
IF( APPLYLEFT ) THEN
*
* Form H * C
*
IF( LASTV.GT.0 ) THEN
*
* w(1:lastc,1) := C(1:lastv,1:lastc)**H * v(1:lastv,1)
*
CALL CGEMV( 'Conjugate transpose', LASTV, LASTC, ONE,
$ C, LDC, V, INCV, ZERO, WORK, 1 )
*
* C(1:lastv,1:lastc) := C(...) - v(1:lastv,1) * w(1:lastc,1)**H
*
CALL CGERC( LASTV, LASTC, -TAU, V, INCV, WORK, 1, C, LDC )
END IF
ELSE
*
* Form C * H
*
IF( LASTV.GT.0 ) THEN
*
* w(1:lastc,1) := C(1:lastc,1:lastv) * v(1:lastv,1)
*
CALL CGEMV( 'No transpose', LASTC, LASTV, ONE, C, LDC,
$ V, INCV, ZERO, WORK, 1 )
*
* C(1:lastc,1:lastv) := C(...) - w(1:lastc,1) * v(1:lastv,1)**H
*
CALL CGERC( LASTC, LASTV, -TAU, WORK, 1, V, INCV, C, LDC )
END IF
END IF
RETURN
*
* End of CLARF
*
END
| bsd-3-clause |
grisuthedragon/OpenBLAS | kernel/arm/omatcopy_cn.c | 24 | 2519 | /***************************************************************************
Copyright (c) 2013, The OpenBLAS Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of the OpenBLAS project nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE 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 OPENBLAS PROJECT OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include "common.h"
/*****************************************************
* 2014/06/09 Saar
*
* Order ColMajor
* No Trans
*
******************************************************/
int CNAME(BLASLONG rows, BLASLONG cols, FLOAT alpha, FLOAT *a, BLASLONG lda, FLOAT *b, BLASLONG ldb)
{
BLASLONG i,j;
FLOAT *aptr,*bptr;
if ( rows <= 0 ) return(0);
if ( cols <= 0 ) return(0);
aptr = a;
bptr = b;
if ( alpha == 0.0 )
{
for ( i=0; i<cols ; i++ )
{
for(j=0; j<rows; j++)
{
bptr[j] = 0.0;
}
bptr += ldb;
}
return(0);
}
if ( alpha == 1.0 )
{
for ( i=0; i<cols ; i++ )
{
for(j=0; j<rows; j++)
{
bptr[j] = aptr[j];
}
aptr += lda;
bptr += ldb;
}
return(0);
}
for ( i=0; i<cols ; i++ )
{
for(j=0; j<rows; j++)
{
bptr[j] = alpha * aptr[j];
}
aptr += lda;
bptr += ldb;
}
return(0);
}
| bsd-3-clause |
GaloisInc/hacrypto | src/C/FELICS/block_ciphers/source/ciphers/LBlock_64_80_v08/source/constants1.c | 24 | 1636 | /*
*
* University of Luxembourg
* Laboratory of Algorithmics, Cryptology and Security (LACS)
*
* FELICS - Fair Evaluation of Lightweight Cryptographic Systems
*
* Copyright (C) 2015 University of Luxembourg
*
* Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu>
*
* This file is part of FELICS.
*
* FELICS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* FELICS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR 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 <stdint.h>
#include "constants.h"
/*
*
* Cipher S-boxes
*
*/
SBOX_BYTE S0[16] = {14, 9, 15, 0, 13, 4, 10, 11, 1, 2, 8, 3, 7, 6, 12, 5};
SBOX_BYTE S1[16] = {4, 11, 14, 9, 15, 13, 0, 10, 7, 12, 5, 6, 2, 8, 1, 3};
SBOX_BYTE S2[16] = {1, 14, 7, 12, 15, 13, 0, 6, 11, 5, 9, 3, 2, 4, 8, 10};
SBOX_BYTE S3[16] = {7, 6, 8, 11, 0, 15, 3, 14, 9, 10, 12, 13, 5, 2, 4, 1};
SBOX_BYTE S4[16] = {14, 5, 15, 0, 7, 2, 12, 13, 1, 8, 4, 9, 11, 10, 6, 3};
SBOX_BYTE S5[16] = {2, 13, 11, 12, 15, 14, 0, 9, 7, 10, 6, 3, 1, 8, 4, 5};
SBOX_BYTE S6[16] = {11, 9, 4, 14, 0, 15, 10, 13, 6, 12, 5, 7, 3, 8, 1, 2};
SBOX_BYTE S7[16] = {13, 10, 15, 0, 14, 4, 9, 11, 2, 1, 8, 3, 7, 5, 12, 6};
| bsd-3-clause |
UCSantaCruzComputationalGenomicsLab/clapack | SRC/cung2l.c | 26 | 4873 | /* cung2l.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static integer c__1 = 1;
/* Subroutine */ int cung2l_(integer *m, integer *n, integer *k, complex *a,
integer *lda, complex *tau, complex *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
complex q__1;
/* Local variables */
integer i__, j, l, ii;
extern /* Subroutine */ int cscal_(integer *, complex *, complex *,
integer *), clarf_(char *, integer *, integer *, complex *,
integer *, complex *, complex *, integer *, complex *),
xerbla_(char *, integer *);
/* -- LAPACK routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CUNG2L generates an m by n complex matrix Q with orthonormal columns, */
/* which is defined as the last n columns of a product of k elementary */
/* reflectors of order m */
/* Q = H(k) . . . H(2) H(1) */
/* as returned by CGEQLF. */
/* Arguments */
/* ========= */
/* M (input) INTEGER */
/* The number of rows of the matrix Q. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix Q. M >= N >= 0. */
/* K (input) INTEGER */
/* The number of elementary reflectors whose product defines the */
/* matrix Q. N >= K >= 0. */
/* A (input/output) COMPLEX array, dimension (LDA,N) */
/* On entry, the (n-k+i)-th column must contain the vector which */
/* defines the elementary reflector H(i), for i = 1,2,...,k, as */
/* returned by CGEQLF in the last k columns of its array */
/* argument A. */
/* On exit, the m-by-n matrix Q. */
/* LDA (input) INTEGER */
/* The first dimension of the array A. LDA >= max(1,M). */
/* TAU (input) COMPLEX array, dimension (K) */
/* TAU(i) must contain the scalar factor of the elementary */
/* reflector H(i), as returned by CGEQLF. */
/* WORK (workspace) COMPLEX array, dimension (N) */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument has an illegal value */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0 || *n > *m) {
*info = -2;
} else if (*k < 0 || *k > *n) {
*info = -3;
} else if (*lda < max(1,*m)) {
*info = -5;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CUNG2L", &i__1);
return 0;
}
/* Quick return if possible */
if (*n <= 0) {
return 0;
}
/* Initialise columns 1:n-k to columns of the unit matrix */
i__1 = *n - *k;
for (j = 1; j <= i__1; ++j) {
i__2 = *m;
for (l = 1; l <= i__2; ++l) {
i__3 = l + j * a_dim1;
a[i__3].r = 0.f, a[i__3].i = 0.f;
/* L10: */
}
i__2 = *m - *n + j + j * a_dim1;
a[i__2].r = 1.f, a[i__2].i = 0.f;
/* L20: */
}
i__1 = *k;
for (i__ = 1; i__ <= i__1; ++i__) {
ii = *n - *k + i__;
/* Apply H(i) to A(1:m-k+i,1:n-k+i) from the left */
i__2 = *m - *n + ii + ii * a_dim1;
a[i__2].r = 1.f, a[i__2].i = 0.f;
i__2 = *m - *n + ii;
i__3 = ii - 1;
clarf_("Left", &i__2, &i__3, &a[ii * a_dim1 + 1], &c__1, &tau[i__], &
a[a_offset], lda, &work[1]);
i__2 = *m - *n + ii - 1;
i__3 = i__;
q__1.r = -tau[i__3].r, q__1.i = -tau[i__3].i;
cscal_(&i__2, &q__1, &a[ii * a_dim1 + 1], &c__1);
i__2 = *m - *n + ii + ii * a_dim1;
i__3 = i__;
q__1.r = 1.f - tau[i__3].r, q__1.i = 0.f - tau[i__3].i;
a[i__2].r = q__1.r, a[i__2].i = q__1.i;
/* Set A(m-k+i+1:m,n-k+i) to zero */
i__2 = *m;
for (l = *m - *n + ii + 1; l <= i__2; ++l) {
i__3 = l + ii * a_dim1;
a[i__3].r = 0.f, a[i__3].i = 0.f;
/* L30: */
}
/* L40: */
}
return 0;
/* End of CUNG2L */
} /* cung2l_ */
| bsd-3-clause |
gnu3ra/SCC15HPCRepast | INSTALLATION/hdf5-1.8.13/src/H5Tnative.c | 26 | 40783 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Module Info: This module contains the functionality for querying
* a "native" datatype for the H5T interface.
*/
#define H5T_PACKAGE /*suppress error about including H5Tpkg */
/* Interface initialization */
#define H5_INTERFACE_INIT_FUNC H5T_init_native_interface
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5Iprivate.h" /* IDs */
#include "H5Pprivate.h" /* Property lists */
#include "H5MMprivate.h" /* Memory management */
#include "H5Tpkg.h" /* Datatypes */
/* Static local functions */
static H5T_t *H5T_get_native_type(H5T_t *dt, H5T_direction_t direction,
size_t *struct_align, size_t *offset, size_t *comp_size);
static H5T_t *H5T_get_native_integer(size_t prec, H5T_sign_t sign, H5T_direction_t direction,
size_t *struct_align, size_t *offset, size_t *comp_size);
static H5T_t *H5T_get_native_float(size_t size, H5T_direction_t direction,
size_t *struct_align, size_t *offset, size_t *comp_size);
static H5T_t* H5T_get_native_bitfield(size_t prec, H5T_direction_t direction,
size_t *struct_align, size_t *offset, size_t *comp_size);
static herr_t H5T_cmp_offset(size_t *comp_size, size_t *offset, size_t elem_size,
size_t nelems, size_t align, size_t *struct_align);
/*--------------------------------------------------------------------------
NAME
H5T_init_native_interface -- Initialize interface-specific information
USAGE
herr_t H5T_init_native_interface()
RETURNS
Non-negative on success/Negative on failure
DESCRIPTION
Initializes any interface-specific data or routines. (Just calls
H5T_init_iterface currently).
--------------------------------------------------------------------------*/
static herr_t
H5T_init_native_interface(void)
{
FUNC_ENTER_NOAPI_NOINIT_NOERR
FUNC_LEAVE_NOAPI(H5T_init())
} /* H5T_init_native_interface() */
/*-------------------------------------------------------------------------
* Function: H5Tget_native_type
*
* Purpose: High-level API to return the native type of a datatype.
* The native type is chosen by matching the size and class of
* querried datatype from the following native premitive
* datatypes:
* H5T_NATIVE_CHAR H5T_NATIVE_UCHAR
* H5T_NATIVE_SHORT H5T_NATIVE_USHORT
* H5T_NATIVE_INT H5T_NATIVE_UINT
* H5T_NATIVE_LONG H5T_NATIVE_ULONG
* H5T_NATIVE_LLONG H5T_NATIVE_ULLONG
*
* H5T_NATIVE_FLOAT
* H5T_NATIVE_DOUBLE
* H5T_NATIVE_LDOUBLE
*
* Compound, array, enum, and VL types all choose among these
* types for theire members. Time, Bifield, Opaque, Reference
* types are only copy out.
*
* Return: Success: Returns the native data type if successful.
*
* Failure: negative
*
* Programmer: Raymond Lu
* Oct 3, 2002
*
*-------------------------------------------------------------------------
*/
hid_t
H5Tget_native_type(hid_t type_id, H5T_direction_t direction)
{
H5T_t *dt; /* Datatype to create native datatype from */
H5T_t *new_dt=NULL; /* Datatype for native datatype created */
size_t comp_size=0; /* Compound datatype's size */
hid_t ret_value; /* Return value */
FUNC_ENTER_API(FAIL)
H5TRACE2("i", "iTd", type_id, direction);
/* check argument */
if(NULL==(dt=(H5T_t *)H5I_object_verify(type_id, H5I_DATATYPE)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a data type")
if(direction!=H5T_DIR_DEFAULT && direction!=H5T_DIR_ASCEND
&& direction!=H5T_DIR_DESCEND)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not valid direction value")
if((new_dt = H5T_get_native_type(dt, direction, NULL, NULL, &comp_size))==NULL)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "cannot retrieve native type")
if((ret_value=H5I_register(H5I_DATATYPE, new_dt, TRUE)) < 0)
HGOTO_ERROR(H5E_DATATYPE, H5E_CANTREGISTER, FAIL, "unable to register data type")
done:
/* Error cleanup */
if(ret_value<0) {
if(new_dt)
if(H5T_close(new_dt)<0)
HDONE_ERROR(H5E_DATATYPE, H5E_CLOSEERROR, FAIL, "unable to release datatype")
} /* end if */
FUNC_LEAVE_API(ret_value)
}
/*-------------------------------------------------------------------------
* Function: H5T_get_native_type
*
* Purpose: Returns the native type of a datatype.
*
* Return: Success: Returns the native data type if successful.
*
* Failure: negative
*
* Programmer: Raymond Lu
* Oct 3, 2002
*
*-------------------------------------------------------------------------
*/
static H5T_t *
H5T_get_native_type(H5T_t *dtype, H5T_direction_t direction, size_t *struct_align, size_t *offset, size_t *comp_size)
{
H5T_t *dt; /* Datatype to make native */
H5T_t *super_type; /* Super type of VL, array and enum datatypes */
H5T_t *nat_super_type; /* Native form of VL, array & enum super datatype */
H5T_t *new_type = NULL; /* New native datatype */
H5T_t *memb_type = NULL; /* Datatype of member */
H5T_t **memb_list = NULL; /* List of compound member IDs */
size_t *memb_offset = NULL; /* List of member offsets in compound type, including member size and alignment */
char **comp_mname = NULL; /* List of member names in compound type */
char *memb_name = NULL; /* Enum's member name */
void *memb_value = NULL; /* Enum's member value */
void *tmp_memb_value = NULL; /* Enum's member value */
hsize_t *dims = NULL; /* Dimension sizes for array */
H5T_class_t h5_class; /* Class of datatype to make native */
size_t size; /* Size of datatype to make native */
size_t prec; /* Precision of datatype to make native */
int snmemb; /* Number of members in compound & enum types */
unsigned nmemb = 0; /* Number of members in compound & enum types */
unsigned u; /* Local index variable */
H5T_t *ret_value; /* Return value */
FUNC_ENTER_NOAPI(NULL)
HDassert(dtype);
if(H5T_NO_CLASS == (h5_class = H5T_get_class(dtype, FALSE)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a valid class")
if(0 == (size = H5T_get_size(dtype)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a valid size")
switch(h5_class) {
case H5T_INTEGER:
{
H5T_sign_t sign; /* Signedness of integer type */
if(H5T_SGN_ERROR == (sign = H5T_get_sign(dtype)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a valid signess")
prec = dtype->shared->u.atomic.prec;
if(NULL == (ret_value = H5T_get_native_integer(prec, sign, direction, struct_align, offset, comp_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve integer type")
} /* end case */
break;
case H5T_FLOAT:
if(NULL == (ret_value = H5T_get_native_float(size, direction, struct_align, offset, comp_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve float type")
break;
case H5T_STRING:
if(NULL == (ret_value = H5T_copy(dtype, H5T_COPY_TRANSIENT)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve float type")
if(H5T_IS_VL_STRING(dtype->shared)) {
/* Update size, offset and compound alignment for parent. */
if(H5T_cmp_offset(comp_size, offset, sizeof(char *), (size_t)1, H5T_POINTER_COMP_ALIGN_g, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
} /* end if */
else {
/* Update size, offset and compound alignment for parent. */
if(H5T_cmp_offset(comp_size, offset, sizeof(char), size, H5T_NATIVE_SCHAR_COMP_ALIGN_g, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
} /* end else */
break;
/* The time type will be supported in the future. Simply return "not supported"
* message for now.*/
case H5T_TIME:
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "time type is not supported yet")
case H5T_BITFIELD:
{
prec = dtype->shared->u.atomic.prec;
if(NULL == (ret_value = H5T_get_native_bitfield(prec, direction, struct_align, offset, comp_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve integer for bitfield type")
} /* end case */
break;
case H5T_OPAQUE:
if(NULL == (ret_value = H5T_copy(dtype, H5T_COPY_TRANSIENT)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve float type")
/* Update size, offset and compound alignment for parent. */
if(H5T_cmp_offset(comp_size, offset, sizeof(char), size, H5T_NATIVE_SCHAR_COMP_ALIGN_g, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
break;
case H5T_REFERENCE:
{
size_t align;
size_t ref_size;
int not_equal;
if(NULL == (ret_value = H5T_copy(dtype, H5T_COPY_TRANSIENT)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve float type")
/* Decide if the data type is object or dataset region reference. */
if(NULL == (dt = (H5T_t *)H5I_object(H5T_STD_REF_OBJ_g)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a data type")
not_equal = H5T_cmp(ret_value, dt, FALSE);
/* Update size, offset and compound alignment for parent. */
if(!not_equal) {
align = H5T_HOBJREF_COMP_ALIGN_g;
ref_size = sizeof(hobj_ref_t);
} /* end if */
else {
align = H5T_HDSETREGREF_COMP_ALIGN_g;
ref_size = sizeof(hdset_reg_ref_t);
} /* end else */
if(H5T_cmp_offset(comp_size, offset, ref_size, (size_t)1, align, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
} /* end case */
break;
case H5T_COMPOUND:
{
size_t children_size = 0;/* Total size of compound members */
size_t children_st_align = 0; /* The max alignment among compound members. This'll be the compound alignment */
if((snmemb = H5T_get_nmembers(dtype)) <= 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "compound data type doesn't have any member")
H5_ASSIGN_OVERFLOW(nmemb, snmemb, int, unsigned);
if(NULL == (memb_list = (H5T_t **)H5MM_calloc(nmemb * sizeof(H5T_t *))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
if(NULL == (memb_offset = (size_t *)H5MM_calloc(nmemb * sizeof(size_t))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
if(NULL == (comp_mname = (char **)H5MM_calloc(nmemb * sizeof(char *))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
/* Construct child compound type and retrieve a list of their IDs, offsets, total size, and alignment for compound type. */
for(u = 0; u < nmemb; u++) {
if(NULL == (memb_type = H5T_get_member_type(dtype, u, H5T_COPY_TRANSIENT)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "member type retrieval failed")
if(NULL == (comp_mname[u] = H5T__get_member_name(dtype, u)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "member type retrieval failed")
if(NULL == (memb_list[u] = H5T_get_native_type(memb_type, direction, &children_st_align, &(memb_offset[u]), &children_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "member identifier retrieval failed")
if(H5T_close(memb_type) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot close datatype")
} /* end for */
/* The alignment for whole compound type */
if(children_st_align && children_size % children_st_align)
children_size += children_st_align - (children_size % children_st_align);
/* Construct new compound type based on native type */
if(NULL == (new_type = H5T__create(H5T_COMPOUND, children_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot create a compound type")
/* Insert members for the new compound type */
for(u = 0; u < nmemb; u++)
if(H5T__insert(new_type, comp_mname[u], memb_offset[u], memb_list[u]) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot insert member to compound datatype")
/* Update size, offset and compound alignment for parent in the case of
* nested compound type. The alignment for a compound type as one field in
* a compound type is the biggest compound alignment among all its members.
* e.g. in the structure
* typedef struct s1 {
* char c;
* int i;
* s2 st;
* unsigned long long l;
* } s1;
* typedef struct s2 {
* short c2;
* long l2;
* long long ll2;
* } s2;
* The alignment for ST in S1 is the biggest structure alignment of all the
* members of S2, which is probably the LL2 of 'long long'. -SLU 2010/4/28
*/
if(H5T_cmp_offset(comp_size, offset, children_size, (size_t)1, children_st_align,
struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
/* Close member data type */
for(u = 0; u < nmemb; u++) {
if(H5T_close(memb_list[u]) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot close datatype")
/* Free member names in list */
comp_mname[u] = (char *)H5MM_xfree(comp_mname[u]);
} /* end for */
/* Free lists for members */
memb_list = (H5T_t **)H5MM_xfree(memb_list);
memb_offset = (size_t *)H5MM_xfree(memb_offset);
comp_mname = (char **)H5MM_xfree(comp_mname);
ret_value = new_type;
} /* end case */
break;
case H5T_ENUM:
{
H5T_path_t *tpath; /* Type conversion info */
hid_t super_type_id, nat_super_type_id;
/* Don't need to do anything special for alignment, offset since the ENUM type usually is integer. */
/* Retrieve base type for enumerated type */
if(NULL == (super_type = H5T_get_super(dtype)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to get base type for enumerate type")
if(NULL == (nat_super_type = H5T_get_native_type(super_type, direction, struct_align, offset, comp_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "base native type retrieval failed")
if((super_type_id = H5I_register(H5I_DATATYPE, super_type, FALSE)) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot register datatype")
if((nat_super_type_id = H5I_register(H5I_DATATYPE, nat_super_type, FALSE)) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot register datatype")
/* Allocate room for the enum values */
if(NULL == (tmp_memb_value = H5MM_calloc(H5T_get_size(super_type))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
if(NULL == (memb_value = H5MM_calloc(H5T_get_size(nat_super_type))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
/* Construct new enum type based on native type */
if(NULL == (new_type = H5T__enum_create(nat_super_type)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to create enum type")
/* Find the conversion function */
if(NULL == (tpath = H5T_path_find(super_type, nat_super_type, NULL, NULL, H5P_DEFAULT, FALSE)))
HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to convert between src and dst data types")
/* Retrieve member info and insert members into new enum type */
if((snmemb = H5T_get_nmembers(dtype)) <= 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "enumerate data type doesn't have any member")
H5_ASSIGN_OVERFLOW(nmemb, snmemb, int, unsigned);
for(u = 0; u < nmemb; u++) {
if(NULL == (memb_name = H5T__get_member_name(dtype, u)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot get member name")
if(H5T__get_member_value(dtype, u, tmp_memb_value) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot get member value")
HDmemcpy(memb_value, tmp_memb_value, H5T_get_size(super_type));
if(H5T_convert(tpath, super_type_id, nat_super_type_id, (size_t)1, (size_t)0, (size_t)0, memb_value, NULL, H5P_DEFAULT) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot get member value")
if(H5T__enum_insert(new_type, memb_name, memb_value) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot insert member")
memb_name = (char *)H5MM_xfree(memb_name);
}
memb_value = H5MM_xfree(memb_value);
tmp_memb_value = H5MM_xfree(tmp_memb_value);
/* Close base type */
if(H5I_dec_app_ref(nat_super_type_id) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot close datatype")
/* Close super type */
if(H5I_dec_app_ref(super_type_id) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot close datatype")
ret_value = new_type;
} /* end case */
break;
case H5T_ARRAY:
{
int sarray_rank; /* Array's rank */
unsigned array_rank; /* Array's rank */
hsize_t nelems = 1;
size_t super_offset = 0;
size_t super_size = 0;
size_t super_align = 0;
/* Retrieve dimension information for array data type */
if((sarray_rank = H5T__get_array_ndims(dtype)) <= 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot get dimension rank")
H5_ASSIGN_OVERFLOW(array_rank, sarray_rank, int, unsigned);
if(NULL == (dims = (hsize_t*)H5MM_malloc(array_rank * sizeof(hsize_t))))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot allocate memory")
if(H5T__get_array_dims(dtype, dims) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot get dimension size")
/* Retrieve base type for array type */
if(NULL == (super_type = H5T_get_super(dtype)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to get parent type for array type")
if(NULL == (nat_super_type = H5T_get_native_type(super_type, direction, &super_align,
&super_offset, &super_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "parent native type retrieval failed")
/* Close super type */
if(H5T_close(super_type) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_CLOSEERROR, NULL, "cannot close datatype")
/* Create a new array type based on native type */
if(NULL == (new_type = H5T__array_create(nat_super_type, array_rank, dims)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to create array type")
/* Close base type */
if(H5T_close(nat_super_type) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_CLOSEERROR, NULL, "cannot close datatype")
for(u = 0; u < array_rank; u++)
nelems *= dims[u];
H5_CHECK_OVERFLOW(nelems, hsize_t, size_t);
if(H5T_cmp_offset(comp_size, offset, super_size, (size_t)nelems, super_align, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
dims = (hsize_t *)H5MM_xfree(dims);
ret_value = new_type;
} /* end case */
break;
case H5T_VLEN:
{
size_t vl_align = 0;
size_t vl_size = 0;
size_t super_size = 0;
/* Retrieve base type for array type */
if(NULL == (super_type = H5T_get_super(dtype)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to get parent type for VL type")
/* Don't need alignment, offset information if this VL isn't a field of compound type. If it
* is, go to a few steps below to compute the information directly. */
if(NULL == (nat_super_type = H5T_get_native_type(super_type, direction, NULL, NULL, &super_size)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "parent native type retrieval failed")
/* Close super type */
if(H5T_close(super_type) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_CLOSEERROR, NULL, "cannot close datatype")
/* Create a new array type based on native type */
if(NULL == (new_type = H5T__vlen_create(nat_super_type)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "unable to create VL type")
/* Close base type */
if(H5T_close(nat_super_type) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_CLOSEERROR, NULL, "cannot close datatype")
/* Update size, offset and compound alignment for parent compound type directly. */
vl_align = H5T_HVL_COMP_ALIGN_g;
vl_size = sizeof(hvl_t);
if(H5T_cmp_offset(comp_size, offset, vl_size, (size_t)1, vl_align, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
ret_value = new_type;
} /* end case */
break;
case H5T_NO_CLASS:
case H5T_NCLASSES:
default:
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "data type doesn't match any native type")
} /* end switch */
done:
/* Error cleanup */
if(NULL == ret_value) {
if(new_type)
if(H5T_close(new_type) < 0)
HDONE_ERROR(H5E_DATATYPE, H5E_CLOSEERROR, NULL, "unable to release datatype")
/* Free lists for members */
if(memb_list) {
for(u = 0; u < nmemb; u++)
if(memb_list[u] && H5T_close(memb_list[u]) < 0)
HDONE_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot close datatype")
memb_list = (H5T_t **)H5MM_xfree(memb_list);
} /* end if */
memb_offset = (size_t *)H5MM_xfree(memb_offset);
if(comp_mname) {
for(u = 0; u < nmemb; u++)
if(comp_mname[u])
H5MM_xfree(comp_mname[u]);
comp_mname = (char **)H5MM_xfree(comp_mname);
} /* end if */
memb_name = (char *)H5MM_xfree(memb_name);
memb_value = H5MM_xfree(memb_value);
tmp_memb_value = H5MM_xfree(tmp_memb_value);
dims = (hsize_t *)H5MM_xfree(dims);
} /* end if */
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5T_get_native_type() */
/*-------------------------------------------------------------------------
* Function: H5T_get_native_integer
*
* Purpose: Returns the native integer type of a datatype.
*
* Return: Success: Returns the native data type if successful.
*
* Failure: negative
*
* Programmer: Raymond Lu
* Oct 3, 2002
*
*-------------------------------------------------------------------------
*/
static H5T_t *
H5T_get_native_integer(size_t prec, H5T_sign_t sign, H5T_direction_t direction,
size_t *struct_align, size_t *offset, size_t *comp_size)
{
H5T_t *dt; /* Appropriate native datatype to copy */
hid_t tid = (-1); /* Datatype ID of appropriate native datatype */
size_t align = 0; /* Alignment necessary for native datatype */
size_t native_size = 0; /* Datatype size of the native type */
enum match_type { /* The different kinds of integers we can match */
H5T_NATIVE_INT_MATCH_CHAR,
H5T_NATIVE_INT_MATCH_SHORT,
H5T_NATIVE_INT_MATCH_INT,
H5T_NATIVE_INT_MATCH_LONG,
H5T_NATIVE_INT_MATCH_LLONG,
H5T_NATIVE_INT_MATCH_UNKNOWN
} match = H5T_NATIVE_INT_MATCH_UNKNOWN;
H5T_t *ret_value; /* Return value */
FUNC_ENTER_NOAPI(NULL)
if(direction == H5T_DIR_DEFAULT || direction == H5T_DIR_ASCEND) {
if(prec <= H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_SCHAR_g))) {
match = H5T_NATIVE_INT_MATCH_CHAR;
native_size = sizeof(char);
} else if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_SHORT_g))) {
match = H5T_NATIVE_INT_MATCH_SHORT;
native_size = sizeof(short);
} else if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_INT_g))) {
match = H5T_NATIVE_INT_MATCH_INT;
native_size = sizeof(int);
} else if(prec <= H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_LONG_g))) {
match = H5T_NATIVE_INT_MATCH_LONG;
native_size = sizeof(long);
} else if(prec <= H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_LLONG_g))) {
match = H5T_NATIVE_INT_MATCH_LLONG;
native_size = sizeof(long long);
} else { /* If no native type matches the querried datatype, simply choose the type of biggest size. */
match = H5T_NATIVE_INT_MATCH_LLONG;
native_size = sizeof(long long);
}
} else if(direction == H5T_DIR_DESCEND) {
if(prec > H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_LONG_g))) {
match = H5T_NATIVE_INT_MATCH_LLONG;
native_size = sizeof(long long);
} else if(prec > H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_INT_g))) {
match = H5T_NATIVE_INT_MATCH_LONG;
native_size = sizeof(long);
} else if(prec > H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_SHORT_g))) {
match = H5T_NATIVE_INT_MATCH_INT;
native_size = sizeof(int);
} else if(prec > H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_SCHAR_g))) {
match = H5T_NATIVE_INT_MATCH_SHORT;
native_size = sizeof(short);
} else {
match = H5T_NATIVE_INT_MATCH_CHAR;
native_size = sizeof(char);
}
}
/* Set the appropriate native datatype information */
switch(match) {
case H5T_NATIVE_INT_MATCH_CHAR:
if(sign == H5T_SGN_2)
tid = H5T_NATIVE_SCHAR;
else
tid = H5T_NATIVE_UCHAR;
align = H5T_NATIVE_SCHAR_COMP_ALIGN_g;
break;
case H5T_NATIVE_INT_MATCH_SHORT:
if(sign == H5T_SGN_2)
tid = H5T_NATIVE_SHORT;
else
tid = H5T_NATIVE_USHORT;
align = H5T_NATIVE_SHORT_COMP_ALIGN_g;
break;
case H5T_NATIVE_INT_MATCH_INT:
if(sign == H5T_SGN_2)
tid = H5T_NATIVE_INT;
else
tid = H5T_NATIVE_UINT;
align = H5T_NATIVE_INT_COMP_ALIGN_g;
break;
case H5T_NATIVE_INT_MATCH_LONG:
if(sign == H5T_SGN_2)
tid = H5T_NATIVE_LONG;
else
tid = H5T_NATIVE_ULONG;
align = H5T_NATIVE_LONG_COMP_ALIGN_g;
break;
case H5T_NATIVE_INT_MATCH_LLONG:
if(sign == H5T_SGN_2)
tid = H5T_NATIVE_LLONG;
else
tid = H5T_NATIVE_ULLONG;
align = H5T_NATIVE_LLONG_COMP_ALIGN_g;
break;
case H5T_NATIVE_INT_MATCH_UNKNOWN:
default:
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "Unknown native integer match")
} /* end switch */
/* Create new native type */
HDassert(tid >= 0);
if(NULL == (dt = (H5T_t *)H5I_object(tid)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a data type")
if(NULL == (ret_value = H5T_copy(dt, H5T_COPY_TRANSIENT)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot copy type")
/* compute size and offset of compound type member. */
if(H5T_cmp_offset(comp_size, offset, native_size, (size_t)1, align, struct_align) < 0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5T_get_native_integer() */
/*-------------------------------------------------------------------------
* Function: H5T_get_native_float
*
* Purpose: Returns the native floatt type of a datatype.
*
* Return: Success: Returns the native data type if successful.
*
* Failure: negative
*
* Programmer: Raymond Lu
* Oct 3, 2002
*
*-------------------------------------------------------------------------
*/
static H5T_t*
H5T_get_native_float(size_t size, H5T_direction_t direction, size_t *struct_align, size_t *offset, size_t *comp_size)
{
H5T_t *dt=NULL; /* Appropriate native datatype to copy */
hid_t tid=(-1); /* Datatype ID of appropriate native datatype */
size_t align=0; /* Alignment necessary for native datatype */
size_t native_size=0; /* Datatype size of the native type */
enum match_type { /* The different kinds of floating point types we can match */
H5T_NATIVE_FLOAT_MATCH_FLOAT,
H5T_NATIVE_FLOAT_MATCH_DOUBLE,
#if H5_SIZEOF_LONG_DOUBLE !=0
H5T_NATIVE_FLOAT_MATCH_LDOUBLE,
#endif
H5T_NATIVE_FLOAT_MATCH_UNKNOWN
} match=H5T_NATIVE_FLOAT_MATCH_UNKNOWN;
H5T_t *ret_value; /* Return value */
FUNC_ENTER_NOAPI(NULL)
HDassert(size>0);
if(direction == H5T_DIR_DEFAULT || direction == H5T_DIR_ASCEND) {
if(size<=sizeof(float)) {
match=H5T_NATIVE_FLOAT_MATCH_FLOAT;
native_size = sizeof(float);
}
else if(size<=sizeof(double)) {
match=H5T_NATIVE_FLOAT_MATCH_DOUBLE;
native_size = sizeof(double);
}
#if H5_SIZEOF_LONG_DOUBLE !=0
else if(size<=sizeof(long double)) {
match=H5T_NATIVE_FLOAT_MATCH_LDOUBLE;
native_size = sizeof(long double);
}
#endif
else { /* If not match, return the biggest datatype */
#if H5_SIZEOF_LONG_DOUBLE !=0
match=H5T_NATIVE_FLOAT_MATCH_LDOUBLE;
native_size = sizeof(long double);
#else
match=H5T_NATIVE_FLOAT_MATCH_DOUBLE;
native_size = sizeof(double);
#endif
}
} else {
#if H5_SIZEOF_LONG_DOUBLE !=0
if(size>sizeof(double)) {
match=H5T_NATIVE_FLOAT_MATCH_LDOUBLE;
native_size = sizeof(long double);
}
else if(size>sizeof(float)) {
match=H5T_NATIVE_FLOAT_MATCH_DOUBLE;
native_size = sizeof(double);
}
else {
match=H5T_NATIVE_FLOAT_MATCH_FLOAT;
native_size = sizeof(float);
}
#else
if(size>sizeof(float)) {
match=H5T_NATIVE_FLOAT_MATCH_DOUBLE;
native_size = sizeof(double);
}
else {
match=H5T_NATIVE_FLOAT_MATCH_FLOAT;
native_size = sizeof(float);
}
#endif
}
/* Set the appropriate native floating point information */
switch(match) {
case H5T_NATIVE_FLOAT_MATCH_FLOAT:
tid = H5T_NATIVE_FLOAT;
align = H5T_NATIVE_FLOAT_COMP_ALIGN_g;
break;
case H5T_NATIVE_FLOAT_MATCH_DOUBLE:
tid = H5T_NATIVE_DOUBLE;
align = H5T_NATIVE_DOUBLE_COMP_ALIGN_g;
break;
#if H5_SIZEOF_LONG_DOUBLE !=0
case H5T_NATIVE_FLOAT_MATCH_LDOUBLE:
tid = H5T_NATIVE_LDOUBLE;
align = H5T_NATIVE_LDOUBLE_COMP_ALIGN_g;
break;
#endif
case H5T_NATIVE_FLOAT_MATCH_UNKNOWN:
default:
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "Unknown native floating-point match")
} /* end switch */
/* Create new native type */
HDassert(tid>=0);
if(NULL==(dt=(H5T_t *)H5I_object(tid)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a data type")
if((ret_value=H5T_copy(dt, H5T_COPY_TRANSIENT))==NULL)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot retrieve float type")
/* compute offset of compound type member. */
if(H5T_cmp_offset(comp_size, offset, native_size, (size_t)1, align, struct_align)<0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
done:
FUNC_LEAVE_NOAPI(ret_value)
}
/*-------------------------------------------------------------------------
* Function: H5T_get_native_bitfield
*
* Purpose: Returns the native bitfield type of a datatype. Bitfield
* is similar to unsigned integer.
*
* Return: Success: Returns the native data type if successful.
*
* Failure: negative
*
* Programmer: Raymond Lu
* 1 December 2009
*
*-------------------------------------------------------------------------
*/
static H5T_t*
H5T_get_native_bitfield(size_t prec, H5T_direction_t direction, size_t *struct_align,
size_t *offset, size_t *comp_size)
{
H5T_t *dt; /* Appropriate native datatype to copy */
hid_t tid=(-1); /* Datatype ID of appropriate native datatype */
size_t align=0; /* Alignment necessary for native datatype */
size_t native_size=0; /* Datatype size of the native type */
H5T_t *ret_value; /* Return value */
FUNC_ENTER_NOAPI(NULL)
if(direction == H5T_DIR_DEFAULT || direction == H5T_DIR_ASCEND) {
if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B8_g))) {
tid = H5T_NATIVE_B8;
native_size = 1;
align = H5T_NATIVE_UINT8_ALIGN_g;
} else if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B16_g))) {
tid = H5T_NATIVE_B16;
native_size = 2;
align = H5T_NATIVE_UINT16_ALIGN_g;
} else if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B32_g))) {
tid = H5T_NATIVE_B32;
native_size = 4;
align = H5T_NATIVE_UINT32_ALIGN_g;
} else if(prec<=H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B64_g))) {
tid = H5T_NATIVE_B64;
native_size = 8;
align = H5T_NATIVE_UINT64_ALIGN_g;
} else { /* If no native type matches the querried datatype, simply choose the type of biggest size. */
tid = H5T_NATIVE_B64;
native_size = 8;
align = H5T_NATIVE_UINT64_ALIGN_g;
}
} else if(direction == H5T_DIR_DESCEND) {
if(prec>H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B32_g))) {
tid = H5T_NATIVE_B64;
native_size = 8;
align = H5T_NATIVE_UINT64_ALIGN_g;
} else if(prec>H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B16_g))) {
tid = H5T_NATIVE_B32;
native_size = 4;
align = H5T_NATIVE_UINT32_ALIGN_g;
} else if(prec>H5T_get_precision((H5T_t *)H5I_object(H5T_NATIVE_B8_g))) {
tid = H5T_NATIVE_B16;
native_size = 2;
align = H5T_NATIVE_UINT16_ALIGN_g;
} else {
tid = H5T_NATIVE_B8;
native_size = 1;
align = H5T_NATIVE_UINT8_ALIGN_g;
}
}
/* Create new native type */
HDassert(tid>=0);
if(NULL==(dt=(H5T_t *)H5I_object(tid)))
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "not a data type")
if((ret_value=H5T_copy(dt, H5T_COPY_TRANSIENT))==NULL)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot copy type")
/* compute size and offset of compound type member. */
if(H5T_cmp_offset(comp_size, offset, native_size, (size_t)1, align, struct_align)<0)
HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, NULL, "cannot compute compound offset")
done:
FUNC_LEAVE_NOAPI(ret_value)
}
/*-------------------------------------------------------------------------
* Function: H5T_cmp_offset
*
* Purpose: This function is only for convenience. It computes the
* compound type size, offset of the member being considered
* and the alignment for the whole compound type.
*
* Return: Success: Non-negative value.
*
* Failure: Negative value.
*
* Programmer: Raymond Lu
* December 10, 2002
*
*-------------------------------------------------------------------------
*/
static herr_t
H5T_cmp_offset(size_t *comp_size, size_t *offset, size_t elem_size,
size_t nelems, size_t align, size_t *struct_align)
{
herr_t ret_value = SUCCEED;
FUNC_ENTER_NOAPI(FAIL)
if(offset && comp_size) {
if(align>1 && *comp_size%align) {
/* Add alignment value */
*offset = *comp_size + (align - *comp_size%align);
*comp_size += (align - *comp_size%align);
} else
*offset = *comp_size;
/* compute size of compound type member. */
*comp_size += nelems*elem_size;
}
if(struct_align && *struct_align < align)
*struct_align = align;
done:
FUNC_LEAVE_NOAPI(ret_value)
}
| bsd-3-clause |
johnmarinelli/nmatrix | ext/nmatrix_lapacke/lapacke/src/lapacke_zgesdd.c | 29 | 4492 | /*****************************************************************************
Copyright (c) 2011, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function zgesdd
* Author: Intel Corporation
* Generated November, 2011
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_zgesdd( int matrix_order, char jobz, lapack_int m,
lapack_int n, lapack_complex_double* a,
lapack_int lda, double* s, lapack_complex_double* u,
lapack_int ldu, lapack_complex_double* vt,
lapack_int ldvt )
{
lapack_int info = 0;
lapack_int lwork = -1;
/* Additional scalars declarations for work arrays */
size_t lrwork;
lapack_int* iwork = NULL;
double* rwork = NULL;
lapack_complex_double* work = NULL;
lapack_complex_double work_query;
if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_zgesdd", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_zge_nancheck( matrix_order, m, n, a, lda ) ) {
return -5;
}
#endif
/* Additional scalars initializations for work arrays */
if( LAPACKE_lsame( jobz, 'n' ) ) {
lrwork = MAX(1,5*MIN(m,n));
} else {
lrwork = (size_t)5*MAX(1,MIN(m,n))*MAX(1,MIN(m,n))+7*MIN(m,n);
}
/* Allocate memory for working array(s) */
iwork = (lapack_int*)
LAPACKE_malloc( sizeof(lapack_int) * MAX(1,8*MIN(m,n)) );
if( iwork == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
rwork = (double*)LAPACKE_malloc( sizeof(double) * lrwork );
if( rwork == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_1;
}
/* Query optimal working array(s) size */
info = LAPACKE_zgesdd_work( matrix_order, jobz, m, n, a, lda, s, u, ldu, vt,
ldvt, &work_query, lwork, rwork, iwork );
if( info != 0 ) {
goto exit_level_2;
}
lwork = LAPACK_Z2INT( work_query );
/* Allocate memory for work arrays */
work = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) * lwork );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_2;
}
/* Call middle-level interface */
info = LAPACKE_zgesdd_work( matrix_order, jobz, m, n, a, lda, s, u, ldu, vt,
ldvt, work, lwork, rwork, iwork );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_2:
LAPACKE_free( rwork );
exit_level_1:
LAPACKE_free( iwork );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_zgesdd", info );
}
return info;
}
| bsd-3-clause |
hunslater/pdfium | core/src/fxcodec/libjpeg/fpdfapi_jfdctfst.c | 31 | 7634 | #if !defined(_FX_JPEG_TURBO_)
/*
* jfdctfst.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a fast, not so accurate integer implementation of the
* forward DCT (Discrete Cosine Transform).
*
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
* on each column. Direct algorithms are also available, but they are
* much more complex and seem not to be any faster when reduced to code.
*
* This implementation is based on Arai, Agui, and Nakajima's algorithm for
* scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
* Japanese, but the algorithm is described in the Pennebaker & Mitchell
* JPEG textbook (see REFERENCES section in file README). The following code
* is based directly on figure 4-8 in P&M.
* While an 8-point DCT cannot be done in less than 11 multiplies, it is
* possible to arrange the computation so that many of the multiplies are
* simple scalings of the final outputs. These multiplies can then be
* folded into the multiplications or divisions by the JPEG quantization
* table entries. The AA&N method leaves only 5 multiplies and 29 adds
* to be done in the DCT itself.
* The primary disadvantage of this method is that with fixed-point math,
* accuracy is lost due to imprecise representation of the scaled
* quantization values. The smaller the quantization table entry, the less
* precise the scaled value, so this implementation does worse with high-
* quality-setting files than with low-quality ones.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdct.h" /* Private declarations for DCT subsystem */
#ifdef DCT_IFAST_SUPPORTED
/*
* This module is specialized to the case DCTSIZE = 8.
*/
#if DCTSIZE != 8
Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
#endif
/* Scaling decisions are generally the same as in the LL&M algorithm;
* see jfdctint.c for more details. However, we choose to descale
* (right shift) multiplication products as soon as they are formed,
* rather than carrying additional fractional bits into subsequent additions.
* This compromises accuracy slightly, but it lets us save a few shifts.
* More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
* everywhere except in the multiplications proper; this saves a good deal
* of work on 16-bit-int machines.
*
* Again to save a few shifts, the intermediate results between pass 1 and
* pass 2 are not upscaled, but are represented only to integral precision.
*
* A final compromise is to represent the multiplicative constants to only
* 8 fractional bits, rather than 13. This saves some shifting work on some
* machines, and may also reduce the cost of multiplication (since there
* are fewer one-bits in the constants).
*/
#define CONST_BITS 8
/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
* causing a lot of useless floating-point operations at run time.
* To get around this we use the following pre-calculated constants.
* If you change CONST_BITS you may want to add appropriate values.
* (With a reasonable C compiler, you can just rely on the FIX() macro...)
*/
#if CONST_BITS == 8
#define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
#define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
#define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
#define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
#else
#define FIX_0_382683433 FIX(0.382683433)
#define FIX_0_541196100 FIX(0.541196100)
#define FIX_0_707106781 FIX(0.707106781)
#define FIX_1_306562965 FIX(1.306562965)
#endif
/* We can gain a little more speed, with a further compromise in accuracy,
* by omitting the addition in a descaling shift. This yields an incorrectly
* rounded result half the time...
*/
#ifndef USE_ACCURATE_ROUNDING
#undef DESCALE
#define DESCALE(x,n) RIGHT_SHIFT(x, n)
#endif
/* Multiply a DCTELEM variable by an INT32 constant, and immediately
* descale to yield a DCTELEM result.
*/
#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
/*
* Perform the forward DCT on one block of samples.
*/
GLOBAL(void)
jpeg_fdct_ifast (DCTELEM * data)
{
DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
DCTELEM tmp10, tmp11, tmp12, tmp13;
DCTELEM z1, z2, z3, z4, z5, z11, z13;
DCTELEM *dataptr;
int ctr;
SHIFT_TEMPS
/* Pass 1: process rows. */
dataptr = data;
for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
tmp0 = dataptr[0] + dataptr[7];
tmp7 = dataptr[0] - dataptr[7];
tmp1 = dataptr[1] + dataptr[6];
tmp6 = dataptr[1] - dataptr[6];
tmp2 = dataptr[2] + dataptr[5];
tmp5 = dataptr[2] - dataptr[5];
tmp3 = dataptr[3] + dataptr[4];
tmp4 = dataptr[3] - dataptr[4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
dataptr[0] = tmp10 + tmp11; /* phase 3 */
dataptr[4] = tmp10 - tmp11;
z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
dataptr[2] = tmp13 + z1; /* phase 5 */
dataptr[6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[5] = z13 + z2; /* phase 6 */
dataptr[3] = z13 - z2;
dataptr[1] = z11 + z4;
dataptr[7] = z11 - z4;
dataptr += DCTSIZE; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataptr = data;
for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
dataptr[DCTSIZE*4] = tmp10 - tmp11;
z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
dataptr[DCTSIZE*6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
dataptr[DCTSIZE*3] = z13 - z2;
dataptr[DCTSIZE*1] = z11 + z4;
dataptr[DCTSIZE*7] = z11 - z4;
dataptr++; /* advance pointer to next column */
}
}
#endif /* DCT_IFAST_SUPPORTED */
#endif //_FX_JPEG_TURBO_
| bsd-3-clause |
windyuuy/opera | chromium/src/third_party/mesa/src/src/gallium/auxiliary/draw/draw_pt_emit.c | 33 | 8606 | /**************************************************************************
*
* Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
* 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 TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#include "util/u_memory.h"
#include "draw/draw_context.h"
#include "draw/draw_private.h"
#include "draw/draw_vbuf.h"
#include "draw/draw_vertex.h"
#include "draw/draw_pt.h"
#include "translate/translate.h"
#include "translate/translate_cache.h"
struct pt_emit {
struct draw_context *draw;
struct translate *translate;
struct translate_cache *cache;
unsigned prim;
const struct vertex_info *vinfo;
};
void draw_pt_emit_prepare( struct pt_emit *emit,
unsigned prim,
unsigned *max_vertices )
{
struct draw_context *draw = emit->draw;
const struct vertex_info *vinfo;
unsigned dst_offset;
struct translate_key hw_key;
unsigned i;
boolean ok;
/* XXX: need to flush to get prim_vbuf.c to release its allocation??
*/
draw_do_flush( draw, DRAW_FLUSH_BACKEND );
/* XXX: may need to defensively reset this later on as clipping can
* clobber this state in the render backend.
*/
emit->prim = prim;
ok = draw->render->set_primitive(draw->render, emit->prim);
if (!ok) {
assert(0);
return;
}
/* Must do this after set_primitive() above:
*/
emit->vinfo = vinfo = draw->render->get_vertex_info(draw->render);
/* Translate from pipeline vertices to hw vertices.
*/
dst_offset = 0;
for (i = 0; i < vinfo->num_attribs; i++) {
unsigned emit_sz = 0;
unsigned src_buffer = 0;
unsigned output_format;
unsigned src_offset = (vinfo->attrib[i].src_index * 4 * sizeof(float) );
output_format = draw_translate_vinfo_format(vinfo->attrib[i].emit);
emit_sz = draw_translate_vinfo_size(vinfo->attrib[i].emit);
/* doesn't handle EMIT_OMIT */
assert(emit_sz != 0);
if (vinfo->attrib[i].emit == EMIT_1F_PSIZE) {
src_buffer = 1;
src_offset = 0;
}
hw_key.element[i].type = TRANSLATE_ELEMENT_NORMAL;
hw_key.element[i].input_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
hw_key.element[i].input_buffer = src_buffer;
hw_key.element[i].input_offset = src_offset;
hw_key.element[i].instance_divisor = 0;
hw_key.element[i].output_format = output_format;
hw_key.element[i].output_offset = dst_offset;
dst_offset += emit_sz;
}
hw_key.nr_elements = vinfo->num_attribs;
hw_key.output_stride = vinfo->size * 4;
if (!emit->translate ||
translate_key_compare(&emit->translate->key, &hw_key) != 0)
{
translate_key_sanitize(&hw_key);
emit->translate = translate_cache_find(emit->cache, &hw_key);
}
*max_vertices = (draw->render->max_vertex_buffer_bytes /
(vinfo->size * 4));
}
void draw_pt_emit( struct pt_emit *emit,
const struct draw_vertex_info *vert_info,
const struct draw_prim_info *prim_info)
{
const float (*vertex_data)[4] = (const float (*)[4])vert_info->verts->data;
unsigned vertex_count = vert_info->count;
unsigned stride = vert_info->stride;
const ushort *elts = prim_info->elts;
struct draw_context *draw = emit->draw;
struct translate *translate = emit->translate;
struct vbuf_render *render = draw->render;
unsigned start, i;
void *hw_verts;
/* XXX: need to flush to get prim_vbuf.c to release its allocation??
*/
draw_do_flush( draw, DRAW_FLUSH_BACKEND );
if (vertex_count == 0)
return;
/* XXX: and work out some way to coordinate the render primitive
* between vbuf.c and here...
*/
if (!draw->render->set_primitive(draw->render, emit->prim)) {
assert(0);
return;
}
render->allocate_vertices(render,
(ushort)translate->key.output_stride,
(ushort)vertex_count);
hw_verts = render->map_vertices( render );
if (!hw_verts) {
assert(0);
return;
}
translate->set_buffer(translate,
0,
vertex_data,
stride,
~0);
translate->set_buffer(translate,
1,
&draw->rasterizer->point_size,
0,
~0);
/* fetch/translate vertex attribs to fill hw_verts[] */
translate->run( translate,
0,
vertex_count,
draw->instance_id,
hw_verts );
render->unmap_vertices( render,
0,
vertex_count - 1 );
for (start = i = 0;
i < prim_info->primitive_count;
start += prim_info->primitive_lengths[i], i++)
{
render->draw_elements(render,
elts + start,
prim_info->primitive_lengths[i]);
}
render->release_vertices(render);
}
void draw_pt_emit_linear(struct pt_emit *emit,
const struct draw_vertex_info *vert_info,
const struct draw_prim_info *prim_info)
{
const float (*vertex_data)[4] = (const float (*)[4])vert_info->verts->data;
unsigned stride = vert_info->stride;
unsigned count = vert_info->count;
struct draw_context *draw = emit->draw;
struct translate *translate = emit->translate;
struct vbuf_render *render = draw->render;
void *hw_verts;
unsigned start, i;
#if 0
debug_printf("Linear emit\n");
#endif
/* XXX: need to flush to get prim_vbuf.c to release its allocation??
*/
draw_do_flush( draw, DRAW_FLUSH_BACKEND );
/* XXX: and work out some way to coordinate the render primitive
* between vbuf.c and here...
*/
if (!draw->render->set_primitive(draw->render, emit->prim))
goto fail;
if (!render->allocate_vertices(render,
(ushort)translate->key.output_stride,
(ushort)count))
goto fail;
hw_verts = render->map_vertices( render );
if (!hw_verts)
goto fail;
translate->set_buffer(translate, 0,
vertex_data, stride, count - 1);
translate->set_buffer(translate, 1,
&draw->rasterizer->point_size,
0, ~0);
translate->run(translate,
0,
count,
draw->instance_id,
hw_verts);
if (0) {
unsigned i;
for (i = 0; i < count; i++) {
debug_printf("\n\n%s vertex %d:\n", __FUNCTION__, i);
draw_dump_emitted_vertex( emit->vinfo,
(const uint8_t *)hw_verts +
translate->key.output_stride * i );
}
}
render->unmap_vertices( render, 0, count - 1 );
for (start = i = 0;
i < prim_info->primitive_count;
start += prim_info->primitive_lengths[i], i++)
{
render->draw_arrays(render,
start,
prim_info->primitive_lengths[i]);
}
render->release_vertices(render);
return;
fail:
assert(0);
return;
}
struct pt_emit *draw_pt_emit_create( struct draw_context *draw )
{
struct pt_emit *emit = CALLOC_STRUCT(pt_emit);
if (!emit)
return NULL;
emit->draw = draw;
emit->cache = translate_cache_create();
if (!emit->cache) {
FREE(emit);
return NULL;
}
return emit;
}
void draw_pt_emit_destroy( struct pt_emit *emit )
{
if (emit->cache)
translate_cache_destroy(emit->cache);
FREE(emit);
}
| bsd-3-clause |
zimbatm/deb-redis | src/adlist.c | 40 | 9528 | /* adlist.c - A generic doubly linked list implementation
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez 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.
*/
#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"
/* Create a new list. The created list can be freed with
* AlFreeList(), but private value of every node need to be freed
* by the user before to call AlFreeList().
*
* On error, NULL is returned. Otherwise the pointer to the new list. */
list *listCreate(void)
{
struct list *list;
if ((list = zmalloc(sizeof(*list))) == NULL)
return NULL;
list->head = list->tail = NULL;
list->len = 0;
list->dup = NULL;
list->free = NULL;
list->match = NULL;
return list;
}
/* Free the whole list.
*
* This function can't fail. */
void listRelease(list *list)
{
unsigned int len;
listNode *current, *next;
current = list->head;
len = list->len;
while(len--) {
next = current->next;
if (list->free) list->free(current->value);
zfree(current);
current = next;
}
zfree(list);
}
/* Add a new node to the list, to head, contaning the specified 'value'
* pointer as value.
*
* On error, NULL is returned and no operation is performed (i.e. the
* list remains unaltered).
* On success the 'list' pointer you pass to the function is returned. */
list *listAddNodeHead(list *list, void *value)
{
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (list->len == 0) {
list->head = list->tail = node;
node->prev = node->next = NULL;
} else {
node->prev = NULL;
node->next = list->head;
list->head->prev = node;
list->head = node;
}
list->len++;
return list;
}
/* Add a new node to the list, to tail, contaning the specified 'value'
* pointer as value.
*
* On error, NULL is returned and no operation is performed (i.e. the
* list remains unaltered).
* On success the 'list' pointer you pass to the function is returned. */
list *listAddNodeTail(list *list, void *value)
{
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (list->len == 0) {
list->head = list->tail = node;
node->prev = node->next = NULL;
} else {
node->prev = list->tail;
node->next = NULL;
list->tail->next = node;
list->tail = node;
}
list->len++;
return list;
}
list *listInsertNode(list *list, listNode *old_node, void *value, int after) {
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (after) {
node->prev = old_node;
node->next = old_node->next;
if (list->tail == old_node) {
list->tail = node;
}
} else {
node->next = old_node;
node->prev = old_node->prev;
if (list->head == old_node) {
list->head = node;
}
}
if (node->prev != NULL) {
node->prev->next = node;
}
if (node->next != NULL) {
node->next->prev = node;
}
list->len++;
return list;
}
/* Remove the specified node from the specified list.
* It's up to the caller to free the private value of the node.
*
* This function can't fail. */
void listDelNode(list *list, listNode *node)
{
if (node->prev)
node->prev->next = node->next;
else
list->head = node->next;
if (node->next)
node->next->prev = node->prev;
else
list->tail = node->prev;
if (list->free) list->free(node->value);
zfree(node);
list->len--;
}
/* Returns a list iterator 'iter'. After the initialization every
* call to listNext() will return the next element of the list.
*
* This function can't fail. */
listIter *listGetIterator(list *list, int direction)
{
listIter *iter;
if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;
if (direction == AL_START_HEAD)
iter->next = list->head;
else
iter->next = list->tail;
iter->direction = direction;
return iter;
}
/* Release the iterator memory */
void listReleaseIterator(listIter *iter) {
zfree(iter);
}
/* Create an iterator in the list private iterator structure */
void listRewind(list *list, listIter *li) {
li->next = list->head;
li->direction = AL_START_HEAD;
}
void listRewindTail(list *list, listIter *li) {
li->next = list->tail;
li->direction = AL_START_TAIL;
}
/* Return the next element of an iterator.
* It's valid to remove the currently returned element using
* listDelNode(), but not to remove other elements.
*
* The function returns a pointer to the next element of the list,
* or NULL if there are no more elements, so the classical usage patter
* is:
*
* iter = listGetIterator(list,<direction>);
* while ((node = listNext(iter)) != NULL) {
* doSomethingWith(listNodeValue(node));
* }
*
* */
listNode *listNext(listIter *iter)
{
listNode *current = iter->next;
if (current != NULL) {
if (iter->direction == AL_START_HEAD)
iter->next = current->next;
else
iter->next = current->prev;
}
return current;
}
/* Duplicate the whole list. On out of memory NULL is returned.
* On success a copy of the original list is returned.
*
* The 'Dup' method set with listSetDupMethod() function is used
* to copy the node value. Otherwise the same pointer value of
* the original node is used as value of the copied node.
*
* The original list both on success or error is never modified. */
list *listDup(list *orig)
{
list *copy;
listIter *iter;
listNode *node;
if ((copy = listCreate()) == NULL)
return NULL;
copy->dup = orig->dup;
copy->free = orig->free;
copy->match = orig->match;
iter = listGetIterator(orig, AL_START_HEAD);
while((node = listNext(iter)) != NULL) {
void *value;
if (copy->dup) {
value = copy->dup(node->value);
if (value == NULL) {
listRelease(copy);
listReleaseIterator(iter);
return NULL;
}
} else
value = node->value;
if (listAddNodeTail(copy, value) == NULL) {
listRelease(copy);
listReleaseIterator(iter);
return NULL;
}
}
listReleaseIterator(iter);
return copy;
}
/* Search the list for a node matching a given key.
* The match is performed using the 'match' method
* set with listSetMatchMethod(). If no 'match' method
* is set, the 'value' pointer of every node is directly
* compared with the 'key' pointer.
*
* On success the first matching node pointer is returned
* (search starts from head). If no matching node exists
* NULL is returned. */
listNode *listSearchKey(list *list, void *key)
{
listIter *iter;
listNode *node;
iter = listGetIterator(list, AL_START_HEAD);
while((node = listNext(iter)) != NULL) {
if (list->match) {
if (list->match(node->value, key)) {
listReleaseIterator(iter);
return node;
}
} else {
if (key == node->value) {
listReleaseIterator(iter);
return node;
}
}
}
listReleaseIterator(iter);
return NULL;
}
/* Return the element at the specified zero-based index
* where 0 is the head, 1 is the element next to head
* and so on. Negative integers are used in order to count
* from the tail, -1 is the last element, -2 the penultimante
* and so on. If the index is out of range NULL is returned. */
listNode *listIndex(list *list, int index) {
listNode *n;
if (index < 0) {
index = (-index)-1;
n = list->tail;
while(index-- && n) n = n->prev;
} else {
n = list->head;
while(index-- && n) n = n->next;
}
return n;
}
| bsd-3-clause |
Cue/skia | tests/RefCntTest.cpp | 40 | 4078 | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#include "Test.h"
#include "SkRefCnt.h"
#include "SkThreadUtils.h"
#include "SkWeakRefCnt.h"
#include "SkTRefArray.h"
///////////////////////////////////////////////////////////////////////////////
class InstCounterClass {
public:
InstCounterClass() { fCount = gInstCounter++; }
InstCounterClass(const InstCounterClass& src) {
fCount = src.fCount;
gInstCounter += 1;
}
virtual ~InstCounterClass() { gInstCounter -= 1; }
static int gInstCounter;
int fCount;
};
int InstCounterClass::gInstCounter;
static void test_refarray(skiatest::Reporter* reporter) {
REPORTER_ASSERT(reporter, 0 == InstCounterClass::gInstCounter);
const int N = 10;
SkTRefArray<InstCounterClass>* array = SkTRefArray<InstCounterClass>::Create(N);
REPORTER_ASSERT(reporter, 1 == array->getRefCnt());
REPORTER_ASSERT(reporter, N == array->count());
REPORTER_ASSERT(reporter, N == InstCounterClass::gInstCounter);
array->unref();
REPORTER_ASSERT(reporter, 0 == InstCounterClass::gInstCounter);
// Now test the copy factory
int i;
InstCounterClass* src = new InstCounterClass[N];
REPORTER_ASSERT(reporter, N == InstCounterClass::gInstCounter);
for (i = 0; i < N; ++i) {
REPORTER_ASSERT(reporter, i == src[i].fCount);
}
array = SkTRefArray<InstCounterClass>::Create(src, N);
REPORTER_ASSERT(reporter, 1 == array->getRefCnt());
REPORTER_ASSERT(reporter, N == array->count());
REPORTER_ASSERT(reporter, 2*N == InstCounterClass::gInstCounter);
for (i = 0; i < N; ++i) {
REPORTER_ASSERT(reporter, i == (*array)[i].fCount);
}
delete[] src;
REPORTER_ASSERT(reporter, N == InstCounterClass::gInstCounter);
for (i = 0; i < N; ++i) {
REPORTER_ASSERT(reporter, i == (*array)[i].fCount);
}
array->unref();
REPORTER_ASSERT(reporter, 0 == InstCounterClass::gInstCounter);
}
static void bounce_ref(void* data) {
SkRefCnt* ref = static_cast<SkRefCnt*>(data);
for (int i = 0; i < 100000; ++i) {
ref->ref();
ref->unref();
}
}
static void test_refCnt(skiatest::Reporter* reporter) {
SkRefCnt* ref = new SkRefCnt();
SkThread thing1(bounce_ref, ref);
SkThread thing2(bounce_ref, ref);
thing1.setProcessorAffinity(0);
thing2.setProcessorAffinity(23);
SkASSERT(thing1.start());
SkASSERT(thing2.start());
thing1.join();
thing2.join();
REPORTER_ASSERT(reporter, ref->getRefCnt() == 1);
ref->unref();
}
static void bounce_weak_ref(void* data) {
SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);
for (int i = 0; i < 100000; ++i) {
if (ref->try_ref()) {
ref->unref();
}
}
}
static void bounce_weak_weak_ref(void* data) {
SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);
for (int i = 0; i < 100000; ++i) {
ref->weak_ref();
ref->weak_unref();
}
}
static void test_weakRefCnt(skiatest::Reporter* reporter) {
SkWeakRefCnt* ref = new SkWeakRefCnt();
SkThread thing1(bounce_ref, ref);
SkThread thing2(bounce_ref, ref);
SkThread thing3(bounce_weak_ref, ref);
SkThread thing4(bounce_weak_weak_ref, ref);
thing1.setProcessorAffinity(0);
thing2.setProcessorAffinity(23);
thing3.setProcessorAffinity(2);
thing4.setProcessorAffinity(17);
SkASSERT(thing1.start());
SkASSERT(thing2.start());
SkASSERT(thing3.start());
SkASSERT(thing4.start());
thing1.join();
thing2.join();
thing3.join();
thing4.join();
REPORTER_ASSERT(reporter, ref->getRefCnt() == 1);
REPORTER_ASSERT(reporter, ref->getWeakCnt() == 1);
ref->unref();
}
static void test_refCntTests(skiatest::Reporter* reporter) {
test_refCnt(reporter);
test_weakRefCnt(reporter);
test_refarray(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("RefCnt", RefCntTestClass, test_refCntTests)
| bsd-3-clause |
hedisdb/hedis | deps/lua/src/lstate.c | 1327 | 5674 | /*
** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $
** Global State
** See Copyright Notice in lua.h
*/
#include <stddef.h>
#define lstate_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "llex.h"
#include "lmem.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#define state_size(x) (sizeof(x) + LUAI_EXTRASPACE)
#define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE)
#define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE))
/*
** Main thread combines a thread state and the global state
*/
typedef struct LG {
lua_State l;
global_State g;
} LG;
static void stack_init (lua_State *L1, lua_State *L) {
/* initialize CallInfo array */
L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo);
L1->ci = L1->base_ci;
L1->size_ci = BASIC_CI_SIZE;
L1->end_ci = L1->base_ci + L1->size_ci - 1;
/* initialize stack array */
L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue);
L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK;
L1->top = L1->stack;
L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1;
/* initialize first ci */
L1->ci->func = L1->top;
setnilvalue(L1->top++); /* `function' entry for this `ci' */
L1->base = L1->ci->base = L1->top;
L1->ci->top = L1->top + LUA_MINSTACK;
}
static void freestack (lua_State *L, lua_State *L1) {
luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo);
luaM_freearray(L, L1->stack, L1->stacksize, TValue);
}
/*
** open parts that may cause memory-allocation errors
*/
static void f_luaopen (lua_State *L, void *ud) {
global_State *g = G(L);
UNUSED(ud);
stack_init(L, L); /* init stack */
sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */
sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */
luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
luaT_init(L);
luaX_init(L);
luaS_fix(luaS_newliteral(L, MEMERRMSG));
g->GCthreshold = 4*g->totalbytes;
}
static void preinit_state (lua_State *L, global_State *g) {
G(L) = g;
L->stack = NULL;
L->stacksize = 0;
L->errorJmp = NULL;
L->hook = NULL;
L->hookmask = 0;
L->basehookcount = 0;
L->allowhook = 1;
resethookcount(L);
L->openupval = NULL;
L->size_ci = 0;
L->nCcalls = L->baseCcalls = 0;
L->status = 0;
L->base_ci = L->ci = NULL;
L->savedpc = NULL;
L->errfunc = 0;
setnilvalue(gt(L));
}
static void close_state (lua_State *L) {
global_State *g = G(L);
luaF_close(L, L->stack); /* close all upvalues for this thread */
luaC_freeall(L); /* collect all objects */
lua_assert(g->rootgc == obj2gco(L));
lua_assert(g->strt.nuse == 0);
luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
luaZ_freebuffer(L, &g->buff);
freestack(L, L);
lua_assert(g->totalbytes == sizeof(LG));
(*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0);
}
lua_State *luaE_newthread (lua_State *L) {
lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State)));
luaC_link(L, obj2gco(L1), LUA_TTHREAD);
preinit_state(L1, G(L));
stack_init(L1, L); /* init stack */
setobj2n(L, gt(L1), gt(L)); /* share table of globals */
L1->hookmask = L->hookmask;
L1->basehookcount = L->basehookcount;
L1->hook = L->hook;
resethookcount(L1);
lua_assert(iswhite(obj2gco(L1)));
return L1;
}
void luaE_freethread (lua_State *L, lua_State *L1) {
luaF_close(L1, L1->stack); /* close all upvalues for this thread */
lua_assert(L1->openupval == NULL);
luai_userstatefree(L1);
freestack(L, L1);
luaM_freemem(L, fromstate(L1), state_size(lua_State));
}
LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
int i;
lua_State *L;
global_State *g;
void *l = (*f)(ud, NULL, 0, state_size(LG));
if (l == NULL) return NULL;
L = tostate(l);
g = &((LG *)L)->g;
L->next = NULL;
L->tt = LUA_TTHREAD;
g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
L->marked = luaC_white(g);
set2bits(L->marked, FIXEDBIT, SFIXEDBIT);
preinit_state(L, g);
g->frealloc = f;
g->ud = ud;
g->mainthread = L;
g->uvhead.u.l.prev = &g->uvhead;
g->uvhead.u.l.next = &g->uvhead;
g->GCthreshold = 0; /* mark it as unfinished state */
g->strt.size = 0;
g->strt.nuse = 0;
g->strt.hash = NULL;
setnilvalue(registry(L));
luaZ_initbuffer(L, &g->buff);
g->panic = NULL;
g->gcstate = GCSpause;
g->rootgc = obj2gco(L);
g->sweepstrgc = 0;
g->sweepgc = &g->rootgc;
g->gray = NULL;
g->grayagain = NULL;
g->weak = NULL;
g->tmudata = NULL;
g->totalbytes = sizeof(LG);
g->gcpause = LUAI_GCPAUSE;
g->gcstepmul = LUAI_GCMUL;
g->gcdept = 0;
for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL;
if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) {
/* memory allocation error: free partial state */
close_state(L);
L = NULL;
}
else
luai_userstateopen(L);
return L;
}
static void callallgcTM (lua_State *L, void *ud) {
UNUSED(ud);
luaC_callGCTM(L); /* call GC metamethods for all udata */
}
LUA_API void lua_close (lua_State *L) {
L = G(L)->mainthread; /* only the main thread can be closed */
lua_lock(L);
luaF_close(L, L->stack); /* close all upvalues for this thread */
luaC_separateudata(L, 1); /* separate udata that have GC metamethods */
L->errfunc = 0; /* no error function during GC metamethods */
do { /* repeat until no more errors */
L->ci = L->base_ci;
L->base = L->top = L->ci->base;
L->nCcalls = L->baseCcalls = 0;
} while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0);
lua_assert(G(L)->tmudata == NULL);
luai_userstateclose(L);
close_state(L);
}
| bsd-3-clause |
rsadhu/phantomjs | src/qt/src/3rdparty/webkit/Source/WebCore/css/SVGCSSParser.cpp | 56 | 13637 | /*
Copyright (C) 2008 Eric Seidel <eric@webkit.org>
Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
2004, 2005, 2007, 2010 Rob Buis <buis@kde.org>
Copyright (C) 2005, 2006 Apple Computer, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "CSSInheritedValue.h"
#include "CSSInitialValue.h"
#include "CSSParser.h"
#include "CSSProperty.h"
#include "CSSPropertyNames.h"
#include "CSSQuirkPrimitiveValue.h"
#include "CSSValueKeywords.h"
#include "CSSValueList.h"
#include "RenderTheme.h"
#include "SVGPaint.h"
using namespace std;
namespace WebCore {
bool CSSParser::parseSVGValue(int propId, bool important)
{
CSSParserValue* value = m_valueList->current();
if (!value)
return false;
int id = value->id;
bool valid_primitive = false;
RefPtr<CSSValue> parsedValue;
switch (propId) {
/* The comment to the right defines all valid value of these
* properties as defined in SVG 1.1, Appendix N. Property index */
case CSSPropertyAlignmentBaseline:
// auto | baseline | before-edge | text-before-edge | middle |
// central | after-edge | text-after-edge | ideographic | alphabetic |
// hanging | mathematical | inherit
if (id == CSSValueAuto || id == CSSValueBaseline || id == CSSValueMiddle ||
(id >= CSSValueBeforeEdge && id <= CSSValueMathematical))
valid_primitive = true;
break;
case CSSPropertyBaselineShift:
// baseline | super | sub | <percentage> | <length> | inherit
if (id == CSSValueBaseline || id == CSSValueSub ||
id >= CSSValueSuper)
valid_primitive = true;
else
valid_primitive = validUnit(value, FLength|FPercent, false);
break;
case CSSPropertyDominantBaseline:
// auto | use-script | no-change | reset-size | ideographic |
// alphabetic | hanging | mathematical | central | middle |
// text-after-edge | text-before-edge | inherit
if (id == CSSValueAuto || id == CSSValueMiddle ||
(id >= CSSValueUseScript && id <= CSSValueResetSize) ||
(id >= CSSValueCentral && id <= CSSValueMathematical))
valid_primitive = true;
break;
case CSSPropertyEnableBackground:
// accumulate | new [x] [y] [width] [height] | inherit
if (id == CSSValueAccumulate) // TODO : new
valid_primitive = true;
break;
case CSSPropertyMarkerStart:
case CSSPropertyMarkerMid:
case CSSPropertyMarkerEnd:
case CSSPropertyMask:
if (id == CSSValueNone)
valid_primitive = true;
else if (value->unit == CSSPrimitiveValue::CSS_URI) {
parsedValue = CSSPrimitiveValue::create(value->string, CSSPrimitiveValue::CSS_URI);
if (parsedValue)
m_valueList->next();
}
break;
case CSSPropertyClipRule: // nonzero | evenodd | inherit
case CSSPropertyFillRule:
if (id == CSSValueNonzero || id == CSSValueEvenodd)
valid_primitive = true;
break;
case CSSPropertyStrokeMiterlimit: // <miterlimit> | inherit
valid_primitive = validUnit(value, FNumber|FNonNeg, false);
break;
case CSSPropertyStrokeLinejoin: // miter | round | bevel | inherit
if (id == CSSValueMiter || id == CSSValueRound || id == CSSValueBevel)
valid_primitive = true;
break;
case CSSPropertyStrokeLinecap: // butt | round | square | inherit
if (id == CSSValueButt || id == CSSValueRound || id == CSSValueSquare)
valid_primitive = true;
break;
case CSSPropertyStrokeOpacity: // <opacity-value> | inherit
case CSSPropertyFillOpacity:
case CSSPropertyStopOpacity:
case CSSPropertyFloodOpacity:
valid_primitive = (!id && validUnit(value, FNumber|FPercent, false));
break;
case CSSPropertyShapeRendering:
// auto | optimizeSpeed | crispEdges | geometricPrecision | inherit
if (id == CSSValueAuto || id == CSSValueOptimizespeed ||
id == CSSValueCrispedges || id == CSSValueGeometricprecision)
valid_primitive = true;
break;
case CSSPropertyImageRendering: // auto | optimizeSpeed |
case CSSPropertyColorRendering: // optimizeQuality | inherit
if (id == CSSValueAuto || id == CSSValueOptimizespeed ||
id == CSSValueOptimizequality)
valid_primitive = true;
break;
case CSSPropertyColorProfile: // auto | sRGB | <name> | <uri> inherit
if (id == CSSValueAuto || id == CSSValueSrgb)
valid_primitive = true;
break;
case CSSPropertyColorInterpolation: // auto | sRGB | linearRGB | inherit
case CSSPropertyColorInterpolationFilters:
if (id == CSSValueAuto || id == CSSValueSrgb || id == CSSValueLinearrgb)
valid_primitive = true;
break;
/* Start of supported CSS properties with validation. This is needed for parseShortHand to work
* correctly and allows optimization in applyRule(..)
*/
case CSSPropertyTextAnchor: // start | middle | end | inherit
if (id == CSSValueStart || id == CSSValueMiddle || id == CSSValueEnd)
valid_primitive = true;
break;
case CSSPropertyGlyphOrientationVertical: // auto | <angle> | inherit
if (id == CSSValueAuto) {
valid_primitive = true;
break;
}
/* fallthrough intentional */
case CSSPropertyGlyphOrientationHorizontal: // <angle> (restricted to _deg_ per SVG 1.1 spec) | inherit
if (value->unit == CSSPrimitiveValue::CSS_DEG || value->unit == CSSPrimitiveValue::CSS_NUMBER) {
parsedValue = CSSPrimitiveValue::create(value->fValue, CSSPrimitiveValue::CSS_DEG);
if (parsedValue)
m_valueList->next();
}
break;
case CSSPropertyFill: // <paint> | inherit
case CSSPropertyStroke: // <paint> | inherit
{
if (id == CSSValueNone)
parsedValue = SVGPaint::createNone();
else if (id == CSSValueCurrentcolor)
parsedValue = SVGPaint::createCurrentColor();
else if ((id >= CSSValueActiveborder && id <= CSSValueWindowtext) || id == CSSValueMenu)
parsedValue = SVGPaint::createColor(RenderTheme::defaultTheme()->systemColor(id));
else if (value->unit == CSSPrimitiveValue::CSS_URI) {
RGBA32 c = Color::transparent;
if (m_valueList->next() && parseColorFromValue(m_valueList->current(), c)) {
parsedValue = SVGPaint::createURIAndColor(value->string, c);
} else
parsedValue = SVGPaint::createURI(value->string);
} else
parsedValue = parseSVGPaint();
if (parsedValue)
m_valueList->next();
}
break;
case CSSPropertyColor: // <color> | inherit
if ((id >= CSSValueAqua && id <= CSSValueWindowtext) ||
(id >= CSSValueAliceblue && id <= CSSValueYellowgreen))
parsedValue = SVGColor::createFromString(value->string);
else
parsedValue = parseSVGColor();
if (parsedValue)
m_valueList->next();
break;
case CSSPropertyStopColor: // TODO : icccolor
case CSSPropertyFloodColor:
case CSSPropertyLightingColor:
if ((id >= CSSValueAqua && id <= CSSValueWindowtext) ||
(id >= CSSValueAliceblue && id <= CSSValueYellowgreen))
parsedValue = SVGColor::createFromString(value->string);
else if (id == CSSValueCurrentcolor)
parsedValue = SVGColor::createCurrentColor();
else // TODO : svgcolor (iccColor)
parsedValue = parseSVGColor();
if (parsedValue)
m_valueList->next();
break;
case CSSPropertyVectorEffect: // none | non-scaling-stroke | inherit
if (id == CSSValueNone || id == CSSValueNonScalingStroke)
valid_primitive = true;
break;
case CSSPropertyWritingMode:
// lr-tb | rl_tb | tb-rl | lr | rl | tb | inherit
if (id == CSSValueLrTb || id == CSSValueRlTb || id == CSSValueTbRl || id == CSSValueLr || id == CSSValueRl || id == CSSValueTb)
valid_primitive = true;
break;
case CSSPropertyStrokeWidth: // <length> | inherit
case CSSPropertyStrokeDashoffset:
valid_primitive = validUnit(value, FLength | FPercent, false);
break;
case CSSPropertyStrokeDasharray: // none | <dasharray> | inherit
if (id == CSSValueNone)
valid_primitive = true;
else
parsedValue = parseSVGStrokeDasharray();
break;
case CSSPropertyKerning: // auto | normal | <length> | inherit
if (id == CSSValueAuto || id == CSSValueNormal)
valid_primitive = true;
else
valid_primitive = validUnit(value, FLength, false);
break;
case CSSPropertyClipPath: // <uri> | none | inherit
case CSSPropertyFilter:
if (id == CSSValueNone)
valid_primitive = true;
else if (value->unit == CSSPrimitiveValue::CSS_URI) {
parsedValue = CSSPrimitiveValue::create(value->string, (CSSPrimitiveValue::UnitTypes) value->unit);
if (parsedValue)
m_valueList->next();
}
break;
case CSSPropertyWebkitSvgShadow:
if (id == CSSValueNone)
valid_primitive = true;
else
return parseShadow(propId, important);
/* shorthand properties */
case CSSPropertyMarker:
{
ShorthandScope scope(this, propId);
m_implicitShorthand = true;
if (!parseValue(CSSPropertyMarkerStart, important))
return false;
if (m_valueList->current()) {
rollbackLastProperties(1);
return false;
}
CSSValue* value = m_parsedProperties[m_numParsedProperties - 1]->value();
addProperty(CSSPropertyMarkerMid, value, important);
addProperty(CSSPropertyMarkerEnd, value, important);
m_implicitShorthand = false;
return true;
}
default:
// If you crash here, it's because you added a css property and are not handling it
// in either this switch statement or the one in CSSParser::parseValue
ASSERT_WITH_MESSAGE(0, "unimplemented propertyID: %d", propId);
return false;
}
if (valid_primitive) {
if (id != 0)
parsedValue = CSSPrimitiveValue::createIdentifier(id);
else if (value->unit == CSSPrimitiveValue::CSS_STRING)
parsedValue = CSSPrimitiveValue::create(value->string, (CSSPrimitiveValue::UnitTypes) value->unit);
else if (value->unit >= CSSPrimitiveValue::CSS_NUMBER && value->unit <= CSSPrimitiveValue::CSS_KHZ)
parsedValue = CSSPrimitiveValue::create(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit);
else if (value->unit >= CSSParserValue::Q_EMS)
parsedValue = CSSQuirkPrimitiveValue::create(value->fValue, CSSPrimitiveValue::CSS_EMS);
m_valueList->next();
}
if (!parsedValue || (m_valueList->current() && !inShorthand()))
return false;
addProperty(propId, parsedValue.release(), important);
return true;
}
PassRefPtr<CSSValue> CSSParser::parseSVGStrokeDasharray()
{
RefPtr<CSSValueList> ret = CSSValueList::createCommaSeparated();
CSSParserValue* value = m_valueList->current();
bool valid_primitive = true;
while (value) {
valid_primitive = validUnit(value, FLength | FPercent |FNonNeg, false);
if (!valid_primitive)
break;
if (value->id != 0)
ret->append(CSSPrimitiveValue::createIdentifier(value->id));
else if (value->unit >= CSSPrimitiveValue::CSS_NUMBER && value->unit <= CSSPrimitiveValue::CSS_KHZ)
ret->append(CSSPrimitiveValue::create(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit));
value = m_valueList->next();
if (value && value->unit == CSSParserValue::Operator && value->iValue == ',')
value = m_valueList->next();
}
if (!valid_primitive)
return 0;
return ret.release();
}
PassRefPtr<CSSValue> CSSParser::parseSVGPaint()
{
RGBA32 c = Color::transparent;
if (!parseColorFromValue(m_valueList->current(), c))
return SVGPaint::createUnknown();
return SVGPaint::createColor(Color(c));
}
PassRefPtr<CSSValue> CSSParser::parseSVGColor()
{
RGBA32 c = Color::transparent;
if (!parseColorFromValue(m_valueList->current(), c))
return 0;
return SVGColor::createFromColor(Color(c));
}
}
#endif // ENABLE(SVG)
| bsd-3-clause |
stan-dev/math | lib/boost_1.78.0/tools/auto_index/src/tiny_xml.cpp | 58 | 7004 | // tiny XML sub-set tools implementation -----------------------------------//
// (C) Copyright Beman Dawes 2002. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "tiny_xml.hpp"
#include <cassert>
#include <cstring>
namespace
{
inline void eat_whitespace( char & c, std::istream & in )
{
while ( c == ' ' || c == '\r' || c == '\n' || c == '\t' )
in.get( c );
}
void eat_comment( char & c, std::istream & in )
{
in.get(c);
if(c != '-')
throw std::string("Invalid comment in XML");
in.get(c);
if(c != '-')
throw std::string("Invalid comment in XML");
do{
while(in.get(c) && (c != '-'));
in.get(c);
if(c != '-')
continue;
in.get(c);
if(c != '>')
continue;
else
break;
}
while(true);
}
std::string get_name( char & c, std::istream & in )
{
std::string result;
eat_whitespace( c, in );
while ( std::strchr(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.:", c )
!= 0 )
{
result += c;
if(!in.get( c ))
throw std::string("xml: unexpected eof");
}
return result;
}
void eat_delim( char & c, std::istream & in,
char delim, const std::string & msg )
{
eat_whitespace( c, in );
if ( c != delim )
throw std::string("xml syntax error, expected ") + delim
+ " (" + msg + ")";
in.get( c );
}
std::string get_value( char & c, std::istream & in )
{
std::string result;
while ( c != '\"' )
{
result += c;
in.get( c );
}
in.get( c );
return result;
}
}
namespace boost
{
namespace tiny_xml
{
// parse -----------------------------------------------------------------//
element_ptr parse( std::istream & in, const std::string & msg )
{
char c = 0; // current character
element_ptr e( new element );
if(!in.get( c ))
throw std::string("xml: unexpected eof");
if ( c == '<' )
if(!in.get( c ))
throw std::string("xml: unexpected eof");
if(c == '!')
{
eat_comment(c, in);
return e;
}
if(c == '?')
{
// XML processing instruction.
e->name += c;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
e->name += get_name(c, in);
in >> std::ws;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
while(c != '?')
{
e->content += c;
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
}
if(!in.get( c )) // next char
throw std::string("xml: unexpected eof");
if(c != '>')
throw std::string("Invalid XML processing instruction.");
return e;
}
e->name = get_name( c, in );
eat_whitespace( c, in );
// attributes
while ( (c != '>') && (c != '/') )
{
attribute a;
a.name = get_name( c, in );
eat_delim( c, in, '=', msg );
eat_delim( c, in, '\"', msg );
a.value = get_value( c, in );
e->attributes.push_back( a );
eat_whitespace( c, in );
}
if(c == '/')
{
if(!in.get( c )) // next after '/'
throw std::string("xml: unexpected eof");
eat_whitespace( c, in );
if(c != '>')
throw std::string("xml: unexpected /");
return e;
}
if(!in.get( c )) // next after '>'
throw std::string("xml: unexpected eof");
//eat_whitespace( c, in );
do{
// sub-elements
while ( c == '<' )
{
if ( in.peek() == '/' )
break;
element_ptr child(parse( in, msg ));
child->parent = e;
e->elements.push_back(child);
in.get( c ); // next after '>'
//eat_whitespace( c, in );
}
if (( in.peek() == '/' ) && (c == '<'))
break;
// content
if ( (c != '<') )
{
element_ptr sub( new element );
while ( c != '<' )
{
sub->content += c;
if(!in.get( c ))
throw std::string("xml: unexpected eof");
}
sub->parent = e;
e->elements.push_back( sub );
}
assert( c == '<' );
if( in.peek() == '/' )
break;
}while(true);
in.get(c);
eat_delim( c, in, '/', msg );
std::string end_name( get_name( c, in ) );
if ( e->name != end_name )
throw std::string("xml syntax error: beginning name ")
+ e->name + " did not match end name " + end_name
+ " (" + msg + ")";
eat_delim( c, in, '>', msg );
if(c != '>')
{
// we've eaten one character past the >, put it back:
if(!in.putback(c))
throw std::string("Unable to put back character");
}
return e;
}
// write ---------------------------------------------------------------//
void write( const element & e, std::ostream & out )
{
if(e.name.size())
{
out << "<" << e.name;
if ( !e.attributes.empty() )
{
for( attribute_list::const_iterator itr = e.attributes.begin();
itr != e.attributes.end(); ++itr )
{
out << " " << itr->name << "=\"" << itr->value << "\"";
}
}
if(e.name[0] == '?')
{
out << " " << e.content << "?>";
return;
}
if(e.elements.empty() && e.content.empty())
{
out << "/>";
return;
}
out << ">";
}
if ( !e.elements.empty() )
{
for( element_list::const_iterator itr = e.elements.begin();
itr != e.elements.end(); ++itr )
{
write( **itr, out );
}
}
if ( !e.content.empty() )
{
out << e.content;
}
if(e.name.size() && (e.name[0] != '?'))
{
out << "</" << e.name << ">";
}
}
} // namespace tiny_xml
} // namespace boost
| bsd-3-clause |
libigl/eigen | unsupported/bench/bench_svd.cpp | 314 | 3905 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/
// Bench to compare the efficiency of SVD algorithms
#include <iostream>
#include <bench/BenchTimer.h>
#include <unsupported/Eigen/SVD>
using namespace Eigen;
using namespace std;
// number of computations of each algorithm before the print of the time
#ifndef REPEAT
#define REPEAT 10
#endif
// number of tests of the same type
#ifndef NUMBER_SAMPLE
#define NUMBER_SAMPLE 2
#endif
template<typename MatrixType>
void bench_svd(const MatrixType& a = MatrixType())
{
MatrixType m = MatrixType::Random(a.rows(), a.cols());
BenchTimer timerJacobi;
BenchTimer timerBDC;
timerJacobi.reset();
timerBDC.reset();
cout << " Only compute Singular Values" <<endl;
for (int k=1; k<=NUMBER_SAMPLE; ++k)
{
timerBDC.start();
for (int i=0; i<REPEAT; ++i)
{
BDCSVD<MatrixType> bdc_matrix(m);
}
timerBDC.stop();
timerJacobi.start();
for (int i=0; i<REPEAT; ++i)
{
JacobiSVD<MatrixType> jacobi_matrix(m);
}
timerJacobi.stop();
cout << "Sample " << k << " : " << REPEAT << " computations : Jacobi : " << fixed << timerJacobi.value() << "s ";
cout << " || " << " BDC : " << timerBDC.value() << "s " <<endl <<endl;
if (timerBDC.value() >= timerJacobi.value())
cout << "KO : BDC is " << timerJacobi.value() / timerBDC.value() << " times faster than Jacobi" <<endl;
else
cout << "OK : BDC is " << timerJacobi.value() / timerBDC.value() << " times faster than Jacobi" <<endl;
}
cout << " =================" <<endl;
std::cout<< std::endl;
timerJacobi.reset();
timerBDC.reset();
cout << " Computes rotaion matrix" <<endl;
for (int k=1; k<=NUMBER_SAMPLE; ++k)
{
timerBDC.start();
for (int i=0; i<REPEAT; ++i)
{
BDCSVD<MatrixType> bdc_matrix(m, ComputeFullU|ComputeFullV);
}
timerBDC.stop();
timerJacobi.start();
for (int i=0; i<REPEAT; ++i)
{
JacobiSVD<MatrixType> jacobi_matrix(m, ComputeFullU|ComputeFullV);
}
timerJacobi.stop();
cout << "Sample " << k << " : " << REPEAT << " computations : Jacobi : " << fixed << timerJacobi.value() << "s ";
cout << " || " << " BDC : " << timerBDC.value() << "s " <<endl <<endl;
if (timerBDC.value() >= timerJacobi.value())
cout << "KO : BDC is " << timerJacobi.value() / timerBDC.value() << " times faster than Jacobi" <<endl;
else
cout << "OK : BDC is " << timerJacobi.value() / timerBDC.value() << " times faster than Jacobi" <<endl;
}
std::cout<< std::endl;
}
int main(int argc, char* argv[])
{
std::cout<< std::endl;
std::cout<<"On a (Dynamic, Dynamic) (6, 6) Matrix" <<std::endl;
bench_svd<Matrix<double,Dynamic,Dynamic> >(Matrix<double,Dynamic,Dynamic>(6, 6));
std::cout<<"On a (Dynamic, Dynamic) (32, 32) Matrix" <<std::endl;
bench_svd<Matrix<double,Dynamic,Dynamic> >(Matrix<double,Dynamic,Dynamic>(32, 32));
//std::cout<<"On a (Dynamic, Dynamic) (128, 128) Matrix" <<std::endl;
//bench_svd<Matrix<double,Dynamic,Dynamic> >(Matrix<double,Dynamic,Dynamic>(128, 128));
std::cout<<"On a (Dynamic, Dynamic) (160, 160) Matrix" <<std::endl;
bench_svd<Matrix<double,Dynamic,Dynamic> >(Matrix<double,Dynamic,Dynamic>(160, 160));
std::cout<< "--------------------------------------------------------------------"<< std::endl;
}
| bsd-3-clause |
felipebetancur/scipy | scipy/special/cephes/ellpk.c | 60 | 2709 | /* ellpk.c
*
* Complete elliptic integral of the first kind
*
*
*
* SYNOPSIS:
*
* double m, y, ellpk();
*
* y = ellpk( m );
*
*
*
* DESCRIPTION:
*
* Approximates the integral
*
*
*
* pi/2
* -
* | |
* | dt
* K(m) = | ------------------
* | 2
* | | sqrt( 1 - m sin t )
* -
* 0
*
* where m = 1 - m1, using the approximation
*
* P(x) - log x Q(x).
*
* The argument m1 is used internally rather than m so that the logarithmic
* singularity at m = 1 will be shifted to the origin; this
* preserves maximum accuracy.
*
* K(0) = pi/2.
*
* ACCURACY:
*
* Relative error:
* arithmetic domain # trials peak rms
* IEEE 0,1 30000 2.5e-16 6.8e-17
*
* ERROR MESSAGES:
*
* message condition value returned
* ellpk domain x<0, x>1 0.0
*
*/
/* ellpk.c */
/*
* Cephes Math Library, Release 2.0: April, 1987
* Copyright 1984, 1987 by Stephen L. Moshier
* Direct inquiries to 30 Frost Street, Cambridge, MA 02140
*
* Feb, 2002: altered by Travis Oliphant
* so that it is called with argument m
* (which gets immediately converted to m1 = 1-m)
*/
#include "mconf.h"
static double P[] = {
1.37982864606273237150E-4,
2.28025724005875567385E-3,
7.97404013220415179367E-3,
9.85821379021226008714E-3,
6.87489687449949877925E-3,
6.18901033637687613229E-3,
8.79078273952743772254E-3,
1.49380448916805252718E-2,
3.08851465246711995998E-2,
9.65735902811690126535E-2,
1.38629436111989062502E0
};
static double Q[] = {
2.94078955048598507511E-5,
9.14184723865917226571E-4,
5.94058303753167793257E-3,
1.54850516649762399335E-2,
2.39089602715924892727E-2,
3.01204715227604046988E-2,
3.73774314173823228969E-2,
4.88280347570998239232E-2,
7.03124996963957469739E-2,
1.24999999999870820058E-1,
4.99999999999999999821E-1
};
static double C1 = 1.3862943611198906188E0; /* log(4) */
extern double MACHEP;
double ellpk(x)
double x;
{
if (x < 0.0) {
mtherr("ellpk", DOMAIN);
return (NPY_NAN);
}
if (x > 1.0) {
if (cephes_isinf(x)) {
return 0.0;
}
return ellpk(1/x)/sqrt(x);
}
if (x > MACHEP) {
return (polevl(x, P, 10) - log(x) * polevl(x, Q, 10));
}
else {
if (x == 0.0) {
mtherr("ellpk", SING);
return (NPY_INFINITY);
}
else {
return (C1 - 0.5 * log(x));
}
}
}
| bsd-3-clause |
guorendong/iridium-browser-ubuntu | native_client_sdk/src/libraries/third_party/pthreads-win32/pthread_mutex_consistent.c | 324 | 6747 | /*
* pthread_mutex_consistent.c
*
* Description:
* This translation unit implements mutual exclusion (mutex) primitives.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/*
* From the Sun Multi-threaded Programming Guide
*
* robustness defines the behavior when the owner of the mutex terminates without unlocking the
* mutex, usually because its process terminated abnormally. The value of robustness that is
* defined in pthread.h is PTHREAD_MUTEX_ROBUST or PTHREAD_MUTEX_STALLED. The
* default value is PTHREAD_MUTEX_STALLED .
* ■ PTHREAD_MUTEX_STALLED
* When the owner of the mutex terminates without unlocking the mutex, all subsequent calls
* to pthread_mutex_lock() are blocked from progress in an unspecified manner.
* ■ PTHREAD_MUTEX_ROBUST
* When the owner of the mutex terminates without unlocking the mutex, the mutex is
* unlocked. The next owner of this mutex acquires the mutex with an error return of
* EOWNERDEAD.
* Note – Your application must always check the return code from pthread_mutex_lock() for
* a mutex initialized with the PTHREAD_MUTEX_ROBUST attribute.
* ■ The new owner of this mutex should make the state protected by the mutex consistent.
* This state might have been left inconsistent when the previous owner terminated.
* ■ If the new owner is able to make the state consistent, call
* pthread_mutex_consistent() for the mutex before unlocking the mutex. This
* marks the mutex as consistent and subsequent calls to pthread_mutex_lock() and
* pthread_mutex_unlock() will behave in the normal manner.
* ■ If the new owner is not able to make the state consistent, do not call
* pthread_mutex_consistent() for the mutex, but unlock the mutex.
* All waiters are woken up and all subsequent calls to pthread_mutex_lock() fail to
* acquire the mutex. The return code is ENOTRECOVERABLE. The mutex can be made
* consistent by calling pthread_mutex_destroy() to uninitialize the mutex, and calling
* pthread_mutex_int() to reinitialize the mutex.However, the state that was protected
* by the mutex remains inconsistent and some form of application recovery is required.
* ■ If the thread that acquires the lock with EOWNERDEAD terminates without unlocking the
* mutex, the next owner acquires the lock with an EOWNERDEAD return code.
*/
#if !defined(_UWIN)
/*# include <process.h> */
#endif
#include "pthread.h"
#include "implement.h"
INLINE
int
ptw32_robust_mutex_inherit(pthread_mutex_t * mutex)
{
int result;
pthread_mutex_t mx = *mutex;
ptw32_robust_node_t* robust = mx->robustNode;
switch ((LONG)PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG(
(PTW32_INTERLOCKED_LONGPTR)&robust->stateInconsistent,
(PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT,
(PTW32_INTERLOCKED_LONG)-1 /* The terminating thread sets this */))
{
case -1L:
result = EOWNERDEAD;
break;
case (LONG)PTW32_ROBUST_NOTRECOVERABLE:
result = ENOTRECOVERABLE;
break;
default:
result = 0;
break;
}
return result;
}
/*
* The next two internal support functions depend on only being
* called by the thread that owns the robust mutex. This enables
* us to avoid additional locks.
* Any mutex currently in the thread's robust mutex list is held
* by the thread, again eliminating the need for locks.
* The forward/backward links allow the thread to unlock mutexes
* in any order, not necessarily the reverse locking order.
* This is all possible because it is an error if a thread that
* does not own the [robust] mutex attempts to unlock it.
*/
INLINE
void
ptw32_robust_mutex_add(pthread_mutex_t* mutex, pthread_t self)
{
ptw32_robust_node_t** list;
pthread_mutex_t mx = *mutex;
ptw32_thread_t* tp = (ptw32_thread_t*)self.p;
ptw32_robust_node_t* robust = mx->robustNode;
list = &tp->robustMxList;
mx->ownerThread = self;
if (NULL == *list)
{
robust->prev = NULL;
robust->next = NULL;
*list = robust;
}
else
{
robust->prev = NULL;
robust->next = *list;
(*list)->prev = robust;
*list = robust;
}
}
INLINE
void
ptw32_robust_mutex_remove(pthread_mutex_t* mutex, ptw32_thread_t* otp)
{
ptw32_robust_node_t** list;
pthread_mutex_t mx = *mutex;
ptw32_robust_node_t* robust = mx->robustNode;
list = &(((ptw32_thread_t*)mx->ownerThread.p)->robustMxList);
mx->ownerThread.p = otp;
if (robust->next != NULL)
{
robust->next->prev = robust->prev;
}
if (robust->prev != NULL)
{
robust->prev->next = robust->next;
}
if (*list == robust)
{
*list = robust->next;
}
}
int
pthread_mutex_consistent (pthread_mutex_t* mutex)
{
pthread_mutex_t mx = *mutex;
int result = 0;
/*
* Let the system deal with invalid pointers.
*/
if (mx == NULL)
{
return EINVAL;
}
if (mx->kind >= 0
|| (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT != PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG(
(PTW32_INTERLOCKED_LONGPTR)&mx->robustNode->stateInconsistent,
(PTW32_INTERLOCKED_LONG)PTW32_ROBUST_CONSISTENT,
(PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT))
{
result = EINVAL;
}
return (result);
}
| bsd-3-clause |
fling-mstar/external-skia | gm/pathreverse.cpp | 70 | 2897 | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkTypeface.h"
static void test_path(SkCanvas* canvas, const SkPath& path) {
SkPaint paint;
paint.setAntiAlias(true);
canvas->drawPath(path, paint);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(SK_ColorRED);
canvas->drawPath(path, paint);
}
static void test_rev(SkCanvas* canvas, const SkPath& path) {
test_path(canvas, path);
SkPath rev;
rev.reverseAddPath(path);
canvas->save();
canvas->translate(150, 0);
test_path(canvas, rev);
canvas->restore();
}
static void test_rev(SkCanvas* canvas) {
SkRect r = { 10, 10, 100, 60 };
SkPath path;
path.addRect(r); test_rev(canvas, path);
canvas->translate(0, 100);
path.offset(20, 20);
path.addRect(r); test_rev(canvas, path);
canvas->translate(0, 100);
path.reset();
path.moveTo(10, 10); path.lineTo(30, 30);
path.addOval(r);
r.offset(50, 20);
path.addOval(r);
test_rev(canvas, path);
SkPaint paint;
paint.setTextSize(SkIntToScalar(100));
SkTypeface* hira = SkTypeface::CreateFromName("Hiragino Maru Gothic Pro", SkTypeface::kNormal);
SkSafeUnref(paint.setTypeface(hira));
path.reset();
paint.getTextPath("e", 1, 50, 50, &path);
canvas->translate(0, 100);
test_rev(canvas, path);
}
namespace skiagm {
class PathReverseGM : public GM {
public:
PathReverseGM() {
}
protected:
virtual SkString onShortName() {
return SkString("path-reverse");
}
virtual SkISize onISize() {
return make_isize(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
if (false) test_rev(canvas); // avoid bit rot, suppress warning
SkRect r = { 10, 10, 100, 60 };
SkPath path;
path.addRect(r); test_rev(canvas, path);
canvas->translate(0, 100);
path.offset(20, 20);
path.addRect(r); test_rev(canvas, path);
canvas->translate(0, 100);
path.reset();
path.moveTo(10, 10); path.lineTo(30, 30);
path.addOval(r);
r.offset(50, 20);
path.addOval(r);
test_rev(canvas, path);
SkPaint paint;
paint.setTextSize(SkIntToScalar(100));
SkTypeface* hira = SkTypeface::CreateFromName("Hiragino Maru Gothic Pro", SkTypeface::kNormal);
SkSafeUnref(paint.setTypeface(hira));
path.reset();
paint.getTextPath("e", 1, 50, 50, &path);
canvas->translate(0, 100);
test_rev(canvas, path);
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new PathReverseGM; }
static GMRegistry reg(MyFactory);
}
| bsd-3-clause |
AndroidOpenDevelopment/android_external_chromium_org | content/shell/tools/plugin/Tests/SlowNPPNew.cpp | 79 | 3115 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/*
* Copyright (C) 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PluginTest.h"
#include <string.h>
using namespace std;
class SlowNPPNew : public PluginTest {
public:
SlowNPPNew(NPP npp, const string& identifier)
: PluginTest(npp, identifier)
{
}
private:
class PluginObject : public Object<PluginObject> {
public:
PluginObject()
{
}
~PluginObject()
{
}
bool hasProperty(NPIdentifier propertyName)
{
return true;
}
bool getProperty(NPIdentifier propertyName, NPVariant* result)
{
static const char* message = "My name is ";
char* propertyString = pluginTest()->NPN_UTF8FromIdentifier(propertyName);
int bufferLength = strlen(propertyString) + strlen(message) + 1;
char* resultBuffer = static_cast<char*>(pluginTest()->NPN_MemAlloc(bufferLength));
snprintf(resultBuffer, bufferLength, "%s%s", message, propertyString);
STRINGZ_TO_NPVARIANT(resultBuffer, *result);
return true;
}
};
virtual NPError NPP_GetValue(NPPVariable variable, void *value)
{
if (variable != NPPVpluginScriptableNPObject)
return NPERR_GENERIC_ERROR;
*(NPObject**)value = PluginObject::create(this);
return NPERR_NO_ERROR;
}
virtual NPError NPP_New(NPMIMEType pluginType, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData *saved)
{
usleep(550000);
return NPERR_NO_ERROR;
}
};
static PluginTest::Register<SlowNPPNew> slowNPPNew("slow-npp-new");
| bsd-3-clause |
befelix/scipy | scipy/linalg/_blas_subroutine_wrappers.f | 79 | 5440 | c This file was generated by _cython_wrapper_generators.py.
c Do not edit this file directly.
subroutine cdotcwrp(ret, n, cx, incx, cy, incy)
external wcdotc
complex wcdotc
complex ret
integer n
complex cx(n)
integer incx
complex cy(n)
integer incy
ret = wcdotc(n, cx, incx, cy, incy)
end
subroutine cdotuwrp(ret, n, cx, incx, cy, incy)
external wcdotu
complex wcdotu
complex ret
integer n
complex cx(n)
integer incx
complex cy(n)
integer incy
ret = wcdotu(n, cx, incx, cy, incy)
end
subroutine dasumwrp(ret, n, dx, incx)
external dasum
double precision dasum
double precision ret
integer n
double precision dx(n)
integer incx
ret = dasum(n, dx, incx)
end
subroutine dcabs1wrp(ret, z)
external dcabs1
double precision dcabs1
double precision ret
complex*16 z
ret = dcabs1(z)
end
subroutine ddotwrp(ret, n, dx, incx, dy, incy)
external ddot
double precision ddot
double precision ret
integer n
double precision dx(n)
integer incx
double precision dy(n)
integer incy
ret = ddot(n, dx, incx, dy, incy)
end
subroutine dnrm2wrp(ret, n, x, incx)
external dnrm2
double precision dnrm2
double precision ret
integer n
double precision x(n)
integer incx
ret = dnrm2(n, x, incx)
end
subroutine dsdotwrp(ret, n, sx, incx, sy, incy)
external dsdot
double precision dsdot
double precision ret
integer n
real sx(n)
integer incx
real sy(n)
integer incy
ret = dsdot(n, sx, incx, sy, incy)
end
subroutine dzasumwrp(ret, n, zx, incx)
external dzasum
double precision dzasum
double precision ret
integer n
complex*16 zx(n)
integer incx
ret = dzasum(n, zx, incx)
end
subroutine dznrm2wrp(ret, n, x, incx)
external dznrm2
double precision dznrm2
double precision ret
integer n
complex*16 x(n)
integer incx
ret = dznrm2(n, x, incx)
end
subroutine icamaxwrp(ret, n, cx, incx)
external icamax
integer icamax
integer ret
integer n
complex cx(n)
integer incx
ret = icamax(n, cx, incx)
end
subroutine idamaxwrp(ret, n, dx, incx)
external idamax
integer idamax
integer ret
integer n
double precision dx(n)
integer incx
ret = idamax(n, dx, incx)
end
subroutine isamaxwrp(ret, n, sx, incx)
external isamax
integer isamax
integer ret
integer n
real sx(n)
integer incx
ret = isamax(n, sx, incx)
end
subroutine izamaxwrp(ret, n, zx, incx)
external izamax
integer izamax
integer ret
integer n
complex*16 zx(n)
integer incx
ret = izamax(n, zx, incx)
end
subroutine lsamewrp(ret, ca, cb)
external lsame
logical lsame
logical ret
character ca
character cb
ret = lsame(ca, cb)
end
subroutine sasumwrp(ret, n, sx, incx)
external wsasum
real wsasum
real ret
integer n
real sx(n)
integer incx
ret = wsasum(n, sx, incx)
end
subroutine scasumwrp(ret, n, cx, incx)
external wscasum
real wscasum
real ret
integer n
complex cx(n)
integer incx
ret = wscasum(n, cx, incx)
end
subroutine scnrm2wrp(ret, n, x, incx)
external wscnrm2
real wscnrm2
real ret
integer n
complex x(n)
integer incx
ret = wscnrm2(n, x, incx)
end
subroutine sdotwrp(ret, n, sx, incx, sy, incy)
external wsdot
real wsdot
real ret
integer n
real sx(n)
integer incx
real sy(n)
integer incy
ret = wsdot(n, sx, incx, sy, incy)
end
subroutine sdsdotwrp(ret, n, sb, sx, incx, sy, incy)
external wsdsdot
real wsdsdot
real ret
integer n
real sb
real sx(n)
integer incx
real sy(n)
integer incy
ret = wsdsdot(n, sb, sx, incx, sy, incy)
end
subroutine snrm2wrp(ret, n, x, incx)
external wsnrm2
real wsnrm2
real ret
integer n
real x(n)
integer incx
ret = wsnrm2(n, x, incx)
end
subroutine zdotcwrp(ret, n, zx, incx, zy, incy)
external wzdotc
complex*16 wzdotc
complex*16 ret
integer n
complex*16 zx(n)
integer incx
complex*16 zy(n)
integer incy
ret = wzdotc(n, zx, incx, zy, incy)
end
subroutine zdotuwrp(ret, n, zx, incx, zy, incy)
external wzdotu
complex*16 wzdotu
complex*16 ret
integer n
complex*16 zx(n)
integer incx
complex*16 zy(n)
integer incy
ret = wzdotu(n, zx, incx, zy, incy)
end
| bsd-3-clause |
gfreed/android_external_chromium-org | native_client_sdk/src/libraries/third_party/pthreads-win32/signal.c | 335 | 5207 | /*
* signal.c
*
* Description:
* Thread-aware signal functions.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/*
* Possible future strategy for implementing pthread_kill()
* ========================================================
*
* Win32 does not implement signals.
* Signals are simply software interrupts.
* pthread_kill() asks the system to deliver a specified
* signal (interrupt) to a specified thread in the same
* process.
* Signals are always asynchronous (no deferred signals).
* Pthread-win32 has an async cancelation mechanism.
* A similar system can be written to deliver signals
* within the same process (on ix86 processors at least).
*
* Each thread maintains information about which
* signals it will respond to. Handler routines
* are set on a per-process basis - not per-thread.
* When signalled, a thread will check it's sigmask
* and, if the signal is not being ignored, call the
* handler routine associated with the signal. The
* thread must then (except for some signals) return to
* the point where it was interrupted.
*
* Ideally the system itself would check the target thread's
* mask before possibly needlessly bothering the thread
* itself. This could be done by pthread_kill(), that is,
* in the signaling thread since it has access to
* all pthread_t structures. It could also retrieve
* the handler routine address to minimise the target
* threads response overhead. This may also simplify
* serialisation of the access to the per-thread signal
* structures.
*
* pthread_kill() eventually calls a routine similar to
* ptw32_cancel_thread() which manipulates the target
* threads processor context to cause the thread to
* run the handler launcher routine. pthread_kill() must
* save the target threads current context so that the
* handler launcher routine can restore the context after
* the signal handler has returned. Some handlers will not
* return, eg. the default SIGKILL handler may simply
* call pthread_exit().
*
* The current context is saved in the target threads
* pthread_t structure.
*/
#include "pthread.h"
#include "implement.h"
#if defined(HAVE_SIGSET_T)
static void
ptw32_signal_thread ()
{
}
static void
ptw32_signal_callhandler ()
{
}
int
pthread_sigmask (int how, sigset_t const *set, sigset_t * oset)
{
pthread_t thread = pthread_self ();
if (thread.p == NULL)
{
return ENOENT;
}
/* Validate the `how' argument. */
if (set != NULL)
{
switch (how)
{
case SIG_BLOCK:
break;
case SIG_UNBLOCK:
break;
case SIG_SETMASK:
break;
default:
/* Invalid `how' argument. */
return EINVAL;
}
}
/* Copy the old mask before modifying it. */
if (oset != NULL)
{
memcpy (oset, &(thread.p->sigmask), sizeof (sigset_t));
}
if (set != NULL)
{
unsigned int i;
/* FIXME: this code assumes that sigmask is an even multiple of
the size of a long integer. */
unsigned long *src = (unsigned long const *) set;
unsigned long *dest = (unsigned long *) &(thread.p->sigmask);
switch (how)
{
case SIG_BLOCK:
for (i = 0; i < (sizeof (sigset_t) / sizeof (unsigned long)); i++)
{
/* OR the bit field longword-wise. */
*dest++ |= *src++;
}
break;
case SIG_UNBLOCK:
for (i = 0; i < (sizeof (sigset_t) / sizeof (unsigned long)); i++)
{
/* XOR the bitfield longword-wise. */
*dest++ ^= *src++;
}
case SIG_SETMASK:
/* Replace the whole sigmask. */
memcpy (&(thread.p->sigmask), set, sizeof (sigset_t));
break;
}
}
return 0;
}
int
sigwait (const sigset_t * set, int *sig)
{
/* This routine is a cancellation point */
pthread_test_cancel();
}
int
sigaction (int signum, const struct sigaction *act, struct sigaction *oldact)
{
}
#endif /* HAVE_SIGSET_T */
| bsd-3-clause |
hhli/redis | deps/jemalloc/src/mutex.c | 336 | 3339 | #define JEMALLOC_MUTEX_C_
#include "jemalloc/internal/jemalloc_internal.h"
#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
#include <dlfcn.h>
#endif
#ifndef _CRT_SPINCOUNT
#define _CRT_SPINCOUNT 4000
#endif
/******************************************************************************/
/* Data. */
#ifdef JEMALLOC_LAZY_LOCK
bool isthreaded = false;
#endif
#ifdef JEMALLOC_MUTEX_INIT_CB
static bool postpone_init = true;
static malloc_mutex_t *postponed_mutexes = NULL;
#endif
#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
static void pthread_create_once(void);
#endif
/******************************************************************************/
/*
* We intercept pthread_create() calls in order to toggle isthreaded if the
* process goes multi-threaded.
*/
#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
static int (*pthread_create_fptr)(pthread_t *__restrict, const pthread_attr_t *,
void *(*)(void *), void *__restrict);
static void
pthread_create_once(void)
{
pthread_create_fptr = dlsym(RTLD_NEXT, "pthread_create");
if (pthread_create_fptr == NULL) {
malloc_write("<jemalloc>: Error in dlsym(RTLD_NEXT, "
"\"pthread_create\")\n");
abort();
}
isthreaded = true;
}
JEMALLOC_EXPORT int
pthread_create(pthread_t *__restrict thread,
const pthread_attr_t *__restrict attr, void *(*start_routine)(void *),
void *__restrict arg)
{
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
pthread_once(&once_control, pthread_create_once);
return (pthread_create_fptr(thread, attr, start_routine, arg));
}
#endif
/******************************************************************************/
#ifdef JEMALLOC_MUTEX_INIT_CB
JEMALLOC_EXPORT int _pthread_mutex_init_calloc_cb(pthread_mutex_t *mutex,
void *(calloc_cb)(size_t, size_t));
#endif
bool
malloc_mutex_init(malloc_mutex_t *mutex)
{
#ifdef _WIN32
if (!InitializeCriticalSectionAndSpinCount(&mutex->lock,
_CRT_SPINCOUNT))
return (true);
#elif (defined(JEMALLOC_OSSPIN))
mutex->lock = 0;
#elif (defined(JEMALLOC_MUTEX_INIT_CB))
if (postpone_init) {
mutex->postponed_next = postponed_mutexes;
postponed_mutexes = mutex;
} else {
if (_pthread_mutex_init_calloc_cb(&mutex->lock, base_calloc) !=
0)
return (true);
}
#else
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0)
return (true);
pthread_mutexattr_settype(&attr, MALLOC_MUTEX_TYPE);
if (pthread_mutex_init(&mutex->lock, &attr) != 0) {
pthread_mutexattr_destroy(&attr);
return (true);
}
pthread_mutexattr_destroy(&attr);
#endif
return (false);
}
void
malloc_mutex_prefork(malloc_mutex_t *mutex)
{
malloc_mutex_lock(mutex);
}
void
malloc_mutex_postfork_parent(malloc_mutex_t *mutex)
{
malloc_mutex_unlock(mutex);
}
void
malloc_mutex_postfork_child(malloc_mutex_t *mutex)
{
#ifdef JEMALLOC_MUTEX_INIT_CB
malloc_mutex_unlock(mutex);
#else
if (malloc_mutex_init(mutex)) {
malloc_printf("<jemalloc>: Error re-initializing mutex in "
"child\n");
if (opt_abort)
abort();
}
#endif
}
bool
mutex_boot(void)
{
#ifdef JEMALLOC_MUTEX_INIT_CB
postpone_init = false;
while (postponed_mutexes != NULL) {
if (_pthread_mutex_init_calloc_cb(&postponed_mutexes->lock,
base_calloc) != 0)
return (true);
postponed_mutexes = postponed_mutexes->postponed_next;
}
#endif
return (false);
}
| bsd-3-clause |
chirilo/phantomjs | src/qt/qtbase/src/widgets/widgets/qtoolbararealayout.cpp | 84 | 43995 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QWidgetItem>
#include <QToolBar>
#include <QStyleOption>
#include <QApplication>
#include <qdebug.h>
#include "qtoolbararealayout_p.h"
#include "qmainwindowlayout_p.h"
#include "qwidgetanimator_p.h"
#include "qtoolbarlayout_p.h"
#include "qtoolbar_p.h"
/******************************************************************************
** QToolBarAreaLayoutItem
*/
#ifndef QT_NO_TOOLBAR
QT_BEGIN_NAMESPACE
// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *mainWindow);
QSize QToolBarAreaLayoutItem::minimumSize() const
{
if (skip())
return QSize(0, 0);
return qSmartMinSize(static_cast<QWidgetItem*>(widgetItem));
}
QSize QToolBarAreaLayoutItem::sizeHint() const
{
if (skip())
return QSize(0, 0);
return realSizeHint();
}
//returns the real size hint not taking into account the visibility of the widget
QSize QToolBarAreaLayoutItem::realSizeHint() const
{
QWidget *wid = widgetItem->widget();
QSize s = wid->sizeHint().expandedTo(wid->minimumSizeHint());
if (wid->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored)
s.setWidth(0);
if (wid->sizePolicy().verticalPolicy() == QSizePolicy::Ignored)
s.setHeight(0);
s = s.boundedTo(wid->maximumSize())
.expandedTo(wid->minimumSize());
return s;
}
bool QToolBarAreaLayoutItem::skip() const
{
if (gap)
return false;
return widgetItem == 0 || widgetItem->isEmpty();
}
/******************************************************************************
** QToolBarAreaLayoutLine
*/
QToolBarAreaLayoutLine::QToolBarAreaLayoutLine(Qt::Orientation orientation)
: o(orientation)
{
}
QSize QToolBarAreaLayoutLine::sizeHint() const
{
int a = 0, b = 0;
for (int i = 0; i < toolBarItems.count(); ++i) {
const QToolBarAreaLayoutItem &item = toolBarItems.at(i);
if (item.skip())
continue;
QSize sh = item.sizeHint();
a += item.preferredSize > 0 ? item.preferredSize : pick(o, sh);
b = qMax(b, perp(o, sh));
}
QSize result;
rpick(o, result) = a;
rperp(o, result) = b;
return result;
}
QSize QToolBarAreaLayoutLine::minimumSize() const
{
int a = 0, b = 0;
for (int i = 0; i < toolBarItems.count(); ++i) {
const QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
QSize ms = item.minimumSize();
a += pick(o, ms);
b = qMax(b, perp(o, ms));
}
QSize result;
rpick(o, result) = a;
rperp(o, result) = b;
return result;
}
void QToolBarAreaLayoutLine::fitLayout()
{
int last = -1;
int min = pick(o, minimumSize());
int space = pick(o, rect.size());
int extra = qMax(0, space - min);
for (int i = 0; i < toolBarItems.count(); ++i) {
QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
if (QToolBarLayout *tblayout = qobject_cast<QToolBarLayout*>(item.widgetItem->widget()->layout()))
tblayout->checkUsePopupMenu();
const int itemMin = pick(o, item.minimumSize());
//preferredSize is the default if it is set, otherwise, we take the sizehint
item.size = item.preferredSize > 0 ? item.preferredSize : pick(o, item.sizeHint());
//the extraspace is the space above the item minimum sizehint
const int extraSpace = qMin(item.size - itemMin, extra);
item.size = itemMin + extraSpace; //that is the real size
extra -= extraSpace;
last = i;
}
// calculate the positions from the sizes
int pos = 0;
for (int i = 0; i < toolBarItems.count(); ++i) {
QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
item.pos = pos;
if (i == last) // stretch the last item to the end of the line
item.size = qMax(0, pick(o, rect.size()) - item.pos);
pos += item.size;
}
}
bool QToolBarAreaLayoutLine::skip() const
{
for (int i = 0; i < toolBarItems.count(); ++i) {
if (!toolBarItems.at(i).skip())
return false;
}
return true;
}
/******************************************************************************
** QToolBarAreaLayoutInfo
*/
QToolBarAreaLayoutInfo::QToolBarAreaLayoutInfo(QInternal::DockPosition pos)
: dockPos(pos), dirty(false)
{
switch (pos) {
case QInternal::LeftDock:
case QInternal::RightDock:
o = Qt::Vertical;
break;
case QInternal::TopDock:
case QInternal::BottomDock:
o = Qt::Horizontal;
break;
default:
o = Qt::Horizontal;
break;
}
}
QSize QToolBarAreaLayoutInfo::sizeHint() const
{
int a = 0, b = 0;
for (int i = 0; i < lines.count(); ++i) {
const QToolBarAreaLayoutLine &l = lines.at(i);
if (l.skip())
continue;
QSize hint = l.sizeHint();
a = qMax(a, pick(o, hint));
b += perp(o, hint);
}
QSize result;
rpick(o, result) = a;
rperp(o, result) = b;
return result;
}
QSize QToolBarAreaLayoutInfo::minimumSize() const
{
int a = 0, b = 0;
for (int i = 0; i < lines.count(); ++i) {
const QToolBarAreaLayoutLine &l = lines.at(i);
if (l.skip())
continue;
QSize m = l.minimumSize();
a = qMax(a, pick(o, m));
b += perp(o, m);
}
QSize result;
rpick(o, result) = a;
rperp(o, result) = b;
return result;
}
void QToolBarAreaLayoutInfo::fitLayout()
{
dirty = false;
int b = 0;
bool reverse = dockPos == QInternal::RightDock || dockPos == QInternal::BottomDock;
int i = reverse ? lines.count() - 1 : 0;
for (;;) {
if ((reverse && i < 0) || (!reverse && i == lines.count()))
break;
QToolBarAreaLayoutLine &l = lines[i];
if (!l.skip()) {
if (o == Qt::Horizontal) {
l.rect.setLeft(rect.left());
l.rect.setRight(rect.right());
l.rect.setTop(b + rect.top());
b += l.sizeHint().height();
l.rect.setBottom(b - 1 + rect.top());
} else {
l.rect.setTop(rect.top());
l.rect.setBottom(rect.bottom());
l.rect.setLeft(b + rect.left());
b += l.sizeHint().width();
l.rect.setRight(b - 1 + rect.left());
}
l.fitLayout();
}
i += reverse ? -1 : 1;
}
}
QLayoutItem *QToolBarAreaLayoutInfo::insertToolBar(QToolBar *before, QToolBar *toolBar)
{
toolBar->setOrientation(o);
QLayoutItem *item = new QWidgetItemV2(toolBar);
insertItem(before, item);
return item;
}
void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item)
{
if (before == 0) {
if (lines.isEmpty())
lines.append(QToolBarAreaLayoutLine(o));
lines.last().toolBarItems.append(item);
return;
}
for (int j = 0; j < lines.count(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
line.toolBarItems.insert(k, item);
return;
}
}
}
}
void QToolBarAreaLayoutInfo::removeToolBar(QToolBar *toolBar)
{
for (int j = 0; j < lines.count(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
for (int k = 0; k < line.toolBarItems.count(); ++k) {
QToolBarAreaLayoutItem &item = line.toolBarItems[k];
if (item.widgetItem->widget() == toolBar) {
delete item.widgetItem;
item.widgetItem = 0;
line.toolBarItems.removeAt(k);
if (line.toolBarItems.isEmpty() && j < lines.count() - 1)
lines.removeAt(j);
return;
}
}
}
}
void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before)
{
if (before == 0) {
if (!lines.isEmpty() && lines.last().toolBarItems.isEmpty())
return;
lines.append(QToolBarAreaLayoutLine(o));
return;
}
for (int j = 0; j < lines.count(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
if (k == 0)
return;
QToolBarAreaLayoutLine newLine(o);
newLine.toolBarItems = line.toolBarItems.mid(k);
line.toolBarItems = line.toolBarItems.mid(0, k);
lines.insert(j + 1, newLine);
return;
}
}
}
}
void QToolBarAreaLayoutInfo::removeToolBarBreak(QToolBar *before)
{
for (int j = 0; j < lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
if (k != 0)
return;
if (j == 0)
return;
lines[j - 1].toolBarItems += lines[j].toolBarItems;
lines.removeAt(j);
return;
}
}
}
}
void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos)
{
if (dirty)
fitLayout();
dirty = true;
if (o == Qt::Vertical)
pos -= rect.top();
//here we actually update the preferredSize for the line containing the toolbar so that we move it
for (int j = 0; j < lines.count(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
int previousIndex = -1;
int minPos = 0;
for (int k = 0; k < line.toolBarItems.count(); ++k) {
QToolBarAreaLayoutItem ¤t = line.toolBarItems[k];
if (current.widgetItem->widget() == toolbar) {
int newPos = current.pos;
if (previousIndex >= 0) {
QToolBarAreaLayoutItem &previous = line.toolBarItems[previousIndex];
if (pos < current.pos) {
newPos = qMax(pos, minPos);
} else {
//we check the max value for the position (until everything at the right is "compressed")
int maxPos = pick(o, rect.size());
for(int l = k; l < line.toolBarItems.count(); ++l) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(l);
if (!item.skip()) {
maxPos -= pick(o, item.minimumSize());
}
}
newPos = qMin(pos, maxPos);
}
//extra is the number of pixels to add to the previous toolbar
int extra = newPos - current.pos;
//we check if the previous is near its size hint
//in which case we try to stick to it
const int diff = pick(o, previous.sizeHint()) - (previous.size + extra);
if (qAbs(diff) < QApplication::startDragDistance()) {
//we stick to the default place and size
extra += diff;
}
//update for the current item
current.extendSize(line.o, -extra);
if (extra >= 0) {
previous.extendSize(line.o, extra);
} else {
//we need to push the toolbars on the left starting with previous
extra = -extra; // we just need to know the number of pixels
///at this point we need to get extra pixels from the toolbars at the left
for(int l = previousIndex; l >=0; --l) {
QToolBarAreaLayoutItem &item = line.toolBarItems[l];
if (!item.skip()) {
const int minPreferredSize = pick(o, item.minimumSize());
const int margin = item.size - minPreferredSize;
if (margin < extra) {
item.resize(line.o, minPreferredSize);
extra -= margin;
} else {
item.extendSize(line.o, -extra);
extra = 0;
}
}
}
Q_ASSERT(extra == 0);
}
} else {
//the item is the first one, it should be at position 0
}
return;
} else if (!current.skip()) {
previousIndex = k;
minPos += pick(o, current.minimumSize());
}
}
}
}
QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) const
{
if (rect.contains(pos)) {
// <pos> is in QToolBarAreaLayout coordinates.
// <item.pos> is in local dockarea coordinates (see ~20 lines below)
// Since we're comparing p with item.pos, we put them in the same coordinate system.
const int p = pick(o, pos - rect.topLeft());
for (int j = 0; j < lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = lines.at(j);
if (line.skip())
continue;
if (!line.rect.contains(pos))
continue;
int k = 0;
for (; k < line.toolBarItems.count(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (item.skip())
continue;
int size = qMin(item.size, pick(o, item.sizeHint()));
if (p > item.pos + size)
continue;
if (p > item.pos + size/2)
++k;
break;
}
QList<int> result;
result << j << k;
*minDistance = 0; //we found a perfect match
return result;
}
} else {
const int dist = distance(pos);
//it will only return a path if the minDistance is higher than the current distance
if (dist >= 0 && *minDistance > dist) {
*minDistance = dist;
QList<int> result;
result << lines.count() << 0;
return result;
}
}
return QList<int>();
}
bool QToolBarAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *item)
{
Q_ASSERT(path.count() == 2);
int j = path.first();
if (j == lines.count())
lines.append(QToolBarAreaLayoutLine(o));
QToolBarAreaLayoutLine &line = lines[j];
const int k = path.at(1);
QToolBarAreaLayoutItem gap_item;
gap_item.gap = true;
gap_item.widgetItem = item;
//update the previous item's preferred size
for(int p = k - 1 ; p >= 0; --p) {
QToolBarAreaLayoutItem &previous = line.toolBarItems[p];
if (!previous.skip()) {
//we found the previous one
int previousSizeHint = pick(line.o, previous.sizeHint());
int previousExtraSpace = previous.size - previousSizeHint;
if (previousExtraSpace > 0) {
//in this case we reset the space
previous.preferredSize = -1;
previous.size = previousSizeHint;
gap_item.resize(o, previousExtraSpace);
}
break;
}
}
line.toolBarItems.insert(k, gap_item);
return true;
}
void QToolBarAreaLayoutInfo::clear()
{
lines.clear();
rect = QRect();
}
QRect QToolBarAreaLayoutInfo::itemRect(const QList<int> &path) const
{
Q_ASSERT(path.count() == 2);
int j = path.at(0);
int k = path.at(1);
const QToolBarAreaLayoutLine &line = lines.at(j);
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
QRect result = line.rect;
if (o == Qt::Horizontal) {
result.setLeft(item.pos + line.rect.left());
result.setWidth(item.size);
} else {
result.setTop(item.pos + line.rect.top());
result.setHeight(item.size);
}
return result;
}
int QToolBarAreaLayoutInfo::distance(const QPoint &pos) const
{
switch (dockPos) {
case QInternal::LeftDock:
if (pos.y() < rect.bottom())
return pos.x() - rect.right();
case QInternal::RightDock:
if (pos.y() < rect.bottom())
return rect.left() - pos.x();
case QInternal::TopDock:
if (pos.x() < rect.right())
return pos.y() - rect.bottom();
case QInternal::BottomDock:
if (pos.x() < rect.right())
return rect.top() - pos.y();
default:
break;
}
return -1;
}
/******************************************************************************
** QToolBarAreaLayout
*/
QToolBarAreaLayout::QToolBarAreaLayout(const QMainWindow *win) : mainWindow(win), visible(true)
{
for (int i = 0; i < QInternal::DockCount; ++i) {
QInternal::DockPosition pos = static_cast<QInternal::DockPosition>(i);
docks[i] = QToolBarAreaLayoutInfo(pos);
}
}
QRect QToolBarAreaLayout::fitLayout()
{
if (!visible)
return rect;
QSize left_hint = docks[QInternal::LeftDock].sizeHint();
QSize right_hint = docks[QInternal::RightDock].sizeHint();
QSize top_hint = docks[QInternal::TopDock].sizeHint();
QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
QRect center = rect.adjusted(left_hint.width(), top_hint.height(),
-right_hint.width(), -bottom_hint.height());
docks[QInternal::TopDock].rect = QRect(rect.left(), rect.top(),
rect.width(), top_hint.height());
docks[QInternal::LeftDock].rect = QRect(rect.left(), center.top(),
left_hint.width(), center.height());
docks[QInternal::RightDock].rect = QRect(center.right() + 1, center.top(),
right_hint.width(), center.height());
docks[QInternal::BottomDock].rect = QRect(rect.left(), center.bottom() + 1,
rect.width(), bottom_hint.height());
docks[QInternal::TopDock].fitLayout();
docks[QInternal::LeftDock].fitLayout();
docks[QInternal::RightDock].fitLayout();
docks[QInternal::BottomDock].fitLayout();
return center;
}
QSize QToolBarAreaLayout::minimumSize(const QSize ¢erMin) const
{
if (!visible)
return centerMin;
QSize result = centerMin;
QSize left_min = docks[QInternal::LeftDock].minimumSize();
QSize right_min = docks[QInternal::RightDock].minimumSize();
QSize top_min = docks[QInternal::TopDock].minimumSize();
QSize bottom_min = docks[QInternal::BottomDock].minimumSize();
result.setWidth(qMax(top_min.width(), result.width()));
result.setWidth(qMax(bottom_min.width(), result.width()));
result.setHeight(qMax(left_min.height(), result.height()));
result.setHeight(qMax(right_min.height(), result.height()));
result.rwidth() += left_min.width() + right_min.width();
result.rheight() += top_min.height() + bottom_min.height();
return result;
}
QSize QToolBarAreaLayout::sizeHint(const QSize ¢erHint) const
{
if (!visible)
return centerHint;
QSize result = centerHint;
QSize left_hint = docks[QInternal::LeftDock].sizeHint();
QSize right_hint = docks[QInternal::RightDock].sizeHint();
QSize top_hint = docks[QInternal::TopDock].sizeHint();
QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
result.setWidth(qMax(top_hint.width(), result.width()));
result.setWidth(qMax(bottom_hint.width(), result.width()));
result.setHeight(qMax(left_hint.height(), result.height()));
result.setHeight(qMax(right_hint.height(), result.height()));
result.rwidth() += left_hint.width() + right_hint.width();
result.rheight() += top_hint.height() + bottom_hint.height();
return result;
}
QRect QToolBarAreaLayout::rectHint(const QRect &r) const
{
int coef = visible ? 1 : -1;
QRect result = r;
QSize left_hint = docks[QInternal::LeftDock].sizeHint();
QSize right_hint = docks[QInternal::RightDock].sizeHint();
QSize top_hint = docks[QInternal::TopDock].sizeHint();
QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
result.adjust(-left_hint.width()*coef, -top_hint.height()*coef,
right_hint.width()*coef, bottom_hint.height()*coef);
return result;
}
QLayoutItem *QToolBarAreaLayout::itemAt(int *x, int index) const
{
Q_ASSERT(x != 0);
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if ((*x)++ == index)
return line.toolBarItems.at(k).widgetItem;
}
}
}
return 0;
}
QLayoutItem *QToolBarAreaLayout::takeAt(int *x, int index)
{
Q_ASSERT(x != 0);
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if ((*x)++ == index) {
QLayoutItem *result = line.toolBarItems.takeAt(k).widgetItem;
if (line.toolBarItems.isEmpty())
dock.lines.removeAt(j);
return result;
}
}
}
}
return 0;
}
void QToolBarAreaLayout::deleteAllLayoutItems()
{
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
for (int k = 0; k < line.toolBarItems.count(); ++k) {
QToolBarAreaLayoutItem &item = line.toolBarItems[k];
if (!item.gap)
delete item.widgetItem;
item.widgetItem = 0;
}
}
}
}
QInternal::DockPosition QToolBarAreaLayout::findToolBar(QToolBar *toolBar) const
{
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
return static_cast<QInternal::DockPosition>(i);
}
}
}
return QInternal::DockCount;
}
QLayoutItem *QToolBarAreaLayout::insertToolBar(QToolBar *before, QToolBar *toolBar)
{
QInternal::DockPosition pos = findToolBar(before);
if (pos == QInternal::DockCount)
return 0;
return docks[pos].insertToolBar(before, toolBar);
}
void QToolBarAreaLayout::removeToolBar(QToolBar *toolBar)
{
QInternal::DockPosition pos = findToolBar(toolBar);
if (pos == QInternal::DockCount)
return;
docks[pos].removeToolBar(toolBar);
}
QLayoutItem *QToolBarAreaLayout::addToolBar(QInternal::DockPosition pos, QToolBar *toolBar)
{
return docks[pos].insertToolBar(0, toolBar);
}
void QToolBarAreaLayout::insertToolBarBreak(QToolBar *before)
{
QInternal::DockPosition pos = findToolBar(before);
if (pos == QInternal::DockCount)
return;
docks[pos].insertToolBarBreak(before);
}
void QToolBarAreaLayout::removeToolBarBreak(QToolBar *before)
{
QInternal::DockPosition pos = findToolBar(before);
if (pos == QInternal::DockCount)
return;
docks[pos].removeToolBarBreak(before);
}
void QToolBarAreaLayout::addToolBarBreak(QInternal::DockPosition pos)
{
docks[pos].insertToolBarBreak(0);
}
void QToolBarAreaLayout::moveToolBar(QToolBar *toolbar, int p)
{
QInternal::DockPosition pos = findToolBar(toolbar);
if (pos == QInternal::DockCount)
return;
docks[pos].moveToolBar(toolbar, p);
}
void QToolBarAreaLayout::insertItem(QInternal::DockPosition pos, QLayoutItem *item)
{
if (docks[pos].lines.isEmpty())
docks[pos].lines.append(QToolBarAreaLayoutLine(docks[pos].o));
docks[pos].lines.last().toolBarItems.append(item);
}
void QToolBarAreaLayout::insertItem(QToolBar *before, QLayoutItem *item)
{
QInternal::DockPosition pos = findToolBar(before);
if (pos == QInternal::DockCount)
return;
docks[pos].insertItem(before, item);
}
void QToolBarAreaLayout::apply(bool animate)
{
QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
Q_ASSERT(layout != 0);
Qt::LayoutDirection dir = mainWindow->layoutDirection();
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
if (line.skip())
continue;
for (int k = 0; k < line.toolBarItems.count(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (item.skip() || item.gap)
continue;
QRect geo;
if (visible) {
if (line.o == Qt::Horizontal) {
geo.setTop(line.rect.top());
geo.setBottom(line.rect.bottom());
geo.setLeft(line.rect.left() + item.pos);
geo.setRight(line.rect.left() + item.pos + item.size - 1);
} else {
geo.setLeft(line.rect.left());
geo.setRight(line.rect.right());
geo.setTop(line.rect.top() + item.pos);
geo.setBottom(line.rect.top() + item.pos + item.size - 1);
}
}
QWidget *widget = item.widgetItem->widget();
if (QToolBar *toolBar = qobject_cast<QToolBar*>(widget)) {
QToolBarLayout *tbl = qobject_cast<QToolBarLayout*>(toolBar->layout());
if (tbl->expanded) {
QPoint tr = geo.topRight();
QSize size = tbl->expandedSize(geo.size());
geo.setSize(size);
geo.moveTopRight(tr);
if (geo.bottom() > rect.bottom())
geo.moveBottom(rect.bottom());
if (geo.right() > rect.right())
geo.moveRight(rect.right());
if (geo.left() < 0)
geo.moveLeft(0);
if (geo.top() < 0)
geo.moveTop(0);
}
}
if (visible && dock.o == Qt::Horizontal)
geo = QStyle::visualRect(dir, line.rect, geo);
layout->widgetAnimator.animate(widget, geo, animate);
}
}
}
}
bool QToolBarAreaLayout::toolBarBreak(QToolBar *toolBar) const
{
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
return j > 0 && k == 0;
}
}
}
return false;
}
void QToolBarAreaLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const
{
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) {
if (line.toolBarItems.count() == 1)
option->positionWithinLine = QStyleOptionToolBar::OnlyOne;
else if (k == 0)
option->positionWithinLine = QStyleOptionToolBar::Beginning;
else if (k == line.toolBarItems.count() - 1)
option->positionWithinLine = QStyleOptionToolBar::End;
else
option->positionWithinLine = QStyleOptionToolBar::Middle;
if (dock.lines.count() == 1)
option->positionOfLine = QStyleOptionToolBar::OnlyOne;
else if (j == 0)
option->positionOfLine = QStyleOptionToolBar::Beginning;
else if (j == dock.lines.count() - 1)
option->positionOfLine = QStyleOptionToolBar::End;
else
option->positionOfLine = QStyleOptionToolBar::Middle;
return;
}
}
}
}
}
QList<int> QToolBarAreaLayout::indexOf(QWidget *toolBar) const
{
QList<int> result;
bool found = false;
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
for (int k = 0; k < line.toolBarItems.count(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (!item.gap && item.widgetItem->widget() == toolBar) {
found = true;
result.prepend(k);
break;
}
}
if (found) {
result.prepend(j);
break;
}
}
if (found) {
result.prepend(i);
break;
}
}
return result;
}
//this functions returns the path to the possible gapindex for the position pos
QList<int> QToolBarAreaLayout::gapIndex(const QPoint &pos) const
{
Qt::LayoutDirection dir = mainWindow->layoutDirection();
int minDistance = 80; // when a dock area is empty, how "wide" is it?
QList<int> ret; //return value
for (int i = 0; i < QInternal::DockCount; ++i) {
QPoint p = pos;
if (docks[i].o == Qt::Horizontal)
p = QStyle::visualPos(dir, docks[i].rect, p);
QList<int> result = docks[i].gapIndex(p, &minDistance);
if (!result.isEmpty()) {
result.prepend(i);
ret = result;
}
}
return ret;
}
QList<int> QToolBarAreaLayout::currentGapIndex() const
{
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines[j];
for (int k = 0; k < line.toolBarItems.count(); k++) {
if (line.toolBarItems[k].gap) {
QList<int> result;
result << i << j << k;
return result;
}
}
}
}
return QList<int>();
}
bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item)
{
Q_ASSERT(path.count() == 3);
const int i = path.first();
Q_ASSERT(i >= 0 && i < QInternal::DockCount);
return docks[i].insertGap(path.mid(1), item);
}
void QToolBarAreaLayout::remove(const QList<int> &path)
{
Q_ASSERT(path.count() == 3);
docks[path.at(0)].lines[path.at(1)].toolBarItems.removeAt(path.at(2));
}
void QToolBarAreaLayout::remove(QLayoutItem *item)
{
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
for (int k = 0; k < line.toolBarItems.count(); k++) {
if (line.toolBarItems[k].widgetItem == item) {
line.toolBarItems.removeAt(k);
if (line.toolBarItems.isEmpty())
dock.lines.removeAt(j);
return;
}
}
}
}
}
void QToolBarAreaLayout::clear()
{
for (int i = 0; i < QInternal::DockCount; ++i)
docks[i].clear();
rect = QRect();
}
QToolBarAreaLayoutItem *QToolBarAreaLayout::item(const QList<int> &path)
{
Q_ASSERT(path.count() == 3);
if (path.at(0) < 0 || path.at(0) >= QInternal::DockCount)
return 0;
QToolBarAreaLayoutInfo &info = docks[path.at(0)];
if (path.at(1) < 0 || path.at(1) >= info.lines.count())
return 0;
QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
if (path.at(2) < 0 || path.at(2) >= line.toolBarItems.count())
return 0;
return &(line.toolBarItems[path.at(2)]);
}
QRect QToolBarAreaLayout::itemRect(const QList<int> &path) const
{
const int i = path.first();
QRect r = docks[i].itemRect(path.mid(1));
if (docks[i].o == Qt::Horizontal)
r = QStyle::visualRect(mainWindow->layoutDirection(),
docks[i].rect, r);
return r;
}
QLayoutItem *QToolBarAreaLayout::plug(const QList<int> &path)
{
QToolBarAreaLayoutItem *item = this->item(path);
if (!item) {
qWarning() << Q_FUNC_INFO << "No item at" << path;
return 0;
}
Q_ASSERT(item->gap);
Q_ASSERT(item->widgetItem != 0);
item->gap = false;
return item->widgetItem;
}
QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayout *other)
{
//other needs to be update as well
Q_ASSERT(path.count() == 3);
QToolBarAreaLayoutItem *item = this->item(path);
Q_ASSERT(item);
//update the leading space here
QToolBarAreaLayoutInfo &info = docks[path.at(0)];
QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
if (item->size != pick(line.o, item->realSizeHint())) {
//the item doesn't have its default size
//so we'll give this to the next item
int newExtraSpace = 0;
//let's iterate over the siblings of the current item that pare placed before it
//we need to find just the one before
for (int i = path.at(2) - 1; i >= 0; --i) {
QToolBarAreaLayoutItem &previous = line.toolBarItems[i];
if (!previous.skip()) {
//we need to check if it has a previous element and a next one
//the previous will get its size changed
for (int j = path.at(2) + 1; j < line.toolBarItems.count(); ++j) {
const QToolBarAreaLayoutItem &next = line.toolBarItems.at(j);
if (!next.skip()) {
newExtraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint());
previous.resize(line.o, next.pos - previous.pos);
break;
}
}
break;
}
}
if (other) {
QToolBarAreaLayoutInfo &info = other->docks[path.at(0)];
QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
for (int i = path.at(2) - 1; i >= 0; --i) {
QToolBarAreaLayoutItem &previous = line.toolBarItems[i];
if (!previous.skip()) {
previous.resize(line.o, pick(line.o, previous.sizeHint()) + newExtraSpace);
break;
}
}
}
}
Q_ASSERT(!item->gap);
item->gap = true;
return item->widgetItem;
}
static QRect unpackRect(uint geom0, uint geom1, bool *floating)
{
*floating = geom0 & 1;
if (!*floating)
return QRect();
geom0 >>= 1;
int x = (int)(geom0 & 0x0000ffff) - 0x7FFF;
int y = (int)(geom1 & 0x0000ffff) - 0x7FFF;
geom0 >>= 16;
geom1 >>= 16;
int w = geom0 & 0x0000ffff;
int h = geom1 & 0x0000ffff;
return QRect(x, y, w, h);
}
static void packRect(uint *geom0, uint *geom1, const QRect &rect, bool floating)
{
*geom0 = 0;
*geom1 = 0;
if (!floating)
return;
// The 0x7FFF is half of 0xFFFF. We add it so we can handle negative coordinates on
// dual monitors. It's subtracted when unpacking.
*geom0 |= qMax(0, rect.width()) & 0x0000ffff;
*geom1 |= qMax(0, rect.height()) & 0x0000ffff;
*geom0 <<= 16;
*geom1 <<= 16;
*geom0 |= qMax(0, rect.x() + 0x7FFF) & 0x0000ffff;
*geom1 |= qMax(0, rect.y() + 0x7FFF) & 0x0000ffff;
// yeah, we chop one bit off the width, but it still has a range up to 32512
*geom0 <<= 1;
*geom0 |= 1;
}
void QToolBarAreaLayout::saveState(QDataStream &stream) const
{
// save toolbar state
stream << (uchar) ToolBarStateMarkerEx;
int lineCount = 0;
for (int i = 0; i < QInternal::DockCount; ++i)
lineCount += docks[i].lines.count();
stream << lineCount;
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
for (int j = 0; j < dock.lines.count(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
stream << i << line.toolBarItems.count();
for (int k = 0; k < line.toolBarItems.count(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
QWidget *widget = const_cast<QLayoutItem*>(item.widgetItem)->widget();
QString objectName = widget->objectName();
if (objectName.isEmpty()) {
qWarning("QMainWindow::saveState(): 'objectName' not set for QToolBar %p '%s'",
widget, widget->windowTitle().toLocal8Bit().constData());
}
stream << objectName;
// we store information as:
// 1st bit: 1 if shown
// 2nd bit: 1 if orientation is vertical (default is horizontal)
uchar shownOrientation = (uchar)!widget->isHidden();
if (QToolBar * tb= qobject_cast<QToolBar*>(widget)) {
if (tb->orientation() == Qt::Vertical)
shownOrientation |= 2;
}
stream << shownOrientation;
stream << item.pos;
//we store the preferred size. If the use rdidn't resize the toolbars it will be -1
stream << item.preferredSize;
uint geom0, geom1;
packRect(&geom0, &geom1, widget->geometry(), widget->isWindow());
stream << geom0 << geom1;
}
}
}
}
static inline int getInt(QDataStream &stream)
{
int x;
stream >> x;
return x;
}
bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar*> &_toolBars, uchar tmarker, bool testing)
{
QList<QToolBar*> toolBars = _toolBars;
int lines;
stream >> lines;
for (int j = 0; j < lines; ++j) {
int pos;
stream >> pos;
if (pos < 0 || pos >= QInternal::DockCount)
return false;
int cnt;
stream >> cnt;
QToolBarAreaLayoutInfo &dock = docks[pos];
const bool applyingLayout = !testing;
QToolBarAreaLayoutLine line(dock.o);
for (int k = 0; k < cnt; ++k) {
QToolBarAreaLayoutItem item;
QString objectName;
stream >> objectName;
uchar shown;
stream >> shown;
item.pos = getInt(stream);
item.size = getInt(stream);
/*
4.3.0 added floating toolbars, but failed to add the ability to restore them.
We need to store there geometry (four ints). We cannot change the format in a
patch release (4.3.1) by adding ToolBarStateMarkerEx2 to signal extra data. So
for now we'll pack it in the two legacy ints we no longer used in Qt4.3.0.
In 4.4, we should add ToolBarStateMarkerEx2 and fix this properly.
*/
QRect rect;
bool floating = false;
uint geom0, geom1;
geom0 = getInt(stream);
if (tmarker == ToolBarStateMarkerEx) {
geom1 = getInt(stream);
rect = unpackRect(geom0, geom1, &floating);
}
QToolBar *toolBar = 0;
for (int x = 0; x < toolBars.count(); ++x) {
if (toolBars.at(x)->objectName() == objectName) {
toolBar = toolBars.takeAt(x);
break;
}
}
if (toolBar == 0) {
continue;
}
if (applyingLayout) {
item.widgetItem = new QWidgetItemV2(toolBar);
toolBar->setOrientation(floating ? ((shown & 2) ? Qt::Vertical : Qt::Horizontal) : dock.o);
toolBar->setVisible(shown & 1);
toolBar->d_func()->setWindowState(floating, true, rect);
item.preferredSize = item.size;
line.toolBarItems.append(item);
}
}
if (applyingLayout) {
dock.lines.append(line);
}
}
return stream.status() == QDataStream::Ok;
}
bool QToolBarAreaLayout::isEmpty() const
{
for (int i = 0; i < QInternal::DockCount; ++i) {
if (!docks[i].lines.isEmpty())
return false;
}
return true;
}
QT_END_NAMESPACE
#endif // QT_NO_TOOLBAR
| bsd-3-clause |
iver333/phantomjs | src/qt/qtbase/src/plugins/platforms/qnx/qqnxbuttoneventnotifier.cpp | 84 | 7083 | /***************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqnxbuttoneventnotifier.h"
#include <QtGui/QGuiApplication>
#include <qpa/qwindowsysteminterface.h>
#include <QtCore/QDebug>
#include <QtCore/QMetaEnum>
#include <QtCore/QSocketNotifier>
#include <QtCore/private/qcore_unix_p.h>
#if defined(QQNXBUTTON_DEBUG)
#define qButtonDebug qDebug
#else
#define qButtonDebug QT_NO_QDEBUG_MACRO
#endif
QT_BEGIN_NAMESPACE
static const char *ppsPath = "/pps/system/buttons/status";
static const int ppsBufferSize = 256;
QQnxButtonEventNotifier::QQnxButtonEventNotifier(QObject *parent)
: QObject(parent),
m_fd(-1),
m_readNotifier(0)
{
// Set initial state of buttons to ButtonUp and
// fetch the new button ids
int enumeratorIndex = QQnxButtonEventNotifier::staticMetaObject.indexOfEnumerator(QByteArrayLiteral("ButtonId"));
QMetaEnum enumerator = QQnxButtonEventNotifier::staticMetaObject.enumerator(enumeratorIndex);
for (int buttonId = bid_minus; buttonId < ButtonCount; ++buttonId) {
m_buttonKeys.append(enumerator.valueToKey(buttonId));
m_state[buttonId] = ButtonUp;
}
}
QQnxButtonEventNotifier::~QQnxButtonEventNotifier()
{
close();
}
void QQnxButtonEventNotifier::start()
{
qButtonDebug() << Q_FUNC_INFO << "starting hardware button event processing";
if (m_fd != -1)
return;
// Open the pps interface
errno = 0;
m_fd = qt_safe_open(ppsPath, O_RDONLY);
if (m_fd == -1) {
#if defined(Q_OS_BLACKBERRY) || defined (QQNXBUTTON_DEBUG)
qWarning("QQNX: failed to open buttons pps, errno=%d", errno);
#endif
return;
}
m_readNotifier = new QSocketNotifier(m_fd, QSocketNotifier::Read);
QObject::connect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(updateButtonStates()));
qButtonDebug() << Q_FUNC_INFO << "successfully connected to Navigator. fd =" << m_fd;
}
void QQnxButtonEventNotifier::updateButtonStates()
{
// Allocate buffer for pps data
char buffer[ppsBufferSize];
// Attempt to read pps data
errno = 0;
int bytes = qt_safe_read(m_fd, buffer, ppsBufferSize - 1);
qButtonDebug() << "Read" << bytes << "bytes of data";
if (bytes == -1) {
qWarning("QQNX: failed to read hardware buttons pps object, errno=%d", errno);
return;
}
// We seem to get a spurious read notification after the real one. Ignore it
if (bytes == 0)
return;
// Ensure data is null terminated
buffer[bytes] = '\0';
qButtonDebug() << Q_FUNC_INFO << "received PPS message:\n" << buffer;
// Process received message
QByteArray ppsData = QByteArray::fromRawData(buffer, bytes);
QHash<QByteArray, QByteArray> fields;
if (!parsePPS(ppsData, &fields))
return;
// Update our state and inject key events as needed
for (int buttonId = bid_minus; buttonId < ButtonCount; ++buttonId) {
// Extract the new button state
QByteArray key = m_buttonKeys.at(buttonId);
ButtonState newState = (fields.value(key) == "b_up" ? ButtonUp : ButtonDown);
// If state has changed, update our state and inject a keypress event
if (m_state[buttonId] != newState) {
qButtonDebug() << "Hardware button event: button =" << key << "state =" << fields.value(key);
m_state[buttonId] = newState;
// Is it a key press or key release event?
QEvent::Type type = (newState == ButtonDown) ? QEvent::KeyPress : QEvent::KeyRelease;
Qt::Key key;
switch (buttonId) {
case bid_minus:
key = Qt::Key_VolumeDown;
break;
case bid_playpause:
key = Qt::Key_Play;
break;
case bid_plus:
key = Qt::Key_VolumeUp;
break;
case bid_power:
key = Qt::Key_PowerDown;
break;
default:
qButtonDebug() << "Unknown hardware button";
continue;
}
// No modifiers
Qt::KeyboardModifiers modifier = Qt::NoModifier;
// Post the event
QWindowSystemInterface::handleKeyEvent(QGuiApplication::focusWindow(), type, key, modifier);
}
}
}
void QQnxButtonEventNotifier::close()
{
delete m_readNotifier;
m_readNotifier = 0;
if (m_fd != -1) {
qt_safe_close(m_fd);
m_fd = -1;
}
}
bool QQnxButtonEventNotifier::parsePPS(const QByteArray &ppsData, QHash<QByteArray, QByteArray> *messageFields) const
{
// tokenize pps data into lines
QList<QByteArray> lines = ppsData.split('\n');
// validate pps object
if (lines.size() == 0 || !lines.at(0).contains(QByteArrayLiteral("@status"))) {
qWarning("QQNX: unrecognized pps object, data=%s", ppsData.constData());
return false;
}
// parse pps object attributes and extract values
for (int i = 1; i < lines.size(); i++) {
// tokenize current attribute
const QByteArray &attr = lines.at(i);
qButtonDebug() << Q_FUNC_INFO << "attr=" << attr;
int doubleColon = attr.indexOf(QByteArrayLiteral("::"));
if (doubleColon == -1) {
// abort - malformed attribute
continue;
}
QByteArray key = attr.left(doubleColon);
QByteArray value = attr.mid(doubleColon + 2);
messageFields->insert(key, value);
}
return true;
}
QT_END_NAMESPACE
| bsd-3-clause |
JosefMeixner/opentoonz | thirdparty/superlu/SuperLU_4.1/SRC/sgsrfs.c | 86 | 15129 |
/*! @file sgsrfs.c
* \brief Improves computed solution to a system of inear equations
*
* <pre>
* -- SuperLU routine (version 3.0) --
* Univ. of California Berkeley, Xerox Palo Alto Research Center,
* and Lawrence Berkeley National Lab.
* October 15, 2003
*
* Modified from lapack routine SGERFS
* </pre>
*/
/*
* File name: sgsrfs.c
* History: Modified from lapack routine SGERFS
*/
#include <math.h>
#include "slu_sdefs.h"
/*! \brief
*
* <pre>
* Purpose
* =======
*
* SGSRFS improves the computed solution to a system of linear
* equations and provides error bounds and backward error estimates for
* the solution.
*
* If equilibration was performed, the system becomes:
* (diag(R)*A_original*diag(C)) * X = diag(R)*B_original.
*
* See supermatrix.h for the definition of 'SuperMatrix' structure.
*
* Arguments
* =========
*
* trans (input) trans_t
* Specifies the form of the system of equations:
* = NOTRANS: A * X = B (No transpose)
* = TRANS: A'* X = B (Transpose)
* = CONJ: A**H * X = B (Conjugate transpose)
*
* A (input) SuperMatrix*
* The original matrix A in the system, or the scaled A if
* equilibration was done. The type of A can be:
* Stype = SLU_NC, Dtype = SLU_S, Mtype = SLU_GE.
*
* L (input) SuperMatrix*
* The factor L from the factorization Pr*A*Pc=L*U. Use
* compressed row subscripts storage for supernodes,
* i.e., L has types: Stype = SLU_SC, Dtype = SLU_S, Mtype = SLU_TRLU.
*
* U (input) SuperMatrix*
* The factor U from the factorization Pr*A*Pc=L*U as computed by
* sgstrf(). Use column-wise storage scheme,
* i.e., U has types: Stype = SLU_NC, Dtype = SLU_S, Mtype = SLU_TRU.
*
* perm_c (input) int*, dimension (A->ncol)
* Column permutation vector, which defines the
* permutation matrix Pc; perm_c[i] = j means column i of A is
* in position j in A*Pc.
*
* perm_r (input) int*, dimension (A->nrow)
* Row permutation vector, which defines the permutation matrix Pr;
* perm_r[i] = j means row i of A is in position j in Pr*A.
*
* equed (input) Specifies the form of equilibration that was done.
* = 'N': No equilibration.
* = 'R': Row equilibration, i.e., A was premultiplied by diag(R).
* = 'C': Column equilibration, i.e., A was postmultiplied by
* diag(C).
* = 'B': Both row and column equilibration, i.e., A was replaced
* by diag(R)*A*diag(C).
*
* R (input) float*, dimension (A->nrow)
* The row scale factors for A.
* If equed = 'R' or 'B', A is premultiplied by diag(R).
* If equed = 'N' or 'C', R is not accessed.
*
* C (input) float*, dimension (A->ncol)
* The column scale factors for A.
* If equed = 'C' or 'B', A is postmultiplied by diag(C).
* If equed = 'N' or 'R', C is not accessed.
*
* B (input) SuperMatrix*
* B has types: Stype = SLU_DN, Dtype = SLU_S, Mtype = SLU_GE.
* The right hand side matrix B.
* if equed = 'R' or 'B', B is premultiplied by diag(R).
*
* X (input/output) SuperMatrix*
* X has types: Stype = SLU_DN, Dtype = SLU_S, Mtype = SLU_GE.
* On entry, the solution matrix X, as computed by sgstrs().
* On exit, the improved solution matrix X.
* if *equed = 'C' or 'B', X should be premultiplied by diag(C)
* in order to obtain the solution to the original system.
*
* FERR (output) float*, dimension (B->ncol)
* The estimated forward error bound for each solution vector
* X(j) (the j-th column of the solution matrix X).
* If XTRUE is the true solution corresponding to X(j), FERR(j)
* is an estimated upper bound for the magnitude of the largest
* element in (X(j) - XTRUE) divided by the magnitude of the
* largest element in X(j). The estimate is as reliable as
* the estimate for RCOND, and is almost always a slight
* overestimate of the true error.
*
* BERR (output) float*, dimension (B->ncol)
* The componentwise relative backward error of each solution
* vector X(j) (i.e., the smallest relative change in
* any element of A or B that makes X(j) an exact solution).
*
* stat (output) SuperLUStat_t*
* Record the statistics on runtime and floating-point operation count.
* See util.h for the definition of 'SuperLUStat_t'.
*
* info (output) int*
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
*
* Internal Parameters
* ===================
*
* ITMAX is the maximum number of steps of iterative refinement.
*
* </pre>
*/
void
sgsrfs(trans_t trans, SuperMatrix *A, SuperMatrix *L, SuperMatrix *U,
int *perm_c, int *perm_r, char *equed, float *R, float *C,
SuperMatrix *B, SuperMatrix *X, float *ferr, float *berr,
SuperLUStat_t *stat, int *info)
{
#define ITMAX 5
/* Table of constant values */
int ione = 1;
float ndone = -1.;
float done = 1.;
/* Local variables */
NCformat *Astore;
float *Aval;
SuperMatrix Bjcol;
DNformat *Bstore, *Xstore, *Bjcol_store;
float *Bmat, *Xmat, *Bptr, *Xptr;
int kase;
float safe1, safe2;
int i, j, k, irow, nz, count, notran, rowequ, colequ;
int ldb, ldx, nrhs;
float s, xk, lstres, eps, safmin;
char transc[1];
trans_t transt;
float *work;
float *rwork;
int *iwork;
extern int slacon_(int *, float *, float *, int *, float *, int *);
#ifdef _CRAY
extern int SCOPY(int *, float *, int *, float *, int *);
extern int SSAXPY(int *, float *, float *, int *, float *, int *);
#else
extern int scopy_(int *, float *, int *, float *, int *);
extern int saxpy_(int *, float *, float *, int *, float *, int *);
#endif
Astore = A->Store;
Aval = Astore->nzval;
Bstore = B->Store;
Xstore = X->Store;
Bmat = Bstore->nzval;
Xmat = Xstore->nzval;
ldb = Bstore->lda;
ldx = Xstore->lda;
nrhs = B->ncol;
/* Test the input parameters */
*info = 0;
notran = (trans == NOTRANS);
if ( !notran && trans != TRANS && trans != CONJ ) *info = -1;
else if ( A->nrow != A->ncol || A->nrow < 0 ||
A->Stype != SLU_NC || A->Dtype != SLU_S || A->Mtype != SLU_GE )
*info = -2;
else if ( L->nrow != L->ncol || L->nrow < 0 ||
L->Stype != SLU_SC || L->Dtype != SLU_S || L->Mtype != SLU_TRLU )
*info = -3;
else if ( U->nrow != U->ncol || U->nrow < 0 ||
U->Stype != SLU_NC || U->Dtype != SLU_S || U->Mtype != SLU_TRU )
*info = -4;
else if ( ldb < SUPERLU_MAX(0, A->nrow) ||
B->Stype != SLU_DN || B->Dtype != SLU_S || B->Mtype != SLU_GE )
*info = -10;
else if ( ldx < SUPERLU_MAX(0, A->nrow) ||
X->Stype != SLU_DN || X->Dtype != SLU_S || X->Mtype != SLU_GE )
*info = -11;
if (*info != 0) {
i = -(*info);
xerbla_("sgsrfs", &i);
return;
}
/* Quick return if possible */
if ( A->nrow == 0 || nrhs == 0) {
for (j = 0; j < nrhs; ++j) {
ferr[j] = 0.;
berr[j] = 0.;
}
return;
}
rowequ = lsame_(equed, "R") || lsame_(equed, "B");
colequ = lsame_(equed, "C") || lsame_(equed, "B");
/* Allocate working space */
work = floatMalloc(2*A->nrow);
rwork = (float *) SUPERLU_MALLOC( A->nrow * sizeof(float) );
iwork = intMalloc(2*A->nrow);
if ( !work || !rwork || !iwork )
ABORT("Malloc fails for work/rwork/iwork.");
if ( notran ) {
*(unsigned char *)transc = 'N';
transt = TRANS;
} else {
*(unsigned char *)transc = 'T';
transt = NOTRANS;
}
/* NZ = maximum number of nonzero elements in each row of A, plus 1 */
nz = A->ncol + 1;
eps = slamch_("Epsilon");
safmin = slamch_("Safe minimum");
/* Set SAFE1 essentially to be the underflow threshold times the
number of additions in each row. */
safe1 = nz * safmin;
safe2 = safe1 / eps;
/* Compute the number of nonzeros in each row (or column) of A */
for (i = 0; i < A->nrow; ++i) iwork[i] = 0;
if ( notran ) {
for (k = 0; k < A->ncol; ++k)
for (i = Astore->colptr[k]; i < Astore->colptr[k+1]; ++i)
++iwork[Astore->rowind[i]];
} else {
for (k = 0; k < A->ncol; ++k)
iwork[k] = Astore->colptr[k+1] - Astore->colptr[k];
}
/* Copy one column of RHS B into Bjcol. */
Bjcol.Stype = B->Stype;
Bjcol.Dtype = B->Dtype;
Bjcol.Mtype = B->Mtype;
Bjcol.nrow = B->nrow;
Bjcol.ncol = 1;
Bjcol.Store = (void *) SUPERLU_MALLOC( sizeof(DNformat) );
if ( !Bjcol.Store ) ABORT("SUPERLU_MALLOC fails for Bjcol.Store");
Bjcol_store = Bjcol.Store;
Bjcol_store->lda = ldb;
Bjcol_store->nzval = work; /* address aliasing */
/* Do for each right hand side ... */
for (j = 0; j < nrhs; ++j) {
count = 0;
lstres = 3.;
Bptr = &Bmat[j*ldb];
Xptr = &Xmat[j*ldx];
while (1) { /* Loop until stopping criterion is satisfied. */
/* Compute residual R = B - op(A) * X,
where op(A) = A, A**T, or A**H, depending on TRANS. */
#ifdef _CRAY
SCOPY(&A->nrow, Bptr, &ione, work, &ione);
#else
scopy_(&A->nrow, Bptr, &ione, work, &ione);
#endif
sp_sgemv(transc, ndone, A, Xptr, ione, done, work, ione);
/* Compute componentwise relative backward error from formula
max(i) ( abs(R(i)) / ( abs(op(A))*abs(X) + abs(B) )(i) )
where abs(Z) is the componentwise absolute value of the matrix
or vector Z. If the i-th component of the denominator is less
than SAFE2, then SAFE1 is added to the i-th component of the
numerator before dividing. */
for (i = 0; i < A->nrow; ++i) rwork[i] = fabs( Bptr[i] );
/* Compute abs(op(A))*abs(X) + abs(B). */
if (notran) {
for (k = 0; k < A->ncol; ++k) {
xk = fabs( Xptr[k] );
for (i = Astore->colptr[k]; i < Astore->colptr[k+1]; ++i)
rwork[Astore->rowind[i]] += fabs(Aval[i]) * xk;
}
} else {
for (k = 0; k < A->ncol; ++k) {
s = 0.;
for (i = Astore->colptr[k]; i < Astore->colptr[k+1]; ++i) {
irow = Astore->rowind[i];
s += fabs(Aval[i]) * fabs(Xptr[irow]);
}
rwork[k] += s;
}
}
s = 0.;
for (i = 0; i < A->nrow; ++i) {
if (rwork[i] > safe2) {
s = SUPERLU_MAX( s, fabs(work[i]) / rwork[i] );
} else if ( rwork[i] != 0.0 ) {
/* Adding SAFE1 to the numerator guards against
spuriously zero residuals (underflow). */
s = SUPERLU_MAX( s, (safe1 + fabs(work[i])) / rwork[i] );
}
/* If rwork[i] is exactly 0.0, then we know the true
residual also must be exactly 0.0. */
}
berr[j] = s;
/* Test stopping criterion. Continue iterating if
1) The residual BERR(J) is larger than machine epsilon, and
2) BERR(J) decreased by at least a factor of 2 during the
last iteration, and
3) At most ITMAX iterations tried. */
if (berr[j] > eps && berr[j] * 2. <= lstres && count < ITMAX) {
/* Update solution and try again. */
sgstrs (trans, L, U, perm_c, perm_r, &Bjcol, stat, info);
#ifdef _CRAY
SAXPY(&A->nrow, &done, work, &ione,
&Xmat[j*ldx], &ione);
#else
saxpy_(&A->nrow, &done, work, &ione,
&Xmat[j*ldx], &ione);
#endif
lstres = berr[j];
++count;
} else {
break;
}
} /* end while */
stat->RefineSteps = count;
/* Bound error from formula:
norm(X - XTRUE) / norm(X) .le. FERR = norm( abs(inv(op(A)))*
( abs(R) + NZ*EPS*( abs(op(A))*abs(X)+abs(B) ))) / norm(X)
where
norm(Z) is the magnitude of the largest component of Z
inv(op(A)) is the inverse of op(A)
abs(Z) is the componentwise absolute value of the matrix or
vector Z
NZ is the maximum number of nonzeros in any row of A, plus 1
EPS is machine epsilon
The i-th component of abs(R)+NZ*EPS*(abs(op(A))*abs(X)+abs(B))
is incremented by SAFE1 if the i-th component of
abs(op(A))*abs(X) + abs(B) is less than SAFE2.
Use SLACON to estimate the infinity-norm of the matrix
inv(op(A)) * diag(W),
where W = abs(R) + NZ*EPS*( abs(op(A))*abs(X)+abs(B) ))) */
for (i = 0; i < A->nrow; ++i) rwork[i] = fabs( Bptr[i] );
/* Compute abs(op(A))*abs(X) + abs(B). */
if ( notran ) {
for (k = 0; k < A->ncol; ++k) {
xk = fabs( Xptr[k] );
for (i = Astore->colptr[k]; i < Astore->colptr[k+1]; ++i)
rwork[Astore->rowind[i]] += fabs(Aval[i]) * xk;
}
} else {
for (k = 0; k < A->ncol; ++k) {
s = 0.;
for (i = Astore->colptr[k]; i < Astore->colptr[k+1]; ++i) {
irow = Astore->rowind[i];
xk = fabs( Xptr[irow] );
s += fabs(Aval[i]) * xk;
}
rwork[k] += s;
}
}
for (i = 0; i < A->nrow; ++i)
if (rwork[i] > safe2)
rwork[i] = fabs(work[i]) + (iwork[i]+1)*eps*rwork[i];
else
rwork[i] = fabs(work[i])+(iwork[i]+1)*eps*rwork[i]+safe1;
kase = 0;
do {
slacon_(&A->nrow, &work[A->nrow], work,
&iwork[A->nrow], &ferr[j], &kase);
if (kase == 0) break;
if (kase == 1) {
/* Multiply by diag(W)*inv(op(A)**T)*(diag(C) or diag(R)). */
if ( notran && colequ )
for (i = 0; i < A->ncol; ++i) work[i] *= C[i];
else if ( !notran && rowequ )
for (i = 0; i < A->nrow; ++i) work[i] *= R[i];
sgstrs (transt, L, U, perm_c, perm_r, &Bjcol, stat, info);
for (i = 0; i < A->nrow; ++i) work[i] *= rwork[i];
} else {
/* Multiply by (diag(C) or diag(R))*inv(op(A))*diag(W). */
for (i = 0; i < A->nrow; ++i) work[i] *= rwork[i];
sgstrs (trans, L, U, perm_c, perm_r, &Bjcol, stat, info);
if ( notran && colequ )
for (i = 0; i < A->ncol; ++i) work[i] *= C[i];
else if ( !notran && rowequ )
for (i = 0; i < A->ncol; ++i) work[i] *= R[i];
}
} while ( kase != 0 );
/* Normalize error. */
lstres = 0.;
if ( notran && colequ ) {
for (i = 0; i < A->nrow; ++i)
lstres = SUPERLU_MAX( lstres, C[i] * fabs( Xptr[i]) );
} else if ( !notran && rowequ ) {
for (i = 0; i < A->nrow; ++i)
lstres = SUPERLU_MAX( lstres, R[i] * fabs( Xptr[i]) );
} else {
for (i = 0; i < A->nrow; ++i)
lstres = SUPERLU_MAX( lstres, fabs( Xptr[i]) );
}
if ( lstres != 0. )
ferr[j] /= lstres;
} /* for each RHS j ... */
SUPERLU_FREE(work);
SUPERLU_FREE(rwork);
SUPERLU_FREE(iwork);
SUPERLU_FREE(Bjcol.Store);
return;
} /* sgsrfs */
| bsd-3-clause |
mydongistiny/external_chromium_org_third_party_skia | samplecode/SampleStringArt.cpp | 89 | 2155 | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkCanvas.h"
// Reproduces https://code.google.com/p/chromium/issues/detail?id=279014
// Renders a string art shape.
// The particular shape rendered can be controlled by clicking horizontally, thereby
// generating an angle from 0 to 1.
class StringArtView : public SampleView {
public:
StringArtView() : fAngle(0.305f) {}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "StringArt");
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual void onDrawContent(SkCanvas* canvas) SK_OVERRIDE {
SkScalar angle = fAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);
SkPoint center = SkPoint::Make(SkScalarHalf(this->width()), SkScalarHalf(this->height()));
SkScalar length = 5;
SkScalar step = angle;
SkPath path;
path.moveTo(center);
while (length < (SkScalarHalf(SkMinScalar(this->width(), this->height())) - 10.f))
{
SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,
length*SkScalarSin(step) + center.fY);
path.lineTo(rp);
length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));
step += angle;
}
path.close();
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(0xFF007700);
canvas->drawPath(path, paint);
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned) SK_OVERRIDE {
fAngle = x/width();
this->inval(NULL);
return NULL;
}
private:
SkScalar fAngle;
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new StringArtView; }
static SkViewRegister reg(MyFactory);
| bsd-3-clause |
Srisai85/scipy | scipy/sparse/linalg/dsolve/SuperLU/SRC/spruneL.c | 92 | 4069 |
/*! @file spruneL.c
* \brief Prunes the L-structure
*
*<pre>
* -- SuperLU routine (version 2.0) --
* Univ. of California Berkeley, Xerox Palo Alto Research Center,
* and Lawrence Berkeley National Lab.
* November 15, 1997
*
* Copyright (c) 1994 by Xerox Corporation. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program for any
* purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is
* granted, provided the above notices are retained, and a notice that
* the code was modified is included with the above copyright notice.
*</pre>
*/
#include "slu_sdefs.h"
/*! \brief
*
* <pre>
* Purpose
* =======
* Prunes the L-structure of supernodes whose L-structure
* contains the current pivot row "pivrow"
* </pre>
*/
void
spruneL(
const int jcol, /* in */
const int *perm_r, /* in */
const int pivrow, /* in */
const int nseg, /* in */
const int *segrep, /* in */
const int *repfnz, /* in */
int *xprune, /* out */
GlobalLU_t *Glu /* modified - global LU data structures */
)
{
float utemp;
int jsupno, irep, irep1, kmin, kmax, krow, movnum;
int i, ktemp, minloc, maxloc;
int do_prune; /* logical variable */
int *xsup, *supno;
int *lsub, *xlsub;
float *lusup;
int *xlusup;
xsup = Glu->xsup;
supno = Glu->supno;
lsub = Glu->lsub;
xlsub = Glu->xlsub;
lusup = Glu->lusup;
xlusup = Glu->xlusup;
/*
* For each supernode-rep irep in U[*,j]
*/
jsupno = supno[jcol];
for (i = 0; i < nseg; i++) {
irep = segrep[i];
irep1 = irep + 1;
do_prune = FALSE;
/* Don't prune with a zero U-segment */
if ( repfnz[irep] == EMPTY )
continue;
/* If a snode overlaps with the next panel, then the U-segment
* is fragmented into two parts -- irep and irep1. We should let
* pruning occur at the rep-column in irep1's snode.
*/
if ( supno[irep] == supno[irep1] ) /* Don't prune */
continue;
/*
* If it has not been pruned & it has a nonz in row L[pivrow,i]
*/
if ( supno[irep] != jsupno ) {
if ( xprune[irep] >= xlsub[irep1] ) {
kmin = xlsub[irep];
kmax = xlsub[irep1] - 1;
for (krow = kmin; krow <= kmax; krow++)
if ( lsub[krow] == pivrow ) {
do_prune = TRUE;
break;
}
}
if ( do_prune ) {
/* Do a quicksort-type partition
* movnum=TRUE means that the num values have to be exchanged.
*/
movnum = FALSE;
if ( irep == xsup[supno[irep]] ) /* Snode of size 1 */
movnum = TRUE;
while ( kmin <= kmax ) {
if ( perm_r[lsub[kmax]] == EMPTY )
kmax--;
else if ( perm_r[lsub[kmin]] != EMPTY )
kmin++;
else { /* kmin below pivrow (not yet pivoted), and kmax
* above pivrow: interchange the two subscripts
*/
ktemp = lsub[kmin];
lsub[kmin] = lsub[kmax];
lsub[kmax] = ktemp;
/* If the supernode has only one column, then we
* only keep one set of subscripts. For any subscript
* interchange performed, similar interchange must be
* done on the numerical values.
*/
if ( movnum ) {
minloc = xlusup[irep] + (kmin - xlsub[irep]);
maxloc = xlusup[irep] + (kmax - xlsub[irep]);
utemp = lusup[minloc];
lusup[minloc] = lusup[maxloc];
lusup[maxloc] = utemp;
}
kmin++;
kmax--;
}
} /* while */
xprune[irep] = kmin; /* Pruning */
#ifdef CHK_PRUNE
printf(" After spruneL(),using col %d: xprune[%d] = %d\n",
jcol, irep, kmin);
#endif
} /* if do_prune */
} /* if */
} /* for each U-segment... */
}
| bsd-3-clause |
jtyuan/racetrack | ext/libelf/gelf_checksum.c | 93 | 1851 | /*-
* Copyright (c) 2006 Joseph Koshy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "gelf.h"
#include "libelf.h"
#include "_libelf.h"
long
elf32_checksum(Elf *e)
{
return (_libelf_checksum(e, ELFCLASS32));
}
long
elf64_checksum(Elf *e)
{
return (_libelf_checksum(e, ELFCLASS64));
}
long
gelf_checksum(Elf *e)
{
int ec;
if (e == NULL ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0L);
}
return (_libelf_checksum(e, ec));
}
| bsd-3-clause |
zhengyongbo/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/graphics/texmap/coordinated/CoordinatedImageBacking.cpp | 112 | 5695 | /*
* Copyright (C) 2012 Company 100, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if USE(COORDINATED_GRAPHICS)
#include "CoordinatedImageBacking.h"
#include "CoordinatedGraphicsState.h"
#include "GraphicsContext.h"
namespace WebCore {
class ImageBackingSurfaceClient : public CoordinatedSurface::Client {
public:
ImageBackingSurfaceClient(Image* image, const IntRect& rect)
: m_image(image)
, m_rect(rect)
{
}
virtual void paintToSurfaceContext(GraphicsContext* context) OVERRIDE
{
context->drawImage(m_image, ColorSpaceDeviceRGB, m_rect, m_rect);
}
private:
Image* m_image;
IntRect m_rect;
};
CoordinatedImageBackingID CoordinatedImageBacking::getCoordinatedImageBackingID(Image* image)
{
// CoordinatedImageBacking keeps a RefPtr<Image> member, so the same Image pointer can not refer two different instances until CoordinatedImageBacking releases the member.
return reinterpret_cast<CoordinatedImageBackingID>(image);
}
PassRefPtr<CoordinatedImageBacking> CoordinatedImageBacking::create(Client* client, PassRefPtr<Image> image)
{
return adoptRef(new CoordinatedImageBacking(client, image));
}
CoordinatedImageBacking::CoordinatedImageBacking(Client* client, PassRefPtr<Image> image)
: m_client(client)
, m_image(image)
, m_id(getCoordinatedImageBackingID(m_image.get()))
, m_clearContentsTimer(this, &CoordinatedImageBacking::clearContentsTimerFired)
, m_isDirty(false)
, m_isVisible(false)
{
// FIXME: We would need to decode a small image directly into a GraphicsSurface.
// http://webkit.org/b/101426
m_client->createImageBacking(id());
}
CoordinatedImageBacking::~CoordinatedImageBacking()
{
}
void CoordinatedImageBacking::addHost(Host* host)
{
ASSERT(!m_hosts.contains(host));
m_hosts.append(host);
}
void CoordinatedImageBacking::removeHost(Host* host)
{
size_t position = m_hosts.find(host);
ASSERT(position != notFound);
m_hosts.remove(position);
if (m_hosts.isEmpty()) {
m_client->removeImageBacking(id());
m_clearContentsTimer.stop();
}
}
void CoordinatedImageBacking::markDirty()
{
m_isDirty = true;
}
void CoordinatedImageBacking::update()
{
releaseSurfaceIfNeeded();
bool changedToVisible;
updateVisibilityIfNeeded(changedToVisible);
if (!m_isVisible)
return;
if (!changedToVisible) {
if (!m_isDirty)
return;
if (m_nativeImagePtr == m_image->nativeImageForCurrentFrame()) {
m_isDirty = false;
return;
}
}
m_surface = CoordinatedSurface::create(m_image->size(), !m_image->currentFrameKnownToBeOpaque() ? CoordinatedSurface::SupportsAlpha : CoordinatedSurface::NoFlags);
if (!m_surface) {
m_isDirty = false;
return;
}
IntRect rect(IntPoint::zero(), m_image->size());
ImageBackingSurfaceClient surfaceClient(m_image.get(), rect);
m_surface->paintToSurface(rect, &surfaceClient);
m_nativeImagePtr = m_image->nativeImageForCurrentFrame();
m_client->updateImageBacking(id(), m_surface);
m_isDirty = false;
}
void CoordinatedImageBacking::releaseSurfaceIfNeeded()
{
// We must keep m_surface until UI Process reads m_surface.
// If m_surface exists, it was created in the previous update.
m_surface.clear();
}
static const double clearContentsTimerInterval = 3;
void CoordinatedImageBacking::updateVisibilityIfNeeded(bool& changedToVisible)
{
bool previousIsVisible = m_isVisible;
m_isVisible = false;
for (size_t i = 0; i < m_hosts.size(); ++i) {
if (m_hosts[i]->imageBackingVisible()) {
m_isVisible = true;
break;
}
}
bool changedToInvisible = previousIsVisible && !m_isVisible;
if (changedToInvisible) {
ASSERT(!m_clearContentsTimer.isActive());
m_clearContentsTimer.startOneShot(clearContentsTimerInterval);
}
changedToVisible = !previousIsVisible && m_isVisible;
if (m_isVisible && m_clearContentsTimer.isActive()) {
m_clearContentsTimer.stop();
// We don't want to update the texture if we didn't remove the texture.
changedToVisible = false;
}
}
void CoordinatedImageBacking::clearContentsTimerFired(Timer<CoordinatedImageBacking>*)
{
m_client->clearImageBackingContents(id());
}
} // namespace WebCore
#endif
| bsd-3-clause |
bakhet/badvpn | lwip/src/core/timers.c | 368 | 14651 | /**
* @file
* Stack-internal timers implementation.
* This file includes timer callbacks for stack-internal timers as well as
* functions to set up or stop timers and check for expired timers.
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
* Simon Goldschmidt
*
*/
#include "lwip/opt.h"
#include "lwip/timers.h"
#include "lwip/tcp_impl.h"
#if LWIP_TIMERS
#include "lwip/def.h"
#include "lwip/memp.h"
#include "lwip/tcpip.h"
#include "lwip/ip_frag.h"
#include "netif/etharp.h"
#include "lwip/dhcp.h"
#include "lwip/autoip.h"
#include "lwip/igmp.h"
#include "lwip/dns.h"
#include "lwip/nd6.h"
#include "lwip/ip6_frag.h"
#include "lwip/mld6.h"
#include "lwip/sys.h"
#include "lwip/pbuf.h"
/** The one and only timeout list */
static struct sys_timeo *next_timeout;
#if NO_SYS
static u32_t timeouts_last_time;
#endif /* NO_SYS */
#if LWIP_TCP
/** global variable that shows if the tcp timer is currently scheduled or not */
static int tcpip_tcp_timer_active;
/**
* Timer callback function that calls tcp_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
tcpip_tcp_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
/* call TCP timer handler */
tcp_tmr();
/* timer still needed? */
if (tcp_active_pcbs || tcp_tw_pcbs) {
/* restart timer */
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
} else {
/* disable timer */
tcpip_tcp_timer_active = 0;
}
}
/**
* Called from TCP_REG when registering a new PCB:
* the reason is to have the TCP timer only running when
* there are active (or time-wait) PCBs.
*/
void
tcp_timer_needed(void)
{
/* timer is off but needed again? */
if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs)) {
/* enable and start timer */
tcpip_tcp_timer_active = 1;
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
}
}
#endif /* LWIP_TCP */
#if IP_REASSEMBLY
/**
* Timer callback function that calls ip_reass_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
ip_reass_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: ip_reass_tmr()\n"));
ip_reass_tmr();
sys_timeout(IP_TMR_INTERVAL, ip_reass_timer, NULL);
}
#endif /* IP_REASSEMBLY */
#if LWIP_ARP
/**
* Timer callback function that calls etharp_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
arp_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: etharp_tmr()\n"));
etharp_tmr();
sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL);
}
#endif /* LWIP_ARP */
#if LWIP_DHCP
/**
* Timer callback function that calls dhcp_coarse_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
dhcp_timer_coarse(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dhcp_coarse_tmr()\n"));
dhcp_coarse_tmr();
sys_timeout(DHCP_COARSE_TIMER_MSECS, dhcp_timer_coarse, NULL);
}
/**
* Timer callback function that calls dhcp_fine_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
dhcp_timer_fine(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dhcp_fine_tmr()\n"));
dhcp_fine_tmr();
sys_timeout(DHCP_FINE_TIMER_MSECS, dhcp_timer_fine, NULL);
}
#endif /* LWIP_DHCP */
#if LWIP_AUTOIP
/**
* Timer callback function that calls autoip_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
autoip_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: autoip_tmr()\n"));
autoip_tmr();
sys_timeout(AUTOIP_TMR_INTERVAL, autoip_timer, NULL);
}
#endif /* LWIP_AUTOIP */
#if LWIP_IGMP
/**
* Timer callback function that calls igmp_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
igmp_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: igmp_tmr()\n"));
igmp_tmr();
sys_timeout(IGMP_TMR_INTERVAL, igmp_timer, NULL);
}
#endif /* LWIP_IGMP */
#if LWIP_DNS
/**
* Timer callback function that calls dns_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
dns_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dns_tmr()\n"));
dns_tmr();
sys_timeout(DNS_TMR_INTERVAL, dns_timer, NULL);
}
#endif /* LWIP_DNS */
#if LWIP_IPV6
/**
* Timer callback function that calls nd6_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
nd6_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: nd6_tmr()\n"));
nd6_tmr();
sys_timeout(ND6_TMR_INTERVAL, nd6_timer, NULL);
}
#if LWIP_IPV6_REASS
/**
* Timer callback function that calls ip6_reass_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
ip6_reass_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: ip6_reass_tmr()\n"));
ip6_reass_tmr();
sys_timeout(IP6_REASS_TMR_INTERVAL, ip6_reass_timer, NULL);
}
#endif /* LWIP_IPV6_REASS */
#if LWIP_IPV6_MLD
/**
* Timer callback function that calls mld6_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
mld6_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: mld6_tmr()\n"));
mld6_tmr();
sys_timeout(MLD6_TMR_INTERVAL, mld6_timer, NULL);
}
#endif /* LWIP_IPV6_MLD */
#endif /* LWIP_IPV6 */
/** Initialize this module */
void sys_timeouts_init(void)
{
#if IP_REASSEMBLY
sys_timeout(IP_TMR_INTERVAL, ip_reass_timer, NULL);
#endif /* IP_REASSEMBLY */
#if LWIP_ARP
sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL);
#endif /* LWIP_ARP */
#if LWIP_DHCP
sys_timeout(DHCP_COARSE_TIMER_MSECS, dhcp_timer_coarse, NULL);
sys_timeout(DHCP_FINE_TIMER_MSECS, dhcp_timer_fine, NULL);
#endif /* LWIP_DHCP */
#if LWIP_AUTOIP
sys_timeout(AUTOIP_TMR_INTERVAL, autoip_timer, NULL);
#endif /* LWIP_AUTOIP */
#if LWIP_IGMP
sys_timeout(IGMP_TMR_INTERVAL, igmp_timer, NULL);
#endif /* LWIP_IGMP */
#if LWIP_DNS
sys_timeout(DNS_TMR_INTERVAL, dns_timer, NULL);
#endif /* LWIP_DNS */
#if LWIP_IPV6
sys_timeout(ND6_TMR_INTERVAL, nd6_timer, NULL);
#if LWIP_IPV6_REASS
sys_timeout(IP6_REASS_TMR_INTERVAL, ip6_reass_timer, NULL);
#endif /* LWIP_IPV6_REASS */
#if LWIP_IPV6_MLD
sys_timeout(MLD6_TMR_INTERVAL, mld6_timer, NULL);
#endif /* LWIP_IPV6_MLD */
#endif /* LWIP_IPV6 */
#if NO_SYS
/* Initialise timestamp for sys_check_timeouts */
timeouts_last_time = sys_now();
#endif
}
/**
* Create a one-shot timer (aka timeout). Timeouts are processed in the
* following cases:
* - while waiting for a message using sys_timeouts_mbox_fetch()
* - by calling sys_check_timeouts() (NO_SYS==1 only)
*
* @param msecs time in milliseconds after that the timer should expire
* @param handler callback function to call when msecs have elapsed
* @param arg argument to pass to the callback function
*/
#if LWIP_DEBUG_TIMERNAMES
void
sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name)
#else /* LWIP_DEBUG_TIMERNAMES */
void
sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg)
#endif /* LWIP_DEBUG_TIMERNAMES */
{
struct sys_timeo *timeout, *t;
timeout = (struct sys_timeo *)memp_malloc(MEMP_SYS_TIMEOUT);
if (timeout == NULL) {
LWIP_ASSERT("sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty", timeout != NULL);
return;
}
timeout->next = NULL;
timeout->h = handler;
timeout->arg = arg;
timeout->time = msecs;
#if LWIP_DEBUG_TIMERNAMES
timeout->handler_name = handler_name;
LWIP_DEBUGF(TIMERS_DEBUG, ("sys_timeout: %p msecs=%"U32_F" handler=%s arg=%p\n",
(void *)timeout, msecs, handler_name, (void *)arg));
#endif /* LWIP_DEBUG_TIMERNAMES */
if (next_timeout == NULL) {
next_timeout = timeout;
return;
}
if (next_timeout->time > msecs) {
next_timeout->time -= msecs;
timeout->next = next_timeout;
next_timeout = timeout;
} else {
for(t = next_timeout; t != NULL; t = t->next) {
timeout->time -= t->time;
if (t->next == NULL || t->next->time > timeout->time) {
if (t->next != NULL) {
t->next->time -= timeout->time;
}
timeout->next = t->next;
t->next = timeout;
break;
}
}
}
}
/**
* Go through timeout list (for this task only) and remove the first matching
* entry, even though the timeout has not triggered yet.
*
* @note This function only works as expected if there is only one timeout
* calling 'handler' in the list of timeouts.
*
* @param handler callback function that would be called by the timeout
* @param arg callback argument that would be passed to handler
*/
void
sys_untimeout(sys_timeout_handler handler, void *arg)
{
struct sys_timeo *prev_t, *t;
if (next_timeout == NULL) {
return;
}
for (t = next_timeout, prev_t = NULL; t != NULL; prev_t = t, t = t->next) {
if ((t->h == handler) && (t->arg == arg)) {
/* We have a match */
/* Unlink from previous in list */
if (prev_t == NULL) {
next_timeout = t->next;
} else {
prev_t->next = t->next;
}
/* If not the last one, add time of this one back to next */
if (t->next != NULL) {
t->next->time += t->time;
}
memp_free(MEMP_SYS_TIMEOUT, t);
return;
}
}
return;
}
#if NO_SYS
/** Handle timeouts for NO_SYS==1 (i.e. without using
* tcpip_thread/sys_timeouts_mbox_fetch(). Uses sys_now() to call timeout
* handler functions when timeouts expire.
*
* Must be called periodically from your main loop.
*/
void
sys_check_timeouts(void)
{
if (next_timeout) {
struct sys_timeo *tmptimeout;
u32_t diff;
sys_timeout_handler handler;
void *arg;
u8_t had_one;
u32_t now;
now = sys_now();
/* this cares for wraparounds */
diff = now - timeouts_last_time;
do
{
#if PBUF_POOL_FREE_OOSEQ
PBUF_CHECK_FREE_OOSEQ();
#endif /* PBUF_POOL_FREE_OOSEQ */
had_one = 0;
tmptimeout = next_timeout;
if (tmptimeout && (tmptimeout->time <= diff)) {
/* timeout has expired */
had_one = 1;
timeouts_last_time = now;
diff -= tmptimeout->time;
next_timeout = tmptimeout->next;
handler = tmptimeout->h;
arg = tmptimeout->arg;
#if LWIP_DEBUG_TIMERNAMES
if (handler != NULL) {
LWIP_DEBUGF(TIMERS_DEBUG, ("sct calling h=%s arg=%p\n",
tmptimeout->handler_name, arg));
}
#endif /* LWIP_DEBUG_TIMERNAMES */
memp_free(MEMP_SYS_TIMEOUT, tmptimeout);
if (handler != NULL) {
handler(arg);
}
}
/* repeat until all expired timers have been called */
}while(had_one);
}
}
/** Set back the timestamp of the last call to sys_check_timeouts()
* This is necessary if sys_check_timeouts() hasn't been called for a long
* time (e.g. while saving energy) to prevent all timer functions of that
* period being called.
*/
void
sys_restart_timeouts(void)
{
timeouts_last_time = sys_now();
}
#else /* NO_SYS */
/**
* Wait (forever) for a message to arrive in an mbox.
* While waiting, timeouts are processed.
*
* @param mbox the mbox to fetch the message from
* @param msg the place to store the message
*/
void
sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg)
{
u32_t time_needed;
struct sys_timeo *tmptimeout;
sys_timeout_handler handler;
void *arg;
again:
if (!next_timeout) {
time_needed = sys_arch_mbox_fetch(mbox, msg, 0);
} else {
if (next_timeout->time > 0) {
time_needed = sys_arch_mbox_fetch(mbox, msg, next_timeout->time);
} else {
time_needed = SYS_ARCH_TIMEOUT;
}
if (time_needed == SYS_ARCH_TIMEOUT) {
/* If time == SYS_ARCH_TIMEOUT, a timeout occured before a message
could be fetched. We should now call the timeout handler and
deallocate the memory allocated for the timeout. */
tmptimeout = next_timeout;
next_timeout = tmptimeout->next;
handler = tmptimeout->h;
arg = tmptimeout->arg;
#if LWIP_DEBUG_TIMERNAMES
if (handler != NULL) {
LWIP_DEBUGF(TIMERS_DEBUG, ("stmf calling h=%s arg=%p\n",
tmptimeout->handler_name, arg));
}
#endif /* LWIP_DEBUG_TIMERNAMES */
memp_free(MEMP_SYS_TIMEOUT, tmptimeout);
if (handler != NULL) {
/* For LWIP_TCPIP_CORE_LOCKING, lock the core before calling the
timeout handler function. */
LOCK_TCPIP_CORE();
handler(arg);
UNLOCK_TCPIP_CORE();
}
LWIP_TCPIP_THREAD_ALIVE();
/* We try again to fetch a message from the mbox. */
goto again;
} else {
/* If time != SYS_ARCH_TIMEOUT, a message was received before the timeout
occured. The time variable is set to the number of
milliseconds we waited for the message. */
if (time_needed < next_timeout->time) {
next_timeout->time -= time_needed;
} else {
next_timeout->time = 0;
}
}
}
}
#endif /* NO_SYS */
#else /* LWIP_TIMERS */
/* Satisfy the TCP code which calls this function */
void
tcp_timer_needed(void)
{
}
#endif /* LWIP_TIMERS */
| bsd-3-clause |
fxtentacle/phantomjs | src/qt/qtwebkit/Source/JavaScriptCore/runtime/SymbolTable.cpp | 113 | 3419 | /*
* Copyright (C) 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSDestructibleObject.h"
#include "JSCellInlines.h"
#include "SymbolTable.h"
namespace JSC {
const ClassInfo SharedSymbolTable::s_info = { "SharedSymbolTable", 0, 0, 0, CREATE_METHOD_TABLE(SharedSymbolTable) };
SymbolTableEntry& SymbolTableEntry::copySlow(const SymbolTableEntry& other)
{
ASSERT(other.isFat());
FatEntry* newFatEntry = new FatEntry(*other.fatEntry());
freeFatEntry();
m_bits = bitwise_cast<intptr_t>(newFatEntry);
return *this;
}
void SharedSymbolTable::destroy(JSCell* cell)
{
SharedSymbolTable* thisObject = jsCast<SharedSymbolTable*>(cell);
thisObject->SharedSymbolTable::~SharedSymbolTable();
}
void SymbolTableEntry::freeFatEntrySlow()
{
ASSERT(isFat());
delete fatEntry();
}
bool SymbolTableEntry::couldBeWatched()
{
if (!isFat())
return false;
WatchpointSet* watchpoints = fatEntry()->m_watchpoints.get();
if (!watchpoints)
return false;
return watchpoints->isStillValid();
}
void SymbolTableEntry::attemptToWatch()
{
FatEntry* entry = inflate();
if (!entry->m_watchpoints)
entry->m_watchpoints = adoptRef(new WatchpointSet(InitializedWatching));
}
bool* SymbolTableEntry::addressOfIsWatched()
{
ASSERT(couldBeWatched());
return fatEntry()->m_watchpoints->addressOfIsWatched();
}
void SymbolTableEntry::addWatchpoint(Watchpoint* watchpoint)
{
ASSERT(couldBeWatched());
fatEntry()->m_watchpoints->add(watchpoint);
}
void SymbolTableEntry::notifyWriteSlow()
{
WatchpointSet* watchpoints = fatEntry()->m_watchpoints.get();
if (!watchpoints)
return;
watchpoints->notifyWrite();
}
SymbolTableEntry::FatEntry* SymbolTableEntry::inflateSlow()
{
FatEntry* entry = new FatEntry(m_bits);
m_bits = bitwise_cast<intptr_t>(entry);
return entry;
}
} // namespace JSC
| bsd-3-clause |
revolutionaryG/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/efl/LocalizedStringsEfl.cpp | 113 | 13181 | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com
* Copyright (C) 2007 Holger Hans Peter Freyther
* Copyright (C) 2008 Christian Dywan <christian@imendio.com>
* Copyright (C) 2008 Nuanti Ltd.
* Copyright (C) 2008 INdT Instituto Nokia de Tecnologia
* Copyright (C) 2009-2010 ProFUSION embedded systems
* Copyright (C) 2009-2010 Samsung Electronics
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "LocalizedStrings.h"
#include "NotImplemented.h"
#include <wtf/text/WTFString.h>
namespace WebCore {
String submitButtonDefaultLabel()
{
return String::fromUTF8("Submit");
}
String inputElementAltText()
{
return String::fromUTF8("Submit");
}
String resetButtonDefaultLabel()
{
return String::fromUTF8("Reset");
}
String defaultDetailsSummaryText()
{
return String::fromUTF8("Details");
}
String searchableIndexIntroduction()
{
return String::fromUTF8("This is a searchable index. Enter search keywords: ");
}
String fileButtonChooseFileLabel()
{
return String::fromUTF8("Choose File");
}
String fileButtonChooseMultipleFilesLabel()
{
return String::fromUTF8("Choose Files");
}
String fileButtonNoFileSelectedLabel()
{
return String::fromUTF8("No file selected");
}
String fileButtonNoFilesSelectedLabel()
{
return String::fromUTF8("No files selected");
}
String contextMenuItemTagOpenLinkInNewWindow()
{
return String::fromUTF8("Open Link in New Window");
}
String contextMenuItemTagDownloadLinkToDisk()
{
return String::fromUTF8("Download Linked File");
}
String contextMenuItemTagCopyLinkToClipboard()
{
return String::fromUTF8("Copy Link Location");
}
String contextMenuItemTagOpenImageInNewWindow()
{
return String::fromUTF8("Open Image in New Window");
}
String contextMenuItemTagDownloadImageToDisk()
{
return String::fromUTF8("Save Image As");
}
String contextMenuItemTagCopyImageToClipboard()
{
return String::fromUTF8("Copy Image");
}
String contextMenuItemTagCopyImageUrlToClipboard()
{
return String::fromUTF8("Copy Image Address");
}
String contextMenuItemTagOpenVideoInNewWindow()
{
return String::fromUTF8("Open Video in New Window");
}
String contextMenuItemTagOpenAudioInNewWindow()
{
return String::fromUTF8("Open Audio in New Window");
}
String contextMenuItemTagDownloadVideoToDisk()
{
return String::fromUTF8("Download Video");
}
String contextMenuItemTagDownloadAudioToDisk()
{
return String::fromUTF8("Download Audio");
}
String contextMenuItemTagCopyVideoLinkToClipboard()
{
return String::fromUTF8("Copy Video Link Location");
}
String contextMenuItemTagCopyAudioLinkToClipboard()
{
return String::fromUTF8("Copy Audio Link Location");
}
String contextMenuItemTagToggleMediaControls()
{
return String::fromUTF8("Toggle Media Controls");
}
String contextMenuItemTagShowMediaControls()
{
return String::fromUTF8("Show Media Controls");
}
String contextMenuitemTagHideMediaControls()
{
return String::fromUTF8("Hide Media Controls");
}
String contextMenuItemTagToggleMediaLoop()
{
return String::fromUTF8("Toggle Media Loop Playback");
}
String contextMenuItemTagEnterVideoFullscreen()
{
return String::fromUTF8("Switch Video to Fullscreen");
}
String contextMenuItemTagMediaPlay()
{
return String::fromUTF8("Play");
}
String contextMenuItemTagMediaPause()
{
return String::fromUTF8("Pause");
}
String contextMenuItemTagMediaMute()
{
return String::fromUTF8("Mute");
}
String contextMenuItemTagOpenFrameInNewWindow()
{
return String::fromUTF8("Open Frame in New Window");
}
String contextMenuItemTagCopy()
{
return String::fromUTF8("Copy");
}
String contextMenuItemTagDelete()
{
return String::fromUTF8("Delete");
}
String contextMenuItemTagSelectAll()
{
return String::fromUTF8("Select All");
}
String contextMenuItemTagUnicode()
{
return String::fromUTF8("Insert Unicode Control Character");
}
String contextMenuItemTagInputMethods()
{
return String::fromUTF8("Input Methods");
}
String contextMenuItemTagGoBack()
{
return String::fromUTF8("Go Back");
}
String contextMenuItemTagGoForward()
{
return String::fromUTF8("Go Forward");
}
String contextMenuItemTagStop()
{
return String::fromUTF8("Stop");
}
String contextMenuItemTagReload()
{
return String::fromUTF8("Reload");
}
String contextMenuItemTagCut()
{
return String::fromUTF8("Cut");
}
String contextMenuItemTagPaste()
{
return String::fromUTF8("Paste");
}
String contextMenuItemTagNoGuessesFound()
{
return String::fromUTF8("No Guesses Found");
}
String contextMenuItemTagIgnoreSpelling()
{
return String::fromUTF8("Ignore Spelling");
}
String contextMenuItemTagLearnSpelling()
{
return String::fromUTF8("Learn Spelling");
}
String contextMenuItemTagSearchWeb()
{
return String::fromUTF8("Search the Web");
}
String contextMenuItemTagLookUpInDictionary(const String&)
{
return String::fromUTF8("Look Up in Dictionary");
}
String contextMenuItemTagOpenLink()
{
return String::fromUTF8("Open Link");
}
String contextMenuItemTagIgnoreGrammar()
{
return String::fromUTF8("Ignore Grammar");
}
String contextMenuItemTagSpellingMenu()
{
return String::fromUTF8("Spelling and Grammar");
}
String contextMenuItemTagShowSpellingPanel(bool show)
{
return String::fromUTF8(show ? "Show Spelling and Grammar" : "Hide Spelling and Grammar");
}
String contextMenuItemTagCheckSpelling()
{
return String::fromUTF8("Check Document Now");
}
String contextMenuItemTagCheckSpellingWhileTyping()
{
return String::fromUTF8("Check Spelling While Typing");
}
String contextMenuItemTagCheckGrammarWithSpelling()
{
return String::fromUTF8("Check Grammar With Spelling");
}
String contextMenuItemTagFontMenu()
{
return String::fromUTF8("Font");
}
String contextMenuItemTagBold()
{
return String::fromUTF8("Bold");
}
String contextMenuItemTagItalic()
{
return String::fromUTF8("Italic");
}
String contextMenuItemTagUnderline()
{
return String::fromUTF8("Underline");
}
String contextMenuItemTagOutline()
{
return String::fromUTF8("Outline");
}
String contextMenuItemTagInspectElement()
{
return String::fromUTF8("Inspect Element");
}
String contextMenuItemTagRightToLeft()
{
return String::fromUTF8("Right to Left");
}
String contextMenuItemTagLeftToRight()
{
return String::fromUTF8("Left to Right");
}
String contextMenuItemTagWritingDirectionMenu()
{
return String::fromUTF8("Writing Direction");
}
String contextMenuItemTagTextDirectionMenu()
{
return String::fromUTF8("Text Direction");
}
String contextMenuItemTagDefaultDirection()
{
return String::fromUTF8("Default");
}
String searchMenuNoRecentSearchesText()
{
return String::fromUTF8("No recent searches");
}
String searchMenuRecentSearchesText()
{
return String::fromUTF8("Recent searches");
}
String searchMenuClearRecentSearchesText()
{
return String::fromUTF8("Clear recent searches");
}
String AXDefinitionText()
{
return String::fromUTF8("definition");
}
String AXDescriptionListText()
{
return String::fromUTF8("description list");
}
String AXDescriptionListTermText()
{
return String::fromUTF8("term");
}
String AXDescriptionListDetailText()
{
return String::fromUTF8("description");
}
String AXFooterRoleDescriptionText()
{
return String::fromUTF8("footer");
}
String AXButtonActionVerb()
{
return String::fromUTF8("press");
}
String AXRadioButtonActionVerb()
{
return String::fromUTF8("select");
}
String AXTextFieldActionVerb()
{
return String::fromUTF8("activate");
}
String AXCheckedCheckBoxActionVerb()
{
return String::fromUTF8("uncheck");
}
String AXUncheckedCheckBoxActionVerb()
{
return String::fromUTF8("check");
}
String AXLinkActionVerb()
{
return String::fromUTF8("jump");
}
String unknownFileSizeText()
{
return String::fromUTF8("Unknown");
}
String imageTitle(const String&, const IntSize&)
{
notImplemented();
return String();
}
String AXListItemActionVerb()
{
notImplemented();
return String();
}
#if ENABLE(VIDEO)
String localizedMediaControlElementString(const String&)
{
notImplemented();
return String();
}
String localizedMediaControlElementHelpText(const String&)
{
notImplemented();
return String();
}
String localizedMediaTimeDescription(float)
{
notImplemented();
return String();
}
#endif
String mediaElementLoadingStateText()
{
return String::fromUTF8("Loading...");
}
String mediaElementLiveBroadcastStateText()
{
return String::fromUTF8("Live Broadcast");
}
String validationMessagePatternMismatchText()
{
return String::fromUTF8("pattern mismatch");
}
String validationMessageRangeOverflowText(const String& maximum)
{
return ASCIILiteral("Value must be less than or equal to ") + maximum;
}
String validationMessageRangeUnderflowText(const String& minimum)
{
return ASCIILiteral("Value must be greater than or equal to ") + minimum;
}
String validationMessageStepMismatchText(const String&, const String&)
{
return String::fromUTF8("step mismatch");
}
String validationMessageTooLongText(int, int)
{
return String::fromUTF8("too long");
}
String validationMessageTypeMismatchText()
{
return String::fromUTF8("type mismatch");
}
String validationMessageTypeMismatchForEmailText()
{
return ASCIILiteral("Please enter an email address");
}
String validationMessageTypeMismatchForMultipleEmailText()
{
return ASCIILiteral("Please enter an email address");
}
String validationMessageTypeMismatchForURLText()
{
return ASCIILiteral("Please enter a URL");
}
String validationMessageValueMissingText()
{
return String::fromUTF8("value missing");
}
String validationMessageValueMissingForCheckboxText()
{
notImplemented();
return validationMessageValueMissingText();
}
String validationMessageValueMissingForFileText()
{
notImplemented();
return validationMessageValueMissingText();
}
String validationMessageValueMissingForMultipleFileText()
{
notImplemented();
return validationMessageValueMissingText();
}
String validationMessageValueMissingForRadioText()
{
notImplemented();
return validationMessageValueMissingText();
}
String validationMessageValueMissingForSelectText()
{
notImplemented();
return validationMessageValueMissingText();
}
String validationMessageBadInputForNumberText()
{
notImplemented();
return validationMessageTypeMismatchText();
}
String missingPluginText()
{
return String::fromUTF8("missing plugin");
}
String AXMenuListPopupActionVerb()
{
return String();
}
String AXMenuListActionVerb()
{
return String();
}
String multipleFileUploadText(unsigned numberOfFiles)
{
return String::number(numberOfFiles) + String::fromUTF8(" files");
}
String crashedPluginText()
{
return String::fromUTF8("plugin crashed");
}
String blockedPluginByContentSecurityPolicyText()
{
notImplemented();
return String();
}
String insecurePluginVersionText()
{
notImplemented();
return String();
}
String inactivePluginText()
{
notImplemented();
return String();
}
String unacceptableTLSCertificate()
{
return String::fromUTF8("Unacceptable TLS certificate");
}
String localizedString(const char* key)
{
return String::fromUTF8(key, strlen(key));
}
#if ENABLE(VIDEO_TRACK)
String textTrackClosedCaptionsText()
{
return String::fromUTF8("Closed Captions");
}
String textTrackSubtitlesText()
{
return String::fromUTF8("Subtitles");
}
String textTrackOffText()
{
return String::fromUTF8("Off");
}
String textTrackNoLabelText()
{
return String::fromUTF8("No label");
}
#endif
String snapshottedPlugInLabelTitle()
{
return String("Snapshotted Plug-In");
}
String snapshottedPlugInLabelSubtitle()
{
return String("Click to restart");
}
}
| bsd-3-clause |
RobertoMalatesta/phantomjs | src/qt/qtwebkit/Source/WTF/wtf/FastMalloc.cpp | 113 | 166170 | // Copyright (c) 2005, 2007, Google Inc.
// All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat <opensource@google.com>
//
// A malloc that uses a per-thread cache to satisfy small malloc requests.
// (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
//
// See doc/tcmalloc.html for a high-level
// description of how this malloc works.
//
// SYNCHRONIZATION
// 1. The thread-specific lists are accessed without acquiring any locks.
// This is safe because each such list is only accessed by one thread.
// 2. We have a lock per central free-list, and hold it while manipulating
// the central free list for a particular size.
// 3. The central page allocator is protected by "pageheap_lock".
// 4. The pagemap (which maps from page-number to descriptor),
// can be read without holding any locks, and written while holding
// the "pageheap_lock".
// 5. To improve performance, a subset of the information one can get
// from the pagemap is cached in a data structure, pagemap_cache_,
// that atomically reads and writes its entries. This cache can be
// read and written without locking.
//
// This multi-threaded access to the pagemap is safe for fairly
// subtle reasons. We basically assume that when an object X is
// allocated by thread A and deallocated by thread B, there must
// have been appropriate synchronization in the handoff of object
// X from thread A to thread B. The same logic applies to pagemap_cache_.
//
// THE PAGEID-TO-SIZECLASS CACHE
// Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
// returns 0 for a particular PageID then that means "no information," not that
// the sizeclass is 0. The cache may have stale information for pages that do
// not hold the beginning of any free()'able object. Staleness is eliminated
// in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
// do_memalign() for all other relevant pages.
//
// TODO: Bias reclamation to larger addresses
// TODO: implement mallinfo/mallopt
// TODO: Better testing
//
// 9/28/2003 (new page-level allocator replaces ptmalloc2):
// * malloc/free of small objects goes from ~300 ns to ~50 ns.
// * allocation of a reasonably complicated struct
// goes from about 1100 ns to about 300 ns.
#include "config.h"
#include "FastMalloc.h"
#include "Assertions.h"
#include "CurrentTime.h"
#include <limits>
#if OS(WINDOWS)
#include <windows.h>
#else
#include <pthread.h>
#endif
#include <string.h>
#include <wtf/StdLibExtras.h>
#if OS(DARWIN)
#include <malloc/malloc.h>
#endif
#ifndef NO_TCMALLOC_SAMPLES
#ifdef WTF_CHANGES
#define NO_TCMALLOC_SAMPLES
#endif
#endif
#if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
#define FORCE_SYSTEM_MALLOC 0
#else
#define FORCE_SYSTEM_MALLOC 1
#endif
// Harden the pointers stored in the TCMalloc linked lists
#if COMPILER(GCC) && !PLATFORM(QT)
#define ENABLE_TCMALLOC_HARDENING 1
#endif
// Use a background thread to periodically scavenge memory to release back to the system
#if PLATFORM(IOS)
#define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
#else
#define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 1
#endif
#ifndef NDEBUG
namespace WTF {
#if OS(WINDOWS)
// TLS_OUT_OF_INDEXES is not defined on WinCE.
#ifndef TLS_OUT_OF_INDEXES
#define TLS_OUT_OF_INDEXES 0xffffffff
#endif
static DWORD isForibiddenTlsIndex = TLS_OUT_OF_INDEXES;
static const LPVOID kTlsAllowValue = reinterpret_cast<LPVOID>(0); // Must be zero.
static const LPVOID kTlsForbiddenValue = reinterpret_cast<LPVOID>(1);
#if !ASSERT_DISABLED
static bool isForbidden()
{
// By default, fastMalloc is allowed so we don't allocate the
// tls index unless we're asked to make it forbidden. If TlsSetValue
// has not been called on a thread, the value returned by TlsGetValue is 0.
return (isForibiddenTlsIndex != TLS_OUT_OF_INDEXES) && (TlsGetValue(isForibiddenTlsIndex) == kTlsForbiddenValue);
}
#endif
void fastMallocForbid()
{
if (isForibiddenTlsIndex == TLS_OUT_OF_INDEXES)
isForibiddenTlsIndex = TlsAlloc(); // a little racey, but close enough for debug only
TlsSetValue(isForibiddenTlsIndex, kTlsForbiddenValue);
}
void fastMallocAllow()
{
if (isForibiddenTlsIndex == TLS_OUT_OF_INDEXES)
return;
TlsSetValue(isForibiddenTlsIndex, kTlsAllowValue);
}
#else // !OS(WINDOWS)
static pthread_key_t isForbiddenKey;
static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
static void initializeIsForbiddenKey()
{
pthread_key_create(&isForbiddenKey, 0);
}
#if !ASSERT_DISABLED
static bool isForbidden()
{
pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
return !!pthread_getspecific(isForbiddenKey);
}
#endif
void fastMallocForbid()
{
pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
pthread_setspecific(isForbiddenKey, &isForbiddenKey);
}
void fastMallocAllow()
{
pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
pthread_setspecific(isForbiddenKey, 0);
}
#endif // OS(WINDOWS)
} // namespace WTF
#endif // NDEBUG
namespace WTF {
namespace Internal {
#if !ENABLE(WTF_MALLOC_VALIDATION)
WTF_EXPORT_PRIVATE void fastMallocMatchFailed(void*);
#else
COMPILE_ASSERT(((sizeof(ValidationHeader) % sizeof(AllocAlignmentInteger)) == 0), ValidationHeader_must_produce_correct_alignment);
#endif
NO_RETURN_DUE_TO_CRASH void fastMallocMatchFailed(void*)
{
CRASH();
}
} // namespace Internal
void* fastZeroedMalloc(size_t n)
{
void* result = fastMalloc(n);
memset(result, 0, n);
return result;
}
char* fastStrDup(const char* src)
{
size_t len = strlen(src) + 1;
char* dup = static_cast<char*>(fastMalloc(len));
memcpy(dup, src, len);
return dup;
}
TryMallocReturnValue tryFastZeroedMalloc(size_t n)
{
void* result;
if (!tryFastMalloc(n).getValue(result))
return 0;
memset(result, 0, n);
return result;
}
} // namespace WTF
#if FORCE_SYSTEM_MALLOC
#if OS(WINDOWS)
#include <malloc.h>
#endif
namespace WTF {
size_t fastMallocGoodSize(size_t bytes)
{
#if OS(DARWIN)
return malloc_good_size(bytes);
#else
return bytes;
#endif
}
TryMallocReturnValue tryFastMalloc(size_t n)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= n) // If overflow would occur...
return 0;
void* result = malloc(n + Internal::ValidationBufferSize);
if (!result)
return 0;
Internal::ValidationHeader* header = static_cast<Internal::ValidationHeader*>(result);
header->m_size = n;
header->m_type = Internal::AllocTypeMalloc;
header->m_prefix = static_cast<unsigned>(Internal::ValidationPrefix);
result = header + 1;
*Internal::fastMallocValidationSuffix(result) = Internal::ValidationSuffix;
fastMallocValidate(result);
return result;
#else
return malloc(n);
#endif
}
void* fastMalloc(size_t n)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
TryMallocReturnValue returnValue = tryFastMalloc(n);
void* result;
if (!returnValue.getValue(result))
CRASH();
#else
void* result = malloc(n);
#endif
if (!result)
CRASH();
return result;
}
TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
size_t totalBytes = n_elements * element_size;
if (n_elements > 1 && element_size && (totalBytes / element_size) != n_elements)
return 0;
TryMallocReturnValue returnValue = tryFastMalloc(totalBytes);
void* result;
if (!returnValue.getValue(result))
return 0;
memset(result, 0, totalBytes);
fastMallocValidate(result);
return result;
#else
return calloc(n_elements, element_size);
#endif
}
void* fastCalloc(size_t n_elements, size_t element_size)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
TryMallocReturnValue returnValue = tryFastCalloc(n_elements, element_size);
void* result;
if (!returnValue.getValue(result))
CRASH();
#else
void* result = calloc(n_elements, element_size);
#endif
if (!result)
CRASH();
return result;
}
void fastFree(void* p)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
if (!p)
return;
fastMallocMatchValidateFree(p, Internal::AllocTypeMalloc);
Internal::ValidationHeader* header = Internal::fastMallocValidationHeader(p);
memset(p, 0xCC, header->m_size);
free(header);
#else
free(p);
#endif
}
TryMallocReturnValue tryFastRealloc(void* p, size_t n)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
if (p) {
if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= n) // If overflow would occur...
return 0;
fastMallocValidate(p);
Internal::ValidationHeader* result = static_cast<Internal::ValidationHeader*>(realloc(Internal::fastMallocValidationHeader(p), n + Internal::ValidationBufferSize));
if (!result)
return 0;
result->m_size = n;
result = result + 1;
*fastMallocValidationSuffix(result) = Internal::ValidationSuffix;
fastMallocValidate(result);
return result;
} else {
return fastMalloc(n);
}
#else
return realloc(p, n);
#endif
}
void* fastRealloc(void* p, size_t n)
{
ASSERT(!isForbidden());
#if ENABLE(WTF_MALLOC_VALIDATION)
TryMallocReturnValue returnValue = tryFastRealloc(p, n);
void* result;
if (!returnValue.getValue(result))
CRASH();
#else
void* result = realloc(p, n);
#endif
if (!result)
CRASH();
return result;
}
void releaseFastMallocFreeMemory() { }
FastMallocStatistics fastMallocStatistics()
{
FastMallocStatistics statistics = { 0, 0, 0 };
return statistics;
}
size_t fastMallocSize(const void* p)
{
#if ENABLE(WTF_MALLOC_VALIDATION)
return Internal::fastMallocValidationHeader(const_cast<void*>(p))->m_size;
#elif OS(DARWIN)
return malloc_size(p);
#elif OS(WINDOWS)
return _msize(const_cast<void*>(p));
#else
UNUSED_PARAM(p);
return 1;
#endif
}
} // namespace WTF
#if OS(DARWIN)
// This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
// It will never be used in this case, so it's type and value are less interesting than its presence.
extern "C" WTF_EXPORT_PRIVATE const int jscore_fastmalloc_introspection = 0;
#endif
#else // FORCE_SYSTEM_MALLOC
#include "TCPackedCache.h"
#include "TCPageMap.h"
#include "TCSpinLock.h"
#include "TCSystemAlloc.h"
#include "ThreadSpecific.h"
#include <algorithm>
#if USE(PTHREADS)
#include <pthread.h>
#endif
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#if HAVE(ERRNO_H)
#include <errno.h>
#endif
#if OS(UNIX)
#include <unistd.h>
#endif
#if OS(WINDOWS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#ifdef WTF_CHANGES
#if OS(DARWIN)
#include <wtf/HashSet.h>
#include <wtf/Vector.h>
#endif
#if HAVE(DISPATCH_H)
#include <dispatch/dispatch.h>
#endif
#ifdef __has_include
#if __has_include(<System/pthread_machdep.h>)
#include <System/pthread_machdep.h>
#if defined(__PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0)
#define WTF_USE_PTHREAD_GETSPECIFIC_DIRECT 1
#endif
#endif
#endif
#ifndef PRIuS
#define PRIuS "zu"
#endif
// Calling pthread_getspecific through a global function pointer is faster than a normal
// call to the function on Mac OS X, and it's used in performance-critical code. So we
// use a function pointer. But that's not necessarily faster on other platforms, and we had
// problems with this technique on Windows, so we'll do this only on Mac OS X.
#if OS(DARWIN)
#if !USE(PTHREAD_GETSPECIFIC_DIRECT)
static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
#define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
#else
#define pthread_getspecific(key) _pthread_getspecific_direct(key)
#define pthread_setspecific(key, val) _pthread_setspecific_direct(key, (val))
#endif
#endif
#define DEFINE_VARIABLE(type, name, value, meaning) \
namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
type FLAGS_##name(value); \
char FLAGS_no##name; \
} \
using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
#define DEFINE_int64(name, value, meaning) \
DEFINE_VARIABLE(int64_t, name, value, meaning)
#define DEFINE_double(name, value, meaning) \
DEFINE_VARIABLE(double, name, value, meaning)
namespace WTF {
#define malloc fastMalloc
#define calloc fastCalloc
#define free fastFree
#define realloc fastRealloc
#define MESSAGE LOG_ERROR
#define CHECK_CONDITION ASSERT
static const char kLLHardeningMask = 0;
template <unsigned> struct EntropySource;
template <> struct EntropySource<4> {
static uint32_t value()
{
#if OS(DARWIN)
return arc4random();
#else
return static_cast<uint32_t>(static_cast<uintptr_t>(currentTime() * 10000) ^ reinterpret_cast<uintptr_t>(&kLLHardeningMask));
#endif
}
};
template <> struct EntropySource<8> {
static uint64_t value()
{
return EntropySource<4>::value() | (static_cast<uint64_t>(EntropySource<4>::value()) << 32);
}
};
#if ENABLE(TCMALLOC_HARDENING)
/*
* To make it harder to exploit use-after free style exploits
* we mask the addresses we put into our linked lists with the
* address of kLLHardeningMask. Due to ASLR the address of
* kLLHardeningMask should be sufficiently randomized to make direct
* freelist manipulation much more difficult.
*/
enum {
MaskKeyShift = 13
};
static ALWAYS_INLINE uintptr_t internalEntropyValue()
{
static uintptr_t value = EntropySource<sizeof(uintptr_t)>::value() | 1;
ASSERT(value);
return value;
}
#define HARDENING_ENTROPY internalEntropyValue()
#define ROTATE_VALUE(value, amount) (((value) >> (amount)) | ((value) << (sizeof(value) * 8 - (amount))))
#define XOR_MASK_PTR_WITH_KEY(ptr, key, entropy) (reinterpret_cast<__typeof__(ptr)>(reinterpret_cast<uintptr_t>(ptr)^(ROTATE_VALUE(reinterpret_cast<uintptr_t>(key), MaskKeyShift)^entropy)))
static ALWAYS_INLINE uint32_t freedObjectStartPoison()
{
static uint32_t value = EntropySource<sizeof(uint32_t)>::value() | 1;
ASSERT(value);
return value;
}
static ALWAYS_INLINE uint32_t freedObjectEndPoison()
{
static uint32_t value = EntropySource<sizeof(uint32_t)>::value() | 1;
ASSERT(value);
return value;
}
#define PTR_TO_UINT32(ptr) static_cast<uint32_t>(reinterpret_cast<uintptr_t>(ptr))
#define END_POISON_INDEX(allocationSize) (((allocationSize) - sizeof(uint32_t)) / sizeof(uint32_t))
#define POISON_ALLOCATION(allocation, allocationSize) do { \
ASSERT((allocationSize) >= 2 * sizeof(uint32_t)); \
reinterpret_cast<uint32_t*>(allocation)[0] = 0xbadbeef1; \
reinterpret_cast<uint32_t*>(allocation)[1] = 0xbadbeef3; \
if ((allocationSize) < 4 * sizeof(uint32_t)) \
break; \
reinterpret_cast<uint32_t*>(allocation)[2] = 0xbadbeef5; \
reinterpret_cast<uint32_t*>(allocation)[END_POISON_INDEX(allocationSize)] = 0xbadbeef7; \
} while (false);
#define POISON_DEALLOCATION_EXPLICIT(allocation, allocationSize, startPoison, endPoison) do { \
ASSERT((allocationSize) >= 2 * sizeof(uint32_t)); \
reinterpret_cast_ptr<uint32_t*>(allocation)[0] = 0xbadbeef9; \
reinterpret_cast_ptr<uint32_t*>(allocation)[1] = 0xbadbeefb; \
if ((allocationSize) < 4 * sizeof(uint32_t)) \
break; \
reinterpret_cast_ptr<uint32_t*>(allocation)[2] = (startPoison) ^ PTR_TO_UINT32(allocation); \
reinterpret_cast_ptr<uint32_t*>(allocation)[END_POISON_INDEX(allocationSize)] = (endPoison) ^ PTR_TO_UINT32(allocation); \
} while (false)
#define POISON_DEALLOCATION(allocation, allocationSize) \
POISON_DEALLOCATION_EXPLICIT(allocation, (allocationSize), freedObjectStartPoison(), freedObjectEndPoison())
#define MAY_BE_POISONED(allocation, allocationSize) (((allocationSize) >= 4 * sizeof(uint32_t)) && ( \
(reinterpret_cast<uint32_t*>(allocation)[2] == (freedObjectStartPoison() ^ PTR_TO_UINT32(allocation))) || \
(reinterpret_cast<uint32_t*>(allocation)[END_POISON_INDEX(allocationSize)] == (freedObjectEndPoison() ^ PTR_TO_UINT32(allocation))) \
))
#define IS_DEFINITELY_POISONED(allocation, allocationSize) (((allocationSize) < 4 * sizeof(uint32_t)) || ( \
(reinterpret_cast<uint32_t*>(allocation)[2] == (freedObjectStartPoison() ^ PTR_TO_UINT32(allocation))) && \
(reinterpret_cast<uint32_t*>(allocation)[END_POISON_INDEX(allocationSize)] == (freedObjectEndPoison() ^ PTR_TO_UINT32(allocation))) \
))
#else
#define POISON_ALLOCATION(allocation, allocationSize)
#define POISON_DEALLOCATION(allocation, allocationSize)
#define POISON_DEALLOCATION_EXPLICIT(allocation, allocationSize, startPoison, endPoison)
#define MAY_BE_POISONED(allocation, allocationSize) (false)
#define IS_DEFINITELY_POISONED(allocation, allocationSize) (true)
#define XOR_MASK_PTR_WITH_KEY(ptr, key, entropy) (((void)entropy), ((void)key), ptr)
#define HARDENING_ENTROPY 0
#endif
//-------------------------------------------------------------------
// Configuration
//-------------------------------------------------------------------
// Not all possible combinations of the following parameters make
// sense. In particular, if kMaxSize increases, you may have to
// increase kNumClasses as well.
#if OS(DARWIN)
# define K_PAGE_SHIFT PAGE_SHIFT
# if (K_PAGE_SHIFT == 12)
# define K_NUM_CLASSES 68
# elif (K_PAGE_SHIFT == 14)
# define K_NUM_CLASSES 77
# else
# error "Unsupported PAGE_SHIFT amount"
# endif
#else
# define K_PAGE_SHIFT 12
# define K_NUM_CLASSES 68
#endif
static const size_t kPageShift = K_PAGE_SHIFT;
static const size_t kPageSize = 1 << kPageShift;
static const size_t kMaxSize = 32u * 1024;
static const size_t kAlignShift = 3;
static const size_t kAlignment = 1 << kAlignShift;
static const size_t kNumClasses = K_NUM_CLASSES;
// Allocates a big block of memory for the pagemap once we reach more than
// 128MB
static const size_t kPageMapBigAllocationThreshold = 128 << 20;
// Minimum number of pages to fetch from system at a time. Must be
// significantly bigger than kPageSize to amortize system-call
// overhead, and also to reduce external fragementation. Also, we
// should keep this value big because various incarnations of Linux
// have small limits on the number of mmap() regions per
// address-space.
static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
// Number of objects to move between a per-thread list and a central
// list in one shot. We want this to be not too small so we can
// amortize the lock overhead for accessing the central list. Making
// it too big may temporarily cause unnecessary memory wastage in the
// per-thread free list until the scavenger cleans up the list.
static int num_objects_to_move[kNumClasses];
// Maximum length we allow a per-thread free-list to have before we
// move objects from it into the corresponding central free-list. We
// want this big to avoid locking the central free-list too often. It
// should not hurt to make this list somewhat big because the
// scavenging code will shrink it down when its contents are not in use.
static const int kMaxFreeListLength = 256;
// Lower and upper bounds on the per-thread cache sizes
static const size_t kMinThreadCacheSize = kMaxSize * 2;
#if PLATFORM(IOS)
static const size_t kMaxThreadCacheSize = 512 * 1024;
#else
static const size_t kMaxThreadCacheSize = 2 << 20;
#endif
// Default bound on the total amount of thread caches
static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
// For all span-lengths < kMaxPages we keep an exact-size list.
// REQUIRED: kMaxPages >= kMinSystemAlloc;
static const size_t kMaxPages = kMinSystemAlloc;
/* The smallest prime > 2^n */
static int primes_list[] = {
// Small values might cause high rates of sampling
// and hence commented out.
// 2, 5, 11, 17, 37, 67, 131, 257,
// 521, 1031, 2053, 4099, 8209, 16411,
32771, 65537, 131101, 262147, 524309, 1048583,
2097169, 4194319, 8388617, 16777259, 33554467 };
// Twice the approximate gap between sampling actions.
// I.e., we take one sample approximately once every
// tcmalloc_sample_parameter/2
// bytes of allocation, i.e., ~ once every 128KB.
// Must be a prime number.
#ifdef NO_TCMALLOC_SAMPLES
DEFINE_int64(tcmalloc_sample_parameter, 0,
"Unused: code is compiled with NO_TCMALLOC_SAMPLES");
static size_t sample_period = 0;
#else
DEFINE_int64(tcmalloc_sample_parameter, 262147,
"Twice the approximate gap between sampling actions."
" Must be a prime number. Otherwise will be rounded up to a "
" larger prime number");
static size_t sample_period = 262147;
#endif
// Protects sample_period above
static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
// Parameters for controlling how fast memory is returned to the OS.
DEFINE_double(tcmalloc_release_rate, 1,
"Rate at which we release unused memory to the system. "
"Zero means we never release memory back to the system. "
"Increase this flag to return memory faster; decrease it "
"to return memory slower. Reasonable rates are in the "
"range [0,10]");
//-------------------------------------------------------------------
// Mapping from size to size_class and vice versa
//-------------------------------------------------------------------
// Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
// array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
// So for these larger sizes we have an array indexed by ceil(size/128).
//
// We flatten both logical arrays into one physical array and use
// arithmetic to compute an appropriate index. The constants used by
// ClassIndex() were selected to make the flattening work.
//
// Examples:
// Size Expression Index
// -------------------------------------------------------
// 0 (0 + 7) / 8 0
// 1 (1 + 7) / 8 1
// ...
// 1024 (1024 + 7) / 8 128
// 1025 (1025 + 127 + (120<<7)) / 128 129
// ...
// 32768 (32768 + 127 + (120<<7)) / 128 376
static const size_t kMaxSmallSize = 1024;
static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
static const int add_amount[2] = { 7, 127 + (120 << 7) };
static unsigned char class_array[377];
// Compute index of the class_array[] entry for a given size
static inline int ClassIndex(size_t s) {
const int i = (s > kMaxSmallSize);
return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
}
// Mapping from size class to max size storable in that class
static size_t class_to_size[kNumClasses];
// Mapping from size class to number of pages to allocate at a time
static size_t class_to_pages[kNumClasses];
// Hardened singly linked list. We make this a class to allow compiler to
// statically prevent mismatching hardened and non-hardened list
class HardenedSLL {
public:
static ALWAYS_INLINE HardenedSLL create(void* value)
{
HardenedSLL result;
result.m_value = value;
return result;
}
static ALWAYS_INLINE HardenedSLL null()
{
HardenedSLL result;
result.m_value = 0;
return result;
}
ALWAYS_INLINE void setValue(void* value) { m_value = value; }
ALWAYS_INLINE void* value() const { return m_value; }
ALWAYS_INLINE bool operator!() const { return !m_value; }
typedef void* (HardenedSLL::*UnspecifiedBoolType);
ALWAYS_INLINE operator UnspecifiedBoolType() const { return m_value ? &HardenedSLL::m_value : 0; }
bool operator!=(const HardenedSLL& other) const { return m_value != other.m_value; }
bool operator==(const HardenedSLL& other) const { return m_value == other.m_value; }
private:
void* m_value;
};
// TransferCache is used to cache transfers of num_objects_to_move[size_class]
// back and forth between thread caches and the central cache for a given size
// class.
struct TCEntry {
HardenedSLL head; // Head of chain of objects.
HardenedSLL tail; // Tail of chain of objects.
};
// A central cache freelist can have anywhere from 0 to kNumTransferEntries
// slots to put link list chains into. To keep memory usage bounded the total
// number of TCEntries across size classes is fixed. Currently each size
// class is initially given one TCEntry which also means that the maximum any
// one class can have is kNumClasses.
static const int kNumTransferEntries = kNumClasses;
// Note: the following only works for "n"s that fit in 32-bits, but
// that is fine since we only use it for small sizes.
static inline int LgFloor(size_t n) {
int log = 0;
for (int i = 4; i >= 0; --i) {
int shift = (1 << i);
size_t x = n >> shift;
if (x != 0) {
n = x;
log += shift;
}
}
ASSERT(n == 1);
return log;
}
// Functions for using our simple hardened singly linked list
static ALWAYS_INLINE HardenedSLL SLL_Next(HardenedSLL t, uintptr_t entropy) {
return HardenedSLL::create(XOR_MASK_PTR_WITH_KEY(*(reinterpret_cast<void**>(t.value())), t.value(), entropy));
}
static ALWAYS_INLINE void SLL_SetNext(HardenedSLL t, HardenedSLL n, uintptr_t entropy) {
*(reinterpret_cast<void**>(t.value())) = XOR_MASK_PTR_WITH_KEY(n.value(), t.value(), entropy);
}
static ALWAYS_INLINE void SLL_Push(HardenedSLL* list, HardenedSLL element, uintptr_t entropy) {
SLL_SetNext(element, *list, entropy);
*list = element;
}
static ALWAYS_INLINE HardenedSLL SLL_Pop(HardenedSLL *list, uintptr_t entropy) {
HardenedSLL result = *list;
*list = SLL_Next(*list, entropy);
return result;
}
// Remove N elements from a linked list to which head points. head will be
// modified to point to the new head. start and end will point to the first
// and last nodes of the range. Note that end will point to NULL after this
// function is called.
static ALWAYS_INLINE void SLL_PopRange(HardenedSLL* head, int N, HardenedSLL *start, HardenedSLL *end, uintptr_t entropy) {
if (N == 0) {
*start = HardenedSLL::null();
*end = HardenedSLL::null();
return;
}
HardenedSLL tmp = *head;
for (int i = 1; i < N; ++i) {
tmp = SLL_Next(tmp, entropy);
}
*start = *head;
*end = tmp;
*head = SLL_Next(tmp, entropy);
// Unlink range from list.
SLL_SetNext(tmp, HardenedSLL::null(), entropy);
}
static ALWAYS_INLINE void SLL_PushRange(HardenedSLL *head, HardenedSLL start, HardenedSLL end, uintptr_t entropy) {
if (!start) return;
SLL_SetNext(end, *head, entropy);
*head = start;
}
static ALWAYS_INLINE size_t SLL_Size(HardenedSLL head, uintptr_t entropy) {
int count = 0;
while (head) {
count++;
head = SLL_Next(head, entropy);
}
return count;
}
// Setup helper functions.
static ALWAYS_INLINE size_t SizeClass(size_t size) {
return class_array[ClassIndex(size)];
}
// Get the byte-size for a specified class
static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
return class_to_size[cl];
}
static int NumMoveSize(size_t size) {
if (size == 0) return 0;
// Use approx 64k transfers between thread and central caches.
int num = static_cast<int>(64.0 * 1024.0 / size);
if (num < 2) num = 2;
// Clamp well below kMaxFreeListLength to avoid ping pong between central
// and thread caches.
if (num > static_cast<int>(0.8 * kMaxFreeListLength))
num = static_cast<int>(0.8 * kMaxFreeListLength);
// Also, avoid bringing in too many objects into small object free
// lists. There are lots of such lists, and if we allow each one to
// fetch too many at a time, we end up having to scavenge too often
// (especially when there are lots of threads and each thread gets a
// small allowance for its thread cache).
//
// TODO: Make thread cache free list sizes dynamic so that we do not
// have to equally divide a fixed resource amongst lots of threads.
if (num > 32) num = 32;
return num;
}
// Initialize the mapping arrays
static void InitSizeClasses() {
// Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
if (ClassIndex(0) < 0) {
MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
CRASH();
}
if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
CRASH();
}
// Compute the size classes we want to use
size_t sc = 1; // Next size class to assign
unsigned char alignshift = kAlignShift;
int last_lg = -1;
for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
int lg = LgFloor(size);
if (lg > last_lg) {
// Increase alignment every so often.
//
// Since we double the alignment every time size doubles and
// size >= 128, this means that space wasted due to alignment is
// at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
// bytes, so the space wasted as a percentage starts falling for
// sizes > 2K.
if ((lg >= 7) && (alignshift < 8)) {
alignshift++;
}
last_lg = lg;
}
// Allocate enough pages so leftover is less than 1/8 of total.
// This bounds wasted space to at most 12.5%.
size_t psize = kPageSize;
while ((psize % size) > (psize >> 3)) {
psize += kPageSize;
}
const size_t my_pages = psize >> kPageShift;
if (sc > 1 && my_pages == class_to_pages[sc-1]) {
// See if we can merge this into the previous class without
// increasing the fragmentation of the previous class.
const size_t my_objects = (my_pages << kPageShift) / size;
const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
/ class_to_size[sc-1];
if (my_objects == prev_objects) {
// Adjust last class to include this size
class_to_size[sc-1] = size;
continue;
}
}
// Add new class
class_to_pages[sc] = my_pages;
class_to_size[sc] = size;
sc++;
}
if (sc != kNumClasses) {
MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
sc, int(kNumClasses));
CRASH();
}
// Initialize the mapping arrays
int next_size = 0;
for (unsigned char c = 1; c < kNumClasses; c++) {
const size_t max_size_in_class = class_to_size[c];
for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
class_array[ClassIndex(s)] = c;
}
next_size = static_cast<int>(max_size_in_class + kAlignment);
}
// Double-check sizes just to be safe
for (size_t size = 0; size <= kMaxSize; size++) {
const size_t sc = SizeClass(size);
if (sc == 0) {
MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
CRASH();
}
if (sc > 1 && size <= class_to_size[sc-1]) {
MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
"\n", sc, size);
CRASH();
}
if (sc >= kNumClasses) {
MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
CRASH();
}
const size_t s = class_to_size[sc];
if (size > s) {
MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
CRASH();
}
if (s == 0) {
MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
CRASH();
}
}
// Initialize the num_objects_to_move array.
for (size_t cl = 1; cl < kNumClasses; ++cl) {
num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
}
#ifndef WTF_CHANGES
if (false) {
// Dump class sizes and maximum external wastage per size class
for (size_t cl = 1; cl < kNumClasses; ++cl) {
const int alloc_size = class_to_pages[cl] << kPageShift;
const int alloc_objs = alloc_size / class_to_size[cl];
const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
const int max_waste = alloc_size - min_used;
MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
int(cl),
int(class_to_size[cl-1] + 1),
int(class_to_size[cl]),
int(class_to_pages[cl] << kPageShift),
max_waste * 100.0 / alloc_size
);
}
}
#endif
}
// -------------------------------------------------------------------------
// Simple allocator for objects of a specified type. External locking
// is required before accessing one of these objects.
// -------------------------------------------------------------------------
// Metadata allocator -- keeps stats about how many bytes allocated
static uint64_t metadata_system_bytes = 0;
static void* MetaDataAlloc(size_t bytes) {
void* result = TCMalloc_SystemAlloc(bytes, 0);
if (result != NULL) {
metadata_system_bytes += bytes;
}
return result;
}
#if defined(WTF_CHANGES) && OS(DARWIN)
class RemoteMemoryReader;
#endif
template <class T>
class PageHeapAllocator {
private:
// How much to allocate from system at a time
static const size_t kAllocIncrement = 32 << 10;
// Aligned size of T
static const size_t kAlignedSize
= (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
// Free area from which to carve new objects
char* free_area_;
size_t free_avail_;
// Linked list of all regions allocated by this allocator
HardenedSLL allocated_regions_;
// Free list of already carved objects
HardenedSLL free_list_;
// Number of allocated but unfreed objects
int inuse_;
uintptr_t entropy_;
public:
void Init(uintptr_t entropy) {
ASSERT(kAlignedSize <= kAllocIncrement);
inuse_ = 0;
allocated_regions_ = HardenedSLL::null();
free_area_ = NULL;
free_avail_ = 0;
free_list_.setValue(NULL);
entropy_ = entropy;
}
T* New() {
// Consult free list
void* result;
if (free_list_) {
result = free_list_.value();
free_list_ = SLL_Next(free_list_, entropy_);
} else {
if (free_avail_ < kAlignedSize) {
// Need more room
char* new_allocation = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
if (!new_allocation)
CRASH();
HardenedSLL new_head = HardenedSLL::create(new_allocation);
SLL_SetNext(new_head, allocated_regions_, entropy_);
allocated_regions_ = new_head;
free_area_ = new_allocation + kAlignedSize;
free_avail_ = kAllocIncrement - kAlignedSize;
}
result = free_area_;
free_area_ += kAlignedSize;
free_avail_ -= kAlignedSize;
}
inuse_++;
return reinterpret_cast<T*>(result);
}
void Delete(T* p) {
HardenedSLL new_head = HardenedSLL::create(p);
SLL_SetNext(new_head, free_list_, entropy_);
free_list_ = new_head;
inuse_--;
}
int inuse() const { return inuse_; }
#if defined(WTF_CHANGES) && OS(DARWIN)
template <typename Recorder>
void recordAdministrativeRegions(Recorder&, const RemoteMemoryReader&);
#endif
};
// -------------------------------------------------------------------------
// Span - a contiguous run of pages
// -------------------------------------------------------------------------
// Type that can hold a page number
typedef uintptr_t PageID;
// Type that can hold the length of a run of pages
typedef uintptr_t Length;
static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
// Convert byte size into pages. This won't overflow, but may return
// an unreasonably large value if bytes is huge enough.
static inline Length pages(size_t bytes) {
return (bytes >> kPageShift) +
((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
}
// Convert a user size into the number of bytes that will actually be
// allocated
static size_t AllocationSize(size_t bytes) {
if (bytes > kMaxSize) {
// Large object: we allocate an integral number of pages
ASSERT(bytes <= (kMaxValidPages << kPageShift));
return pages(bytes) << kPageShift;
} else {
// Small object: find the size class to which it belongs
return ByteSizeForClass(SizeClass(bytes));
}
}
enum {
kSpanCookieBits = 10,
kSpanCookieMask = (1 << 10) - 1,
kSpanThisShift = 7
};
static uint32_t spanValidationCookie;
static uint32_t spanInitializerCookie()
{
static uint32_t value = EntropySource<sizeof(uint32_t)>::value() & kSpanCookieMask;
spanValidationCookie = value;
return value;
}
// Information kept for a span (a contiguous run of pages).
struct Span {
PageID start; // Starting page number
Length length; // Number of pages in span
Span* next(uintptr_t entropy) const { return XOR_MASK_PTR_WITH_KEY(m_next, this, entropy); }
Span* remoteNext(const Span* remoteSpanPointer, uintptr_t entropy) const { return XOR_MASK_PTR_WITH_KEY(m_next, remoteSpanPointer, entropy); }
Span* prev(uintptr_t entropy) const { return XOR_MASK_PTR_WITH_KEY(m_prev, this, entropy); }
void setNext(Span* next, uintptr_t entropy) { m_next = XOR_MASK_PTR_WITH_KEY(next, this, entropy); }
void setPrev(Span* prev, uintptr_t entropy) { m_prev = XOR_MASK_PTR_WITH_KEY(prev, this, entropy); }
private:
Span* m_next; // Used when in link list
Span* m_prev; // Used when in link list
public:
HardenedSLL objects; // Linked list of free objects
unsigned int free : 1; // Is the span free
#ifndef NO_TCMALLOC_SAMPLES
unsigned int sample : 1; // Sampled object?
#endif
unsigned int sizeclass : 8; // Size-class for small objects (or 0)
unsigned int refcount : 11; // Number of non-free objects
bool decommitted : 1;
void initCookie()
{
m_cookie = ((reinterpret_cast<uintptr_t>(this) >> kSpanThisShift) & kSpanCookieMask) ^ spanInitializerCookie();
}
void clearCookie() { m_cookie = 0; }
bool isValid() const
{
return (((reinterpret_cast<uintptr_t>(this) >> kSpanThisShift) & kSpanCookieMask) ^ m_cookie) == spanValidationCookie;
}
private:
uint32_t m_cookie : kSpanCookieBits;
#undef SPAN_HISTORY
#ifdef SPAN_HISTORY
// For debugging, we can keep a log events per span
int nexthistory;
char history[64];
int value[64];
#endif
};
#define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
#ifdef SPAN_HISTORY
void Event(Span* span, char op, int v = 0) {
span->history[span->nexthistory] = op;
span->value[span->nexthistory] = v;
span->nexthistory++;
if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
}
#else
#define Event(s,o,v) ((void) 0)
#endif
// Allocator/deallocator for spans
static PageHeapAllocator<Span> span_allocator;
static Span* NewSpan(PageID p, Length len) {
Span* result = span_allocator.New();
memset(result, 0, sizeof(*result));
result->start = p;
result->length = len;
result->initCookie();
#ifdef SPAN_HISTORY
result->nexthistory = 0;
#endif
return result;
}
static inline void DeleteSpan(Span* span) {
RELEASE_ASSERT(span->isValid());
#ifndef NDEBUG
// In debug mode, trash the contents of deleted Spans
memset(span, 0x3f, sizeof(*span));
#endif
span->clearCookie();
span_allocator.Delete(span);
}
// -------------------------------------------------------------------------
// Doubly linked list of spans.
// -------------------------------------------------------------------------
static inline void DLL_Init(Span* list, uintptr_t entropy) {
list->setNext(list, entropy);
list->setPrev(list, entropy);
}
static inline void DLL_Remove(Span* span, uintptr_t entropy) {
span->prev(entropy)->setNext(span->next(entropy), entropy);
span->next(entropy)->setPrev(span->prev(entropy), entropy);
span->setPrev(NULL, entropy);
span->setNext(NULL, entropy);
}
static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list, uintptr_t entropy) {
return list->next(entropy) == list;
}
static int DLL_Length(const Span* list, uintptr_t entropy) {
int result = 0;
for (Span* s = list->next(entropy); s != list; s = s->next(entropy)) {
result++;
}
return result;
}
#if 0 /* Not needed at the moment -- causes compiler warnings if not used */
static void DLL_Print(const char* label, const Span* list) {
MESSAGE("%-10s %p:", label, list);
for (const Span* s = list->next; s != list; s = s->next) {
MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
}
MESSAGE("\n");
}
#endif
static inline void DLL_Prepend(Span* list, Span* span, uintptr_t entropy) {
span->setNext(list->next(entropy), entropy);
span->setPrev(list, entropy);
list->next(entropy)->setPrev(span, entropy);
list->setNext(span, entropy);
}
//-------------------------------------------------------------------
// Data kept per size-class in central cache
//-------------------------------------------------------------------
class TCMalloc_Central_FreeList {
public:
void Init(size_t cl, uintptr_t entropy);
// These methods all do internal locking.
// Insert the specified range into the central freelist. N is the number of
// elements in the range.
void InsertRange(HardenedSLL start, HardenedSLL end, int N);
// Returns the actual number of fetched elements into N.
void RemoveRange(HardenedSLL* start, HardenedSLL* end, int *N);
// Returns the number of free objects in cache.
size_t length() {
SpinLockHolder h(&lock_);
return counter_;
}
// Returns the number of free objects in the transfer cache.
int tc_length() {
SpinLockHolder h(&lock_);
return used_slots_ * num_objects_to_move[size_class_];
}
#ifdef WTF_CHANGES
template <class Finder, class Reader>
void enumerateFreeObjects(Finder& finder, const Reader& reader, TCMalloc_Central_FreeList* remoteCentralFreeList)
{
{
static const ptrdiff_t emptyOffset = reinterpret_cast<const char*>(&empty_) - reinterpret_cast<const char*>(this);
Span* remoteEmpty = reinterpret_cast<Span*>(reinterpret_cast<char*>(remoteCentralFreeList) + emptyOffset);
Span* remoteSpan = nonempty_.remoteNext(remoteEmpty, entropy_);
for (Span* span = reader(remoteEmpty); span && span != &empty_; remoteSpan = span->remoteNext(remoteSpan, entropy_), span = (remoteSpan ? reader(remoteSpan) : 0))
ASSERT(!span->objects);
}
ASSERT(!nonempty_.objects);
static const ptrdiff_t nonemptyOffset = reinterpret_cast<const char*>(&nonempty_) - reinterpret_cast<const char*>(this);
Span* remoteNonempty = reinterpret_cast<Span*>(reinterpret_cast<char*>(remoteCentralFreeList) + nonemptyOffset);
Span* remoteSpan = nonempty_.remoteNext(remoteNonempty, entropy_);
for (Span* span = reader(remoteSpan); span && remoteSpan != remoteNonempty; remoteSpan = span->remoteNext(remoteSpan, entropy_), span = (remoteSpan ? reader(remoteSpan) : 0)) {
for (HardenedSLL nextObject = span->objects; nextObject; nextObject.setValue(reader.nextEntryInHardenedLinkedList(reinterpret_cast<void**>(nextObject.value()), entropy_))) {
finder.visit(nextObject.value());
}
}
for (int slot = 0; slot < used_slots_; ++slot) {
for (HardenedSLL entry = tc_slots_[slot].head; entry; entry.setValue(reader.nextEntryInHardenedLinkedList(reinterpret_cast<void**>(entry.value()), entropy_)))
finder.visit(entry.value());
}
}
#endif
uintptr_t entropy() const { return entropy_; }
private:
// REQUIRES: lock_ is held
// Remove object from cache and return.
// Return NULL if no free entries in cache.
HardenedSLL FetchFromSpans();
// REQUIRES: lock_ is held
// Remove object from cache and return. Fetches
// from pageheap if cache is empty. Only returns
// NULL on allocation failure.
HardenedSLL FetchFromSpansSafe();
// REQUIRES: lock_ is held
// Release a linked list of objects to spans.
// May temporarily release lock_.
void ReleaseListToSpans(HardenedSLL start);
// REQUIRES: lock_ is held
// Release an object to spans.
// May temporarily release lock_.
ALWAYS_INLINE void ReleaseToSpans(HardenedSLL object);
// REQUIRES: lock_ is held
// Populate cache by fetching from the page heap.
// May temporarily release lock_.
ALWAYS_INLINE void Populate();
// REQUIRES: lock is held.
// Tries to make room for a TCEntry. If the cache is full it will try to
// expand it at the cost of some other cache size. Return false if there is
// no space.
bool MakeCacheSpace();
// REQUIRES: lock_ for locked_size_class is held.
// Picks a "random" size class to steal TCEntry slot from. In reality it
// just iterates over the sizeclasses but does so without taking a lock.
// Returns true on success.
// May temporarily lock a "random" size class.
static ALWAYS_INLINE bool EvictRandomSizeClass(size_t locked_size_class, bool force);
// REQUIRES: lock_ is *not* held.
// Tries to shrink the Cache. If force is true it will relase objects to
// spans if it allows it to shrink the cache. Return false if it failed to
// shrink the cache. Decrements cache_size_ on succeess.
// May temporarily take lock_. If it takes lock_, the locked_size_class
// lock is released to the thread from holding two size class locks
// concurrently which could lead to a deadlock.
bool ShrinkCache(int locked_size_class, bool force);
// This lock protects all the data members. cached_entries and cache_size_
// may be looked at without holding the lock.
SpinLock lock_;
// We keep linked lists of empty and non-empty spans.
size_t size_class_; // My size class
Span empty_; // Dummy header for list of empty spans
Span nonempty_; // Dummy header for list of non-empty spans
size_t counter_; // Number of free objects in cache entry
// Here we reserve space for TCEntry cache slots. Since one size class can
// end up getting all the TCEntries quota in the system we just preallocate
// sufficient number of entries here.
TCEntry tc_slots_[kNumTransferEntries];
// Number of currently used cached entries in tc_slots_. This variable is
// updated under a lock but can be read without one.
int32_t used_slots_;
// The current number of slots for this size class. This is an
// adaptive value that is increased if there is lots of traffic
// on a given size class.
int32_t cache_size_;
uintptr_t entropy_;
};
#if COMPILER(CLANG) && defined(__has_warning)
#pragma clang diagnostic push
#if __has_warning("-Wunused-private-field")
#pragma clang diagnostic ignored "-Wunused-private-field"
#endif
#endif
// Pad each CentralCache object to multiple of 64 bytes
template <size_t SizeToPad>
class TCMalloc_Central_FreeListPadded_Template : public TCMalloc_Central_FreeList {
private:
char pad[64 - SizeToPad];
};
// Zero-size specialization to avoid compiler error when TCMalloc_Central_FreeList happens
// to be exactly 64 bytes.
template <> class TCMalloc_Central_FreeListPadded_Template<0> : public TCMalloc_Central_FreeList {
};
typedef TCMalloc_Central_FreeListPadded_Template<sizeof(TCMalloc_Central_FreeList) % 64> TCMalloc_Central_FreeListPadded;
#if COMPILER(CLANG) && defined(__has_warning)
#pragma clang diagnostic pop
#endif
#if OS(DARWIN)
struct Span;
class TCMalloc_PageHeap;
class TCMalloc_ThreadCache;
template <typename T> class PageHeapAllocator;
class FastMallocZone {
public:
static void init();
static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
static boolean_t check(malloc_zone_t*) { return true; }
static void print(malloc_zone_t*, boolean_t) { }
static void log(malloc_zone_t*, void*) { }
static void forceLock(malloc_zone_t*) { }
static void forceUnlock(malloc_zone_t*) { }
static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
private:
FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*, PageHeapAllocator<Span>*, PageHeapAllocator<TCMalloc_ThreadCache>*);
static size_t size(malloc_zone_t*, const void*);
static void* zoneMalloc(malloc_zone_t*, size_t);
static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
static void zoneFree(malloc_zone_t*, void*);
static void* zoneRealloc(malloc_zone_t*, void*, size_t);
static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
static void zoneDestroy(malloc_zone_t*) { }
malloc_zone_t m_zone;
TCMalloc_PageHeap* m_pageHeap;
TCMalloc_ThreadCache** m_threadHeaps;
TCMalloc_Central_FreeListPadded* m_centralCaches;
PageHeapAllocator<Span>* m_spanAllocator;
PageHeapAllocator<TCMalloc_ThreadCache>* m_pageHeapAllocator;
};
#endif
#endif
#ifndef WTF_CHANGES
// This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
// you're porting to a system where you really can't get a stacktrace.
#ifdef NO_TCMALLOC_SAMPLES
// We use #define so code compiles even if you #include stacktrace.h somehow.
# define GetStackTrace(stack, depth, skip) (0)
#else
# include <google/stacktrace.h>
#endif
#endif
// Even if we have support for thread-local storage in the compiler
// and linker, the OS may not support it. We need to check that at
// runtime. Right now, we have to keep a manual set of "bad" OSes.
#if defined(HAVE_TLS)
static bool kernel_supports_tls = false; // be conservative
static inline bool KernelSupportsTLS() {
return kernel_supports_tls;
}
# if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
static void CheckIfKernelSupportsTLS() {
kernel_supports_tls = false;
}
# else
# include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
static void CheckIfKernelSupportsTLS() {
struct utsname buf;
if (uname(&buf) != 0) { // should be impossible
MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
kernel_supports_tls = false;
} else if (strcasecmp(buf.sysname, "linux") == 0) {
// The linux case: the first kernel to support TLS was 2.6.0
if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
kernel_supports_tls = false;
else if (buf.release[0] == '2' && buf.release[1] == '.' &&
buf.release[2] >= '0' && buf.release[2] < '6' &&
buf.release[3] == '.') // 2.0 - 2.5
kernel_supports_tls = false;
else
kernel_supports_tls = true;
} else { // some other kernel, we'll be optimisitic
kernel_supports_tls = true;
}
// TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
}
# endif // HAVE_DECL_UNAME
#endif // HAVE_TLS
// __THROW is defined in glibc systems. It means, counter-intuitively,
// "This function will never throw an exception." It's an optional
// optimization tool, but we may need to use it to match glibc prototypes.
#ifndef __THROW // I guess we're not on a glibc system
# define __THROW // __THROW is just an optimization, so ok to make it ""
#endif
// -------------------------------------------------------------------------
// Stack traces kept for sampled allocations
// The following state is protected by pageheap_lock_.
// -------------------------------------------------------------------------
// size/depth are made the same size as a pointer so that some generic
// code below can conveniently cast them back and forth to void*.
static const int kMaxStackDepth = 31;
struct StackTrace {
uintptr_t size; // Size of object
uintptr_t depth; // Number of PC values stored in array below
void* stack[kMaxStackDepth];
};
static PageHeapAllocator<StackTrace> stacktrace_allocator;
static Span sampled_objects;
// -------------------------------------------------------------------------
// Map from page-id to per-page data
// -------------------------------------------------------------------------
// We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
// We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
// because sometimes the sizeclass is all the information we need.
// Selector class -- general selector uses 3-level map
template <int BITS> class MapSelector {
public:
typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
typedef PackedCache<BITS, uint64_t> CacheType;
};
#if defined(WTF_CHANGES)
#if CPU(X86_64)
// On all known X86-64 platforms, the upper 16 bits are always unused and therefore
// can be excluded from the PageMap key.
// See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
static const size_t kBitsUnusedOn64Bit = 16;
#else
static const size_t kBitsUnusedOn64Bit = 0;
#endif
// A three-level map for 64-bit machines
template <> class MapSelector<64> {
public:
typedef TCMalloc_PageMap3<64 - kPageShift - kBitsUnusedOn64Bit> Type;
typedef PackedCache<64, uint64_t> CacheType;
};
#endif
// A two-level map for 32-bit machines
template <> class MapSelector<32> {
public:
typedef TCMalloc_PageMap2<32 - kPageShift> Type;
typedef PackedCache<32 - kPageShift, uint16_t> CacheType;
};
// -------------------------------------------------------------------------
// Page-level allocator
// * Eager coalescing
//
// Heap for page-level allocation. We allow allocating and freeing a
// contiguous runs of pages (called a "span").
// -------------------------------------------------------------------------
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// The page heap maintains a free list for spans that are no longer in use by
// the central cache or any thread caches. We use a background thread to
// periodically scan the free list and release a percentage of it back to the OS.
// If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
// background thread:
// - wakes up
// - pauses for kScavengeDelayInSeconds
// - returns to the OS a percentage of the memory that remained unused during
// that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
// The goal of this strategy is to reduce memory pressure in a timely fashion
// while avoiding thrashing the OS allocator.
// Time delay before the page heap scavenger will consider returning pages to
// the OS.
static const int kScavengeDelayInSeconds = 2;
// Approximate percentage of free committed pages to return to the OS in one
// scavenge.
static const float kScavengePercentage = .5f;
// number of span lists to keep spans in when memory is returned.
static const int kMinSpanListsWithSpans = 32;
// Number of free committed pages that we want to keep around. The minimum number of pages used when there
// is 1 span in each of the first kMinSpanListsWithSpans spanlists. Currently 528 pages.
static const size_t kMinimumFreeCommittedPageCount = kMinSpanListsWithSpans * ((1.0f+kMinSpanListsWithSpans) / 2.0f);
#endif
static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
class TCMalloc_PageHeap {
public:
void init();
// Allocate a run of "n" pages. Returns zero if out of memory.
Span* New(Length n);
// Delete the span "[p, p+n-1]".
// REQUIRES: span was returned by earlier call to New() and
// has not yet been deleted.
void Delete(Span* span);
// Mark an allocated span as being used for small objects of the
// specified size-class.
// REQUIRES: span was returned by an earlier call to New()
// and has not yet been deleted.
void RegisterSizeClass(Span* span, size_t sc);
// Split an allocated span into two spans: one of length "n" pages
// followed by another span of length "span->length - n" pages.
// Modifies "*span" to point to the first span of length "n" pages.
// Returns a pointer to the second span.
//
// REQUIRES: "0 < n < span->length"
// REQUIRES: !span->free
// REQUIRES: span->sizeclass == 0
Span* Split(Span* span, Length n);
// Return the descriptor for the specified page.
inline Span* GetDescriptor(PageID p) const {
return reinterpret_cast<Span*>(pagemap_.get(p));
}
#ifdef WTF_CHANGES
inline Span* GetDescriptorEnsureSafe(PageID p)
{
pagemap_.Ensure(p, 1);
return GetDescriptor(p);
}
size_t ReturnedBytes() const;
#endif
// Dump state to stderr
#ifndef WTF_CHANGES
void Dump(TCMalloc_Printer* out);
#endif
// Return number of bytes allocated from system
inline uint64_t SystemBytes() const { return system_bytes_; }
// Return number of free bytes in heap
uint64_t FreeBytes() const {
return (static_cast<uint64_t>(free_pages_) << kPageShift);
}
bool Check();
size_t CheckList(Span* list, Length min_pages, Length max_pages, bool decommitted);
// Release all pages on the free list for reuse by the OS:
void ReleaseFreePages();
void ReleaseFreeList(Span*, Span*);
// Return 0 if we have no information, or else the correct sizeclass for p.
// Reads and writes to pagemap_cache_ do not require locking.
// The entries are 64 bits on 64-bit hardware and 16 bits on
// 32-bit hardware, and we don't mind raciness as long as each read of
// an entry yields a valid entry, not a partially updated entry.
size_t GetSizeClassIfCached(PageID p) const {
return pagemap_cache_.GetOrDefault(p, 0);
}
void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
private:
// Pick the appropriate map and cache types based on pointer size
typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
PageMap pagemap_;
mutable PageMapCache pagemap_cache_;
// We segregate spans of a given size into two circular linked
// lists: one for normal spans, and one for spans whose memory
// has been returned to the system.
struct SpanList {
Span normal;
Span returned;
};
// List of free spans of length >= kMaxPages
SpanList large_;
// Array mapping from span length to a doubly linked list of free spans
SpanList free_[kMaxPages];
// Number of pages kept in free lists
uintptr_t free_pages_;
// Used for hardening
uintptr_t entropy_;
// Bytes allocated from system
uint64_t system_bytes_;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// Number of pages kept in free lists that are still committed.
Length free_committed_pages_;
// Minimum number of free committed pages since last scavenge. (Can be 0 if
// we've committed new pages since the last scavenge.)
Length min_free_committed_pages_since_last_scavenge_;
#endif
bool GrowHeap(Length n);
// REQUIRES span->length >= n
// Remove span from its free list, and move any leftover part of
// span into appropriate free lists. Also update "span" to have
// length exactly "n" and mark it as non-free so it can be returned
// to the client.
//
// "released" is true iff "span" was found on a "returned" list.
void Carve(Span* span, Length n, bool released);
void RecordSpan(Span* span) {
pagemap_.set(span->start, span);
if (span->length > 1) {
pagemap_.set(span->start + span->length - 1, span);
}
}
// Allocate a large span of length == n. If successful, returns a
// span of exactly the specified length. Else, returns NULL.
Span* AllocLarge(Length n);
#if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// Incrementally release some memory to the system.
// IncrementalScavenge(n) is called whenever n pages are freed.
void IncrementalScavenge(Length n);
#endif
// Number of pages to deallocate before doing more scavenging
int64_t scavenge_counter_;
// Index of last free list we scavenged
size_t scavenge_index_;
#if defined(WTF_CHANGES) && OS(DARWIN)
friend class FastMallocZone;
#endif
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
void initializeScavenger();
ALWAYS_INLINE void signalScavenger();
void scavenge();
ALWAYS_INLINE bool shouldScavenge() const;
#if HAVE(DISPATCH_H) || OS(WINDOWS)
void periodicScavenge();
ALWAYS_INLINE bool isScavengerSuspended();
ALWAYS_INLINE void scheduleScavenger();
ALWAYS_INLINE void rescheduleScavenger();
ALWAYS_INLINE void suspendScavenger();
#endif
#if HAVE(DISPATCH_H)
dispatch_queue_t m_scavengeQueue;
dispatch_source_t m_scavengeTimer;
bool m_scavengingSuspended;
#elif OS(WINDOWS)
static void CALLBACK scavengerTimerFired(void*, BOOLEAN);
HANDLE m_scavengeQueueTimer;
#else
static NO_RETURN_WITH_VALUE void* runScavengerThread(void*);
NO_RETURN void scavengerThread();
// Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
// it's blocked waiting for more pages to be deleted.
bool m_scavengeThreadActive;
pthread_mutex_t m_scavengeMutex;
pthread_cond_t m_scavengeCondition;
#endif
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
};
void TCMalloc_PageHeap::init()
{
pagemap_.init(MetaDataAlloc);
pagemap_cache_ = PageMapCache(0);
free_pages_ = 0;
system_bytes_ = 0;
entropy_ = HARDENING_ENTROPY;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
free_committed_pages_ = 0;
min_free_committed_pages_since_last_scavenge_ = 0;
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
scavenge_counter_ = 0;
// Start scavenging at kMaxPages list
scavenge_index_ = kMaxPages-1;
COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
DLL_Init(&large_.normal, entropy_);
DLL_Init(&large_.returned, entropy_);
for (size_t i = 0; i < kMaxPages; i++) {
DLL_Init(&free_[i].normal, entropy_);
DLL_Init(&free_[i].returned, entropy_);
}
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
initializeScavenger();
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
}
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
#if HAVE(DISPATCH_H)
void TCMalloc_PageHeap::initializeScavenger()
{
m_scavengeQueue = dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL);
m_scavengeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, m_scavengeQueue);
uint64_t scavengeDelayInNanoseconds = kScavengeDelayInSeconds * NSEC_PER_SEC;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, scavengeDelayInNanoseconds);
dispatch_source_set_timer(m_scavengeTimer, startTime, scavengeDelayInNanoseconds, scavengeDelayInNanoseconds / 10);
dispatch_source_set_event_handler(m_scavengeTimer, ^{ periodicScavenge(); });
m_scavengingSuspended = true;
}
ALWAYS_INLINE bool TCMalloc_PageHeap::isScavengerSuspended()
{
ASSERT(pageheap_lock.IsHeld());
return m_scavengingSuspended;
}
ALWAYS_INLINE void TCMalloc_PageHeap::scheduleScavenger()
{
ASSERT(pageheap_lock.IsHeld());
m_scavengingSuspended = false;
dispatch_resume(m_scavengeTimer);
}
ALWAYS_INLINE void TCMalloc_PageHeap::rescheduleScavenger()
{
// Nothing to do here for libdispatch.
}
ALWAYS_INLINE void TCMalloc_PageHeap::suspendScavenger()
{
ASSERT(pageheap_lock.IsHeld());
m_scavengingSuspended = true;
dispatch_suspend(m_scavengeTimer);
}
#elif OS(WINDOWS)
void TCMalloc_PageHeap::scavengerTimerFired(void* context, BOOLEAN)
{
static_cast<TCMalloc_PageHeap*>(context)->periodicScavenge();
}
void TCMalloc_PageHeap::initializeScavenger()
{
m_scavengeQueueTimer = 0;
}
ALWAYS_INLINE bool TCMalloc_PageHeap::isScavengerSuspended()
{
ASSERT(pageheap_lock.IsHeld());
return !m_scavengeQueueTimer;
}
ALWAYS_INLINE void TCMalloc_PageHeap::scheduleScavenger()
{
// We need to use WT_EXECUTEONLYONCE here and reschedule the timer, because
// Windows will fire the timer event even when the function is already running.
ASSERT(pageheap_lock.IsHeld());
CreateTimerQueueTimer(&m_scavengeQueueTimer, 0, scavengerTimerFired, this, kScavengeDelayInSeconds * 1000, 0, WT_EXECUTEONLYONCE);
}
ALWAYS_INLINE void TCMalloc_PageHeap::rescheduleScavenger()
{
// We must delete the timer and create it again, because it is not possible to retrigger a timer on Windows.
suspendScavenger();
scheduleScavenger();
}
ALWAYS_INLINE void TCMalloc_PageHeap::suspendScavenger()
{
ASSERT(pageheap_lock.IsHeld());
HANDLE scavengeQueueTimer = m_scavengeQueueTimer;
m_scavengeQueueTimer = 0;
DeleteTimerQueueTimer(0, scavengeQueueTimer, 0);
}
#else
void TCMalloc_PageHeap::initializeScavenger()
{
// Create a non-recursive mutex.
#if !defined(PTHREAD_MUTEX_NORMAL) || PTHREAD_MUTEX_NORMAL == PTHREAD_MUTEX_DEFAULT
pthread_mutex_init(&m_scavengeMutex, 0);
#else
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
pthread_mutex_init(&m_scavengeMutex, &attr);
pthread_mutexattr_destroy(&attr);
#endif
pthread_cond_init(&m_scavengeCondition, 0);
m_scavengeThreadActive = true;
pthread_t thread;
pthread_create(&thread, 0, runScavengerThread, this);
}
void* TCMalloc_PageHeap::runScavengerThread(void* context)
{
static_cast<TCMalloc_PageHeap*>(context)->scavengerThread();
#if (COMPILER(MSVC) || COMPILER(SUNCC))
// Without this, Visual Studio and Sun Studio will complain that this method does not return a value.
return 0;
#endif
}
ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
{
// shouldScavenge() should be called only when the pageheap_lock spinlock is held, additionally,
// m_scavengeThreadActive is only set to false whilst pageheap_lock is held. The caller must ensure this is
// taken prior to calling this method. If the scavenger thread is sleeping and shouldScavenge() indicates there
// is memory to free the scavenger thread is signalled to start.
ASSERT(pageheap_lock.IsHeld());
if (!m_scavengeThreadActive && shouldScavenge())
pthread_cond_signal(&m_scavengeCondition);
}
#endif
void TCMalloc_PageHeap::scavenge()
{
size_t pagesToRelease = min_free_committed_pages_since_last_scavenge_ * kScavengePercentage;
size_t targetPageCount = std::max<size_t>(kMinimumFreeCommittedPageCount, free_committed_pages_ - pagesToRelease);
Length lastFreeCommittedPages = free_committed_pages_;
while (free_committed_pages_ > targetPageCount) {
ASSERT(Check());
for (int i = kMaxPages; i > 0 && free_committed_pages_ >= targetPageCount; i--) {
SpanList* slist = (static_cast<size_t>(i) == kMaxPages) ? &large_ : &free_[i];
// If the span size is bigger than kMinSpanListsWithSpans pages return all the spans in the list, else return all but 1 span.
// Return only 50% of a spanlist at a time so spans of size 1 are not the only ones left.
size_t length = DLL_Length(&slist->normal, entropy_);
size_t numSpansToReturn = (i > kMinSpanListsWithSpans) ? length : length / 2;
for (int j = 0; static_cast<size_t>(j) < numSpansToReturn && !DLL_IsEmpty(&slist->normal, entropy_) && free_committed_pages_ > targetPageCount; j++) {
Span* s = slist->normal.prev(entropy_);
DLL_Remove(s, entropy_);
ASSERT(!s->decommitted);
if (!s->decommitted) {
TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
static_cast<size_t>(s->length << kPageShift));
ASSERT(free_committed_pages_ >= s->length);
free_committed_pages_ -= s->length;
s->decommitted = true;
}
DLL_Prepend(&slist->returned, s, entropy_);
}
}
if (lastFreeCommittedPages == free_committed_pages_)
break;
lastFreeCommittedPages = free_committed_pages_;
}
min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
}
ALWAYS_INLINE bool TCMalloc_PageHeap::shouldScavenge() const
{
return free_committed_pages_ > kMinimumFreeCommittedPageCount;
}
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
inline Span* TCMalloc_PageHeap::New(Length n) {
ASSERT(Check());
ASSERT(n > 0);
// Find first size >= n that has a non-empty list
for (Length s = n; s < kMaxPages; s++) {
Span* ll = NULL;
bool released = false;
if (!DLL_IsEmpty(&free_[s].normal, entropy_)) {
// Found normal span
ll = &free_[s].normal;
} else if (!DLL_IsEmpty(&free_[s].returned, entropy_)) {
// Found returned span; reallocate it
ll = &free_[s].returned;
released = true;
} else {
// Keep looking in larger classes
continue;
}
Span* result = ll->next(entropy_);
Carve(result, n, released);
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// The newly allocated memory is from a span that's in the normal span list (already committed). Update the
// free committed pages count.
ASSERT(free_committed_pages_ >= n);
free_committed_pages_ -= n;
if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
ASSERT(Check());
free_pages_ -= n;
return result;
}
Span* result = AllocLarge(n);
if (result != NULL) {
ASSERT_SPAN_COMMITTED(result);
return result;
}
// Grow the heap and try again
if (!GrowHeap(n)) {
ASSERT(Check());
return NULL;
}
return New(n);
}
Span* TCMalloc_PageHeap::AllocLarge(Length n) {
// find the best span (closest to n in size).
// The following loops implements address-ordered best-fit.
bool from_released = false;
Span *best = NULL;
// Search through normal list
for (Span* span = large_.normal.next(entropy_);
span != &large_.normal;
span = span->next(entropy_)) {
if (span->length >= n) {
if ((best == NULL)
|| (span->length < best->length)
|| ((span->length == best->length) && (span->start < best->start))) {
best = span;
from_released = false;
}
}
}
// Search through released list in case it has a better fit
for (Span* span = large_.returned.next(entropy_);
span != &large_.returned;
span = span->next(entropy_)) {
if (span->length >= n) {
if ((best == NULL)
|| (span->length < best->length)
|| ((span->length == best->length) && (span->start < best->start))) {
best = span;
from_released = true;
}
}
}
if (best != NULL) {
Carve(best, n, from_released);
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// The newly allocated memory is from a span that's in the normal span list (already committed). Update the
// free committed pages count.
ASSERT(free_committed_pages_ >= n);
free_committed_pages_ -= n;
if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
ASSERT(Check());
free_pages_ -= n;
return best;
}
return NULL;
}
Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
ASSERT(0 < n);
ASSERT(n < span->length);
ASSERT(!span->free);
ASSERT(span->sizeclass == 0);
Event(span, 'T', n);
const Length extra = span->length - n;
Span* leftover = NewSpan(span->start + n, extra);
Event(leftover, 'U', extra);
RecordSpan(leftover);
pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
span->length = n;
return leftover;
}
inline void TCMalloc_PageHeap::Carve(Span* span, Length n, bool released) {
ASSERT(n > 0);
DLL_Remove(span, entropy_);
span->free = 0;
Event(span, 'A', n);
if (released) {
// If the span chosen to carve from is decommited, commit the entire span at once to avoid committing spans 1 page at a time.
ASSERT(span->decommitted);
TCMalloc_SystemCommit(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift));
span->decommitted = false;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
free_committed_pages_ += span->length;
#endif
}
const int extra = static_cast<int>(span->length - n);
ASSERT(extra >= 0);
if (extra > 0) {
Span* leftover = NewSpan(span->start + n, extra);
leftover->free = 1;
leftover->decommitted = false;
Event(leftover, 'S', extra);
RecordSpan(leftover);
// Place leftover span on appropriate free list
SpanList* listpair = (static_cast<size_t>(extra) < kMaxPages) ? &free_[extra] : &large_;
Span* dst = &listpair->normal;
DLL_Prepend(dst, leftover, entropy_);
span->length = n;
pagemap_.set(span->start + n - 1, span);
}
}
static ALWAYS_INLINE void mergeDecommittedStates(Span* destination, Span* other)
{
if (destination->decommitted && !other->decommitted) {
TCMalloc_SystemRelease(reinterpret_cast<void*>(other->start << kPageShift),
static_cast<size_t>(other->length << kPageShift));
} else if (other->decommitted && !destination->decommitted) {
TCMalloc_SystemRelease(reinterpret_cast<void*>(destination->start << kPageShift),
static_cast<size_t>(destination->length << kPageShift));
destination->decommitted = true;
}
}
inline void TCMalloc_PageHeap::Delete(Span* span) {
ASSERT(Check());
ASSERT(!span->free);
ASSERT(span->length > 0);
ASSERT(GetDescriptor(span->start) == span);
ASSERT(GetDescriptor(span->start + span->length - 1) == span);
span->sizeclass = 0;
#ifndef NO_TCMALLOC_SAMPLES
span->sample = 0;
#endif
// Coalesce -- we guarantee that "p" != 0, so no bounds checking
// necessary. We do not bother resetting the stale pagemap
// entries for the pieces we are merging together because we only
// care about the pagemap entries for the boundaries.
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
// Track the total size of the neighboring free spans that are committed.
Length neighboringCommittedSpansLength = 0;
#endif
const PageID p = span->start;
const Length n = span->length;
Span* prev = GetDescriptor(p-1);
if (prev != NULL && prev->free) {
// Merge preceding span into this span
ASSERT(prev->start + prev->length == p);
const Length len = prev->length;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
if (!prev->decommitted)
neighboringCommittedSpansLength += len;
#endif
mergeDecommittedStates(span, prev);
DLL_Remove(prev, entropy_);
DeleteSpan(prev);
span->start -= len;
span->length += len;
pagemap_.set(span->start, span);
Event(span, 'L', len);
}
Span* next = GetDescriptor(p+n);
if (next != NULL && next->free) {
// Merge next span into this span
ASSERT(next->start == p+n);
const Length len = next->length;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
if (!next->decommitted)
neighboringCommittedSpansLength += len;
#endif
mergeDecommittedStates(span, next);
DLL_Remove(next, entropy_);
DeleteSpan(next);
span->length += len;
pagemap_.set(span->start + span->length - 1, span);
Event(span, 'R', len);
}
Event(span, 'D', span->length);
span->free = 1;
if (span->decommitted) {
if (span->length < kMaxPages)
DLL_Prepend(&free_[span->length].returned, span, entropy_);
else
DLL_Prepend(&large_.returned, span, entropy_);
} else {
if (span->length < kMaxPages)
DLL_Prepend(&free_[span->length].normal, span, entropy_);
else
DLL_Prepend(&large_.normal, span, entropy_);
}
free_pages_ += n;
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
if (span->decommitted) {
// If the merged span is decommitted, that means we decommitted any neighboring spans that were
// committed. Update the free committed pages count.
free_committed_pages_ -= neighboringCommittedSpansLength;
if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
} else {
// If the merged span remains committed, add the deleted span's size to the free committed pages count.
free_committed_pages_ += n;
}
// Make sure the scavenge thread becomes active if we have enough freed pages to release some back to the system.
signalScavenger();
#else
IncrementalScavenge(n);
#endif
ASSERT(Check());
}
#if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
void TCMalloc_PageHeap::IncrementalScavenge(Length n) {
// Fast path; not yet time to release memory
scavenge_counter_ -= n;
if (scavenge_counter_ >= 0) return; // Not yet time to scavenge
#if PLATFORM(IOS)
static const size_t kDefaultReleaseDelay = 64;
#else
// If there is nothing to release, wait for so many pages before
// scavenging again. With 4K pages, this comes to 16MB of memory.
static const size_t kDefaultReleaseDelay = 1 << 8;
#endif
// Find index of free list to scavenge
size_t index = scavenge_index_ + 1;
uintptr_t entropy = entropy_;
for (size_t i = 0; i < kMaxPages+1; i++) {
if (index > kMaxPages) index = 0;
SpanList* slist = (index == kMaxPages) ? &large_ : &free_[index];
if (!DLL_IsEmpty(&slist->normal, entropy)) {
// Release the last span on the normal portion of this list
Span* s = slist->normal.prev(entropy);
DLL_Remove(s, entropy_);
TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
static_cast<size_t>(s->length << kPageShift));
s->decommitted = true;
DLL_Prepend(&slist->returned, s, entropy);
#if PLATFORM(IOS)
scavenge_counter_ = std::max<size_t>(16UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
#else
scavenge_counter_ = std::max<size_t>(64UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
#endif
if (index == kMaxPages && !DLL_IsEmpty(&slist->normal, entropy))
scavenge_index_ = index - 1;
else
scavenge_index_ = index;
return;
}
index++;
}
// Nothing to scavenge, delay for a while
scavenge_counter_ = kDefaultReleaseDelay;
}
#endif
void TCMalloc_PageHeap::RegisterSizeClass(Span* span, size_t sc) {
// Associate span object with all interior pages as well
ASSERT(!span->free);
ASSERT(GetDescriptor(span->start) == span);
ASSERT(GetDescriptor(span->start+span->length-1) == span);
Event(span, 'C', sc);
span->sizeclass = static_cast<unsigned int>(sc);
for (Length i = 1; i < span->length-1; i++) {
pagemap_.set(span->start+i, span);
}
}
#ifdef WTF_CHANGES
size_t TCMalloc_PageHeap::ReturnedBytes() const {
size_t result = 0;
for (unsigned s = 0; s < kMaxPages; s++) {
const int r_length = DLL_Length(&free_[s].returned, entropy_);
unsigned r_pages = s * r_length;
result += r_pages << kPageShift;
}
for (Span* s = large_.returned.next(entropy_); s != &large_.returned; s = s->next(entropy_))
result += s->length << kPageShift;
return result;
}
#endif
#ifndef WTF_CHANGES
static double PagesToMB(uint64_t pages) {
return (pages << kPageShift) / 1048576.0;
}
void TCMalloc_PageHeap::Dump(TCMalloc_Printer* out) {
int nonempty_sizes = 0;
for (int s = 0; s < kMaxPages; s++) {
if (!DLL_IsEmpty(&free_[s].normal) || !DLL_IsEmpty(&free_[s].returned)) {
nonempty_sizes++;
}
}
out->printf("------------------------------------------------\n");
out->printf("PageHeap: %d sizes; %6.1f MB free\n",
nonempty_sizes, PagesToMB(free_pages_));
out->printf("------------------------------------------------\n");
uint64_t total_normal = 0;
uint64_t total_returned = 0;
for (int s = 0; s < kMaxPages; s++) {
const int n_length = DLL_Length(&free_[s].normal);
const int r_length = DLL_Length(&free_[s].returned);
if (n_length + r_length > 0) {
uint64_t n_pages = s * n_length;
uint64_t r_pages = s * r_length;
total_normal += n_pages;
total_returned += r_pages;
out->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum"
"; unmapped: %6.1f MB; %6.1f MB cum\n",
s,
(n_length + r_length),
PagesToMB(n_pages + r_pages),
PagesToMB(total_normal + total_returned),
PagesToMB(r_pages),
PagesToMB(total_returned));
}
}
uint64_t n_pages = 0;
uint64_t r_pages = 0;
int n_spans = 0;
int r_spans = 0;
out->printf("Normal large spans:\n");
for (Span* s = large_.normal.next; s != &large_.normal; s = s->next) {
out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
s->length, PagesToMB(s->length));
n_pages += s->length;
n_spans++;
}
out->printf("Unmapped large spans:\n");
for (Span* s = large_.returned.next; s != &large_.returned; s = s->next) {
out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
s->length, PagesToMB(s->length));
r_pages += s->length;
r_spans++;
}
total_normal += n_pages;
total_returned += r_pages;
out->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum"
"; unmapped: %6.1f MB; %6.1f MB cum\n",
(n_spans + r_spans),
PagesToMB(n_pages + r_pages),
PagesToMB(total_normal + total_returned),
PagesToMB(r_pages),
PagesToMB(total_returned));
}
#endif
bool TCMalloc_PageHeap::GrowHeap(Length n) {
ASSERT(kMaxPages >= kMinSystemAlloc);
if (n > kMaxValidPages) return false;
Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc);
size_t actual_size;
void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
if (ptr == NULL) {
if (n < ask) {
// Try growing just "n" pages
ask = n;
ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
}
if (ptr == NULL) return false;
}
ask = actual_size >> kPageShift;
uint64_t old_system_bytes = system_bytes_;
system_bytes_ += (ask << kPageShift);
const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
ASSERT(p > 0);
// If we have already a lot of pages allocated, just pre allocate a bunch of
// memory for the page map. This prevents fragmentation by pagemap metadata
// when a program keeps allocating and freeing large blocks.
if (old_system_bytes < kPageMapBigAllocationThreshold
&& system_bytes_ >= kPageMapBigAllocationThreshold) {
pagemap_.PreallocateMoreMemory();
}
// Make sure pagemap_ has entries for all of the new pages.
// Plus ensure one before and one after so coalescing code
// does not need bounds-checking.
if (pagemap_.Ensure(p-1, ask+2)) {
// Pretend the new area is allocated and then Delete() it to
// cause any necessary coalescing to occur.
//
// We do not adjust free_pages_ here since Delete() will do it for us.
Span* span = NewSpan(p, ask);
RecordSpan(span);
Delete(span);
ASSERT(Check());
return true;
} else {
// We could not allocate memory within "pagemap_"
// TODO: Once we can return memory to the system, return the new span
return false;
}
}
bool TCMalloc_PageHeap::Check() {
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
size_t totalFreeCommitted = 0;
#endif
ASSERT(free_[0].normal.next(entropy_) == &free_[0].normal);
ASSERT(free_[0].returned.next(entropy_) == &free_[0].returned);
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
totalFreeCommitted = CheckList(&large_.normal, kMaxPages, 1000000000, false);
#else
CheckList(&large_.normal, kMaxPages, 1000000000, false);
#endif
CheckList(&large_.returned, kMaxPages, 1000000000, true);
for (Length s = 1; s < kMaxPages; s++) {
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
totalFreeCommitted += CheckList(&free_[s].normal, s, s, false);
#else
CheckList(&free_[s].normal, s, s, false);
#endif
CheckList(&free_[s].returned, s, s, true);
}
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
ASSERT(totalFreeCommitted == free_committed_pages_);
#endif
return true;
}
#if ASSERT_DISABLED
size_t TCMalloc_PageHeap::CheckList(Span*, Length, Length, bool) {
return 0;
}
#else
size_t TCMalloc_PageHeap::CheckList(Span* list, Length min_pages, Length max_pages, bool decommitted) {
size_t freeCount = 0;
for (Span* s = list->next(entropy_); s != list; s = s->next(entropy_)) {
CHECK_CONDITION(s->free);
CHECK_CONDITION(s->length >= min_pages);
CHECK_CONDITION(s->length <= max_pages);
CHECK_CONDITION(GetDescriptor(s->start) == s);
CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s);
CHECK_CONDITION(s->decommitted == decommitted);
freeCount += s->length;
}
return freeCount;
}
#endif
void TCMalloc_PageHeap::ReleaseFreeList(Span* list, Span* returned) {
// Walk backwards through list so that when we push these
// spans on the "returned" list, we preserve the order.
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
size_t freePageReduction = 0;
#endif
while (!DLL_IsEmpty(list, entropy_)) {
Span* s = list->prev(entropy_);
DLL_Remove(s, entropy_);
s->decommitted = true;
DLL_Prepend(returned, s, entropy_);
TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
static_cast<size_t>(s->length << kPageShift));
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
freePageReduction += s->length;
#endif
}
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
free_committed_pages_ -= freePageReduction;
if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
#endif
}
void TCMalloc_PageHeap::ReleaseFreePages() {
for (Length s = 0; s < kMaxPages; s++) {
ReleaseFreeList(&free_[s].normal, &free_[s].returned);
}
ReleaseFreeList(&large_.normal, &large_.returned);
ASSERT(Check());
}
//-------------------------------------------------------------------
// Free list
//-------------------------------------------------------------------
class TCMalloc_ThreadCache_FreeList {
private:
HardenedSLL list_; // Linked list of nodes
uint16_t length_; // Current length
uint16_t lowater_; // Low water mark for list length
uintptr_t entropy_; // Entropy source for hardening
public:
void Init(uintptr_t entropy) {
list_.setValue(NULL);
length_ = 0;
lowater_ = 0;
entropy_ = entropy;
#if ENABLE(TCMALLOC_HARDENING)
ASSERT(entropy_);
#endif
}
// Return current length of list
int length() const {
return length_;
}
// Is list empty?
bool empty() const {
return !list_;
}
// Low-water mark management
int lowwatermark() const { return lowater_; }
void clear_lowwatermark() { lowater_ = length_; }
ALWAYS_INLINE void Push(HardenedSLL ptr) {
SLL_Push(&list_, ptr, entropy_);
length_++;
}
void PushRange(int N, HardenedSLL start, HardenedSLL end) {
SLL_PushRange(&list_, start, end, entropy_);
length_ = length_ + static_cast<uint16_t>(N);
}
void PopRange(int N, HardenedSLL* start, HardenedSLL* end) {
SLL_PopRange(&list_, N, start, end, entropy_);
ASSERT(length_ >= N);
length_ = length_ - static_cast<uint16_t>(N);
if (length_ < lowater_) lowater_ = length_;
}
ALWAYS_INLINE void* Pop() {
ASSERT(list_);
length_--;
if (length_ < lowater_) lowater_ = length_;
return SLL_Pop(&list_, entropy_).value();
}
// Runs through the linked list to ensure that
// we can do that, and ensures that 'missing'
// is not present
NEVER_INLINE void Validate(HardenedSLL missing, size_t size) {
HardenedSLL node = list_;
UNUSED_PARAM(size);
while (node) {
RELEASE_ASSERT(node != missing);
RELEASE_ASSERT(IS_DEFINITELY_POISONED(node.value(), size));
node = SLL_Next(node, entropy_);
}
}
#ifdef WTF_CHANGES
template <class Finder, class Reader>
void enumerateFreeObjects(Finder& finder, const Reader& reader)
{
for (HardenedSLL nextObject = list_; nextObject; nextObject.setValue(reader.nextEntryInHardenedLinkedList(reinterpret_cast<void**>(nextObject.value()), entropy_)))
finder.visit(nextObject.value());
}
#endif
};
//-------------------------------------------------------------------
// Data kept per thread
//-------------------------------------------------------------------
class TCMalloc_ThreadCache {
private:
typedef TCMalloc_ThreadCache_FreeList FreeList;
#if OS(WINDOWS)
typedef DWORD ThreadIdentifier;
#else
typedef pthread_t ThreadIdentifier;
#endif
size_t size_; // Combined size of data
ThreadIdentifier tid_; // Which thread owns it
bool in_setspecific_; // Called pthread_setspecific?
FreeList list_[kNumClasses]; // Array indexed by size-class
// We sample allocations, biased by the size of the allocation
uint32_t rnd_; // Cheap random number generator
size_t bytes_until_sample_; // Bytes until we sample next
uintptr_t entropy_; // Entropy value used for hardening
// Allocate a new heap. REQUIRES: pageheap_lock is held.
static inline TCMalloc_ThreadCache* NewHeap(ThreadIdentifier tid, uintptr_t entropy);
// Use only as pthread thread-specific destructor function.
static void DestroyThreadCache(void* ptr);
public:
// All ThreadCache objects are kept in a linked list (for stats collection)
TCMalloc_ThreadCache* next_;
TCMalloc_ThreadCache* prev_;
void Init(ThreadIdentifier tid, uintptr_t entropy);
void Cleanup();
// Accessors (mostly just for printing stats)
int freelist_length(size_t cl) const { return list_[cl].length(); }
// Total byte size in cache
size_t Size() const { return size_; }
ALWAYS_INLINE void* Allocate(size_t size);
void Deallocate(HardenedSLL ptr, size_t size_class);
ALWAYS_INLINE void FetchFromCentralCache(size_t cl, size_t allocationSize);
void ReleaseToCentralCache(size_t cl, int N);
void Scavenge();
void Print() const;
// Record allocation of "k" bytes. Return true iff allocation
// should be sampled
bool SampleAllocation(size_t k);
// Pick next sampling point
void PickNextSample(size_t k);
static void InitModule();
static void InitTSD();
static TCMalloc_ThreadCache* GetThreadHeap();
static TCMalloc_ThreadCache* GetCache();
static TCMalloc_ThreadCache* GetCacheIfPresent();
static TCMalloc_ThreadCache* CreateCacheIfNecessary();
static void DeleteCache(TCMalloc_ThreadCache* heap);
static void BecomeIdle();
static void RecomputeThreadCacheSize();
#ifdef WTF_CHANGES
template <class Finder, class Reader>
void enumerateFreeObjects(Finder& finder, const Reader& reader)
{
for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
list_[sizeClass].enumerateFreeObjects(finder, reader);
}
#endif
};
//-------------------------------------------------------------------
// Global variables
//-------------------------------------------------------------------
// Central cache -- a collection of free-lists, one per size-class.
// We have a separate lock per free-list to reduce contention.
static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
// Page-level allocator
static AllocAlignmentInteger pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(AllocAlignmentInteger) - 1) / sizeof(AllocAlignmentInteger)];
static bool phinited = false;
// Avoid extra level of indirection by making "pageheap" be just an alias
// of pageheap_memory.
typedef union {
void* m_memory;
TCMalloc_PageHeap* m_pageHeap;
} PageHeapUnion;
static inline TCMalloc_PageHeap* getPageHeap()
{
PageHeapUnion u = { &pageheap_memory[0] };
return u.m_pageHeap;
}
#define pageheap getPageHeap()
size_t fastMallocGoodSize(size_t bytes)
{
if (!phinited)
TCMalloc_ThreadCache::InitModule();
return AllocationSize(bytes);
}
#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
#if HAVE(DISPATCH_H) || OS(WINDOWS)
void TCMalloc_PageHeap::periodicScavenge()
{
SpinLockHolder h(&pageheap_lock);
pageheap->scavenge();
if (shouldScavenge()) {
rescheduleScavenger();
return;
}
suspendScavenger();
}
ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
{
ASSERT(pageheap_lock.IsHeld());
if (isScavengerSuspended() && shouldScavenge())
scheduleScavenger();
}
#else
void TCMalloc_PageHeap::scavengerThread()
{
#if HAVE(PTHREAD_SETNAME_NP)
pthread_setname_np("JavaScriptCore: FastMalloc scavenger");
#endif
while (1) {
pageheap_lock.Lock();
if (!shouldScavenge()) {
// Set to false so that signalScavenger() will check whether we need to be siganlled.
m_scavengeThreadActive = false;
// We need to unlock now, as this thread will block on the condvar until scavenging is required.
pageheap_lock.Unlock();
// Block until there are enough free committed pages to release back to the system.
pthread_mutex_lock(&m_scavengeMutex);
pthread_cond_wait(&m_scavengeCondition, &m_scavengeMutex);
// After exiting the pthread_cond_wait, we hold the lock on m_scavengeMutex. Unlock it to prevent
// deadlock next time round the loop.
pthread_mutex_unlock(&m_scavengeMutex);
// Set to true to prevent unnecessary signalling of the condvar.
m_scavengeThreadActive = true;
} else
pageheap_lock.Unlock();
// Wait for a while to calculate how much memory remains unused during this pause.
sleep(kScavengeDelayInSeconds);
{
SpinLockHolder h(&pageheap_lock);
pageheap->scavenge();
}
}
}
#endif
#endif
// If TLS is available, we also store a copy
// of the per-thread object in a __thread variable
// since __thread variables are faster to read
// than pthread_getspecific(). We still need
// pthread_setspecific() because __thread
// variables provide no way to run cleanup
// code when a thread is destroyed.
#ifdef HAVE_TLS
static __thread TCMalloc_ThreadCache *threadlocal_heap;
#endif
// Thread-specific key. Initialization here is somewhat tricky
// because some Linux startup code invokes malloc() before it
// is in a good enough state to handle pthread_keycreate().
// Therefore, we use TSD keys only after tsd_inited is set to true.
// Until then, we use a slow path to get the heap object.
static bool tsd_inited = false;
#if USE(PTHREAD_GETSPECIFIC_DIRECT)
static const pthread_key_t heap_key = __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0;
#else
static ThreadSpecificKey heap_key;
#endif
static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
{
#if USE(PTHREAD_GETSPECIFIC_DIRECT)
// Can't have two libraries both doing this in the same process,
// so check and make this crash right away.
if (pthread_getspecific(heap_key))
CRASH();
#endif
#if OS(DARWIN)
// Still do pthread_setspecific even if there's an alternate form
// of thread-local storage in use, to benefit from the delete callback.
pthread_setspecific(heap_key, heap);
#else
threadSpecificSet(heap_key, heap);
#endif
}
// Allocator for thread heaps
static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
// Linked list of heap objects. Protected by pageheap_lock.
static TCMalloc_ThreadCache* thread_heaps = NULL;
static int thread_heap_count = 0;
// Overall thread cache size. Protected by pageheap_lock.
static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
// Global per-thread cache size. Writes are protected by
// pageheap_lock. Reads are done without any locking, which should be
// fine as long as size_t can be written atomically and we don't place
// invariants between this variable and other pieces of state.
static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
//-------------------------------------------------------------------
// Central cache implementation
//-------------------------------------------------------------------
void TCMalloc_Central_FreeList::Init(size_t cl, uintptr_t entropy) {
lock_.Init();
size_class_ = cl;
entropy_ = entropy;
#if ENABLE(TCMALLOC_HARDENING)
ASSERT(entropy_);
#endif
DLL_Init(&empty_, entropy_);
DLL_Init(&nonempty_, entropy_);
counter_ = 0;
cache_size_ = 1;
used_slots_ = 0;
ASSERT(cache_size_ <= kNumTransferEntries);
}
void TCMalloc_Central_FreeList::ReleaseListToSpans(HardenedSLL start) {
while (start) {
HardenedSLL next = SLL_Next(start, entropy_);
ReleaseToSpans(start);
start = next;
}
}
ALWAYS_INLINE void TCMalloc_Central_FreeList::ReleaseToSpans(HardenedSLL object) {
const PageID p = reinterpret_cast<uintptr_t>(object.value()) >> kPageShift;
Span* span = pageheap->GetDescriptor(p);
ASSERT(span != NULL);
ASSERT(span->refcount > 0);
// If span is empty, move it to non-empty list
if (!span->objects) {
DLL_Remove(span, entropy_);
DLL_Prepend(&nonempty_, span, entropy_);
Event(span, 'N', 0);
}
// The following check is expensive, so it is disabled by default
if (false) {
// Check that object does not occur in list
unsigned got = 0;
for (HardenedSLL p = span->objects; !p; SLL_Next(p, entropy_)) {
ASSERT(p.value() != object.value());
got++;
}
ASSERT(got + span->refcount ==
(span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
}
counter_++;
span->refcount--;
if (span->refcount == 0) {
Event(span, '#', 0);
counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
DLL_Remove(span, entropy_);
// Release central list lock while operating on pageheap
lock_.Unlock();
{
SpinLockHolder h(&pageheap_lock);
pageheap->Delete(span);
}
lock_.Lock();
} else {
SLL_SetNext(object, span->objects, entropy_);
span->objects.setValue(object.value());
}
}
ALWAYS_INLINE bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
size_t locked_size_class, bool force) {
static int race_counter = 0;
int t = race_counter++; // Updated without a lock, but who cares.
if (t >= static_cast<int>(kNumClasses)) {
while (t >= static_cast<int>(kNumClasses)) {
t -= kNumClasses;
}
race_counter = t;
}
ASSERT(t >= 0);
ASSERT(t < static_cast<int>(kNumClasses));
if (t == static_cast<int>(locked_size_class)) return false;
return central_cache[t].ShrinkCache(static_cast<int>(locked_size_class), force);
}
bool TCMalloc_Central_FreeList::MakeCacheSpace() {
// Is there room in the cache?
if (used_slots_ < cache_size_) return true;
// Check if we can expand this cache?
if (cache_size_ == kNumTransferEntries) return false;
// Ok, we'll try to grab an entry from some other size class.
if (EvictRandomSizeClass(size_class_, false) ||
EvictRandomSizeClass(size_class_, true)) {
// Succeeded in evicting, we're going to make our cache larger.
cache_size_++;
return true;
}
return false;
}
namespace {
class LockInverter {
private:
SpinLock *held_, *temp_;
public:
inline explicit LockInverter(SpinLock* held, SpinLock *temp)
: held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); }
inline ~LockInverter() { temp_->Unlock(); held_->Lock(); }
};
}
bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class, bool force) {
// Start with a quick check without taking a lock.
if (cache_size_ == 0) return false;
// We don't evict from a full cache unless we are 'forcing'.
if (force == false && used_slots_ == cache_size_) return false;
// Grab lock, but first release the other lock held by this thread. We use
// the lock inverter to ensure that we never hold two size class locks
// concurrently. That can create a deadlock because there is no well
// defined nesting order.
LockInverter li(¢ral_cache[locked_size_class].lock_, &lock_);
ASSERT(used_slots_ <= cache_size_);
ASSERT(0 <= cache_size_);
if (cache_size_ == 0) return false;
if (used_slots_ == cache_size_) {
if (force == false) return false;
// ReleaseListToSpans releases the lock, so we have to make all the
// updates to the central list before calling it.
cache_size_--;
used_slots_--;
ReleaseListToSpans(tc_slots_[used_slots_].head);
return true;
}
cache_size_--;
return true;
}
void TCMalloc_Central_FreeList::InsertRange(HardenedSLL start, HardenedSLL end, int N) {
SpinLockHolder h(&lock_);
if (N == num_objects_to_move[size_class_] &&
MakeCacheSpace()) {
int slot = used_slots_++;
ASSERT(slot >=0);
ASSERT(slot < kNumTransferEntries);
TCEntry *entry = &tc_slots_[slot];
entry->head = start;
entry->tail = end;
return;
}
ReleaseListToSpans(start);
}
ALWAYS_INLINE void TCMalloc_Central_FreeList::RemoveRange(HardenedSLL* start, HardenedSLL* end, int *N) {
int num = *N;
ASSERT(num > 0);
SpinLockHolder h(&lock_);
if (num == num_objects_to_move[size_class_] && used_slots_ > 0) {
int slot = --used_slots_;
ASSERT(slot >= 0);
TCEntry *entry = &tc_slots_[slot];
*start = entry->head;
*end = entry->tail;
return;
}
// TODO: Prefetch multiple TCEntries?
HardenedSLL tail = FetchFromSpansSafe();
if (!tail) {
// We are completely out of memory.
*start = *end = HardenedSLL::null();
*N = 0;
return;
}
SLL_SetNext(tail, HardenedSLL::null(), entropy_);
HardenedSLL head = tail;
int count = 1;
while (count < num) {
HardenedSLL t = FetchFromSpans();
if (!t) break;
SLL_Push(&head, t, entropy_);
count++;
}
*start = head;
*end = tail;
*N = count;
}
ALWAYS_INLINE HardenedSLL TCMalloc_Central_FreeList::FetchFromSpansSafe() {
HardenedSLL t = FetchFromSpans();
if (!t) {
Populate();
t = FetchFromSpans();
}
return t;
}
HardenedSLL TCMalloc_Central_FreeList::FetchFromSpans() {
if (DLL_IsEmpty(&nonempty_, entropy_)) return HardenedSLL::null();
Span* span = nonempty_.next(entropy_);
ASSERT(span->objects);
ASSERT_SPAN_COMMITTED(span);
span->refcount++;
HardenedSLL result = span->objects;
span->objects = SLL_Next(result, entropy_);
if (!span->objects) {
// Move to empty list
DLL_Remove(span, entropy_);
DLL_Prepend(&empty_, span, entropy_);
Event(span, 'E', 0);
}
counter_--;
return result;
}
// Fetch memory from the system and add to the central cache freelist.
ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
// Release central list lock while operating on pageheap
lock_.Unlock();
const size_t npages = class_to_pages[size_class_];
Span* span;
{
SpinLockHolder h(&pageheap_lock);
span = pageheap->New(npages);
if (span) pageheap->RegisterSizeClass(span, size_class_);
}
if (span == NULL) {
#if HAVE(ERRNO_H)
MESSAGE("allocation failed: %d\n", errno);
#elif OS(WINDOWS)
MESSAGE("allocation failed: %d\n", ::GetLastError());
#else
MESSAGE("allocation failed\n");
#endif
lock_.Lock();
return;
}
ASSERT_SPAN_COMMITTED(span);
ASSERT(span->length == npages);
// Cache sizeclass info eagerly. Locking is not necessary.
// (Instead of being eager, we could just replace any stale info
// about this span, but that seems to be no better in practice.)
for (size_t i = 0; i < npages; i++) {
pageheap->CacheSizeClass(span->start + i, size_class_);
}
// Split the block into pieces and add to the free-list
// TODO: coloring of objects to avoid cache conflicts?
HardenedSLL head = HardenedSLL::null();
char* start = reinterpret_cast<char*>(span->start << kPageShift);
const size_t size = ByteSizeForClass(size_class_);
char* ptr = start + (npages << kPageShift) - ((npages << kPageShift) % size);
int num = 0;
#if ENABLE(TCMALLOC_HARDENING)
uint32_t startPoison = freedObjectStartPoison();
uint32_t endPoison = freedObjectEndPoison();
#endif
while (ptr > start) {
ptr -= size;
HardenedSLL node = HardenedSLL::create(ptr);
POISON_DEALLOCATION_EXPLICIT(ptr, size, startPoison, endPoison);
SLL_SetNext(node, head, entropy_);
head = node;
num++;
}
ASSERT(ptr == start);
ASSERT(ptr == head.value());
#ifndef NDEBUG
{
HardenedSLL node = head;
while (node) {
ASSERT(IS_DEFINITELY_POISONED(node.value(), size));
node = SLL_Next(node, entropy_);
}
}
#endif
span->objects = head;
ASSERT(span->objects.value() == head.value());
span->refcount = 0; // No sub-object in use yet
// Add span to list of non-empty spans
lock_.Lock();
DLL_Prepend(&nonempty_, span, entropy_);
counter_ += num;
}
//-------------------------------------------------------------------
// TCMalloc_ThreadCache implementation
//-------------------------------------------------------------------
inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
if (bytes_until_sample_ < k) {
PickNextSample(k);
return true;
} else {
bytes_until_sample_ -= k;
return false;
}
}
void TCMalloc_ThreadCache::Init(ThreadIdentifier tid, uintptr_t entropy) {
size_ = 0;
next_ = NULL;
prev_ = NULL;
tid_ = tid;
in_setspecific_ = false;
entropy_ = entropy;
#if ENABLE(TCMALLOC_HARDENING)
ASSERT(entropy_);
#endif
for (size_t cl = 0; cl < kNumClasses; ++cl) {
list_[cl].Init(entropy_);
}
// Initialize RNG -- run it for a bit to get to good values
bytes_until_sample_ = 0;
rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
for (int i = 0; i < 100; i++) {
PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter * 2));
}
}
void TCMalloc_ThreadCache::Cleanup() {
// Put unused memory back into central cache
for (size_t cl = 0; cl < kNumClasses; ++cl) {
if (list_[cl].length() > 0) {
ReleaseToCentralCache(cl, list_[cl].length());
}
}
}
ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
ASSERT(size <= kMaxSize);
const size_t cl = SizeClass(size);
FreeList* list = &list_[cl];
size_t allocationSize = ByteSizeForClass(cl);
if (list->empty()) {
FetchFromCentralCache(cl, allocationSize);
if (list->empty()) return NULL;
}
size_ -= allocationSize;
void* result = list->Pop();
if (!result)
return 0;
RELEASE_ASSERT(IS_DEFINITELY_POISONED(result, allocationSize));
POISON_ALLOCATION(result, allocationSize);
return result;
}
inline void TCMalloc_ThreadCache::Deallocate(HardenedSLL ptr, size_t cl) {
size_t allocationSize = ByteSizeForClass(cl);
size_ += allocationSize;
FreeList* list = &list_[cl];
if (MAY_BE_POISONED(ptr.value(), allocationSize))
list->Validate(ptr, allocationSize);
POISON_DEALLOCATION(ptr.value(), allocationSize);
list->Push(ptr);
// If enough data is free, put back into central cache
if (list->length() > kMaxFreeListLength) {
ReleaseToCentralCache(cl, num_objects_to_move[cl]);
}
if (size_ >= per_thread_cache_size) Scavenge();
}
// Remove some objects of class "cl" from central cache and add to thread heap
ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t allocationSize) {
int fetch_count = num_objects_to_move[cl];
HardenedSLL start, end;
central_cache[cl].RemoveRange(&start, &end, &fetch_count);
list_[cl].PushRange(fetch_count, start, end);
size_ += allocationSize * fetch_count;
}
// Remove some objects of class "cl" from thread heap and add to central cache
inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
ASSERT(N > 0);
FreeList* src = &list_[cl];
if (N > src->length()) N = src->length();
size_ -= N*ByteSizeForClass(cl);
// We return prepackaged chains of the correct size to the central cache.
// TODO: Use the same format internally in the thread caches?
int batch_size = num_objects_to_move[cl];
while (N > batch_size) {
HardenedSLL tail, head;
src->PopRange(batch_size, &head, &tail);
central_cache[cl].InsertRange(head, tail, batch_size);
N -= batch_size;
}
HardenedSLL tail, head;
src->PopRange(N, &head, &tail);
central_cache[cl].InsertRange(head, tail, N);
}
// Release idle memory to the central cache
inline void TCMalloc_ThreadCache::Scavenge() {
// If the low-water mark for the free list is L, it means we would
// not have had to allocate anything from the central cache even if
// we had reduced the free list size by L. We aim to get closer to
// that situation by dropping L/2 nodes from the free list. This
// may not release much memory, but if so we will call scavenge again
// pretty soon and the low-water marks will be high on that call.
//int64 start = CycleClock::Now();
for (size_t cl = 0; cl < kNumClasses; cl++) {
FreeList* list = &list_[cl];
const int lowmark = list->lowwatermark();
if (lowmark > 0) {
const int drop = (lowmark > 1) ? lowmark/2 : 1;
ReleaseToCentralCache(cl, drop);
}
list->clear_lowwatermark();
}
//int64 finish = CycleClock::Now();
//CycleTimer ct;
//MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
}
void TCMalloc_ThreadCache::PickNextSample(size_t k) {
// Make next "random" number
// x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
uint32_t r = rnd_;
rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
// Next point is "rnd_ % (sample_period)". I.e., average
// increment is "sample_period/2".
const int flag_value = static_cast<int>(FLAGS_tcmalloc_sample_parameter);
static int last_flag_value = -1;
if (flag_value != last_flag_value) {
SpinLockHolder h(&sample_period_lock);
int i;
for (i = 0; i < (static_cast<int>(sizeof(primes_list)/sizeof(primes_list[0])) - 1); i++) {
if (primes_list[i] >= flag_value) {
break;
}
}
sample_period = primes_list[i];
last_flag_value = flag_value;
}
bytes_until_sample_ += rnd_ % sample_period;
if (k > (static_cast<size_t>(-1) >> 2)) {
// If the user has asked for a huge allocation then it is possible
// for the code below to loop infinitely. Just return (note that
// this throws off the sampling accuracy somewhat, but a user who
// is allocating more than 1G of memory at a time can live with a
// minor inaccuracy in profiling of small allocations, and also
// would rather not wait for the loop below to terminate).
return;
}
while (bytes_until_sample_ < k) {
// Increase bytes_until_sample_ by enough average sampling periods
// (sample_period >> 1) to allow us to sample past the current
// allocation.
bytes_until_sample_ += (sample_period >> 1);
}
bytes_until_sample_ -= k;
}
void TCMalloc_ThreadCache::InitModule() {
// There is a slight potential race here because of double-checked
// locking idiom. However, as long as the program does a small
// allocation before switching to multi-threaded mode, we will be
// fine. We increase the chances of doing such a small allocation
// by doing one in the constructor of the module_enter_exit_hook
// object declared below.
SpinLockHolder h(&pageheap_lock);
if (!phinited) {
uintptr_t entropy = HARDENING_ENTROPY;
#ifdef WTF_CHANGES
InitTSD();
#endif
InitSizeClasses();
threadheap_allocator.Init(entropy);
span_allocator.Init(entropy);
span_allocator.New(); // Reduce cache conflicts
span_allocator.New(); // Reduce cache conflicts
stacktrace_allocator.Init(entropy);
DLL_Init(&sampled_objects, entropy);
for (size_t i = 0; i < kNumClasses; ++i) {
central_cache[i].Init(i, entropy);
}
pageheap->init();
phinited = 1;
#if defined(WTF_CHANGES) && OS(DARWIN)
FastMallocZone::init();
#endif
}
}
inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid, uintptr_t entropy) {
// Create the heap and add it to the linked list
TCMalloc_ThreadCache *heap = threadheap_allocator.New();
heap->Init(tid, entropy);
heap->next_ = thread_heaps;
heap->prev_ = NULL;
if (thread_heaps != NULL) thread_heaps->prev_ = heap;
thread_heaps = heap;
thread_heap_count++;
RecomputeThreadCacheSize();
return heap;
}
inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetThreadHeap() {
#ifdef HAVE_TLS
// __thread is faster, but only when the kernel supports it
if (KernelSupportsTLS())
return threadlocal_heap;
#elif OS(DARWIN)
return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
#else
return static_cast<TCMalloc_ThreadCache*>(threadSpecificGet(heap_key));
#endif
}
inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
TCMalloc_ThreadCache* ptr = NULL;
if (!tsd_inited) {
InitModule();
} else {
ptr = GetThreadHeap();
}
if (ptr == NULL) ptr = CreateCacheIfNecessary();
return ptr;
}
// In deletion paths, we do not try to create a thread-cache. This is
// because we may be in the thread destruction code and may have
// already cleaned up the cache for this thread.
inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
if (!tsd_inited) return NULL;
void* const p = GetThreadHeap();
return reinterpret_cast<TCMalloc_ThreadCache*>(p);
}
void TCMalloc_ThreadCache::InitTSD() {
ASSERT(!tsd_inited);
#if USE(PTHREAD_GETSPECIFIC_DIRECT)
pthread_key_init_np(heap_key, DestroyThreadCache);
#else
threadSpecificKeyCreate(&heap_key, DestroyThreadCache);
#endif
tsd_inited = true;
#if !OS(WINDOWS)
// We may have used a fake pthread_t for the main thread. Fix it.
pthread_t zero;
memset(&zero, 0, sizeof(zero));
#endif
#ifndef WTF_CHANGES
SpinLockHolder h(&pageheap_lock);
#else
ASSERT(pageheap_lock.IsHeld());
#endif
for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
#if OS(WINDOWS)
if (h->tid_ == 0) {
h->tid_ = GetCurrentThreadId();
}
#else
if (pthread_equal(h->tid_, zero)) {
h->tid_ = pthread_self();
}
#endif
}
}
TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
// Initialize per-thread data if necessary
TCMalloc_ThreadCache* heap = NULL;
{
SpinLockHolder h(&pageheap_lock);
#if OS(WINDOWS)
DWORD me;
if (!tsd_inited) {
me = 0;
} else {
me = GetCurrentThreadId();
}
#else
// Early on in glibc's life, we cannot even call pthread_self()
pthread_t me;
if (!tsd_inited) {
memset(&me, 0, sizeof(me));
} else {
me = pthread_self();
}
#endif
// This may be a recursive malloc call from pthread_setspecific()
// In that case, the heap for this thread has already been created
// and added to the linked list. So we search for that first.
for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
#if OS(WINDOWS)
if (h->tid_ == me) {
#else
if (pthread_equal(h->tid_, me)) {
#endif
heap = h;
break;
}
}
if (heap == NULL) heap = NewHeap(me, HARDENING_ENTROPY);
}
// We call pthread_setspecific() outside the lock because it may
// call malloc() recursively. The recursive call will never get
// here again because it will find the already allocated heap in the
// linked list of heaps.
if (!heap->in_setspecific_ && tsd_inited) {
heap->in_setspecific_ = true;
setThreadHeap(heap);
}
return heap;
}
void TCMalloc_ThreadCache::BecomeIdle() {
if (!tsd_inited) return; // No caches yet
TCMalloc_ThreadCache* heap = GetThreadHeap();
if (heap == NULL) return; // No thread cache to remove
if (heap->in_setspecific_) return; // Do not disturb the active caller
heap->in_setspecific_ = true;
setThreadHeap(NULL);
#ifdef HAVE_TLS
// Also update the copy in __thread
threadlocal_heap = NULL;
#endif
heap->in_setspecific_ = false;
if (GetThreadHeap() == heap) {
// Somehow heap got reinstated by a recursive call to malloc
// from pthread_setspecific. We give up in this case.
return;
}
// We can now get rid of the heap
DeleteCache(heap);
}
void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr) {
// Note that "ptr" cannot be NULL since pthread promises not
// to invoke the destructor on NULL values, but for safety,
// we check anyway.
if (ptr == NULL) return;
#ifdef HAVE_TLS
// Prevent fast path of GetThreadHeap() from returning heap.
threadlocal_heap = NULL;
#endif
DeleteCache(reinterpret_cast<TCMalloc_ThreadCache*>(ptr));
}
void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache* heap) {
// Remove all memory from heap
heap->Cleanup();
// Remove from linked list
SpinLockHolder h(&pageheap_lock);
if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
if (thread_heaps == heap) thread_heaps = heap->next_;
thread_heap_count--;
RecomputeThreadCacheSize();
threadheap_allocator.Delete(heap);
}
void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
// Divide available space across threads
int n = thread_heap_count > 0 ? thread_heap_count : 1;
size_t space = overall_thread_cache_size / n;
// Limit to allowed range
if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
per_thread_cache_size = space;
}
void TCMalloc_ThreadCache::Print() const {
for (size_t cl = 0; cl < kNumClasses; ++cl) {
MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
ByteSizeForClass(cl),
list_[cl].length(),
list_[cl].lowwatermark());
}
}
// Extract interesting stats
struct TCMallocStats {
uint64_t system_bytes; // Bytes alloced from system
uint64_t thread_bytes; // Bytes in thread caches
uint64_t central_bytes; // Bytes in central cache
uint64_t transfer_bytes; // Bytes in central transfer cache
uint64_t pageheap_bytes; // Bytes in page heap
uint64_t metadata_bytes; // Bytes alloced for metadata
};
#ifndef WTF_CHANGES
// Get stats into "r". Also get per-size-class counts if class_count != NULL
static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
r->central_bytes = 0;
r->transfer_bytes = 0;
for (int cl = 0; cl < kNumClasses; ++cl) {
const int length = central_cache[cl].length();
const int tc_length = central_cache[cl].tc_length();
r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
r->transfer_bytes +=
static_cast<uint64_t>(ByteSizeForClass(cl)) * tc_length;
if (class_count) class_count[cl] = length + tc_length;
}
// Add stats from per-thread heaps
r->thread_bytes = 0;
{ // scope
SpinLockHolder h(&pageheap_lock);
for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
r->thread_bytes += h->Size();
if (class_count) {
for (size_t cl = 0; cl < kNumClasses; ++cl) {
class_count[cl] += h->freelist_length(cl);
}
}
}
}
{ //scope
SpinLockHolder h(&pageheap_lock);
r->system_bytes = pageheap->SystemBytes();
r->metadata_bytes = metadata_system_bytes;
r->pageheap_bytes = pageheap->FreeBytes();
}
}
#endif
#ifndef WTF_CHANGES
// WRITE stats to "out"
static void DumpStats(TCMalloc_Printer* out, int level) {
TCMallocStats stats;
uint64_t class_count[kNumClasses];
ExtractStats(&stats, (level >= 2 ? class_count : NULL));
if (level >= 2) {
out->printf("------------------------------------------------\n");
uint64_t cumulative = 0;
for (int cl = 0; cl < kNumClasses; ++cl) {
if (class_count[cl] > 0) {
uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
cumulative += class_bytes;
out->printf("class %3d [ %8" PRIuS " bytes ] : "
"%8" PRIu64 " objs; %5.1f MB; %5.1f cum MB\n",
cl, ByteSizeForClass(cl),
class_count[cl],
class_bytes / 1048576.0,
cumulative / 1048576.0);
}
}
SpinLockHolder h(&pageheap_lock);
pageheap->Dump(out);
}
const uint64_t bytes_in_use = stats.system_bytes
- stats.pageheap_bytes
- stats.central_bytes
- stats.transfer_bytes
- stats.thread_bytes;
out->printf("------------------------------------------------\n"
"MALLOC: %12" PRIu64 " Heap size\n"
"MALLOC: %12" PRIu64 " Bytes in use by application\n"
"MALLOC: %12" PRIu64 " Bytes free in page heap\n"
"MALLOC: %12" PRIu64 " Bytes free in central cache\n"
"MALLOC: %12" PRIu64 " Bytes free in transfer cache\n"
"MALLOC: %12" PRIu64 " Bytes free in thread caches\n"
"MALLOC: %12" PRIu64 " Spans in use\n"
"MALLOC: %12" PRIu64 " Thread heaps in use\n"
"MALLOC: %12" PRIu64 " Metadata allocated\n"
"------------------------------------------------\n",
stats.system_bytes,
bytes_in_use,
stats.pageheap_bytes,
stats.central_bytes,
stats.transfer_bytes,
stats.thread_bytes,
uint64_t(span_allocator.inuse()),
uint64_t(threadheap_allocator.inuse()),
stats.metadata_bytes);
}
static void PrintStats(int level) {
const int kBufferSize = 16 << 10;
char* buffer = new char[kBufferSize];
TCMalloc_Printer printer(buffer, kBufferSize);
DumpStats(&printer, level);
write(STDERR_FILENO, buffer, strlen(buffer));
delete[] buffer;
}
static void** DumpStackTraces() {
// Count how much space we need
int needed_slots = 0;
{
SpinLockHolder h(&pageheap_lock);
for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
needed_slots += 3 + stack->depth;
}
needed_slots += 100; // Slop in case sample grows
needed_slots += needed_slots/8; // An extra 12.5% slop
}
void** result = new void*[needed_slots];
if (result == NULL) {
MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
needed_slots);
return NULL;
}
SpinLockHolder h(&pageheap_lock);
int used_slots = 0;
for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
ASSERT(used_slots < needed_slots); // Need to leave room for terminator
StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
if (used_slots + 3 + stack->depth >= needed_slots) {
// No more room
break;
}
result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
result[used_slots+1] = reinterpret_cast<void*>(stack->size);
result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
for (int d = 0; d < stack->depth; d++) {
result[used_slots+3+d] = stack->stack[d];
}
used_slots += 3 + stack->depth;
}
result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
return result;
}
#endif
#ifndef WTF_CHANGES
// TCMalloc's support for extra malloc interfaces
class TCMallocImplementation : public MallocExtension {
public:
virtual void GetStats(char* buffer, int buffer_length) {
ASSERT(buffer_length > 0);
TCMalloc_Printer printer(buffer, buffer_length);
// Print level one stats unless lots of space is available
if (buffer_length < 10000) {
DumpStats(&printer, 1);
} else {
DumpStats(&printer, 2);
}
}
virtual void** ReadStackTraces() {
return DumpStackTraces();
}
virtual bool GetNumericProperty(const char* name, size_t* value) {
ASSERT(name != NULL);
if (strcmp(name, "generic.current_allocated_bytes") == 0) {
TCMallocStats stats;
ExtractStats(&stats, NULL);
*value = stats.system_bytes
- stats.thread_bytes
- stats.central_bytes
- stats.pageheap_bytes;
return true;
}
if (strcmp(name, "generic.heap_size") == 0) {
TCMallocStats stats;
ExtractStats(&stats, NULL);
*value = stats.system_bytes;
return true;
}
if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
// We assume that bytes in the page heap are not fragmented too
// badly, and are therefore available for allocation.
SpinLockHolder l(&pageheap_lock);
*value = pageheap->FreeBytes();
return true;
}
if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
SpinLockHolder l(&pageheap_lock);
*value = overall_thread_cache_size;
return true;
}
if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
TCMallocStats stats;
ExtractStats(&stats, NULL);
*value = stats.thread_bytes;
return true;
}
return false;
}
virtual bool SetNumericProperty(const char* name, size_t value) {
ASSERT(name != NULL);
if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
// Clip the value to a reasonable range
if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
if (value > (1<<30)) value = (1<<30); // Limit to 1GB
SpinLockHolder l(&pageheap_lock);
overall_thread_cache_size = static_cast<size_t>(value);
TCMalloc_ThreadCache::RecomputeThreadCacheSize();
return true;
}
return false;
}
virtual void MarkThreadIdle() {
TCMalloc_ThreadCache::BecomeIdle();
}
virtual void ReleaseFreeMemory() {
SpinLockHolder h(&pageheap_lock);
pageheap->ReleaseFreePages();
}
};
#endif
// The constructor allocates an object to ensure that initialization
// runs before main(), and therefore we do not have a chance to become
// multi-threaded before initialization. We also create the TSD key
// here. Presumably by the time this constructor runs, glibc is in
// good enough shape to handle pthread_key_create().
//
// The constructor also takes the opportunity to tell STL to use
// tcmalloc. We want to do this early, before construct time, so
// all user STL allocations go through tcmalloc (which works really
// well for STL).
//
// The destructor prints stats when the program exits.
class TCMallocGuard {
public:
TCMallocGuard() {
#ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
// Check whether the kernel also supports TLS (needs to happen at runtime)
CheckIfKernelSupportsTLS();
#endif
#ifndef WTF_CHANGES
#ifdef WIN32 // patch the windows VirtualAlloc, etc.
PatchWindowsFunctions(); // defined in windows/patch_functions.cc
#endif
#endif
free(malloc(1));
TCMalloc_ThreadCache::InitTSD();
free(malloc(1));
#ifndef WTF_CHANGES
MallocExtension::Register(new TCMallocImplementation);
#endif
}
#ifndef WTF_CHANGES
~TCMallocGuard() {
const char* env = getenv("MALLOCSTATS");
if (env != NULL) {
int level = atoi(env);
if (level < 1) level = 1;
PrintStats(level);
}
#ifdef WIN32
UnpatchWindowsFunctions();
#endif
}
#endif
};
#ifndef WTF_CHANGES
static TCMallocGuard module_enter_exit_hook;
#endif
//-------------------------------------------------------------------
// Helpers for the exported routines below
//-------------------------------------------------------------------
#ifndef WTF_CHANGES
static Span* DoSampledAllocation(size_t size) {
// Grab the stack trace outside the heap lock
StackTrace tmp;
tmp.depth = GetStackTrace(tmp.stack, kMaxStackDepth, 1);
tmp.size = size;
SpinLockHolder h(&pageheap_lock);
// Allocate span
Span *span = pageheap->New(pages(size == 0 ? 1 : size));
if (span == NULL) {
return NULL;
}
// Allocate stack trace
StackTrace *stack = stacktrace_allocator.New();
if (stack == NULL) {
// Sampling failed because of lack of memory
return span;
}
*stack = tmp;
span->sample = 1;
span->objects = stack;
DLL_Prepend(&sampled_objects, span);
return span;
}
#endif
static inline bool CheckCachedSizeClass(void *ptr) {
PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
size_t cached_value = pageheap->GetSizeClassIfCached(p);
return cached_value == 0 ||
cached_value == pageheap->GetDescriptor(p)->sizeclass;
}
static inline void* CheckedMallocResult(void *result)
{
ASSERT(result == 0 || CheckCachedSizeClass(result));
return result;
}
static inline void* SpanToMallocResult(Span *span) {
ASSERT_SPAN_COMMITTED(span);
pageheap->CacheSizeClass(span->start, 0);
void* result = reinterpret_cast<void*>(span->start << kPageShift);
POISON_ALLOCATION(result, span->length << kPageShift);
return CheckedMallocResult(result);
}
#ifdef WTF_CHANGES
template <bool crashOnFailure>
#endif
static ALWAYS_INLINE void* do_malloc(size_t size) {
void* ret = NULL;
#ifdef WTF_CHANGES
ASSERT(!isForbidden());
#endif
// The following call forces module initialization
TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
#ifndef WTF_CHANGES
if ((FLAGS_tcmalloc_sample_parameter > 0) && heap->SampleAllocation(size)) {
Span* span = DoSampledAllocation(size);
if (span != NULL) {
ret = SpanToMallocResult(span);
}
} else
#endif
if (size > kMaxSize) {
// Use page-level allocator
SpinLockHolder h(&pageheap_lock);
Span* span = pageheap->New(pages(size));
if (span != NULL) {
ret = SpanToMallocResult(span);
}
} else {
// The common case, and also the simplest. This just pops the
// size-appropriate freelist, afer replenishing it if it's empty.
ret = CheckedMallocResult(heap->Allocate(size));
}
if (!ret) {
#ifdef WTF_CHANGES
if (crashOnFailure) // This branch should be optimized out by the compiler.
CRASH();
#else
errno = ENOMEM;
#endif
}
return ret;
}
static ALWAYS_INLINE void do_free(void* ptr) {
if (ptr == NULL) return;
ASSERT(pageheap != NULL); // Should not call free() before malloc()
const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
Span* span = pageheap->GetDescriptor(p);
RELEASE_ASSERT(span->isValid());
size_t cl = span->sizeclass;
if (cl) {
size_t byteSizeForClass = ByteSizeForClass(cl);
RELEASE_ASSERT(!((reinterpret_cast<char*>(ptr) - reinterpret_cast<char*>(span->start << kPageShift)) % byteSizeForClass));
pageheap->CacheSizeClass(p, cl);
#ifndef NO_TCMALLOC_SAMPLES
ASSERT(!pageheap->GetDescriptor(p)->sample);
#endif
TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
if (heap != NULL) {
heap->Deallocate(HardenedSLL::create(ptr), cl);
} else {
// Delete directly into central cache
POISON_DEALLOCATION(ptr, byteSizeForClass);
SLL_SetNext(HardenedSLL::create(ptr), HardenedSLL::null(), central_cache[cl].entropy());
central_cache[cl].InsertRange(HardenedSLL::create(ptr), HardenedSLL::create(ptr), 1);
}
} else {
SpinLockHolder h(&pageheap_lock);
ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
ASSERT(span != NULL && span->start == p);
#ifndef NO_TCMALLOC_SAMPLES
if (span->sample) {
DLL_Remove(span);
stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
span->objects = NULL;
}
#endif
RELEASE_ASSERT(reinterpret_cast<void*>(span->start << kPageShift) == ptr);
POISON_DEALLOCATION(ptr, span->length << kPageShift);
pageheap->Delete(span);
}
}
#ifndef WTF_CHANGES
// For use by exported routines below that want specific alignments
//
// Note: this code can be slow, and can significantly fragment memory.
// The expectation is that memalign/posix_memalign/valloc/pvalloc will
// not be invoked very often. This requirement simplifies our
// implementation and allows us to tune for expected allocation
// patterns.
static void* do_memalign(size_t align, size_t size) {
ASSERT((align & (align - 1)) == 0);
ASSERT(align > 0);
if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
// Allocate at least one byte to avoid boundary conditions below
if (size == 0) size = 1;
if (size <= kMaxSize && align < kPageSize) {
// Search through acceptable size classes looking for one with
// enough alignment. This depends on the fact that
// InitSizeClasses() currently produces several size classes that
// are aligned at powers of two. We will waste time and space if
// we miss in the size class array, but that is deemed acceptable
// since memalign() should be used rarely.
size_t cl = SizeClass(size);
while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
cl++;
}
if (cl < kNumClasses) {
TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
return CheckedMallocResult(heap->Allocate(class_to_size[cl]));
}
}
// We will allocate directly from the page heap
SpinLockHolder h(&pageheap_lock);
if (align <= kPageSize) {
// Any page-level allocation will be fine
// TODO: We could put the rest of this page in the appropriate
// TODO: cache but it does not seem worth it.
Span* span = pageheap->New(pages(size));
return span == NULL ? NULL : SpanToMallocResult(span);
}
// Allocate extra pages and carve off an aligned portion
const Length alloc = pages(size + align);
Span* span = pageheap->New(alloc);
if (span == NULL) return NULL;
// Skip starting portion so that we end up aligned
Length skip = 0;
while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
skip++;
}
ASSERT(skip < alloc);
if (skip > 0) {
Span* rest = pageheap->Split(span, skip);
pageheap->Delete(span);
span = rest;
}
// Skip trailing portion that we do not need to return
const Length needed = pages(size);
ASSERT(span->length >= needed);
if (span->length > needed) {
Span* trailer = pageheap->Split(span, needed);
pageheap->Delete(trailer);
}
return SpanToMallocResult(span);
}
#endif
// Helpers for use by exported routines below:
#ifndef WTF_CHANGES
static inline void do_malloc_stats() {
PrintStats(1);
}
#endif
static inline int do_mallopt(int, int) {
return 1; // Indicates error
}
#ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
static inline struct mallinfo do_mallinfo() {
TCMallocStats stats;
ExtractStats(&stats, NULL);
// Just some of the fields are filled in.
struct mallinfo info;
memset(&info, 0, sizeof(info));
// Unfortunately, the struct contains "int" field, so some of the
// size values will be truncated.
info.arena = static_cast<int>(stats.system_bytes);
info.fsmblks = static_cast<int>(stats.thread_bytes
+ stats.central_bytes
+ stats.transfer_bytes);
info.fordblks = static_cast<int>(stats.pageheap_bytes);
info.uordblks = static_cast<int>(stats.system_bytes
- stats.thread_bytes
- stats.central_bytes
- stats.transfer_bytes
- stats.pageheap_bytes);
return info;
}
#endif
//-------------------------------------------------------------------
// Exported routines
//-------------------------------------------------------------------
// CAVEAT: The code structure below ensures that MallocHook methods are always
// called from the stack frame of the invoked allocation function.
// heap-checker.cc depends on this to start a stack trace from
// the call to the (de)allocation function.
#ifndef WTF_CHANGES
extern "C"
#else
#define do_malloc do_malloc<crashOnFailure>
template <bool crashOnFailure>
ALWAYS_INLINE void* malloc(size_t);
void* fastMalloc(size_t size)
{
return malloc<true>(size);
}
TryMallocReturnValue tryFastMalloc(size_t size)
{
return malloc<false>(size);
}
template <bool crashOnFailure>
ALWAYS_INLINE
#endif
void* malloc(size_t size) {
#if ENABLE(WTF_MALLOC_VALIDATION)
if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= size) // If overflow would occur...
return 0;
void* result = do_malloc(size + Internal::ValidationBufferSize);
if (!result)
return 0;
Internal::ValidationHeader* header = static_cast<Internal::ValidationHeader*>(result);
header->m_size = size;
header->m_type = Internal::AllocTypeMalloc;
header->m_prefix = static_cast<unsigned>(Internal::ValidationPrefix);
result = header + 1;
*Internal::fastMallocValidationSuffix(result) = Internal::ValidationSuffix;
fastMallocValidate(result);
#else
void* result = do_malloc(size);
#endif
#ifndef WTF_CHANGES
MallocHook::InvokeNewHook(result, size);
#endif
return result;
}
#ifndef WTF_CHANGES
extern "C"
#endif
void free(void* ptr) {
#ifndef WTF_CHANGES
MallocHook::InvokeDeleteHook(ptr);
#endif
#if ENABLE(WTF_MALLOC_VALIDATION)
if (!ptr)
return;
fastMallocValidate(ptr);
Internal::ValidationHeader* header = Internal::fastMallocValidationHeader(ptr);
memset(ptr, 0xCC, header->m_size);
do_free(header);
#else
do_free(ptr);
#endif
}
#ifndef WTF_CHANGES
extern "C"
#else
template <bool crashOnFailure>
ALWAYS_INLINE void* calloc(size_t, size_t);
void* fastCalloc(size_t n, size_t elem_size)
{
void* result = calloc<true>(n, elem_size);
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(result);
#endif
return result;
}
TryMallocReturnValue tryFastCalloc(size_t n, size_t elem_size)
{
void* result = calloc<false>(n, elem_size);
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(result);
#endif
return result;
}
template <bool crashOnFailure>
ALWAYS_INLINE
#endif
void* calloc(size_t n, size_t elem_size) {
size_t totalBytes = n * elem_size;
// Protect against overflow
if (n > 1 && elem_size && (totalBytes / elem_size) != n)
return 0;
#if ENABLE(WTF_MALLOC_VALIDATION)
void* result = malloc<crashOnFailure>(totalBytes);
if (!result)
return 0;
memset(result, 0, totalBytes);
fastMallocValidate(result);
#else
void* result = do_malloc(totalBytes);
if (result != NULL) {
memset(result, 0, totalBytes);
}
#endif
#ifndef WTF_CHANGES
MallocHook::InvokeNewHook(result, totalBytes);
#endif
return result;
}
// Since cfree isn't used anywhere, we don't compile it in.
#ifndef WTF_CHANGES
#ifndef WTF_CHANGES
extern "C"
#endif
void cfree(void* ptr) {
#ifndef WTF_CHANGES
MallocHook::InvokeDeleteHook(ptr);
#endif
do_free(ptr);
}
#endif
#ifndef WTF_CHANGES
extern "C"
#else
template <bool crashOnFailure>
ALWAYS_INLINE void* realloc(void*, size_t);
void* fastRealloc(void* old_ptr, size_t new_size)
{
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(old_ptr);
#endif
void* result = realloc<true>(old_ptr, new_size);
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(result);
#endif
return result;
}
TryMallocReturnValue tryFastRealloc(void* old_ptr, size_t new_size)
{
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(old_ptr);
#endif
void* result = realloc<false>(old_ptr, new_size);
#if ENABLE(WTF_MALLOC_VALIDATION)
fastMallocValidate(result);
#endif
return result;
}
template <bool crashOnFailure>
ALWAYS_INLINE
#endif
void* realloc(void* old_ptr, size_t new_size) {
if (old_ptr == NULL) {
#if ENABLE(WTF_MALLOC_VALIDATION)
void* result = malloc<crashOnFailure>(new_size);
#else
void* result = do_malloc(new_size);
#ifndef WTF_CHANGES
MallocHook::InvokeNewHook(result, new_size);
#endif
#endif
return result;
}
if (new_size == 0) {
#ifndef WTF_CHANGES
MallocHook::InvokeDeleteHook(old_ptr);
#endif
free(old_ptr);
return NULL;
}
#if ENABLE(WTF_MALLOC_VALIDATION)
if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= new_size) // If overflow would occur...
return 0;
Internal::ValidationHeader* header = Internal::fastMallocValidationHeader(old_ptr);
fastMallocValidate(old_ptr);
old_ptr = header;
header->m_size = new_size;
new_size += Internal::ValidationBufferSize;
#endif
// Get the size of the old entry
const PageID p = reinterpret_cast<uintptr_t>(old_ptr) >> kPageShift;
size_t cl = pageheap->GetSizeClassIfCached(p);
Span *span = NULL;
size_t old_size;
if (cl == 0) {
span = pageheap->GetDescriptor(p);
cl = span->sizeclass;
pageheap->CacheSizeClass(p, cl);
}
if (cl != 0) {
old_size = ByteSizeForClass(cl);
} else {
ASSERT(span != NULL);
old_size = span->length << kPageShift;
}
// Reallocate if the new size is larger than the old size,
// or if the new size is significantly smaller than the old size.
if ((new_size > old_size) || (AllocationSize(new_size) < old_size)) {
// Need to reallocate
void* new_ptr = do_malloc(new_size);
if (new_ptr == NULL) {
return NULL;
}
#ifndef WTF_CHANGES
MallocHook::InvokeNewHook(new_ptr, new_size);
#endif
memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
#ifndef WTF_CHANGES
MallocHook::InvokeDeleteHook(old_ptr);
#endif
// We could use a variant of do_free() that leverages the fact
// that we already know the sizeclass of old_ptr. The benefit
// would be small, so don't bother.
do_free(old_ptr);
#if ENABLE(WTF_MALLOC_VALIDATION)
new_ptr = static_cast<Internal::ValidationHeader*>(new_ptr) + 1;
*Internal::fastMallocValidationSuffix(new_ptr) = Internal::ValidationSuffix;
#endif
return new_ptr;
} else {
#if ENABLE(WTF_MALLOC_VALIDATION)
old_ptr = static_cast<Internal::ValidationHeader*>(old_ptr) + 1; // Set old_ptr back to the user pointer.
*Internal::fastMallocValidationSuffix(old_ptr) = Internal::ValidationSuffix;
#endif
return old_ptr;
}
}
#ifdef WTF_CHANGES
#undef do_malloc
#else
static SpinLock set_new_handler_lock = SPINLOCK_INITIALIZER;
static inline void* cpp_alloc(size_t size, bool nothrow) {
for (;;) {
void* p = do_malloc(size);
#ifdef PREANSINEW
return p;
#else
if (p == NULL) { // allocation failed
// Get the current new handler. NB: this function is not
// thread-safe. We make a feeble stab at making it so here, but
// this lock only protects against tcmalloc interfering with
// itself, not with other libraries calling set_new_handler.
std::new_handler nh;
{
SpinLockHolder h(&set_new_handler_lock);
nh = std::set_new_handler(0);
(void) std::set_new_handler(nh);
}
// If no new_handler is established, the allocation failed.
if (!nh) {
if (nothrow) return 0;
throw std::bad_alloc();
}
// Otherwise, try the new_handler. If it returns, retry the
// allocation. If it throws std::bad_alloc, fail the allocation.
// if it throws something else, don't interfere.
try {
(*nh)();
} catch (const std::bad_alloc&) {
if (!nothrow) throw;
return p;
}
} else { // allocation success
return p;
}
#endif
}
}
#if ENABLE(GLOBAL_FASTMALLOC_NEW)
void* operator new(size_t size) {
void* p = cpp_alloc(size, false);
// We keep this next instruction out of cpp_alloc for a reason: when
// it's in, and new just calls cpp_alloc, the optimizer may fold the
// new call into cpp_alloc, which messes up our whole section-based
// stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
// isn't the last thing this fn calls, and prevents the folding.
MallocHook::InvokeNewHook(p, size);
return p;
}
void* operator new(size_t size, const std::nothrow_t&) __THROW {
void* p = cpp_alloc(size, true);
MallocHook::InvokeNewHook(p, size);
return p;
}
void operator delete(void* p) __THROW {
MallocHook::InvokeDeleteHook(p);
do_free(p);
}
void operator delete(void* p, const std::nothrow_t&) __THROW {
MallocHook::InvokeDeleteHook(p);
do_free(p);
}
void* operator new[](size_t size) {
void* p = cpp_alloc(size, false);
// We keep this next instruction out of cpp_alloc for a reason: when
// it's in, and new just calls cpp_alloc, the optimizer may fold the
// new call into cpp_alloc, which messes up our whole section-based
// stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
// isn't the last thing this fn calls, and prevents the folding.
MallocHook::InvokeNewHook(p, size);
return p;
}
void* operator new[](size_t size, const std::nothrow_t&) __THROW {
void* p = cpp_alloc(size, true);
MallocHook::InvokeNewHook(p, size);
return p;
}
void operator delete[](void* p) __THROW {
MallocHook::InvokeDeleteHook(p);
do_free(p);
}
void operator delete[](void* p, const std::nothrow_t&) __THROW {
MallocHook::InvokeDeleteHook(p);
do_free(p);
}
#endif
extern "C" void* memalign(size_t align, size_t size) __THROW {
void* result = do_memalign(align, size);
MallocHook::InvokeNewHook(result, size);
return result;
}
extern "C" int posix_memalign(void** result_ptr, size_t align, size_t size)
__THROW {
if (((align % sizeof(void*)) != 0) ||
((align & (align - 1)) != 0) ||
(align == 0)) {
return EINVAL;
}
void* result = do_memalign(align, size);
MallocHook::InvokeNewHook(result, size);
if (result == NULL) {
return ENOMEM;
} else {
*result_ptr = result;
return 0;
}
}
static size_t pagesize = 0;
extern "C" void* valloc(size_t size) __THROW {
// Allocate page-aligned object of length >= size bytes
if (pagesize == 0) pagesize = getpagesize();
void* result = do_memalign(pagesize, size);
MallocHook::InvokeNewHook(result, size);
return result;
}
extern "C" void* pvalloc(size_t size) __THROW {
// Round up size to a multiple of pagesize
if (pagesize == 0) pagesize = getpagesize();
size = (size + pagesize - 1) & ~(pagesize - 1);
void* result = do_memalign(pagesize, size);
MallocHook::InvokeNewHook(result, size);
return result;
}
extern "C" void malloc_stats(void) {
do_malloc_stats();
}
extern "C" int mallopt(int cmd, int value) {
return do_mallopt(cmd, value);
}
#ifdef HAVE_STRUCT_MALLINFO
extern "C" struct mallinfo mallinfo(void) {
return do_mallinfo();
}
#endif
//-------------------------------------------------------------------
// Some library routines on RedHat 9 allocate memory using malloc()
// and free it using __libc_free() (or vice-versa). Since we provide
// our own implementations of malloc/free, we need to make sure that
// the __libc_XXX variants (defined as part of glibc) also point to
// the same implementations.
//-------------------------------------------------------------------
#if defined(__GLIBC__)
extern "C" {
#if COMPILER(GCC) && !defined(__MACH__) && defined(HAVE___ATTRIBUTE__)
// Potentially faster variants that use the gcc alias extension.
// Mach-O (Darwin) does not support weak aliases, hence the __MACH__ check.
# define ALIAS(x) __attribute__ ((weak, alias (x)))
void* __libc_malloc(size_t size) ALIAS("malloc");
void __libc_free(void* ptr) ALIAS("free");
void* __libc_realloc(void* ptr, size_t size) ALIAS("realloc");
void* __libc_calloc(size_t n, size_t size) ALIAS("calloc");
void __libc_cfree(void* ptr) ALIAS("cfree");
void* __libc_memalign(size_t align, size_t s) ALIAS("memalign");
void* __libc_valloc(size_t size) ALIAS("valloc");
void* __libc_pvalloc(size_t size) ALIAS("pvalloc");
int __posix_memalign(void** r, size_t a, size_t s) ALIAS("posix_memalign");
# undef ALIAS
# else /* not __GNUC__ */
// Portable wrappers
void* __libc_malloc(size_t size) { return malloc(size); }
void __libc_free(void* ptr) { free(ptr); }
void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
void __libc_cfree(void* ptr) { cfree(ptr); }
void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
void* __libc_valloc(size_t size) { return valloc(size); }
void* __libc_pvalloc(size_t size) { return pvalloc(size); }
int __posix_memalign(void** r, size_t a, size_t s) {
return posix_memalign(r, a, s);
}
# endif /* __GNUC__ */
}
#endif /* __GLIBC__ */
// Override __libc_memalign in libc on linux boxes specially.
// They have a bug in libc that causes them to (very rarely) allocate
// with __libc_memalign() yet deallocate with free() and the
// definitions above don't catch it.
// This function is an exception to the rule of calling MallocHook method
// from the stack frame of the allocation function;
// heap-checker handles this special case explicitly.
static void *MemalignOverride(size_t align, size_t size, const void *caller)
__THROW {
void* result = do_memalign(align, size);
MallocHook::InvokeNewHook(result, size);
return result;
}
void *(*__memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
#endif
#ifdef WTF_CHANGES
void releaseFastMallocFreeMemory()
{
// Flush free pages in the current thread cache back to the page heap.
if (TCMalloc_ThreadCache* threadCache = TCMalloc_ThreadCache::GetCacheIfPresent())
threadCache->Cleanup();
SpinLockHolder h(&pageheap_lock);
pageheap->ReleaseFreePages();
}
FastMallocStatistics fastMallocStatistics()
{
FastMallocStatistics statistics;
SpinLockHolder lockHolder(&pageheap_lock);
statistics.reservedVMBytes = static_cast<size_t>(pageheap->SystemBytes());
statistics.committedVMBytes = statistics.reservedVMBytes - pageheap->ReturnedBytes();
statistics.freeListBytes = 0;
for (unsigned cl = 0; cl < kNumClasses; ++cl) {
const int length = central_cache[cl].length();
const int tc_length = central_cache[cl].tc_length();
statistics.freeListBytes += ByteSizeForClass(cl) * (length + tc_length);
}
for (TCMalloc_ThreadCache* threadCache = thread_heaps; threadCache ; threadCache = threadCache->next_)
statistics.freeListBytes += threadCache->Size();
return statistics;
}
size_t fastMallocSize(const void* ptr)
{
#if ENABLE(WTF_MALLOC_VALIDATION)
return Internal::fastMallocValidationHeader(const_cast<void*>(ptr))->m_size;
#else
const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
Span* span = pageheap->GetDescriptorEnsureSafe(p);
if (!span || span->free)
return 0;
for (HardenedSLL free = span->objects; free; free = SLL_Next(free, HARDENING_ENTROPY)) {
if (ptr == free.value())
return 0;
}
if (size_t cl = span->sizeclass)
return ByteSizeForClass(cl);
return span->length << kPageShift;
#endif
}
#if OS(DARWIN)
class RemoteMemoryReader {
task_t m_task;
memory_reader_t* m_reader;
public:
RemoteMemoryReader(task_t task, memory_reader_t* reader)
: m_task(task)
, m_reader(reader)
{ }
void* operator()(vm_address_t address, size_t size) const
{
void* output;
kern_return_t err = (*m_reader)(m_task, address, size, static_cast<void**>(&output));
if (err)
output = 0;
return output;
}
template <typename T>
T* operator()(T* address, size_t size = sizeof(T)) const
{
return static_cast<T*>((*this)(reinterpret_cast<vm_address_t>(address), size));
}
template <typename T>
T* nextEntryInHardenedLinkedList(T** remoteAddress, uintptr_t entropy) const
{
T** localAddress = (*this)(remoteAddress);
if (!localAddress)
return 0;
T* hardenedNext = *localAddress;
if (!hardenedNext || hardenedNext == (void*)entropy)
return 0;
return XOR_MASK_PTR_WITH_KEY(hardenedNext, remoteAddress, entropy);
}
};
template <typename T>
template <typename Recorder>
void PageHeapAllocator<T>::recordAdministrativeRegions(Recorder& recorder, const RemoteMemoryReader& reader)
{
for (HardenedSLL adminAllocation = allocated_regions_; adminAllocation; adminAllocation.setValue(reader.nextEntryInHardenedLinkedList(reinterpret_cast<void**>(adminAllocation.value()), entropy_)))
recorder.recordRegion(reinterpret_cast<vm_address_t>(adminAllocation.value()), kAllocIncrement);
}
class FreeObjectFinder {
const RemoteMemoryReader& m_reader;
HashSet<void*> m_freeObjects;
public:
FreeObjectFinder(const RemoteMemoryReader& reader) : m_reader(reader) { }
void visit(void* ptr) { m_freeObjects.add(ptr); }
bool isFreeObject(void* ptr) const { return m_freeObjects.contains(ptr); }
bool isFreeObject(vm_address_t ptr) const { return isFreeObject(reinterpret_cast<void*>(ptr)); }
size_t freeObjectCount() const { return m_freeObjects.size(); }
void findFreeObjects(TCMalloc_ThreadCache* threadCache)
{
for (; threadCache; threadCache = (threadCache->next_ ? m_reader(threadCache->next_) : 0))
threadCache->enumerateFreeObjects(*this, m_reader);
}
void findFreeObjects(TCMalloc_Central_FreeListPadded* centralFreeList, size_t numSizes, TCMalloc_Central_FreeListPadded* remoteCentralFreeList)
{
for (unsigned i = 0; i < numSizes; i++)
centralFreeList[i].enumerateFreeObjects(*this, m_reader, remoteCentralFreeList + i);
}
};
class PageMapFreeObjectFinder {
const RemoteMemoryReader& m_reader;
FreeObjectFinder& m_freeObjectFinder;
uintptr_t m_entropy;
public:
PageMapFreeObjectFinder(const RemoteMemoryReader& reader, FreeObjectFinder& freeObjectFinder, uintptr_t entropy)
: m_reader(reader)
, m_freeObjectFinder(freeObjectFinder)
, m_entropy(entropy)
{
#if ENABLE(TCMALLOC_HARDENING)
ASSERT(m_entropy);
#endif
}
int visit(void* ptr) const
{
if (!ptr)
return 1;
Span* span = m_reader(reinterpret_cast<Span*>(ptr));
if (!span)
return 1;
if (span->free) {
void* ptr = reinterpret_cast<void*>(span->start << kPageShift);
m_freeObjectFinder.visit(ptr);
} else if (span->sizeclass) {
// Walk the free list of the small-object span, keeping track of each object seen
for (HardenedSLL nextObject = span->objects; nextObject; nextObject.setValue(m_reader.nextEntryInHardenedLinkedList(reinterpret_cast<void**>(nextObject.value()), m_entropy)))
m_freeObjectFinder.visit(nextObject.value());
}
return span->length;
}
};
class PageMapMemoryUsageRecorder {
task_t m_task;
void* m_context;
unsigned m_typeMask;
vm_range_recorder_t* m_recorder;
const RemoteMemoryReader& m_reader;
const FreeObjectFinder& m_freeObjectFinder;
HashSet<void*> m_seenPointers;
Vector<Span*> m_coalescedSpans;
public:
PageMapMemoryUsageRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader, const FreeObjectFinder& freeObjectFinder)
: m_task(task)
, m_context(context)
, m_typeMask(typeMask)
, m_recorder(recorder)
, m_reader(reader)
, m_freeObjectFinder(freeObjectFinder)
{ }
~PageMapMemoryUsageRecorder()
{
ASSERT(!m_coalescedSpans.size());
}
void recordPendingRegions()
{
if (!(m_typeMask & (MALLOC_PTR_IN_USE_RANGE_TYPE | MALLOC_PTR_REGION_RANGE_TYPE))) {
m_coalescedSpans.clear();
return;
}
Vector<vm_range_t, 1024> allocatedPointers;
for (size_t i = 0; i < m_coalescedSpans.size(); ++i) {
Span *theSpan = m_coalescedSpans[i];
if (theSpan->free)
continue;
vm_address_t spanStartAddress = theSpan->start << kPageShift;
vm_size_t spanSizeInBytes = theSpan->length * kPageSize;
if (!theSpan->sizeclass) {
// If it's an allocated large object span, mark it as in use
if (!m_freeObjectFinder.isFreeObject(spanStartAddress))
allocatedPointers.append((vm_range_t){spanStartAddress, spanSizeInBytes});
} else {
const size_t objectSize = ByteSizeForClass(theSpan->sizeclass);
// Mark each allocated small object within the span as in use
const vm_address_t endOfSpan = spanStartAddress + spanSizeInBytes;
for (vm_address_t object = spanStartAddress; object + objectSize <= endOfSpan; object += objectSize) {
if (!m_freeObjectFinder.isFreeObject(object))
allocatedPointers.append((vm_range_t){object, objectSize});
}
}
}
(*m_recorder)(m_task, m_context, m_typeMask & (MALLOC_PTR_IN_USE_RANGE_TYPE | MALLOC_PTR_REGION_RANGE_TYPE), allocatedPointers.data(), allocatedPointers.size());
m_coalescedSpans.clear();
}
int visit(void* ptr)
{
if (!ptr)
return 1;
Span* span = m_reader(reinterpret_cast<Span*>(ptr));
if (!span || !span->start)
return 1;
if (!m_seenPointers.add(ptr).isNewEntry)
return span->length;
if (!m_coalescedSpans.size()) {
m_coalescedSpans.append(span);
return span->length;
}
Span* previousSpan = m_coalescedSpans[m_coalescedSpans.size() - 1];
vm_address_t previousSpanStartAddress = previousSpan->start << kPageShift;
vm_size_t previousSpanSizeInBytes = previousSpan->length * kPageSize;
// If the new span is adjacent to the previous span, do nothing for now.
vm_address_t spanStartAddress = span->start << kPageShift;
if (spanStartAddress == previousSpanStartAddress + previousSpanSizeInBytes) {
m_coalescedSpans.append(span);
return span->length;
}
// New span is not adjacent to previous span, so record the spans coalesced so far.
recordPendingRegions();
m_coalescedSpans.append(span);
return span->length;
}
};
class AdminRegionRecorder {
task_t m_task;
void* m_context;
unsigned m_typeMask;
vm_range_recorder_t* m_recorder;
Vector<vm_range_t, 1024> m_pendingRegions;
public:
AdminRegionRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder)
: m_task(task)
, m_context(context)
, m_typeMask(typeMask)
, m_recorder(recorder)
{ }
void recordRegion(vm_address_t ptr, size_t size)
{
if (m_typeMask & MALLOC_ADMIN_REGION_RANGE_TYPE)
m_pendingRegions.append((vm_range_t){ ptr, size });
}
void visit(void *ptr, size_t size)
{
recordRegion(reinterpret_cast<vm_address_t>(ptr), size);
}
void recordPendingRegions()
{
if (m_pendingRegions.size()) {
(*m_recorder)(m_task, m_context, MALLOC_ADMIN_REGION_RANGE_TYPE, m_pendingRegions.data(), m_pendingRegions.size());
m_pendingRegions.clear();
}
}
~AdminRegionRecorder()
{
ASSERT(!m_pendingRegions.size());
}
};
kern_return_t FastMallocZone::enumerate(task_t task, void* context, unsigned typeMask, vm_address_t zoneAddress, memory_reader_t reader, vm_range_recorder_t recorder)
{
RemoteMemoryReader memoryReader(task, reader);
InitSizeClasses();
FastMallocZone* mzone = memoryReader(reinterpret_cast<FastMallocZone*>(zoneAddress));
TCMalloc_PageHeap* pageHeap = memoryReader(mzone->m_pageHeap);
TCMalloc_ThreadCache** threadHeapsPointer = memoryReader(mzone->m_threadHeaps);
TCMalloc_ThreadCache* threadHeaps = memoryReader(*threadHeapsPointer);
TCMalloc_Central_FreeListPadded* centralCaches = memoryReader(mzone->m_centralCaches, sizeof(TCMalloc_Central_FreeListPadded) * kNumClasses);
FreeObjectFinder finder(memoryReader);
finder.findFreeObjects(threadHeaps);
finder.findFreeObjects(centralCaches, kNumClasses, mzone->m_centralCaches);
TCMalloc_PageHeap::PageMap* pageMap = &pageHeap->pagemap_;
PageMapFreeObjectFinder pageMapFinder(memoryReader, finder, pageHeap->entropy_);
pageMap->visitValues(pageMapFinder, memoryReader);
PageMapMemoryUsageRecorder usageRecorder(task, context, typeMask, recorder, memoryReader, finder);
pageMap->visitValues(usageRecorder, memoryReader);
usageRecorder.recordPendingRegions();
AdminRegionRecorder adminRegionRecorder(task, context, typeMask, recorder);
pageMap->visitAllocations(adminRegionRecorder, memoryReader);
PageHeapAllocator<Span>* spanAllocator = memoryReader(mzone->m_spanAllocator);
PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator = memoryReader(mzone->m_pageHeapAllocator);
spanAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
pageHeapAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
adminRegionRecorder.recordPendingRegions();
return 0;
}
size_t FastMallocZone::size(malloc_zone_t*, const void*)
{
return 0;
}
void* FastMallocZone::zoneMalloc(malloc_zone_t*, size_t)
{
return 0;
}
void* FastMallocZone::zoneCalloc(malloc_zone_t*, size_t, size_t)
{
return 0;
}
void FastMallocZone::zoneFree(malloc_zone_t*, void* ptr)
{
// Due to <rdar://problem/5671357> zoneFree may be called by the system free even if the pointer
// is not in this zone. When this happens, the pointer being freed was not allocated by any
// zone so we need to print a useful error for the application developer.
malloc_printf("*** error for object %p: pointer being freed was not allocated\n", ptr);
}
void* FastMallocZone::zoneRealloc(malloc_zone_t*, void*, size_t)
{
return 0;
}
#undef malloc
#undef free
#undef realloc
#undef calloc
extern "C" {
malloc_introspection_t jscore_fastmalloc_introspection = { &FastMallocZone::enumerate, &FastMallocZone::goodSize, &FastMallocZone::check, &FastMallocZone::print,
&FastMallocZone::log, &FastMallocZone::forceLock, &FastMallocZone::forceUnlock, &FastMallocZone::statistics
, 0 // zone_locked will not be called on the zone unless it advertises itself as version five or higher.
#if OS(IOS) || __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
, 0, 0, 0, 0 // These members will not be used unless the zone advertises itself as version seven or higher.
#endif
};
}
FastMallocZone::FastMallocZone(TCMalloc_PageHeap* pageHeap, TCMalloc_ThreadCache** threadHeaps, TCMalloc_Central_FreeListPadded* centralCaches, PageHeapAllocator<Span>* spanAllocator, PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator)
: m_pageHeap(pageHeap)
, m_threadHeaps(threadHeaps)
, m_centralCaches(centralCaches)
, m_spanAllocator(spanAllocator)
, m_pageHeapAllocator(pageHeapAllocator)
{
memset(&m_zone, 0, sizeof(m_zone));
m_zone.version = 4;
m_zone.zone_name = "JavaScriptCore FastMalloc";
m_zone.size = &FastMallocZone::size;
m_zone.malloc = &FastMallocZone::zoneMalloc;
m_zone.calloc = &FastMallocZone::zoneCalloc;
m_zone.realloc = &FastMallocZone::zoneRealloc;
m_zone.free = &FastMallocZone::zoneFree;
m_zone.valloc = &FastMallocZone::zoneValloc;
m_zone.destroy = &FastMallocZone::zoneDestroy;
m_zone.introspect = &jscore_fastmalloc_introspection;
malloc_zone_register(&m_zone);
}
void FastMallocZone::init()
{
static FastMallocZone zone(pageheap, &thread_heaps, static_cast<TCMalloc_Central_FreeListPadded*>(central_cache), &span_allocator, &threadheap_allocator);
}
#endif // OS(DARWIN)
} // namespace WTF
#endif // WTF_CHANGES
#endif // FORCE_SYSTEM_MALLOC
| bsd-3-clause |
sharma1nitish/phantomjs | src/qt/qtwebkit/Tools/WebKitTestRunner/InjectedBundle/InjectedBundle.cpp | 116 | 25291 | /*
* Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "InjectedBundle.h"
#include "ActivateFonts.h"
#include "InjectedBundlePage.h"
#include "StringFunctions.h"
#include <WebKit2/WKBundle.h>
#include <WebKit2/WKBundlePage.h>
#include <WebKit2/WKBundlePagePrivate.h>
#include <WebKit2/WKBundlePrivate.h>
#include <WebKit2/WKRetainPtr.h>
#include <WebKit2/WebKit2_C.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/Vector.h>
namespace WTR {
InjectedBundle& InjectedBundle::shared()
{
static InjectedBundle& shared = *new InjectedBundle;
return shared;
}
InjectedBundle::InjectedBundle()
: m_bundle(0)
, m_topLoadingFrame(0)
, m_state(Idle)
, m_dumpPixels(false)
, m_useWaitToDumpWatchdogTimer(true)
, m_useWorkQueue(false)
, m_timeout(0)
{
}
void InjectedBundle::didCreatePage(WKBundleRef bundle, WKBundlePageRef page, const void* clientInfo)
{
static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didCreatePage(page);
}
void InjectedBundle::willDestroyPage(WKBundleRef bundle, WKBundlePageRef page, const void* clientInfo)
{
static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->willDestroyPage(page);
}
void InjectedBundle::didInitializePageGroup(WKBundleRef bundle, WKBundlePageGroupRef pageGroup, const void* clientInfo)
{
static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didInitializePageGroup(pageGroup);
}
void InjectedBundle::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
{
static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didReceiveMessage(messageName, messageBody);
}
void InjectedBundle::didReceiveMessageToPage(WKBundleRef bundle, WKBundlePageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
{
static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didReceiveMessageToPage(page, messageName, messageBody);
}
void InjectedBundle::initialize(WKBundleRef bundle, WKTypeRef initializationUserData)
{
m_bundle = bundle;
WKBundleClient client = {
kWKBundleClientCurrentVersion,
this,
didCreatePage,
willDestroyPage,
didInitializePageGroup,
didReceiveMessage,
didReceiveMessageToPage
};
WKBundleSetClient(m_bundle, &client);
platformInitialize(initializationUserData);
activateFonts();
WKBundleActivateMacFontAscentHack(m_bundle);
// FIXME: We'd like to start with a clean state for every test, but this function can't be used more than once yet.
WKBundleSwitchNetworkLoaderToNewTestingSession(m_bundle);
}
void InjectedBundle::didCreatePage(WKBundlePageRef page)
{
m_pages.append(adoptPtr(new InjectedBundlePage(page)));
}
void InjectedBundle::willDestroyPage(WKBundlePageRef page)
{
size_t size = m_pages.size();
for (size_t i = 0; i < size; ++i) {
if (m_pages[i]->page() == page) {
m_pages.remove(i);
break;
}
}
}
void InjectedBundle::didInitializePageGroup(WKBundlePageGroupRef pageGroup)
{
m_pageGroup = pageGroup;
}
InjectedBundlePage* InjectedBundle::page() const
{
// It might be better to have the UI process send over a reference to the main
// page instead of just assuming it's the first one.
return m_pages[0].get();
}
void InjectedBundle::resetLocalSettings()
{
setlocale(LC_ALL, "");
}
void InjectedBundle::didReceiveMessage(WKStringRef messageName, WKTypeRef messageBody)
{
if (WKStringIsEqualToUTF8CString(messageName, "BeginTest")) {
ASSERT(messageBody);
ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
WKRetainPtr<WKStringRef> dumpPixelsKey(AdoptWK, WKStringCreateWithUTF8CString("DumpPixels"));
m_dumpPixels = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, dumpPixelsKey.get())));
WKRetainPtr<WKStringRef> useWaitToDumpWatchdogTimerKey(AdoptWK, WKStringCreateWithUTF8CString("UseWaitToDumpWatchdogTimer"));
m_useWaitToDumpWatchdogTimer = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, useWaitToDumpWatchdogTimerKey.get())));
WKRetainPtr<WKStringRef> timeoutKey(AdoptWK, WKStringCreateWithUTF8CString("Timeout"));
m_timeout = (int)WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeoutKey.get())));
WKRetainPtr<WKStringRef> ackMessageName(AdoptWK, WKStringCreateWithUTF8CString("Ack"));
WKRetainPtr<WKStringRef> ackMessageBody(AdoptWK, WKStringCreateWithUTF8CString("BeginTest"));
WKBundlePostMessage(m_bundle, ackMessageName.get(), ackMessageBody.get());
beginTesting(messageBodyDictionary);
return;
} else if (WKStringIsEqualToUTF8CString(messageName, "Reset")) {
ASSERT(messageBody);
ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
WKRetainPtr<WKStringRef> shouldGCKey(AdoptWK, WKStringCreateWithUTF8CString("ShouldGC"));
bool shouldGC = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, shouldGCKey.get())));
if (shouldGC)
WKBundleGarbageCollectJavaScriptObjects(m_bundle);
m_state = Idle;
m_dumpPixels = false;
resetLocalSettings();
m_testRunner->removeAllWebNotificationPermissions();
page()->resetAfterTest();
return;
}
if (WKStringIsEqualToUTF8CString(messageName, "CallAddChromeInputFieldCallback")) {
m_testRunner->callAddChromeInputFieldCallback();
return;
}
if (WKStringIsEqualToUTF8CString(messageName, "CallRemoveChromeInputFieldCallback")) {
m_testRunner->callRemoveChromeInputFieldCallback();
return;
}
if (WKStringIsEqualToUTF8CString(messageName, "CallFocusWebViewCallback")) {
m_testRunner->callFocusWebViewCallback();
return;
}
if (WKStringIsEqualToUTF8CString(messageName, "CallSetBackingScaleFactorCallback")) {
m_testRunner->callSetBackingScaleFactorCallback();
return;
}
if (WKStringIsEqualToUTF8CString(messageName, "WorkQueueProcessedCallback")) {
if (!topLoadingFrame() && !m_testRunner->waitToDump())
page()->dump();
return;
}
WKRetainPtr<WKStringRef> errorMessageName(AdoptWK, WKStringCreateWithUTF8CString("Error"));
WKRetainPtr<WKStringRef> errorMessageBody(AdoptWK, WKStringCreateWithUTF8CString("Unknown"));
WKBundlePostMessage(m_bundle, errorMessageName.get(), errorMessageBody.get());
}
void InjectedBundle::didReceiveMessageToPage(WKBundlePageRef page, WKStringRef messageName, WKTypeRef messageBody)
{
WKRetainPtr<WKStringRef> errorMessageName(AdoptWK, WKStringCreateWithUTF8CString("Error"));
WKRetainPtr<WKStringRef> errorMessageBody(AdoptWK, WKStringCreateWithUTF8CString("Unknown"));
WKBundlePostMessage(m_bundle, errorMessageName.get(), errorMessageBody.get());
}
bool InjectedBundle::booleanForKey(WKDictionaryRef dictionary, const char* key)
{
WKRetainPtr<WKStringRef> wkKey(AdoptWK, WKStringCreateWithUTF8CString(key));
WKTypeRef value = WKDictionaryGetItemForKey(dictionary, wkKey.get());
if (WKGetTypeID(value) != WKBooleanGetTypeID()) {
outputText(makeString("Boolean value for key", key, " not found in dictionary\n"));
return false;
}
return WKBooleanGetValue(static_cast<WKBooleanRef>(value));
}
void InjectedBundle::beginTesting(WKDictionaryRef settings)
{
m_state = Testing;
m_pixelResult.clear();
m_repaintRects.clear();
m_testRunner = TestRunner::create();
m_gcController = GCController::create();
m_eventSendingController = EventSendingController::create();
m_textInputController = TextInputController::create();
m_accessibilityController = AccessibilityController::create();
WKBundleSetShouldTrackVisitedLinks(m_bundle, false);
WKBundleRemoveAllVisitedLinks(m_bundle);
WKBundleSetAllowUniversalAccessFromFileURLs(m_bundle, m_pageGroup, true);
WKBundleSetJavaScriptCanAccessClipboard(m_bundle, m_pageGroup, true);
WKBundleSetPrivateBrowsingEnabled(m_bundle, m_pageGroup, false);
WKBundleSetAuthorAndUserStylesEnabled(m_bundle, m_pageGroup, true);
WKBundleSetFrameFlatteningEnabled(m_bundle, m_pageGroup, false);
WKBundleSetMinimumLogicalFontSize(m_bundle, m_pageGroup, 9);
WKBundleSetSpatialNavigationEnabled(m_bundle, m_pageGroup, false);
WKBundleSetAllowFileAccessFromFileURLs(m_bundle, m_pageGroup, true);
WKBundleSetPluginsEnabled(m_bundle, m_pageGroup, true);
WKBundleSetPopupBlockingEnabled(m_bundle, m_pageGroup, false);
WKBundleSetAlwaysAcceptCookies(m_bundle, false);
WKBundleSetSerialLoadingEnabled(m_bundle, false);
WKBundleSetShadowDOMEnabled(m_bundle, true);
WKBundleSetSeamlessIFramesEnabled(m_bundle, true);
WKBundleSetCacheModel(m_bundle, 1 /*CacheModelDocumentBrowser*/);
WKBundleRemoveAllUserContent(m_bundle, m_pageGroup);
m_testRunner->setShouldDumpFrameLoadCallbacks(booleanForKey(settings, "DumpFrameLoadDelegates"));
m_testRunner->setUserStyleSheetEnabled(false);
m_testRunner->setXSSAuditorEnabled(false);
m_testRunner->setCloseRemainingWindowsWhenComplete(false);
m_testRunner->setAcceptsEditing(true);
m_testRunner->setTabKeyCyclesThroughElements(true);
m_testRunner->setCustomTimeout(m_timeout);
page()->prepare();
WKBundleClearAllDatabases(m_bundle);
WKBundleClearApplicationCache(m_bundle);
WKBundleResetOriginAccessWhitelists(m_bundle);
// [WK2] REGRESSION(r128623): It made layout tests extremely slow
// https://bugs.webkit.org/show_bug.cgi?id=96862
// WKBundleSetDatabaseQuota(m_bundle, 5 * 1024 * 1024);
}
void InjectedBundle::done()
{
m_state = Stopping;
m_useWorkQueue = false;
page()->stopLoading();
setTopLoadingFrame(0);
m_accessibilityController->resetToConsistentState();
WKRetainPtr<WKStringRef> doneMessageName(AdoptWK, WKStringCreateWithUTF8CString("Done"));
WKRetainPtr<WKMutableDictionaryRef> doneMessageBody(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> pixelResultKey = adoptWK(WKStringCreateWithUTF8CString("PixelResult"));
WKDictionaryAddItem(doneMessageBody.get(), pixelResultKey.get(), m_pixelResult.get());
WKRetainPtr<WKStringRef> repaintRectsKey = adoptWK(WKStringCreateWithUTF8CString("RepaintRects"));
WKDictionaryAddItem(doneMessageBody.get(), repaintRectsKey.get(), m_repaintRects.get());
WKRetainPtr<WKStringRef> audioResultKey = adoptWK(WKStringCreateWithUTF8CString("AudioResult"));
WKDictionaryAddItem(doneMessageBody.get(), audioResultKey.get(), m_audioResult.get());
WKBundlePostMessage(m_bundle, doneMessageName.get(), doneMessageBody.get());
closeOtherPages();
m_state = Idle;
}
void InjectedBundle::closeOtherPages()
{
Vector<WKBundlePageRef> pagesToClose;
size_t size = m_pages.size();
for (size_t i = 1; i < size; ++i)
pagesToClose.append(m_pages[i]->page());
size = pagesToClose.size();
for (size_t i = 0; i < size; ++i)
WKBundlePageClose(pagesToClose[i]);
}
void InjectedBundle::dumpBackForwardListsForAllPages(StringBuilder& stringBuilder)
{
size_t size = m_pages.size();
for (size_t i = 0; i < size; ++i)
m_pages[i]->dumpBackForwardList(stringBuilder);
}
void InjectedBundle::outputText(const String& output)
{
if (m_state != Testing)
return;
if (output.isEmpty())
return;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("TextOutput"));
WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithUTF8CString(output.utf8().data()));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::postNewBeforeUnloadReturnValue(bool value)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("BeforeUnloadReturnValue"));
WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::postAddChromeInputField()
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("AddChromeInputField"));
WKBundlePostMessage(m_bundle, messageName.get(), 0);
}
void InjectedBundle::postRemoveChromeInputField()
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RemoveChromeInputField"));
WKBundlePostMessage(m_bundle, messageName.get(), 0);
}
void InjectedBundle::postFocusWebView()
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("FocusWebView"));
WKBundlePostMessage(m_bundle, messageName.get(), 0);
}
void InjectedBundle::postSetBackingScaleFactor(double backingScaleFactor)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBackingScaleFactor"));
WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(backingScaleFactor));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::postSetWindowIsKey(bool isKey)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetWindowIsKey"));
WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(isKey));
WKBundlePostSynchronousMessage(m_bundle, messageName.get(), messageBody.get(), 0);
}
void InjectedBundle::postSimulateWebNotificationClick(uint64_t notificationID)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SimulateWebNotificationClick"));
WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(notificationID));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::setGeolocationPermission(bool enabled)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetGeolocationPermission"));
WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(enabled));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::setMockGeolocationPosition(double latitude, double longitude, double accuracy, bool providesAltitude, double altitude, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGeolocationPosition"));
WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> latitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("latitude"));
WKRetainPtr<WKDoubleRef> latitudeWK(AdoptWK, WKDoubleCreate(latitude));
WKDictionaryAddItem(messageBody.get(), latitudeKeyWK.get(), latitudeWK.get());
WKRetainPtr<WKStringRef> longitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("longitude"));
WKRetainPtr<WKDoubleRef> longitudeWK(AdoptWK, WKDoubleCreate(longitude));
WKDictionaryAddItem(messageBody.get(), longitudeKeyWK.get(), longitudeWK.get());
WKRetainPtr<WKStringRef> accuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("accuracy"));
WKRetainPtr<WKDoubleRef> accuracyWK(AdoptWK, WKDoubleCreate(accuracy));
WKDictionaryAddItem(messageBody.get(), accuracyKeyWK.get(), accuracyWK.get());
WKRetainPtr<WKStringRef> providesAltitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesAltitude"));
WKRetainPtr<WKBooleanRef> providesAltitudeWK(AdoptWK, WKBooleanCreate(providesAltitude));
WKDictionaryAddItem(messageBody.get(), providesAltitudeKeyWK.get(), providesAltitudeWK.get());
WKRetainPtr<WKStringRef> altitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("altitude"));
WKRetainPtr<WKDoubleRef> altitudeWK(AdoptWK, WKDoubleCreate(altitude));
WKDictionaryAddItem(messageBody.get(), altitudeKeyWK.get(), altitudeWK.get());
WKRetainPtr<WKStringRef> providesAltitudeAccuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesAltitudeAccuracy"));
WKRetainPtr<WKBooleanRef> providesAltitudeAccuracyWK(AdoptWK, WKBooleanCreate(providesAltitudeAccuracy));
WKDictionaryAddItem(messageBody.get(), providesAltitudeAccuracyKeyWK.get(), providesAltitudeAccuracyWK.get());
WKRetainPtr<WKStringRef> altitudeAccuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("altitudeAccuracy"));
WKRetainPtr<WKDoubleRef> altitudeAccuracyWK(AdoptWK, WKDoubleCreate(altitudeAccuracy));
WKDictionaryAddItem(messageBody.get(), altitudeAccuracyKeyWK.get(), altitudeAccuracyWK.get());
WKRetainPtr<WKStringRef> providesHeadingKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesHeading"));
WKRetainPtr<WKBooleanRef> providesHeadingWK(AdoptWK, WKBooleanCreate(providesHeading));
WKDictionaryAddItem(messageBody.get(), providesHeadingKeyWK.get(), providesHeadingWK.get());
WKRetainPtr<WKStringRef> headingKeyWK(AdoptWK, WKStringCreateWithUTF8CString("heading"));
WKRetainPtr<WKDoubleRef> headingWK(AdoptWK, WKDoubleCreate(heading));
WKDictionaryAddItem(messageBody.get(), headingKeyWK.get(), headingWK.get());
WKRetainPtr<WKStringRef> providesSpeedKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesSpeed"));
WKRetainPtr<WKBooleanRef> providesSpeedWK(AdoptWK, WKBooleanCreate(providesSpeed));
WKDictionaryAddItem(messageBody.get(), providesSpeedKeyWK.get(), providesSpeedWK.get());
WKRetainPtr<WKStringRef> speedKeyWK(AdoptWK, WKStringCreateWithUTF8CString("speed"));
WKRetainPtr<WKDoubleRef> speedWK(AdoptWK, WKDoubleCreate(speed));
WKDictionaryAddItem(messageBody.get(), speedKeyWK.get(), speedWK.get());
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGeolocationPositionUnavailableError"));
WKBundlePostMessage(m_bundle, messageName.get(), errorMessage);
}
void InjectedBundle::setCustomPolicyDelegate(bool enabled, bool permissive)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetCustomPolicyDelegate"));
WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> enabledKeyWK(AdoptWK, WKStringCreateWithUTF8CString("enabled"));
WKRetainPtr<WKBooleanRef> enabledWK(AdoptWK, WKBooleanCreate(enabled));
WKDictionaryAddItem(messageBody.get(), enabledKeyWK.get(), enabledWK.get());
WKRetainPtr<WKStringRef> permissiveKeyWK(AdoptWK, WKStringCreateWithUTF8CString("permissive"));
WKRetainPtr<WKBooleanRef> permissiveWK(AdoptWK, WKBooleanCreate(permissive));
WKDictionaryAddItem(messageBody.get(), permissiveKeyWK.get(), permissiveWK.get());
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::setVisibilityState(WKPageVisibilityState visibilityState, bool isInitialState)
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetVisibilityState"));
WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> visibilityStateKeyWK(AdoptWK, WKStringCreateWithUTF8CString("visibilityState"));
WKRetainPtr<WKUInt64Ref> visibilityStateWK(AdoptWK, WKUInt64Create(visibilityState));
WKDictionaryAddItem(messageBody.get(), visibilityStateKeyWK.get(), visibilityStateWK.get());
WKRetainPtr<WKStringRef> isInitialKeyWK(AdoptWK, WKStringCreateWithUTF8CString("isInitialState"));
WKRetainPtr<WKBooleanRef> isInitialWK(AdoptWK, WKBooleanCreate(isInitialState));
WKDictionaryAddItem(messageBody.get(), isInitialKeyWK.get(), isInitialWK.get());
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
bool InjectedBundle::shouldProcessWorkQueue() const
{
if (!m_useWorkQueue)
return false;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsWorkQueueEmpty"));
WKTypeRef resultToPass = 0;
WKBundlePostSynchronousMessage(m_bundle, messageName.get(), 0, &resultToPass);
WKRetainPtr<WKBooleanRef> isEmpty(AdoptWK, static_cast<WKBooleanRef>(resultToPass));
return !WKBooleanGetValue(isEmpty.get());
}
void InjectedBundle::processWorkQueue()
{
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ProcessWorkQueue"));
WKBundlePostMessage(m_bundle, messageName.get(), 0);
}
void InjectedBundle::queueBackNavigation(unsigned howFarBackward)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueBackNavigation"));
WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(howFarBackward));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::queueForwardNavigation(unsigned howFarForward)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueForwardNavigation"));
WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(howFarForward));
WKBundlePostMessage(m_bundle, messageName.get(), messageBody.get());
}
void InjectedBundle::queueLoad(WKStringRef url, WKStringRef target)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoad"));
WKRetainPtr<WKMutableDictionaryRef> loadData(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> urlKey(AdoptWK, WKStringCreateWithUTF8CString("url"));
WKDictionaryAddItem(loadData.get(), urlKey.get(), url);
WKRetainPtr<WKStringRef> targetKey(AdoptWK, WKStringCreateWithUTF8CString("target"));
WKDictionaryAddItem(loadData.get(), targetKey.get(), target);
WKBundlePostMessage(m_bundle, messageName.get(), loadData.get());
}
void InjectedBundle::queueLoadHTMLString(WKStringRef content, WKStringRef baseURL, WKStringRef unreachableURL)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoadHTMLString"));
WKRetainPtr<WKMutableDictionaryRef> loadData(AdoptWK, WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> contentKey(AdoptWK, WKStringCreateWithUTF8CString("content"));
WKDictionaryAddItem(loadData.get(), contentKey.get(), content);
if (baseURL) {
WKRetainPtr<WKStringRef> baseURLKey(AdoptWK, WKStringCreateWithUTF8CString("baseURL"));
WKDictionaryAddItem(loadData.get(), baseURLKey.get(), baseURL);
}
if (unreachableURL) {
WKRetainPtr<WKStringRef> unreachableURLKey(AdoptWK, WKStringCreateWithUTF8CString("unreachableURL"));
WKDictionaryAddItem(loadData.get(), unreachableURLKey.get(), unreachableURL);
}
WKBundlePostMessage(m_bundle, messageName.get(), loadData.get());
}
void InjectedBundle::queueReload()
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueReload"));
WKBundlePostMessage(m_bundle, messageName.get(), 0);
}
void InjectedBundle::queueLoadingScript(WKStringRef script)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoadingScript"));
WKBundlePostMessage(m_bundle, messageName.get(), script);
}
void InjectedBundle::queueNonLoadingScript(WKStringRef script)
{
m_useWorkQueue = true;
WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueNonLoadingScript"));
WKBundlePostMessage(m_bundle, messageName.get(), script);
}
} // namespace WTR
| bsd-3-clause |
AlbandeCrevoisier/ldd-athens | linux-socfpga/net/netfilter/ipset/ip_set_getport.c | 886 | 3884 | /* Copyright (C) 2003-2011 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* 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.
*/
/* Get Layer-4 data from the packets */
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/icmp.h>
#include <linux/icmpv6.h>
#include <linux/sctp.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <linux/netfilter/ipset/ip_set_getport.h>
#include <linux/export.h>
/* We must handle non-linear skbs */
static bool
get_port(const struct sk_buff *skb, int protocol, unsigned int protooff,
bool src, __be16 *port, u8 *proto)
{
switch (protocol) {
case IPPROTO_TCP: {
struct tcphdr _tcph;
const struct tcphdr *th;
th = skb_header_pointer(skb, protooff, sizeof(_tcph), &_tcph);
if (!th)
/* No choice either */
return false;
*port = src ? th->source : th->dest;
break;
}
case IPPROTO_SCTP: {
sctp_sctphdr_t _sh;
const sctp_sctphdr_t *sh;
sh = skb_header_pointer(skb, protooff, sizeof(_sh), &_sh);
if (!sh)
/* No choice either */
return false;
*port = src ? sh->source : sh->dest;
break;
}
case IPPROTO_UDP:
case IPPROTO_UDPLITE: {
struct udphdr _udph;
const struct udphdr *uh;
uh = skb_header_pointer(skb, protooff, sizeof(_udph), &_udph);
if (!uh)
/* No choice either */
return false;
*port = src ? uh->source : uh->dest;
break;
}
case IPPROTO_ICMP: {
struct icmphdr _ich;
const struct icmphdr *ic;
ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
if (!ic)
return false;
*port = (__force __be16)htons((ic->type << 8) | ic->code);
break;
}
case IPPROTO_ICMPV6: {
struct icmp6hdr _ich;
const struct icmp6hdr *ic;
ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
if (!ic)
return false;
*port = (__force __be16)
htons((ic->icmp6_type << 8) | ic->icmp6_code);
break;
}
default:
break;
}
*proto = protocol;
return true;
}
bool
ip_set_get_ip4_port(const struct sk_buff *skb, bool src,
__be16 *port, u8 *proto)
{
const struct iphdr *iph = ip_hdr(skb);
unsigned int protooff = skb_network_offset(skb) + ip_hdrlen(skb);
int protocol = iph->protocol;
/* See comments at tcp_match in ip_tables.c */
if (protocol <= 0)
return false;
if (ntohs(iph->frag_off) & IP_OFFSET)
switch (protocol) {
case IPPROTO_TCP:
case IPPROTO_SCTP:
case IPPROTO_UDP:
case IPPROTO_UDPLITE:
case IPPROTO_ICMP:
/* Port info not available for fragment offset > 0 */
return false;
default:
/* Other protocols doesn't have ports,
* so we can match fragments.
*/
*proto = protocol;
return true;
}
return get_port(skb, protocol, protooff, src, port, proto);
}
EXPORT_SYMBOL_GPL(ip_set_get_ip4_port);
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
bool
ip_set_get_ip6_port(const struct sk_buff *skb, bool src,
__be16 *port, u8 *proto)
{
int protoff;
u8 nexthdr;
__be16 frag_off = 0;
nexthdr = ipv6_hdr(skb)->nexthdr;
protoff = ipv6_skip_exthdr(skb,
skb_network_offset(skb) +
sizeof(struct ipv6hdr), &nexthdr,
&frag_off);
if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
return false;
return get_port(skb, nexthdr, protoff, src, port, proto);
}
EXPORT_SYMBOL_GPL(ip_set_get_ip6_port);
#endif
bool
ip_set_get_ip_port(const struct sk_buff *skb, u8 pf, bool src, __be16 *port)
{
bool ret;
u8 proto;
switch (pf) {
case NFPROTO_IPV4:
ret = ip_set_get_ip4_port(skb, src, port, &proto);
break;
case NFPROTO_IPV6:
ret = ip_set_get_ip6_port(skb, src, port, &proto);
break;
default:
return false;
}
if (!ret)
return ret;
switch (proto) {
case IPPROTO_TCP:
case IPPROTO_UDP:
return true;
default:
return false;
}
}
EXPORT_SYMBOL_GPL(ip_set_get_ip_port);
| bsd-3-clause |
kyroskoh/phantomjs | src/qt/qtwebkit/Source/WebCore/bridge/jsc/BridgeJSC.cpp | 119 | 3158 | /*
* Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
* Copyright 2010, The Android Open Source Project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BridgeJSC.h"
#include "JSDOMWindowBase.h"
#include "runtime_object.h"
#include "runtime_root.h"
#include "runtime/JSLock.h"
#include "runtime/ObjectPrototype.h"
#if PLATFORM(QT)
#include "qt_instance.h"
#endif
namespace JSC {
namespace Bindings {
Array::Array(PassRefPtr<RootObject> rootObject)
: m_rootObject(rootObject)
{
ASSERT(m_rootObject);
}
Array::~Array()
{
}
Instance::Instance(PassRefPtr<RootObject> rootObject)
: m_rootObject(rootObject)
{
ASSERT(m_rootObject);
}
Instance::~Instance()
{
ASSERT(!m_runtimeObject);
}
void Instance::begin()
{
virtualBegin();
}
void Instance::end()
{
virtualEnd();
}
JSObject* Instance::createRuntimeObject(ExecState* exec)
{
ASSERT(m_rootObject);
ASSERT(m_rootObject->isValid());
if (RuntimeObject* existingObject = m_runtimeObject.get())
return existingObject;
JSLockHolder lock(exec);
RuntimeObject* newObject = newRuntimeObject(exec);
m_runtimeObject = PassWeak<RuntimeObject>(newObject);
m_rootObject->addRuntimeObject(exec->vm(), newObject);
return newObject;
}
RuntimeObject* Instance::newRuntimeObject(ExecState* exec)
{
JSLockHolder lock(exec);
// FIXME: deprecatedGetDOMStructure uses the prototype off of the wrong global object
// We need to pass in the right global object for "i".
return RuntimeObject::create(exec, exec->lexicalGlobalObject(), WebCore::deprecatedGetDOMStructure<RuntimeObject>(exec), this);
}
void Instance::willInvalidateRuntimeObject()
{
m_runtimeObject.clear();
}
RootObject* Instance::rootObject() const
{
return m_rootObject && m_rootObject->isValid() ? m_rootObject.get() : 0;
}
} // namespace Bindings
} // namespace JSC
| bsd-3-clause |
joomel1/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/audio/HRTFKernel.cpp | 119 | 5490 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "HRTFKernel.h"
#include "AudioChannel.h"
#include "Biquad.h"
#include "FFTFrame.h"
#include "FloatConversion.h"
#include <wtf/MathExtras.h>
using namespace std;
namespace WebCore {
// Takes the input AudioChannel as an input impulse response and calculates the average group delay.
// This represents the initial delay before the most energetic part of the impulse response.
// The sample-frame delay is removed from the impulseP impulse response, and this value is returned.
// the length of the passed in AudioChannel must be a power of 2.
static float extractAverageGroupDelay(AudioChannel* channel, size_t analysisFFTSize)
{
ASSERT(channel);
float* impulseP = channel->mutableData();
bool isSizeGood = channel->length() >= analysisFFTSize;
ASSERT(isSizeGood);
if (!isSizeGood)
return 0;
// Check for power-of-2.
ASSERT(1UL << static_cast<unsigned>(log2(analysisFFTSize)) == analysisFFTSize);
FFTFrame estimationFrame(analysisFFTSize);
estimationFrame.doFFT(impulseP);
float frameDelay = narrowPrecisionToFloat(estimationFrame.extractAverageGroupDelay());
estimationFrame.doInverseFFT(impulseP);
return frameDelay;
}
HRTFKernel::HRTFKernel(AudioChannel* channel, size_t fftSize, float sampleRate)
: m_frameDelay(0)
, m_sampleRate(sampleRate)
{
ASSERT(channel);
// Determine the leading delay (average group delay) for the response.
m_frameDelay = extractAverageGroupDelay(channel, fftSize / 2);
float* impulseResponse = channel->mutableData();
size_t responseLength = channel->length();
// We need to truncate to fit into 1/2 the FFT size (with zero padding) in order to do proper convolution.
size_t truncatedResponseLength = min(responseLength, fftSize / 2); // truncate if necessary to max impulse response length allowed by FFT
// Quick fade-out (apply window) at truncation point
unsigned numberOfFadeOutFrames = static_cast<unsigned>(sampleRate / 4410); // 10 sample-frames @44.1KHz sample-rate
ASSERT(numberOfFadeOutFrames < truncatedResponseLength);
if (numberOfFadeOutFrames < truncatedResponseLength) {
for (unsigned i = truncatedResponseLength - numberOfFadeOutFrames; i < truncatedResponseLength; ++i) {
float x = 1.0f - static_cast<float>(i - (truncatedResponseLength - numberOfFadeOutFrames)) / numberOfFadeOutFrames;
impulseResponse[i] *= x;
}
}
m_fftFrame = adoptPtr(new FFTFrame(fftSize));
m_fftFrame->doPaddedFFT(impulseResponse, truncatedResponseLength);
}
size_t HRTFKernel::fftSize() const
{
return m_fftFrame->fftSize();
}
PassOwnPtr<AudioChannel> HRTFKernel::createImpulseResponse()
{
OwnPtr<AudioChannel> channel = adoptPtr(new AudioChannel(fftSize()));
FFTFrame fftFrame(*m_fftFrame);
// Add leading delay back in.
fftFrame.addConstantGroupDelay(m_frameDelay);
fftFrame.doInverseFFT(channel->mutableData());
return channel.release();
}
// Interpolates two kernels with x: 0 -> 1 and returns the result.
PassRefPtr<HRTFKernel> HRTFKernel::createInterpolatedKernel(HRTFKernel* kernel1, HRTFKernel* kernel2, float x)
{
ASSERT(kernel1 && kernel2);
if (!kernel1 || !kernel2)
return 0;
ASSERT(x >= 0.0 && x < 1.0);
x = min(1.0f, max(0.0f, x));
float sampleRate1 = kernel1->sampleRate();
float sampleRate2 = kernel2->sampleRate();
ASSERT(sampleRate1 == sampleRate2);
if (sampleRate1 != sampleRate2)
return 0;
float frameDelay = (1 - x) * kernel1->frameDelay() + x * kernel2->frameDelay();
OwnPtr<FFTFrame> interpolatedFrame = FFTFrame::createInterpolatedFrame(*kernel1->fftFrame(), *kernel2->fftFrame(), x);
return HRTFKernel::create(interpolatedFrame.release(), frameDelay, sampleRate1);
}
} // namespace WebCore
#endif // ENABLE(WEB_AUDIO)
| bsd-3-clause |
admetricks/phantomjs | src/qt/qtwebkit/Source/WebKit/win/WebKitClassFactory.cpp | 123 | 5884 | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitDLL.h"
#include "WebKitClassFactory.h"
#include "CFDictionaryPropertyBag.h"
#include "ForEachCoClass.h"
#include "WebArchive.h"
#include "WebCache.h"
#include "WebCookieManager.h"
#include "WebCoreStatistics.h"
#include "WebDatabaseManager.h"
#include "WebDownload.h"
#include "WebError.h"
#include "WebFrame.h"
#include "WebGeolocationPosition.h"
#include "WebHistory.h"
#include "WebHistoryItem.h"
#include "WebIconDatabase.h"
#include "WebJavaScriptCollector.h"
#include "WebKit.h"
#include "WebKitStatistics.h"
#include "WebMutableURLRequest.h"
#include "WebNotificationCenter.h"
#include "WebPreferences.h"
#include "WebScriptWorld.h"
#include "WebScrollBar.h"
#include "WebSerializedJSValue.h"
#include "WebTextRenderer.h"
#include "WebURLCredential.h"
#include "WebURLProtectionSpace.h"
#include "WebURLResponse.h"
#include "WebUserContentURLPattern.h"
#include "WebView.h"
#include "WebWorkersPrivate.h"
#include <JavaScriptCore/InitializeThreading.h>
#include <WebCore/SoftLinking.h>
#include <wtf/MainThread.h>
// WebKitClassFactory ---------------------------------------------------------
#if USE(SAFARI_THEME)
#ifdef DEBUG_ALL
SOFT_LINK_DEBUG_LIBRARY(SafariTheme)
#else
SOFT_LINK_LIBRARY(SafariTheme)
#endif
SOFT_LINK(SafariTheme, STInitialize, void, APIENTRY, (), ())
#endif
WebKitClassFactory::WebKitClassFactory(CLSID targetClass)
: m_targetClass(targetClass)
, m_refCount(0)
{
#if USE(SAFARI_THEME)
static bool didInitializeSafariTheme;
if (!didInitializeSafariTheme) {
if (SafariThemeLibrary())
STInitialize();
didInitializeSafariTheme = true;
}
#endif
JSC::initializeThreading();
WTF::initializeMainThread();
gClassCount++;
gClassNameCount.add("WebKitClassFactory");
}
WebKitClassFactory::~WebKitClassFactory()
{
gClassCount--;
gClassNameCount.remove("WebKitClassFactory");
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebKitClassFactory::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IUnknown*>(this);
else if (IsEqualGUID(riid, IID_IClassFactory))
*ppvObject = static_cast<IClassFactory*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebKitClassFactory::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebKitClassFactory::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef && !gLockCount)
delete(this);
return newRef;
}
// FIXME: Remove these functions once all createInstance() functions return COMPtr.
template <typename T>
static T* leakRefFromCreateInstance(T* object)
{
return object;
}
template <typename T>
static T* leakRefFromCreateInstance(COMPtr<T> object)
{
return object.leakRef();
}
// IClassFactory --------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebKitClassFactory::CreateInstance(IUnknown* pUnkOuter, REFIID riid, void** ppvObject)
{
IUnknown* unknown = 0;
*ppvObject = 0;
if (pUnkOuter)
return CLASS_E_NOAGGREGATION;
#define INITIALIZE_IF_CLASS(cls) \
if (IsEqualGUID(m_targetClass, CLSID_##cls)) \
unknown = static_cast<I##cls*>(leakRefFromCreateInstance(cls::createInstance())); \
else \
// end of macro
// These #defines are needed to appease the INITIALIZE_IF_CLASS macro.
// There is no ICFDictionaryPropertyBag, we use IPropertyBag instead.
#define ICFDictionaryPropertyBag IPropertyBag
// There is no IWebScrollBar, we only have IWebScrollBarPrivate.
#define IWebScrollBar IWebScrollBarPrivate
// There is no class called WebURLRequest -- WebMutableURLRequest implements it for us.
#define WebURLRequest WebMutableURLRequest
FOR_EACH_COCLASS(INITIALIZE_IF_CLASS)
// This is the final else case
return CLASS_E_CLASSNOTAVAILABLE;
#undef ICFDictionaryPropertyBag
#undef IWebScrollBar
#undef WebURLRequest
#undef INITIALIZE_IF_CLASS
if (!unknown)
return E_OUTOFMEMORY;
HRESULT hr = unknown->QueryInterface(riid, ppvObject);
if (FAILED(hr))
delete unknown;
else
unknown->Release(); // both createInstance() and QueryInterface() added refs
return hr;
}
HRESULT STDMETHODCALLTYPE WebKitClassFactory::LockServer(BOOL fLock)
{
if (fLock)
gLockCount++;
else
gLockCount--;
return S_OK;
}
| bsd-3-clause |
Lochlan/phantomjs | src/qt/qtwebkit/Source/WebCore/rendering/mathml/RenderMathMLSquareRoot.cpp | 125 | 1705 | /*
* Copyright (C) 2009 Alex Milowski (alex@milowski.com). All rights reserved.
* Copyright (C) 2010 François Sausset (sausset@gmail.com). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(MATHML)
#include "RenderMathMLSquareRoot.h"
namespace WebCore {
RenderMathMLSquareRoot::RenderMathMLSquareRoot(Element* element)
: RenderMathMLRoot(element)
{
}
}
#endif // ENABLE(MATHML)
| bsd-3-clause |
GeyerA/android_external_chromium_org | third_party/sqlite/src/src/test_wholenumber.c | 144 | 8380 | /*
** 2011 April 02
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements a virtual table that returns the whole numbers
** between 1 and 4294967295, inclusive.
**
** Example:
**
** CREATE VIRTUAL TABLE nums USING wholenumber;
** SELECT value FROM nums WHERE value<10;
**
** Results in:
**
** 1 2 3 4 5 6 7 8 9
*/
#include "sqlite3.h"
#include <assert.h>
#include <string.h>
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* A wholenumber cursor object */
typedef struct wholenumber_cursor wholenumber_cursor;
struct wholenumber_cursor {
sqlite3_vtab_cursor base; /* Base class - must be first */
unsigned iValue; /* Current value */
unsigned mxValue; /* Maximum value */
};
/* Methods for the wholenumber module */
static int wholenumberConnect(
sqlite3 *db,
void *pAux,
int argc, const char *const*argv,
sqlite3_vtab **ppVtab,
char **pzErr
){
sqlite3_vtab *pNew;
pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
if( pNew==0 ) return SQLITE_NOMEM;
sqlite3_declare_vtab(db, "CREATE TABLE x(value)");
memset(pNew, 0, sizeof(*pNew));
return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */
static int wholenumberDisconnect(sqlite3_vtab *pVtab){
sqlite3_free(pVtab);
return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */
/*
** Open a new wholenumber cursor.
*/
static int wholenumberOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
wholenumber_cursor *pCur;
pCur = sqlite3_malloc( sizeof(*pCur) );
if( pCur==0 ) return SQLITE_NOMEM;
memset(pCur, 0, sizeof(*pCur));
*ppCursor = &pCur->base;
return SQLITE_OK;
}
/*
** Close a wholenumber cursor.
*/
static int wholenumberClose(sqlite3_vtab_cursor *cur){
sqlite3_free(cur);
return SQLITE_OK;
}
/*
** Advance a cursor to its next row of output
*/
static int wholenumberNext(sqlite3_vtab_cursor *cur){
wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
pCur->iValue++;
return SQLITE_OK;
}
/*
** Return the value associated with a wholenumber.
*/
static int wholenumberColumn(
sqlite3_vtab_cursor *cur,
sqlite3_context *ctx,
int i
){
wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
sqlite3_result_int64(ctx, pCur->iValue);
return SQLITE_OK;
}
/*
** The rowid.
*/
static int wholenumberRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
*pRowid = pCur->iValue;
return SQLITE_OK;
}
/*
** When the wholenumber_cursor.rLimit value is 0 or less, that is a signal
** that the cursor has nothing more to output.
*/
static int wholenumberEof(sqlite3_vtab_cursor *cur){
wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
return pCur->iValue>pCur->mxValue || pCur->iValue==0;
}
/*
** Called to "rewind" a cursor back to the beginning so that
** it starts its output over again. Always called at least once
** prior to any wholenumberColumn, wholenumberRowid, or wholenumberEof call.
**
** idxNum Constraints
** ------ ---------------------
** 0 (none)
** 1 value > $argv0
** 2 value >= $argv0
** 4 value < $argv0
** 8 value <= $argv0
**
** 5 value > $argv0 AND value < $argv1
** 6 value >= $argv0 AND value < $argv1
** 9 value > $argv0 AND value <= $argv1
** 10 value >= $argv0 AND value <= $argv1
*/
static int wholenumberFilter(
sqlite3_vtab_cursor *pVtabCursor,
int idxNum, const char *idxStr,
int argc, sqlite3_value **argv
){
wholenumber_cursor *pCur = (wholenumber_cursor *)pVtabCursor;
sqlite3_int64 v;
int i = 0;
pCur->iValue = 1;
pCur->mxValue = 0xffffffff; /* 4294967295 */
if( idxNum & 3 ){
v = sqlite3_value_int64(argv[0]) + (idxNum&1);
if( v>pCur->iValue && v<=pCur->mxValue ) pCur->iValue = v;
i++;
}
if( idxNum & 12 ){
v = sqlite3_value_int64(argv[i]) - ((idxNum>>2)&1);
if( v>=pCur->iValue && v<pCur->mxValue ) pCur->mxValue = v;
}
return SQLITE_OK;
}
/*
** Search for terms of these forms:
**
** (1) value > $value
** (2) value >= $value
** (4) value < $value
** (8) value <= $value
**
** idxNum is an ORed combination of 1 or 2 with 4 or 8.
*/
static int wholenumberBestIndex(
sqlite3_vtab *tab,
sqlite3_index_info *pIdxInfo
){
int i;
int idxNum = 0;
int argvIdx = 1;
int ltIdx = -1;
int gtIdx = -1;
const struct sqlite3_index_constraint *pConstraint;
pConstraint = pIdxInfo->aConstraint;
for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
if( pConstraint->usable==0 ) continue;
if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GT ){
idxNum |= 1;
ltIdx = i;
}
if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GE ){
idxNum |= 2;
ltIdx = i;
}
if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ){
idxNum |= 4;
gtIdx = i;
}
if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE ){
idxNum |= 8;
gtIdx = i;
}
}
pIdxInfo->idxNum = idxNum;
if( ltIdx>=0 ){
pIdxInfo->aConstraintUsage[ltIdx].argvIndex = argvIdx++;
pIdxInfo->aConstraintUsage[ltIdx].omit = 1;
}
if( gtIdx>=0 ){
pIdxInfo->aConstraintUsage[gtIdx].argvIndex = argvIdx;
pIdxInfo->aConstraintUsage[gtIdx].omit = 1;
}
if( pIdxInfo->nOrderBy==1
&& pIdxInfo->aOrderBy[0].desc==0
){
pIdxInfo->orderByConsumed = 1;
}
pIdxInfo->estimatedCost = (double)1;
return SQLITE_OK;
}
/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite3_module wholenumberModule = {
0, /* iVersion */
wholenumberConnect,
wholenumberConnect,
wholenumberBestIndex,
wholenumberDisconnect,
wholenumberDisconnect,
wholenumberOpen, /* xOpen - open a cursor */
wholenumberClose, /* xClose - close a cursor */
wholenumberFilter, /* xFilter - configure scan constraints */
wholenumberNext, /* xNext - advance a cursor */
wholenumberEof, /* xEof - check for end of scan */
wholenumberColumn, /* xColumn - read data */
wholenumberRowid, /* xRowid - read data */
0, /* xUpdate */
0, /* xBegin */
0, /* xSync */
0, /* xCommit */
0, /* xRollback */
0, /* xFindMethod */
0, /* xRename */
};
#endif /* SQLITE_OMIT_VIRTUALTABLE */
/*
** Register the wholenumber virtual table
*/
int wholenumber_register(sqlite3 *db){
int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_VIRTUALTABLE
rc = sqlite3_create_module(db, "wholenumber", &wholenumberModule, 0);
#endif
return rc;
}
#ifdef SQLITE_TEST
#include <tcl.h>
/*
** Decode a pointer to an sqlite3 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);
/*
** Register the echo virtual table module.
*/
static int register_wholenumber_module(
ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int objc, /* Number of arguments */
Tcl_Obj *CONST objv[] /* Command arguments */
){
sqlite3 *db;
if( objc!=2 ){
Tcl_WrongNumArgs(interp, 1, objv, "DB");
return TCL_ERROR;
}
if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
wholenumber_register(db);
return TCL_OK;
}
/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestwholenumber_Init(Tcl_Interp *interp){
static struct {
char *zName;
Tcl_ObjCmdProc *xProc;
void *clientData;
} aObjCmd[] = {
{ "register_wholenumber_module", register_wholenumber_module, 0 },
};
int i;
for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
}
return TCL_OK;
}
#endif /* SQLITE_TEST */
| bsd-3-clause |
Dapid/scipy | scipy/special/amos/zwrsk.f | 157 | 3329 | SUBROUTINE ZWRSK(ZRR, ZRI, FNU, KODE, N, YR, YI, NZ, CWR, CWI,
* TOL, ELIM, ALIM)
C***BEGIN PROLOGUE ZWRSK
C***REFER TO ZBESI,ZBESK
C
C ZWRSK COMPUTES THE I BESSEL FUNCTION FOR RE(Z).GE.0.0 BY
C NORMALIZING THE I FUNCTION RATIOS FROM ZRATI BY THE WRONSKIAN
C
C***ROUTINES CALLED D1MACH,ZBKNU,ZRATI,AZABS
C***END PROLOGUE ZWRSK
C COMPLEX CINU,CSCL,CT,CW,C1,C2,RCT,ST,Y,ZR
DOUBLE PRECISION ACT, ACW, ALIM, ASCLE, CINUI, CINUR, CSCLR, CTI,
* CTR, CWI, CWR, C1I, C1R, C2I, C2R, ELIM, FNU, PTI, PTR, RACT,
* STI, STR, TOL, YI, YR, ZRI, ZRR, AZABS, D1MACH
INTEGER I, KODE, N, NW, NZ
DIMENSION YR(N), YI(N), CWR(2), CWI(2)
C-----------------------------------------------------------------------
C I(FNU+I-1,Z) BY BACKWARD RECURRENCE FOR RATIOS
C Y(I)=I(FNU+I,Z)/I(FNU+I-1,Z) FROM CRATI NORMALIZED BY THE
C WRONSKIAN WITH K(FNU,Z) AND K(FNU+1,Z) FROM CBKNU.
C-----------------------------------------------------------------------
NZ = 0
CALL ZBKNU(ZRR, ZRI, FNU, KODE, 2, CWR, CWI, NW, TOL, ELIM, ALIM)
IF (NW.NE.0) GO TO 50
CALL ZRATI(ZRR, ZRI, FNU, N, YR, YI, TOL)
C-----------------------------------------------------------------------
C RECUR FORWARD ON I(FNU+1,Z) = R(FNU,Z)*I(FNU,Z),
C R(FNU+J-1,Z)=Y(J), J=1,...,N
C-----------------------------------------------------------------------
CINUR = 1.0D0
CINUI = 0.0D0
IF (KODE.EQ.1) GO TO 10
CINUR = DCOS(ZRI)
CINUI = DSIN(ZRI)
10 CONTINUE
C-----------------------------------------------------------------------
C ON LOW EXPONENT MACHINES THE K FUNCTIONS CAN BE CLOSE TO BOTH
C THE UNDER AND OVERFLOW LIMITS AND THE NORMALIZATION MUST BE
C SCALED TO PREVENT OVER OR UNDERFLOW. CUOIK HAS DETERMINED THAT
C THE RESULT IS ON SCALE.
C-----------------------------------------------------------------------
ACW = AZABS(CWR(2),CWI(2))
ASCLE = 1.0D+3*D1MACH(1)/TOL
CSCLR = 1.0D0
IF (ACW.GT.ASCLE) GO TO 20
CSCLR = 1.0D0/TOL
GO TO 30
20 CONTINUE
ASCLE = 1.0D0/ASCLE
IF (ACW.LT.ASCLE) GO TO 30
CSCLR = TOL
30 CONTINUE
C1R = CWR(1)*CSCLR
C1I = CWI(1)*CSCLR
C2R = CWR(2)*CSCLR
C2I = CWI(2)*CSCLR
STR = YR(1)
STI = YI(1)
C-----------------------------------------------------------------------
C CINU=CINU*(CONJG(CT)/CABS(CT))*(1.0D0/CABS(CT) PREVENTS
C UNDER- OR OVERFLOW PREMATURELY BY SQUARING CABS(CT)
C-----------------------------------------------------------------------
PTR = STR*C1R - STI*C1I
PTI = STR*C1I + STI*C1R
PTR = PTR + C2R
PTI = PTI + C2I
CTR = ZRR*PTR - ZRI*PTI
CTI = ZRR*PTI + ZRI*PTR
ACT = AZABS(CTR,CTI)
RACT = 1.0D0/ACT
CTR = CTR*RACT
CTI = -CTI*RACT
PTR = CINUR*RACT
PTI = CINUI*RACT
CINUR = PTR*CTR - PTI*CTI
CINUI = PTR*CTI + PTI*CTR
YR(1) = CINUR*CSCLR
YI(1) = CINUI*CSCLR
IF (N.EQ.1) RETURN
DO 40 I=2,N
PTR = STR*CINUR - STI*CINUI
CINUI = STR*CINUI + STI*CINUR
CINUR = PTR
STR = YR(I)
STI = YI(I)
YR(I) = CINUR*CSCLR
YI(I) = CINUI*CSCLR
40 CONTINUE
RETURN
50 CONTINUE
NZ = -1
IF(NW.EQ.(-2)) NZ=-2
RETURN
END
| bsd-3-clause |
VanirAOSP/external_chromium_org | native_client_sdk/src/libraries/third_party/pthreads-win32/pthread_attr_setschedpolicy.c | 420 | 1810 | /*
* pthread_attr_setschedpolicy.c
*
* Description:
* POSIX thread functions that deal with thread scheduling.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
#include "sched.h"
int
pthread_attr_setschedpolicy (pthread_attr_t * attr, int policy)
{
if (ptw32_is_attr (attr) != 0)
{
return EINVAL;
}
if (policy != SCHED_OTHER)
{
return ENOTSUP;
}
return 0;
}
| bsd-3-clause |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/gcc/testsuite/gcc.c-torture/execute/builtins/mempcpy-2.c | 216 | 4486 | /* Copyright (C) 2003 Free Software Foundation.
Ensure that builtin mempcpy and stpcpy perform correctly.
Written by Jakub Jelinek, 21/05/2003. */
extern void abort (void);
typedef __SIZE_TYPE__ size_t;
extern void *mempcpy (void *, const void *, size_t);
extern int memcmp (const void *, const void *, size_t);
extern int inside_main;
long buf1[64];
char *buf2 = (char *) (buf1 + 32);
long buf5[20];
char buf7[20];
void
__attribute__((noinline))
test (long *buf3, char *buf4, char *buf6, int n)
{
int i = 0;
/* These should probably be handled by store_by_pieces on most arches. */
if (mempcpy (buf1, "ABCDEFGHI", 9) != (char *) buf1 + 9
|| memcmp (buf1, "ABCDEFGHI\0", 11))
abort ();
if (mempcpy (buf1, "abcdefghijklmnopq", 17) != (char *) buf1 + 17
|| memcmp (buf1, "abcdefghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf3, "ABCDEF", 6) != (char *) buf1 + 6
|| memcmp (buf1, "ABCDEFghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf3, "a", 1) != (char *) buf1 + 1
|| memcmp (buf1, "aBCDEFghijklmnopq\0", 19))
abort ();
if (mempcpy ((char *) buf3 + 2, "bcd" + ++i, 2) != (char *) buf1 + 4
|| memcmp (buf1, "aBcdEFghijklmnopq\0", 19)
|| i != 1)
abort ();
/* These should probably be handled by move_by_pieces on most arches. */
if (mempcpy ((char *) buf3 + 4, buf5, 6) != (char *) buf1 + 10
|| memcmp (buf1, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy ((char *) buf1 + ++i + 8, (char *) buf5 + 1, 1)
!= (char *) buf1 + 11
|| memcmp (buf1, "aBcdRSTUVWSlmnopq\0", 19)
|| i != 2)
abort ();
if (mempcpy ((char *) buf3 + 14, buf6, 2) != (char *) buf1 + 16
|| memcmp (buf1, "aBcdRSTUVWSlmnrsq\0", 19))
abort ();
if (mempcpy (buf3, buf5, 8) != (char *) buf1 + 8
|| memcmp (buf1, "RSTUVWXYVWSlmnrsq\0", 19))
abort ();
if (mempcpy (buf3, buf5, 17) != (char *) buf1 + 17
|| memcmp (buf1, "RSTUVWXYZ01234567\0", 19))
abort ();
__builtin_memcpy (buf3, "aBcdEFghijklmnopq\0", 19);
/* These should be handled either by movmemendM or mempcpy
call. */
if (mempcpy ((char *) buf3 + 4, buf5, n + 6) != (char *) buf1 + 10
|| memcmp (buf1, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy ((char *) buf1 + ++i + 8, (char *) buf5 + 1, n + 1)
!= (char *) buf1 + 12
|| memcmp (buf1, "aBcdRSTUVWkSmnopq\0", 19)
|| i != 3)
abort ();
if (mempcpy ((char *) buf3 + 14, buf6, n + 2) != (char *) buf1 + 16
|| memcmp (buf1, "aBcdRSTUVWkSmnrsq\0", 19))
abort ();
i = 1;
/* These might be handled by store_by_pieces. */
if (mempcpy (buf2, "ABCDEFGHI", 9) != buf2 + 9
|| memcmp (buf2, "ABCDEFGHI\0", 11))
abort ();
if (mempcpy (buf2, "abcdefghijklmnopq", 17) != buf2 + 17
|| memcmp (buf2, "abcdefghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf4, "ABCDEF", 6) != buf2 + 6
|| memcmp (buf2, "ABCDEFghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf4, "a", 1) != buf2 + 1
|| memcmp (buf2, "aBCDEFghijklmnopq\0", 19))
abort ();
if (mempcpy (buf4 + 2, "bcd" + i++, 2) != buf2 + 4
|| memcmp (buf2, "aBcdEFghijklmnopq\0", 19)
|| i != 2)
abort ();
/* These might be handled by move_by_pieces. */
if (mempcpy (buf4 + 4, buf7, 6) != buf2 + 10
|| memcmp (buf2, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf2 + i++ + 8, buf7 + 1, 1)
!= buf2 + 11
|| memcmp (buf2, "aBcdRSTUVWSlmnopq\0", 19)
|| i != 3)
abort ();
if (mempcpy (buf4 + 14, buf6, 2) != buf2 + 16
|| memcmp (buf2, "aBcdRSTUVWSlmnrsq\0", 19))
abort ();
__builtin_memcpy (buf4, "aBcdEFghijklmnopq\0", 19);
/* These should be handled either by movmemendM or mempcpy
call. */
if (mempcpy (buf4 + 4, buf7, n + 6) != buf2 + 10
|| memcmp (buf2, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf2 + i++ + 8, buf7 + 1, n + 1)
!= buf2 + 12
|| memcmp (buf2, "aBcdRSTUVWkSmnopq\0", 19)
|| i != 4)
abort ();
if (mempcpy (buf4 + 14, buf6, n + 2) != buf2 + 16
|| memcmp (buf2, "aBcdRSTUVWkSmnrsq\0", 19))
abort ();
}
void
main_test (void)
{
/* All these tests are allowed to call mempcpy/stpcpy. */
inside_main = 0;
__builtin_memcpy (buf5, "RSTUVWXYZ0123456789", 20);
__builtin_memcpy (buf7, "RSTUVWXYZ0123456789", 20);
test (buf1, buf2, "rstuvwxyz", 0);
}
| bsd-3-clause |