code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/**************************************************************************** * * ftcglyph.h * * FreeType abstract glyph cache (specification). * * Copyright (C) 2000-2020 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /* * * FTC_GCache is an _abstract_ cache object optimized to store glyph * data. It works as follows: * * - It manages FTC_GNode objects. Each one of them can hold one or more * glyph `items'. Item types are not specified in the FTC_GCache but * in classes that extend it. * * - Glyph attributes, like face ID, character size, render mode, etc., * can be grouped into abstract `glyph families'. This avoids storing * the attributes within the FTC_GCache, since it is likely that many * FTC_GNodes will belong to the same family in typical uses. * * - Each FTC_GNode is thus an FTC_Node with two additional fields: * * * gindex: A glyph index, or the first index in a glyph range. * * family: A pointer to a glyph `family'. * * - Family types are not fully specific in the FTC_Family type, but * by classes that extend it. * * Note that both FTC_ImageCache and FTC_SBitCache extend FTC_GCache. * They share an FTC_Family sub-class called FTC_BasicFamily which is * used to store the following data: face ID, pixel/point sizes, load * flags. For more details see the file `src/cache/ftcbasic.c'. * * Client applications can extend FTC_GNode with their own FTC_GNode * and FTC_Family sub-classes to implement more complex caches (e.g., * handling automatic synthesis, like obliquing & emboldening, colored * glyphs, etc.). * * See also the FTC_ICache & FTC_SCache classes in `ftcimage.h' and * `ftcsbits.h', which both extend FTC_GCache with additional * optimizations. * * A typical FTC_GCache implementation must provide at least the * following: * * - FTC_GNode sub-class, e.g. MyNode, with relevant methods: * my_node_new (must call FTC_GNode_Init) * my_node_free (must call FTC_GNode_Done) * my_node_compare (must call FTC_GNode_Compare) * my_node_remove_faceid (must call ftc_gnode_unselect in case * of match) * * - FTC_Family sub-class, e.g. MyFamily, with relevant methods: * my_family_compare * my_family_init * my_family_reset (optional) * my_family_done * * - FTC_GQuery sub-class, e.g. MyQuery, to hold cache-specific query * data. * * - Constant structures for a FTC_GNodeClass. * * - MyCacheNew() can be implemented easily as a call to the convenience * function FTC_GCache_New. * * - MyCacheLookup with a call to FTC_GCache_Lookup. This function will * automatically: * * - Search for the corresponding family in the cache, or create * a new one if necessary. Put it in FTC_GQUERY(myquery).family * * - Call FTC_Cache_Lookup. * * If it returns NULL, you should create a new node, then call * ftc_cache_add as usual. */ /************************************************************************** * * Important: The functions defined in this file are only used to * implement an abstract glyph cache class. You need to * provide additional logic to implement a complete cache. * */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********* *********/ /********* WARNING, THIS IS BETA CODE. *********/ /********* *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifndef FTCGLYPH_H_ #define FTCGLYPH_H_ #include <ft2build.h> #include "ftcmanag.h" FT_BEGIN_HEADER /* * We can group glyphs into `families'. Each family correspond to a * given face ID, character size, transform, etc. * * Families are implemented as MRU list nodes. They are * reference-counted. */ typedef struct FTC_FamilyRec_ { FTC_MruNodeRec mrunode; FT_UInt num_nodes; /* current number of nodes in this family */ FTC_Cache cache; FTC_MruListClass clazz; } FTC_FamilyRec, *FTC_Family; #define FTC_FAMILY(x) ( (FTC_Family)(x) ) #define FTC_FAMILY_P(x) ( (FTC_Family*)(x) ) typedef struct FTC_GNodeRec_ { FTC_NodeRec node; FTC_Family family; FT_UInt gindex; } FTC_GNodeRec, *FTC_GNode; #define FTC_GNODE( x ) ( (FTC_GNode)(x) ) #define FTC_GNODE_P( x ) ( (FTC_GNode*)(x) ) typedef struct FTC_GQueryRec_ { FT_UInt gindex; FTC_Family family; } FTC_GQueryRec, *FTC_GQuery; #define FTC_GQUERY( x ) ( (FTC_GQuery)(x) ) /************************************************************************** * * These functions are exported so that they can be called from * user-provided cache classes; otherwise, they are really part of the * cache sub-system internals. */ /* must be called by derived FTC_Node_InitFunc routines */ FT_LOCAL( void ) FTC_GNode_Init( FTC_GNode node, FT_UInt gindex, /* glyph index for node */ FTC_Family family ); #ifdef FTC_INLINE /* returns TRUE iff the query's glyph index correspond to the node; */ /* this assumes that the `family' and `hash' fields of the query are */ /* already correctly set */ FT_LOCAL( FT_Bool ) FTC_GNode_Compare( FTC_GNode gnode, FTC_GQuery gquery, FTC_Cache cache, FT_Bool* list_changed ); #endif /* call this function to clear a node's family -- this is necessary */ /* to implement the `node_remove_faceid' cache method correctly */ FT_LOCAL( void ) FTC_GNode_UnselectFamily( FTC_GNode gnode, FTC_Cache cache ); /* must be called by derived FTC_Node_DoneFunc routines */ FT_LOCAL( void ) FTC_GNode_Done( FTC_GNode node, FTC_Cache cache ); FT_LOCAL( void ) FTC_Family_Init( FTC_Family family, FTC_Cache cache ); typedef struct FTC_GCacheRec_ { FTC_CacheRec cache; FTC_MruListRec families; } FTC_GCacheRec, *FTC_GCache; #define FTC_GCACHE( x ) ((FTC_GCache)(x)) #if 0 /* can be used as @FTC_Cache_InitFunc */ FT_LOCAL( FT_Error ) FTC_GCache_Init( FTC_GCache cache ); #endif #if 0 /* can be used as @FTC_Cache_DoneFunc */ FT_LOCAL( void ) FTC_GCache_Done( FTC_GCache cache ); #endif /* the glyph cache class adds fields for the family implementation */ typedef struct FTC_GCacheClassRec_ { FTC_CacheClassRec clazz; FTC_MruListClass family_class; } FTC_GCacheClassRec; typedef const FTC_GCacheClassRec* FTC_GCacheClass; #define FTC_GCACHE_CLASS( x ) ((FTC_GCacheClass)(x)) #define FTC_CACHE_GCACHE_CLASS( x ) \ FTC_GCACHE_CLASS( FTC_CACHE(x)->org_class ) #define FTC_CACHE_FAMILY_CLASS( x ) \ ( (FTC_MruListClass)FTC_CACHE_GCACHE_CLASS( x )->family_class ) /* convenience function; use it instead of FTC_Manager_Register_Cache */ FT_LOCAL( FT_Error ) FTC_GCache_New( FTC_Manager manager, FTC_GCacheClass clazz, FTC_GCache *acache ); #ifndef FTC_INLINE FT_LOCAL( FT_Error ) FTC_GCache_Lookup( FTC_GCache cache, FT_Offset hash, FT_UInt gindex, FTC_GQuery query, FTC_Node *anode ); #endif /* */ #define FTC_FAMILY_FREE( family, cache ) \ FTC_MruList_Remove( &FTC_GCACHE((cache))->families, \ (FTC_MruNode)(family) ) #ifdef FTC_INLINE #define FTC_GCACHE_LOOKUP_CMP( cache, famcmp, nodecmp, hash, \ gindex, query, node, error ) \ FT_BEGIN_STMNT \ FTC_GCache _gcache = FTC_GCACHE( cache ); \ FTC_GQuery _gquery = (FTC_GQuery)( query ); \ FTC_MruNode_CompareFunc _fcompare = (FTC_MruNode_CompareFunc)(famcmp); \ FTC_MruNode _mrunode; \ \ \ _gquery->gindex = (gindex); \ \ FTC_MRULIST_LOOKUP_CMP( &_gcache->families, _gquery, _fcompare, \ _mrunode, error ); \ _gquery->family = FTC_FAMILY( _mrunode ); \ if ( !error ) \ { \ FTC_Family _gqfamily = _gquery->family; \ \ \ _gqfamily->num_nodes++; \ \ FTC_CACHE_LOOKUP_CMP( cache, nodecmp, hash, query, node, error ); \ \ if ( --_gqfamily->num_nodes == 0 ) \ FTC_FAMILY_FREE( _gqfamily, _gcache ); \ } \ FT_END_STMNT /* */ #else /* !FTC_INLINE */ #define FTC_GCACHE_LOOKUP_CMP( cache, famcmp, nodecmp, hash, \ gindex, query, node, error ) \ FT_BEGIN_STMNT \ \ error = FTC_GCache_Lookup( FTC_GCACHE( cache ), hash, gindex, \ FTC_GQUERY( query ), &node ); \ \ FT_END_STMNT #endif /* !FTC_INLINE */ FT_END_HEADER #endif /* FTCGLYPH_H_ */ /* END */
Paulloz/godot
thirdparty/freetype/src/cache/ftcglyph.h
C
mit
11,574
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}}; "undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define&&define([],function(){return sjcl}); sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,g=this.s[0][4],f=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=g[c>>>24]<<24^g[c>>16&255]<<16^g[c>>8&255]<<8^g[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:f[0][g[c>>>24]]^f[1][g[c>>16&255]]^f[2][g[c>>8&255]]^f[3][g[c& 255]]}; sjcl.cipher.aes.prototype={encrypt:function(a){return u(this,a,0)},decrypt:function(a){return u(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,g,f,h=[],l=[],k,m,n,p;for(e=0;0x100>e;e++)l[(h[e]=e<<1^283*(e>>7))^e]=e;for(g=f=0;!c[g];g^=k||1,f=l[f]||1)for(n=f^f<<1^f<<2^f<<3^f<<4,n=n>>8^n&255^99,c[g]=n,d[n]=g,m=h[e=h[k=h[g]]],p=0x1010101*m^0x10001*e^0x101*k^0x1010100*g,m=0x101*h[n]^0x1010100*n,e=0;4>e;e++)a[e][g]=m=m<<24^m>>>8,b[e][n]=p=p<<24^p>>>8;for(e= 0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}}; function u(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],g=b[c?3:1]^d[1],f=b[2]^d[2];b=b[c?1:3]^d[3];var h,l,k,m=d.length/4-2,n,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],t=h[2],w=h[3],x=h[4];for(n=0;n<m;n++)h=a[e>>>24]^q[g>>16&255]^t[f>>8&255]^w[b&255]^d[p],l=a[g>>>24]^q[f>>16&255]^t[b>>8&255]^w[e&255]^d[p+1],k=a[f>>>24]^q[b>>16&255]^t[e>>8&255]^w[g&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^t[g>>8&255]^w[f&255]^d[p+3],p+=4,e=h,g=l,f=k;for(n= 0;4>n;n++)r[c?3&-n:n]=x[e>>>24]<<24^x[g>>16&255]<<16^x[f>>8&255]<<8^x[b&255]^d[p++],h=e,e=g,g=f,f=b,b=h;return r} sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0=== b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0=== c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}}; sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>24),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}}; sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}}; sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,g="",f=0,h=sjcl.codec.base32.B,l=0,k=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;g.length*d<k;)g+=h.charAt((l^a[c]>>>f)>>>e),f<d?(l=a[c]<<d-f,f+=e,c++):(l<<=d,f-=d);for(;g.length&7&&!b;)g+="=";return g},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS, d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,g=[],f,h=0,l=sjcl.codec.base32.B,k=0,m,n="base32";b&&(l=sjcl.codec.base32.X,n="base32hex");for(f=0;f<a.length;f++){m=l.indexOf(a.charAt(f));if(0>m){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+n+"!");}h>e?(h-=e,g.push(k^m>>>h),k=m<<c-h):(h+=d,k^=m<<c-h)}h&56&&g.push(sjcl.bitArray.partial(h&56,k,1));return g}}; sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32.toBits(a,1)}}; sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d="",e=0,g=sjcl.codec.base64.B,f=0,h=sjcl.bitArray.bitLength(a);c&&(g=g.substr(0,62)+"-_");for(c=0;6*d.length<h;)d+=g.charAt((f^a[c]>>>e)>>>26),6>e?(f=a[c]<<6-e,e+=26,c++):(f<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,g=sjcl.codec.base64.B,f=0,h;b&&(g=g.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=g.indexOf(a.charAt(d)); if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(f^h>>>e),f=h<<32-e):(e+=6,f^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,f,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()}; sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);for(b=512+b&-512;b<=a;b+=512)v(this,c.splice(0,16));return this},finalize:function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.l/ 4294967296));for(b.push(this.l|0);b.length;)v(this,b.splice(0,16));this.reset();return c},Y:[],b:[],O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}var b=0,c=2,d;a:for(;64>b;c++){for(d=2;d*d<=c;d++)if(0===c%d)continue a;8>b&&(this.Y[b]=a(Math.pow(c,.5)));this.b[b]=a(Math.pow(c,1/3));b++}}}; function v(a,b){var c,d,e,g=b.slice(0),f=a.F,h=a.b,l=f[0],k=f[1],m=f[2],n=f[3],p=f[4],r=f[5],q=f[6],t=f[7];for(c=0;64>c;c++)16>c?d=g[c]:(d=g[c+1&15],e=g[c+14&15],d=g[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+g[c&15]+g[c+9&15]|0),d=d+t+(p>>>6^p>>>11^p>>>25^p<<26^p<<21^p<<7)+(q^p&(r^q))+h[c],t=q,q=r,r=p,p=n+d|0,n=m,m=k,k=l,l=d+(k&m^n&(k^m))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+l|0;f[1]=f[1]+k|0;f[2]=f[2]+m|0;f[3]=f[3]+n|0;f[4]=f[4]+p|0;f[5]=f[5]+r|0;f[6]= f[6]+q|0;f[7]=f[7]+t|0} sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var g,f=b.slice(0),h=sjcl.bitArray,l=h.bitLength(c)/8,k=h.bitLength(f)/8;e=e||64;d=d||[];if(7>l)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(g=2;4>g&&k>>>8*g;g++);g<15-l&&(g=15-l);c=h.clamp(c, 8*(15-g));b=sjcl.mode.ccm.V(a,b,c,d,e,g);f=sjcl.mode.ccm.C(a,f,c,b,e,g);return h.concat(f.data,f.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var g=sjcl.bitArray,f=g.bitLength(c)/8,h=g.bitLength(b),l=g.clamp(b,h-e),k=g.bitSlice(b,h-e),h=(h-e)/8;if(7>f)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-f&&(b=15-f);c=g.clamp(c,8*(15-b));l=sjcl.mode.ccm.C(a,l,c,k,e,b);a=sjcl.mode.ccm.V(a,l.data,c,d,e,b);if(!g.equal(l.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match"); return l.data},na:function(a,b,c,d,e,g){var f=[],h=sjcl.bitArray,l=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|g-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?f=[h.partial(16,c)]:0xffffffff>=c&&(f=h.concat([h.partial(16,65534)],[c])),f=h.concat(f,b),b=0;b<f.length;b+=4)d=a.encrypt(l(d,f.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,g){var f=sjcl.bitArray,h=f.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid tag length"); if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data");c=sjcl.mode.ccm.na(a,d,c,e,f.bitLength(b)/8,g);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));return f.clamp(c,8*e)},C:function(a,b,c,d,e,g){var f,h=sjcl.bitArray;f=h.i;var l=b.length,k=h.bitLength(b),m=l/50,n=m;c=h.concat([h.partial(8,g-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(f(d,a.encrypt(c)),0,e);if(!l)return{tag:d,data:[]};for(f=0;f<l;f+=4)f>m&&(sjcl.mode.ccm.fa(f/ l),m+=n),c[3]++,e=a.encrypt(c),b[f]^=e[0],b[f+1]^=e[1],b[f+2]^=e[2],b[f+3]^=e[3];return{tag:d,data:h.clamp(b,k)}}}; sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,g){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var f,h=sjcl.mode.ocb2.S,l=sjcl.bitArray,k=l.i,m=[0,0,0,0];c=h(a.encrypt(c));var n,p=[];d=d||[];e=e||64;for(f=0;f+4<b.length;f+=4)n=b.slice(f,f+4),m=k(m,n),p=p.concat(k(c,a.encrypt(k(c,n)))),c=h(c);n=b.slice(f);b=l.bitLength(n);f=a.encrypt(k(c,[0,0,0,b]));n=l.clamp(k(n.concat([0,0,0]),f),b);m=k(m,k(n.concat([0,0,0]),f));m=a.encrypt(k(m,k(c,h(c)))); d.length&&(m=k(m,g?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(l.concat(n,l.clamp(m,e)))},decrypt:function(a,b,c,d,e,g){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var f=sjcl.mode.ocb2.S,h=sjcl.bitArray,l=h.i,k=[0,0,0,0],m=f(a.encrypt(c)),n,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;c+=4)n=l(m,a.decrypt(l(m,b.slice(c,c+4)))),k=l(k,n),q=q.concat(n),m=f(m);p=r-32*c;n=a.encrypt(l(m,[0,0,0,p]));n=l(n,h.clamp(b.slice(c),p).concat([0, 0,0]));k=l(k,n);k=a.encrypt(l(k,l(m,f(m))));d.length&&(k=l(k,g?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(k,e),h.bitSlice(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(n,p))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,g=e.i,f=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=g(h,d(d(h)));for(c=0;c+4<b.length;c+=4)h=d(h),f=g(f,a.encrypt(g(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=g(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));f=g(f,c); return a.encrypt(g(d(g(h,d(h))),f))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}}; sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var g=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,g,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var g=b.slice(0),f=sjcl.bitArray,h=f.bitLength(g);e=e||128;d=d||[];e<=h?(b=f.bitSlice(g,h-e),g=f.bitSlice(g,0,h-e)):(b=g,g=[]);a=sjcl.mode.gcm.C(!1,a,g,d,c,e);if(!f.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,g,f,h=sjcl.bitArray.i;e=[0,0, 0,0];g=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,g));f=0!==(g[3]&1);for(d=3;0<d;d--)g[d]=g[d]>>>1|(g[d-1]&1)<<31;g[0]>>>=1;f&&(g[0]^=-0x1f000000)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,g){var f,h,l,k,m,n,p,r,q=sjcl.bitArray;n=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e); f=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(f,[0,0,0,0],e),e=sjcl.mode.gcm.j(f,e,[0,0,Math.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(f,[0,0,0,0],d);m=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(f,h,c));for(k=0;k<n;k+=4)m[3]++,l=b.encrypt(m),c[k]^=l[0],c[k+1]^=l[1],c[k+2]^=l[2],c[k+3]^=l[3];c=q.clamp(c,p);a&&(d=sjcl.mode.gcm.j(f,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(f,d,a);l=b.encrypt(e); d[0]^=l[0];d[1]^=l[1];d[2]^=l[2];d[3]^=l[3];return{tag:q.bitSlice(d,0,g),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])}; sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a}; sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E3;if(0>d||0>c)throw sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var g,f,h,l,k=[],m=sjcl.bitArray;for(l=1;32*k.length<(d||1);l++){e=g=a.encrypt(m.concat(b,[l]));for(f=1;f<c;f++)for(g=a.encrypt(g),h=0;h<g.length;h++)e[h]^=g[h];k=k.concat(e)}d&&(k=m.clamp(k,d));return k}; sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80}; sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var g=0,f;this.Z=e[0]=(new Date).valueOf()+this.da;for(f=0;16>f;f++)e.push(0x100000000*Math.random()|0);for(f=0;f<this.c.length&&(e=e.concat(this.c[f].finalize()),g+=this.m[f],this.m[f]=0,d||!(this.P&1<<f));f++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=g;g>this.o&&(this.o= g);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b)throw"Setting paranoia=0 will ruin your security; use it only for testing";this.M=a},addEntropy:function(a,b,c){c=c||"user"; var d,e,g=(new Date).valueOf(),f=this.H[c],h=this.isReady(),l=0;d=this.U[c];void 0===d&&(d=this.U[c]=this.ha++);void 0===f&&(f=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number":void 0===b&&(b=1);this.c[f].update([d,this.N++,1,b,g,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]"!==c&&(l=1),c=0;c<a.length&&!l;c++)"number"!==typeof a[c]&&(l=1);if(!l){if(void 0=== b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[f].update([d,this.N++,2,b,g,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[f].update([d,this.N++,3,b,g,a.length]);this.c[f].update(a);break;default:l=1}if(l)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[f]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!== a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector, !1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event"); this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove", this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],g=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&g.push(d);for(c=0;c<g.length;c++)d=g[c],delete e[d]},la:function(){C(1)},oa:function(a){var b,c;try{b=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&sjcl.random.addEntropy([b,c],2,"mouse");C(0)},qa:function(a){a= a.touches[0]||a.changedTouches[0];sjcl.random.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(0)},ma:function(){C(2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&sjcl.random.addEntropy(b,1,"accelerometer")}a&&sjcl.random.addEntropy(a,2,"accelerometer");C(0)}}; function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c](b)}function C(a){"undefined"!==typeof window&&window.performance&&"function"===typeof window.performance.now?sjcl.random.addEntropy(window.performance.now(),a,"loadtime"):sjcl.random.addEntropy((new Date).valueOf(),a,"loadtime")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)} function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6); a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F); else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))} sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,g=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),f;e.g(g,c);c=g.adata;"string"===typeof g.salt&&(g.salt=sjcl.codec.base64.toBits(g.salt));"string"===typeof g.iv&&(g.iv=sjcl.codec.base64.toBits(g.iv));if(!sjcl.mode[g.mode]||!sjcl.cipher[g.cipher]||"string"===typeof a&&100>=g.iter||64!==g.ts&&96!==g.ts&&128!==g.ts||128!==g.ks&&192!==g.ks&&0x100!==g.ks||2>g.iv.length|| 4<g.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,g),a=f.key.slice(0,g.ks/32),g.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(f=a.kem(),g.kemtag=f.tag,a=f.key.slice(0,g.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(g.adata=c=sjcl.codec.utf8String.toBits(c));f=new sjcl.cipher[g.cipher](a);e.g(d,g);d.key=a;g.ct="ccm"===g.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&& b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(f,b,g.iv,c,g.ts):sjcl.mode[g.mode].encrypt(f,b,g.iv,c,g.ts);return g},encrypt:function(a,b,c,d){var e=sjcl.json,g=e.ja.apply(e,arguments);return e.encode(g)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var g,f;g=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"=== typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,b),a=f.key.slice(0,b.ks/32),b.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof g&&(g=sjcl.codec.utf8String.toBits(g));f=new sjcl.cipher[b.cipher](a);g="ccm"=== b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt(f,b.ct,b.iv,b.tag,g,b.ts):sjcl.mode[b.mode].decrypt(f,b.ct,b.iv,g,b.ts);e.g(d,b);d.key=a;return 1===c.raw?g:sjcl.codec.utf8String.fromBits(g)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+ b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!"); null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a, b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
99xt/interns-portal
web/src/assets/script/sjcl.js
JavaScript
mit
25,092
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head> <title>CURLOPT_VERBOSE man page</title> <meta name="generator" content="roffit"> <STYLE type="text/css"> P.level0 { padding-left: 2em; } P.level1 { padding-left: 4em; } P.level2 { padding-left: 6em; } span.emphasis { font-style: italic; } span.bold { font-weight: bold; } span.manpage { font-weight: bold; } h2.nroffsh { background-color: #e0e0e0; } span.nroffip { font-weight: bold; font-size: 120%; font-family: monospace; } p.roffit { text-align: center; font-size: 80%; } </STYLE> </head><body> <p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2> <p class="level0">CURLOPT_VERBOSE - set verbose mode on/off <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2> <p class="level0">#include &lt;curl/curl.h&gt; <p class="level0">CURLcode curl_easy_setopt(CURL *handle, CURLOPT_VERBOSE, long onoff); <a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2> <p class="level0">Set the <span Class="emphasis">onoff</span> parameter to 1 to make the library display a lot of verbose information about its operations on this <span Class="emphasis">handle</span>. Very useful for libcurl and/or protocol debugging and understanding. The verbose information will be sent to stderr, or the stream set with <a Class="emphasis" href="./CURLOPT_STDERR.html">CURLOPT_STDERR</a>. <p class="level0">You hardly ever want this set in production use, you will almost always want this when you debug/report problems. <p class="level0">To also get all the protocol data sent and received, consider using the <a Class="emphasis" href="./CURLOPT_DEBUGFUNCTION.html">CURLOPT_DEBUGFUNCTION</a>. <a name="DEFAULT"></a><h2 class="nroffsh">DEFAULT</h2> <p class="level0">0, meaning disabled. <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2> <p class="level0">Returns CURLE_OK. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2> <p class="level0"><a Class="manpage" href="./CURLOPT_STDERR.html">CURLOPT_STDERR</a> <a Class="manpage" href="./CURLOPT_DEBUGFUNCTION.html">CURLOPT_DEBUGFUNCTION</a> <span Class="manpage"> </span> <p class="roffit"> This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>. </body></html>
iSCInc/cURL
v7.38.0/docs/libcurl/opts/CURLOPT_VERBOSE.html
HTML
mit
2,300
// seedrandom.js // Author: David Bau 12/25/2010 // // Defines a method Math.seedrandom() that, when called, substitutes // an explicitly seeded RC4-based algorithm for Math.random(). Also // supports automatic seeding from local or network sources of entropy. // // Usage: // // <script src=http://davidbau.com/encode/seedrandom-min.js></script> // // Math.seedrandom('yipee'); Sets Math.random to a function that is // initialized using the given explicit seed. // // Math.seedrandom(); Sets Math.random to a function that is // seeded using the current time, dom state, // and other accumulated local entropy. // The generated seed string is returned. // // Math.seedrandom('yowza', true); // Seeds using the given explicit seed mixed // together with accumulated entropy. // // <script src="http://bit.ly/srandom-512"></script> // Seeds using physical random bits downloaded // from random.org. // // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom"> // </script> Seeds using urandom bits from call.jsonlib.com, // which is faster than random.org. // // Examples: // // Math.seedrandom("hello"); // Use "hello" as the seed. // document.write(Math.random()); // Always 0.5463663768140734 // document.write(Math.random()); // Always 0.43973793770592234 // var rng1 = Math.random; // Remember the current prng. // // var autoseed = Math.seedrandom(); // New prng with an automatic seed. // document.write(Math.random()); // Pretty much unpredictable. // // Math.random = rng1; // Continue "hello" prng sequence. // document.write(Math.random()); // Always 0.554769432473455 // // Math.seedrandom(autoseed); // Restart at the previous seed. // document.write(Math.random()); // Repeat the 'unpredictable' value. // // Notes: // // Each time seedrandom('arg') is called, entropy from the passed seed // is accumulated in a pool to help generate future seeds for the // zero-argument form of Math.seedrandom, so entropy can be injected over // time by calling seedrandom with explicit data repeatedly. // // On speed - This javascript implementation of Math.random() is about // 3-10x slower than the built-in Math.random() because it is not native // code, but this is typically fast enough anyway. Seeding is more expensive, // especially if you use auto-seeding. Some details (timings on Chrome 4): // // Our Math.random() - avg less than 0.002 milliseconds per call // seedrandom('explicit') - avg less than 0.5 milliseconds per call // seedrandom('explicit', true) - avg less than 2 milliseconds per call // seedrandom() - avg about 38 milliseconds per call // // LICENSE (BSD): // // Copyright 2010 David Bau, 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 this module 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. // /** * All code is in an anonymous closure to keep the global namespace clean. * * @param {number=} overflow * @param {number=} startdenom */ (function (pool, math, width, chunks, significance, overflow, startdenom) { // // seedrandom() // This is the seedrandom function described above. // math['seedrandom'] = function seedrandom(seed, use_entropy) { var key = []; var arc4; // Flatten the seed string or build one from local entropy if needed. seed = mixkey(flatten( use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool, window], 3), key); // Use the seed to initialize an ARC4 generator. arc4 = new ARC4(key); // Mix the randomness into accumulated entropy. mixkey(arc4.S, pool); // Override Math.random // This function returns a random double in [0, 1) that contains // randomness in every bit of the mantissa of the IEEE 754 value. math['random'] = function random() { // Closure to return a random double: var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 var d = startdenom; // and denominator d = 2 ^ 48. var x = 0; // and no 'extra last byte'. while (n < significance) { // Fill up all significant digits by n = (n + x) * width; // shifting numerator and d *= width; // denominator and generating a x = arc4.g(1); // new least-significant-byte. } while (n >= overflow) { // To avoid rounding up, before adding n /= 2; // last byte, shift everything d /= 2; // right using integer math until x >>>= 1; // we have exactly the desired bits. } return (n + x) / d; // Form the number within [0, 1). }; // Return the seed that was used return seed; }; // // ARC4 // // An ARC4 implementation. The constructor takes a key in the form of // an array of at most (width) integers that should be 0 <= x < (width). // // The g(count) method returns a pseudorandom integer that concatenates // the next (count) outputs from ARC4. Its return value is a number x // that is in the range 0 <= x < (width ^ count). // /** @constructor */ function ARC4(key) { var t, u, me = this, keylen = key.length; var i = 0, j = me.i = me.j = me.m = 0; me.S = []; me.c = []; // The empty key [] is treated as [0]. if (!keylen) { key = [keylen++]; } // Set up S using the standard key scheduling algorithm. while (i < width) { me.S[i] = i++; } for (i = 0; i < width; i++) { t = me.S[i]; j = lowbits(j + t + key[i % keylen]); u = me.S[j]; me.S[i] = u; me.S[j] = t; } // The "g" method returns the next (count) outputs as one number. me.g = function getnext(count) { var s = me.S; var i = lowbits(me.i + 1); var t = s[i]; var j = lowbits(me.j + t); var u = s[j]; s[i] = u; s[j] = t; var r = s[lowbits(t + u)]; while (--count) { i = lowbits(i + 1); t = s[i]; j = lowbits(j + t); u = s[j]; s[i] = u; s[j] = t; r = r * width + s[lowbits(t + u)]; } me.i = i; me.j = j; return r; }; // For robust unpredictability discard an initial batch of values. // See http://www.rsa.com/rsalabs/node.asp?id=2009 me.g(width); } // // flatten() // Converts an object tree to nested arrays of strings. // /** @param {Object=} result * @param {string=} prop */ function flatten(obj, depth, result, prop) { result = []; if (depth && typeof(obj) == 'object') { for (prop in obj) { if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } } return result.length ? result : '' + obj; } // // mixkey() // Mixes a string seed into a key that is an array of integers, and // returns a shortened string seed that is equivalent to the result key. // /** @param {number=} smear * @param {number=} j */ function mixkey(seed, key, smear, j) { seed += ''; // Ensure the seed is a string smear = 0; for (j = 0; j < seed.length; j++) { key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); } seed = ''; for (j in key) { seed += String.fromCharCode(key[j]); } return seed; } // // lowbits() // A quick "n mod width" for width a power of 2. // function lowbits(n) { return n & (width - 1); } // // The following constants are related to IEEE 754 limits. // startdenom = math.pow(width, chunks); significance = math.pow(2, significance); overflow = significance * 2; // // When seedrandom.js is loaded, we immediately mix a few bits // from the built-in RNG into the entropy pool. Because we do // not want to intefere with determinstic PRNG state later, // seedrandom will not call math.random on its own again after // initialization. // mixkey(math.random(), pool); // End anonymous scope, and pass initial values. })( [], // pool: entropy pool starts empty Math, // math: package containing random, pow, and seedrandom 256, // width: each RC4 output is 0 <= x < 256 6, // chunks: at least six RC4 outputs for each double 52 // significance: there are 52 significant digits in a double );
gswalden/jsdelivr
files/seedrandom/1.0.0/seedrandom.js
JavaScript
mit
10,013
<?php /** * PHPExcel * * Copyright (c) 2006 - 2014 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Worksheet * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** * PHPExcel_Worksheet_CellIterator * * Used to iterate rows in a PHPExcel_Worksheet * * @category PHPExcel * @package PHPExcel_Worksheet * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Worksheet_CellIterator implements Iterator { /** * PHPExcel_Worksheet to iterate * * @var PHPExcel_Worksheet */ private $_subject; /** * Row index * * @var int */ private $_rowIndex; /** * Current iterator position * * @var int */ private $_position = 0; /** * Loop only existing cells * * @var boolean */ private $_onlyExistingCells = true; /** * Create a new cell iterator * * @param PHPExcel_Worksheet $subject * @param int $rowIndex */ public function __construct(PHPExcel_Worksheet $subject = null, $rowIndex = 1) { // Set subject and row index $this->_subject = $subject; $this->_rowIndex = $rowIndex; } /** * Destructor */ public function __destruct() { unset($this->_subject); } /** * Rewind iterator */ public function rewind() { $this->_position = 0; } /** * Current PHPExcel_Cell * * @return PHPExcel_Cell */ public function current() { return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex); } /** * Current key * * @return int */ public function key() { return $this->_position; } /** * Next value */ public function next() { ++$this->_position; } /** * Are there any more PHPExcel_Cell instances available? * * @return boolean */ public function valid() { // columnIndexFromString() returns an index based at one, // treat it as a count when comparing it to the base zero // position. $columnCount = PHPExcel_Cell::columnIndexFromString($this->_subject->getHighestColumn()); if ($this->_onlyExistingCells) { // If we aren't looking at an existing cell, either // because the first column doesn't exist or next() has // been called onto a nonexistent cell, then loop until we // find one, or pass the last column. while ($this->_position < $columnCount && !$this->_subject->cellExistsByColumnAndRow($this->_position, $this->_rowIndex)) { ++$this->_position; } } return $this->_position < $columnCount; } /** * Get loop only existing cells * * @return boolean */ public function getIterateOnlyExistingCells() { return $this->_onlyExistingCells; } /** * Set the iterator to loop only existing cells * * @param boolean $value */ public function setIterateOnlyExistingCells($value = true) { $this->_onlyExistingCells = $value; } }
bjohare/cloughjordan.ie
wp-content/plugins/leaflet-maps-marker/inc/import-export/PHPExcel/Worksheet/CellIterator.php
PHP
cc0-1.0
4,109
package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.collection.IsMapContaining.hasValue; public class IsMapContainingValueTest extends AbstractMatcherTest { @Override protected Matcher<?> createMatcher() { return hasValue("foo"); } public void testHasReadableDescription() { assertDescription("map containing [ANYTHING->\"a\"]", hasValue("a")); } public void testDoesNotMatchEmptyMap() { Map<String,Integer> map = new HashMap<String,Integer>(); assertMismatchDescription("map was []", hasValue(1), map); } public void testMatchesSingletonMapContainingValue() { Map<String,Integer> map = new HashMap<String,Integer>(); map.put("a", 1); assertMatches("Singleton map", hasValue(1), map); } public void testMatchesMapContainingValue() { Map<String,Integer> map = new TreeMap<String,Integer>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMatches("hasValue 1", hasValue(1), map); assertMatches("hasValue 3", hasValue(3), map); assertMismatchDescription("map was [<a=1>, <b=2>, <c=3>]", hasValue(4), map); } }
jasonCarNormal0101/StockAdviser
lib/hamcrest-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingValueTest.java
Java
epl-1.0
1,379
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.binding.api.mount; import java.util.EventListener; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; /** * Provider MountProviderService, this version allows access to MD-SAL services * specific for this mountpoint and registration / provision of interfaces for * mount point. * * @author ttkacik * */ public interface MountProviderService extends MountService { @Override public MountProviderInstance getMountPoint(InstanceIdentifier<?> path); MountProviderInstance createMountPoint(InstanceIdentifier<?> path); MountProviderInstance createOrGetMountPoint(InstanceIdentifier<?> path); ListenerRegistration<MountProvisionListener> registerProvisionListener(MountProvisionListener listener); public interface MountProvisionListener extends EventListener { void onMountPointCreated(InstanceIdentifier<?> path); void onMountPointRemoved(InstanceIdentifier<?> path); } }
Johnson-Chou/test
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/mount/MountProviderService.java
Java
epl-1.0
1,359
/* * fstat() - POSIX 1003.1b 5.6.2 - Get File Status * * COPYRIGHT (c) 1989-1999. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.org/license/LICENSE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <rtems/libio_.h> #include <rtems/seterr.h> int fstat( int fd, struct stat *sbuf ) { rtems_libio_t *iop; /* * Check to see if we were passed a valid pointer. */ if ( !sbuf ) rtems_set_errno_and_return_minus_one( EFAULT ); /* * Now process the stat() request. */ iop = rtems_libio_iop( fd ); rtems_libio_check_fd( fd ); rtems_libio_check_is_open(iop); /* * Zero out the stat structure so the various support * versions of stat don't have to. */ memset( sbuf, 0, sizeof(struct stat) ); return (*iop->pathinfo.handlers->fstat_h)( &iop->pathinfo, sbuf ); } /* * _fstat_r * * This is the Newlib dependent reentrant version of fstat(). */ #if defined(RTEMS_NEWLIB) && !defined(HAVE_FSTAT_R) #include <reent.h> int _fstat_r( struct _reent *ptr __attribute__((unused)), int fd, struct stat *buf ) { return fstat( fd, buf ); } #endif
swordsmaster/waf
cpukit/libcsupport/src/fstat.c
C
gpl-2.0
1,347
/* * drivers/power/mm8033_battery.c * * Gas Gauge driver for MITSUMI's MM8033A01 * * Copyright (c) 2014, ASUSTek Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #include <linux/module.h> #include <linux/param.h> #include <linux/jiffies.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/switch.h> #include <linux/HWVersion.h> #include <linux/earlysuspend.h> #include <asm/unaligned.h> #include <asm/intel_mid_gpadc.h> #include <asm/intel_mid_thermal.h> #include "asus_battery.h" #include "smb_external_include.h" #define DRIVER_VERSION "1.5.7" #define TRY 5 #define SKIP 10 #define MM8033_ID 0x0110 #define SYSTEM_LOWVOLTAGE_LIMIT 3400 #define REG_STATUS 0x00 #define REG_V_ALERT_THRESHOLD 0x01 #define REG_T_ALERT_THRESHOLD 0x02 #define REG_S_ALERT_THRESHOLD 0x03 #define REG_ATRATE 0x04 #define REG_REM_CAPACITY 0x05 #define REG_SOC 0x06 #define REG_SOH 0x07 #define REG_TEMPERATURE 0x08 #define REG_VOLTAGE 0x09 #define REG_CURRENT 0x0A #define REG_AVERAGE_CURRENT 0x0B #define REG_IC_TEMPERATURE 0x0C #define REG_ABSOLUTE_SOC 0x0D #define REG_SOC_NF 0x0E #define REG_ABSOLUTE_REM_CAPACITY 0x0F #define REG_FULL_CHARGE_CAPACITY 0x10 #define REG_TTE 0x11 #define REG_SOI 0x12 #define REG_FULL_VOLTAGE_THR 0x13 #define REG_CYCLE_COUNT 0x17 #define REG_DESIGN_CAPACITY 0x18 #define REG_AVERAGE_VOLTAGE 0x19 #define REG_PEAK_TEMPERATURE 0x1A #define REG_PEAK_VOLTAGE 0x1B #define REG_PEAK_CURRENT 0x1C #define REG_CONFIG 0x1D #define REG_CHARGE_TERMINAL_CURRENT 0x1E #define REG_REM_CAPACITY_NF 0x1F #define REG_FG_CONDITION 0x20 #define REG_IDENTIFY 0x21 #define REG_BATTERY_IMPEDANCE 0x22 #define REG_BATTERY_CAPACITY 0x23 #define REG_PROJECT_NAME 0x2C #define REG_PACKCELL_VENDOR 0x2D #define REG_DATE 0x2E #define REG_EMPTY_VOLTAGE 0x3A #define REG_FG_STAT 0x3D #define GAUGE_ERR(...) printk("[MM8033_ERR] " __VA_ARGS__); #define GAUGE_INFO(...) printk("[MM8033] " __VA_ARGS__); #define SOC_SMOOTH_ALGO struct mm8033_batparams { u8 params[512]; u8 en_i2c_sh; int fullvoltage_thr; int designcapacity; int charge_terminal_current; int paramrevision; int batterycode; int default_cyclecount; int default_batterycapacity; int default_batteryimpedance; }; struct mm8033_chip { #ifdef REGISTER_POWER_SUPPLY struct power_supply battery; #endif struct i2c_client *client; int cyclecount; int batterycapacity; int batteryimpedance; int skipcheck; struct mm8033_batparams batparams; #ifdef CONFIG_HAS_EARLYSUSPEND struct early_suspend es; #endif }; /* global variables */ extern int Read_HW_ID(void); extern int Read_PROJ_ID(void); static struct switch_dev mm8033_batt_dev; static struct dev_func mm8033_tbl; static struct mm8033_chip *g_mm8033_chip; static char *batt_id; static int bat_year, bat_week_1, bat_week_2, invalid_bat=0; static u16 parameter_version, battery_ctrlcode; struct delayed_work batt_state_wq; #ifdef SOC_SMOOTH_ALGO static int mm8033_pre_soc=0; #endif static int mm8033_write_reg(struct i2c_client *client, u8 reg, u16 value) { int ret = i2c_smbus_write_word_data(client, reg, value); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); msleep(4); return ret; } static int mm8033_read_reg(struct i2c_client *client, u8 reg) { int ret = i2c_smbus_read_word_data(client, reg); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); msleep(4); return ret; } static int mm8033_writex_reg(struct i2c_client *client, u8 reg, u8 *buf, u16 len) { struct i2c_msg msg[1]; int i, ret; u8 *wbuf; wbuf = kzalloc(sizeof(u8) * (len + 1), GFP_KERNEL); wbuf[0] = reg; for (i = 0; i < len; i++) { wbuf[i + 1] = buf[i]; } msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = (u16)(len + 1); msg[0].buf = wbuf; ret = i2c_transfer(client->adapter, msg, 1); kfree(wbuf); if (ret < 0) { return ret; } return 0; } static int mm8033_readx_reg(struct i2c_client *client, u8 reg, u8 *buf, u16 len) { struct i2c_msg msg[2]; int ret; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = &reg; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].buf = buf; msg[1].len = len; ret = i2c_transfer(client->adapter, msg, 2); if (ret < 0) return ret; return 0; } #ifdef REGISTER_POWER_SUPPLY static int mm8033_soc(struct mm8033_chip *chip, int *val) { int soc = mm8033_read_reg(chip->client, REG_SOC); if (soc < 0) return soc; *val = soc / 256; return 0; } static int mm8033_current(struct mm8033_chip *chip, int *val) { int curr = mm8033_read_reg(chip->client, REG_CURRENT); if (curr < 0) return curr; if (curr > 32767) { curr -= 65536; } *val = curr; return 0; } static int mm8033_temperature(struct mm8033_chip *chip, int *val) { int temp = mm8033_read_reg(chip->client, REG_IC_TEMPERATURE); if (temp < 0) return temp; if (temp > 32767) { temp -= 65536; } *val = temp; return 0; } #endif static int mm8033_status(struct mm8033_chip *chip, int *val) { int stat = mm8033_read_reg(chip->client, REG_STATUS); if (stat < 0) return stat; *val = stat; return 0; } static int mm8033_voltage(struct mm8033_chip *chip, int *val) { int volt = mm8033_read_reg(chip->client, REG_VOLTAGE); if (volt < 0) return volt; *val = volt; return 0; } static int mm8033_identify(struct mm8033_chip *chip, int *val) { int id = mm8033_read_reg(chip->client, REG_IDENTIFY); if (id < 0) return id; *val = id; return 0; } static int mm8033_projectname(struct mm8033_chip *chip, int *val) { int pn = mm8033_read_reg(chip->client, REG_PROJECT_NAME); if (pn < 0) return pn; *val = pn; return 0; } static int mm8033_packcellvendor(struct mm8033_chip *chip, int *val) { int pcv = mm8033_read_reg(chip->client, REG_PACKCELL_VENDOR); if (pcv < 0) return pcv; *val = pcv; return 0; } static int mm8033_bat_date(struct mm8033_chip *chip, int *val) { int date = mm8033_read_reg(chip->client, REG_DATE); if (date < 0) return date; *val = date; return 0; } static int mm8033_fgstat(struct mm8033_chip *chip, int *val) { int stat = mm8033_read_reg(chip->client, REG_FG_STAT); if (stat < 0) return stat; *val = stat; return 0; } static int mm8033_designcapacity(struct mm8033_chip *chip, int *val) { int dc = mm8033_read_reg(chip->client, REG_DESIGN_CAPACITY); if (dc < 0) return dc; *val = dc; return 0; } static int mm8033_cyclecount(struct mm8033_chip *chip, int *val) { int cc = mm8033_read_reg(chip->client, REG_CYCLE_COUNT); if (cc < 0) return cc; *val = cc; return 0; } static int mm8033_batteryimpedance(struct mm8033_chip *chip, int *val) { int bi = mm8033_read_reg(chip->client, REG_BATTERY_IMPEDANCE); if (bi < 0) return bi; *val = bi; return 0; } static int mm8033_batterycapacity(struct mm8033_chip *chip, int *val) { int bc = mm8033_read_reg(chip->client, REG_BATTERY_CAPACITY); if (bc < 0) return bc; *val = bc; return 0; } static int mm8033_setFgParameter(struct mm8033_chip *chip) { int i, j; int ret; int val; u8 buf[8]; u8 buf_89[8] = {0x5F, 0xF3, 0xFF, 0xFF, 0xFF, 0x18, 0xFF, 0xFF}; u8 buf_8a[8] = {0xFF, 0xFF, 0xDA, 0x1D, 0x0B, 0x00, 0xFF, 0xFF}; #if 0 for (i = 0; i < 0x40; i++) { if ((i != 0x9) && (i != 0xa)) { for (j = 0; j < 8; j++) { buf[j] = chip->batparams.params[i*8 + j]; } ret = mm8033_writex_reg(chip->client, (u8)(0x80 + i), buf, (u16)8); if (ret) { dev_err(&chip->client->dev, "failed to send parameter.\n"); return ret; } msleep(5); }else if((Read_HW_ID()==HW_ID_ER)||(Read_HW_ID()==HW_ID_ER1_1)||(Read_HW_ID()==HW_ID_ER1_2)) { // write 0x89, 0x8a GAUGE_INFO("0x89=0x%04x\n", mm8033_read_reg(chip->client, 0x89)); if(mm8033_read_reg(chip->client, 0x89)!=0xF35F) { GAUGE_INFO("write 0x89 for correcting wrong value writen to these register\n"); ret = mm8033_writex_reg(chip->client, (u8)0x89, buf_89, (u16)8); if (ret) { dev_err(&chip->client->dev, "failed to send parameter(0x89).\n"); return ret; } msleep(5); GAUGE_INFO("write 0x8a for correcting wrong value writen to these register\n"); ret = mm8033_writex_reg(chip->client, (u8)0x8a, buf_8a, (u16)8); if (ret) { dev_err(&chip->client->dev, "failed to send parameter(0x8a).\n"); return ret; } msleep(5); }else { GAUGE_INFO("no need to re-write 0x89/0x8a\n"); } } } #ifdef I2CLOW_RESTART if (chip->batparams.en_i2c_sh) { ret = mm8033_write_reg(chip->client, REG_CONFIG, 0x40); if (ret < 0) return ret; msleep(5); } #endif ret = mm8033_write_reg(chip->client, REG_FULL_VOLTAGE_THR, chip->batparams.fullvoltage_thr); if (ret < 0) return ret; msleep(5); ret = mm8033_write_reg(chip->client, REG_DESIGN_CAPACITY, chip->batparams.designcapacity); if (ret < 0) return ret; msleep(5); ret = mm8033_write_reg(chip->client, REG_CHARGE_TERMINAL_CURRENT, chip->batparams.charge_terminal_current); if (ret < 0) return ret; msleep(5); ret = mm8033_write_reg(chip->client, REG_BATTERY_IMPEDANCE, chip->batteryimpedance); if (ret < 0) return ret; msleep(5); ret = mm8033_write_reg(chip->client, REG_BATTERY_CAPACITY, chip->batterycapacity); if (ret < 0) return ret; msleep(5); ret = mm8033_write_reg(chip->client, REG_CYCLE_COUNT, chip->cyclecount); if (ret < 0) return ret; if (smb1357_get_charging_status() == POWER_SUPPLY_STATUS_CHARGING) { GAUGE_INFO("make sure not charging when reset IC and get soc.\n"); smb1357_charging_toggle(false); msleep(3000); ret = mm8033_write_reg(chip->client, REG_FG_CONDITION, 0x24); if (ret < 0) return ret; smb1357_charging_toggle(true); }else { GAUGE_INFO("charging status=%d\n", smb1357_get_charging_status()); msleep(5); ret = mm8033_write_reg(chip->client, REG_FG_CONDITION, 0x24); if (ret < 0) return ret; } msleep(100); do { ret = mm8033_fgstat(chip, &val); if (ret) return ret; } while (val & 0x0001); #else GAUGE_INFO("%s: do not set parameter\n", __func__); #endif return 0; } static int mm8033_checkRamData(struct mm8033_chip *chip) { int i, ret, val; u8 buf[8]; GAUGE_INFO("%s +++\n", __func__); ret = mm8033_readx_reg(chip->client, 0xBE, buf, (u16)8); if (ret) return ret; if (((((buf[7] & 0xff) << 8) | (buf[6] & 0xff)) < chip->batparams.paramrevision) || ((((buf[5] & 0xff) << 8) | (buf[4] & 0xff)) != chip->batparams.batterycode)) { if((Read_HW_ID()==HW_ID_ER)||(Read_HW_ID()==HW_ID_ER1_1)||(Read_HW_ID()==HW_ID_ER1_2)) { if ( (((buf[7] & 0xff) << 8) | (buf[6] & 0xff)) < chip->batparams.paramrevision ) { GAUGE_INFO("paramrevision = 0x%02x%02x, set parameter\n", buf[7], buf[6]); goto SETPARAMETER; } }else { GAUGE_INFO("paramrevision = 0x%02x%02x, set parameter\n", buf[7], buf[6]); goto SETPARAMETER; } } else { ret = mm8033_designcapacity(chip, &val); if (ret) return ret; if (val != chip->batparams.designcapacity) { if((Read_HW_ID()==HW_ID_ER)||(Read_HW_ID()==HW_ID_ER1_1)||(Read_HW_ID()==HW_ID_ER1_2)) { if((val<2800)||(val>3000)) { GAUGE_INFO("capacity = %d, set parameter\n", val); goto SETPARAMETER; } }else { GAUGE_INFO("capacity = %d, set parameter\n", val); goto SETPARAMETER; } } else { goto GETPARAMETER; } } GETPARAMETER: GAUGE_INFO("GETPARAMETER\n"); ret = mm8033_cyclecount(chip, &val); if (ret) return ret; chip->cyclecount = val; ret = mm8033_batteryimpedance(chip, &val); if (ret) return ret; chip->batteryimpedance = val; ret = mm8033_batterycapacity(chip, &val); if (ret) return ret; chip->batterycapacity = val; goto EXIT; SETPARAMETER: GAUGE_INFO("SETPARAMETER\n"); for (i = 0; i < TRY; i++) { ret = mm8033_setFgParameter(chip); if (ret) return ret; ret = mm8033_readx_reg(chip->client, 0xBE, buf, (u16)8); if (ret) return ret; /* need to check after */ if ((((buf[7] & 0xff) << 8) | (buf[6] & 0xff)) != chip->batparams.paramrevision) continue; if ((((buf[5] & 0xff) << 8) | (buf[4] & 0xff)) != chip->batparams.batterycode) continue; ret = mm8033_cyclecount(chip, &val); if (ret) return ret; if (val != chip->cyclecount) continue; ret = mm8033_designcapacity(chip, &val); if (ret) return ret; if (val != chip->batparams.designcapacity) continue; break; } if (i >= TRY) return -1; EXIT: GAUGE_INFO("%s ---\n", __func__); return 0; } static int mm8033_checkdevice(struct mm8033_chip *chip) { int i; int val; int ret; u8 projectname_low; u8 projectname_high; u8 packvendor; u8 cellvendor; u8 date_low; u8 date_high; u8 buf[8]; struct mm8033_batparams *batparams; // NVT ATL battery parameter struct mm8033_batparams params_nvt = { { 0xAB, 0x17, 0x94, 0x1E, 0xED, 0x2A, 0xE4, 0x3F, 0xA8, 0x5D, 0xE3, 0x5D, 0x22, 0x70, 0x6A, 0x78, 0x5B, 0x11, 0x42, 0xC2, 0x0D, 0x45, 0xF6, 0x0A, 0xDA, 0xE4, 0x48, 0x16, 0x48, 0x07, 0x40, 0xF4, 0x2B, 0x06, 0x46, 0x05, 0x3D, 0xFA, 0xB4, 0x01, 0x86, 0x03, 0xBD, 0xFD, 0xF3, 0xFF, 0x3F, 0x08, 0x49, 0xF7, 0x27, 0x02, 0x60, 0xFD, 0x1C, 0x06, 0x1A, 0xFD, 0xFE, 0xDE, 0xCA, 0x28, 0x34, 0xF3, 0x00, 0x0E, 0x0D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x04, 0x2F, 0x01, 0x66, 0x30, 0x00, 0x72, 0x06, 0x54, 0x0B, 0x48, 0x0D, 0x30, 0x11, 0x32, 0x41, 0x1E, 0x05, 0x3C, 0x2D, 0x78, 0x01, 0x00, 0x01, 0xB1, 0x0C, 0xED, 0x0C, 0x25, 0x0D, 0x97, 0x0D, 0x1E, 0x0E, 0x41, 0x0E, 0x60, 0x0E, 0x6F, 0x0E, 0x7A, 0x0E, 0x93, 0x0E, 0xB1, 0x0E, 0xC9, 0x0E, 0xE3, 0x0E, 0x0A, 0x0F, 0x34, 0x0F, 0x71, 0x0F, 0xAD, 0x0F, 0xFA, 0x0F, 0x72, 0x10, 0x1A, 0x11, 0x00, 0x00, 0x05, 0x00, 0x0A, 0x00, 0x14, 0x00, 0x26, 0x00, 0x32, 0x00, 0x4B, 0x00, 0x67, 0x00, 0x84, 0x00, 0xB4, 0x00, 0xFA, 0x00, 0x36, 0x01, 0x90, 0x01, 0xEA, 0x01, 0x2B, 0x02, 0x62, 0x02, 0xA8, 0x02, 0xF8, 0x02, 0x66, 0x03, 0xFC, 0x03, 0x00, 0xE1, 0x00, 0x4D, 0xE1, 0x00, 0xA6, 0xF0, 0x00, 0xFF, 0xD9, 0x00, 0x0D, 0xF6, 0x00, 0x39, 0xCB, 0x00, 0x5A, 0xF6, 0x00, 0x80, 0x3C, 0x00, 0x14, 0x0A, 0x05, 0x0A, 0x5C, 0xFF, 0xE4, 0x00, 0x9A, 0x0B, 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0xFF, 0x28, 0x00, 0x28, 0x00, 0x2D, 0x00, 0x46, 0x00, 0x00, 0x07, 0x08, 0xFF, 0xC8, 0x00, 0xC8, 0x00, 0x6E, 0x00, 0x82, 0x00, 0x00, 0x07, 0x08, 0xFF, 0xFE, 0x01, 0xFE, 0x01, 0xC8, 0x00, 0x18, 0x01, 0x00, 0x07, 0x08, 0x78, 0xFF, 0xFF, 0x9E, 0x02, 0x9E, 0x02, 0x2C, 0x01, 0x2C, 0x01, 0xA4, 0x01, 0xFF, 0xFF, 0x00, 0x07, 0x08, 0xE6, 0xFF, 0xFF, 0x1A, 0x04, 0x1A, 0x04, 0xF0, 0x00, 0x94, 0x02, 0x94, 0x02, 0xFF, 0xFF, 0x56, 0x0E, 0x0A, 0x2C, 0xD8, 0x0E, 0x0A, 0x20, 0xE6, 0x0C, 0x0C, 0xFE, 0x3A, 0xFC, 0x68, 0x03, 0x82, 0x00, 0xA8, 0x94, 0x0F, 0x66, 0xFA, 0x1E, 0xF4, 0x01, 0xE4, 0x00, 0x02, 0x02, 0x32, 0x0A, 0xA4, 0x01, 0x1A, 0x01, 0xA0, 0x00, 0xFF, 0xFF, 0xAA, 0x02, 0x35, 0x01, 0x20, 0x03, 0x60, 0x62, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x9C, 0xCE, 0xFF, 0x01, 0x32, 0x64, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x80, 0xFA, 0xFD, 0xFF, 0x01, 0x03, 0x06, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x00, 0x00, 0x14, 0x14, 0x14, 0x05, 0x00, 0x00, 0x06, 0x00, 0x19, 0x10, 0x17, 0x17, 0x3E, 0x17, 0x17, 0x02, 0x1C, 0x03, 0x0D, 0x32, 0x0A, 0xFF, 0x0A, 0x12, 0x66, 0xFF, 0x02, 0x05, 0x05, 0x01, 0x70, 0xC2, 0x0A, 0x00, 0x00, 0x00, 0x03, 0x99, 0x99, 0x96, 0xFF, 0xCC, 0x4B, 0x0F, 0x71, 0xC1, 0x62, 0x05, 0x14, 0x0A, 0x2C, 0x01, 0x5F, 0x05, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x7A, 0x0D, 0x48, 0x0D, 0x03, 0x00, 0x0A, 0x0A, 0x64, 0x00, 0x54, 0x0B, 0x64, 0x02, 0x02, 0x02, 0x7D, 0x73, 0xFA, 0xE6, 0xBC, 0xB7, 0x6C, 0x71, 0x4B, 0x78, 0x78, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x30, 0x74, 0x0F, 0xFF, 0x03, 0x00, 0x04, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }, #ifdef I2CLOW_RESTART 1, // enable i2c_sh #else 0, // enable i2c_sh #endif 4350, // full voltage threshold 2970, // design capacity 130, // charge terminal current 0x0104, // parameter revision 0x0003, // battery code 0, // default cycle count 2970, // default battery capacity 130 // default battery impedance }; // Simplo Coslight battery parameter struct mm8033_batparams params_simplo = { { 0xEB, 0x17, 0xC0, 0x1F, 0x35, 0x2C, 0xBE, 0x3F, 0xB0, 0x42, 0x36, 0x60, 0xB6, 0x71, 0x41, 0x79, 0x73, 0x11, 0xB7, 0xC1, 0xC8, 0x45, 0x53, 0x0A, 0xD8, 0xE7, 0xC5, 0x12, 0x14, 0x07, 0xF0, 0xF4, 0x93, 0x05, 0x2D, 0x05, 0x72, 0xFA, 0x96, 0x01, 0xB4, 0x04, 0x65, 0xFB, 0x1C, 0x01, 0x56, 0x03, 0x05, 0xFE, 0xDA, 0xFF, 0x48, 0xFD, 0x12, 0x06, 0x2C, 0xFD, 0xA4, 0xD1, 0x33, 0x37, 0x59, 0xEF, 0x00, 0x0E, 0x0D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x04, 0x2F, 0x01, 0x66, 0x30, 0x00, 0x72, 0x06, 0x54, 0x0B, 0x48, 0x0D, 0x30, 0x11, 0x32, 0x41, 0x1E, 0x05, 0x3C, 0x2D, 0x78, 0x01, 0x00, 0x01, 0xB8, 0x0C, 0xFC, 0x0C, 0x45, 0x0D, 0xAF, 0x0D, 0x0F, 0x0E, 0x3C, 0x0E, 0x63, 0x0E, 0x70, 0x0E, 0x7A, 0x0E, 0x91, 0x0E, 0xAF, 0x0E, 0xC7, 0x0E, 0xE3, 0x0E, 0x08, 0x0F, 0x31, 0x0F, 0x6C, 0x0F, 0xA9, 0x0F, 0xF9, 0x0F, 0x6E, 0x10, 0x15, 0x11, 0x00, 0x00, 0x05, 0x00, 0x0A, 0x00, 0x14, 0x00, 0x26, 0x00, 0x37, 0x00, 0x4D, 0x00, 0x67, 0x00, 0x84, 0x00, 0xB4, 0x00, 0xFA, 0x00, 0x36, 0x01, 0x90, 0x01, 0xEA, 0x01, 0x2B, 0x02, 0x62, 0x02, 0xA8, 0x02, 0xF8, 0x02, 0x66, 0x03, 0xFC, 0x03, 0x00, 0xE1, 0x00, 0x4D, 0xE1, 0x00, 0xA6, 0xF0, 0x00, 0xFF, 0xD4, 0x00, 0x0D, 0xF6, 0x00, 0x39, 0xCB, 0x00, 0x5A, 0xF6, 0x00, 0x80, 0x3C, 0x00, 0x14, 0x0A, 0x05, 0x0A, 0x5C, 0xFF, 0xE4, 0x00, 0x54, 0x0B, 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0xFF, 0x96, 0x00, 0x96, 0x00, 0x58, 0x00, 0x5A, 0x00, 0x00, 0x07, 0x08, 0xFF, 0xDC, 0x00, 0xDC, 0x00, 0x69, 0x00, 0x8C, 0x00, 0x00, 0x07, 0x08, 0xFF, 0x1C, 0x02, 0x1C, 0x02, 0x09, 0x01, 0x5E, 0x01, 0x00, 0x07, 0x08, 0x6E, 0xFF, 0xFF, 0x80, 0x02, 0x80, 0x02, 0x7C, 0x01, 0x68, 0x01, 0xF4, 0x01, 0xFF, 0xFF, 0x00, 0x07, 0x08, 0x78, 0xFF, 0xFF, 0x84, 0x03, 0x84, 0x03, 0x58, 0x02, 0xE0, 0x01, 0x8A, 0x02, 0xFF, 0xFF, 0x42, 0x0E, 0x0A, 0x1E, 0xEC, 0x0E, 0x0A, 0x32, 0xE6, 0x0C, 0xD4, 0xFE, 0x57, 0xFC, 0x92, 0x03, 0x8C, 0x00, 0xA8, 0x94, 0x0F, 0x66, 0xFA, 0x1E, 0xF4, 0x01, 0xD4, 0x00, 0x02, 0x02, 0x32, 0x0A, 0x6D, 0x01, 0xFB, 0x00, 0x96, 0x00, 0xFF, 0xFF, 0xAA, 0x02, 0x35, 0x01, 0x20, 0x03, 0x60, 0x62, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x9C, 0xCE, 0xFF, 0x01, 0x32, 0x64, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x80, 0xFA, 0xFD, 0xFF, 0x01, 0x03, 0x06, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x00, 0x00, 0x14, 0x14, 0x14, 0x05, 0x00, 0x00, 0x06, 0x00, 0x19, 0x10, 0x17, 0x17, 0x3E, 0x17, 0x17, 0x02, 0x1C, 0x03, 0x0D, 0x32, 0x0A, 0xFF, 0x0A, 0x12, 0x66, 0xFF, 0x02, 0x05, 0x05, 0x01, 0x70, 0xC2, 0x0A, 0x00, 0x00, 0x00, 0x03, 0x99, 0x99, 0x96, 0xFF, 0xCC, 0x4B, 0x0F, 0x71, 0xC1, 0x62, 0x05, 0x14, 0x0A, 0x2C, 0x01, 0x5F, 0x05, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x98, 0x0D, 0x48, 0x0D, 0x03, 0x00, 0x0A, 0x0A, 0x64, 0x00, 0x54, 0x0B, 0x64, 0x02, 0x02, 0x02, 0x7D, 0x73, 0xFA, 0xE6, 0xBC, 0xB7, 0x6C, 0x71, 0x4B, 0x78, 0x78, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0x7A, 0x0F, 0xFF, 0x04, 0x00, 0x04, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }, #ifdef I2CLOW_RESTART 1, // enable i2c_sh #else 0, // enable i2c_sh #endif 4350, // full voltage threshold 2900, // design capacity 130, // charge terminal current 0x0104, // parameter revision 0x0004, // battery code 0, // default cycle count 2900, // default battery capacity 140 // default battery impedance }; // Celxpert Coslight battery parameter struct mm8033_batparams params_celxpert = { { 0xEB, 0x17, 0xC0, 0x1F, 0x35, 0x2C, 0xBE, 0x3F, 0xB0, 0x42, 0x36, 0x60, 0xB6, 0x71, 0x41, 0x79, 0x73, 0x11, 0xB7, 0xC1, 0xC8, 0x45, 0x53, 0x0A, 0xD8, 0xE7, 0xC5, 0x12, 0x14, 0x07, 0xF0, 0xF4, 0x93, 0x05, 0x2D, 0x05, 0x72, 0xFA, 0x96, 0x01, 0xB4, 0x04, 0x65, 0xFB, 0x1C, 0x01, 0x56, 0x03, 0x05, 0xFE, 0xDA, 0xFF, 0x48, 0xFD, 0x12, 0x06, 0x2C, 0xFD, 0xA4, 0xD1, 0x33, 0x37, 0x59, 0xEF, 0x00, 0x0E, 0x0D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x04, 0x2F, 0x01, 0x66, 0x30, 0x00, 0x72, 0x06, 0x54, 0x0B, 0x48, 0x0D, 0x30, 0x11, 0x32, 0x41, 0x1E, 0x05, 0x3C, 0x2D, 0x78, 0x01, 0x00, 0x01, 0x9E, 0x0C, 0xF2, 0x0C, 0x39, 0x0D, 0x8E, 0x0D, 0xF3, 0x0D, 0x2F, 0x0E, 0x5D, 0x0E, 0x69, 0x0E, 0x74, 0x0E, 0x8D, 0x0E, 0xAB, 0x0E, 0xC4, 0x0E, 0xE3, 0x0E, 0x09, 0x0F, 0x31, 0x0F, 0x62, 0x0F, 0xA7, 0x0F, 0xF6, 0x0F, 0x6B, 0x10, 0x13, 0x11, 0x00, 0x00, 0x05, 0x00, 0x0A, 0x00, 0x14, 0x00, 0x26, 0x00, 0x32, 0x00, 0x41, 0x00, 0x67, 0x00, 0x84, 0x00, 0xB4, 0x00, 0xFA, 0x00, 0x36, 0x01, 0x90, 0x01, 0xEA, 0x01, 0x2B, 0x02, 0x62, 0x02, 0xA8, 0x02, 0xF8, 0x02, 0x66, 0x03, 0xFC, 0x03, 0x00, 0xE1, 0x00, 0x4D, 0xE1, 0x00, 0xA6, 0xF0, 0x00, 0xFF, 0xDD, 0x00, 0x0D, 0xF6, 0x00, 0x39, 0xCB, 0x00, 0x5A, 0xF6, 0x00, 0x80, 0x3C, 0x00, 0x14, 0x0A, 0x05, 0x0A, 0x5C, 0xFF, 0xE4, 0x00, 0x54, 0x0B, 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x09, 0xFF, 0x6E, 0x00, 0x6E, 0x00, 0x50, 0x00, 0x5A, 0x00, 0x00, 0x08, 0x09, 0xFF, 0xFA, 0x00, 0xFA, 0x00, 0xA0, 0x00, 0xAA, 0x00, 0x00, 0x08, 0x09, 0xFF, 0x3A, 0x02, 0x3A, 0x02, 0x2C, 0x01, 0x90, 0x01, 0x00, 0x08, 0x09, 0x8C, 0xFF, 0xFF, 0x94, 0x02, 0x94, 0x02, 0x90, 0x01, 0x90, 0x01, 0xE0, 0x01, 0xFF, 0xFF, 0x00, 0x08, 0x09, 0xB4, 0xFF, 0xFF, 0x84, 0x03, 0x84, 0x03, 0x58, 0x02, 0x3A, 0x02, 0xA8, 0x02, 0xFF, 0xFF, 0x56, 0x0E, 0x0A, 0x1E, 0xEC, 0x0E, 0x0A, 0x10, 0xE6, 0x0C, 0xD4, 0xFE, 0x94, 0xFB, 0x98, 0x03, 0xAA, 0x00, 0xA8, 0x94, 0x0F, 0x66, 0xFA, 0x1E, 0xF4, 0x01, 0xAE, 0x00, 0x02, 0x02, 0x32, 0x0A, 0x72, 0x01, 0xFC, 0x00, 0x96, 0x00, 0xFF, 0xFF, 0xAA, 0x02, 0x35, 0x01, 0x20, 0x03, 0x60, 0x62, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x9C, 0xCE, 0xFF, 0x01, 0x32, 0x64, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x80, 0xFA, 0xFD, 0xFF, 0x01, 0x03, 0x06, 0x7F, 0x04, 0x05, 0x06, 0x08, 0x0F, 0x14, 0x19, 0x19, 0x00, 0x00, 0x14, 0x14, 0x14, 0x05, 0x00, 0x00, 0x06, 0x00, 0x19, 0x10, 0x17, 0x17, 0x3E, 0x17, 0x17, 0x02, 0x1C, 0x03, 0x0D, 0x32, 0x0A, 0xFF, 0x0A, 0x12, 0x66, 0xFF, 0x02, 0x05, 0x05, 0x01, 0x70, 0xC2, 0x0A, 0x00, 0x00, 0x00, 0x03, 0x99, 0x99, 0x96, 0xFF, 0xCC, 0x4B, 0x0F, 0x71, 0xC1, 0x62, 0x05, 0x14, 0x0A, 0x2C, 0x01, 0x5F, 0x05, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xAC, 0x0D, 0x48, 0x0D, 0x03, 0x00, 0x0A, 0x0A, 0x64, 0x00, 0x54, 0x0B, 0x64, 0x02, 0x02, 0x02, 0x7D, 0x73, 0xFA, 0xE6, 0xBC, 0xB7, 0x6C, 0x71, 0x4B, 0x78, 0x78, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x30, 0x64, 0x0F, 0xFF, 0x05, 0x00, 0x04, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }, #ifdef I2CLOW_RESTART 1, // enable i2c_sh #else 0, // enable i2c_sh #endif 4350, // full voltage threshold 2900, // design capacity 130, // charge terminal current 0x0104, // parameter revision 0x0005, // battery code 0, // default cycle count 2900, // default battery capacity 170 // default battery impedance }; if((Read_HW_ID()!=HW_ID_SR1)&&(Read_HW_ID()!=HW_ID_SR2)) { //SR's battery ID in OTP is old so donnot check ret = mm8033_identify(chip, &val); if (ret) return ret; if (val != MM8033_ID) { GAUGE_INFO("ID = 0x%04x\n", val); return -1; } } do { ret = mm8033_fgstat(chip, &val); if (ret) return ret; } while (val & 0x0001); ret = mm8033_voltage(chip, &val); if (ret) return ret; if (val < SYSTEM_LOWVOLTAGE_LIMIT) return -1; // get project ids ret = mm8033_projectname(chip, &val); if (ret) return ret; projectname_low = (u8)((val & 0x00ff) >> 0); projectname_high = (u8)((val & 0xff00) >> 8); //get vendor id ret = mm8033_packcellvendor(chip, &val); if (ret) return ret; packvendor = (u8)((val & 0x00ff) >> 0); cellvendor = (u8)((val & 0xff00) >> 8); //get ic date ret = mm8033_bat_date(chip, &val); if (ret) return ret; date_low = (u8)((val & 0x00ff) >> 0); date_high = (u8)((val & 0xff00) >> 8); //show bat parameter date[15:9]=year, date[8:5]=week_1, date[4:0]=week_2 bat_year = (int)(date_high >> 1); bat_week_1 = (int)( ((date_high & 0x01) << 3) +((date_low & 0xe0) >> 5) ); bat_week_2 = (int)(date_low & 0x1f); // select params if ((projectname_low != (u8)'Z') || (projectname_high != (u8)'2')) { if(((projectname_low == (u8)'2') && (projectname_high == (u8)'Z'))&&((packvendor == (u8)'3') && (cellvendor == (u8)'C'))) { batparams = &params_celxpert; GAUGE_INFO("BATTERY is CELXPERT(inverse ID info)\n"); batt_id = "Z2C3"; } else { batparams = &params_nvt; GAUGE_INFO("PROJECT is 0x%02x%02x, not Z2, use NVT as default\n", projectname_high, projectname_low); batt_id = "----"; invalid_bat = 1; } } else { if ((packvendor == (u8)'N') && (cellvendor == (u8)'3')) { batparams = &params_nvt; GAUGE_INFO("BATTERY is NVT\n"); batt_id = "Z2N3"; } else if ((packvendor == (u8)'S') && (cellvendor == (u8)'3')) { batparams = &params_simplo; GAUGE_INFO("BATTERY is SIMPLO\n"); batt_id = "Z2S3"; } else if ((packvendor == (u8)'C') && (cellvendor == (u8)'3')) { batparams = &params_celxpert; GAUGE_INFO("BATTERY is CELXPERT\n"); batt_id = "Z2C3"; } else { batparams = &params_nvt; GAUGE_INFO("BATTERY is 0x%02x%02x, not valid, use NVT as default\n", cellvendor, packvendor); batt_id = "----"; invalid_bat = 1; } } // copy params for (i = 0; i < 512; i++) { chip->batparams.params[i] = batparams->params[i]; } chip->batparams.en_i2c_sh = batparams->en_i2c_sh; chip->batparams.fullvoltage_thr = batparams->fullvoltage_thr; chip->batparams.designcapacity = batparams->designcapacity; chip->batparams.charge_terminal_current = batparams->charge_terminal_current; chip->batparams.paramrevision = batparams->paramrevision; chip->batparams.batterycode = batparams->batterycode; chip->batparams.default_cyclecount = batparams->default_cyclecount; chip->batparams.default_batterycapacity = batparams->default_batterycapacity; chip->batparams.default_batteryimpedance = batparams->default_batteryimpedance; chip->cyclecount = batparams->default_cyclecount; chip->batterycapacity = batparams->default_batterycapacity; chip->batteryimpedance = batparams->default_batteryimpedance; ret = mm8033_readx_reg(chip->client, 0xBE, buf, (u16)8); if (ret) return ret; parameter_version = ((buf[7] & 0xff) << 8) | (buf[6] & 0xff); battery_ctrlcode = ((buf[5] & 0xff) << 8) | (buf[4] & 0xff); if((Read_HW_ID()!=HW_ID_SR1)&&(Read_HW_ID()!=HW_ID_SR2)) { ret = mm8033_checkRamData(chip); if (ret) return ret; } return 0; } #ifdef REGISTER_POWER_SUPPLY static enum power_supply_property mm8033_battery_props[] = { POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_TEMP, }; static int mm8033_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret = 0; struct mm8033_chip *chip = container_of(psy, struct mm8033_chip, battery); if (chip->skipcheck > SKIP) { chip->skipcheck = 0; ret = mm8033_checkRamData(chip); } else { chip->skipcheck++; } switch (psp) { case POWER_SUPPLY_PROP_CAPACITY: ret = mm8033_soc(chip, &(val->intval)); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = mm8033_voltage(chip, &(val->intval)); break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = mm8033_current(chip, &(val->intval)); break; case POWER_SUPPLY_PROP_TEMP: ret = mm8033_temperature(chip, &(val->intval)); break; default: return -EINVAL; } return ret; } #endif /* +++for tbl usage+++*/ int mm8033_read_current(void) { int curr = mm8033_read_reg(g_mm8033_chip->client, REG_CURRENT); if (curr < 0) { GAUGE_ERR("error in reading battery current = 0x%04x\n", curr); return 0x10000; }else { if (curr > 32767) { curr -= 65536; } curr += 0x10000; //GAUGE_INFO("curr = %d\n", curr); return curr; } } int mm8033_read_volt(void) { int volt = mm8033_read_reg(g_mm8033_chip->client, REG_VOLTAGE); if (volt < 0) { GAUGE_ERR("error in reading battery voltage = 0x%04x\n", volt); return 3000; }else { //GAUGE_INFO("volt = %d\n", volt); return volt; } } int mm8033_read_percentage(void) { int soc = mm8033_read_reg(g_mm8033_chip->client, REG_SOC); #ifdef SOC_SMOOTH_ALGO int soc_final = 0, ret = 0; #endif if (soc < 0) { GAUGE_ERR("error in reading battery soc = 0x%04x\n", soc); return 50; }else { //GAUGE_INFO("percentage = %d\n", soc / 256); /*>.5% + 1%*/ if (((soc+128) / 256)>100) { return 100; } else { #ifdef SOC_SMOOTH_ALGO soc_final = (soc+128) / 256; GAUGE_INFO("%s start smooth algo, soc last=%d, soc now=%d\n",__func__, mm8033_pre_soc, soc_final); if (mm8033_pre_soc!=0) { if ((mm8033_pre_soc+3) <= soc_final) { /* reset ocv if gauge soc=100, now soc<100, 0<cur<150 */ if ((soc_final==100)&&((mm8033_read_current()-0x10000)>0)&&((mm8033_read_current()-0x10000)<150)) { ret = mm8033_write_reg(g_mm8033_chip->client, REG_FG_CONDITION, 0x0020); if (ret < 0) { GAUGE_ERR("reset OCV failed with ret=%d\n", ret); } else { GAUGE_INFO("reset OCV success\n"); } } soc_final = mm8033_pre_soc + 3; } else if((soc_final>2)&&(mm8033_read_volt()>3200)&&(mm8033_read_volt()<3300)) { /* reset ocv if gauge soc>2, 3.2V<bat<3.3V*/ ret = mm8033_write_reg(g_mm8033_chip->client, REG_FG_CONDITION, 0x0020); if (ret < 0) { GAUGE_ERR("reset OCV failed with ret=%d\n", ret); } else { GAUGE_INFO("reset OCV success\n"); } } } mm8033_pre_soc = soc_final; return soc_final; #else return (soc+128) / 256; #endif } } } int mm8033_read_temp(void) { int temp = mm8033_read_reg(g_mm8033_chip->client, REG_TEMPERATURE); if (temp < 0) { GAUGE_ERR("error in reading battery temperature = 0x%04x\n", temp); return 250; }else { if (temp > 32767) { temp -= 65536; } //GAUGE_INFO("temp = %d\n", temp); return temp; } } int mm8033_read_fcc(void) { int fcc = mm8033_read_reg(g_mm8033_chip->client, REG_FULL_CHARGE_CAPACITY); if (fcc < 0) { GAUGE_ERR("error in reading battery fcc = 0x%04x\n", fcc); return 3000; }else { //GAUGE_INFO("fcc = %d\n", fcc); return 3000; } } int mm8033_read_rm(void) { int rm = mm8033_read_reg(g_mm8033_chip->client, REG_REM_CAPACITY); if (rm < 0) { GAUGE_ERR("error in reading battery rm = 0x%04x\n", rm); return 1500; }else { //GAUGE_INFO("rm = %d\n", rm); return rm; } } /* ---for tbl usage---*/ static void batt_state_func(struct work_struct *work) { u8 buf[8]; GAUGE_INFO("%s +++ in every 60s \n",__func__); mm8033_readx_reg(g_mm8033_chip->client, 0xBE, buf, (u16)8); parameter_version = ((buf[7] & 0xff) << 8) | (buf[6] & 0xff); battery_ctrlcode = ((buf[5] & 0xff) << 8) | (buf[4] & 0xff); GAUGE_INFO("0x00=0x%04x, 0x06=0x%04x, 0x08=0x%04x, 0x09=0x%04x, 0x0A=0x%04x, 0x0C=0x%04x, 0x10=0x%04x, 0x17=0x%04x, 0x18=0x%04x, 0x1D=0x%04x, 0x23=0x%04x\n", mm8033_read_reg(g_mm8033_chip->client, REG_STATUS), mm8033_read_reg(g_mm8033_chip->client, REG_SOC), mm8033_read_reg(g_mm8033_chip->client, REG_TEMPERATURE), mm8033_read_reg(g_mm8033_chip->client, REG_VOLTAGE), mm8033_read_reg(g_mm8033_chip->client, REG_CURRENT), mm8033_read_reg(g_mm8033_chip->client, REG_IC_TEMPERATURE), mm8033_read_reg(g_mm8033_chip->client, REG_FULL_CHARGE_CAPACITY), mm8033_read_reg(g_mm8033_chip->client, REG_CYCLE_COUNT), mm8033_read_reg(g_mm8033_chip->client, REG_DESIGN_CAPACITY), mm8033_read_reg(g_mm8033_chip->client, REG_CONFIG), mm8033_read_reg(g_mm8033_chip->client, REG_BATTERY_CAPACITY) ); if(invalid_bat==1) { GAUGE_INFO("info: ---- %04x%04x ------ version: %s\n", parameter_version, battery_ctrlcode, DRIVER_VERSION); }else { GAUGE_INFO("info: %s %04x%04x %d%d%d version: %s\n", batt_id, parameter_version, battery_ctrlcode, bat_year, bat_week_1, bat_week_2, DRIVER_VERSION); } //check ram data after state work 10 times if (g_mm8033_chip->skipcheck > SKIP) { g_mm8033_chip->skipcheck = 0; mm8033_checkRamData(g_mm8033_chip); } else { g_mm8033_chip->skipcheck++; } schedule_delayed_work(&batt_state_wq, 60*HZ); } static ssize_t batt_switch_name(struct switch_dev *sdev, char *buf) { if(invalid_bat==1) { return sprintf(buf, "---- %04x%04x ------\n", parameter_version, battery_ctrlcode); }else { return sprintf(buf, "%s %04x%04x %d%d%d\n", batt_id, parameter_version, battery_ctrlcode, bat_year, bat_week_1, bat_week_2); } } #ifdef CONFIG_HAS_EARLYSUSPEND static void mm8033_early_suspend(struct early_suspend *h) { GAUGE_INFO("%s ++\n", __func__); cancel_delayed_work(&batt_state_wq); flush_delayed_work(&batt_state_wq); } static void mm8033_late_resume(struct early_suspend *h) { GAUGE_INFO("%s ++\n", __func__); schedule_delayed_work(&batt_state_wq, 5*HZ); } static void mm8033_config_earlysuspend(struct mm8033_chip *chip) { chip->es.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN - 2; chip->es.suspend = mm8033_early_suspend; chip->es.resume = mm8033_late_resume; register_early_suspend(&chip->es); } #else #define mm8033_early_suspend NULL #define mm8033_late_resume NULL static void mm8033_config_earlysuspend(struct mm8033_chip *chip) { return; } #endif static int mm8033_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct mm8033_chip *chip; int ret; u32 test_major_flag=0; struct asus_bat_config bat_cfg; #ifndef STOP_IF_FAIL int i; #endif GAUGE_INFO("%s ++\n", __func__); //turn to jiffeys bat_cfg.polling_time = 0; bat_cfg.critical_polling_time = 0; bat_cfg.polling_time *= HZ; bat_cfg.critical_polling_time *= HZ; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) return -EIO; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; chip->client = client; i2c_set_clientdata(client, chip); #ifdef REGISTER_POWER_SUPPLY chip->battery.name = "mm8033_battery"; chip->battery.type = POWER_SUPPLY_TYPE_BATTERY; chip->battery.get_property = mm8033_get_property; chip->battery.properties = mm8033_battery_props; chip->battery.num_properties = 4; ret = power_supply_register(&client->dev, &chip->battery); if (ret) { dev_err(&client->dev, "failed: power supply register\n"); i2c_set_clientdata(client, NULL); kfree(chip); return ret; } #endif // read stored data chip->skipcheck = SKIP; ret = mm8033_checkdevice(chip); #ifdef STOP_IF_FAIL if (ret) { dev_err(&client->dev, "failed to access\n"); i2c_set_clientdata(client, NULL); kfree(chip); return ret; }else { GAUGE_INFO("init asus battery\n"); ret = asus_battery_init(bat_cfg.polling_time, bat_cfg.critical_polling_time, test_major_flag); if (ret) GAUGE_ERR("asus_battery_init fail\n"); } #else for(i=0;i<1;i++) { if (ret) { GAUGE_ERR("error in checkdevice with ret: %d in loop %d\n", ret, i); msleep(50); ret = mm8033_checkdevice(chip); }else { GAUGE_INFO("checkdevice success in loop %d\n", i); break; } } GAUGE_INFO("init asus battery\n"); ret = asus_battery_init(bat_cfg.polling_time, bat_cfg.critical_polling_time, test_major_flag); if (ret) GAUGE_ERR("asus_battery_init fail\n"); #endif g_mm8033_chip = chip; /* register switch device for battery information versions report */ mm8033_batt_dev.name = "battery"; mm8033_batt_dev.print_name = batt_switch_name; if (switch_dev_register(&mm8033_batt_dev) < 0) GAUGE_ERR("%s: fail to register battery switch\n", __func__); switch_set_state(&mm8033_batt_dev, 0); /* register power supply in asus_battery_power.c */ mm8033_tbl.read_percentage = mm8033_read_percentage; mm8033_tbl.read_current = mm8033_read_current; mm8033_tbl.read_volt = mm8033_read_volt; mm8033_tbl.read_temp = mm8033_read_temp; mm8033_tbl.read_fcc = mm8033_read_fcc; mm8033_tbl.read_rm = mm8033_read_rm; ret = asus_register_power_supply(&client->dev, &mm8033_tbl); if (ret) GAUGE_ERR("asus_register_power_supply fail\n"); INIT_DELAYED_WORK(&batt_state_wq, batt_state_func); schedule_delayed_work(&batt_state_wq, 10*HZ); #ifdef CONFIG_HAS_EARLYSUSPEND mm8033_config_earlysuspend(chip); #endif GAUGE_INFO("%s --\n", __func__); return 0; } static int mm8033_remove(struct i2c_client *client) { struct mm8033_chip *chip = i2c_get_clientdata(client); #ifdef REGISTER_POWER_SUPPLY power_supply_unregister(&chip->battery); #endif i2c_set_clientdata(client, NULL); kfree(chip); return 0; } static const struct i2c_device_id mm8033_id[] = { { "mm8033_batt", 0 }, {}, }; MODULE_DEVICE_TABLE(i2c, mm8033_id); static struct i2c_driver mm8033_i2c_driver = { .driver = { .name = "mm8033_batt", }, .probe = mm8033_probe, .remove = mm8033_remove, .id_table = mm8033_id, }; #ifdef REGISTER_I2C static struct i2c_board_info mm8033_board_info[] = { { I2C_BOARD_INFO("mm8033", 0x36), }, }; #endif static int __init mm8033_init(void) { int ret; GAUGE_INFO("%s +++\n", __func__); if(Read_HW_ID()==HW_ID_EVB) { GAUGE_INFO("HW version is EVB, so donot init\n"); return 0; }else if (Read_PROJ_ID()==PROJ_ID_ZX550ML) { GAUGE_INFO("Project version is ZX550ML, so donot init\n"); return 0; } ret = i2c_add_driver(&mm8033_i2c_driver); if (ret) GAUGE_ERR("%s: i2c_add_driver failed\n", __func__); #ifdef REGISTER_I2C ret = i2c_register_board_info(2, mm8033_board_info, ARRAY_SIZE(mm8033_board_info)); if (ret) GAUGE_ERR("%s: i2c_register_board_info failed\n", __func__); #endif GAUGE_INFO("%s ---\n", __func__); return ret; } late_initcall(mm8033_init); static void __exit mm8033_exit(void) { i2c_del_driver(&mm8033_i2c_driver); } module_exit(mm8033_exit); MODULE_AUTHOR("Chih-Hsuan Chang <Chih-Hsuan_Chang@asus.com>"); MODULE_DESCRIPTION("mm8033a01 battery monitor driver"); MODULE_LICENSE("GPL");
TheSSJ/android_kernel_asus_moorefield
drivers/power/ASUS_BATTERY/mm8033_battery.c
C
gpl-2.0
40,327
/*++ Copyright (c) Realtek Semiconductor Corp. All rights reserved. Module Name: RateAdaptive.c Abstract: Implement Rate Adaptive functions for common operations. Major Change History: When Who What ---------- --------------- ------------------------------- 2011-08-12 Page Create. --*/ #include "../odm_precomp.h" //#if( DM_ODM_SUPPORT_TYPE == ODM_MP) //#include "Mp_Precomp.h" //#endif #if (RATE_ADAPTIVE_SUPPORT == 1) // Rate adaptive parameters static u1Byte RETRY_PENALTY[PERENTRY][RETRYSIZE+1] = {{5,4,3,2,0,3},//92 , idx=0 {6,5,4,3,0,4},//86 , idx=1 {6,5,4,2,0,4},//81 , idx=2 {8,7,6,4,0,6},//75 , idx=3 {10,9,8,6,0,8},//71 , idx=4 {10,9,8,4,0,8},//66 , idx=5 {10,9,8,2,0,8},//62 , idx=6 {10,9,8,0,0,8},//59 , idx=7 {18,17,16,8,0,16},//53 , idx=8 {26,25,24,16,0,24},//50 , idx=9 {34,33,32,24,0,32},//47 , idx=0x0a //{34,33,32,16,0,32},//43 , idx=0x0b //{34,33,32,8,0,32},//40 , idx=0x0c //{34,33,28,8,0,32},//37 , idx=0x0d //{34,33,20,8,0,32},//32 , idx=0x0e //{34,32,24,8,0,32},//26 , idx=0x0f //{49,48,32,16,0,48},//20 , idx=0x10 //{49,48,24,0,0,48},//17 , idx=0x11 //{49,47,16,16,0,48},//15 , idx=0x12 //{49,44,16,16,0,48},//12 , idx=0x13 //{49,40,16,0,0,48},//9 , idx=0x14 {34,31,28,20,0,32},//43 , idx=0x0b {34,31,27,18,0,32},//40 , idx=0x0c {34,31,26,16,0,32},//37 , idx=0x0d {34,30,22,16,0,32},//32 , idx=0x0e {34,30,24,16,0,32},//26 , idx=0x0f {49,46,40,16,0,48},//20 , idx=0x10 {49,45,32,0,0,48},//17 , idx=0x11 {49,45,22,18,0,48},//15 , idx=0x12 {49,40,24,16,0,48},//12 , idx=0x13 {49,32,18,12,0,48},//9 , idx=0x14 {49,22,18,14,0,48},//6 , idx=0x15 {49,16,16,0,0,48}};//3 //3, idx=0x16 static u1Byte RETRY_PENALTY_UP[RETRYSIZE+1]={49,44,16,16,0,48}; // 12% for rate up static u1Byte PT_PENALTY[RETRYSIZE+1]={34,31,30,24,0,32}; #if 0 static u1Byte RETRY_PENALTY_IDX[2][RATESIZE] = {{4,4,4,5,4,4,5,7,7,7,8,0x0a, // SS>TH 4,4,4,4,6,0x0a,0x0b,0x0d, 5,5,7,7,8,0x0b,0x0d,0x0f}, // 0329 R01 {4,4,4,5,7,7,9,9,0x0c,0x0e,0x10,0x12, // SS<TH 4,4,5,5,6,0x0a,0x11,0x13, 9,9,9,9,0x0c,0x0e,0x11,0x13}}; #endif #if (DM_ODM_SUPPORT_TYPE & ODM_AP) static u1Byte RETRY_PENALTY_IDX[2][RATESIZE] = {{4,4,4,5,4,4,5,7,7,7,8,0x0a, // SS>TH 4,4,4,4,6,0x0a,0x0b,0x0d, 5,5,7,7,8,0x0b,0x0d,0x0f}, // 0329 R01 {0x0a,0x0a,0x0a,0x0a,0x0c,0x0c,0x0e,0x10,0x11,0x12,0x12,0x13, // SS<TH 0x0e,0x0f,0x10,0x10,0x11,0x14,0x14,0x15, 9,9,9,9,0x0c,0x0e,0x11,0x13}}; static u1Byte RETRY_PENALTY_UP_IDX[RATESIZE] = {0x10,0x10,0x10,0x10,0x11,0x11,0x12,0x12,0x12,0x13,0x13,0x14, // SS>TH 0x13,0x13,0x14,0x14,0x15,0x15,0x15,0x15, 0x11,0x11,0x12,0x13,0x13,0x13,0x14,0x15}; static u1Byte RSSI_THRESHOLD[RATESIZE] = {0,0,0,0, 0,0,0,0,0,0x24,0x26,0x2a, 0x13,0x15,0x17,0x18,0x1a,0x1c,0x1d,0x1f, 0,0,0,0x1f,0x23,0x28,0x2a,0x2c}; #else // wilson modify static u1Byte RETRY_PENALTY_IDX[2][RATESIZE] = {{4,4,4,5,4,4,5,7,7,7,8,0x0a, // SS>TH 4,4,4,4,6,0x0a,0x0b,0x0d, 5,5,7,7,8,0x0b,0x0d,0x0f}, // 0329 R01 {0x0a,0x0a,0x0b,0x0c,0x0a,0x0a,0x0b,0x0c,0x0d,0x10,0x13,0x14, // SS<TH 0x0b,0x0c,0x0d,0x0e,0x0f,0x11,0x13,0x15, 9,9,9,9,0x0c,0x0e,0x11,0x13}}; static u1Byte RETRY_PENALTY_UP_IDX[RATESIZE] = {0x0c,0x0d,0x0d,0x0f,0x0d,0x0e,0x0f,0x0f,0x10,0x12,0x13,0x14, // SS>TH 0x0f,0x10,0x10,0x12,0x12,0x13,0x14,0x15, 0x11,0x11,0x12,0x13,0x13,0x13,0x14,0x15}; static u1Byte RSSI_THRESHOLD[RATESIZE] = {0,0,0,0, 0,0,0,0,0,0x24,0x26,0x2a, 0x18,0x1a,0x1d,0x1f,0x21,0x27,0x29,0x2a, 0,0,0,0x1f,0x23,0x28,0x2a,0x2c}; #endif /*static u1Byte RSSI_THRESHOLD[RATESIZE] = {0,0,0,0, 0,0,0,0,0,0x24,0x26,0x2a, 0x1a,0x1c,0x1e,0x21,0x24,0x2a,0x2b,0x2d, 0,0,0,0x1f,0x23,0x28,0x2a,0x2c};*/ static u2Byte N_THRESHOLD_HIGH[RATESIZE] = {4,4,8,16, 24,36,48,72,96,144,192,216, 60,80,100,160,240,400,560,640, 300,320,480,720,1000,1200,1600,2000}; static u2Byte N_THRESHOLD_LOW[RATESIZE] = {2,2,4,8, 12,18,24,36,48,72,96,108, 30,40,50,80,120,200,280,320, 150,160,240,360,500,600,800,1000}; static u1Byte TRYING_NECESSARY[RATESIZE] = {2,2,2,2, 2,2,3,3,4,4,5,7, 4,4,7,10,10,12,12,18, 5,7,7,8,11,18,36,60}; // 0329 // 1207 #if 0 static u1Byte POOL_RETRY_TH[RATESIZE] = {30,30,30,30, 30,30,25,25,20,15,15,10, 30,25,25,20,15,10,10,10, 30,25,25,20,15,10,10,10}; #endif static u1Byte DROPING_NECESSARY[RATESIZE] = {1,1,1,1, 1,2,3,4,5,6,7,8, 1,2,3,4,5,6,7,8, 5,6,7,8,9,10,11,12}; static u4Byte INIT_RATE_FALLBACK_TABLE[16]={0x0f8ff015, // 0: 40M BGN mode 0x0f8ff010, // 1: 40M GN mode 0x0f8ff005, // 2: BN mode/ 40M BGN mode 0x0f8ff000, // 3: N mode 0x00000ff5, // 4: BG mode 0x00000ff0, // 5: G mode 0x0000000d, // 6: B mode 0, // 7: 0, // 8: 0, // 9: 0, // 10: 0, // 11: 0, // 12: 0, // 13: 0, // 14: 0, // 15: }; static u1Byte PendingForRateUpFail[5]={2,10,24,40,60}; static u2Byte DynamicTxRPTTiming[6]={0x186a, 0x30d4, 0x493e, 0x61a8, 0x7a12 ,0x927c}; // 200ms-1200ms // End Rate adaptive parameters static void odm_SetTxRPTTiming_8188E( IN PDM_ODM_T pDM_Odm, IN PODM_RA_INFO_T pRaInfo, IN u1Byte extend ) { u1Byte idx = 0; for(idx=0; idx<5; idx++) if(DynamicTxRPTTiming[idx] == pRaInfo->RptTime) break; if (extend==0) // back to default timing idx=0; //200ms else if (extend==1) {// increase the timing idx+=1; if (idx>5) idx=5; } else if (extend==2) {// decrease the timing if(idx!=0) idx-=1; } pRaInfo->RptTime=DynamicTxRPTTiming[idx]; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("pRaInfo->RptTime=0x%x\n", pRaInfo->RptTime)); } static int odm_RateDown_8188E( IN PDM_ODM_T pDM_Odm, IN PODM_RA_INFO_T pRaInfo ) { u1Byte RateID, LowestRate, HighestRate; u1Byte i; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("=====>odm_RateDown_8188E()\n")); if(NULL == pRaInfo) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("odm_RateDown_8188E(): pRaInfo is NULL\n")); return -1; } RateID = pRaInfo->PreRate; LowestRate = pRaInfo->LowestRate; HighestRate = pRaInfo->HighestRate; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" RateID=%d LowestRate=%d HighestRate=%d RateSGI=%d\n", RateID, LowestRate, HighestRate, pRaInfo->RateSGI)); if (RateID > HighestRate) { RateID=HighestRate; } else if(pRaInfo->RateSGI) { pRaInfo->RateSGI=0; } else if (RateID > LowestRate) { if (RateID > 0) { for (i=RateID-1; i>LowestRate;i--) { if (pRaInfo->RAUseRate & BIT(i)) { RateID=i; goto RateDownFinish; } } } } else if (RateID <= LowestRate) { RateID = LowestRate; } RateDownFinish: if (pRaInfo->RAWaitingCounter==1){ pRaInfo->RAWaitingCounter+=1; pRaInfo->RAPendingCounter+=1; } else if(pRaInfo->RAWaitingCounter==0){ } else{ pRaInfo->RAWaitingCounter=0; pRaInfo->RAPendingCounter=0; } if(pRaInfo->RAPendingCounter>=4) pRaInfo->RAPendingCounter=4; pRaInfo->DecisionRate=RateID; odm_SetTxRPTTiming_8188E(pDM_Odm,pRaInfo, 2); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("Rate down, RPT Timing default\n")); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("RAWaitingCounter %d, RAPendingCounter %d",pRaInfo->RAWaitingCounter,pRaInfo->RAPendingCounter)); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("Rate down to RateID %d RateSGI %d\n", RateID, pRaInfo->RateSGI)); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("<=====odm_RateDown_8188E() \n")); return 0; } static int odm_RateUp_8188E( IN PDM_ODM_T pDM_Odm, IN PODM_RA_INFO_T pRaInfo ) { u1Byte RateID, HighestRate; u1Byte i; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("=====>odm_RateUp_8188E() \n")); if(NULL == pRaInfo) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("odm_RateUp_8188E(): pRaInfo is NULL\n")); return -1; } RateID = pRaInfo->PreRate; HighestRate = pRaInfo->HighestRate; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" RateID=%d HighestRate=%d\n", RateID, HighestRate)); if (pRaInfo->RAWaitingCounter==1){ pRaInfo->RAWaitingCounter=0; pRaInfo->RAPendingCounter=0; } else if (pRaInfo->RAWaitingCounter>1){ pRaInfo->PreRssiStaRA=pRaInfo->RssiStaRA; goto RateUpfinish; } odm_SetTxRPTTiming_8188E(pDM_Odm,pRaInfo, 0); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("odm_RateUp_8188E():Decrease RPT Timing\n")); if (RateID < HighestRate) { for (i=RateID+1; i<=HighestRate; i++) { if (pRaInfo->RAUseRate & BIT(i)) { RateID=i; goto RateUpfinish; } } } else if(RateID == HighestRate) { if (pRaInfo->SGIEnable && (pRaInfo->RateSGI != 1)) pRaInfo->RateSGI = 1; else if((pRaInfo->SGIEnable) !=1 ) pRaInfo->RateSGI = 0; } else //if((sta_info_ra->Decision_rate) > (sta_info_ra->Highest_rate)) { RateID = HighestRate; } RateUpfinish: //if(pRaInfo->RAWaitingCounter==10) if(pRaInfo->RAWaitingCounter==(4+PendingForRateUpFail[pRaInfo->RAPendingCounter])) pRaInfo->RAWaitingCounter=0; else pRaInfo->RAWaitingCounter++; pRaInfo->DecisionRate=RateID; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("Rate up to RateID %d\n", RateID)); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("RAWaitingCounter %d, RAPendingCounter %d",pRaInfo->RAWaitingCounter,pRaInfo->RAPendingCounter)); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("<=====odm_RateUp_8188E() \n")); return 0; } static void odm_ResetRaCounter_8188E( IN PODM_RA_INFO_T pRaInfo){ u1Byte RateID; RateID=pRaInfo->DecisionRate; pRaInfo->NscUp=(N_THRESHOLD_HIGH[RateID]+N_THRESHOLD_LOW[RateID])>>1; pRaInfo->NscDown=(N_THRESHOLD_HIGH[RateID]+N_THRESHOLD_LOW[RateID])>>1; } static void odm_RateDecision_8188E( IN PDM_ODM_T pDM_Odm, IN PODM_RA_INFO_T pRaInfo ) { u1Byte RateID = 0, RtyPtID = 0, PenaltyID1 = 0, PenaltyID2 = 0; //u4Byte pool_retry; static u1Byte DynamicTxRPTTimingCounter=0; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("=====>odm_RateDecision_8188E() \n")); if (pRaInfo->Active && (pRaInfo->TOTAL > 0)) // STA used and data packet exits { if ( (pRaInfo->RssiStaRA<(pRaInfo->PreRssiStaRA-3))|| (pRaInfo->RssiStaRA>(pRaInfo->PreRssiStaRA+3))){ pRaInfo->RAWaitingCounter=0; pRaInfo->RAPendingCounter=0; } // Start RA decision if (pRaInfo->PreRate > pRaInfo->HighestRate) RateID = pRaInfo->HighestRate; else RateID = pRaInfo->PreRate; if (pRaInfo->RssiStaRA > RSSI_THRESHOLD[RateID]) RtyPtID=0; else RtyPtID=1; PenaltyID1 = RETRY_PENALTY_IDX[RtyPtID][RateID]; //TODO by page ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" NscDown init is %d\n", pRaInfo->NscDown)); //pool_retry=pRaInfo->RTY[2]+pRaInfo->RTY[3]+pRaInfo->RTY[4]+pRaInfo->DROP; pRaInfo->NscDown += pRaInfo->RTY[0] * RETRY_PENALTY[PenaltyID1][0]; pRaInfo->NscDown += pRaInfo->RTY[1] * RETRY_PENALTY[PenaltyID1][1]; pRaInfo->NscDown += pRaInfo->RTY[2] * RETRY_PENALTY[PenaltyID1][2]; pRaInfo->NscDown += pRaInfo->RTY[3] * RETRY_PENALTY[PenaltyID1][3]; pRaInfo->NscDown += pRaInfo->RTY[4] * RETRY_PENALTY[PenaltyID1][4]; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" NscDown is %d, total*penalty[5] is %d\n", pRaInfo->NscDown, (pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID1][5]))); if (pRaInfo->NscDown > (pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID1][5])) pRaInfo->NscDown -= pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID1][5]; else pRaInfo->NscDown=0; // rate up PenaltyID2 = RETRY_PENALTY_UP_IDX[RateID]; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" NscUp init is %d\n", pRaInfo->NscUp)); pRaInfo->NscUp += pRaInfo->RTY[0] * RETRY_PENALTY[PenaltyID2][0]; pRaInfo->NscUp += pRaInfo->RTY[1] * RETRY_PENALTY[PenaltyID2][1]; pRaInfo->NscUp += pRaInfo->RTY[2] * RETRY_PENALTY[PenaltyID2][2]; pRaInfo->NscUp += pRaInfo->RTY[3] * RETRY_PENALTY[PenaltyID2][3]; pRaInfo->NscUp += pRaInfo->RTY[4] * RETRY_PENALTY[PenaltyID2][4]; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("NscUp is %d, total*up[5] is %d\n", pRaInfo->NscUp, (pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID2][5]))); if (pRaInfo->NscUp > (pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID2][5])) pRaInfo->NscUp -= pRaInfo->TOTAL * RETRY_PENALTY[PenaltyID2][5]; else pRaInfo->NscUp = 0; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE|ODM_COMP_INIT, ODM_DBG_LOUD, (" RssiStaRa= %d RtyPtID=%d PenaltyID1=0x%x PenaltyID2=0x%x RateID=%d NscDown=%d NscUp=%d SGI=%d\n", pRaInfo->RssiStaRA,RtyPtID, PenaltyID1,PenaltyID2, RateID, pRaInfo->NscDown, pRaInfo->NscUp, pRaInfo->RateSGI)); if ((pRaInfo->NscDown < N_THRESHOLD_LOW[RateID]) ||(pRaInfo->DROP>DROPING_NECESSARY[RateID])) odm_RateDown_8188E(pDM_Odm,pRaInfo); //else if ((pRaInfo->NscUp > N_THRESHOLD_HIGH[RateID])&&(pool_retry<POOL_RETRY_TH[RateID])) else if (pRaInfo->NscUp > N_THRESHOLD_HIGH[RateID]) odm_RateUp_8188E(pDM_Odm,pRaInfo); if(pRaInfo->DecisionRate > pRaInfo->HighestRate) pRaInfo->DecisionRate = pRaInfo->HighestRate; if ((pRaInfo->DecisionRate)==(pRaInfo->PreRate)) DynamicTxRPTTimingCounter+=1; else DynamicTxRPTTimingCounter=0; if (DynamicTxRPTTimingCounter>=4) { odm_SetTxRPTTiming_8188E(pDM_Odm,pRaInfo, 1); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("<=====Rate don't change 4 times, Extend RPT Timing\n")); DynamicTxRPTTimingCounter=0; } pRaInfo->PreRate = pRaInfo->DecisionRate; //YJ,add,120120 odm_ResetRaCounter_8188E( pRaInfo); } ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("<=====odm_RateDecision_8188E() \n")); } static int odm_ARFBRefresh_8188E( IN PDM_ODM_T pDM_Odm, IN PODM_RA_INFO_T pRaInfo ) { // Wilson 2011/10/26 u4Byte MaskFromReg; s1Byte i; switch(pRaInfo->RateID){ case RATR_INX_WIRELESS_NGB: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x0f8ff015; break; case RATR_INX_WIRELESS_NG: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x0f8ff010; break; case RATR_INX_WIRELESS_NB: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x0f8ff005; break; case RATR_INX_WIRELESS_N: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x0f8ff000; break; case RATR_INX_WIRELESS_GB: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x00000ff5; break; case RATR_INX_WIRELESS_G: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x00000ff0; break; case RATR_INX_WIRELESS_B: pRaInfo->RAUseRate=(pRaInfo->RateMask)&0x0000000d; break; case 12: MaskFromReg=ODM_Read4Byte(pDM_Odm, REG_ARFR0); pRaInfo->RAUseRate=(pRaInfo->RateMask)&MaskFromReg; break; case 13: MaskFromReg=ODM_Read4Byte(pDM_Odm, REG_ARFR1); pRaInfo->RAUseRate=(pRaInfo->RateMask)&MaskFromReg; break; case 14: MaskFromReg=ODM_Read4Byte(pDM_Odm, REG_ARFR2); pRaInfo->RAUseRate=(pRaInfo->RateMask)&MaskFromReg; break; case 15: MaskFromReg=ODM_Read4Byte(pDM_Odm, REG_ARFR3); pRaInfo->RAUseRate=(pRaInfo->RateMask)&MaskFromReg; break; default: pRaInfo->RAUseRate=(pRaInfo->RateMask); break; } // Highest rate if (pRaInfo->RAUseRate){ for (i=RATESIZE;i>=0;i--) { if((pRaInfo->RAUseRate)&BIT(i)){ pRaInfo->HighestRate=i; break; } } } else{ pRaInfo->HighestRate=0; } // Lowest rate if (pRaInfo->RAUseRate){ for (i=0;i<RATESIZE;i++) { if((pRaInfo->RAUseRate)&BIT(i)) { pRaInfo->LowestRate=i; break; } } } else{ pRaInfo->LowestRate=0; } #if POWER_TRAINING_ACTIVE == 1 if (pRaInfo->HighestRate >0x13) pRaInfo->PTModeSS=3; else if(pRaInfo->HighestRate >0x0b) pRaInfo->PTModeSS=2; else if(pRaInfo->HighestRate >0x0b) pRaInfo->PTModeSS=1; else pRaInfo->PTModeSS=0; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("ODM_ARFBRefresh_8188E(): PTModeSS=%d\n", pRaInfo->PTModeSS)); #endif if(pRaInfo->DecisionRate > pRaInfo->HighestRate) pRaInfo->DecisionRate = pRaInfo->HighestRate; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("ODM_ARFBRefresh_8188E(): RateID=%d RateMask=%8.8x RAUseRate=%8.8x HighestRate=%d,DecisionRate=%d \n", pRaInfo->RateID, pRaInfo->RateMask, pRaInfo->RAUseRate, pRaInfo->HighestRate,pRaInfo->DecisionRate)); return 0; } #if POWER_TRAINING_ACTIVE == 1 static void odm_PTTryState_8188E( IN PODM_RA_INFO_T pRaInfo ) { pRaInfo->PTTryState=0; switch (pRaInfo->PTModeSS) { case 3: if (pRaInfo->DecisionRate>=0x19) pRaInfo->PTTryState=1; break; case 2: if (pRaInfo->DecisionRate>=0x11) pRaInfo->PTTryState=1; break; case 1: if (pRaInfo->DecisionRate>=0x0a) pRaInfo->PTTryState=1; break; case 0: if (pRaInfo->DecisionRate>=0x03) pRaInfo->PTTryState=1; break; default: pRaInfo->PTTryState=0; } if (pRaInfo->RssiStaRA<48) { pRaInfo->PTStage=0; } else if (pRaInfo->PTTryState==1) { if ((pRaInfo->PTStopCount>=10)||(pRaInfo->PTPreRssi>pRaInfo->RssiStaRA+5) ||(pRaInfo->PTPreRssi<pRaInfo->RssiStaRA-5)||(pRaInfo->DecisionRate!=pRaInfo->PTPreRate)) { if (pRaInfo->PTStage==0) pRaInfo->PTStage=1; else if(pRaInfo->PTStage==1) pRaInfo->PTStage=3; else pRaInfo->PTStage=5; pRaInfo->PTPreRssi=pRaInfo->RssiStaRA; pRaInfo->PTStopCount=0; } else{ pRaInfo->RAstage=0; pRaInfo->PTStopCount++; } } else{ pRaInfo->PTStage=0; pRaInfo->RAstage=0; } pRaInfo->PTPreRate=pRaInfo->DecisionRate; } static void odm_PTDecision_8188E( IN PODM_RA_INFO_T pRaInfo ) { u1Byte stage_BUF; u1Byte j; u1Byte temp_stage; u4Byte numsc; u4Byte num_total; u1Byte stage_id; stage_BUF=pRaInfo->PTStage; numsc = 0; num_total= pRaInfo->TOTAL* PT_PENALTY[5]; for(j=0;j<=4;j++) { numsc += pRaInfo->RTY[j] * PT_PENALTY[j]; if(numsc>num_total) break; } j=j>>1; temp_stage= (pRaInfo->PTStage +1)>>1; if (temp_stage>j) stage_id=temp_stage-j; else stage_id=0; pRaInfo->PTSmoothFactor=(pRaInfo->PTSmoothFactor>>1) + (pRaInfo->PTSmoothFactor>>2) + stage_id*16+2; if (pRaInfo->PTSmoothFactor>192) pRaInfo->PTSmoothFactor=192; stage_id =pRaInfo->PTSmoothFactor>>6; temp_stage=stage_id*2; if (temp_stage!=0) temp_stage-=1; if (pRaInfo->DROP>3) temp_stage=0; pRaInfo->PTStage=temp_stage; } #endif static VOID odm_RATxRPTTimerSetting( IN PDM_ODM_T pDM_Odm, IN u2Byte minRptTime ) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE,(" =====>odm_RATxRPTTimerSetting()\n")); if(pDM_Odm->CurrminRptTime != minRptTime){ ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, (" CurrminRptTime =0x%04x minRptTime=0x%04x\n", pDM_Odm->CurrminRptTime, minRptTime)); #if(DM_ODM_SUPPORT_TYPE & (ODM_MP|ODM_AP)) ODM_RA_Set_TxRPT_Time(pDM_Odm,minRptTime); #else rtw_rpt_timer_cfg_cmd(pDM_Odm->Adapter,minRptTime); #endif pDM_Odm->CurrminRptTime = minRptTime; } ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE,(" <=====odm_RATxRPTTimerSetting()\n")); } VOID ODM_RASupport_Init( IN PDM_ODM_T pDM_Odm ) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("=====>ODM_RASupport_Init()\n")); // 2012/02/14 MH Be noticed, the init must be after IC type is recognized!!!!! if (pDM_Odm->SupportICType == ODM_RTL8188E) pDM_Odm->RaSupport88E = TRUE; } int ODM_RAInfo_Init( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { PODM_RA_INFO_T pRaInfo = &pDM_Odm->RAInfo[MacID]; #if 1 u1Byte WirelessMode=0xFF; //invalid value u1Byte max_rate_idx = 0x13; //MCS7 if(pDM_Odm->pWirelessMode!=NULL){ WirelessMode=*(pDM_Odm->pWirelessMode); } if(WirelessMode != 0xFF ){ if(WirelessMode & ODM_WM_N24G) max_rate_idx = 0x13; else if(WirelessMode & ODM_WM_G) max_rate_idx = 0x0b; else if(WirelessMode & ODM_WM_B) max_rate_idx = 0x03; } //printk("%s ==>WirelessMode:0x%08x ,max_raid_idx:0x%02x\n ",__FUNCTION__,WirelessMode,max_rate_idx); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("ODM_RAInfo_Init(): WirelessMode:0x%08x ,max_raid_idx:0x%02x \n", WirelessMode,max_rate_idx)); pRaInfo->DecisionRate = max_rate_idx; pRaInfo->PreRate = max_rate_idx; pRaInfo->HighestRate=max_rate_idx; #else pRaInfo->DecisionRate = 0x13; pRaInfo->PreRate = 0x13; pRaInfo->HighestRate= 0x13; #endif pRaInfo->LowestRate=0; pRaInfo->RateID=0; pRaInfo->RateMask=0xffffffff; pRaInfo->RssiStaRA=0; pRaInfo->PreRssiStaRA=0; pRaInfo->SGIEnable=0; pRaInfo->RAUseRate=0xffffffff; pRaInfo->NscDown=(N_THRESHOLD_HIGH[0x13]+N_THRESHOLD_LOW[0x13])/2; pRaInfo->NscUp=(N_THRESHOLD_HIGH[0x13]+N_THRESHOLD_LOW[0x13])/2; pRaInfo->RateSGI=0; pRaInfo->Active=1; //Active is not used at present. by page, 110819 pRaInfo->RptTime = 0x927c; pRaInfo->DROP=0; pRaInfo->RTY[0]=0; pRaInfo->RTY[1]=0; pRaInfo->RTY[2]=0; pRaInfo->RTY[3]=0; pRaInfo->RTY[4]=0; pRaInfo->TOTAL=0; pRaInfo->RAWaitingCounter=0; pRaInfo->RAPendingCounter=0; #if POWER_TRAINING_ACTIVE == 1 pRaInfo->PTActive=1; // Active when this STA is use pRaInfo->PTTryState=0; pRaInfo->PTStage=5; // Need to fill into HW_PWR_STATUS pRaInfo->PTSmoothFactor=192; pRaInfo->PTStopCount=0; pRaInfo->PTPreRate=0; pRaInfo->PTPreRssi=0; pRaInfo->PTModeSS=0; pRaInfo->RAstage=0; #endif return 0; } int ODM_RAInfo_Init_all( IN PDM_ODM_T pDM_Odm ) { u1Byte MacID = 0; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("=====>\n")); pDM_Odm->CurrminRptTime = 0; for(MacID=0; MacID<ODM_ASSOCIATE_ENTRY_NUM; MacID++) ODM_RAInfo_Init(pDM_Odm,MacID); return 0; } u1Byte ODM_RA_GetShortGI_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { if((NULL == pDM_Odm) || (MacID >= ASSOCIATE_ENTRY_NUM)) return 0; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("MacID=%d SGI=%d\n", MacID, pDM_Odm->RAInfo[MacID].RateSGI)); return pDM_Odm->RAInfo[MacID].RateSGI; } u1Byte ODM_RA_GetDecisionRate_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { u1Byte DecisionRate = 0; if((NULL == pDM_Odm) || (MacID >= ASSOCIATE_ENTRY_NUM)) return 0; DecisionRate = (pDM_Odm->RAInfo[MacID].DecisionRate); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" MacID=%d DecisionRate=0x%x\n", MacID, DecisionRate)); return DecisionRate; } u1Byte ODM_RA_GetHwPwrStatus_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { u1Byte PTStage = 5; if((NULL == pDM_Odm) || (MacID >= ASSOCIATE_ENTRY_NUM)) return 0; PTStage = (pDM_Odm->RAInfo[MacID].PTStage); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, ("MacID=%d PTStage=0x%x\n", MacID, PTStage)); return PTStage; } VOID ODM_RA_UpdateRateInfo_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID, IN u1Byte RateID, IN u4Byte RateMask, IN u1Byte SGIEnable ) { PODM_RA_INFO_T pRaInfo = NULL; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("MacID=%d RateID=0x%x RateMask=0x%x SGIEnable=%d\n", MacID, RateID, RateMask, SGIEnable)); if((NULL == pDM_Odm) || (MacID >= ASSOCIATE_ENTRY_NUM)) return; pRaInfo = &(pDM_Odm->RAInfo[MacID]); pRaInfo->RateID = RateID; pRaInfo->RateMask = RateMask; pRaInfo->SGIEnable = SGIEnable; odm_ARFBRefresh_8188E(pDM_Odm, pRaInfo); } VOID ODM_RA_SetRSSI_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID, IN u1Byte Rssi ) { PODM_RA_INFO_T pRaInfo = NULL; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_TRACE, (" MacID=%d Rssi=%d\n", MacID, Rssi)); if((NULL == pDM_Odm) || (MacID >= ASSOCIATE_ENTRY_NUM)) return; pRaInfo = &(pDM_Odm->RAInfo[MacID]); pRaInfo->RssiStaRA = Rssi; } VOID ODM_RA_Set_TxRPT_Time( IN PDM_ODM_T pDM_Odm, IN u2Byte minRptTime ) { #if(DM_ODM_SUPPORT_TYPE & (ODM_AP)) if (minRptTime != 0xffff) #endif ODM_Write2Byte(pDM_Odm, REG_TX_RPT_TIME, minRptTime); } VOID ODM_RA_TxRPT2Handle_8188E( IN PDM_ODM_T pDM_Odm, IN pu1Byte TxRPT_Buf, IN u2Byte TxRPT_Len, IN u4Byte MacIDValidEntry0, IN u4Byte MacIDValidEntry1 ) { PODM_RA_INFO_T pRAInfo = NULL; u1Byte MacId = 0; pu1Byte pBuffer = NULL; u4Byte valid = 0, ItemNum = 0; u2Byte minRptTime = 0x927c; ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("=====>ODM_RA_TxRPT2Handle_8188E(): valid0=%d valid1=%d BufferLength=%d\n", MacIDValidEntry0, MacIDValidEntry1, TxRPT_Len)); ItemNum = TxRPT_Len >> 3; pBuffer = TxRPT_Buf; do { if(MacId >= ASSOCIATE_ENTRY_NUM) valid = 0; else if(MacId >= 32) valid = (1<<(MacId-32)) & MacIDValidEntry1; else valid = (1<<MacId) & MacIDValidEntry0; pRAInfo = &(pDM_Odm->RAInfo[MacId]); if(valid) { #if (DM_ODM_SUPPORT_TYPE & (ODM_MP|ODM_CE)) pRAInfo->RTY[0] = (u2Byte)GET_TX_REPORT_TYPE1_RERTY_0(pBuffer); pRAInfo->RTY[1] = (u2Byte)GET_TX_REPORT_TYPE1_RERTY_1(pBuffer); pRAInfo->RTY[2] = (u2Byte)GET_TX_REPORT_TYPE1_RERTY_2(pBuffer); pRAInfo->RTY[3] = (u2Byte)GET_TX_REPORT_TYPE1_RERTY_3(pBuffer); pRAInfo->RTY[4] = (u2Byte)GET_TX_REPORT_TYPE1_RERTY_4(pBuffer); pRAInfo->DROP = (u2Byte)GET_TX_REPORT_TYPE1_DROP_0(pBuffer); #else pRAInfo->RTY[0] = (unsigned short)(pBuffer[1] << 8 | pBuffer[0]); pRAInfo->RTY[1] = pBuffer[2]; pRAInfo->RTY[2] = pBuffer[3]; pRAInfo->RTY[3] = pBuffer[4]; pRAInfo->RTY[4] = pBuffer[5]; pRAInfo->DROP = pBuffer[6]; #endif pRAInfo->TOTAL = pRAInfo->RTY[0] + \ pRAInfo->RTY[1] + \ pRAInfo->RTY[2] + \ pRAInfo->RTY[3] + \ pRAInfo->RTY[4] + \ pRAInfo->DROP; if(pRAInfo->TOTAL != 0) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("macid=%d Total=%d R0=%d R1=%d R2=%d R3=%d R4=%d D0=%d valid0=%x valid1=%x\n", MacId, pRAInfo->TOTAL, pRAInfo->RTY[0], pRAInfo->RTY[1], pRAInfo->RTY[2], pRAInfo->RTY[3], pRAInfo->RTY[4], pRAInfo->DROP, MacIDValidEntry0 , MacIDValidEntry1)); #if POWER_TRAINING_ACTIVE == 1 if (pRAInfo->PTActive){ if(pRAInfo->RAstage<5){ odm_RateDecision_8188E(pDM_Odm,pRAInfo); } else if(pRAInfo->RAstage==5){ // Power training try state odm_PTTryState_8188E(pRAInfo); } else {// RAstage==6 odm_PTDecision_8188E(pRAInfo); } // Stage_RA counter if (pRAInfo->RAstage<=5) pRAInfo->RAstage++; else pRAInfo->RAstage=0; } else{ odm_RateDecision_8188E(pDM_Odm,pRAInfo); } #else odm_RateDecision_8188E(pDM_Odm, pRAInfo); #endif #if (DM_ODM_SUPPORT_TYPE & ODM_AP) extern void RTL8188E_SetStationTxRateInfo(PDM_ODM_T, PODM_RA_INFO_T, int); RTL8188E_SetStationTxRateInfo(pDM_Odm, pRAInfo, MacId); #ifdef DETECT_STA_EXISTANCE void RTL8188E_DetectSTAExistance(PDM_ODM_T pDM_Odm, PODM_RA_INFO_T pRAInfo, int MacID); RTL8188E_DetectSTAExistance(pDM_Odm, pRAInfo, MacId); #endif #endif ODM_RT_TRACE(pDM_Odm, ODM_COMP_INIT, ODM_DBG_LOUD, ("macid=%d R0=%d R1=%d R2=%d R3=%d R4=%d drop=%d valid0=%x RateID=%d SGI=%d\n", MacId, pRAInfo->RTY[0], pRAInfo->RTY[1], pRAInfo->RTY[2], pRAInfo->RTY[3], pRAInfo->RTY[4], pRAInfo->DROP, MacIDValidEntry0, pRAInfo->DecisionRate, pRAInfo->RateSGI)); } else ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, (" TOTAL=0!!!!\n")); } if(minRptTime > pRAInfo->RptTime) minRptTime = pRAInfo->RptTime; pBuffer += TX_RPT2_ITEM_SIZE; MacId++; }while(MacId < ItemNum); odm_RATxRPTTimerSetting(pDM_Odm,minRptTime); ODM_RT_TRACE(pDM_Odm,ODM_COMP_RATE_ADAPTIVE, ODM_DBG_LOUD, ("<===== ODM_RA_TxRPT2Handle_8188E()\n")); } #else static VOID odm_RATxRPTTimerSetting( IN PDM_ODM_T pDM_Odm, IN u2Byte minRptTime ) { return; } VOID ODM_RASupport_Init( IN PDM_ODM_T pDM_Odm ) { return; } int ODM_RAInfo_Init( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { return 0; } int ODM_RAInfo_Init_all( IN PDM_ODM_T pDM_Odm ) { return 0; } u1Byte ODM_RA_GetShortGI_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { return 0; } u1Byte ODM_RA_GetDecisionRate_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { return 0; } u1Byte ODM_RA_GetHwPwrStatus_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID ) { return 0; } VOID ODM_RA_UpdateRateInfo_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID, IN u1Byte RateID, IN u4Byte RateMask, IN u1Byte SGIEnable ) { return; } VOID ODM_RA_SetRSSI_8188E( IN PDM_ODM_T pDM_Odm, IN u1Byte MacID, IN u1Byte Rssi ) { return; } VOID ODM_RA_Set_TxRPT_Time( IN PDM_ODM_T pDM_Odm, IN u2Byte minRptTime ) { return; } VOID ODM_RA_TxRPT2Handle_8188E( IN PDM_ODM_T pDM_Odm, IN pu1Byte TxRPT_Buf, IN u2Byte TxRPT_Len, IN u4Byte MacIDValidEntry0, IN u4Byte MacIDValidEntry1 ) { return; } #endif
mozilla-b2g/kernel_flatfish
drivers/net/wireless/rtl8189es/hal/OUTSRC/rtl8188e/Hal8188ERateAdaptive.c
C
gpl-2.0
29,655
<?php // $Id: index.php,v 1.9.2.1 2008/05/02 04:07:29 dongsheng Exp $ /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // http://moodle.com // // // // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details: // // // // http://www.gnu.org/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// /// This is the main script for the complete XMLDB interface. From here /// all the actions supported will be launched. /// Add required XMLDB constants require_once('../../lib/xmldb/classes/XMLDBConstants.php'); /// Add required XMLDB action classes require_once('actions/XMLDBAction.class.php'); /// Add main XMLDB Generator require_once('../../lib/xmldb/classes/generators/XMLDBGenerator.class.php'); /// Add required XMLDB DB classes require_once('../../lib/xmldb/classes/XMLDBObject.class.php'); require_once('../../lib/xmldb/classes/XMLDBFile.class.php'); require_once('../../lib/xmldb/classes/XMLDBStructure.class.php'); require_once('../../lib/xmldb/classes/XMLDBTable.class.php'); require_once('../../lib/xmldb/classes/XMLDBField.class.php'); require_once('../../lib/xmldb/classes/XMLDBKey.class.php'); require_once('../../lib/xmldb/classes/XMLDBIndex.class.php'); require_once('../../lib/xmldb/classes/XMLDBStatement.class.php'); /// Add Moodle config script (this is loaded AFTER all the rest /// of classes because it starts the SESSION and classes to be /// stored there MUST be declared before in order to avoid /// getting "incomplete" objects require_once('../../config.php'); require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/ddllib.php'); // Install/upgrade related db functions admin_externalpage_setup('xmldbeditor'); /// Add other used libraries require_once($CFG->libdir . '/xmlize.php'); /// Add all the available SQL generators $generators = get_list_of_plugins('lib/xmldb/classes/generators'); foreach($generators as $generator) { require_once ('../../lib/xmldb/classes/generators/' . $generator . '/' . $generator . '.class.php'); } /// Handle session data global $XMLDB; /// The global SESSION object where everything will happen if (!isset($SESSION->xmldb)) { $SESSION->xmldb = new stdClass; } $XMLDB =& $SESSION->xmldb; /// Some previous checks if (! $site = get_site()) { redirect("$CFG->wwwroot/$CFG->admin/index.php"); } require_login(); require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); /// Body of the script, based on action, we delegate the work $action = optional_param ('action', 'main_view', PARAM_ALPHAEXT); /// Get the action path and invoke it $actionsroot = "$CFG->dirroot/$CFG->admin/xmldb/actions"; $actionclass = $action . '.class.php'; $actionpath = "$actionsroot/$action/$actionclass"; /// Load and invoke the proper action if (file_exists($actionpath) && is_readable($actionpath)) { require_once($actionpath); if ($xmldb_action = new $action) { //Invoke it $result = $xmldb_action->invoke(); if ($result) { /// Based on getDoesGenerate() switch ($xmldb_action->getDoesGenerate()) { case ACTION_GENERATE_HTML: /// Define $CFG->javascript to use our custom javascripts. /// Save the original one to add it from ours. Global too! :-( global $standard_javascript; $standard_javascript = $CFG->javascript; // Save original javascript file $CFG->javascript = $CFG->dirroot.'/'.$CFG->admin.'/xmldb/javascript.php'; //Use our custom javascript code /// Go with standard admin header admin_externalpage_print_header(); print_heading($xmldb_action->getTitle()); echo $xmldb_action->getOutput(); admin_externalpage_print_footer(); break; case ACTION_GENERATE_XML: header('Content-type: application/xhtml+xml'); echo $xmldb_action->getOutput(); break; } } else { error($xmldb_action->getError()); } } else { error ("Error: cannot instantiate class (actions/$action/$actionclass)"); } } else { error ("Error: wrong action specified ($action)"); } if ($xmldb_action->getDoesGenerate() != ACTION_GENERATE_XML) { if (debugging()) { ///print_object($XMLDB); } } ?>
damasiorafael/inppnet
cursos/admin/xmldb/index.php
PHP
gpl-2.0
6,222
#!/usr/bin/env python # # asn2wrs.py # ASN.1 to Wireshark dissector compiler # Copyright 2004 Tomas Kukosa # # 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, and/or sell copies of the Software, and to permit persons # to whom the Software is furnished to do so, provided that the above # copyright notice(s) and this permission notice appear in all copies of # the Software and that both the above copyright notice(s) and this # permission notice appear in supporting documentation. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT # OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL # INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Except as contained in this notice, the name of a copyright holder # shall not be used in advertising or otherwise to promote the sale, use # or other dealings in this Software without prior written authorization # of the copyright holder. """ASN.1 to Wireshark dissector compiler""" # # Compiler from ASN.1 specification to the Wireshark dissector # # Based on ASN.1 to Python compiler from Aaron S. Lav's PyZ3950 package licensed under the X Consortium license # http://www.pobox.com/~asl2/software/PyZ3950/ # (ASN.1 to Python compiler functionality is broken but not removed, it could be revived if necessary) # # It requires Dave Beazley's PLY parsing package licensed under the LGPL (tested with version 2.3) # http://www.dabeaz.com/ply/ # # # ITU-T Recommendation X.680 (07/2002), # Information technology - Abstract Syntax Notation One (ASN.1): Specification of basic notation # # ITU-T Recommendation X.681 (07/2002), # Information technology - Abstract Syntax Notation One (ASN.1): Information object specification # # ITU-T Recommendation X.682 (07/2002), # Information technology - Abstract Syntax Notation One (ASN.1): Constraint specification # # ITU-T Recommendation X.683 (07/2002), # Information technology - Abstract Syntax Notation One (ASN.1): Parameterization of ASN.1 specifications # # ITU-T Recommendation X.880 (07/1994), # Information technology - Remote Operations: Concepts, model and notation # import warnings import re import sys import os import os.path import time import getopt import traceback import lex import yacc if sys.version_info[0] < 3: from string import maketrans # OID name -> number conversion table oid_names = { '/itu-t' : 0, '/itu' : 0, '/ccitt' : 0, '/itu-r' : 0, '0/recommendation' : 0, '0.0/a' : 1, '0.0/b' : 2, '0.0/c' : 3, '0.0/d' : 4, '0.0/e' : 5, '0.0/f' : 6, '0.0/g' : 7, '0.0/h' : 8, '0.0/i' : 9, '0.0/j' : 10, '0.0/k' : 11, '0.0/l' : 12, '0.0/m' : 13, '0.0/n' : 14, '0.0/o' : 15, '0.0/p' : 16, '0.0/q' : 17, '0.0/r' : 18, '0.0/s' : 19, '0.0/t' : 20, '0.0/tseries' : 20, '0.0/u' : 21, '0.0/v' : 22, '0.0/w' : 23, '0.0/x' : 24, '0.0/y' : 25, '0.0/z' : 26, '0/question' : 1, '0/administration' : 2, '0/network-operator' : 3, '0/identified-organization' : 4, '0/r-recommendation' : 5, '0/data' : 9, '/iso' : 1, '1/standard' : 0, '1/registration-authority' : 1, '1/member-body' : 2, '1/identified-organization' : 3, '/joint-iso-itu-t' : 2, '/joint-iso-ccitt' : 2, '2/presentation' : 0, '2/asn1' : 1, '2/association-control' : 2, '2/reliable-transfer' : 3, '2/remote-operations' : 4, '2/ds' : 5, '2/directory' : 5, '2/mhs' : 6, '2/mhs-motis' : 6, '2/ccr' : 7, '2/oda' : 8, '2/ms' : 9, '2/osi-management' : 9, '2/transaction-processing' : 10, '2/dor' : 11, '2/distinguished-object-reference' : 11, '2/reference-data-transfe' : 12, '2/network-layer' : 13, '2/network-layer-management' : 13, '2/transport-layer' : 14, '2/transport-layer-management' : 14, '2/datalink-layer' : 15, '2/datalink-layer-managemen' : 15, '2/datalink-layer-management-information' : 15, '2/country' : 16, '2/registration-procedures' : 17, '2/registration-procedure' : 17, '2/physical-layer' : 18, '2/physical-layer-management' : 18, '2/mheg' : 19, '2/genericULS' : 20, '2/generic-upper-layers-security' : 20, '2/guls' : 20, '2/transport-layer-security-protocol' : 21, '2/network-layer-security-protocol' : 22, '2/international-organizations' : 23, '2/internationalRA' : 23, '2/sios' : 24, '2/uuid' : 25, '2/odp' : 26, '2/upu' : 40, } ITEM_FIELD_NAME = '_item' UNTAG_TYPE_NAME = '_untag' def asn2c(id): return id.replace('-', '_').replace('.', '_').replace('&', '_') input_file = None g_conform = None lexer = None in_oid = False class LexError(Exception): def __init__(self, tok, filename=None): self.tok = tok self.filename = filename self.msg = "Unexpected character %r" % (self.tok.value[0]) Exception.__init__(self, self.msg) def __repr__(self): return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg) __str__ = __repr__ class ParseError(Exception): def __init__(self, tok, filename=None): self.tok = tok self.filename = filename self.msg = "Unexpected token %s(%r)" % (self.tok.type, self.tok.value) Exception.__init__(self, self.msg) def __repr__(self): return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg) __str__ = __repr__ class DuplicateError(Exception): def __init__(self, type, ident): self.type = type self.ident = ident self.msg = "Duplicate %s for %s" % (self.type, self.ident) Exception.__init__(self, self.msg) def __repr__(self): return self.msg __str__ = __repr__ class CompError(Exception): def __init__(self, msg): self.msg = msg Exception.__init__(self, self.msg) def __repr__(self): return self.msg __str__ = __repr__ states = ( ('braceignore','exclusive'), ) precedence = ( ('left', 'UNION', 'BAR'), ('left', 'INTERSECTION', 'CIRCUMFLEX'), ) # 11 ASN.1 lexical items static_tokens = { r'::=' : 'ASSIGNMENT', # 11.16 Assignment lexical item r'\.\.' : 'RANGE', # 11.17 Range separator r'\.\.\.' : 'ELLIPSIS', # 11.18 Ellipsis r'\[\[' : 'LVERBRACK', # 11.19 Left version brackets r'\]\]' : 'RVERBRACK', # 11.20 Right version brackets # 11.26 Single character lexical items r'\{' : 'LBRACE', r'\}' : 'RBRACE', r'<' : 'LT', #r'>' : 'GT', r',' : 'COMMA', r'\.' : 'DOT', r'\(' : 'LPAREN', r'\)' : 'RPAREN', r'\[' : 'LBRACK', r'\]' : 'RBRACK', r'-' : 'MINUS', r':' : 'COLON', #r'=' : 'EQ', #r'"' : 'QUOTATION', #r"'" : 'APOSTROPHE', r';' : 'SEMICOLON', r'@' : 'AT', r'\!' : 'EXCLAMATION', r'\^' : 'CIRCUMFLEX', r'\&' : 'AMPERSAND', r'\|' : 'BAR' } # 11.27 Reserved words # all keys in reserved_words must start w/ upper case reserved_words = { 'ABSENT' : 'ABSENT', 'ABSTRACT-SYNTAX' : 'ABSTRACT_SYNTAX', 'ALL' : 'ALL', 'APPLICATION' : 'APPLICATION', 'AUTOMATIC' : 'AUTOMATIC', 'BEGIN' : 'BEGIN', 'BIT' : 'BIT', 'BOOLEAN' : 'BOOLEAN', 'BY' : 'BY', 'CHARACTER' : 'CHARACTER', 'CHOICE' : 'CHOICE', 'CLASS' : 'CLASS', 'COMPONENT' : 'COMPONENT', 'COMPONENTS' : 'COMPONENTS', 'CONSTRAINED' : 'CONSTRAINED', 'CONTAINING' : 'CONTAINING', 'DEFAULT' : 'DEFAULT', 'DEFINITIONS' : 'DEFINITIONS', 'EMBEDDED' : 'EMBEDDED', # 'ENCODED' : 'ENCODED', 'END' : 'END', 'ENUMERATED' : 'ENUMERATED', # 'EXCEPT' : 'EXCEPT', 'EXPLICIT' : 'EXPLICIT', 'EXPORTS' : 'EXPORTS', # 'EXTENSIBILITY' : 'EXTENSIBILITY', 'EXTERNAL' : 'EXTERNAL', 'FALSE' : 'FALSE', 'FROM' : 'FROM', 'GeneralizedTime' : 'GeneralizedTime', 'IDENTIFIER' : 'IDENTIFIER', 'IMPLICIT' : 'IMPLICIT', # 'IMPLIED' : 'IMPLIED', 'IMPORTS' : 'IMPORTS', 'INCLUDES' : 'INCLUDES', 'INSTANCE' : 'INSTANCE', 'INTEGER' : 'INTEGER', 'INTERSECTION' : 'INTERSECTION', 'MAX' : 'MAX', 'MIN' : 'MIN', 'MINUS-INFINITY' : 'MINUS_INFINITY', 'NULL' : 'NULL', 'OBJECT' : 'OBJECT', 'ObjectDescriptor' : 'ObjectDescriptor', 'OCTET' : 'OCTET', 'OF' : 'OF', 'OPTIONAL' : 'OPTIONAL', 'PATTERN' : 'PATTERN', 'PDV' : 'PDV', 'PLUS-INFINITY' : 'PLUS_INFINITY', 'PRESENT' : 'PRESENT', 'PRIVATE' : 'PRIVATE', 'REAL' : 'REAL', 'RELATIVE-OID' : 'RELATIVE_OID', 'SEQUENCE' : 'SEQUENCE', 'SET' : 'SET', 'SIZE' : 'SIZE', 'STRING' : 'STRING', 'SYNTAX' : 'SYNTAX', 'TAGS' : 'TAGS', 'TRUE' : 'TRUE', 'TYPE-IDENTIFIER' : 'TYPE_IDENTIFIER', 'UNION' : 'UNION', 'UNIQUE' : 'UNIQUE', 'UNIVERSAL' : 'UNIVERSAL', 'UTCTime' : 'UTCTime', 'WITH' : 'WITH', # X.208 obsolete but still used 'ANY' : 'ANY', 'DEFINED' : 'DEFINED', } for k in list(static_tokens.keys()): if static_tokens [k] == None: static_tokens [k] = k StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8', 'Teletex', 'T61', 'Videotex', 'Graphic', 'ISO646', 'Visible', 'General'] for s in StringTypes: reserved_words[s + 'String'] = s + 'String' tokens = list(static_tokens.values()) \ + list(reserved_words.values()) \ + ['BSTRING', 'HSTRING', 'QSTRING', 'UCASE_IDENT', 'LCASE_IDENT', 'LCASE_IDENT_ASSIGNED', 'CLASS_IDENT', 'REAL_NUMBER', 'NUMBER', 'PYQUOTE'] cur_mod = __import__ (__name__) # XXX blech! for (k, v) in list(static_tokens.items ()): cur_mod.__dict__['t_' + v] = k # 11.10 Binary strings def t_BSTRING (t): r"'[01]*'B" return t # 11.12 Hexadecimal strings def t_HSTRING (t): r"'[0-9A-Fa-f]*'H" return t def t_QSTRING (t): r'"([^"]|"")*"' return t def t_UCASE_IDENT (t): r"[A-Z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-' if (is_class_ident(t.value)): t.type = 'CLASS_IDENT' if (is_class_syntax(t.value)): t.type = t.value t.type = reserved_words.get(t.value, t.type) return t lcase_ident_assigned = {} def t_LCASE_IDENT (t): r"[a-z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-' if (not in_oid and (t.value in lcase_ident_assigned)): t.type = 'LCASE_IDENT_ASSIGNED' return t # 11.9 Real numbers def t_REAL_NUMBER (t): r"[0-9]+\.[0-9]*(?!\.)" return t # 11.8 Numbers def t_NUMBER (t): r"0|([1-9][0-9]*)" return t # 11.6 Comments pyquote_str = 'PYQUOTE' def t_COMMENT(t): r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)" if (t.value.find("\n") >= 0) : t.lexer.lineno += 1 if t.value[2:2+len (pyquote_str)] == pyquote_str: t.value = t.value[2+len(pyquote_str):] t.value = t.value.lstrip () t.type = pyquote_str return t return None t_ignore = " \t\r" def t_NEWLINE(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_error(t): global input_file raise LexError(t, input_file) # state 'braceignore' def t_braceignore_lbrace(t): r'\{' t.lexer.level +=1 def t_braceignore_rbrace(t): r'\}' t.lexer.level -=1 # If closing brace, return token if t.lexer.level == 0: t.type = 'RBRACE' return t def t_braceignore_QSTRING (t): r'"([^"]|"")*"' t.lexer.lineno += t.value.count("\n") def t_braceignore_COMMENT(t): r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)" if (t.value.find("\n") >= 0) : t.lexer.lineno += 1 def t_braceignore_nonspace(t): r'[^\s\{\}\"-]+|-(?!-)' t_braceignore_ignore = " \t\r" def t_braceignore_NEWLINE(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_braceignore_error(t): t.lexer.skip(1) class Ctx: def __init__ (self, defined_dict, indent = 0): self.tags_def = 'EXPLICIT' # default = explicit self.indent_lev = 0 self.assignments = {} self.dependencies = {} self.pyquotes = [] self.defined_dict = defined_dict self.name_ctr = 0 def spaces (self): return " " * (4 * self.indent_lev) def indent (self): self.indent_lev += 1 def outdent (self): self.indent_lev -= 1 assert (self.indent_lev >= 0) def register_assignment (self, ident, val, dependencies): if ident in self.assignments: raise DuplicateError("assignment", ident) if ident in self.defined_dict: raise Exception("cross-module duplicates for %s" % ident) self.defined_dict [ident] = 1 self.assignments[ident] = val self.dependencies [ident] = dependencies return "" # return "#%s depends on %s" % (ident, str (dependencies)) def register_pyquote (self, val): self.pyquotes.append (val) return "" def output_assignments (self): already_output = {} text_list = [] assign_keys = list(self.assignments.keys()) to_output_count = len (assign_keys) while True: any_output = 0 for (ident, val) in list(self.assignments.items ()): if ident in already_output: continue ok = 1 for d in self.dependencies [ident]: if ((d not in already_output) and (d in assign_keys)): ok = 0 if ok: text_list.append ("%s=%s" % (ident, self.assignments [ident])) already_output [ident] = 1 any_output = 1 to_output_count -= 1 assert (to_output_count >= 0) if not any_output: if to_output_count == 0: break # OK, we detected a cycle cycle_list = [] for ident in list(self.assignments.keys ()): if ident not in already_output: depend_list = [d for d in self.dependencies[ident] if d in assign_keys] cycle_list.append ("%s(%s)" % (ident, ",".join (depend_list))) text_list.append ("# Cycle XXX " + ",".join (cycle_list)) for (ident, val) in list(self.assignments.items ()): if ident not in already_output: text_list.append ("%s=%s" % (ident, self.assignments [ident])) break return "\n".join (text_list) def output_pyquotes (self): return "\n".join (self.pyquotes) def make_new_name (self): self.name_ctr += 1 return "_compiler_generated_name_%d" % (self.name_ctr,) #--- Flags for EXPORT, USER_DEFINED, NO_EMIT, MAKE_ENUM ------------------------------- EF_TYPE = 0x0001 EF_VALS = 0x0002 EF_ENUM = 0x0004 EF_WS_DLL = 0x0010 # exported from shared library EF_EXTERN = 0x0020 EF_NO_PROT = 0x0040 EF_NO_TYPE = 0x0080 EF_UCASE = 0x0100 EF_TABLE = 0x0400 EF_DEFINE = 0x0800 EF_MODULE = 0x1000 #--- common dependency computation --- # Input : list of items # dictionary with lists of dependency # # # Output : list of two outputs: # [0] list of items in dependency # [1] list of cycle dependency cycles def dependency_compute(items, dependency, map_fn = lambda t: t, ignore_fn = lambda t: False): item_ord = [] item_cyc = [] x = {} # already emitted #print '# Dependency computation' for t in items: if map_fn(t) in x: #print 'Continue: %s : %s' % (t, (map_fn(t)) continue stack = [t] stackx = {t : dependency.get(t, [])[:]} #print 'Push: %s : %s' % (t, str(stackx[t])) while stack: if stackx[stack[-1]]: # has dependencies d = stackx[stack[-1]].pop(0) if map_fn(d) in x or ignore_fn(d): continue if d in stackx: # cyclic dependency c = stack[:] c.reverse() c = [d] + c[0:c.index(d)+1] c.reverse() item_cyc.append(c) #print 'Cyclic: %s ' % (' -> '.join(c)) continue stack.append(d) stackx[d] = dependency.get(d, [])[:] #print 'Push: %s : %s' % (d, str(stackx[d])) else: #print 'Pop: %s' % (stack[-1]) del stackx[stack[-1]] e = map_fn(stack.pop()) if e in x: continue #print 'Add: %s' % (e) item_ord.append(e) x[e] = True return (item_ord, item_cyc) # Given a filename, return a relative path from epan/dissectors def rel_dissector_path(filename): path_parts = os.path.abspath(filename).split(os.sep) while (len(path_parts) > 3 and path_parts[0] != 'asn1'): path_parts.pop(0) path_parts.insert(0, '..') path_parts.insert(0, '..') return '/'.join(path_parts) #--- EthCtx ------------------------------------------------------------------- class EthCtx: def __init__(self, conform, output, indent = 0): self.conform = conform self.output = output self.conform.ectx = self self.output.ectx = self self.encoding = 'per' self.aligned = False self.default_oid_variant = '' self.default_opentype_variant = '' self.default_containing_variant = '_pdu_new' self.default_embedded_pdv_cb = None self.default_external_type_cb = None self.remove_prefix = None self.srcdir = None self.emitted_pdu = {} self.module = {} self.module_ord = [] self.all_type_attr = {} self.all_tags = {} self.all_vals = {} def encp(self): # encoding protocol encp = self.encoding return encp # Encoding def Per(self): return self.encoding == 'per' def Ber(self): return self.encoding == 'ber' def Aligned(self): return self.aligned def Unaligned(self): return not self.aligned def NeedTags(self): return self.tag_opt or self.Ber() def NAPI(self): return False # disable planned features def Module(self): # current module name return self.modules[-1][0] def groups(self): return self.group_by_prot or (self.conform.last_group > 0) def dbg(self, d): if (self.dbgopt.find(d) >= 0): return True else: return False def value_max(self, a, b): if (a == 'MAX') or (b == 'MAX'): return 'MAX'; if a == 'MIN': return b; if b == 'MIN': return a; try: if (int(a) > int(b)): return a else: return b except (ValueError, TypeError): pass return "MAX((%s),(%s))" % (a, b) def value_min(self, a, b): if (a == 'MIN') or (b == 'MIN'): return 'MIN'; if a == 'MAX': return b; if b == 'MAX': return a; try: if (int(a) < int(b)): return a else: return b except (ValueError, TypeError): pass return "MIN((%s),(%s))" % (a, b) def value_get_eth(self, val): if isinstance(val, Value): return val.to_str(self) ethname = val if val in self.value: ethname = self.value[val]['ethname'] return ethname def value_get_val(self, nm): val = asn2c(nm) if nm in self.value: if self.value[nm]['import']: v = self.get_val_from_all(nm, self.value[nm]['import']) if v is None: msg = 'Need value of imported value identifier %s from %s (%s)' % (nm, self.value[nm]['import'], self.value[nm]['proto']) warnings.warn_explicit(msg, UserWarning, '', 0) else: val = v else: val = self.value[nm]['value'] if isinstance (val, Value): val = val.to_str(self) else: msg = 'Need value of unknown value identifier %s' % (nm) warnings.warn_explicit(msg, UserWarning, '', 0) return val def eth_get_type_attr(self, type): #print "eth_get_type_attr(%s)" % (type) types = [type] while (not self.type[type]['import']): val = self.type[type]['val'] #print val ttype = type while (val.type == 'TaggedType'): val = val.val ttype += '/' + UNTAG_TYPE_NAME if (val.type != 'Type_Ref'): if (type != ttype): types.append(ttype) break type = val.val types.append(type) attr = {} #print " ", types while len(types): t = types.pop() if (self.type[t]['import']): attr.update(self.type[t]['attr']) attr.update(self.eth_get_type_attr_from_all(t, self.type[t]['import'])) elif (self.type[t]['val'].type == 'SelectionType'): val = self.type[t]['val'] (ftype, display) = val.eth_ftype(self) attr.update({ 'TYPE' : ftype, 'DISPLAY' : display, 'STRINGS' : val.eth_strings(), 'BITMASK' : '0' }); else: attr.update(self.type[t]['attr']) attr.update(self.eth_type[self.type[t]['ethname']]['attr']) #print " ", attr return attr def eth_get_type_attr_from_all(self, type, module): attr = {} if module in self.all_type_attr and type in self.all_type_attr[module]: attr = self.all_type_attr[module][type] return attr def get_ttag_from_all(self, type, module): ttag = None if module in self.all_tags and type in self.all_tags[module]: ttag = self.all_tags[module][type] return ttag def get_val_from_all(self, nm, module): val = None if module in self.all_vals and nm in self.all_vals[module]: val = self.all_vals[module][nm] return val def get_obj_repr(self, ident, flds=[], not_flds=[]): def set_type_fn(cls, field, fnfield): obj[fnfield + '_fn'] = 'NULL' obj[fnfield + '_pdu'] = 'NULL' if field in val and isinstance(val[field], Type_Ref): p = val[field].eth_type_default_pars(self, '') obj[fnfield + '_fn'] = p['TYPE_REF_FN'] obj[fnfield + '_fn'] = obj[fnfield + '_fn'] % p # one iteration if (self.conform.check_item('PDU', cls + '.' + field)): obj[fnfield + '_pdu'] = 'dissect_' + self.field[val[field].val]['ethname'] return # end of get_type_fn() obj = { '_name' : ident, '_ident' : asn2c(ident)} obj['_class'] = self.oassign[ident].cls obj['_module'] = self.oassign[ident].module val = self.oassign[ident].val for f in flds: if f not in val: return None for f in not_flds: if f in val: return None for f in list(val.keys()): if isinstance(val[f], Node): obj[f] = val[f].fld_obj_repr(self) else: obj[f] = str(val[f]) if (obj['_class'] == 'TYPE-IDENTIFIER') or (obj['_class'] == 'ABSTRACT-SYNTAX'): set_type_fn(obj['_class'], '&Type', '_type') if (obj['_class'] == 'OPERATION'): set_type_fn(obj['_class'], '&ArgumentType', '_argument') set_type_fn(obj['_class'], '&ResultType', '_result') if (obj['_class'] == 'ERROR'): set_type_fn(obj['_class'], '&ParameterType', '_parameter') return obj #--- eth_reg_module ----------------------------------------------------------- def eth_reg_module(self, module): #print "eth_reg_module(module='%s')" % (module) name = module.get_name() self.modules.append([name, module.get_proto(self)]) if name in self.module: raise DuplicateError("module", name) self.module[name] = [] self.module_ord.append(name) #--- eth_module_dep_add ------------------------------------------------------------ def eth_module_dep_add(self, module, dep): self.module[module].append(dep) #--- eth_exports ------------------------------------------------------------ def eth_exports(self, exports): self.exports_all = False if ((len(exports) == 1) and (exports[0] == 'ALL')): self.exports_all = True return for e in (exports): if isinstance(e, Type_Ref): self.exports.append(e.val) elif isinstance(e, Class_Ref): self.cexports.append(e.val) else: self.vexports.append(e) #--- eth_reg_assign --------------------------------------------------------- def eth_reg_assign(self, ident, val, virt=False): #print "eth_reg_assign(ident='%s')" % (ident) if ident in self.assign: raise DuplicateError("assignment", ident) self.assign[ident] = { 'val' : val , 'virt' : virt } self.assign_ord.append(ident) if (self.exports_all): self.exports.append(ident) #--- eth_reg_vassign -------------------------------------------------------- def eth_reg_vassign(self, vassign): ident = vassign.ident #print "eth_reg_vassign(ident='%s')" % (ident) if ident in self.vassign: raise DuplicateError("value assignment", ident) self.vassign[ident] = vassign self.vassign_ord.append(ident) if (self.exports_all): self.vexports.append(ident) #--- eth_reg_oassign -------------------------------------------------------- def eth_reg_oassign(self, oassign): ident = oassign.ident #print "eth_reg_oassign(ident='%s')" % (ident) if ident in self.oassign: if self.oassign[ident] == oassign: return # OK - already defined else: raise DuplicateError("information object assignment", ident) self.oassign[ident] = oassign self.oassign_ord.append(ident) self.oassign_cls.setdefault(oassign.cls, []).append(ident) #--- eth_import_type -------------------------------------------------------- def eth_import_type(self, ident, mod, proto): #print "eth_import_type(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto) if ident in self.type: #print "already defined '%s' import=%s, module=%s" % (ident, str(self.type[ident]['import']), self.type[ident].get('module', '-')) if not self.type[ident]['import'] and (self.type[ident]['module'] == mod) : return # OK - already defined elif self.type[ident]['import'] and (self.type[ident]['import'] == mod) : return # OK - already imported else: raise DuplicateError("type", ident) self.type[ident] = {'import' : mod, 'proto' : proto, 'ethname' : '' } self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE', 'STRINGS' : 'NULL', 'BITMASK' : '0' } mident = "$%s$%s" % (mod, ident) if (self.conform.check_item('TYPE_ATTR', mident)): self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', mident)) else: self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident)) if (self.conform.check_item('IMPORT_TAG', mident)): self.conform.copy_item('IMPORT_TAG', ident, mident) self.type_imp.append(ident) #--- dummy_import_type -------------------------------------------------------- def dummy_import_type(self, ident): # dummy imported if ident in self.type: raise Exception("Try to dummy import for existing type :%s" % ident) ethtype = asn2c(ident) self.type[ident] = {'import' : 'xxx', 'proto' : 'xxx', 'ethname' : ethtype } self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE', 'STRINGS' : 'NULL', 'BITMASK' : '0' } self.eth_type[ethtype] = { 'import' : 'xxx', 'proto' : 'xxx' , 'attr' : {}, 'ref' : []} print("Dummy imported: %s (%s)" % (ident, ethtype)) return ethtype #--- eth_import_class -------------------------------------------------------- def eth_import_class(self, ident, mod, proto): #print "eth_import_class(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto) if ident in self.objectclass: #print "already defined import=%s, module=%s" % (str(self.objectclass[ident]['import']), self.objectclass[ident]['module']) if not self.objectclass[ident]['import'] and (self.objectclass[ident]['module'] == mod) : return # OK - already defined elif self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == mod) : return # OK - already imported else: raise DuplicateError("object class", ident) self.objectclass[ident] = {'import' : mod, 'proto' : proto, 'ethname' : '' } self.objectclass_imp.append(ident) #--- eth_import_value ------------------------------------------------------- def eth_import_value(self, ident, mod, proto): #print "eth_import_value(ident='%s', mod='%s', prot='%s')" % (ident, mod, prot) if ident in self.value: #print "already defined import=%s, module=%s" % (str(self.value[ident]['import']), self.value[ident]['module']) if not self.value[ident]['import'] and (self.value[ident]['module'] == mod) : return # OK - already defined elif self.value[ident]['import'] and (self.value[ident]['import'] == mod) : return # OK - already imported else: raise DuplicateError("value", ident) self.value[ident] = {'import' : mod, 'proto' : proto, 'ethname' : ''} self.value_imp.append(ident) #--- eth_sel_req ------------------------------------------------------------ def eth_sel_req(self, typ, sel): key = typ + '.' + sel if key not in self.sel_req: self.sel_req[key] = { 'typ' : typ , 'sel' : sel} self.sel_req_ord.append(key) return key #--- eth_comp_req ------------------------------------------------------------ def eth_comp_req(self, type): self.comp_req_ord.append(type) #--- eth_dep_add ------------------------------------------------------------ def eth_dep_add(self, type, dep): if type not in self.type_dep: self.type_dep[type] = [] self.type_dep[type].append(dep) #--- eth_reg_type ----------------------------------------------------------- def eth_reg_type(self, ident, val): #print "eth_reg_type(ident='%s', type='%s')" % (ident, val.type) if ident in self.type: if self.type[ident]['import'] and (self.type[ident]['import'] == self.Module()) : # replace imported type del self.type[ident] self.type_imp.remove(ident) else: raise DuplicateError("type", ident) val.ident = ident self.type[ident] = { 'val' : val, 'import' : None } self.type[ident]['module'] = self.Module() self.type[ident]['proto'] = self.proto if len(ident.split('/')) > 1: self.type[ident]['tname'] = val.eth_tname() else: self.type[ident]['tname'] = asn2c(ident) self.type[ident]['export'] = self.conform.use_item('EXPORTS', ident) self.type[ident]['enum'] = self.conform.use_item('MAKE_ENUM', ident) self.type[ident]['vals_ext'] = self.conform.use_item('USE_VALS_EXT', ident) self.type[ident]['user_def'] = self.conform.use_item('USER_DEFINED', ident) self.type[ident]['no_emit'] = self.conform.use_item('NO_EMIT', ident) self.type[ident]['tname'] = self.conform.use_item('TYPE_RENAME', ident, val_dflt=self.type[ident]['tname']) self.type[ident]['ethname'] = '' if (val.type == 'Type_Ref') or (val.type == 'TaggedType') or (val.type == 'SelectionType') : self.type[ident]['attr'] = {} else: (ftype, display) = val.eth_ftype(self) self.type[ident]['attr'] = { 'TYPE' : ftype, 'DISPLAY' : display, 'STRINGS' : val.eth_strings(), 'BITMASK' : '0' } self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident)) self.type_ord.append(ident) # PDU if (self.conform.check_item('PDU', ident)): self.eth_reg_field(ident, ident, impl=val.HasImplicitTag(self), pdu=self.conform.use_item('PDU', ident)) #--- eth_reg_objectclass ---------------------------------------------------------- def eth_reg_objectclass(self, ident, val): #print "eth_reg_objectclass(ident='%s')" % (ident) if ident in self.objectclass: if self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == self.Module()) : # replace imported object class del self.objectclass[ident] self.objectclass_imp.remove(ident) elif isinstance(self.objectclass[ident]['val'], Class_Ref) and \ isinstance(val, Class_Ref) and \ (self.objectclass[ident]['val'].val == val.val): pass # ignore duplicated CLASS1 ::= CLASS2 else: raise DuplicateError("object class", ident) self.objectclass[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto } self.objectclass[ident]['val'] = val self.objectclass[ident]['export'] = self.conform.use_item('EXPORTS', ident) self.objectclass_ord.append(ident) #--- eth_reg_value ---------------------------------------------------------- def eth_reg_value(self, ident, type, value, ethname=None): #print "eth_reg_value(ident='%s')" % (ident) if ident in self.value: if self.value[ident]['import'] and (self.value[ident]['import'] == self.Module()) : # replace imported value del self.value[ident] self.value_imp.remove(ident) elif ethname: self.value[ident]['ethname'] = ethname return else: raise DuplicateError("value", ident) self.value[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto, 'type' : type, 'value' : value, 'no_emit' : False } self.value[ident]['export'] = self.conform.use_item('EXPORTS', ident) self.value[ident]['ethname'] = '' if (ethname): self.value[ident]['ethname'] = ethname self.value_ord.append(ident) #--- eth_reg_field ---------------------------------------------------------- def eth_reg_field(self, ident, type, idx='', parent=None, impl=False, pdu=None): #print "eth_reg_field(ident='%s', type='%s')" % (ident, type) if ident in self.field: if pdu and (type == self.field[ident]['type']): pass # OK already created PDU else: raise DuplicateError("field", ident) self.field[ident] = {'type' : type, 'idx' : idx, 'impl' : impl, 'pdu' : pdu, 'modified' : '', 'attr' : {} } name = ident.split('/')[-1] if self.remove_prefix and name.startswith(self.remove_prefix): name = name[len(self.remove_prefix):] if len(ident.split('/')) > 1 and name == ITEM_FIELD_NAME: # Sequence/Set of type if len(self.field[ident]['type'].split('/')) > 1: self.field[ident]['attr']['NAME'] = '"%s item"' % ident.split('/')[-2] self.field[ident]['attr']['ABBREV'] = asn2c(ident.split('/')[-2] + name) else: self.field[ident]['attr']['NAME'] = '"%s"' % self.field[ident]['type'] self.field[ident]['attr']['ABBREV'] = asn2c(self.field[ident]['type']) else: self.field[ident]['attr']['NAME'] = '"%s"' % name self.field[ident]['attr']['ABBREV'] = asn2c(name) if self.conform.check_item('FIELD_ATTR', ident): self.field[ident]['modified'] = '#' + str(id(self)) self.field[ident]['attr'].update(self.conform.use_item('FIELD_ATTR', ident)) if (pdu): self.field[ident]['pdu']['export'] = (self.conform.use_item('EXPORTS', ident + '_PDU') != 0) self.pdu_ord.append(ident) else: self.field_ord.append(ident) if parent: self.eth_dep_add(parent, type) def eth_dummy_eag_field_required(self): if (not self.dummy_eag_field): self.dummy_eag_field = 'eag_field' #--- eth_clean -------------------------------------------------------------- def eth_clean(self): self.proto = self.proto_opt; #--- ASN.1 tables ---------------- self.assign = {} self.assign_ord = [] self.field = {} self.pdu_ord = [] self.field_ord = [] self.type = {} self.type_ord = [] self.type_imp = [] self.type_dep = {} self.sel_req = {} self.sel_req_ord = [] self.comp_req_ord = [] self.vassign = {} self.vassign_ord = [] self.value = {} self.value_ord = [] self.value_imp = [] self.objectclass = {} self.objectclass_ord = [] self.objectclass_imp = [] self.oassign = {} self.oassign_ord = [] self.oassign_cls = {} #--- Modules ------------ self.modules = [] self.exports_all = False self.exports = [] self.cexports = [] self.vexports = [] #--- types ------------------- self.eth_type = {} self.eth_type_ord = [] self.eth_export_ord = [] self.eth_type_dupl = {} self.named_bit = [] #--- value dependencies ------------------- self.value_dep = {} #--- values ------------------- self.eth_value = {} self.eth_value_ord = [] #--- fields ------------------------- self.eth_hf = {} self.eth_hf_ord = [] self.eth_hfpdu_ord = [] self.eth_hf_dupl = {} self.dummy_eag_field = None #--- type dependencies ------------------- self.eth_type_ord1 = [] self.eth_dep_cycle = [] self.dep_cycle_eth_type = {} #--- value dependencies and export ------------------- self.eth_value_ord1 = [] self.eth_vexport_ord = [] #--- eth_prepare ------------------------------------------------------------ def eth_prepare(self): self.eproto = asn2c(self.proto) #--- dummy types/fields for PDU registration --- nm = 'NULL' if (self.conform.check_item('PDU', nm)): self.eth_reg_type('_dummy/'+nm, NullType()) self.eth_reg_field(nm, '_dummy/'+nm, pdu=self.conform.use_item('PDU', nm)) #--- required PDUs ---------------------------- for t in self.type_ord: pdu = self.type[t]['val'].eth_need_pdu(self) if not pdu: continue f = pdu['type'] pdu['reg'] = None pdu['hidden'] = False pdu['need_decl'] = True if f not in self.field: self.eth_reg_field(f, f, pdu=pdu) #--- values -> named values ------------------- t_for_update = {} for v in self.value_ord: if (self.value[v]['type'].type == 'Type_Ref') or self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v): if self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v): tnm = self.conform.use_item('ASSIGN_VALUE_TO_TYPE', v) else: tnm = self.value[v]['type'].val if tnm in self.type \ and not self.type[tnm]['import'] \ and (self.type[tnm]['val'].type == 'IntegerType'): self.type[tnm]['val'].add_named_value(v, self.value[v]['value']) self.value[v]['no_emit'] = True t_for_update[tnm] = True for t in list(t_for_update.keys()): self.type[t]['attr']['STRINGS'] = self.type[t]['val'].eth_strings() self.type[t]['attr'].update(self.conform.use_item('TYPE_ATTR', t)) #--- required components of --------------------------- #print "self.comp_req_ord = ", self.comp_req_ord for t in self.comp_req_ord: self.type[t]['val'].eth_reg_sub(t, self, components_available=True) #--- required selection types --------------------------- #print "self.sel_req_ord = ", self.sel_req_ord for t in self.sel_req_ord: tt = self.sel_req[t]['typ'] if tt not in self.type: self.dummy_import_type(t) elif self.type[tt]['import']: self.eth_import_type(t, self.type[tt]['import'], self.type[tt]['proto']) else: self.type[tt]['val'].sel_req(t, self.sel_req[t]['sel'], self) #--- types ------------------- for t in self.type_imp: # imported types nm = asn2c(t) self.eth_type[nm] = { 'import' : self.type[t]['import'], 'proto' : asn2c(self.type[t]['proto']), 'attr' : {}, 'ref' : []} self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm)) self.type[t]['ethname'] = nm for t in self.type_ord: # dummy import for missing type reference tp = self.type[t]['val'] #print "X : %s %s " % (t, tp.type) if isinstance(tp, TaggedType): #print "%s : %s " % (tp.type, t) tp = tp.val if isinstance(tp, Type_Ref): #print "%s : %s ::= %s " % (tp.type, t, tp.val) if tp.val not in self.type: self.dummy_import_type(tp.val) for t in self.type_ord: nm = self.type[t]['tname'] if ((nm.find('#') >= 0) or ((len(t.split('/'))>1) and (self.conform.get_fn_presence(t) or self.conform.check_item('FN_PARS', t) or self.conform.get_fn_presence('/'.join((t,ITEM_FIELD_NAME))) or self.conform.check_item('FN_PARS', '/'.join((t,ITEM_FIELD_NAME)))) and not self.conform.check_item('TYPE_RENAME', t))): if len(t.split('/')) == 2 and t.split('/')[1] == ITEM_FIELD_NAME: # Sequence of type at the 1st level nm = t.split('/')[0] + t.split('/')[1] elif t.split('/')[-1] == ITEM_FIELD_NAME: # Sequence/Set of type at next levels nm = 'T_' + self.conform.use_item('FIELD_RENAME', '/'.join(t.split('/')[0:-1]), val_dflt=t.split('/')[-2]) + t.split('/')[-1] elif t.split('/')[-1] == UNTAG_TYPE_NAME: # Untagged type nm = self.type['/'.join(t.split('/')[0:-1])]['ethname'] + '_U' else: nm = 'T_' + self.conform.use_item('FIELD_RENAME', t, val_dflt=t.split('/')[-1]) nm = asn2c(nm) if nm in self.eth_type: if nm in self.eth_type_dupl: self.eth_type_dupl[nm].append(t) else: self.eth_type_dupl[nm] = [self.eth_type[nm]['ref'][0], t] nm += '_%02d' % (len(self.eth_type_dupl[nm])-1) if nm in self.eth_type: self.eth_type[nm]['ref'].append(t) else: self.eth_type_ord.append(nm) self.eth_type[nm] = { 'import' : None, 'proto' : self.eproto, 'export' : 0, 'enum' : 0, 'vals_ext' : 0, 'user_def' : EF_TYPE|EF_VALS, 'no_emit' : EF_TYPE|EF_VALS, 'val' : self.type[t]['val'], 'attr' : {}, 'ref' : [t]} self.type[t]['ethname'] = nm if (not self.eth_type[nm]['export'] and self.type[t]['export']): # new export self.eth_export_ord.append(nm) self.eth_type[nm]['export'] |= self.type[t]['export'] self.eth_type[nm]['enum'] |= self.type[t]['enum'] self.eth_type[nm]['vals_ext'] |= self.type[t]['vals_ext'] self.eth_type[nm]['user_def'] &= self.type[t]['user_def'] self.eth_type[nm]['no_emit'] &= self.type[t]['no_emit'] if self.type[t]['attr'].get('STRINGS') == '$$': use_ext = self.type[t]['vals_ext'] if (use_ext): self.eth_type[nm]['attr']['STRINGS'] = '&%s_ext' % (self.eth_vals_nm(nm)) else: self.eth_type[nm]['attr']['STRINGS'] = 'VALS(%s)' % (self.eth_vals_nm(nm)) self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm)) for t in self.eth_type_ord: bits = self.eth_type[t]['val'].eth_named_bits() if (bits): for (val, id) in bits: self.named_bit.append({'name' : id, 'val' : val, 'ethname' : 'hf_%s_%s_%s' % (self.eproto, t, asn2c(id)), 'ftype' : 'FT_BOOLEAN', 'display' : '8', 'strings' : 'NULL', 'bitmask' : '0x'+('80','40','20','10','08','04','02','01')[val%8]}) if self.eth_type[t]['val'].eth_need_tree(): self.eth_type[t]['tree'] = "ett_%s_%s" % (self.eth_type[t]['proto'], t) else: self.eth_type[t]['tree'] = None #--- register values from enums ------------ for t in self.eth_type_ord: if (self.eth_type[t]['val'].eth_has_enum(t, self)): self.eth_type[t]['val'].reg_enum_vals(t, self) #--- value dependencies ------------------- for v in self.value_ord: if isinstance (self.value[v]['value'], Value): dep = self.value[v]['value'].get_dep() else: dep = self.value[v]['value'] if dep and dep in self.value: self.value_dep.setdefault(v, []).append(dep) #--- exports all necessary values for v in self.value_ord: if not self.value[v]['export']: continue deparr = self.value_dep.get(v, []) while deparr: d = deparr.pop() if not self.value[d]['import']: if not self.value[d]['export']: self.value[d]['export'] = EF_TYPE deparr.extend(self.value_dep.get(d, [])) #--- values ------------------- for v in self.value_imp: nm = asn2c(v) self.eth_value[nm] = { 'import' : self.value[v]['import'], 'proto' : asn2c(self.value[v]['proto']), 'ref' : []} self.value[v]['ethname'] = nm for v in self.value_ord: if (self.value[v]['ethname']): continue if (self.value[v]['no_emit']): continue nm = asn2c(v) self.eth_value[nm] = { 'import' : None, 'proto' : asn2c(self.value[v]['proto']), 'export' : self.value[v]['export'], 'ref' : [v] } self.eth_value[nm]['value'] = self.value[v]['value'] self.eth_value_ord.append(nm) self.value[v]['ethname'] = nm #--- fields ------------------------- for f in (self.pdu_ord + self.field_ord): if len(f.split('/')) > 1 and f.split('/')[-1] == ITEM_FIELD_NAME: # Sequence/Set of type nm = self.conform.use_item('FIELD_RENAME', '/'.join(f.split('/')[0:-1]), val_dflt=f.split('/')[-2]) + f.split('/')[-1] else: nm = f.split('/')[-1] nm = self.conform.use_item('FIELD_RENAME', f, val_dflt=nm) nm = asn2c(nm) if (self.field[f]['pdu']): nm += '_PDU' if (not self.merge_modules or self.field[f]['pdu']['export']): nm = self.eproto + '_' + nm t = self.field[f]['type'] if t in self.type: ethtype = self.type[t]['ethname'] else: # undefined type ethtype = self.dummy_import_type(t) ethtypemod = ethtype + self.field[f]['modified'] if nm in self.eth_hf: if nm in self.eth_hf_dupl: if ethtypemod in self.eth_hf_dupl[nm]: nm = self.eth_hf_dupl[nm][ethtypemod] self.eth_hf[nm]['ref'].append(f) self.field[f]['ethname'] = nm continue else: nmx = nm + ('_%02d' % (len(self.eth_hf_dupl[nm]))) self.eth_hf_dupl[nm][ethtype] = nmx nm = nmx else: if (self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified']) == ethtypemod: self.eth_hf[nm]['ref'].append(f) self.field[f]['ethname'] = nm continue else: nmx = nm + '_01' self.eth_hf_dupl[nm] = {self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified'] : nm, \ ethtypemod : nmx} nm = nmx if (self.field[f]['pdu']): self.eth_hfpdu_ord.append(nm) else: self.eth_hf_ord.append(nm) fullname = 'hf_%s_%s' % (self.eproto, nm) attr = self.eth_get_type_attr(self.field[f]['type']).copy() attr.update(self.field[f]['attr']) if (self.NAPI() and 'NAME' in attr): attr['NAME'] += self.field[f]['idx'] attr.update(self.conform.use_item('EFIELD_ATTR', nm)) use_vals_ext = self.eth_type[ethtype].get('vals_ext') if (use_vals_ext): attr['DISPLAY'] += '|BASE_EXT_STRING' self.eth_hf[nm] = {'fullname' : fullname, 'pdu' : self.field[f]['pdu'], 'ethtype' : ethtype, 'modified' : self.field[f]['modified'], 'attr' : attr.copy(), 'ref' : [f]} self.field[f]['ethname'] = nm if (self.dummy_eag_field): # Prepending "dummy_" avoids matching checkhf.pl. self.dummy_eag_field = 'dummy_hf_%s_%s' % (self.eproto, self.dummy_eag_field) #--- type dependencies ------------------- (self.eth_type_ord1, self.eth_dep_cycle) = dependency_compute(self.type_ord, self.type_dep, map_fn = lambda t: self.type[t]['ethname'], ignore_fn = lambda t: self.type[t]['import']) i = 0 while i < len(self.eth_dep_cycle): t = self.type[self.eth_dep_cycle[i][0]]['ethname'] self.dep_cycle_eth_type.setdefault(t, []).append(i) i += 1 #--- value dependencies and export ------------------- for v in self.eth_value_ord: if self.eth_value[v]['export']: self.eth_vexport_ord.append(v) else: self.eth_value_ord1.append(v) #--- export tags, values, ... --- for t in self.exports: if t not in self.type: continue if self.type[t]['import']: continue m = self.type[t]['module'] if not self.Per(): if m not in self.all_tags: self.all_tags[m] = {} self.all_tags[m][t] = self.type[t]['val'].GetTTag(self) if m not in self.all_type_attr: self.all_type_attr[m] = {} self.all_type_attr[m][t] = self.eth_get_type_attr(t).copy() for v in self.vexports: if v not in self.value: continue if self.value[v]['import']: continue m = self.value[v]['module'] if m not in self.all_vals: self.all_vals[m] = {} vv = self.value[v]['value'] if isinstance (vv, Value): vv = vv.to_str(self) self.all_vals[m][v] = vv #--- eth_vals_nm ------------------------------------------------------------ def eth_vals_nm(self, tname): out = "" if (not self.eth_type[tname]['export'] & EF_NO_PROT): out += "%s_" % (self.eproto) out += "%s_vals" % (tname) return out #--- eth_vals --------------------------------------------------------------- def eth_vals(self, tname, vals): out = "" has_enum = self.eth_type[tname]['enum'] & EF_ENUM use_ext = self.eth_type[tname]['vals_ext'] if (use_ext): vals.sort(key=lambda vals_entry: int(vals_entry[0])) if (not self.eth_type[tname]['export'] & EF_VALS): out += 'static ' if (self.eth_type[tname]['export'] & EF_VALS) and (self.eth_type[tname]['export'] & EF_TABLE): out += 'static ' out += "const value_string %s[] = {\n" % (self.eth_vals_nm(tname)) for (val, id) in vals: if (has_enum): vval = self.eth_enum_item(tname, id) else: vval = val out += ' { %3s, "%s" },\n' % (vval, id) out += " { 0, NULL }\n};\n" if (use_ext): out += "\nstatic value_string_ext %s_ext = VALUE_STRING_EXT_INIT(%s);\n" % (self.eth_vals_nm(tname), self.eth_vals_nm(tname)) return out #--- eth_enum_prefix ------------------------------------------------------------ def eth_enum_prefix(self, tname, type=False): out = "" if (self.eth_type[tname]['export'] & EF_ENUM): no_prot = self.eth_type[tname]['export'] & EF_NO_PROT else: no_prot = self.eth_type[tname]['enum'] & EF_NO_PROT if (not no_prot): out += self.eproto if ((not self.eth_type[tname]['enum'] & EF_NO_TYPE) or type): if (out): out += '_' out += tname if (self.eth_type[tname]['enum'] & EF_UCASE): out = out.upper() if (out): out += '_' return out #--- eth_enum_nm ------------------------------------------------------------ def eth_enum_nm(self, tname): out = self.eth_enum_prefix(tname, type=True) out += "enum" return out #--- eth_enum_item --------------------------------------------------------------- def eth_enum_item(self, tname, ident): out = self.eth_enum_prefix(tname) out += asn2c(ident) if (self.eth_type[tname]['enum'] & EF_UCASE): out = out.upper() return out #--- eth_enum --------------------------------------------------------------- def eth_enum(self, tname, vals): out = "" if (self.eth_type[tname]['enum'] & EF_DEFINE): out += "/* enumerated values for %s */\n" % (tname) for (val, id) in vals: out += '#define %-12s %3s\n' % (self.eth_enum_item(tname, id), val) else: out += "typedef enum _%s {\n" % (self.eth_enum_nm(tname)) first_line = 1 for (val, id) in vals: if (first_line == 1): first_line = 0 else: out += ",\n" out += ' %-12s = %3s' % (self.eth_enum_item(tname, id), val) out += "\n} %s;\n" % (self.eth_enum_nm(tname)) return out #--- eth_bits --------------------------------------------------------------- def eth_bits(self, tname, bits): out = "" out += "static const " out += "asn_namedbit %(TABLE)s[] = {\n" for (val, id) in bits: out += ' { %2d, &hf_%s_%s_%s, -1, -1, "%s", NULL },\n' % (val, self.eproto, tname, asn2c(id), id) out += " { 0, NULL, 0, 0, NULL, NULL }\n};\n" return out #--- eth_type_fn_h ---------------------------------------------------------- def eth_type_fn_h(self, tname): out = "" if (not self.eth_type[tname]['export'] & EF_TYPE): out += 'static ' out += "int " if (self.Ber()): out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname) elif (self.Per()): out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname) out += ";\n" return out #--- eth_fn_call ------------------------------------------------------------ def eth_fn_call(self, fname, ret=None, indent=2, par=None): out = indent * ' ' if (ret): if (ret == 'return'): out += 'return ' else: out += ret + ' = ' out += fname + '(' ind = len(out) for i in range(len(par)): if (i>0): out += ind * ' ' out += ', '.join(par[i]) if (i<(len(par)-1)): out += ',\n' out += ');\n' return out #--- eth_type_fn_hdr -------------------------------------------------------- def eth_type_fn_hdr(self, tname): out = '\n' if (not self.eth_type[tname]['export'] & EF_TYPE): out += 'static ' out += "int\n" if (self.Ber()): out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname) elif (self.Per()): out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname) #if self.conform.get_fn_presence(tname): # out += self.conform.get_fn_text(tname, 'FN_HDR') #el if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]): out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_HDR') return out #--- eth_type_fn_ftr -------------------------------------------------------- def eth_type_fn_ftr(self, tname): out = '\n' #if self.conform.get_fn_presence(tname): # out += self.conform.get_fn_text(tname, 'FN_FTR') #el if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]): out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_FTR') out += " return offset;\n" out += "}\n" return out #--- eth_type_fn_body ------------------------------------------------------- def eth_type_fn_body(self, tname, body, pars=None): out = body #if self.conform.get_fn_body_presence(tname): # out = self.conform.get_fn_text(tname, 'FN_BODY') #el if self.conform.get_fn_body_presence(self.eth_type[tname]['ref'][0]): out = self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_BODY') if pars: try: out = out % pars except (TypeError): pass return out #--- eth_out_pdu_decl ---------------------------------------------------------- def eth_out_pdu_decl(self, f): t = self.eth_hf[f]['ethtype'] is_new = self.eth_hf[f]['pdu']['new'] out = '' if (not self.eth_hf[f]['pdu']['export']): out += 'static ' if (is_new): out += 'int ' out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_);\n' else: out += 'void ' out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_);\n' return out #--- eth_output_hf ---------------------------------------------------------- def eth_output_hf (self): if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return fx = self.output.file_open('hf') for f in (self.eth_hfpdu_ord + self.eth_hf_ord): fx.write("%-50s/* %s */\n" % ("static int %s = -1; " % (self.eth_hf[f]['fullname']), self.eth_hf[f]['ethtype'])) if (self.named_bit): fx.write('/* named bits */\n') for nb in self.named_bit: fx.write("static int %s = -1;\n" % (nb['ethname'])) if (self.dummy_eag_field): fx.write("static int %s = -1; /* never registered */\n" % (self.dummy_eag_field)) self.output.file_close(fx) #--- eth_output_hf_arr ------------------------------------------------------ def eth_output_hf_arr (self): if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return fx = self.output.file_open('hfarr') for f in (self.eth_hfpdu_ord + self.eth_hf_ord): t = self.eth_hf[f]['ethtype'] if self.remove_prefix and t.startswith(self.remove_prefix): t = t[len(self.remove_prefix):] name=self.eth_hf[f]['attr']['NAME'] try: # Python < 3 trantab = maketrans("- ", "__") except: trantab = str.maketrans("- ", "__") name = name.translate(trantab) namelower = name.lower() tquoted_lower = '"' + t.lower() + '"' # Try to avoid giving blurbs that give no more info than the name if tquoted_lower == namelower or \ t == "NULL" or \ tquoted_lower.replace("t_", "") == namelower: blurb = 'NULL' else: blurb = '"%s"' % (t) attr = self.eth_hf[f]['attr'].copy() if attr['TYPE'] == 'FT_NONE': attr['ABBREV'] = '"%s.%s_element"' % (self.proto, attr['ABBREV']) else: attr['ABBREV'] = '"%s.%s"' % (self.proto, attr['ABBREV']) if 'BLURB' not in attr: attr['BLURB'] = blurb fx.write(' { &%s,\n' % (self.eth_hf[f]['fullname'])) fx.write(' { %(NAME)s, %(ABBREV)s,\n' % attr) fx.write(' %(TYPE)s, %(DISPLAY)s, %(STRINGS)s, %(BITMASK)s,\n' % attr) fx.write(' %(BLURB)s, HFILL }},\n' % attr) for nb in self.named_bit: fx.write(' { &%s,\n' % (nb['ethname'])) fx.write(' { "%s", "%s.%s",\n' % (nb['name'], self.proto, nb['name'])) fx.write(' %s, %s, %s, %s,\n' % (nb['ftype'], nb['display'], nb['strings'], nb['bitmask'])) fx.write(' NULL, HFILL }},\n') self.output.file_close(fx) #--- eth_output_ett --------------------------------------------------------- def eth_output_ett (self): fx = self.output.file_open('ett') fempty = True #fx.write("static gint ett_%s = -1;\n" % (self.eproto)) for t in self.eth_type_ord: if self.eth_type[t]['tree']: fx.write("static gint %s = -1;\n" % (self.eth_type[t]['tree'])) fempty = False self.output.file_close(fx, discard=fempty) #--- eth_output_ett_arr ----------------------------------------------------- def eth_output_ett_arr(self): fx = self.output.file_open('ettarr') fempty = True #fx.write(" &ett_%s,\n" % (self.eproto)) for t in self.eth_type_ord: if self.eth_type[t]['tree']: fx.write(" &%s,\n" % (self.eth_type[t]['tree'])) fempty = False self.output.file_close(fx, discard=fempty) #--- eth_output_export ------------------------------------------------------ def eth_output_export(self): fx = self.output.file_open('exp', ext='h') for t in self.eth_export_ord: # vals if (self.eth_type[t]['export'] & EF_ENUM) and self.eth_type[t]['val'].eth_has_enum(t, self): fx.write(self.eth_type[t]['val'].eth_type_enum(t, self)) if (self.eth_type[t]['export'] & EF_VALS) and self.eth_type[t]['val'].eth_has_vals(): if not self.eth_type[t]['export'] & EF_TABLE: if self.eth_type[t]['export'] & EF_WS_DLL: fx.write("WS_DLL_PUBLIC ") else: fx.write("extern ") fx.write("const value_string %s[];\n" % (self.eth_vals_nm(t))) else: fx.write(self.eth_type[t]['val'].eth_type_vals(t, self)) for t in self.eth_export_ord: # functions if (self.eth_type[t]['export'] & EF_TYPE): if self.eth_type[t]['export'] & EF_EXTERN: if self.eth_type[t]['export'] & EF_WS_DLL: fx.write("WS_DLL_PUBLIC ") else: fx.write("extern ") fx.write(self.eth_type_fn_h(t)) for f in self.eth_hfpdu_ord: # PDUs if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['export']): fx.write(self.eth_out_pdu_decl(f)) self.output.file_close(fx) #--- eth_output_expcnf ------------------------------------------------------ def eth_output_expcnf(self): fx = self.output.file_open('exp', ext='cnf') fx.write('#.MODULE\n') maxw = 0 for (m, p) in self.modules: if (len(m) > maxw): maxw = len(m) for (m, p) in self.modules: fx.write("%-*s %s\n" % (maxw, m, p)) fx.write('#.END\n\n') for cls in self.objectclass_ord: if self.objectclass[cls]['export']: cnm = cls if self.objectclass[cls]['export'] & EF_MODULE: cnm = "$%s$%s" % (self.objectclass[cls]['module'], cnm) fx.write('#.CLASS %s\n' % (cnm)) maxw = 2 for fld in self.objectclass[cls]['val'].fields: w = len(fld.fld_repr()[0]) if (w > maxw): maxw = w for fld in self.objectclass[cls]['val'].fields: repr = fld.fld_repr() fx.write('%-*s %s\n' % (maxw, repr[0], ' '.join(repr[1:]))) fx.write('#.END\n\n') if self.Ber(): fx.write('#.IMPORT_TAG\n') for t in self.eth_export_ord: # tags if (self.eth_type[t]['export'] & EF_TYPE): fx.write('%-24s ' % self.eth_type[t]['ref'][0]) fx.write('%s %s\n' % self.eth_type[t]['val'].GetTag(self)) fx.write('#.END\n\n') fx.write('#.TYPE_ATTR\n') for t in self.eth_export_ord: # attributes if (self.eth_type[t]['export'] & EF_TYPE): tnm = self.eth_type[t]['ref'][0] if self.eth_type[t]['export'] & EF_MODULE: tnm = "$%s$%s" % (self.type[tnm]['module'], tnm) fx.write('%-24s ' % tnm) attr = self.eth_get_type_attr(self.eth_type[t]['ref'][0]).copy() fx.write('TYPE = %(TYPE)-9s DISPLAY = %(DISPLAY)-9s STRINGS = %(STRINGS)s BITMASK = %(BITMASK)s\n' % attr) fx.write('#.END\n\n') self.output.file_close(fx, keep_anyway=True) #--- eth_output_val ------------------------------------------------------ def eth_output_val(self): fx = self.output.file_open('val', ext='h') for v in self.eth_value_ord1: vv = self.eth_value[v]['value'] if isinstance (vv, Value): vv = vv.to_str(self) fx.write("#define %-30s %s\n" % (v, vv)) for t in self.eth_type_ord1: if self.eth_type[t]['import']: continue if self.eth_type[t]['val'].eth_has_enum(t, self) and not (self.eth_type[t]['export'] & EF_ENUM): fx.write(self.eth_type[t]['val'].eth_type_enum(t, self)) self.output.file_close(fx) #--- eth_output_valexp ------------------------------------------------------ def eth_output_valexp(self): if (not len(self.eth_vexport_ord)): return fx = self.output.file_open('valexp', ext='h') for v in self.eth_vexport_ord: vv = self.eth_value[v]['value'] if isinstance (vv, Value): vv = vv.to_str(self) fx.write("#define %-30s %s\n" % (v, vv)) self.output.file_close(fx) #--- eth_output_types ------------------------------------------------------- def eth_output_types(self): def out_pdu(f): t = self.eth_hf[f]['ethtype'] is_new = self.eth_hf[f]['pdu']['new'] impl = 'FALSE' out = '' if (not self.eth_hf[f]['pdu']['export']): out += 'static ' if (is_new): out += 'int ' out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_) {\n' else: out += 'void ' out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_) {\n' if (is_new): out += ' int offset = 0;\n' off_par = 'offset' ret_par = 'offset' else: off_par = '0' ret_par = None if (self.Per()): if (self.Aligned()): aligned = 'TRUE' else: aligned = 'FALSE' out += " asn1_ctx_t asn1_ctx;\n" out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_PER', aligned, 'pinfo'),)) if (self.Ber()): out += " asn1_ctx_t asn1_ctx;\n" out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_BER', 'TRUE', 'pinfo'),)) par=((impl, 'tvb', off_par,'&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),) elif (self.Per()): par=(('tvb', off_par, '&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),) else: par=((),) out += self.eth_fn_call('dissect_%s_%s' % (self.eth_type[t]['proto'], t), ret=ret_par, par=par) if (self.Per() and is_new): out += ' offset += 7; offset >>= 3;\n' if (is_new): out += ' return offset;\n' out += '}\n' return out #end out_pdu() fx = self.output.file_open('fn') pos = fx.tell() if (len(self.eth_hfpdu_ord)): first_decl = True for f in self.eth_hfpdu_ord: if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['need_decl']): if first_decl: fx.write('/*--- PDUs declarations ---*/\n') first_decl = False fx.write(self.eth_out_pdu_decl(f)) if not first_decl: fx.write('\n') if self.eth_dep_cycle: fx.write('/*--- Cyclic dependencies ---*/\n\n') i = 0 while i < len(self.eth_dep_cycle): t = self.type[self.eth_dep_cycle[i][0]]['ethname'] if self.dep_cycle_eth_type[t][0] != i: i += 1; continue fx.write(''.join(['/* %s */\n' % ' -> '.join(self.eth_dep_cycle[i]) for i in self.dep_cycle_eth_type[t]])) fx.write(self.eth_type_fn_h(t)) fx.write('\n') i += 1 fx.write('\n') for t in self.eth_type_ord1: if self.eth_type[t]['import']: continue if self.eth_type[t]['val'].eth_has_vals(): if self.eth_type[t]['no_emit'] & EF_VALS: pass elif self.eth_type[t]['user_def'] & EF_VALS: fx.write("extern const value_string %s[];\n" % (self.eth_vals_nm(t))) elif (self.eth_type[t]['export'] & EF_VALS) and (self.eth_type[t]['export'] & EF_TABLE): pass else: fx.write(self.eth_type[t]['val'].eth_type_vals(t, self)) if self.eth_type[t]['no_emit'] & EF_TYPE: pass elif self.eth_type[t]['user_def'] & EF_TYPE: fx.write(self.eth_type_fn_h(t)) else: fx.write(self.eth_type[t]['val'].eth_type_fn(self.eth_type[t]['proto'], t, self)) fx.write('\n') if (len(self.eth_hfpdu_ord)): fx.write('/*--- PDUs ---*/\n\n') for f in self.eth_hfpdu_ord: if (self.eth_hf[f]['pdu']): if (f in self.emitted_pdu): fx.write(" /* %s already emitted */\n" % (f)) else: fx.write(out_pdu(f)) self.emitted_pdu[f] = True fx.write('\n') fempty = pos == fx.tell() self.output.file_close(fx, discard=fempty) #--- eth_output_dis_hnd ----------------------------------------------------- def eth_output_dis_hnd(self): fx = self.output.file_open('dis-hnd') fempty = True for f in self.eth_hfpdu_ord: pdu = self.eth_hf[f]['pdu'] if (pdu and pdu['reg'] and not pdu['hidden']): dis = self.proto if (pdu['reg'] != '.'): dis += '.' + pdu['reg'] fx.write('static dissector_handle_t %s_handle;\n' % (asn2c(dis))) fempty = False fx.write('\n') self.output.file_close(fx, discard=fempty) #--- eth_output_dis_reg ----------------------------------------------------- def eth_output_dis_reg(self): fx = self.output.file_open('dis-reg') fempty = True for f in self.eth_hfpdu_ord: pdu = self.eth_hf[f]['pdu'] if (pdu and pdu['reg']): new_prefix = '' if (pdu['new']): new_prefix = 'new_' dis = self.proto if (pdu['reg'] != '.'): dis += '.' + pdu['reg'] fx.write(' %sregister_dissector("%s", dissect_%s, proto_%s);\n' % (new_prefix, dis, f, self.eproto)) if (not pdu['hidden']): fx.write(' %s_handle = find_dissector("%s");\n' % (asn2c(dis), dis)) fempty = False fx.write('\n') self.output.file_close(fx, discard=fempty) #--- eth_output_dis_tab ----------------------------------------------------- def eth_output_dis_tab(self): fx = self.output.file_open('dis-tab') fempty = True for k in self.conform.get_order('REGISTER'): reg = self.conform.use_item('REGISTER', k) if reg['pdu'] not in self.field: continue f = self.field[reg['pdu']]['ethname'] pdu = self.eth_hf[f]['pdu'] new_prefix = '' if (pdu['new']): new_prefix = 'new_' if (reg['rtype'] in ('NUM', 'STR')): rstr = '' if (reg['rtype'] == 'STR'): rstr = 'string' else: rstr = 'uint' if (pdu['reg']): dis = self.proto if (pdu['reg'] != '.'): dis += '.' + pdu['reg'] if (not pdu['hidden']): hnd = '%s_handle' % (asn2c(dis)) else: hnd = 'find_dissector("%s")' % (dis) else: hnd = '%screate_dissector_handle(dissect_%s, proto_%s)' % (new_prefix, f, self.eproto) rport = self.value_get_eth(reg['rport']) fx.write(' dissector_add_%s("%s", %s, %s);\n' % (rstr, reg['rtable'], rport, hnd)) elif (reg['rtype'] in ('BER', 'PER')): roid = self.value_get_eth(reg['roid']) fx.write(' %sregister_%s_oid_dissector(%s, dissect_%s, proto_%s, %s);\n' % (new_prefix, reg['rtype'].lower(), roid, f, self.eproto, reg['roidname'])) fempty = False fx.write('\n') self.output.file_close(fx, discard=fempty) #--- eth_output_syn_reg ----------------------------------------------------- def eth_output_syn_reg(self): fx = self.output.file_open('syn-reg') fempty = True first_decl = True for k in self.conform.get_order('SYNTAX'): reg = self.conform.use_item('SYNTAX', k) if reg['pdu'] not in self.field: continue f = self.field[reg['pdu']]['ethname'] pdu = self.eth_hf[f]['pdu'] new_prefix = '' if (pdu['new']): new_prefix = 'new_' if first_decl: fx.write(' /*--- Syntax registrations ---*/\n') first_decl = False fx.write(' %sregister_ber_syntax_dissector(%s, proto_%s, dissect_%s_PDU);\n' % (new_prefix, k, self.eproto, reg['pdu'])); fempty=False self.output.file_close(fx, discard=fempty) #--- eth_output_tables ----------------------------------------------------- def eth_output_tables(self): for num in list(self.conform.report.keys()): fx = self.output.file_open('table' + num) for rep in self.conform.report[num]: self.eth_output_table(fx, rep) self.output.file_close(fx) #--- eth_output_table ----------------------------------------------------- def eth_output_table(self, fx, rep): if rep['type'] == 'HDR': fx.write('\n') if rep['var']: var = rep['var'] var_list = var.split('.', 1) cls = var_list[0] del var_list[0] flds = [] not_flds = [] sort_flds = [] for f in var_list: if f[0] == '!': not_flds.append(f[1:]) continue if f[0] == '#': flds.append(f[1:]) sort_flds.append(f) continue if f[0] == '@': flds.append(f[1:]) sort_flds.append(f[1:]) continue flds.append(f) objs = {} objs_ord = [] if (cls in self.oassign_cls): for ident in self.oassign_cls[cls]: obj = self.get_obj_repr(ident, flds, not_flds) if not obj: continue obj['_LOOP'] = var obj['_DICT'] = str(obj) objs[ident] = obj objs_ord.append(ident) if (sort_flds): # Sort identifiers according to the matching object in objs. # The order is determined by sort_flds, keys prefixed by a # '#' are compared numerically. def obj_key_fn(name): obj = objs[name] return list( int(obj[f[1:]]) if f[0] == '#' else obj[f] for f in sort_flds ) objs_ord.sort(key=obj_key_fn) for ident in objs_ord: obj = objs[ident] try: text = rep['text'] % obj except (KeyError): raise sys.exc_info()[0]("%s:%s invalid key %s for information object %s of %s" % (rep['fn'], rep['lineno'], sys.exc_info()[1], ident, var)) fx.write(text) else: fx.write("/* Unknown or empty loop list %s */\n" % (var)) else: fx.write(rep['text']) if rep['type'] == 'FTR': fx.write('\n') #--- dupl_report ----------------------------------------------------- def dupl_report(self): # types tmplist = sorted(self.eth_type_dupl.keys()) for t in tmplist: msg = "The same type names for different types. Explicit type renaming is recommended.\n" msg += t + "\n" for tt in self.eth_type_dupl[t]: msg += " %-20s %s\n" % (self.type[tt]['ethname'], tt) warnings.warn_explicit(msg, UserWarning, '', 0) # fields tmplist = list(self.eth_hf_dupl.keys()) tmplist.sort() for f in tmplist: msg = "The same field names for different types. Explicit field renaming is recommended.\n" msg += f + "\n" for tt in list(self.eth_hf_dupl[f].keys()): msg += " %-20s %-20s " % (self.eth_hf_dupl[f][tt], tt) msg += ", ".join(self.eth_hf[self.eth_hf_dupl[f][tt]]['ref']) msg += "\n" warnings.warn_explicit(msg, UserWarning, '', 0) #--- eth_do_output ------------------------------------------------------------ def eth_do_output(self): if self.dbg('a'): print("\n# Assignments") for a in self.assign_ord: v = ' ' if (self.assign[a]['virt']): v = '*' print(v, a) print("\n# Value assignments") for a in self.vassign_ord: print(' ', a) print("\n# Information object assignments") for a in self.oassign_ord: print(" %-12s (%s)" % (a, self.oassign[a].cls)) if self.dbg('t'): print("\n# Imported Types") print("%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")) print("-" * 100) for t in self.type_imp: print("%-40s %-24s %-24s" % (t, self.type[t]['import'], self.type[t]['proto'])) print("\n# Imported Values") print("%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")) print("-" * 100) for t in self.value_imp: print("%-40s %-24s %-24s" % (t, self.value[t]['import'], self.value[t]['proto'])) print("\n# Imported Object Classes") print("%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")) print("-" * 100) for t in self.objectclass_imp: print("%-40s %-24s %-24s" % (t, self.objectclass[t]['import'], self.objectclass[t]['proto'])) print("\n# Exported Types") print("%-31s %s" % ("Wireshark type", "Export Flag")) print("-" * 100) for t in self.eth_export_ord: print("%-31s 0x%02X" % (t, self.eth_type[t]['export'])) print("\n# Exported Values") print("%-40s %s" % ("Wireshark name", "Value")) print("-" * 100) for v in self.eth_vexport_ord: vv = self.eth_value[v]['value'] if isinstance (vv, Value): vv = vv.to_str(self) print("%-40s %s" % (v, vv)) print("\n# ASN.1 Object Classes") print("%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")) print("-" * 100) for t in self.objectclass_ord: print("%-40s " % (t)) print("\n# ASN.1 Types") print("%-49s %-24s %-24s" % ("ASN.1 unique name", "'tname'", "Wireshark type")) print("-" * 100) for t in self.type_ord: print("%-49s %-24s %-24s" % (t, self.type[t]['tname'], self.type[t]['ethname'])) print("\n# Wireshark Types") print("Wireshark type References (ASN.1 types)") print("-" * 100) for t in self.eth_type_ord: sys.stdout.write("%-31s %d" % (t, len(self.eth_type[t]['ref']))) print(', '.join(self.eth_type[t]['ref'])) print("\n# ASN.1 Values") print("%-40s %-18s %-20s %s" % ("ASN.1 unique name", "Type", "Value", "Wireshark value")) print("-" * 100) for v in self.value_ord: vv = self.value[v]['value'] if isinstance (vv, Value): vv = vv.to_str(self) print("%-40s %-18s %-20s %s" % (v, self.value[v]['type'].eth_tname(), vv, self.value[v]['ethname'])) #print "\n# Wireshark Values" #print "%-40s %s" % ("Wireshark name", "Value") #print "-" * 100 #for v in self.eth_value_ord: # vv = self.eth_value[v]['value'] # if isinstance (vv, Value): # vv = vv.to_str(self) # print "%-40s %s" % (v, vv) print("\n# ASN.1 Fields") print("ASN.1 unique name Wireshark name ASN.1 type") print("-" * 100) for f in (self.pdu_ord + self.field_ord): print("%-40s %-20s %s" % (f, self.field[f]['ethname'], self.field[f]['type'])) print("\n# Wireshark Fields") print("Wireshark name Wireshark type References (ASN.1 fields)") print("-" * 100) for f in (self.eth_hfpdu_ord + self.eth_hf_ord): sys.stdout.write("%-30s %-20s %s" % (f, self.eth_hf[f]['ethtype'], len(self.eth_hf[f]['ref']))) print(', '.join(self.eth_hf[f]['ref'])) #print "\n# Order after dependencies" #print '\n'.join(self.eth_type_ord1) print("\n# Cyclic dependencies") for c in self.eth_dep_cycle: print(' -> '.join(c)) self.dupl_report() self.output.outnm = self.outnm_opt if (not self.output.outnm): self.output.outnm = self.proto self.output.outnm = self.output.outnm.replace('.', '-') if not self.justexpcnf: self.eth_output_hf() self.eth_output_ett() self.eth_output_types() self.eth_output_hf_arr() self.eth_output_ett_arr() self.eth_output_export() self.eth_output_val() self.eth_output_valexp() self.eth_output_dis_hnd() self.eth_output_dis_reg() self.eth_output_dis_tab() self.eth_output_syn_reg() self.eth_output_tables() if self.expcnf: self.eth_output_expcnf() def dbg_modules(self): def print_mod(m): sys.stdout.write("%-30s " % (m)) dep = self.module[m][:] for i in range(len(dep)): if dep[i] not in self.module: dep[i] = '*' + dep[i] print(', '.join(dep)) # end of print_mod() (mod_ord, mod_cyc) = dependency_compute(self.module_ord, self.module, ignore_fn = lambda t: t not in self.module) print("\n# ASN.1 Moudules") print("Module name Dependency") print("-" * 100) new_ord = False for m in (self.module_ord): print_mod(m) new_ord = new_ord or (self.module_ord.index(m) != mod_ord.index(m)) if new_ord: print("\n# ASN.1 Moudules - in dependency order") print("Module name Dependency") print("-" * 100) for m in (mod_ord): print_mod(m) if mod_cyc: print("\nCyclic dependencies:") for i in (list(range(len(mod_cyc)))): print("%02d: %s" % (i + 1, str(mod_cyc[i]))) #--- EthCnf ------------------------------------------------------------------- class EthCnf: def __init__(self): self.ectx = None self.tblcfg = {} self.table = {} self.order = {} self.fn = {} self.report = {} self.suppress_line = False self.include_path = [] # Value name Default value Duplicity check Usage check self.tblcfg['EXPORTS'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['MAKE_ENUM'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['USE_VALS_EXT'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['PDU'] = { 'val_nm' : 'attr', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['SYNTAX'] = { 'val_nm' : 'attr', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['REGISTER'] = { 'val_nm' : 'attr', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['USER_DEFINED'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['NO_EMIT'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['MODULE'] = { 'val_nm' : 'proto', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : False } self.tblcfg['OMIT_ASSIGNMENT'] = { 'val_nm' : 'omit', 'val_dflt' : False, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['NO_OMIT_ASSGN'] = { 'val_nm' : 'omit', 'val_dflt' : True, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['VIRTUAL_ASSGN'] = { 'val_nm' : 'name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['SET_TYPE'] = { 'val_nm' : 'type', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['TYPE_RENAME'] = { 'val_nm' : 'eth_name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['FIELD_RENAME'] = { 'val_nm' : 'eth_name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['IMPORT_TAG'] = { 'val_nm' : 'ttag', 'val_dflt' : (), 'chk_dup' : True, 'chk_use' : False } self.tblcfg['FN_PARS'] = { 'val_nm' : 'pars', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['TYPE_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : False } self.tblcfg['ETYPE_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : False } self.tblcfg['FIELD_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['EFIELD_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True } self.tblcfg['ASSIGNED_ID'] = { 'val_nm' : 'ids', 'val_dflt' : {}, 'chk_dup' : False,'chk_use' : False } self.tblcfg['ASSIGN_VALUE_TO_TYPE'] = { 'val_nm' : 'name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True } for k in list(self.tblcfg.keys()) : self.table[k] = {} self.order[k] = [] def add_item(self, table, key, fn, lineno, **kw): if self.tblcfg[table]['chk_dup'] and key in self.table[table]: warnings.warn_explicit("Duplicated %s for %s. Previous one is at %s:%d" % (table, key, self.table[table][key]['fn'], self.table[table][key]['lineno']), UserWarning, fn, lineno) return self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False} self.table[table][key].update(kw) self.order[table].append(key) def update_item(self, table, key, fn, lineno, **kw): if key not in self.table[table]: self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False} self.order[table].append(key) self.table[table][key][self.tblcfg[table]['val_nm']] = {} self.table[table][key][self.tblcfg[table]['val_nm']].update(kw[self.tblcfg[table]['val_nm']]) def get_order(self, table): return self.order[table] def check_item(self, table, key): return key in self.table[table] def copy_item(self, table, dst_key, src_key): if (src_key in self.table[table]): self.table[table][dst_key] = self.table[table][src_key] def check_item_value(self, table, key, **kw): return key in self.table[table] and kw.get('val_nm', self.tblcfg[table]['val_nm']) in self.table[table][key] def use_item(self, table, key, **kw): vdflt = kw.get('val_dflt', self.tblcfg[table]['val_dflt']) if key not in self.table[table]: return vdflt vname = kw.get('val_nm', self.tblcfg[table]['val_nm']) #print "use_item() - set used for %s %s" % (table, key) self.table[table][key]['used'] = True return self.table[table][key].get(vname, vdflt) def omit_assignment(self, type, ident, module): if self.ectx.conform.use_item('OMIT_ASSIGNMENT', ident): return True if self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*') or \ self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type) or \ self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*/'+module) or \ self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type+'/'+module): return self.ectx.conform.use_item('NO_OMIT_ASSGN', ident) return False def add_fn_line(self, name, ctx, line, fn, lineno): if name not in self.fn: self.fn[name] = {'FN_HDR' : None, 'FN_FTR' : None, 'FN_BODY' : None} if (self.fn[name][ctx]): self.fn[name][ctx]['text'] += line else: self.fn[name][ctx] = {'text' : line, 'used' : False, 'fn' : fn, 'lineno' : lineno} def get_fn_presence(self, name): #print "get_fn_presence('%s'):%s" % (name, str(self.fn.has_key(name))) #if self.fn.has_key(name): print self.fn[name] return name in self.fn def get_fn_body_presence(self, name): return name in self.fn and self.fn[name]['FN_BODY'] def get_fn_text(self, name, ctx): if (name not in self.fn): return ''; if (not self.fn[name][ctx]): return ''; self.fn[name][ctx]['used'] = True out = self.fn[name][ctx]['text'] if (not self.suppress_line): out = '#line %u "%s"\n%s\n' % (self.fn[name][ctx]['lineno'], rel_dissector_path(self.fn[name][ctx]['fn']), out); return out def add_pdu(self, par, is_new, fn, lineno): #print "add_pdu(par=%s, %s, %d)" % (str(par), fn, lineno) (reg, hidden) = (None, False) if (len(par) > 1): reg = par[1] if (reg and reg[0]=='@'): (reg, hidden) = (reg[1:], True) attr = {'new' : is_new, 'reg' : reg, 'hidden' : hidden, 'need_decl' : False, 'export' : False} self.add_item('PDU', par[0], attr=attr, fn=fn, lineno=lineno) return def add_syntax(self, par, fn, lineno): #print "add_syntax(par=%s, %s, %d)" % (str(par), fn, lineno) if( (len(par) >=2)): name = par[1] else: name = '"'+par[0]+'"' attr = { 'pdu' : par[0] } self.add_item('SYNTAX', name, attr=attr, fn=fn, lineno=lineno) return def add_register(self, pdu, par, fn, lineno): #print "add_register(pdu=%s, par=%s, %s, %d)" % (pdu, str(par), fn, lineno) if (par[0] in ('N', 'NUM')): rtype = 'NUM'; (pmin, pmax) = (2, 2) elif (par[0] in ('S', 'STR')): rtype = 'STR'; (pmin, pmax) = (2, 2) elif (par[0] in ('B', 'BER')): rtype = 'BER'; (pmin, pmax) = (1, 2) elif (par[0] in ('P', 'PER')): rtype = 'PER'; (pmin, pmax) = (1, 2) else: warnings.warn_explicit("Unknown registration type '%s'" % (par[2]), UserWarning, fn, lineno); return if ((len(par)-1) < pmin): warnings.warn_explicit("Too few parameters for %s registration type. At least %d parameters are required" % (rtype, pmin), UserWarning, fn, lineno) return if ((len(par)-1) > pmax): warnings.warn_explicit("Too many parameters for %s registration type. Only %d parameters are allowed" % (rtype, pmax), UserWarning, fn, lineno) attr = {'pdu' : pdu, 'rtype' : rtype} if (rtype in ('NUM', 'STR')): attr['rtable'] = par[1] attr['rport'] = par[2] rkey = '/'.join([rtype, attr['rtable'], attr['rport']]) elif (rtype in ('BER', 'PER')): attr['roid'] = par[1] attr['roidname'] = '""' if (len(par)>=3): attr['roidname'] = par[2] elif attr['roid'][0] != '"': attr['roidname'] = '"' + attr['roid'] + '"' rkey = '/'.join([rtype, attr['roid']]) self.add_item('REGISTER', rkey, attr=attr, fn=fn, lineno=lineno) def check_par(self, par, pmin, pmax, fn, lineno): for i in range(len(par)): if par[i] == '-': par[i] = None continue if par[i][0] == '#': par[i:] = [] break if len(par) < pmin: warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno) return None if (pmax >= 0) and (len(par) > pmax): warnings.warn_explicit("Too many parameters. Only %d parameters are allowed" % (pmax), UserWarning, fn, lineno) return par[0:pmax] return par def read(self, fn): def get_par(line, pmin, pmax, fn, lineno): par = line.split(None, pmax) par = self.check_par(par, pmin, pmax, fn, lineno) return par def get_par_nm(line, pmin, pmax, fn, lineno): if pmax: par = line.split(None, pmax) else: par = [line,] for i in range(len(par)): if par[i][0] == '#': par[i:] = [] break if len(par) < pmin: warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno) return None if len(par) > pmax: nmpar = par[pmax] else: nmpar = '' nmpars = {} nmpar_first = re.compile(r'^\s*(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*') nmpar_next = re.compile(r'\s+(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*') nmpar_end = re.compile(r'\s*$') result = nmpar_first.search(nmpar) pos = 0 while result: k = result.group('attr') pos = result.end() result = nmpar_next.search(nmpar, pos) p1 = pos if result: p2 = result.start() else: p2 = nmpar_end.search(nmpar, pos).start() v = nmpar[p1:p2] nmpars[k] = v if len(par) > pmax: par[pmax] = nmpars return par f = open(fn, "r") lineno = 0 is_import = False directive = re.compile(r'^\s*#\.(?P<name>[A-Z_][A-Z_0-9]*)(\s+|$)') cdirective = re.compile(r'^\s*##') report = re.compile(r'^TABLE(?P<num>\d*)_(?P<type>HDR|BODY|FTR)$') comment = re.compile(r'^\s*#[^.#]') empty = re.compile(r'^\s*$') ctx = None name = '' default_flags = 0x00 stack = [] while True: if not f.closed: line = f.readline() lineno += 1 else: line = None if not line: if not f.closed: f.close() if stack: frec = stack.pop() fn, f, lineno, is_import = frec['fn'], frec['f'], frec['lineno'], frec['is_import'] continue else: break if comment.search(line): continue result = directive.search(line) if result: # directive rep_result = report.search(result.group('name')) if result.group('name') == 'END_OF_CNF': f.close() elif result.group('name') == 'OPT': ctx = result.group('name') par = get_par(line[result.end():], 0, -1, fn=fn, lineno=lineno) if not par: continue self.set_opt(par[0], par[1:], fn, lineno) ctx = None elif result.group('name') in ('PDU', 'PDU_NEW', 'REGISTER', 'REGISTER_NEW', 'MODULE', 'MODULE_IMPORT', 'OMIT_ASSIGNMENT', 'NO_OMIT_ASSGN', 'VIRTUAL_ASSGN', 'SET_TYPE', 'ASSIGN_VALUE_TO_TYPE', 'TYPE_RENAME', 'FIELD_RENAME', 'TF_RENAME', 'IMPORT_TAG', 'TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR', 'SYNTAX', 'SYNTAX_NEW'): ctx = result.group('name') elif result.group('name') in ('OMIT_ALL_ASSIGNMENTS', 'OMIT_ASSIGNMENTS_EXCEPT', 'OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT', 'OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'): ctx = result.group('name') key = '*' if ctx in ('OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT'): key += 'T' if ctx in ('OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'): key += 'V' par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno) if par: key += '/' + par[0] self.add_item('OMIT_ASSIGNMENT', key, omit=True, fn=fn, lineno=lineno) if ctx in ('OMIT_ASSIGNMENTS_EXCEPT', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'): ctx = 'NO_OMIT_ASSGN' else: ctx = None elif result.group('name') in ('EXPORTS', 'MODULE_EXPORTS', 'USER_DEFINED', 'NO_EMIT'): ctx = result.group('name') default_flags = EF_TYPE|EF_VALS if ctx == 'MODULE_EXPORTS': ctx = 'EXPORTS' default_flags |= EF_MODULE if ctx == 'EXPORTS': par = get_par(line[result.end():], 0, 5, fn=fn, lineno=lineno) else: par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno) if not par: continue p = 1 if (par[0] == 'WITH_VALS'): default_flags |= EF_TYPE|EF_VALS elif (par[0] == 'WITHOUT_VALS'): default_flags |= EF_TYPE; default_flags &= ~EF_TYPE elif (par[0] == 'ONLY_VALS'): default_flags &= ~EF_TYPE; default_flags |= EF_VALS elif (ctx == 'EXPORTS'): p = 0 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[0]), UserWarning, fn, lineno) for i in range(p, len(par)): if (par[i] == 'ONLY_ENUM'): default_flags &= ~(EF_TYPE|EF_VALS); default_flags |= EF_ENUM elif (par[i] == 'WITH_ENUM'): default_flags |= EF_ENUM elif (par[i] == 'VALS_WITH_TABLE'): default_flags |= EF_TABLE elif (par[i] == 'WS_DLL'): default_flags |= EF_WS_DLL elif (par[i] == 'EXTERN'): default_flags |= EF_EXTERN elif (par[i] == 'NO_PROT_PREFIX'): default_flags |= EF_NO_PROT else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno) elif result.group('name') in ('MAKE_ENUM', 'MAKE_DEFINES'): ctx = result.group('name') default_flags = EF_ENUM if ctx == 'MAKE_ENUM': default_flags |= EF_NO_PROT|EF_NO_TYPE if ctx == 'MAKE_DEFINES': default_flags |= EF_DEFINE|EF_UCASE|EF_NO_TYPE par = get_par(line[result.end():], 0, 3, fn=fn, lineno=lineno) for i in range(0, len(par)): if (par[i] == 'NO_PROT_PREFIX'): default_flags |= EF_NO_PROT elif (par[i] == 'PROT_PREFIX'): default_flags &= ~ EF_NO_PROT elif (par[i] == 'NO_TYPE_PREFIX'): default_flags |= EF_NO_TYPE elif (par[i] == 'TYPE_PREFIX'): default_flags &= ~ EF_NO_TYPE elif (par[i] == 'UPPER_CASE'): default_flags |= EF_UCASE elif (par[i] == 'NO_UPPER_CASE'): default_flags &= ~EF_UCASE else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno) elif result.group('name') == 'USE_VALS_EXT': ctx = result.group('name') default_flags = 0xFF elif result.group('name') == 'FN_HDR': minp = 1 if (ctx in ('FN_PARS',)) and name: minp = 0 par = get_par(line[result.end():], minp, 1, fn=fn, lineno=lineno) if (not par) and (minp > 0): continue ctx = result.group('name') if par: name = par[0] elif result.group('name') == 'FN_FTR': minp = 1 if (ctx in ('FN_PARS','FN_HDR')) and name: minp = 0 par = get_par(line[result.end():], minp, 1, fn=fn, lineno=lineno) if (not par) and (minp > 0): continue ctx = result.group('name') if par: name = par[0] elif result.group('name') == 'FN_BODY': par = get_par_nm(line[result.end():], 1, 1, fn=fn, lineno=lineno) if not par: continue ctx = result.group('name') name = par[0] if len(par) > 1: self.add_item('FN_PARS', name, pars=par[1], fn=fn, lineno=lineno) elif result.group('name') == 'FN_PARS': par = get_par_nm(line[result.end():], 0, 1, fn=fn, lineno=lineno) ctx = result.group('name') if not par: name = None elif len(par) == 1: name = par[0] self.add_item(ctx, name, pars={}, fn=fn, lineno=lineno) elif len(par) > 1: self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno) ctx = None elif result.group('name') == 'CLASS': par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno) if not par: continue ctx = result.group('name') name = par[0] add_class_ident(name) if not name.split('$')[-1].isupper(): warnings.warn_explicit("No lower-case letters shall be included in information object class name (%s)" % (name), UserWarning, fn, lineno) elif result.group('name') == 'ASSIGNED_OBJECT_IDENTIFIER': par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno) if not par: continue self.update_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER', ids={par[0] : par[0]}, fn=fn, lineno=lineno) elif rep_result: # Reports num = rep_result.group('num') type = rep_result.group('type') if type == 'BODY': par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno) if not par: continue else: par = get_par(line[result.end():], 0, 0, fn=fn, lineno=lineno) rep = { 'type' : type, 'var' : None, 'text' : '', 'fn' : fn, 'lineno' : lineno } if len(par) > 0: rep['var'] = par[0] self.report.setdefault(num, []).append(rep) ctx = 'TABLE' name = num elif result.group('name') in ('INCLUDE', 'IMPORT') : is_imp = result.group('name') == 'IMPORT' par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno) if not par: warnings.warn_explicit("%s requires parameter" % (result.group('name'),), UserWarning, fn, lineno) continue fname = par[0] #print "Try include: %s" % (fname) if (not os.path.exists(fname)): fname = os.path.join(os.path.split(fn)[0], par[0]) #print "Try include: %s" % (fname) i = 0 while not os.path.exists(fname) and (i < len(self.include_path)): fname = os.path.join(self.include_path[i], par[0]) #print "Try include: %s" % (fname) i += 1 if (not os.path.exists(fname)): if is_imp: continue # just ignore else: fname = par[0] # report error fnew = open(fname, "r") stack.append({'fn' : fn, 'f' : f, 'lineno' : lineno, 'is_import' : is_import}) fn, f, lineno, is_import = par[0], fnew, 0, is_imp elif result.group('name') == 'END': ctx = None else: warnings.warn_explicit("Unknown directive '%s'" % (result.group('name')), UserWarning, fn, lineno) continue if not ctx: if not empty.match(line): warnings.warn_explicit("Non-empty line in empty context", UserWarning, fn, lineno) elif ctx == 'OPT': if empty.match(line): continue par = get_par(line, 1, -1, fn=fn, lineno=lineno) if not par: continue self.set_opt(par[0], par[1:], fn, lineno) elif ctx in ('EXPORTS', 'USER_DEFINED', 'NO_EMIT'): if empty.match(line): continue if ctx == 'EXPORTS': par = get_par(line, 1, 6, fn=fn, lineno=lineno) else: par = get_par(line, 1, 2, fn=fn, lineno=lineno) if not par: continue flags = default_flags p = 2 if (len(par)>=2): if (par[1] == 'WITH_VALS'): flags |= EF_TYPE|EF_VALS elif (par[1] == 'WITHOUT_VALS'): flags |= EF_TYPE; flags &= ~EF_TYPE elif (par[1] == 'ONLY_VALS'): flags &= ~EF_TYPE; flags |= EF_VALS elif (ctx == 'EXPORTS'): p = 1 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[1]), UserWarning, fn, lineno) for i in range(p, len(par)): if (par[i] == 'ONLY_ENUM'): flags &= ~(EF_TYPE|EF_VALS); flags |= EF_ENUM elif (par[i] == 'WITH_ENUM'): flags |= EF_ENUM elif (par[i] == 'VALS_WITH_TABLE'): flags |= EF_TABLE elif (par[i] == 'WS_DLL'): flags |= EF_WS_DLL elif (par[i] == 'EXTERN'): flags |= EF_EXTERN elif (par[i] == 'NO_PROT_PREFIX'): flags |= EF_NO_PROT else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno) self.add_item(ctx, par[0], flag=flags, fn=fn, lineno=lineno) elif ctx in ('MAKE_ENUM', 'MAKE_DEFINES'): if empty.match(line): continue par = get_par(line, 1, 4, fn=fn, lineno=lineno) if not par: continue flags = default_flags for i in range(1, len(par)): if (par[i] == 'NO_PROT_PREFIX'): flags |= EF_NO_PROT elif (par[i] == 'PROT_PREFIX'): flags &= ~ EF_NO_PROT elif (par[i] == 'NO_TYPE_PREFIX'): flags |= EF_NO_TYPE elif (par[i] == 'TYPE_PREFIX'): flags &= ~ EF_NO_TYPE elif (par[i] == 'UPPER_CASE'): flags |= EF_UCASE elif (par[i] == 'NO_UPPER_CASE'): flags &= ~EF_UCASE else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno) self.add_item('MAKE_ENUM', par[0], flag=flags, fn=fn, lineno=lineno) elif ctx == 'USE_VALS_EXT': if empty.match(line): continue par = get_par(line, 1, 1, fn=fn, lineno=lineno) if not par: continue flags = default_flags self.add_item('USE_VALS_EXT', par[0], flag=flags, fn=fn, lineno=lineno) elif ctx in ('PDU', 'PDU_NEW'): if empty.match(line): continue par = get_par(line, 1, 5, fn=fn, lineno=lineno) if not par: continue is_new = False if (ctx == 'PDU_NEW'): is_new = True self.add_pdu(par[0:2], is_new, fn, lineno) if (len(par)>=3): self.add_register(par[0], par[2:5], fn, lineno) elif ctx in ('SYNTAX', 'SYNTAX_NEW'): if empty.match(line): continue par = get_par(line, 1, 2, fn=fn, lineno=lineno) if not par: continue if not self.check_item('PDU', par[0]): is_new = False if (ctx == 'SYNTAX_NEW'): is_new = True self.add_pdu(par[0:1], is_new, fn, lineno) self.add_syntax(par, fn, lineno) elif ctx in ('REGISTER', 'REGISTER_NEW'): if empty.match(line): continue par = get_par(line, 3, 4, fn=fn, lineno=lineno) if not par: continue if not self.check_item('PDU', par[0]): is_new = False if (ctx == 'REGISTER_NEW'): is_new = True self.add_pdu(par[0:1], is_new, fn, lineno) self.add_register(par[0], par[1:4], fn, lineno) elif ctx in ('MODULE', 'MODULE_IMPORT'): if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue self.add_item('MODULE', par[0], proto=par[1], fn=fn, lineno=lineno) elif ctx == 'IMPORT_TAG': if empty.match(line): continue par = get_par(line, 3, 3, fn=fn, lineno=lineno) if not par: continue self.add_item(ctx, par[0], ttag=(par[1], par[2]), fn=fn, lineno=lineno) elif ctx == 'OMIT_ASSIGNMENT': if empty.match(line): continue par = get_par(line, 1, 1, fn=fn, lineno=lineno) if not par: continue self.add_item(ctx, par[0], omit=True, fn=fn, lineno=lineno) elif ctx == 'NO_OMIT_ASSGN': if empty.match(line): continue par = get_par(line, 1, 1, fn=fn, lineno=lineno) if not par: continue self.add_item(ctx, par[0], omit=False, fn=fn, lineno=lineno) elif ctx == 'VIRTUAL_ASSGN': if empty.match(line): continue par = get_par(line, 2, -1, fn=fn, lineno=lineno) if not par: continue if (len(par[1].split('/')) > 1) and not self.check_item('SET_TYPE', par[1]): self.add_item('SET_TYPE', par[1], type=par[0], fn=fn, lineno=lineno) self.add_item('VIRTUAL_ASSGN', par[1], name=par[0], fn=fn, lineno=lineno) for nm in par[2:]: self.add_item('SET_TYPE', nm, type=par[0], fn=fn, lineno=lineno) if not par[0][0].isupper(): warnings.warn_explicit("Virtual assignment should have uppercase name (%s)" % (par[0]), UserWarning, fn, lineno) elif ctx == 'SET_TYPE': if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue if not self.check_item('VIRTUAL_ASSGN', par[0]): self.add_item('SET_TYPE', par[0], type=par[1], fn=fn, lineno=lineno) if not par[1][0].isupper(): warnings.warn_explicit("Set type should have uppercase name (%s)" % (par[1]), UserWarning, fn, lineno) elif ctx == 'ASSIGN_VALUE_TO_TYPE': if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue self.add_item(ctx, par[0], name=par[1], fn=fn, lineno=lineno) elif ctx == 'TYPE_RENAME': if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue self.add_item('TYPE_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno) if not par[1][0].isupper(): warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]), UserWarning, fn, lineno) elif ctx == 'FIELD_RENAME': if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue self.add_item('FIELD_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno) if not par[1][0].islower(): warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]), UserWarning, fn, lineno) elif ctx == 'TF_RENAME': if empty.match(line): continue par = get_par(line, 2, 2, fn=fn, lineno=lineno) if not par: continue tmpu = par[1][0].upper() + par[1][1:] tmpl = par[1][0].lower() + par[1][1:] self.add_item('TYPE_RENAME', par[0], eth_name=tmpu, fn=fn, lineno=lineno) if not tmpu[0].isupper(): warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]), UserWarning, fn, lineno) self.add_item('FIELD_RENAME', par[0], eth_name=tmpl, fn=fn, lineno=lineno) if not tmpl[0].islower(): warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]), UserWarning, fn, lineno) elif ctx in ('TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR'): if empty.match(line): continue par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno) if not par: continue self.add_item(ctx, par[0], attr=par[1], fn=fn, lineno=lineno) elif ctx == 'FN_PARS': if empty.match(line): continue if name: par = get_par_nm(line, 0, 0, fn=fn, lineno=lineno) else: par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno) if not par: continue if name: self.update_item(ctx, name, pars=par[0], fn=fn, lineno=lineno) else: self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno) elif ctx in ('FN_HDR', 'FN_FTR', 'FN_BODY'): result = cdirective.search(line) if result: # directive line = '#' + line[result.end():] self.add_fn_line(name, ctx, line, fn=fn, lineno=lineno) elif ctx == 'CLASS': if empty.match(line): continue par = get_par(line, 1, 3, fn=fn, lineno=lineno) if not par: continue if not set_type_to_class(name, par[0], par[1:]): warnings.warn_explicit("Could not set type of class member %s.&%s to %s" % (name, par[0], par[1]), UserWarning, fn, lineno) elif ctx == 'TABLE': self.report[name][-1]['text'] += line def set_opt(self, opt, par, fn, lineno): #print "set_opt: %s, %s" % (opt, par) if opt in ("-I",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.include_path.append(par[0]) elif opt in ("-b", "BER", "CER", "DER"): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.encoding = 'ber' elif opt in ("PER",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.encoding = 'per' elif opt in ("-p", "PROTO"): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.proto_opt = par[0] self.ectx.merge_modules = True elif opt in ("ALIGNED",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.aligned = True elif opt in ("-u", "UNALIGNED"): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.aligned = False elif opt in ("-d",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.dbgopt = par[0] elif opt in ("-e",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.expcnf = True elif opt in ("-S",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.merge_modules = True elif opt in ("GROUP_BY_PROT",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.group_by_prot = True elif opt in ("-o",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.outnm_opt = par[0] elif opt in ("-O",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.output.outdir = par[0] elif opt in ("-s",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.output.single_file = par[0] elif opt in ("-k",): par = self.check_par(par, 0, 0, fn, lineno) self.ectx.output.keep = True elif opt in ("-L",): par = self.check_par(par, 0, 0, fn, lineno) self.suppress_line = True elif opt in ("EMBEDDED_PDV_CB",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.default_embedded_pdv_cb = par[0] elif opt in ("EXTERNAL_TYPE_CB",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.default_external_type_cb = par[0] elif opt in ("-r",): par = self.check_par(par, 1, 1, fn, lineno) if not par: return self.ectx.remove_prefix = par[0] else: warnings.warn_explicit("Unknown option %s" % (opt), UserWarning, fn, lineno) def dbg_print(self): print("\n# Conformance values") print("%-15s %-4s %-15s %-20s %s" % ("File", "Line", "Table", "Key", "Value")) print("-" * 100) tbls = sorted(self.table.keys()) for t in tbls: keys = sorted(self.table[t].keys()) for k in keys: print("%-15s %4s %-15s %-20s %s" % ( self.table[t][k]['fn'], self.table[t][k]['lineno'], t, k, str(self.table[t][k][self.tblcfg[t]['val_nm']]))) def unused_report(self): tbls = sorted(self.table.keys()) for t in tbls: if not self.tblcfg[t]['chk_use']: continue keys = sorted(self.table[t].keys()) for k in keys: if not self.table[t][k]['used']: warnings.warn_explicit("Unused %s for %s" % (t, k), UserWarning, self.table[t][k]['fn'], self.table[t][k]['lineno']) fnms = list(self.fn.keys()) fnms.sort() for f in fnms: keys = sorted(self.fn[f].keys()) for k in keys: if not self.fn[f][k]: continue if not self.fn[f][k]['used']: warnings.warn_explicit("Unused %s for %s" % (k, f), UserWarning, self.fn[f][k]['fn'], self.fn[f][k]['lineno']) #--- EthOut ------------------------------------------------------------------- class EthOut: def __init__(self): self.ectx = None self.outnm = None self.outdir = '.' self.single_file = None self.created_files = {} self.created_files_ord = [] self.keep = False def outcomment(self, ln, comment=None): if comment: return '%s %s\n' % (comment, ln) else: return '/* %-74s */\n' % (ln) def created_file_add(self, name, keep_anyway): name = os.path.normcase(os.path.abspath(name)) if name not in self.created_files: self.created_files_ord.append(name) self.created_files[name] = keep_anyway else: self.created_files[name] = self.created_files[name] or keep_anyway def created_file_exists(self, name): name = os.path.normcase(os.path.abspath(name)) return name in self.created_files #--- output_fname ------------------------------------------------------- def output_fname(self, ftype, ext='c'): fn = '' if not ext in ('cnf',): fn += 'packet-' fn += self.outnm if (ftype): fn += '-' + ftype fn += '.' + ext return fn #--- file_open ------------------------------------------------------- def file_open(self, ftype, ext='c'): fn = self.output_fname(ftype, ext=ext) if self.created_file_exists(fn): fx = open(fn, 'a') else: fx = open(fn, 'w') comment = None if ext in ('cnf',): comment = '#' fx.write(self.fhdr(fn, comment = comment)) else: if (not self.single_file and not self.created_file_exists(fn)): fx.write(self.fhdr(fn)) if not self.ectx.merge_modules: fx.write('\n') mstr = "--- " if self.ectx.groups(): mstr += "Module" if (len(self.ectx.modules) > 1): mstr += "s" for (m, p) in self.ectx.modules: mstr += " %s" % (m) else: mstr += "Module %s" % (self.ectx.Module()) mstr += " --- --- ---" fx.write(self.outcomment(mstr, comment)) fx.write('\n') return fx #--- file_close ------------------------------------------------------- def file_close(self, fx, discard=False, keep_anyway=False): fx.close() if discard and not self.created_file_exists(fx.name): os.unlink(fx.name) else: self.created_file_add(fx.name, keep_anyway) #--- fhdr ------------------------------------------------------- def fhdr(self, fn, comment=None): out = '' out += self.outcomment('Do not modify this file. Changes will be overwritten.', comment) out += self.outcomment('Generated automatically by the ASN.1 to Wireshark dissector compiler', comment) out += self.outcomment(os.path.basename(fn), comment) out += self.outcomment(' '.join(sys.argv), comment) out += '\n' # Make Windows path separator look like Unix path separator out = out.replace('\\', '/') # Change absolute paths and relative paths generated outside # source directory to paths relative to asn1/<proto> subdir. out = re.sub(r'(\s)[./]\S*(/tools/|/epan/)', r'\1../..\2', out) out = re.sub(r'(\s)[./]\S*/asn1/\S*?([\s/])', r'\1.\2', out) return out #--- dbg_print ------------------------------------------------------- def dbg_print(self): print("\n# Output files") print("\n".join(self.created_files_ord)) print("\n") #--- make_single_file ------------------------------------------------------- def make_single_file(self): if (not self.single_file): return in_nm = self.single_file + '.c' out_nm = os.path.join(self.outdir, self.output_fname('')) self.do_include(out_nm, in_nm) in_nm = self.single_file + '.h' if (os.path.exists(in_nm)): out_nm = os.path.join(self.outdir, self.output_fname('', ext='h')) self.do_include(out_nm, in_nm) if (not self.keep): for fn in self.created_files_ord: if not self.created_files[fn]: os.unlink(fn) #--- do_include ------------------------------------------------------- def do_include(self, out_nm, in_nm): def check_file(fn, fnlist): fnfull = os.path.normcase(os.path.abspath(fn)) if (fnfull in fnlist and os.path.exists(fnfull)): return os.path.normpath(fn) return None fin = open(in_nm, "r") fout = open(out_nm, "w") fout.write(self.fhdr(out_nm)) fout.write('/* Input file: ' + os.path.basename(in_nm) +' */\n') fout.write('\n') fout.write('#line %u "%s"\n' % (1, rel_dissector_path(in_nm))) include = re.compile(r'^\s*#\s*include\s+[<"](?P<fname>[^>"]+)[>"]', re.IGNORECASE) cont_linenum = 0; while (True): cont_linenum = cont_linenum + 1; line = fin.readline() if (line == ''): break ifile = None result = include.search(line) #if (result): print os.path.normcase(os.path.abspath(result.group('fname'))) if (result): ifile = check_file(os.path.join(os.path.split(in_nm)[0], result.group('fname')), self.created_files) if (not ifile): ifile = check_file(os.path.join(self.outdir, result.group('fname')), self.created_files) if (not ifile): ifile = check_file(result.group('fname'), self.created_files) if (ifile): fout.write('\n') fout.write('/*--- Included file: ' + ifile + ' ---*/\n') fout.write('#line %u "%s"\n' % (1, rel_dissector_path(ifile))) finc = open(ifile, "r") fout.write(finc.read()) fout.write('\n') fout.write('/*--- End of included file: ' + ifile + ' ---*/\n') fout.write('#line %u "%s"\n' % (cont_linenum+1, rel_dissector_path(in_nm)) ) finc.close() else: fout.write(line) fout.close() fin.close() #--- Node --------------------------------------------------------------------- class Node: def __init__(self,*args, **kw): if len (args) == 0: self.type = self.__class__.__name__ else: assert (len(args) == 1) self.type = args[0] self.__dict__.update (kw) def str_child (self, key, child, depth): indent = " " * (2 * depth) keystr = indent + key + ": " if key == 'type': # already processed in str_depth return "" if isinstance (child, Node): # ugh return keystr + "\n" + child.str_depth (depth+1) if isinstance(child, type ([])): l = [] for x in child: if isinstance (x, Node): l.append (x.str_depth (depth+1)) else: l.append (indent + " " + str(x) + "\n") return keystr + "[\n" + ''.join(l) + indent + "]\n" else: return keystr + str (child) + "\n" def str_depth (self, depth): # ugh indent = " " * (2 * depth) l = ["%s%s" % (indent, self.type)] l.append ("".join ([self.str_child (k_v[0], k_v[1], depth + 1) for k_v in list(self.__dict__.items ())])) return "\n".join (l) def __repr__(self): return "\n" + self.str_depth (0) def to_python (self, ctx): return self.str_depth (ctx.indent_lev) def eth_reg(self, ident, ectx): pass def fld_obj_repr(self, ectx): return "/* TO DO %s */" % (str(self)) #--- ValueAssignment ------------------------------------------------------------- class ValueAssignment (Node): def __init__(self,*args, **kw) : Node.__init__ (self,*args, **kw) def eth_reg(self, ident, ectx): if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit ectx.eth_reg_vassign(self) ectx.eth_reg_value(self.ident, self.typ, self.val) #--- ObjectAssignment ------------------------------------------------------------- class ObjectAssignment (Node): def __init__(self,*args, **kw) : Node.__init__ (self,*args, **kw) def __eq__(self, other): if self.cls != other.cls: return False if len(self.val) != len(other.val): return False for f in (list(self.val.keys())): if f not in other.val: return False if isinstance(self.val[f], Node) and isinstance(other.val[f], Node): if not self.val[f].fld_obj_eq(other.val[f]): return False else: if str(self.val[f]) != str(other.val[f]): return False return True def eth_reg(self, ident, ectx): def make_virtual_type(cls, field, prefix): if isinstance(self.val, str): return if field in self.val and not isinstance(self.val[field], Type_Ref): vnm = prefix + '-' + self.ident virtual_tr = Type_Ref(val = vnm) t = self.val[field] self.val[field] = virtual_tr ectx.eth_reg_assign(vnm, t, virt=True) ectx.eth_reg_type(vnm, t) t.eth_reg_sub(vnm, ectx) if field in self.val and ectx.conform.check_item('PDU', cls + '.' + field): ectx.eth_reg_field(self.val[field].val, self.val[field].val, impl=self.val[field].HasImplicitTag(ectx), pdu=ectx.conform.use_item('PDU', cls + '.' + field)) return # end of make_virtual_type() if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit self.module = ectx.Module() ectx.eth_reg_oassign(self) if (self.cls == 'TYPE-IDENTIFIER') or (self.cls == 'ABSTRACT-SYNTAX'): make_virtual_type(self.cls, '&Type', 'TYPE') if (self.cls == 'OPERATION'): make_virtual_type(self.cls, '&ArgumentType', 'ARG') make_virtual_type(self.cls, '&ResultType', 'RES') if (self.cls == 'ERROR'): make_virtual_type(self.cls, '&ParameterType', 'PAR') #--- Type --------------------------------------------------------------------- class Type (Node): def __init__(self,*args, **kw) : self.name = None self.constr = None self.tags = [] self.named_list = None Node.__init__ (self,*args, **kw) def IsNamed(self): if self.name is None : return False else: return True def HasConstraint(self): if self.constr is None : return False else : return True def HasSizeConstraint(self): return self.HasConstraint() and self.constr.IsSize() def HasValueConstraint(self): return self.HasConstraint() and self.constr.IsValue() def HasPermAlph(self): return self.HasConstraint() and self.constr.IsPermAlph() def HasContentsConstraint(self): return self.HasConstraint() and self.constr.IsContents() def HasOwnTag(self): return len(self.tags) > 0 def HasImplicitTag(self, ectx): return (self.HasOwnTag() and self.tags[0].IsImplicit(ectx)) def IndetermTag(self, ectx): return False def AddTag(self, tag): self.tags[0:0] = [tag] def GetTag(self, ectx): #print "GetTag(%s)\n" % self.name; if (self.HasOwnTag()): return self.tags[0].GetTag(ectx) else: return self.GetTTag(ectx) def GetTTag(self, ectx): print("#Unhandled GetTTag() in %s" % (self.type)) print(self.str_depth(1)) return ('BER_CLASS_unknown', 'TAG_unknown') def SetName(self, name): self.name = name def AddConstraint(self, constr): if not self.HasConstraint(): self.constr = constr else: self.constr = Constraint(type = 'Intersection', subtype = [self.constr, constr]) def eth_tname(self): return '#' + self.type + '_' + str(id(self)) def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def eth_strings(self): return 'NULL' def eth_omit_field(self): return False def eth_need_tree(self): return False def eth_has_vals(self): return False def eth_has_enum(self, tname, ectx): return self.eth_has_vals() and (ectx.eth_type[tname]['enum'] & EF_ENUM) def eth_need_pdu(self, ectx): return None def eth_named_bits(self): return None def eth_reg_sub(self, ident, ectx): pass def get_components(self, ectx): print("#Unhandled get_components() in %s" % (self.type)) print(self.str_depth(1)) return [] def sel_req(self, sel, ectx): print("#Selection '%s' required for non-CHOICE type %s" % (sel, self.type)) print(self.str_depth(1)) def fld_obj_eq(self, other): return isinstance(other, Type) and (self.eth_tname() == other.eth_tname()) def eth_reg(self, ident, ectx, tstrip=0, tagflag=False, selflag=False, idx='', parent=None): #print "eth_reg(): %s, ident=%s, tstrip=%d, tagflag=%s, selflag=%s, parent=%s" %(self.type, ident, tstrip, str(tagflag), str(selflag), str(parent)) #print " ", self if (ectx.NeedTags() and (len(self.tags) > tstrip)): tagged_type = self for i in range(len(self.tags)-1, tstrip-1, -1): tagged_type = TaggedType(val=tagged_type, tstrip=i) tagged_type.AddTag(self.tags[i]) if not tagflag: # 1st tagged level if self.IsNamed() and not selflag: tagged_type.SetName(self.name) tagged_type.eth_reg(ident, ectx, tstrip=1, tagflag=tagflag, idx=idx, parent=parent) return nm = '' if ident and self.IsNamed() and not tagflag and not selflag: nm = ident + '/' + self.name elif ident: nm = ident elif self.IsNamed(): nm = self.name if not ident and ectx.conform.omit_assignment('T', nm, ectx.Module()): return # Assignment to omit if not ident: # Assignment ectx.eth_reg_assign(nm, self) if self.type == 'Type_Ref' and not self.tr_need_own_fn(ectx): ectx.eth_reg_type(nm, self) virtual_tr = Type_Ref(val=ectx.conform.use_item('SET_TYPE', nm)) if (self.type == 'Type_Ref') or ectx.conform.check_item('SET_TYPE', nm): if ident and (ectx.conform.check_item('TYPE_RENAME', nm) or ectx.conform.get_fn_presence(nm) or selflag): if ectx.conform.check_item('SET_TYPE', nm): ectx.eth_reg_type(nm, virtual_tr) # dummy Type Reference else: ectx.eth_reg_type(nm, self) # new type trnm = nm elif ectx.conform.check_item('SET_TYPE', nm): trnm = ectx.conform.use_item('SET_TYPE', nm) elif (self.type == 'Type_Ref') and self.tr_need_own_fn(ectx): ectx.eth_reg_type(nm, self) # need own function, e.g. for constraints trnm = nm else: trnm = self.val else: ectx.eth_reg_type(nm, self) trnm = nm if ectx.conform.check_item('VIRTUAL_ASSGN', nm): vnm = ectx.conform.use_item('VIRTUAL_ASSGN', nm) ectx.eth_reg_assign(vnm, self, virt=True) ectx.eth_reg_type(vnm, self) self.eth_reg_sub(vnm, ectx) if parent and (ectx.type[parent]['val'].type == 'TaggedType'): ectx.type[parent]['val'].eth_set_val_name(parent, trnm, ectx) if ident and not tagflag and not self.eth_omit_field(): ectx.eth_reg_field(nm, trnm, idx=idx, parent=parent, impl=self.HasImplicitTag(ectx)) if ectx.conform.check_item('SET_TYPE', nm): virtual_tr.eth_reg_sub(nm, ectx) else: self.eth_reg_sub(nm, ectx) def eth_get_size_constr(self, ectx): (minv, maxv, ext) = ('MIN', 'MAX', False) if self.HasSizeConstraint(): if self.constr.IsSize(): (minv, maxv, ext) = self.constr.GetSize(ectx) if (self.constr.type == 'Intersection'): if self.constr.subtype[0].IsSize(): (minv, maxv, ext) = self.constr.subtype[0].GetSize(ectx) elif self.constr.subtype[1].IsSize(): (minv, maxv, ext) = self.constr.subtype[1].GetSize(ectx) if minv == 'MIN': minv = 'NO_BOUND' if maxv == 'MAX': maxv = 'NO_BOUND' if (ext): ext = 'TRUE' else: ext = 'FALSE' return (minv, maxv, ext) def eth_get_value_constr(self, ectx): (minv, maxv, ext) = ('MIN', 'MAX', False) if self.HasValueConstraint(): (minv, maxv, ext) = self.constr.GetValue(ectx) if minv == 'MIN': minv = 'NO_BOUND' if maxv == 'MAX': maxv = 'NO_BOUND' if str(minv).isdigit(): minv += 'U' elif (str(minv)[0] == "-") and str(minv)[1:].isdigit(): if (int(minv) == -(2**31)): minv = "G_MININT32" elif (int(minv) < -(2**31)): minv = "G_GINT64_CONSTANT(%s)" % (str(minv)) if str(maxv).isdigit(): if (int(maxv) >= 2**32): maxv = "G_GUINT64_CONSTANT(%s)" % (str(maxv)) else: maxv += 'U' if (ext): ext = 'TRUE' else: ext = 'FALSE' return (minv, maxv, ext) def eth_get_alphabet_constr(self, ectx): (alph, alphlen) = ('NULL', '0') if self.HasPermAlph(): alph = self.constr.GetPermAlph(ectx) if not alph: alph = 'NULL' if (alph != 'NULL'): if (((alph[0] + alph[-1]) == '""') and (not alph.count('"', 1, -1))): alphlen = str(len(alph) - 2) else: alphlen = 'strlen(%s)' % (alph) return (alph, alphlen) def eth_type_vals(self, tname, ectx): if self.eth_has_vals(): print("#Unhandled eth_type_vals('%s') in %s" % (tname, self.type)) print(self.str_depth(1)) return '' def eth_type_enum(self, tname, ectx): if self.eth_has_enum(tname, ectx): print("#Unhandled eth_type_enum('%s') in %s" % (tname, self.type)) print(self.str_depth(1)) return '' def eth_type_default_table(self, ectx, tname): return '' def eth_type_default_body(self, ectx): print("#Unhandled eth_type_default_body() in %s" % (self.type)) print(self.str_depth(1)) return '' def eth_type_default_pars(self, ectx, tname): pars = { 'TNAME' : tname, 'ER' : ectx.encp(), 'FN_VARIANT' : '', 'TREE' : 'tree', 'TVB' : 'tvb', 'OFFSET' : 'offset', 'ACTX' : 'actx', 'HF_INDEX' : 'hf_index', 'VAL_PTR' : 'NULL', 'IMPLICIT_TAG' : 'implicit_tag', } if (ectx.eth_type[tname]['tree']): pars['ETT_INDEX'] = ectx.eth_type[tname]['tree'] if (ectx.merge_modules): pars['PROTOP'] = '' else: pars['PROTOP'] = ectx.eth_type[tname]['proto'] + '_' return pars def eth_type_fn(self, proto, tname, ectx): body = self.eth_type_default_body(ectx, tname) pars = self.eth_type_default_pars(ectx, tname) if ectx.conform.check_item('FN_PARS', tname): pars.update(ectx.conform.use_item('FN_PARS', tname)) elif ectx.conform.check_item('FN_PARS', ectx.eth_type[tname]['ref'][0]): pars.update(ectx.conform.use_item('FN_PARS', ectx.eth_type[tname]['ref'][0])) pars['DEFAULT_BODY'] = body for i in range(4): for k in list(pars.keys()): try: pars[k] = pars[k] % pars except (ValueError,TypeError): raise sys.exc_info()[0]("%s\n%s" % (str(pars), sys.exc_info()[1])) out = '\n' out += self.eth_type_default_table(ectx, tname) % pars out += ectx.eth_type_fn_hdr(tname) out += ectx.eth_type_fn_body(tname, body, pars=pars) out += ectx.eth_type_fn_ftr(tname) return out #--- Value -------------------------------------------------------------------- class Value (Node): def __init__(self,*args, **kw) : self.name = None Node.__init__ (self,*args, **kw) def SetName(self, name) : self.name = name def to_str(self, ectx): return str(self.val) def get_dep(self): return None def fld_obj_repr(self, ectx): return self.to_str(ectx) #--- Value_Ref ----------------------------------------------------------------- class Value_Ref (Value): def to_str(self, ectx): return asn2c(self.val) #--- ObjectClass --------------------------------------------------------------------- class ObjectClass (Node): def __init__(self,*args, **kw) : self.name = None Node.__init__ (self,*args, **kw) def SetName(self, name): self.name = name add_class_ident(self.name) def eth_reg(self, ident, ectx): if ectx.conform.omit_assignment('C', self.name, ectx.Module()): return # Assignment to omit ectx.eth_reg_objectclass(self.name, self) #--- Class_Ref ----------------------------------------------------------------- class Class_Ref (ObjectClass): pass #--- ObjectClassDefn --------------------------------------------------------------------- class ObjectClassDefn (ObjectClass): def reg_types(self): for fld in self.fields: repr = fld.fld_repr() set_type_to_class(self.name, repr[0], repr[1:]) #--- Tag --------------------------------------------------------------- class Tag (Node): def to_python (self, ctx): return 'asn1.TYPE(%s,%s)' % (mk_tag_str (ctx, self.tag.cls, self.tag_typ, self.tag.num), self.typ.to_python (ctx)) def IsImplicit(self, ectx): return ((self.mode == 'IMPLICIT') or ((self.mode == 'default') and (ectx.tag_def != 'EXPLICIT'))) def GetTag(self, ectx): tc = '' if (self.cls == 'UNIVERSAL'): tc = 'BER_CLASS_UNI' elif (self.cls == 'APPLICATION'): tc = 'BER_CLASS_APP' elif (self.cls == 'CONTEXT'): tc = 'BER_CLASS_CON' elif (self.cls == 'PRIVATE'): tc = 'BER_CLASS_PRI' return (tc, self.num) def eth_tname(self): n = '' if (self.cls == 'UNIVERSAL'): n = 'U' elif (self.cls == 'APPLICATION'): n = 'A' elif (self.cls == 'CONTEXT'): n = 'C' elif (self.cls == 'PRIVATE'): n = 'P' return n + str(self.num) #--- Constraint --------------------------------------------------------------- constr_cnt = 0 class Constraint (Node): def to_python (self, ctx): print("Ignoring constraint:", self.type) return self.subtype.typ.to_python (ctx) def __str__ (self): return "Constraint: type=%s, subtype=%s" % (self.type, self.subtype) def eth_tname(self): return '#' + self.type + '_' + str(id(self)) def IsSize(self): return (self.type == 'Size' and self.subtype.IsValue()) \ or (self.type == 'Intersection' and (self.subtype[0].IsSize() or self.subtype[1].IsSize())) \ def GetSize(self, ectx): (minv, maxv, ext) = ('MIN', 'MAX', False) if self.IsSize(): if self.type == 'Size': (minv, maxv, ext) = self.subtype.GetValue(ectx) elif self.type == 'Intersection': if self.subtype[0].IsSize() and not self.subtype[1].IsSize(): (minv, maxv, ext) = self.subtype[0].GetSize(ectx) elif not self.subtype[0].IsSize() and self.subtype[1].IsSize(): (minv, maxv, ext) = self.subtype[1].GetSize(ectx) return (minv, maxv, ext) def IsValue(self): return self.type == 'SingleValue' \ or self.type == 'ValueRange' \ or (self.type == 'Intersection' and (self.subtype[0].IsValue() or self.subtype[1].IsValue())) \ or (self.type == 'Union' and (self.subtype[0].IsValue() and self.subtype[1].IsValue())) def GetValue(self, ectx): (minv, maxv, ext) = ('MIN', 'MAX', False) if self.IsValue(): if self.type == 'SingleValue': minv = ectx.value_get_eth(self.subtype) maxv = ectx.value_get_eth(self.subtype) ext = hasattr(self, 'ext') and self.ext elif self.type == 'ValueRange': minv = ectx.value_get_eth(self.subtype[0]) maxv = ectx.value_get_eth(self.subtype[1]) ext = hasattr(self, 'ext') and self.ext elif self.type == 'Intersection': if self.subtype[0].IsValue() and not self.subtype[1].IsValue(): (minv, maxv, ext) = self.subtype[0].GetValue(ectx) elif not self.subtype[0].IsValue() and self.subtype[1].IsValue(): (minv, maxv, ext) = self.subtype[1].GetValue(ectx) elif self.subtype[0].IsValue() and self.subtype[1].IsValue(): v0 = self.subtype[0].GetValue(ectx) v1 = self.subtype[1].GetValue(ectx) (minv, maxv, ext) = (ectx.value_max(v0[0],v1[0]), ectx.value_min(v0[1],v1[1]), v0[2] and v1[2]) elif self.type == 'Union': if self.subtype[0].IsValue() and self.subtype[1].IsValue(): v0 = self.subtype[0].GetValue(ectx) v1 = self.subtype[1].GetValue(ectx) (minv, maxv, ext) = (ectx.value_min(v0[0],v1[0]), ectx.value_max(v0[1],v1[1]), v0[2] or v1[2]) return (minv, maxv, ext) def IsAlphabet(self): return self.type == 'SingleValue' \ or self.type == 'ValueRange' \ or (self.type == 'Intersection' and (self.subtype[0].IsAlphabet() or self.subtype[1].IsAlphabet())) \ or (self.type == 'Union' and (self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet())) def GetAlphabet(self, ectx): alph = None if self.IsAlphabet(): if self.type == 'SingleValue': alph = ectx.value_get_eth(self.subtype) elif self.type == 'ValueRange': if ((len(self.subtype[0]) == 3) and ((self.subtype[0][0] + self.subtype[0][-1]) == '""') \ and (len(self.subtype[1]) == 3) and ((self.subtype[1][0] + self.subtype[1][-1]) == '""')): alph = '"' for c in range(ord(self.subtype[0][1]), ord(self.subtype[1][1]) + 1): alph += chr(c) alph += '"' elif self.type == 'Union': if self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet(): a0 = self.subtype[0].GetAlphabet(ectx) a1 = self.subtype[1].GetAlphabet(ectx) if (((a0[0] + a0[-1]) == '""') and not a0.count('"', 1, -1) \ and ((a1[0] + a1[-1]) == '""') and not a1.count('"', 1, -1)): alph = '"' + a0[1:-1] + a1[1:-1] + '"' else: alph = a0 + ' ' + a1 return alph def IsPermAlph(self): return self.type == 'From' and self.subtype.IsAlphabet() \ or (self.type == 'Intersection' and (self.subtype[0].IsPermAlph() or self.subtype[1].IsPermAlph())) \ def GetPermAlph(self, ectx): alph = None if self.IsPermAlph(): if self.type == 'From': alph = self.subtype.GetAlphabet(ectx) elif self.type == 'Intersection': if self.subtype[0].IsPermAlph() and not self.subtype[1].IsPermAlph(): alph = self.subtype[0].GetPermAlph(ectx) elif not self.subtype[0].IsPermAlph() and self.subtype[1].IsPermAlph(): alph = self.subtype[1].GetPermAlph(ectx) return alph def IsContents(self): return self.type == 'Contents' \ or (self.type == 'Intersection' and (self.subtype[0].IsContents() or self.subtype[1].IsContents())) \ def GetContents(self, ectx): contents = None if self.IsContents(): if self.type == 'Contents': if self.subtype.type == 'Type_Ref': contents = self.subtype.val elif self.type == 'Intersection': if self.subtype[0].IsContents() and not self.subtype[1].IsContents(): contents = self.subtype[0].GetContents(ectx) elif not self.subtype[0].IsContents() and self.subtype[1].IsContents(): contents = self.subtype[1].GetContents(ectx) return contents def IsNegativ(self): def is_neg(sval): return isinstance(sval, str) and (sval[0] == '-') if self.type == 'SingleValue': return is_neg(self.subtype) elif self.type == 'ValueRange': if self.subtype[0] == 'MIN': return True return is_neg(self.subtype[0]) return False def eth_constrname(self): def int2str(val): if isinstance(val, Value_Ref): return asn2c(val.val) try: if (int(val) < 0): return 'M' + str(-int(val)) else: return str(int(val)) except (ValueError, TypeError): return asn2c(str(val)) ext = '' if hasattr(self, 'ext') and self.ext: ext = '_' if self.type == 'SingleValue': return int2str(self.subtype) + ext elif self.type == 'ValueRange': return int2str(self.subtype[0]) + '_' + int2str(self.subtype[1]) + ext elif self.type == 'Size': return 'SIZE_' + self.subtype.eth_constrname() + ext else: if (not hasattr(self, 'constr_num')): global constr_cnt constr_cnt += 1 self.constr_num = constr_cnt return 'CONSTR%03d%s' % (self.constr_num, ext) def Needs64b(self, ectx): (minv, maxv, ext) = self.GetValue(ectx) if (str(minv).isdigit() or ((str(minv)[0] == "-") and str(minv)[1:].isdigit())) \ and str(maxv).isdigit() and (abs(int(maxv) - int(minv)) >= 2**32): return True return False class Module (Node): def to_python (self, ctx): ctx.tag_def = self.tag_def.dfl_tag return """#%s %s""" % (self.ident, self.body.to_python (ctx)) def get_name(self): return self.ident.val def get_proto(self, ectx): if (ectx.proto): prot = ectx.proto else: prot = ectx.conform.use_item('MODULE', self.get_name(), val_dflt=self.get_name()) return prot def to_eth(self, ectx): ectx.tags_def = 'EXPLICIT' # default = explicit ectx.proto = self.get_proto(ectx) ectx.tag_def = self.tag_def.dfl_tag ectx.eth_reg_module(self) self.body.to_eth(ectx) class Module_Body (Node): def to_python (self, ctx): # XXX handle exports, imports. l = [x.to_python (ctx) for x in self.assign_list] l = [a for a in l if a != ''] return "\n".join (l) def to_eth(self, ectx): # Exports ectx.eth_exports(self.exports) # Imports for i in self.imports: mod = i.module.val proto = ectx.conform.use_item('MODULE', mod, val_dflt=mod) ectx.eth_module_dep_add(ectx.Module(), mod) for s in i.symbol_list: if isinstance(s, Type_Ref): ectx.eth_import_type(s.val, mod, proto) elif isinstance(s, Value_Ref): ectx.eth_import_value(s.val, mod, proto) elif isinstance(s, Class_Ref): ectx.eth_import_class(s.val, mod, proto) else: msg = 'Unknown kind of imported symbol %s from %s' % (str(s), mod) warnings.warn_explicit(msg, UserWarning, '', 0) # AssignmentList for a in self.assign_list: a.eth_reg('', ectx) class Default_Tags (Node): def to_python (self, ctx): # not to be used directly assert (0) # XXX should just calculate dependencies as we go along. def calc_dependencies (node, dict, trace = 0): if not hasattr (node, '__dict__'): if trace: print("#returning, node=", node) return if isinstance (node, Type_Ref): dict [node.val] = 1 if trace: print("#Setting", node.val) return for (a, val) in list(node.__dict__.items ()): if trace: print("# Testing node ", node, "attr", a, " val", val) if a[0] == '_': continue elif isinstance (val, Node): calc_dependencies (val, dict, trace) elif isinstance (val, type ([])): for v in val: calc_dependencies (v, dict, trace) class Type_Assign (Node): def __init__ (self, *args, **kw): Node.__init__ (self, *args, **kw) if isinstance (self.val, Tag): # XXX replace with generalized get_typ_ignoring_tag (no-op for Node, override in Tag) to_test = self.val.typ else: to_test = self.val if isinstance (to_test, SequenceType): to_test.sequence_name = self.name.name def to_python (self, ctx): dep_dict = {} calc_dependencies (self.val, dep_dict, 0) depend_list = list(dep_dict.keys ()) return ctx.register_assignment (self.name.name, self.val.to_python (ctx), depend_list) class PyQuote (Node): def to_python (self, ctx): return ctx.register_pyquote (self.val) #--- Type_Ref ----------------------------------------------------------------- class Type_Ref (Type): def to_python (self, ctx): return self.val def eth_reg_sub(self, ident, ectx): ectx.eth_dep_add(ident, self.val) def eth_tname(self): if self.HasSizeConstraint(): return asn2c(self.val) + '_' + self.constr.eth_constrname() else: return asn2c(self.val) def tr_need_own_fn(self, ectx): return ectx.Per() and self.HasSizeConstraint() def fld_obj_repr(self, ectx): return self.val def get_components(self, ectx): if self.val not in ectx.type or ectx.type[self.val]['import']: msg = "Can not get COMPONENTS OF %s which is imported type" % (self.val) warnings.warn_explicit(msg, UserWarning, '', 0) return [] else: return ectx.type[self.val]['val'].get_components(ectx) def GetTTag(self, ectx): #print "GetTTag(%s)\n" % self.val; if (ectx.type[self.val]['import']): if 'ttag' not in ectx.type[self.val]: ttag = ectx.get_ttag_from_all(self.val, ectx.type[self.val]['import']) if not ttag and not ectx.conform.check_item('IMPORT_TAG', self.val): msg = 'Missing tag information for imported type %s from %s (%s)' % (self.val, ectx.type[self.val]['import'], ectx.type[self.val]['proto']) warnings.warn_explicit(msg, UserWarning, '', 0) ttag = ('-1/*imported*/', '-1/*imported*/') ectx.type[self.val]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.val, val_dflt=ttag) return ectx.type[self.val]['ttag'] else: return ectx.type[self.val]['val'].GetTag(ectx) def IndetermTag(self, ectx): if (ectx.type[self.val]['import']): return False else: return ectx.type[self.val]['val'].IndetermTag(ectx) def eth_type_default_pars(self, ectx, tname): if tname: pars = Type.eth_type_default_pars(self, ectx, tname) else: pars = {} t = ectx.type[self.val]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' if self.HasSizeConstraint(): (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) elif (ectx.Per()): if self.HasSizeConstraint(): body = ectx.eth_fn_call('dissect_%(ER)s_size_constrained_type', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',), ('"%(TYPE_REF_TNAME)s"', '%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),)) else: body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- SelectionType ------------------------------------------------------------ class SelectionType (Type): def to_python (self, ctx): return self.val def sel_of_typeref(self): return self.typ.type == 'Type_Ref' def eth_reg_sub(self, ident, ectx): if not self.sel_of_typeref(): self.seltype = '' return self.seltype = ectx.eth_sel_req(self.typ.val, self.sel) ectx.eth_dep_add(ident, self.seltype) def eth_ftype(self, ectx): (ftype, display) = ('FT_NONE', 'BASE_NONE') if self.sel_of_typeref() and not ectx.type[self.seltype]['import']: (ftype, display) = ectx.type[self.typ.val]['val'].eth_ftype_sel(self.sel, ectx) return (ftype, display) def GetTTag(self, ectx): #print "GetTTag(%s)\n" % self.seltype; if (ectx.type[self.seltype]['import']): if 'ttag' not in ectx.type[self.seltype]: if not ectx.conform.check_item('IMPORT_TAG', self.seltype): msg = 'Missing tag information for imported type %s from %s (%s)' % (self.seltype, ectx.type[self.seltype]['import'], ectx.type[self.seltype]['proto']) warnings.warn_explicit(msg, UserWarning, '', 0) ectx.type[self.seltype]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.seltype, val_dflt=('-1 /*imported*/', '-1 /*imported*/')) return ectx.type[self.seltype]['ttag'] else: return ectx.type[self.typ.val]['val'].GetTTagSel(self.sel, ectx) def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) if self.sel_of_typeref(): t = ectx.type[self.seltype]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' return pars def eth_type_default_body(self, ectx, tname): if not self.sel_of_typeref(): body = '#error Can not decode %s' % (tname) elif (ectx.Ber()): body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) elif (ectx.Per()): body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- TaggedType ----------------------------------------------------------------- class TaggedType (Type): def eth_tname(self): tn = '' for i in range(self.tstrip, len(self.val.tags)): tn += self.val.tags[i].eth_tname() tn += '_' tn += self.val.eth_tname() return tn def eth_set_val_name(self, ident, val_name, ectx): #print "TaggedType::eth_set_val_name(): ident=%s, val_name=%s" % (ident, val_name) self.val_name = val_name ectx.eth_dep_add(ident, self.val_name) def eth_reg_sub(self, ident, ectx): self.val_name = ident + '/' + UNTAG_TYPE_NAME self.val.eth_reg(self.val_name, ectx, tstrip=self.tstrip+1, tagflag=True, parent=ident) def GetTTag(self, ectx): #print "GetTTag(%s)\n" % self.seltype; return self.GetTag(ectx) def eth_ftype(self, ectx): return self.val.eth_ftype(ectx) def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) t = ectx.type[self.val_name]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' (pars['TAG_CLS'], pars['TAG_TAG']) = self.GetTag(ectx) if self.HasImplicitTag(ectx): pars['TAG_IMPL'] = 'TRUE' else: pars['TAG_IMPL'] = 'FALSE' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_tagged_type', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(HF_INDEX)s', '%(TAG_CLS)s', '%(TAG_TAG)s', '%(TAG_IMPL)s', '%(TYPE_REF_FN)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- SqType ----------------------------------------------------------- class SqType (Type): def out_item(self, f, val, optional, ext, ectx): if (val.eth_omit_field()): t = ectx.type[val.ident]['ethname'] fullname = ectx.dummy_eag_field else: ef = ectx.field[f]['ethname'] t = ectx.eth_hf[ef]['ethtype'] fullname = ectx.eth_hf[ef]['fullname'] if (ectx.Ber()): #print "optional=%s, e.val.HasOwnTag()=%s, e.val.IndetermTag()=%s" % (str(e.optional), str(e.val.HasOwnTag()), str(e.val.IndetermTag(ectx))) #print val.str_depth(1) opt = '' if (optional): opt = 'BER_FLAGS_OPTIONAL' if (not val.HasOwnTag()): if (opt): opt += '|' opt += 'BER_FLAGS_NOOWNTAG' elif (val.HasImplicitTag(ectx)): if (opt): opt += '|' opt += 'BER_FLAGS_IMPLTAG' if (val.IndetermTag(ectx)): if (opt): opt += '|' opt += 'BER_FLAGS_NOTCHKTAG' if (not opt): opt = '0' else: if optional: opt = 'ASN1_OPTIONAL' else: opt = 'ASN1_NOT_OPTIONAL' if (ectx.Ber()): (tc, tn) = val.GetTag(ectx) out = ' { %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \ % ('&'+fullname, tc, tn, opt, ectx.eth_type[t]['proto'], t) elif (ectx.Per()): out = ' { %-24s, %-23s, %-17s, dissect_%s_%s },\n' \ % ('&'+fullname, ext, opt, ectx.eth_type[t]['proto'], t) else: out = '' return out #--- SeqType ----------------------------------------------------------- class SeqType (SqType): def all_components(self): lst = self.elt_list[:] if hasattr(self, 'ext_list'): lst.extend(self.ext_list) if hasattr(self, 'elt_list2'): lst.extend(self.elt_list2) return lst def need_components(self): lst = self.all_components() for e in (lst): if e.type == 'components_of': return True return False def expand_components(self, ectx): while self.need_components(): for i in range(len(self.elt_list)): if self.elt_list[i].type == 'components_of': comp = self.elt_list[i].typ.get_components(ectx) self.elt_list[i:i+1] = comp break if hasattr(self, 'ext_list'): for i in range(len(self.ext_list)): if self.ext_list[i].type == 'components_of': comp = self.ext_list[i].typ.get_components(ectx) self.ext_list[i:i+1] = comp break if hasattr(self, 'elt_list2'): for i in range(len(self.elt_list2)): if self.elt_list2[i].type == 'components_of': comp = self.elt_list2[i].typ.get_components(ectx) self.elt_list2[i:i+1] = comp break def get_components(self, ectx): lst = self.elt_list[:] if hasattr(self, 'elt_list2'): lst.extend(self.elt_list2) return lst def eth_reg_sub(self, ident, ectx, components_available=False): # check if autotag is required autotag = False if (ectx.NeedTags() and (ectx.tag_def == 'AUTOMATIC')): autotag = True lst = self.all_components() for e in (self.elt_list): if e.val.HasOwnTag(): autotag = False; break; # expand COMPONENTS OF if self.need_components(): if components_available: self.expand_components(ectx) else: ectx.eth_comp_req(ident) return # extension addition groups if hasattr(self, 'ext_list'): if (ectx.Per()): # add names eag_num = 1 for e in (self.ext_list): if isinstance(e.val, ExtensionAdditionGroup): e.val.parent_ident = ident e.val.parent_tname = ectx.type[ident]['tname'] if (e.val.ver): e.val.SetName("eag_v%s" % (e.val.ver)) else: e.val.SetName("eag_%d" % (eag_num)) eag_num += 1; else: # expand new_ext_list = [] for e in (self.ext_list): if isinstance(e.val, ExtensionAdditionGroup): new_ext_list.extend(e.val.elt_list) else: new_ext_list.append(e) self.ext_list = new_ext_list # do autotag if autotag: atag = 0 for e in (self.elt_list): e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT')) atag += 1 if autotag and hasattr(self, 'elt_list2'): for e in (self.elt_list2): e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT')) atag += 1 if autotag and hasattr(self, 'ext_list'): for e in (self.ext_list): e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT')) atag += 1 # register components for e in (self.elt_list): e.val.eth_reg(ident, ectx, tstrip=1, parent=ident) if hasattr(self, 'ext_list'): for e in (self.ext_list): e.val.eth_reg(ident, ectx, tstrip=1, parent=ident) if hasattr(self, 'elt_list2'): for e in (self.elt_list2): e.val.eth_reg(ident, ectx, tstrip=1, parent=ident) def eth_type_default_table(self, ectx, tname): #print "eth_type_default_table(tname='%s')" % (tname) fname = ectx.eth_type[tname]['ref'][0] table = "static const %(ER)s_sequence_t %(TABLE)s[] = {\n" if hasattr(self, 'ext_list'): ext = 'ASN1_EXTENSION_ROOT' else: ext = 'ASN1_NO_EXTENSIONS' empty_ext_flag = '0' if (len(self.elt_list)==0) and hasattr(self, 'ext_list') and (len(self.ext_list)==0) and (not hasattr(self, 'elt_list2') or (len(self.elt_list2)==0)): empty_ext_flag = ext for e in (self.elt_list): f = fname + '/' + e.val.name table += self.out_item(f, e.val, e.optional, ext, ectx) if hasattr(self, 'ext_list'): for e in (self.ext_list): f = fname + '/' + e.val.name table += self.out_item(f, e.val, e.optional, 'ASN1_NOT_EXTENSION_ROOT', ectx) if hasattr(self, 'elt_list2'): for e in (self.elt_list2): f = fname + '/' + e.val.name table += self.out_item(f, e.val, e.optional, ext, ectx) if (ectx.Ber()): table += " { NULL, 0, 0, 0, NULL }\n};\n" else: table += " { NULL, %s, 0, NULL }\n};\n" % (empty_ext_flag) return table #--- SeqOfType ----------------------------------------------------------- class SeqOfType (SqType): def eth_type_default_table(self, ectx, tname): #print "eth_type_default_table(tname='%s')" % (tname) fname = ectx.eth_type[tname]['ref'][0] if self.val.IsNamed (): f = fname + '/' + self.val.name else: f = fname + '/' + ITEM_FIELD_NAME table = "static const %(ER)s_sequence_t %(TABLE)s[1] = {\n" table += self.out_item(f, self.val, False, 'ASN1_NO_EXTENSIONS', ectx) table += "};\n" return table #--- SequenceOfType ----------------------------------------------------------- class SequenceOfType (SeqOfType): def to_python (self, ctx): # name, tag (None for no tag, EXPLICIT() for explicit), typ) # or '' + (1,) for optional sizestr = '' if self.size_constr != None: print("#Ignoring size constraint:", self.size_constr.subtype) return "%sasn1.SEQUENCE_OF (%s%s)" % (ctx.spaces (), self.val.to_python (ctx), sizestr) def eth_reg_sub(self, ident, ectx): itmnm = ident if not self.val.IsNamed (): itmnm += '/' + ITEM_FIELD_NAME self.val.eth_reg(itmnm, ectx, tstrip=1, idx='[##]', parent=ident) def eth_tname(self): if self.val.type != 'Type_Ref': return '#' + self.type + '_' + str(id(self)) if not self.HasConstraint(): return "SEQUENCE_OF_" + self.val.eth_tname() elif self.constr.IsSize(): return 'SEQUENCE_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname() else: return '#' + self.type + '_' + str(id(self)) def eth_ftype(self, ectx): return ('FT_UINT32', 'BASE_DEC') def eth_need_tree(self): return True def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence_of' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasSizeConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_sequence_of', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) elif (ectx.Per() and not self.HasConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',),)) elif (ectx.Per() and self.constr.type == 'Size'): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_sequence_of', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',), ('%(MIN_VAL)s', '%(MAX_VAL)s','%(EXT)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- SetOfType ---------------------------------------------------------------- class SetOfType (SeqOfType): def eth_reg_sub(self, ident, ectx): itmnm = ident if not self.val.IsNamed (): itmnm += '/' + ITEM_FIELD_NAME self.val.eth_reg(itmnm, ectx, tstrip=1, idx='(##)', parent=ident) def eth_tname(self): if self.val.type != 'Type_Ref': return '#' + self.type + '_' + str(id(self)) if not self.HasConstraint(): return "SET_OF_" + self.val.eth_tname() elif self.constr.IsSize(): return 'SET_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname() else: return '#' + self.type + '_' + str(id(self)) def eth_ftype(self, ectx): return ('FT_UINT32', 'BASE_DEC') def eth_need_tree(self): return True def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set_of' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasSizeConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_set_of', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) elif (ectx.Per() and not self.HasConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',),)) elif (ectx.Per() and self.constr.type == 'Size'): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_set_of', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',), ('%(MIN_VAL)s', '%(MAX_VAL)s','%(EXT)s',),)) else: body = '#error Can not decode %s' % (tname) return body def mk_tag_str (ctx, cls, typ, num): # XXX should do conversion to int earlier! val = int (num) typ = typ.upper() if typ == 'DEFAULT': typ = ctx.tags_def return 'asn1.%s(%d,cls=asn1.%s_FLAG)' % (typ, val, cls) # XXX still ned #--- SequenceType ------------------------------------------------------------- class SequenceType (SeqType): def to_python (self, ctx): # name, tag (None for no tag, EXPLICIT() for explicit), typ) # or '' + (1,) for optional # XXX should also collect names for SEQUENCE inside SEQUENCE or # CHOICE or SEQUENCE_OF (where should the SEQUENCE_OF name come # from? for others, element or arm name would be fine) seq_name = getattr (self, 'sequence_name', None) if seq_name == None: seq_name = 'None' else: seq_name = "'" + seq_name + "'" if 'ext_list' in self.__dict__: return "%sasn1.SEQUENCE ([%s], ext=[%s], seq_name = %s)" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx), self.elts_to_py (self.ext_list, ctx), seq_name) else: return "%sasn1.SEQUENCE ([%s]), seq_name = %s" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx), seq_name) def elts_to_py (self, list, ctx): # we have elt_type, val= named_type, maybe default=, optional= # named_type node: either ident = or typ = # need to dismember these in order to generate Python output syntax. ctx.indent () def elt_to_py (e): assert (e.type == 'elt_type') nt = e.val optflag = e.optional #assert (not hasattr (e, 'default')) # XXX add support for DEFAULT! assert (nt.type == 'named_type') tagstr = 'None' identstr = nt.ident if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh tagstr = mk_tag_str (ctx,nt.typ.tag.cls, nt.typ.tag.tag_typ,nt.typ.tag.num) nt = nt.typ return "('%s',%s,%s,%d)" % (identstr, tagstr, nt.typ.to_python (ctx), optflag) indentstr = ",\n" + ctx.spaces () rv = indentstr.join ([elt_to_py (e) for e in list]) ctx.outdent () return rv def eth_need_tree(self): return True def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ExtensionAdditionGroup --------------------------------------------------- class ExtensionAdditionGroup (SeqType): def __init__(self,*args, **kw) : self.parent_ident = None self.parent_tname = None SeqType.__init__ (self,*args, **kw) def eth_omit_field(self): return True def eth_tname(self): if (self.parent_tname and self.IsNamed()): return self.parent_tname + "_" + self.name else: return SeqType.eth_tname(self) def eth_reg_sub(self, ident, ectx): ectx.eth_dummy_eag_field_required() ectx.eth_dep_add(self.parent_ident, ident) SeqType.eth_reg_sub(self, ident, ectx) def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_sequence_eag', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(TABLE)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- SetType ------------------------------------------------------------------ class SetType (SeqType): def eth_need_tree(self): return True def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ChoiceType --------------------------------------------------------------- class ChoiceType (Type): def to_python (self, ctx): # name, tag (None for no tag, EXPLICIT() for explicit), typ) # or '' + (1,) for optional if 'ext_list' in self.__dict__: return "%sasn1.CHOICE ([%s], ext=[%s])" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx), self.elts_to_py (self.ext_list, ctx)) else: return "%sasn1.CHOICE ([%s])" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx)) def elts_to_py (self, list, ctx): ctx.indent () def elt_to_py (nt): assert (nt.type == 'named_type') tagstr = 'None' if hasattr (nt, 'ident'): identstr = nt.ident else: if hasattr (nt.typ, 'val'): identstr = nt.typ.val # XXX, making up name elif hasattr (nt.typ, 'name'): identstr = nt.typ.name else: identstr = ctx.make_new_name () if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh tagstr = mk_tag_str (ctx,nt.typ.tag.cls, nt.typ.tag.tag_typ,nt.typ.tag.num) nt = nt.typ return "('%s',%s,%s)" % (identstr, tagstr, nt.typ.to_python (ctx)) indentstr = ",\n" + ctx.spaces () rv = indentstr.join ([elt_to_py (e) for e in list]) ctx.outdent () return rv def eth_reg_sub(self, ident, ectx): #print "eth_reg_sub(ident='%s')" % (ident) # check if autotag is required autotag = False if (ectx.NeedTags() and (ectx.tag_def == 'AUTOMATIC')): autotag = True for e in (self.elt_list): if e.HasOwnTag(): autotag = False; break; if autotag and hasattr(self, 'ext_list'): for e in (self.ext_list): if e.HasOwnTag(): autotag = False; break; # do autotag if autotag: atag = 0 for e in (self.elt_list): e.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT')) atag += 1 if autotag and hasattr(self, 'ext_list'): for e in (self.ext_list): e.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT')) atag += 1 for e in (self.elt_list): e.eth_reg(ident, ectx, tstrip=1, parent=ident) if ectx.conform.check_item('EXPORTS', ident + '.' + e.name): ectx.eth_sel_req(ident, e.name) if hasattr(self, 'ext_list'): for e in (self.ext_list): e.eth_reg(ident, ectx, tstrip=1, parent=ident) if ectx.conform.check_item('EXPORTS', ident + '.' + e.name): ectx.eth_sel_req(ident, e.name) def sel_item(self, ident, sel, ectx): lst = self.elt_list[:] if hasattr(self, 'ext_list'): lst.extend(self.ext_list) ee = None for e in (self.elt_list): if e.IsNamed() and (e.name == sel): ee = e break if not ee: print("#CHOICE %s does not contain item %s" % (ident, sel)) return ee def sel_req(self, ident, sel, ectx): #print "sel_req(ident='%s', sel=%s)\n%s" % (ident, sel, str(self)) ee = self.sel_item(ident, sel, ectx) if ee: ee.eth_reg(ident, ectx, tstrip=0, selflag=True) def eth_ftype(self, ectx): return ('FT_UINT32', 'BASE_DEC') def eth_ftype_sel(self, sel, ectx): ee = self.sel_item('', sel, ectx) if ee: return ee.eth_ftype(ectx) else: return ('FT_NONE', 'BASE_NONE') def eth_strings(self): return '$$' def eth_need_tree(self): return True def eth_has_vals(self): return True def GetTTag(self, ectx): lst = self.elt_list cls = 'BER_CLASS_ANY/*choice*/' #if hasattr(self, 'ext_list'): # lst.extend(self.ext_list) #if (len(lst) > 0): # cls = lst[0].GetTag(ectx)[0] #for e in (lst): # if (e.GetTag(ectx)[0] != cls): # cls = '-1/*choice*/' return (cls, '-1/*choice*/') def GetTTagSel(self, sel, ectx): ee = self.sel_item('', sel, ectx) if ee: return ee.GetTag(ectx) else: return ('BER_CLASS_ANY/*unknown selection*/', '-1/*unknown selection*/') def IndetermTag(self, ectx): #print "Choice IndetermTag()=%s" % (str(not self.HasOwnTag())) return not self.HasOwnTag() def detect_tagval(self, ectx): tagval = False lst = self.elt_list[:] if hasattr(self, 'ext_list'): lst.extend(self.ext_list) if (len(lst) > 0) and (not ectx.Per() or lst[0].HasOwnTag()): t = lst[0].GetTag(ectx)[0] tagval = True else: t = '' tagval = False if (t == 'BER_CLASS_UNI'): tagval = False for e in (lst): if not ectx.Per() or e.HasOwnTag(): tt = e.GetTag(ectx)[0] else: tt = '' tagval = False if (tt != t): tagval = False return tagval def get_vals(self, ectx): tagval = self.detect_tagval(ectx) vals = [] cnt = 0 for e in (self.elt_list): if (tagval): val = e.GetTag(ectx)[1] else: val = str(cnt) vals.append((val, e.name)) cnt += 1 if hasattr(self, 'ext_list'): for e in (self.ext_list): if (tagval): val = e.GetTag(ectx)[1] else: val = str(cnt) vals.append((val, e.name)) cnt += 1 return vals def eth_type_vals(self, tname, ectx): out = '\n' vals = self.get_vals(ectx) out += ectx.eth_vals(tname, vals) return out def reg_enum_vals(self, tname, ectx): vals = self.get_vals(ectx) for (val, id) in vals: ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id)) def eth_type_enum(self, tname, ectx): out = '\n' vals = self.get_vals(ectx) out += ectx.eth_enum(tname, vals) return out def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['TABLE'] = '%(PROTOP)s%(TNAME)s_choice' return pars def eth_type_default_table(self, ectx, tname): def out_item(val, e, ext, ectx): has_enum = ectx.eth_type[tname]['enum'] & EF_ENUM if (has_enum): vval = ectx.eth_enum_item(tname, e.name) else: vval = val f = fname + '/' + e.name ef = ectx.field[f]['ethname'] t = ectx.eth_hf[ef]['ethtype'] if (ectx.Ber()): opt = '' if (not e.HasOwnTag()): opt = 'BER_FLAGS_NOOWNTAG' elif (e.HasImplicitTag(ectx)): if (opt): opt += '|' opt += 'BER_FLAGS_IMPLTAG' if (not opt): opt = '0' if (ectx.Ber()): (tc, tn) = e.GetTag(ectx) out = ' { %3s, %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \ % (vval, '&'+ectx.eth_hf[ef]['fullname'], tc, tn, opt, ectx.eth_type[t]['proto'], t) elif (ectx.Per()): out = ' { %3s, %-24s, %-23s, dissect_%s_%s },\n' \ % (vval, '&'+ectx.eth_hf[ef]['fullname'], ext, ectx.eth_type[t]['proto'], t) else: out = '' return out # end out_item() #print "eth_type_default_table(tname='%s')" % (tname) fname = ectx.eth_type[tname]['ref'][0] tagval = self.detect_tagval(ectx) table = "static const %(ER)s_choice_t %(TABLE)s[] = {\n" cnt = 0 if hasattr(self, 'ext_list'): ext = 'ASN1_EXTENSION_ROOT' else: ext = 'ASN1_NO_EXTENSIONS' empty_ext_flag = '0' if (len(self.elt_list)==0) and hasattr(self, 'ext_list') and (len(self.ext_list)==0): empty_ext_flag = ext for e in (self.elt_list): if (tagval): val = e.GetTag(ectx)[1] else: val = str(cnt) table += out_item(val, e, ext, ectx) cnt += 1 if hasattr(self, 'ext_list'): for e in (self.ext_list): if (tagval): val = e.GetTag(ectx)[1] else: val = str(cnt) table += out_item(val, e, 'ASN1_NOT_EXTENSION_ROOT', ectx) cnt += 1 if (ectx.Ber()): table += " { 0, NULL, 0, 0, 0, NULL }\n};\n" else: table += " { 0, NULL, %s, NULL }\n};\n" % (empty_ext_flag) return table def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset', par=(('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ETT_INDEX)s', '%(TABLE)s',), ('%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ChoiceValue ---------------------------------------------------- class ChoiceValue (Value): def to_str(self, ectx): return self.val.to_str(ectx) def fld_obj_eq(self, other): return isinstance(other, ChoiceValue) and (self.choice == other.choice) and (str(self.val.val) == str(other.val.val)) #--- EnumeratedType ----------------------------------------------------------- class EnumeratedType (Type): def to_python (self, ctx): def strify_one (named_num): return "%s=%s" % (named_num.ident, named_num.val) return "asn1.ENUM(%s)" % ",".join (map (strify_one, self.val)) def eth_ftype(self, ectx): return ('FT_UINT32', 'BASE_DEC') def eth_strings(self): return '$$' def eth_has_vals(self): return True def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_ENUMERATED') def get_vals_etc(self, ectx): vals = [] lastv = 0 used = {} maxv = 0 root_num = 0 ext_num = 0 map_table = [] for e in (self.val): if e.type == 'NamedNumber': used[int(e.val)] = True for e in (self.val): if e.type == 'NamedNumber': val = int(e.val) else: while lastv in used: lastv += 1 val = lastv used[val] = True vals.append((val, e.ident)) map_table.append(val) root_num += 1 if val > maxv: maxv = val if self.ext is not None: for e in (self.ext): if e.type == 'NamedNumber': used[int(e.val)] = True for e in (self.ext): if e.type == 'NamedNumber': val = int(e.val) else: while lastv in used: lastv += 1 val = lastv used[val] = True vals.append((val, e.ident)) map_table.append(val) ext_num += 1 if val > maxv: maxv = val need_map = False for i in range(len(map_table)): need_map = need_map or (map_table[i] != i) if (not need_map): map_table = None return (vals, root_num, ext_num, map_table) def eth_type_vals(self, tname, ectx): out = '\n' vals = self.get_vals_etc(ectx)[0] out += ectx.eth_vals(tname, vals) return out def reg_enum_vals(self, tname, ectx): vals = self.get_vals_etc(ectx)[0] for (val, id) in vals: ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id)) def eth_type_enum(self, tname, ectx): out = '\n' vals = self.get_vals_etc(ectx)[0] out += ectx.eth_enum(tname, vals) return out def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) (root_num, ext_num, map_table) = self.get_vals_etc(ectx)[1:] if (self.ext != None): ext = 'TRUE' else: ext = 'FALSE' pars['ROOT_NUM'] = str(root_num) pars['EXT'] = ext pars['EXT_NUM'] = str(ext_num) if (map_table): pars['TABLE'] = '%(PROTOP)s%(TNAME)s_value_map' else: pars['TABLE'] = 'NULL' return pars def eth_type_default_table(self, ectx, tname): if (not ectx.Per()): return '' map_table = self.get_vals_etc(ectx)[3] if (map_table == None): return '' table = "static guint32 %(TABLE)s[%(ROOT_NUM)s+%(EXT_NUM)s] = {" table += ", ".join([str(v) for v in map_table]) table += "};\n" return table def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasValueConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_integer', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_enumerated', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(ROOT_NUM)s', '%(VAL_PTR)s', '%(EXT)s', '%(EXT_NUM)s', '%(TABLE)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- EmbeddedPDVType ----------------------------------------------------------- class EmbeddedPDVType (Type): def eth_tname(self): return 'EMBEDDED_PDV' def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_EMBEDDED_PDV') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) if ectx.default_embedded_pdv_cb: pars['TYPE_REF_FN'] = ectx.default_embedded_pdv_cb else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_EmbeddedPDV_Type', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_embedded_pdv', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ExternalType ----------------------------------------------------------- class ExternalType (Type): def eth_tname(self): return 'EXTERNAL' def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) if ectx.default_external_type_cb: pars['TYPE_REF_FN'] = ectx.default_external_type_cb else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- OpenType ----------------------------------------------------------- class OpenType (Type): def to_python (self, ctx): return "asn1.ANY" def single_type(self): if (self.HasConstraint() and self.constr.type == 'Type' and self.constr.subtype.type == 'Type_Ref'): return self.constr.subtype.val return None def eth_reg_sub(self, ident, ectx): t = self.single_type() if t: ectx.eth_dep_add(ident, t) def eth_tname(self): t = self.single_type() if t: return 'OpenType_' + t else: return Type.eth_tname(self) def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_ANY', '0') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['FN_VARIANT'] = ectx.default_opentype_variant t = self.single_type() if t: t = ectx.type[t]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_open_type%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- InstanceOfType ----------------------------------------------------------- class InstanceOfType (Type): def eth_tname(self): return 'INSTANCE_OF' def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) if ectx.default_external_type_cb: pars['TYPE_REF_FN'] = ectx.default_external_type_cb else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),)) elif (ectx.Per()): body = '#error Can not decode %s' % (tname) else: body = '#error Can not decode %s' % (tname) return body #--- AnyType ----------------------------------------------------------- class AnyType (Type): def to_python (self, ctx): return "asn1.ANY" def eth_ftype(self, ectx): return ('FT_NONE', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_ANY', '0') def eth_type_default_body(self, ectx, tname): body = '#error Can not decode %s' % (tname) return body class Literal (Node): def to_python (self, ctx): return self.val #--- NullType ----------------------------------------------------------------- class NullType (Type): def to_python (self, ctx): return 'asn1.NULL' def eth_tname(self): return 'NULL' def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_NULL') def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- NullValue ---------------------------------------------------- class NullValue (Value): def to_str(self, ectx): return 'NULL' #--- RealType ----------------------------------------------------------------- class RealType (Type): def to_python (self, ctx): return 'asn1.REAL' def eth_tname(self): return 'REAL' def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_REAL') def eth_ftype(self, ectx): return ('FT_DOUBLE', 'BASE_NONE') def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- BooleanType -------------------------------------------------------------- class BooleanType (Type): def to_python (self, ctx): return 'asn1.BOOLEAN' def eth_tname(self): return 'BOOLEAN' def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_BOOLEAN') def eth_ftype(self, ectx): return ('FT_BOOLEAN', 'BASE_NONE') def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s'),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- OctetStringType ---------------------------------------------------------- class OctetStringType (Type): def to_python (self, ctx): return 'asn1.OCTSTRING' def eth_tname(self): if not self.HasConstraint(): return 'OCTET_STRING' elif self.constr.type == 'Size': return 'OCTET_STRING' + '_' + self.constr.eth_constrname() else: return '#' + self.type + '_' + str(id(self)) def eth_ftype(self, ectx): return ('FT_BYTES', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_OCTETSTRING') def eth_need_pdu(self, ectx): pdu = None if self.HasContentsConstraint(): t = self.constr.GetContents(ectx) if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')): pdu = { 'type' : t, 'new' : ectx.default_containing_variant == '_pdu_new' } return pdu def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) if self.HasContentsConstraint(): pars['FN_VARIANT'] = ectx.default_containing_variant t = self.constr.GetContents(ectx) if t: if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'): t = ectx.field[t]['ethname'] pars['TYPE_REF_PROTO'] = '' pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s' else: t = ectx.type[t]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasSizeConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_octet_string', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per()): if self.HasContentsConstraint(): body = ectx.eth_fn_call('dissect_%(ER)s_octet_string_containing%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(TYPE_REF_FN)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- CharacterStringType ------------------------------------------------------ class CharacterStringType (Type): def eth_tname(self): if not self.HasConstraint(): return self.eth_tsname() elif self.constr.type == 'Size': return self.eth_tsname() + '_' + self.constr.eth_constrname() else: return '#' + self.type + '_' + str(id(self)) def eth_ftype(self, ectx): return ('FT_STRING', 'BASE_NONE') class RestrictedCharacterStringType (CharacterStringType): def to_python (self, ctx): return 'asn1.' + self.eth_tsname() def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_' + self.eth_tsname()) def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) (pars['STRING_TYPE'], pars['STRING_TAG']) = (self.eth_tsname(), self.GetTTag(ectx)[1]) (pars['ALPHABET'], pars['ALPHABET_LEN']) = self.eth_get_alphabet_constr(ectx) return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasSizeConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_restricted_string', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(STRING_TAG)s'), ('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_restricted_string', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(STRING_TAG)s'), ('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per() and self.HasPermAlph()): body = ectx.eth_fn_call('dissect_%(ER)s_restricted_character_string', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(ALPHABET)s', '%(ALPHABET_LEN)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per()): if (self.eth_tsname() == 'GeneralString'): body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),)) elif (self.eth_tsname() == 'GeneralizedTime'): body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),)) elif (self.eth_tsname() == 'UTCTime'): body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),)) else: body = '#error Can not decode %s' % (tname) return body class BMPStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'BMPString' class GeneralStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'GeneralString' class GraphicStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'GraphicString' class IA5StringType (RestrictedCharacterStringType): def eth_tsname(self): return 'IA5String' class NumericStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'NumericString' class PrintableStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'PrintableString' class TeletexStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'TeletexString' class T61StringType (RestrictedCharacterStringType): def eth_tsname(self): return 'T61String' def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_TeletexString') class UniversalStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'UniversalString' class UTF8StringType (RestrictedCharacterStringType): def eth_tsname(self): return 'UTF8String' class VideotexStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'VideotexString' class VisibleStringType (RestrictedCharacterStringType): def eth_tsname(self): return 'VisibleString' class ISO646StringType (RestrictedCharacterStringType): def eth_tsname(self): return 'ISO646String' def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_VisibleString') class UnrestrictedCharacterStringType (CharacterStringType): def to_python (self, ctx): return 'asn1.UnrestrictedCharacterString' def eth_tsname(self): return 'CHARACTER_STRING' #--- UsefulType --------------------------------------------------------------- class GeneralizedTime (RestrictedCharacterStringType): def eth_tsname(self): return 'GeneralizedTime' def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),)) return body else: return RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname) class UTCTime (RestrictedCharacterStringType): def eth_tsname(self): return 'UTCTime' def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),)) return body else: return RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname) class ObjectDescriptor (RestrictedCharacterStringType): def eth_tsname(self): return 'ObjectDescriptor' def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_object_descriptor', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ObjectIdentifierType ----------------------------------------------------- class ObjectIdentifierType (Type): def to_python (self, ctx): return 'asn1.OBJECT_IDENTIFIER' def eth_tname(self): return 'OBJECT_IDENTIFIER' def eth_ftype(self, ectx): return ('FT_OID', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_OID') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['FN_VARIANT'] = ectx.default_oid_variant return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- ObjectIdentifierValue ---------------------------------------------------- class ObjectIdentifierValue (Value): def get_num(self, path, val): return str(oid_names.get(path + '/' + val, val)) def to_str(self, ectx): out = '' path = '' first = True sep = '' for v in self.comp_list: if isinstance(v, Node) and (v.type == 'name_and_number'): vstr = v.number elif v.isdigit(): vstr = v else: vstr = self.get_num(path, v) if not first and not vstr.isdigit(): vstr = ectx.value_get_val(vstr) if first: if vstr.isdigit(): out += '"' + vstr else: out += ectx.value_get_eth(vstr) + '"' else: out += sep + vstr path += sep + vstr first = False sep = '.' out += '"' return out def get_dep(self): v = self.comp_list[0] if isinstance(v, Node) and (v.type == 'name_and_number'): return None elif v.isdigit(): return None else: vstr = self.get_num('', v) if vstr.isdigit(): return None else: return vstr class NamedNumber(Node): def to_python (self, ctx): return "('%s',%s)" % (self.ident, self.val) class NamedNumListBase(Node): def to_python (self, ctx): return "asn1.%s_class ([%s])" % (self.asn1_typ,",".join ( [x.to_python (ctx) for x in self.named_list])) #--- RelativeOIDType ---------------------------------------------------------- class RelativeOIDType (Type): def eth_tname(self): return 'RELATIVE_OID' def eth_ftype(self, ectx): return ('FT_REL_OID', 'BASE_NONE') def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_RELATIVE_OID') def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['FN_VARIANT'] = ectx.default_oid_variant return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): body = ectx.eth_fn_call('dissect_%(ER)s_relative_oid%(FN_VARIANT)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) elif (ectx.Per()): body = ectx.eth_fn_call('dissect_%(ER)s_relative_oid%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = '#error Can not decode %s' % (tname) return body #--- IntegerType -------------------------------------------------------------- class IntegerType (Type): def to_python (self, ctx): return "asn1.INTEGER_class ([%s])" % (",".join ( [x.to_python (ctx) for x in self.named_list])) def add_named_value(self, ident, val): e = NamedNumber(ident = ident, val = val) if not self.named_list: self.named_list = [] self.named_list.append(e) def eth_tname(self): if self.named_list: return Type.eth_tname(self) if not self.HasConstraint(): return 'INTEGER' elif self.constr.type == 'SingleValue' or self.constr.type == 'ValueRange': return 'INTEGER' + '_' + self.constr.eth_constrname() else: return 'INTEGER' + '_' + self.constr.eth_tname() def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_INTEGER') def eth_ftype(self, ectx): if self.HasConstraint(): if not self.constr.IsNegativ(): if self.constr.Needs64b(ectx): return ('FT_UINT64', 'BASE_DEC') else: return ('FT_UINT32', 'BASE_DEC') if self.constr.Needs64b(ectx): return ('FT_INT64', 'BASE_DEC') return ('FT_INT32', 'BASE_DEC') def eth_strings(self): if (self.named_list): return '$$' else: return 'NULL' def eth_has_vals(self): if (self.named_list): return True else: return False def get_vals(self, ectx): vals = [] for e in (self.named_list): vals.append((int(e.val), e.ident)) return vals def eth_type_vals(self, tname, ectx): if not self.eth_has_vals(): return '' out = '\n' vals = self.get_vals(ectx) out += ectx.eth_vals(tname, vals) return out def reg_enum_vals(self, tname, ectx): vals = self.get_vals(ectx) for (val, id) in vals: ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id)) def eth_type_enum(self, tname, ectx): if not self.eth_has_enum(tname, ectx): return '' out = '\n' vals = self.get_vals(ectx) out += ectx.eth_enum(tname, vals) return out def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) if self.HasValueConstraint(): (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_value_constr(ectx) if (pars['FN_VARIANT'] == '') and self.constr.Needs64b(ectx): if ectx.Ber(): pars['FN_VARIANT'] = '64' else: pars['FN_VARIANT'] = '_64b' return pars def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasValueConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer%(FN_VARIANT)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_integer%(FN_VARIANT)s', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'), ('%(VAL_PTR)s',),)) elif (ectx.Per() and not self.HasValueConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_integer%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s'),)) elif (ectx.Per() and self.HasValueConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(VAL_PTR)s', '%(EXT)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- BitStringType ------------------------------------------------------------ class BitStringType (Type): def to_python (self, ctx): return "asn1.BITSTRING_class ([%s])" % (",".join ( [x.to_python (ctx) for x in self.named_list])) def eth_tname(self): if self.named_list: return Type.eth_tname(self) elif not self.HasConstraint(): return 'BIT_STRING' elif self.constr.IsSize(): return 'BIT_STRING' + '_' + self.constr.eth_constrname() else: return '#' + self.type + '_' + str(id(self)) def GetTTag(self, ectx): return ('BER_CLASS_UNI', 'BER_UNI_TAG_BITSTRING') def eth_ftype(self, ectx): return ('FT_BYTES', 'BASE_NONE') def eth_need_tree(self): return self.named_list def eth_need_pdu(self, ectx): pdu = None if self.HasContentsConstraint(): t = self.constr.GetContents(ectx) if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')): pdu = { 'type' : t, 'new' : ectx.default_containing_variant == '_pdu_new' } return pdu def eth_named_bits(self): bits = [] if (self.named_list): for e in (self.named_list): bits.append((int(e.val), e.ident)) return bits def eth_type_default_pars(self, ectx, tname): pars = Type.eth_type_default_pars(self, ectx, tname) pars['LEN_PTR'] = 'NULL' (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx) if 'ETT_INDEX' not in pars: pars['ETT_INDEX'] = '-1' pars['TABLE'] = 'NULL' if self.eth_named_bits(): pars['TABLE'] = '%(PROTOP)s%(TNAME)s_bits' if self.HasContentsConstraint(): pars['FN_VARIANT'] = ectx.default_containing_variant t = self.constr.GetContents(ectx) if t: if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'): t = ectx.field[t]['ethname'] pars['TYPE_REF_PROTO'] = '' pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s' else: t = ectx.type[t]['ethname'] pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto'] pars['TYPE_REF_TNAME'] = t pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s' else: pars['TYPE_REF_FN'] = 'NULL' return pars def eth_type_default_table(self, ectx, tname): #print "eth_type_default_table(tname='%s')" % (tname) table = '' bits = self.eth_named_bits() if (bits and ectx.Ber()): table = ectx.eth_bits(tname, bits) return table def eth_type_default_body(self, ectx, tname): if (ectx.Ber()): if (ectx.constraints_check and self.HasSizeConstraint()): body = ectx.eth_fn_call('dissect_%(ER)s_constrained_bitstring', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',), ('%(VAL_PTR)s',),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_bitstring', ret='offset', par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'), ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',), ('%(VAL_PTR)s',),)) elif (ectx.Per()): if self.HasContentsConstraint(): body = ectx.eth_fn_call('dissect_%(ER)s_bit_string_containing%(FN_VARIANT)s', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(TYPE_REF_FN)s'),)) else: body = ectx.eth_fn_call('dissect_%(ER)s_bit_string', ret='offset', par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'), ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(VAL_PTR)s', '%(LEN_PTR)s'),)) else: body = '#error Can not decode %s' % (tname) return body #--- BStringValue ------------------------------------------------------------ bstring_tab = { '0000' : '0', '0001' : '1', '0010' : '2', '0011' : '3', '0100' : '4', '0101' : '5', '0110' : '6', '0111' : '7', '1000' : '8', '1001' : '9', '1010' : 'A', '1011' : 'B', '1100' : 'C', '1101' : 'D', '1110' : 'E', '1111' : 'F', } class BStringValue (Value): def to_str(self, ectx): v = self.val[1:-2] if len(v) % 8: v += '0' * (8 - len(v) % 8) vv = '0x' for i in (list(range(0, len(v), 4))): vv += bstring_tab[v[i:i+4]] return vv #--- HStringValue ------------------------------------------------------------ class HStringValue (Value): def to_str(self, ectx): vv = '0x' vv += self.val[1:-2] return vv def __int__(self): return int(self.val[1:-2], 16) #--- FieldSpec ---------------------------------------------------------------- class FieldSpec (Node): def __init__(self,*args, **kw) : self.name = None Node.__init__ (self,*args, **kw) def SetName(self, name): self.name = name def get_repr(self): return ['#UNSUPPORTED_' + self.type] def fld_repr(self): repr = [self.name] repr.extend(self.get_repr()) return repr class TypeFieldSpec (FieldSpec): def get_repr(self): return [] class FixedTypeValueFieldSpec (FieldSpec): def get_repr(self): if isinstance(self.typ, Type_Ref): repr = ['TypeReference', self.typ.val] else: repr = [self.typ.type] return repr class VariableTypeValueFieldSpec (FieldSpec): def get_repr(self): return ['_' + self.type] class FixedTypeValueSetFieldSpec (FieldSpec): def get_repr(self): return ['_' + self.type] class ObjectFieldSpec (FieldSpec): def get_repr(self): return ['ClassReference', self.cls.val] class ObjectSetFieldSpec (FieldSpec): def get_repr(self): return ['ClassReference', self.cls.val] #============================================================================== def p_module_list_1 (t): 'module_list : module_list ModuleDefinition' t[0] = t[1] + [t[2]] def p_module_list_2 (t): 'module_list : ModuleDefinition' t[0] = [t[1]] #--- ITU-T Recommendation X.680 ----------------------------------------------- # 11 ASN.1 lexical items -------------------------------------------------------- # 11.2 Type references def p_type_ref (t): 'type_ref : UCASE_IDENT' t[0] = Type_Ref(val=t[1]) # 11.3 Identifiers def p_identifier (t): 'identifier : LCASE_IDENT' t[0] = t[1] # 11.4 Value references # cause reduce/reduce conflict #def p_valuereference (t): # 'valuereference : LCASE_IDENT' # t[0] = Value_Ref(val=t[1]) # 11.5 Module references def p_modulereference (t): 'modulereference : UCASE_IDENT' t[0] = t[1] # 12 Module definition -------------------------------------------------------- # 12.1 def p_ModuleDefinition (t): 'ModuleDefinition : ModuleIdentifier DEFINITIONS TagDefault ASSIGNMENT ModuleBegin BEGIN ModuleBody END' t[0] = Module (ident = t[1], tag_def = t[3], body = t[7]) def p_ModuleBegin (t): 'ModuleBegin : ' if t[-4].val == 'Remote-Operations-Information-Objects': x880_module_begin() def p_TagDefault_1 (t): '''TagDefault : EXPLICIT TAGS | IMPLICIT TAGS | AUTOMATIC TAGS ''' t[0] = Default_Tags (dfl_tag = t[1]) def p_TagDefault_2 (t): 'TagDefault : ' # 12.2 The "TagDefault" is taken as EXPLICIT TAGS if it is "empty". t[0] = Default_Tags (dfl_tag = 'EXPLICIT') def p_ModuleIdentifier_1 (t): 'ModuleIdentifier : modulereference DefinitiveIdentifier' # name, oid t [0] = Node('module_ident', val = t[1], ident = t[2]) def p_ModuleIdentifier_2 (t): 'ModuleIdentifier : modulereference' # name, oid t [0] = Node('module_ident', val = t[1], ident = None) def p_DefinitiveIdentifier (t): 'DefinitiveIdentifier : ObjectIdentifierValue' t[0] = t[1] #def p_module_ref (t): # 'module_ref : UCASE_IDENT' # t[0] = t[1] def p_ModuleBody_1 (t): 'ModuleBody : Exports Imports AssignmentList' t[0] = Module_Body (exports = t[1], imports = t[2], assign_list = t[3]) def p_ModuleBody_2 (t): 'ModuleBody : ' t[0] = Node ('module_body', exports = [], imports = [], assign_list = []) def p_Exports_1 (t): 'Exports : EXPORTS syms_exported SEMICOLON' t[0] = t[2] def p_Exports_2 (t): 'Exports : EXPORTS ALL SEMICOLON' t[0] = [ 'ALL' ] def p_Exports_3 (t): 'Exports : ' t[0] = [ 'ALL' ] def p_syms_exported_1 (t): 'syms_exported : exp_sym_list' t[0] = t[1] def p_syms_exported_2 (t): 'syms_exported : ' t[0] = [] def p_exp_sym_list_1 (t): 'exp_sym_list : Symbol' t[0] = [t[1]] def p_exp_sym_list_2 (t): 'exp_sym_list : exp_sym_list COMMA Symbol' t[0] = t[1] + [t[3]] def p_Imports_1 (t): 'Imports : importsbegin IMPORTS SymbolsImported SEMICOLON' t[0] = t[3] global lcase_ident_assigned lcase_ident_assigned = {} def p_importsbegin (t): 'importsbegin : ' global lcase_ident_assigned global g_conform lcase_ident_assigned = {} lcase_ident_assigned.update(g_conform.use_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER')) def p_Imports_2 (t): 'Imports : ' t[0] = [] def p_SymbolsImported_1(t): 'SymbolsImported : ' t[0] = [] def p_SymbolsImported_2 (t): 'SymbolsImported : SymbolsFromModuleList' t[0] = t[1] def p_SymbolsFromModuleList_1 (t): 'SymbolsFromModuleList : SymbolsFromModuleList SymbolsFromModule' t[0] = t[1] + [t[2]] def p_SymbolsFromModuleList_2 (t): 'SymbolsFromModuleList : SymbolsFromModule' t[0] = [t[1]] def p_SymbolsFromModule (t): 'SymbolsFromModule : SymbolList FROM GlobalModuleReference' t[0] = Node ('SymbolList', symbol_list = t[1], module = t[3]) for s in (t[0].symbol_list): if (isinstance(s, Value_Ref)): lcase_ident_assigned[s.val] = t[3] import_symbols_from_module(t[0].module, t[0].symbol_list) def import_symbols_from_module(module, symbol_list): if module.val == 'Remote-Operations-Information-Objects': for i in range(len(symbol_list)): s = symbol_list[i] if isinstance(s, Type_Ref) or isinstance(s, Class_Ref): x880_import(s.val) if isinstance(s, Type_Ref) and is_class_ident(s.val): symbol_list[i] = Class_Ref (val = s.val) return for i in range(len(symbol_list)): s = symbol_list[i] if isinstance(s, Type_Ref) and is_class_ident("$%s$%s" % (module.val, s.val)): import_class_from_module(module.val, s.val) if isinstance(s, Type_Ref) and is_class_ident(s.val): symbol_list[i] = Class_Ref (val = s.val) def p_GlobalModuleReference (t): 'GlobalModuleReference : modulereference AssignedIdentifier' t [0] = Node('module_ident', val = t[1], ident = t[2]) def p_AssignedIdentifier_1 (t): 'AssignedIdentifier : ObjectIdentifierValue' t[0] = t[1] def p_AssignedIdentifier_2 (t): 'AssignedIdentifier : LCASE_IDENT_ASSIGNED' t[0] = t[1] def p_AssignedIdentifier_3 (t): 'AssignedIdentifier : ' pass def p_SymbolList_1 (t): 'SymbolList : Symbol' t[0] = [t[1]] def p_SymbolList_2 (t): 'SymbolList : SymbolList COMMA Symbol' t[0] = t[1] + [t[3]] def p_Symbol (t): '''Symbol : Reference | ParameterizedReference''' t[0] = t[1] def p_Reference_1 (t): '''Reference : type_ref | objectclassreference ''' t[0] = t[1] def p_Reference_2 (t): '''Reference : LCASE_IDENT_ASSIGNED | identifier ''' # instead of valuereference wich causes reduce/reduce conflict t[0] = Value_Ref(val=t[1]) def p_AssignmentList_1 (t): 'AssignmentList : AssignmentList Assignment' t[0] = t[1] + [t[2]] def p_AssignmentList_2 (t): 'AssignmentList : Assignment SEMICOLON' t[0] = [t[1]] def p_AssignmentList_3 (t): 'AssignmentList : Assignment' t[0] = [t[1]] def p_Assignment (t): '''Assignment : TypeAssignment | ValueAssignment | ValueSetTypeAssignment | ObjectClassAssignment | ObjectAssignment | ObjectSetAssignment | ParameterizedAssignment | pyquote ''' t[0] = t[1] # 13 Referencing type and value definitions ----------------------------------- # 13.1 def p_DefinedType (t): '''DefinedType : ExternalTypeReference | type_ref | ParameterizedType''' t[0] = t[1] def p_DefinedValue_1(t): '''DefinedValue : ExternalValueReference''' t[0] = t[1] def p_DefinedValue_2(t): '''DefinedValue : identifier ''' # instead of valuereference wich causes reduce/reduce conflict t[0] = Value_Ref(val=t[1]) # 13.6 def p_ExternalTypeReference (t): 'ExternalTypeReference : modulereference DOT type_ref' t[0] = Node ('ExternalTypeReference', module = t[1], typ = t[3]) def p_ExternalValueReference (t): 'ExternalValueReference : modulereference DOT identifier' t[0] = Node ('ExternalValueReference', module = t[1], ident = t[3]) # 15 Assigning types and values ----------------------------------------------- # 15.1 def p_TypeAssignment (t): 'TypeAssignment : UCASE_IDENT ASSIGNMENT Type' t[0] = t[3] t[0].SetName(t[1]) # 15.2 def p_ValueAssignment (t): 'ValueAssignment : LCASE_IDENT ValueType ASSIGNMENT Value' t[0] = ValueAssignment(ident = t[1], typ = t[2], val = t[4]) # only "simple" types are supported to simplify grammer def p_ValueType (t): '''ValueType : type_ref | BooleanType | IntegerType | ObjectIdentifierType | OctetStringType | RealType ''' t[0] = t[1] # 15.6 def p_ValueSetTypeAssignment (t): 'ValueSetTypeAssignment : UCASE_IDENT ValueType ASSIGNMENT ValueSet' t[0] = Node('ValueSetTypeAssignment', name=t[1], typ=t[2], val=t[4]) # 15.7 def p_ValueSet (t): 'ValueSet : lbraceignore rbraceignore' t[0] = None # 16 Definition of types and values ------------------------------------------- # 16.1 def p_Type (t): '''Type : BuiltinType | ReferencedType | ConstrainedType''' t[0] = t[1] # 16.2 def p_BuiltinType (t): '''BuiltinType : AnyType | BitStringType | BooleanType | CharacterStringType | ChoiceType | EmbeddedPDVType | EnumeratedType | ExternalType | InstanceOfType | IntegerType | NullType | ObjectClassFieldType | ObjectIdentifierType | OctetStringType | RealType | RelativeOIDType | SequenceType | SequenceOfType | SetType | SetOfType | TaggedType''' t[0] = t[1] # 16.3 def p_ReferencedType (t): '''ReferencedType : DefinedType | UsefulType | SelectionType''' t[0] = t[1] # 16.5 def p_NamedType (t): 'NamedType : identifier Type' t[0] = t[2] t[0].SetName (t[1]) # 16.7 def p_Value (t): '''Value : BuiltinValue | ReferencedValue | ObjectClassFieldValue''' t[0] = t[1] # 16.9 def p_BuiltinValue (t): '''BuiltinValue : BooleanValue | ChoiceValue | IntegerValue | ObjectIdentifierValue | RealValue | SequenceValue | hex_string | binary_string | char_string''' # XXX we don't support {data} here t[0] = t[1] # 16.11 def p_ReferencedValue (t): '''ReferencedValue : DefinedValue | ValueFromObject''' t[0] = t[1] # 16.13 #def p_NamedValue (t): # 'NamedValue : identifier Value' # t[0] = Node ('NamedValue', ident = t[1], value = t[2]) # 17 Notation for the boolean type -------------------------------------------- # 17.1 def p_BooleanType (t): 'BooleanType : BOOLEAN' t[0] = BooleanType () # 17.2 def p_BooleanValue (t): '''BooleanValue : TRUE | FALSE''' t[0] = t[1] # 18 Notation for the integer type -------------------------------------------- # 18.1 def p_IntegerType_1 (t): 'IntegerType : INTEGER' t[0] = IntegerType (named_list = None) def p_IntegerType_2 (t): 'IntegerType : INTEGER LBRACE NamedNumberList RBRACE' t[0] = IntegerType(named_list = t[3]) def p_NamedNumberList_1 (t): 'NamedNumberList : NamedNumber' t[0] = [t[1]] def p_NamedNumberList_2 (t): 'NamedNumberList : NamedNumberList COMMA NamedNumber' t[0] = t[1] + [t[3]] def p_NamedNumber (t): '''NamedNumber : identifier LPAREN SignedNumber RPAREN | identifier LPAREN DefinedValue RPAREN''' t[0] = NamedNumber(ident = t[1], val = t[3]) def p_SignedNumber_1 (t): 'SignedNumber : NUMBER' t[0] = t [1] def p_SignedNumber_2 (t): 'SignedNumber : MINUS NUMBER' t[0] = '-' + t[2] # 18.9 def p_IntegerValue (t): 'IntegerValue : SignedNumber' t[0] = t [1] # 19 Notation for the enumerated type ----------------------------------------- # 19.1 def p_EnumeratedType (t): 'EnumeratedType : ENUMERATED LBRACE Enumerations RBRACE' t[0] = EnumeratedType (val = t[3]['val'], ext = t[3]['ext']) def p_Enumerations_1 (t): 'Enumerations : Enumeration' t[0] = { 'val' : t[1], 'ext' : None } def p_Enumerations_2 (t): 'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec' t[0] = { 'val' : t[1], 'ext' : [] } def p_Enumerations_3 (t): 'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec COMMA Enumeration' t[0] = { 'val' : t[1], 'ext' : t[6] } def p_Enumeration_1 (t): 'Enumeration : EnumerationItem' t[0] = [t[1]] def p_Enumeration_2 (t): 'Enumeration : Enumeration COMMA EnumerationItem' t[0] = t[1] + [t[3]] def p_EnumerationItem (t): '''EnumerationItem : Identifier | NamedNumber''' t[0] = t[1] def p_Identifier (t): 'Identifier : identifier' t[0] = Node ('Identifier', ident = t[1]) # 20 Notation for the real type ----------------------------------------------- # 20.1 def p_RealType (t): 'RealType : REAL' t[0] = RealType () # 20.6 def p_RealValue (t): '''RealValue : REAL_NUMBER | SpecialRealValue''' t[0] = t [1] def p_SpecialRealValue (t): '''SpecialRealValue : PLUS_INFINITY | MINUS_INFINITY''' t[0] = t[1] # 21 Notation for the bitstring type ------------------------------------------ # 21.1 def p_BitStringType_1 (t): 'BitStringType : BIT STRING' t[0] = BitStringType (named_list = None) def p_BitStringType_2 (t): 'BitStringType : BIT STRING LBRACE NamedBitList RBRACE' t[0] = BitStringType (named_list = t[4]) def p_NamedBitList_1 (t): 'NamedBitList : NamedBit' t[0] = [t[1]] def p_NamedBitList_2 (t): 'NamedBitList : NamedBitList COMMA NamedBit' t[0] = t[1] + [t[3]] def p_NamedBit (t): '''NamedBit : identifier LPAREN NUMBER RPAREN | identifier LPAREN DefinedValue RPAREN''' t[0] = NamedNumber (ident = t[1], val = t[3]) # 22 Notation for the octetstring type ---------------------------------------- # 22.1 def p_OctetStringType (t): 'OctetStringType : OCTET STRING' t[0] = OctetStringType () # 23 Notation for the null type ----------------------------------------------- # 23.1 def p_NullType (t): 'NullType : NULL' t[0] = NullType () # 23.3 def p_NullValue (t): 'NullValue : NULL' t[0] = NullValue () # 24 Notation for sequence types ---------------------------------------------- # 24.1 def p_SequenceType_1 (t): 'SequenceType : SEQUENCE LBRACE RBRACE' t[0] = SequenceType (elt_list = []) def p_SequenceType_2 (t): 'SequenceType : SEQUENCE LBRACE ComponentTypeLists RBRACE' t[0] = SequenceType (elt_list = t[3]['elt_list']) if 'ext_list' in t[3]: t[0].ext_list = t[3]['ext_list'] if 'elt_list2' in t[3]: t[0].elt_list2 = t[3]['elt_list2'] def p_ExtensionAndException_1 (t): 'ExtensionAndException : ELLIPSIS' t[0] = [] def p_OptionalExtensionMarker_1 (t): 'OptionalExtensionMarker : COMMA ELLIPSIS' t[0] = True def p_OptionalExtensionMarker_2 (t): 'OptionalExtensionMarker : ' t[0] = False def p_ComponentTypeLists_1 (t): 'ComponentTypeLists : ComponentTypeList' t[0] = {'elt_list' : t[1]} def p_ComponentTypeLists_2 (t): 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException OptionalExtensionMarker' t[0] = {'elt_list' : t[1], 'ext_list' : []} def p_ComponentTypeLists_3 (t): 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList OptionalExtensionMarker' t[0] = {'elt_list' : t[1], 'ext_list' : t[4]} def p_ComponentTypeLists_4 (t): 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionEndMarker COMMA ComponentTypeList' t[0] = {'elt_list' : t[1], 'ext_list' : [], 'elt_list2' : t[6]} def p_ComponentTypeLists_5 (t): 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList ExtensionEndMarker COMMA ComponentTypeList' t[0] = {'elt_list' : t[1], 'ext_list' : t[4], 'elt_list2' : t[7]} def p_ComponentTypeLists_6 (t): 'ComponentTypeLists : ExtensionAndException OptionalExtensionMarker' t[0] = {'elt_list' : [], 'ext_list' : []} def p_ComponentTypeLists_7 (t): 'ComponentTypeLists : ExtensionAndException ExtensionAdditionList OptionalExtensionMarker' t[0] = {'elt_list' : [], 'ext_list' : t[2]} def p_ExtensionEndMarker (t): 'ExtensionEndMarker : COMMA ELLIPSIS' pass def p_ExtensionAdditionList_1 (t): 'ExtensionAdditionList : COMMA ExtensionAddition' t[0] = [t[2]] def p_ExtensionAdditionList_2 (t): 'ExtensionAdditionList : ExtensionAdditionList COMMA ExtensionAddition' t[0] = t[1] + [t[3]] def p_ExtensionAddition_1 (t): 'ExtensionAddition : ExtensionAdditionGroup' t[0] = Node ('elt_type', val = t[1], optional = 0) def p_ExtensionAddition_2 (t): 'ExtensionAddition : ComponentType' t[0] = t[1] def p_ExtensionAdditionGroup (t): 'ExtensionAdditionGroup : LVERBRACK VersionNumber ComponentTypeList RVERBRACK' t[0] = ExtensionAdditionGroup (ver = t[2], elt_list = t[3]) def p_VersionNumber_1 (t): 'VersionNumber : ' def p_VersionNumber_2 (t): 'VersionNumber : NUMBER COLON' t[0] = t[1] def p_ComponentTypeList_1 (t): 'ComponentTypeList : ComponentType' t[0] = [t[1]] def p_ComponentTypeList_2 (t): 'ComponentTypeList : ComponentTypeList COMMA ComponentType' t[0] = t[1] + [t[3]] def p_ComponentType_1 (t): 'ComponentType : NamedType' t[0] = Node ('elt_type', val = t[1], optional = 0) def p_ComponentType_2 (t): 'ComponentType : NamedType OPTIONAL' t[0] = Node ('elt_type', val = t[1], optional = 1) def p_ComponentType_3 (t): 'ComponentType : NamedType DEFAULT DefaultValue' t[0] = Node ('elt_type', val = t[1], optional = 1, default = t[3]) def p_ComponentType_4 (t): 'ComponentType : COMPONENTS OF Type' t[0] = Node ('components_of', typ = t[3]) def p_DefaultValue_1 (t): '''DefaultValue : ReferencedValue | BooleanValue | ChoiceValue | IntegerValue | RealValue | hex_string | binary_string | char_string | ObjectClassFieldValue''' t[0] = t[1] def p_DefaultValue_2 (t): 'DefaultValue : lbraceignore rbraceignore' t[0] = '' # 24.17 def p_SequenceValue_1 (t): 'SequenceValue : LBRACE RBRACE' t[0] = [] #def p_SequenceValue_2 (t): # 'SequenceValue : LBRACE ComponentValueList RBRACE' # t[0] = t[2] #def p_ComponentValueList_1 (t): # 'ComponentValueList : NamedValue' # t[0] = [t[1]] #def p_ComponentValueList_2 (t): # 'ComponentValueList : ComponentValueList COMMA NamedValue' # t[0] = t[1] + [t[3]] # 25 Notation for sequence-of types ------------------------------------------- # 25.1 def p_SequenceOfType (t): '''SequenceOfType : SEQUENCE OF Type | SEQUENCE OF NamedType''' t[0] = SequenceOfType (val = t[3], size_constr = None) # 26 Notation for set types --------------------------------------------------- # 26.1 def p_SetType_1 (t): 'SetType : SET LBRACE RBRACE' t[0] = SetType (elt_list = []) def p_SetType_2 (t): 'SetType : SET LBRACE ComponentTypeLists RBRACE' t[0] = SetType (elt_list = t[3]['elt_list']) if 'ext_list' in t[3]: t[0].ext_list = t[3]['ext_list'] if 'elt_list2' in t[3]: t[0].elt_list2 = t[3]['elt_list2'] # 27 Notation for set-of types ------------------------------------------------ # 27.1 def p_SetOfType (t): '''SetOfType : SET OF Type | SET OF NamedType''' t[0] = SetOfType (val = t[3]) # 28 Notation for choice types ------------------------------------------------ # 28.1 def p_ChoiceType (t): 'ChoiceType : CHOICE LBRACE AlternativeTypeLists RBRACE' if 'ext_list' in t[3]: t[0] = ChoiceType (elt_list = t[3]['elt_list'], ext_list = t[3]['ext_list']) else: t[0] = ChoiceType (elt_list = t[3]['elt_list']) def p_AlternativeTypeLists_1 (t): 'AlternativeTypeLists : AlternativeTypeList' t[0] = {'elt_list' : t[1]} def p_AlternativeTypeLists_2 (t): 'AlternativeTypeLists : AlternativeTypeList COMMA ExtensionAndException ExtensionAdditionAlternatives OptionalExtensionMarker' t[0] = {'elt_list' : t[1], 'ext_list' : t[4]} def p_ExtensionAdditionAlternatives_1 (t): 'ExtensionAdditionAlternatives : ExtensionAdditionAlternativesList' t[0] = t[1] def p_ExtensionAdditionAlternatives_2 (t): 'ExtensionAdditionAlternatives : ' t[0] = [] def p_ExtensionAdditionAlternativesList_1 (t): 'ExtensionAdditionAlternativesList : COMMA ExtensionAdditionAlternative' t[0] = t[2] def p_ExtensionAdditionAlternativesList_2 (t): 'ExtensionAdditionAlternativesList : ExtensionAdditionAlternativesList COMMA ExtensionAdditionAlternative' t[0] = t[1] + t[3] def p_ExtensionAdditionAlternative_1 (t): 'ExtensionAdditionAlternative : NamedType' t[0] = [t[1]] def p_ExtensionAdditionAlternative_2 (t): 'ExtensionAdditionAlternative : ExtensionAdditionAlternativesGroup' t[0] = t[1] def p_ExtensionAdditionAlternativesGroup (t): 'ExtensionAdditionAlternativesGroup : LVERBRACK VersionNumber AlternativeTypeList RVERBRACK' t[0] = t[3] def p_AlternativeTypeList_1 (t): 'AlternativeTypeList : NamedType' t[0] = [t[1]] def p_AlternativeTypeList_2 (t): 'AlternativeTypeList : AlternativeTypeList COMMA NamedType' t[0] = t[1] + [t[3]] # 28.10 def p_ChoiceValue_1 (t): '''ChoiceValue : identifier COLON Value | identifier COLON NullValue ''' val = t[3] if not isinstance(val, Value): val = Value(val=val) t[0] = ChoiceValue (choice = t[1], val = val) # 29 Notation for selection types # 29.1 def p_SelectionType (t): # 'SelectionType : identifier LT Type' t[0] = SelectionType (typ = t[3], sel = t[1]) # 30 Notation for tagged types ------------------------------------------------ # 30.1 def p_TaggedType_1 (t): 'TaggedType : Tag Type' t[1].mode = 'default' t[0] = t[2] t[0].AddTag(t[1]) def p_TaggedType_2 (t): '''TaggedType : Tag IMPLICIT Type | Tag EXPLICIT Type''' t[1].mode = t[2] t[0] = t[3] t[0].AddTag(t[1]) def p_Tag (t): 'Tag : LBRACK Class ClassNumber RBRACK' t[0] = Tag(cls = t[2], num = t[3]) def p_ClassNumber_1 (t): 'ClassNumber : number' t[0] = t[1] def p_ClassNumber_2 (t): 'ClassNumber : DefinedValue' t[0] = t[1] def p_Class_1 (t): '''Class : UNIVERSAL | APPLICATION | PRIVATE''' t[0] = t[1] def p_Class_2 (t): 'Class :' t[0] = 'CONTEXT' # 31 Notation for the object identifier type ---------------------------------- # 31.1 def p_ObjectIdentifierType (t): 'ObjectIdentifierType : OBJECT IDENTIFIER' t[0] = ObjectIdentifierType() # 31.3 def p_ObjectIdentifierValue (t): 'ObjectIdentifierValue : LBRACE oid_comp_list RBRACE' t[0] = ObjectIdentifierValue (comp_list=t[2]) def p_oid_comp_list_1 (t): 'oid_comp_list : oid_comp_list ObjIdComponents' t[0] = t[1] + [t[2]] def p_oid_comp_list_2 (t): 'oid_comp_list : ObjIdComponents' t[0] = [t[1]] def p_ObjIdComponents (t): '''ObjIdComponents : NameForm | NumberForm | NameAndNumberForm''' t[0] = t[1] def p_NameForm (t): '''NameForm : LCASE_IDENT | LCASE_IDENT_ASSIGNED''' t [0] = t[1] def p_NumberForm (t): '''NumberForm : NUMBER''' # | DefinedValue''' t [0] = t[1] def p_NameAndNumberForm (t): '''NameAndNumberForm : LCASE_IDENT_ASSIGNED LPAREN NumberForm RPAREN | LCASE_IDENT LPAREN NumberForm RPAREN''' t[0] = Node('name_and_number', ident = t[1], number = t[3]) # 32 Notation for the relative object identifier type ------------------------- # 32.1 def p_RelativeOIDType (t): 'RelativeOIDType : RELATIVE_OID' t[0] = RelativeOIDType() # 33 Notation for the embedded-pdv type --------------------------------------- # 33.1 def p_EmbeddedPDVType (t): 'EmbeddedPDVType : EMBEDDED PDV' t[0] = EmbeddedPDVType() # 34 Notation for the external type ------------------------------------------- # 34.1 def p_ExternalType (t): 'ExternalType : EXTERNAL' t[0] = ExternalType() # 36 Notation for character string types -------------------------------------- # 36.1 def p_CharacterStringType (t): '''CharacterStringType : RestrictedCharacterStringType | UnrestrictedCharacterStringType''' t[0] = t[1] # 37 Definition of restricted character string types -------------------------- def p_RestrictedCharacterStringType_1 (t): 'RestrictedCharacterStringType : BMPString' t[0] = BMPStringType () def p_RestrictedCharacterStringType_2 (t): 'RestrictedCharacterStringType : GeneralString' t[0] = GeneralStringType () def p_RestrictedCharacterStringType_3 (t): 'RestrictedCharacterStringType : GraphicString' t[0] = GraphicStringType () def p_RestrictedCharacterStringType_4 (t): 'RestrictedCharacterStringType : IA5String' t[0] = IA5StringType () def p_RestrictedCharacterStringType_5 (t): 'RestrictedCharacterStringType : ISO646String' t[0] = ISO646StringType () def p_RestrictedCharacterStringType_6 (t): 'RestrictedCharacterStringType : NumericString' t[0] = NumericStringType () def p_RestrictedCharacterStringType_7 (t): 'RestrictedCharacterStringType : PrintableString' t[0] = PrintableStringType () def p_RestrictedCharacterStringType_8 (t): 'RestrictedCharacterStringType : TeletexString' t[0] = TeletexStringType () def p_RestrictedCharacterStringType_9 (t): 'RestrictedCharacterStringType : T61String' t[0] = T61StringType () def p_RestrictedCharacterStringType_10 (t): 'RestrictedCharacterStringType : UniversalString' t[0] = UniversalStringType () def p_RestrictedCharacterStringType_11 (t): 'RestrictedCharacterStringType : UTF8String' t[0] = UTF8StringType () def p_RestrictedCharacterStringType_12 (t): 'RestrictedCharacterStringType : VideotexString' t[0] = VideotexStringType () def p_RestrictedCharacterStringType_13 (t): 'RestrictedCharacterStringType : VisibleString' t[0] = VisibleStringType () # 40 Definition of unrestricted character string types ------------------------ # 40.1 def p_UnrestrictedCharacterStringType (t): 'UnrestrictedCharacterStringType : CHARACTER STRING' t[0] = UnrestrictedCharacterStringType () # 41 Notation for types defined in clauses 42 to 44 --------------------------- # 42 Generalized time --------------------------------------------------------- def p_UsefulType_1 (t): 'UsefulType : GeneralizedTime' t[0] = GeneralizedTime() # 43 Universal time ----------------------------------------------------------- def p_UsefulType_2 (t): 'UsefulType : UTCTime' t[0] = UTCTime() # 44 The object descriptor type ----------------------------------------------- def p_UsefulType_3 (t): 'UsefulType : ObjectDescriptor' t[0] = ObjectDescriptor() # 45 Constrained types -------------------------------------------------------- # 45.1 def p_ConstrainedType_1 (t): 'ConstrainedType : Type Constraint' t[0] = t[1] t[0].AddConstraint(t[2]) def p_ConstrainedType_2 (t): 'ConstrainedType : TypeWithConstraint' t[0] = t[1] # 45.5 def p_TypeWithConstraint_1 (t): '''TypeWithConstraint : SET Constraint OF Type | SET SizeConstraint OF Type''' t[0] = SetOfType (val = t[4], constr = t[2]) def p_TypeWithConstraint_2 (t): '''TypeWithConstraint : SEQUENCE Constraint OF Type | SEQUENCE SizeConstraint OF Type''' t[0] = SequenceOfType (val = t[4], constr = t[2]) def p_TypeWithConstraint_3 (t): '''TypeWithConstraint : SET Constraint OF NamedType | SET SizeConstraint OF NamedType''' t[0] = SetOfType (val = t[4], constr = t[2]) def p_TypeWithConstraint_4 (t): '''TypeWithConstraint : SEQUENCE Constraint OF NamedType | SEQUENCE SizeConstraint OF NamedType''' t[0] = SequenceOfType (val = t[4], constr = t[2]) # 45.6 # 45.7 def p_Constraint (t): 'Constraint : LPAREN ConstraintSpec ExceptionSpec RPAREN' t[0] = t[2] def p_ConstraintSpec (t): '''ConstraintSpec : ElementSetSpecs | GeneralConstraint''' t[0] = t[1] # 46 Element set specification ------------------------------------------------ # 46.1 def p_ElementSetSpecs_1 (t): 'ElementSetSpecs : RootElementSetSpec' t[0] = t[1] def p_ElementSetSpecs_2 (t): 'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS' t[0] = t[1] t[0].ext = True def p_ElementSetSpecs_3 (t): 'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS COMMA AdditionalElementSetSpec' t[0] = t[1] t[0].ext = True def p_RootElementSetSpec (t): 'RootElementSetSpec : ElementSetSpec' t[0] = t[1] def p_AdditionalElementSetSpec (t): 'AdditionalElementSetSpec : ElementSetSpec' t[0] = t[1] def p_ElementSetSpec (t): 'ElementSetSpec : Unions' t[0] = t[1] def p_Unions_1 (t): 'Unions : Intersections' t[0] = t[1] def p_Unions_2 (t): 'Unions : UElems UnionMark Intersections' t[0] = Constraint(type = 'Union', subtype = [t[1], t[3]]) def p_UElems (t): 'UElems : Unions' t[0] = t[1] def p_Intersections_1 (t): 'Intersections : IntersectionElements' t[0] = t[1] def p_Intersections_2 (t): 'Intersections : IElems IntersectionMark IntersectionElements' t[0] = Constraint(type = 'Intersection', subtype = [t[1], t[3]]) def p_IElems (t): 'IElems : Intersections' t[0] = t[1] def p_IntersectionElements (t): 'IntersectionElements : Elements' t[0] = t[1] def p_UnionMark (t): '''UnionMark : BAR | UNION''' def p_IntersectionMark (t): '''IntersectionMark : CIRCUMFLEX | INTERSECTION''' # 46.5 def p_Elements_1 (t): 'Elements : SubtypeElements' t[0] = t[1] def p_Elements_2 (t): 'Elements : LPAREN ElementSetSpec RPAREN' t[0] = t[2] # 47 Subtype elements --------------------------------------------------------- # 47.1 General def p_SubtypeElements (t): '''SubtypeElements : SingleValue | ContainedSubtype | ValueRange | PermittedAlphabet | SizeConstraint | TypeConstraint | InnerTypeConstraints | PatternConstraint''' t[0] = t[1] # 47.2 Single value # 47.2.1 def p_SingleValue (t): 'SingleValue : Value' t[0] = Constraint(type = 'SingleValue', subtype = t[1]) # 47.3 Contained subtype # 47.3.1 def p_ContainedSubtype (t): 'ContainedSubtype : Includes Type' t[0] = Constraint(type = 'ContainedSubtype', subtype = t[2]) def p_Includes (t): '''Includes : INCLUDES | ''' # 47.4 Value range # 47.4.1 def p_ValueRange (t): 'ValueRange : LowerEndpoint RANGE UpperEndpoint' t[0] = Constraint(type = 'ValueRange', subtype = [t[1], t[3]]) # 47.4.3 def p_LowerEndpoint_1 (t): 'LowerEndpoint : LowerEndValue' t[0] = t[1] def p_LowerEndpoint_2 (t): 'LowerEndpoint : LowerEndValue LT' t[0] = t[1] # but not inclusive range def p_UpperEndpoint_1 (t): 'UpperEndpoint : UpperEndValue' t[0] = t[1] def p_UpperEndpoint_2 (t): 'UpperEndpoint : LT UpperEndValue' t[0] = t[1] # but not inclusive range # 47.4.4 def p_LowerEndValue (t): '''LowerEndValue : Value | MIN''' t[0] = t[1] # XXX def p_UpperEndValue (t): '''UpperEndValue : Value | MAX''' t[0] = t[1] # 47.5 Size constraint # 47.5.1 def p_SizeConstraint (t): 'SizeConstraint : SIZE Constraint' t[0] = Constraint (type = 'Size', subtype = t[2]) # 47.6 Type constraint # 47.6.1 def p_TypeConstraint (t): 'TypeConstraint : Type' t[0] = Constraint (type = 'Type', subtype = t[1]) # 47.7 Permitted alphabet # 47.7.1 def p_PermittedAlphabet (t): 'PermittedAlphabet : FROM Constraint' t[0] = Constraint (type = 'From', subtype = t[2]) # 47.8 Inner subtyping # 47.8.1 def p_InnerTypeConstraints (t): '''InnerTypeConstraints : WITH COMPONENT SingleTypeConstraint | WITH COMPONENTS MultipleTypeConstraints''' pass # ignore PER invisible constraint # 47.8.3 def p_SingleTypeConstraint (t): 'SingleTypeConstraint : Constraint' t[0] = t[1] # 47.8.4 def p_MultipleTypeConstraints (t): '''MultipleTypeConstraints : FullSpecification | PartialSpecification''' t[0] = t[1] def p_FullSpecification (t): 'FullSpecification : LBRACE TypeConstraints RBRACE' t[0] = t[2] def p_PartialSpecification (t): 'PartialSpecification : LBRACE ELLIPSIS COMMA TypeConstraints RBRACE' t[0] = t[4] def p_TypeConstraints_1 (t): 'TypeConstraints : named_constraint' t [0] = [t[1]] def p_TypeConstraints_2 (t): 'TypeConstraints : TypeConstraints COMMA named_constraint' t[0] = t[1] + [t[3]] def p_named_constraint_1 (t): 'named_constraint : identifier constraint' return Node ('named_constraint', ident = t[1], constr = t[2]) def p_named_constraint_2 (t): 'named_constraint : constraint' return Node ('named_constraint', constr = t[1]) def p_constraint (t): 'constraint : value_constraint presence_constraint' t[0] = Node ('constraint', value = t[1], presence = t[2]) def p_value_constraint_1 (t): 'value_constraint : Constraint' t[0] = t[1] def p_value_constraint_2 (t): 'value_constraint : ' pass def p_presence_constraint_1 (t): '''presence_constraint : PRESENT | ABSENT | OPTIONAL''' t[0] = t[1] def p_presence_constraint_2 (t): '''presence_constraint : ''' pass # 47.9 Pattern constraint # 47.9.1 def p_PatternConstraint (t): 'PatternConstraint : PATTERN Value' t[0] = Constraint (type = 'Pattern', subtype = t[2]) # 49 The exception identifier # 49.4 def p_ExceptionSpec_1 (t): 'ExceptionSpec : EXCLAMATION ExceptionIdentification' pass def p_ExceptionSpec_2 (t): 'ExceptionSpec : ' pass def p_ExceptionIdentification (t): '''ExceptionIdentification : SignedNumber | DefinedValue | Type COLON Value ''' pass # /*-----------------------------------------------------------------------*/ # /* Value Notation Productions */ # /*-----------------------------------------------------------------------*/ def p_binary_string (t): 'binary_string : BSTRING' t[0] = BStringValue(val = t[1]) def p_hex_string (t): 'hex_string : HSTRING' t[0] = HStringValue(val = t[1]) def p_char_string (t): 'char_string : QSTRING' t[0] = t[1] def p_number (t): 'number : NUMBER' t[0] = t[1] #--- ITU-T Recommendation X.208 ----------------------------------------------- # 27 Notation for the any type ------------------------------------------------ # 27.1 def p_AnyType (t): '''AnyType : ANY | ANY DEFINED BY identifier''' t[0] = AnyType() #--- ITU-T Recommendation X.681 ----------------------------------------------- # 7 ASN.1 lexical items ------------------------------------------------------- # 7.1 Information object class references def p_objectclassreference (t): 'objectclassreference : CLASS_IDENT' t[0] = Class_Ref(val=t[1]) # 7.2 Information object references def p_objectreference (t): 'objectreference : LCASE_IDENT' t[0] = t[1] # 7.3 Information object set references #def p_objectsetreference (t): # 'objectsetreference : UCASE_IDENT' # t[0] = t[1] # 7.4 Type field references # ucasefieldreference # 7.5 Value field references # lcasefieldreference # 7.6 Value set field references # ucasefieldreference # 7.7 Object field references # lcasefieldreference # 7.8 Object set field references # ucasefieldreference def p_ucasefieldreference (t): 'ucasefieldreference : AMPERSAND UCASE_IDENT' t[0] = '&' + t[2] def p_lcasefieldreference (t): 'lcasefieldreference : AMPERSAND LCASE_IDENT' t[0] = '&' + t[2] # 8 Referencing definitions # 8.1 def p_DefinedObjectClass (t): '''DefinedObjectClass : objectclassreference | UsefulObjectClassReference''' t[0] = t[1] global obj_class obj_class = t[0].val def p_DefinedObject (t): '''DefinedObject : objectreference''' t[0] = t[1] # 8.4 def p_UsefulObjectClassReference (t): '''UsefulObjectClassReference : TYPE_IDENTIFIER | ABSTRACT_SYNTAX''' t[0] = Class_Ref(val=t[1]) # 9 Information object class definition and assignment # 9.1 def p_ObjectClassAssignment (t): '''ObjectClassAssignment : CLASS_IDENT ASSIGNMENT ObjectClass | UCASE_IDENT ASSIGNMENT ObjectClass''' t[0] = t[3] t[0].SetName(t[1]) if isinstance(t[0], ObjectClassDefn): t[0].reg_types() # 9.2 def p_ObjectClass (t): '''ObjectClass : DefinedObjectClass | ObjectClassDefn | ParameterizedObjectClass ''' t[0] = t[1] # 9.3 def p_ObjectClassDefn (t): '''ObjectClassDefn : CLASS LBRACE FieldSpecs RBRACE | CLASS LBRACE FieldSpecs RBRACE WithSyntaxSpec''' t[0] = ObjectClassDefn(fields = t[3]) def p_FieldSpecs_1 (t): 'FieldSpecs : FieldSpec' t[0] = [t[1]] def p_FieldSpecs_2 (t): 'FieldSpecs : FieldSpecs COMMA FieldSpec' t[0] = t[1] + [t[3]] def p_WithSyntaxSpec (t): 'WithSyntaxSpec : WITH SYNTAX lbraceignore rbraceignore' t[0] = None # 9.4 def p_FieldSpec (t): '''FieldSpec : TypeFieldSpec | FixedTypeValueFieldSpec | VariableTypeValueFieldSpec | FixedTypeValueSetFieldSpec | ObjectFieldSpec | ObjectSetFieldSpec ''' t[0] = t[1] # 9.5 def p_TypeFieldSpec (t): '''TypeFieldSpec : ucasefieldreference | ucasefieldreference TypeOptionalitySpec ''' t[0] = TypeFieldSpec() t[0].SetName(t[1]) def p_TypeOptionalitySpec_1 (t): 'TypeOptionalitySpec ::= OPTIONAL' pass def p_TypeOptionalitySpec_2 (t): 'TypeOptionalitySpec ::= DEFAULT Type' pass # 9.6 def p_FixedTypeValueFieldSpec (t): '''FixedTypeValueFieldSpec : lcasefieldreference Type | lcasefieldreference Type UNIQUE | lcasefieldreference Type ValueOptionalitySpec | lcasefieldreference Type UNIQUE ValueOptionalitySpec ''' t[0] = FixedTypeValueFieldSpec(typ = t[2]) t[0].SetName(t[1]) def p_ValueOptionalitySpec_1 (t): 'ValueOptionalitySpec ::= OPTIONAL' pass def p_ValueOptionalitySpec_2 (t): 'ValueOptionalitySpec ::= DEFAULT Value' pass # 9.8 def p_VariableTypeValueFieldSpec (t): '''VariableTypeValueFieldSpec : lcasefieldreference FieldName | lcasefieldreference FieldName ValueOptionalitySpec ''' t[0] = VariableTypeValueFieldSpec() t[0].SetName(t[1]) # 9.9 def p_FixedTypeValueSetFieldSpec (t): '''FixedTypeValueSetFieldSpec : ucasefieldreference Type | ucasefieldreference Type ValueSetOptionalitySpec ''' t[0] = FixedTypeValueSetFieldSpec() t[0].SetName(t[1]) def p_ValueSetOptionalitySpec_1 (t): 'ValueSetOptionalitySpec ::= OPTIONAL' pass def p_ValueSetOptionalitySpec_2 (t): 'ValueSetOptionalitySpec ::= DEFAULT ValueSet' pass # 9.11 def p_ObjectFieldSpec (t): '''ObjectFieldSpec : lcasefieldreference DefinedObjectClass | lcasefieldreference DefinedObjectClass ObjectOptionalitySpec ''' t[0] = ObjectFieldSpec(cls=t[2]) t[0].SetName(t[1]) global obj_class obj_class = None def p_ObjectOptionalitySpec_1 (t): 'ObjectOptionalitySpec ::= OPTIONAL' pass def p_ObjectOptionalitySpec_2 (t): 'ObjectOptionalitySpec ::= DEFAULT Object' pass # 9.12 def p_ObjectSetFieldSpec (t): '''ObjectSetFieldSpec : ucasefieldreference DefinedObjectClass | ucasefieldreference DefinedObjectClass ObjectSetOptionalitySpec ''' t[0] = ObjectSetFieldSpec(cls=t[2]) t[0].SetName(t[1]) def p_ObjectSetOptionalitySpec_1 (t): 'ObjectSetOptionalitySpec ::= OPTIONAL' pass def p_ObjectSetOptionalitySpec_2 (t): 'ObjectSetOptionalitySpec ::= DEFAULT ObjectSet' pass # 9.13 def p_PrimitiveFieldName (t): '''PrimitiveFieldName : ucasefieldreference | lcasefieldreference ''' t[0] = t[1] # 9.13 def p_FieldName_1 (t): 'FieldName : PrimitiveFieldName' t[0] = t[1] def p_FieldName_2 (t): 'FieldName : FieldName DOT PrimitiveFieldName' t[0] = t[1] + '.' + t[3] # 11 Information object definition and assignment # 11.1 def p_ObjectAssignment (t): 'ObjectAssignment : objectreference DefinedObjectClass ASSIGNMENT Object' t[0] = ObjectAssignment (ident = t[1], cls=t[2].val, val=t[4]) global obj_class obj_class = None # 11.3 def p_Object (t): '''Object : DefinedObject | ObjectDefn | ParameterizedObject''' t[0] = t[1] # 11.4 def p_ObjectDefn (t): 'ObjectDefn : lbraceobject bodyobject rbraceobject' t[0] = t[2] # {...} block of object definition def p_lbraceobject(t): 'lbraceobject : braceobjectbegin LBRACE' t[0] = t[1] def p_braceobjectbegin(t): 'braceobjectbegin : ' global lexer global obj_class if set_class_syntax(obj_class): state = 'INITIAL' else: lexer.level = 1 state = 'braceignore' lexer.push_state(state) def p_rbraceobject(t): 'rbraceobject : braceobjectend RBRACE' t[0] = t[2] def p_braceobjectend(t): 'braceobjectend : ' global lexer lexer.pop_state() set_class_syntax(None) def p_bodyobject_1 (t): 'bodyobject : ' t[0] = { } def p_bodyobject_2 (t): 'bodyobject : cls_syntax_list' t[0] = t[1] def p_cls_syntax_list_1 (t): 'cls_syntax_list : cls_syntax_list cls_syntax' t[0] = t[1] t[0].update(t[2]) def p_cls_syntax_list_2 (t): 'cls_syntax_list : cls_syntax' t[0] = t[1] # X.681 def p_cls_syntax_1 (t): 'cls_syntax : Type IDENTIFIED BY Value' t[0] = { get_class_fieled(' ') : t[1], get_class_fieled(' '.join((t[2], t[3]))) : t[4] } def p_cls_syntax_2 (t): 'cls_syntax : HAS PROPERTY Value' t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] } # X.880 def p_cls_syntax_3 (t): '''cls_syntax : ERRORS ObjectSet | LINKED ObjectSet | RETURN RESULT BooleanValue | SYNCHRONOUS BooleanValue | INVOKE PRIORITY Value | RESULT_PRIORITY Value | PRIORITY Value | ALWAYS RESPONDS BooleanValue | IDEMPOTENT BooleanValue ''' t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] } def p_cls_syntax_4 (t): '''cls_syntax : ARGUMENT Type | RESULT Type | PARAMETER Type ''' t[0] = { get_class_fieled(t[1]) : t[2] } def p_cls_syntax_5 (t): 'cls_syntax : CODE Value' fld = get_class_fieled(t[1]); t[0] = { fld : t[2] } if isinstance(t[2], ChoiceValue): fldt = fld + '.' + t[2].choice t[0][fldt] = t[2] def p_cls_syntax_6 (t): '''cls_syntax : ARGUMENT Type OPTIONAL BooleanValue | RESULT Type OPTIONAL BooleanValue | PARAMETER Type OPTIONAL BooleanValue ''' t[0] = { get_class_fieled(t[1]) : t[2], get_class_fieled(' '.join((t[1], t[3]))) : t[4] } # 12 Information object set definition and assignment # 12.1 def p_ObjectSetAssignment (t): 'ObjectSetAssignment : UCASE_IDENT CLASS_IDENT ASSIGNMENT ObjectSet' t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[2], val=t[4]) # 12.3 def p_ObjectSet (t): 'ObjectSet : lbraceignore rbraceignore' t[0] = None # 14 Notation for the object class field type --------------------------------- # 14.1 def p_ObjectClassFieldType (t): 'ObjectClassFieldType : DefinedObjectClass DOT FieldName' t[0] = get_type_from_class(t[1], t[3]) # 14.6 def p_ObjectClassFieldValue (t): '''ObjectClassFieldValue : OpenTypeFieldVal''' t[0] = t[1] def p_OpenTypeFieldVal (t): '''OpenTypeFieldVal : Type COLON Value | NullType COLON NullValue''' t[0] = t[3] # 15 Information from objects ------------------------------------------------- # 15.1 def p_ValueFromObject (t): 'ValueFromObject : LCASE_IDENT DOT FieldName' t[0] = t[1] + '.' + t[3] # Annex C - The instance-of type ---------------------------------------------- # C.2 def p_InstanceOfType (t): 'InstanceOfType : INSTANCE OF DefinedObjectClass' t[0] = InstanceOfType() # --- tables --- useful_object_class_types = { # Annex A 'TYPE-IDENTIFIER.&id' : lambda : ObjectIdentifierType(), 'TYPE-IDENTIFIER.&Type' : lambda : OpenType(), # Annex B 'ABSTRACT-SYNTAX.&id' : lambda : ObjectIdentifierType(), 'ABSTRACT-SYNTAX.&Type' : lambda : OpenType(), 'ABSTRACT-SYNTAX.&property' : lambda : BitStringType(), } object_class_types = { } object_class_typerefs = { } object_class_classrefs = { } # dummy types class _VariableTypeValueFieldSpec (AnyType): pass class _FixedTypeValueSetFieldSpec (AnyType): pass class_types_creator = { 'BooleanType' : lambda : BooleanType(), 'IntegerType' : lambda : IntegerType(), 'ObjectIdentifierType' : lambda : ObjectIdentifierType(), 'OpenType' : lambda : OpenType(), # dummy types '_VariableTypeValueFieldSpec' : lambda : _VariableTypeValueFieldSpec(), '_FixedTypeValueSetFieldSpec' : lambda : _FixedTypeValueSetFieldSpec(), } class_names = { } x681_syntaxes = { 'TYPE-IDENTIFIER' : { ' ' : '&Type', 'IDENTIFIED' : 'IDENTIFIED', #'BY' : 'BY', 'IDENTIFIED BY' : '&id', }, 'ABSTRACT-SYNTAX' : { ' ' : '&Type', 'IDENTIFIED' : 'IDENTIFIED', #'BY' : 'BY', 'IDENTIFIED BY' : '&id', 'HAS' : 'HAS', 'PROPERTY' : 'PROPERTY', 'HAS PROPERTY' : '&property', }, } class_syntaxes_enabled = { 'TYPE-IDENTIFIER' : True, 'ABSTRACT-SYNTAX' : True, } class_syntaxes = { 'TYPE-IDENTIFIER' : x681_syntaxes['TYPE-IDENTIFIER'], 'ABSTRACT-SYNTAX' : x681_syntaxes['ABSTRACT-SYNTAX'], } class_current_syntax = None def get_syntax_tokens(syntaxes): tokens = { } for s in (syntaxes): for k in (list(syntaxes[s].keys())): if k.find(' ') < 0: tokens[k] = k tokens[k] = tokens[k].replace('-', '_') return list(tokens.values()) tokens = tokens + get_syntax_tokens(x681_syntaxes) def set_class_syntax(syntax): global class_syntaxes_enabled global class_current_syntax #print "set_class_syntax", syntax, class_current_syntax if class_syntaxes_enabled.get(syntax, False): class_current_syntax = syntax return True else: class_current_syntax = None return False def is_class_syntax(name): global class_syntaxes global class_current_syntax #print "is_class_syntax", name, class_current_syntax if not class_current_syntax: return False return name in class_syntaxes[class_current_syntax] def get_class_fieled(name): if not class_current_syntax: return None return class_syntaxes[class_current_syntax][name] def is_class_ident(name): return name in class_names def add_class_ident(name): #print "add_class_ident", name class_names[name] = name def get_type_from_class(cls, fld): flds = fld.split('.') if (isinstance(cls, Class_Ref)): key = cls.val + '.' + flds[0] else: key = cls + '.' + flds[0] if key in object_class_classrefs: return get_type_from_class(object_class_classrefs[key], '.'.join(flds[1:])) if key in object_class_typerefs: return Type_Ref(val=object_class_typerefs[key]) creator = lambda : AnyType() creator = useful_object_class_types.get(key, creator) creator = object_class_types.get(key, creator) return creator() def set_type_to_class(cls, fld, pars): #print "set_type_to_class", cls, fld, pars key = cls + '.' + fld typename = 'OpenType' if (len(pars) > 0): typename = pars[0] else: pars.append(typename) typeref = None if (len(pars) > 1): if (isinstance(pars[1], Class_Ref)): pars[1] = pars[1].val typeref = pars[1] msg = None if key in object_class_types: msg = object_class_types[key]().type if key in object_class_typerefs: msg = "TypeReference " + object_class_typerefs[key] if key in object_class_classrefs: msg = "ClassReference " + object_class_classrefs[key] if msg == ' '.join(pars): msg = None if msg: msg0 = "Can not define CLASS field %s as '%s'\n" % (key, ' '.join(pars)) msg1 = "Already defined as '%s'" % (msg) raise CompError(msg0 + msg1) if (typename == 'ClassReference'): if not typeref: return False object_class_classrefs[key] = typeref return True if (typename == 'TypeReference'): if not typeref: return False object_class_typerefs[key] = typeref return True creator = class_types_creator.get(typename) if creator: object_class_types[key] = creator return True else: return False def import_class_from_module(mod, cls): add_class_ident(cls) mcls = "$%s$%s" % (mod, cls) for k in list(object_class_classrefs.keys()): kk = k.split('.', 1) if kk[0] == mcls: object_class_classrefs[cls + '.' + kk[0]] = object_class_classrefs[k] for k in list(object_class_typerefs.keys()): kk = k.split('.', 1) if kk[0] == mcls: object_class_typerefs[cls + '.' + kk[0]] = object_class_typerefs[k] for k in list(object_class_types.keys()): kk = k.split('.', 1) if kk[0] == mcls: object_class_types[cls + '.' + kk[0]] = object_class_types[k] #--- ITU-T Recommendation X.682 ----------------------------------------------- # 8 General constraint specification ------------------------------------------ # 8.1 def p_GeneralConstraint (t): '''GeneralConstraint : UserDefinedConstraint | TableConstraint | ContentsConstraint''' t[0] = t[1] # 9 User-defined constraints -------------------------------------------------- # 9.1 def p_UserDefinedConstraint (t): 'UserDefinedConstraint : CONSTRAINED BY LBRACE UserDefinedConstraintParameterList RBRACE' t[0] = Constraint(type = 'UserDefined', subtype = t[4]) def p_UserDefinedConstraintParameterList_1 (t): 'UserDefinedConstraintParameterList : ' t[0] = [] def p_UserDefinedConstraintParameterList_2 (t): 'UserDefinedConstraintParameterList : UserDefinedConstraintParameter' t[0] = [t[1]] def p_UserDefinedConstraintParameterList_3 (t): 'UserDefinedConstraintParameterList : UserDefinedConstraintParameterList COMMA UserDefinedConstraintParameter' t[0] = t[1] + [t[3]] # 9.3 def p_UserDefinedConstraintParameter (t): 'UserDefinedConstraintParameter : Type' t[0] = t[1] # 10 Table constraints, including component relation constraints -------------- # 10.3 def p_TableConstraint (t): '''TableConstraint : SimpleTableConstraint | ComponentRelationConstraint''' t[0] = Constraint(type = 'Table', subtype = t[1]) def p_SimpleTableConstraint (t): 'SimpleTableConstraint : LBRACE UCASE_IDENT RBRACE' t[0] = t[2] # 10.7 def p_ComponentRelationConstraint (t): 'ComponentRelationConstraint : LBRACE UCASE_IDENT RBRACE LBRACE AtNotations RBRACE' t[0] = t[2] + str(t[5]) def p_AtNotations_1 (t): 'AtNotations : AtNotation' t[0] = [t[1]] def p_AtNotations_2 (t): 'AtNotations : AtNotations COMMA AtNotation' t[0] = t[1] + [t[3]] def p_AtNotation_1 (t): 'AtNotation : AT ComponentIdList' t[0] = '@' + t[2] def p_AtNotation_2 (t): 'AtNotation : AT DOT Level ComponentIdList' t[0] = '@.' + t[3] + t[4] def p_Level_1 (t): 'Level : DOT Level' t[0] = '.' + t[2] def p_Level_2 (t): 'Level : ' t[0] = '' def p_ComponentIdList_1 (t): 'ComponentIdList : LCASE_IDENT' t[0] = t[1] def p_ComponentIdList_2 (t): 'ComponentIdList : ComponentIdList DOT LCASE_IDENT' t[0] = t[1] + '.' + t[3] # 11 Contents constraints ----------------------------------------------------- # 11.1 def p_ContentsConstraint (t): 'ContentsConstraint : CONTAINING type_ref' t[0] = Constraint(type = 'Contents', subtype = t[2]) #--- ITU-T Recommendation X.683 ----------------------------------------------- # 8 Parameterized assignments ------------------------------------------------- # 8.1 def p_ParameterizedAssignment (t): '''ParameterizedAssignment : ParameterizedTypeAssignment | ParameterizedObjectClassAssignment | ParameterizedObjectAssignment | ParameterizedObjectSetAssignment''' t[0] = t[1] # 8.2 def p_ParameterizedTypeAssignment (t): 'ParameterizedTypeAssignment : UCASE_IDENT ParameterList ASSIGNMENT Type' t[0] = t[4] t[0].SetName(t[1]) # t[0].SetName(t[1] + 'xxx') def p_ParameterizedObjectClassAssignment (t): '''ParameterizedObjectClassAssignment : CLASS_IDENT ParameterList ASSIGNMENT ObjectClass | UCASE_IDENT ParameterList ASSIGNMENT ObjectClass''' t[0] = t[4] t[0].SetName(t[1]) if isinstance(t[0], ObjectClassDefn): t[0].reg_types() def p_ParameterizedObjectAssignment (t): 'ParameterizedObjectAssignment : objectreference ParameterList DefinedObjectClass ASSIGNMENT Object' t[0] = ObjectAssignment (ident = t[1], cls=t[3].val, val=t[5]) global obj_class obj_class = None def p_ParameterizedObjectSetAssignment (t): 'ParameterizedObjectSetAssignment : UCASE_IDENT ParameterList DefinedObjectClass ASSIGNMENT ObjectSet' t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[3].val, val=t[5]) # 8.3 def p_ParameterList (t): 'ParameterList : lbraceignore rbraceignore' #def p_ParameterList (t): # 'ParameterList : LBRACE Parameters RBRACE' # t[0] = t[2] #def p_Parameters_1 (t): # 'Parameters : Parameter' # t[0] = [t[1]] #def p_Parameters_2 (t): # 'Parameters : Parameters COMMA Parameter' # t[0] = t[1] + [t[3]] #def p_Parameter_1 (t): # 'Parameter : Type COLON Reference' # t[0] = [t[1], t[3]] #def p_Parameter_2 (t): # 'Parameter : Reference' # t[0] = t[1] # 9 Referencing parameterized definitions ------------------------------------- # 9.1 def p_ParameterizedReference (t): 'ParameterizedReference : Reference LBRACE RBRACE' t[0] = t[1] #t[0].val += 'xxx' # 9.2 def p_ParameterizedType (t): 'ParameterizedType : type_ref ActualParameterList' t[0] = t[1] #t[0].val += 'xxx' def p_ParameterizedObjectClass (t): 'ParameterizedObjectClass : DefinedObjectClass ActualParameterList' t[0] = t[1] #t[0].val += 'xxx' def p_ParameterizedObject (t): 'ParameterizedObject : DefinedObject ActualParameterList' t[0] = t[1] #t[0].val += 'xxx' # 9.5 def p_ActualParameterList (t): 'ActualParameterList : lbraceignore rbraceignore' #def p_ActualParameterList (t): # 'ActualParameterList : LBRACE ActualParameters RBRACE' # t[0] = t[2] #def p_ActualParameters_1 (t): # 'ActualParameters : ActualParameter' # t[0] = [t[1]] #def p_ActualParameters_2 (t): # 'ActualParameters : ActualParameters COMMA ActualParameter' # t[0] = t[1] + [t[3]] #def p_ActualParameter (t): # '''ActualParameter : Type # | Value''' # t[0] = t[1] #--- ITU-T Recommendation X.880 ----------------------------------------------- x880_classes = { 'OPERATION' : { '&ArgumentType' : [], '&argumentTypeOptional' : [ 'BooleanType' ], '&returnResult' : [ 'BooleanType' ], '&ResultType' : [], '&resultTypeOptional' : [ 'BooleanType' ], '&Errors' : [ 'ClassReference', 'ERROR' ], '&Linked' : [ 'ClassReference', 'OPERATION' ], '&synchronous' : [ 'BooleanType' ], '&idempotent' : [ 'BooleanType' ], '&alwaysReturns' : [ 'BooleanType' ], '&InvokePriority' : [ '_FixedTypeValueSetFieldSpec' ], '&ResultPriority' : [ '_FixedTypeValueSetFieldSpec' ], '&operationCode' : [ 'TypeReference', 'Code' ], }, 'ERROR' : { '&ParameterType' : [], '&parameterTypeOptional' : [ 'BooleanType' ], '&ErrorPriority' : [ '_FixedTypeValueSetFieldSpec' ], '&errorCode' : [ 'TypeReference', 'Code' ], }, 'OPERATION-PACKAGE' : { '&Both' : [ 'ClassReference', 'OPERATION' ], '&Consumer' : [ 'ClassReference', 'OPERATION' ], '&Supplier' : [ 'ClassReference', 'OPERATION' ], '&id' : [ 'ObjectIdentifierType' ], }, 'CONNECTION-PACKAGE' : { '&bind' : [ 'ClassReference', 'OPERATION' ], '&unbind' : [ 'ClassReference', 'OPERATION' ], '&responderCanUnbind' : [ 'BooleanType' ], '&unbindCanFail' : [ 'BooleanType' ], '&id' : [ 'ObjectIdentifierType' ], }, 'CONTRACT' : { '&connection' : [ 'ClassReference', 'CONNECTION-PACKAGE' ], '&OperationsOf' : [ 'ClassReference', 'OPERATION-PACKAGE' ], '&InitiatorConsumerOf' : [ 'ClassReference', 'OPERATION-PACKAGE' ], '&InitiatorSupplierOf' : [ 'ClassReference', 'OPERATION-PACKAGE' ], '&id' : [ 'ObjectIdentifierType' ], }, 'ROS-OBJECT-CLASS' : { '&Is' : [ 'ClassReference', 'ROS-OBJECT-CLASS' ], '&Initiates' : [ 'ClassReference', 'CONTRACT' ], '&Responds' : [ 'ClassReference', 'CONTRACT' ], '&InitiatesAndResponds' : [ 'ClassReference', 'CONTRACT' ], '&id' : [ 'ObjectIdentifierType' ], }, } x880_syntaxes = { 'OPERATION' : { 'ARGUMENT' : '&ArgumentType', 'ARGUMENT OPTIONAL' : '&argumentTypeOptional', 'RESULT' : '&ResultType', 'RESULT OPTIONAL' : '&resultTypeOptional', 'RETURN' : 'RETURN', 'RETURN RESULT' : '&returnResult', 'ERRORS' : '&Errors', 'LINKED' : '&Linked', 'SYNCHRONOUS' : '&synchronous', 'IDEMPOTENT' : '&idempotent', 'ALWAYS' : 'ALWAYS', 'RESPONDS' : 'RESPONDS', 'ALWAYS RESPONDS' : '&alwaysReturns', 'INVOKE' : 'INVOKE', 'PRIORITY' : 'PRIORITY', 'INVOKE PRIORITY' : '&InvokePriority', 'RESULT-PRIORITY': '&ResultPriority', 'CODE' : '&operationCode', }, 'ERROR' : { 'PARAMETER' : '&ParameterType', 'PARAMETER OPTIONAL' : '&parameterTypeOptional', 'PRIORITY' : '&ErrorPriority', 'CODE' : '&errorCode', }, # 'OPERATION-PACKAGE' : { # }, # 'CONNECTION-PACKAGE' : { # }, # 'CONTRACT' : { # }, # 'ROS-OBJECT-CLASS' : { # }, } def x880_module_begin(): #print "x880_module_begin()" for name in list(x880_classes.keys()): add_class_ident(name) def x880_import(name): if name in x880_syntaxes: class_syntaxes_enabled[name] = True class_syntaxes[name] = x880_syntaxes[name] if name in x880_classes: add_class_ident(name) for f in (list(x880_classes[name].keys())): set_type_to_class(name, f, x880_classes[name][f]) tokens = tokens + get_syntax_tokens(x880_syntaxes) # {...} OID value #def p_lbrace_oid(t): # 'lbrace_oid : brace_oid_begin LBRACE' # t[0] = t[1] #def p_brace_oid_begin(t): # 'brace_oid_begin : ' # global in_oid # in_oid = True #def p_rbrace_oid(t): # 'rbrace_oid : brace_oid_end RBRACE' # t[0] = t[2] #def p_brace_oid_end(t): # 'brace_oid_end : ' # global in_oid # in_oid = False # {...} block to be ignored def p_lbraceignore(t): 'lbraceignore : braceignorebegin LBRACE' t[0] = t[1] def p_braceignorebegin(t): 'braceignorebegin : ' global lexer lexer.level = 1 lexer.push_state('braceignore') def p_rbraceignore(t): 'rbraceignore : braceignoreend RBRACE' t[0] = t[2] def p_braceignoreend(t): 'braceignoreend : ' global lexer lexer.pop_state() def p_error(t): global input_file raise ParseError(t, input_file) def p_pyquote (t): '''pyquote : PYQUOTE''' t[0] = PyQuote (val = t[1]) def testlex (s): lexer.input (s) while True: token = lexer.token () if not token: break print(token) def do_module (ast, defined_dict): assert (ast.type == 'Module') ctx = Ctx (defined_dict) print(ast.to_python (ctx)) print(ctx.output_assignments ()) print(ctx.output_pyquotes ()) def eth_do_module (ast, ectx): assert (ast.type == 'Module') if ectx.dbg('s'): print(ast.str_depth(0)) ast.to_eth(ectx) def testyacc(s, fn, defined_dict): ast = yacc.parse(s, debug=0) time_str = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) print("""#!/usr/bin/env python # Auto-generated from %s at %s from PyZ3950 import asn1""" % (fn, time_str)) for module in ast: eth_do_module (module, defined_dict) # Wireshark compiler def eth_usage(): print(""" asn2wrs [-h|?] [-d dbg] [-b] [-p proto] [-c cnf_file] [-e] input_file(s) ... -h|? : Usage -b : BER (default is PER) -u : Unaligned (default is aligned) -p proto : Protocol name (implies -S). Default is module-name from input_file (renamed by #.MODULE if present) -o name : Output files name core (default is <proto>) -O dir : Output directory for dissector -c cnf_file : Conformance file -I path : Path for conformance file includes -e : Create conformance file for exported types -E : Just create conformance file for exported types -S : Single output for multiple modules -s template : Single file output (template is input file without .c/.h extension) -k : Keep intermediate files though single file output is used -L : Suppress #line directive from .cnf file -D dir : Directory for input_file(s) (default: '.') -C : Add check for SIZE constraints -r prefix : Remove the prefix from type names input_file(s) : Input ASN.1 file(s) -d dbg : Debug output, dbg = [l][y][p][s][a][t][c][m][o] l - lex y - yacc p - parsing s - internal ASN.1 structure a - list of assignments t - tables c - conformance values m - list of compiled modules with dependency o - list of output files """) def eth_main(): global input_file global g_conform global lexer print("ASN.1 to Wireshark dissector compiler"); try: opts, args = getopt.getopt(sys.argv[1:], "h?d:D:buXp:FTo:O:c:I:eESs:kLCr:"); except getopt.GetoptError: eth_usage(); sys.exit(2) if len(args) < 1: eth_usage(); sys.exit(2) conform = EthCnf() conf_to_read = None output = EthOut() ectx = EthCtx(conform, output) ectx.encoding = 'per' ectx.proto_opt = None ectx.fld_opt = {} ectx.tag_opt = False ectx.outnm_opt = None ectx.aligned = True ectx.dbgopt = '' ectx.new = True ectx.expcnf = False ectx.justexpcnf = False ectx.merge_modules = False ectx.group_by_prot = False ectx.conform.last_group = 0 ectx.conform.suppress_line = False; ectx.output.outnm = None ectx.output.single_file = None ectx.constraints_check = False; for o, a in opts: if o in ("-h", "-?"): eth_usage(); sys.exit(2) if o in ("-c",): conf_to_read = a if o in ("-I",): ectx.conform.include_path.append(a) if o in ("-E",): ectx.expcnf = True ectx.justexpcnf = True if o in ("-D",): ectx.srcdir = a if o in ("-C",): ectx.constraints_check = True if o in ("-X",): warnings.warn("Command line option -X is obsolete and can be removed") if o in ("-T",): warnings.warn("Command line option -T is obsolete and can be removed") if conf_to_read: ectx.conform.read(conf_to_read) for o, a in opts: if o in ("-h", "-?", "-c", "-I", "-E", "-D", "-C", "-X", "-T"): pass # already processed else: par = [] if a: par.append(a) ectx.conform.set_opt(o, par, "commandline", 0) (ld, yd, pd) = (0, 0, 0); if ectx.dbg('l'): ld = 1 if ectx.dbg('y'): yd = 1 if ectx.dbg('p'): pd = 2 lexer = lex.lex(debug=ld) yacc.yacc(method='LALR', debug=yd) g_conform = ectx.conform ast = [] for fn in args: input_file = fn lexer.lineno = 1 if (ectx.srcdir): fn = ectx.srcdir + '/' + fn # Read ASN.1 definition, trying one of the common encodings. data = open(fn, "rb").read() for encoding in ('utf-8', 'windows-1252'): try: data = data.decode(encoding) break except: warnings.warn_explicit("Decoding %s as %s failed, trying next." % (fn, encoding), UserWarning, '', 0) # Py2 compat, name.translate in eth_output_hf_arr fails with unicode if not isinstance(data, str): data = data.encode('utf-8') ast.extend(yacc.parse(data, lexer=lexer, debug=pd)) ectx.eth_clean() if (ectx.merge_modules): # common output for all module ectx.eth_clean() for module in ast: eth_do_module(module, ectx) ectx.eth_prepare() ectx.eth_do_output() elif (ectx.groups()): # group by protocols/group groups = [] pr2gr = {} if (ectx.group_by_prot): # group by protocols for module in ast: prot = module.get_proto(ectx) if prot not in pr2gr: pr2gr[prot] = len(groups) groups.append([]) groups[pr2gr[prot]].append(module) else: # group by groups pass for gm in (groups): ectx.eth_clean() for module in gm: eth_do_module(module, ectx) ectx.eth_prepare() ectx.eth_do_output() else: # output for each module for module in ast: ectx.eth_clean() eth_do_module(module, ectx) ectx.eth_prepare() ectx.eth_do_output() if ectx.dbg('m'): ectx.dbg_modules() if ectx.dbg('c'): ectx.conform.dbg_print() if not ectx.justexpcnf: ectx.conform.unused_report() if ectx.dbg('o'): ectx.output.dbg_print() ectx.output.make_single_file() # Python compiler def main(): testfn = testyacc if len (sys.argv) == 1: while True: s = input ('Query: ') if len (s) == 0: break testfn (s, 'console', {}) else: defined_dict = {} for fn in sys.argv [1:]: f = open (fn, "r") testfn (f.read (), fn, defined_dict) f.close () lexer.lineno = 1 #--- BODY --------------------------------------------------------------------- if __name__ == '__main__': if (os.path.splitext(os.path.basename(sys.argv[0]))[0].lower() in ('asn2wrs', 'asn2eth')): eth_main() else: main() #------------------------------------------------------------------------------ # # Editor modelines - http://www.wireshark.org/tools/modelines.html # # c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil # vi: set shiftwidth=4 tabstop=8 expandtab: # :indentSize=4:tabSize=8:noTabs=true:
weinrank/wireshark
tools/asn2wrs.py
Python
gpl-2.0
308,942
#include "Kinetostat.h" #include "ATC_Error.h" #include "ATC_Coupling.h" #include "LammpsInterface.h" #include "PerAtomQuantityLibrary.h" #include "PrescribedDataManager.h" #include "ElasticTimeIntegrator.h" #include "TransferOperator.h" using std::set; using std::pair; using std::string; namespace ATC { //-------------------------------------------------------- //-------------------------------------------------------- // Class Kinetostat //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor //-------------------------------------------------------- Kinetostat::Kinetostat(ATC_Coupling * atc, const string & regulatorPrefix) : AtomicRegulator(atc,regulatorPrefix) { // do nothing } //-------------------------------------------------------- // modify: // parses and adjusts kinetostat state based on // user input, in the style of LAMMPS user input //-------------------------------------------------------- bool Kinetostat::modify(int narg, char **arg) { bool foundMatch = false; int argIndex = 0; if (strcmp(arg[argIndex],"momentum")==0) { argIndex++; // fluxstat type /*! \page man_control_momentum fix_modify AtC control momentum \section syntax fix_modify AtC control momentum none \n fix_modify AtC control momentum rescale <frequency>\n - frequency (int) = time step frequency for applying displacement and velocity rescaling \n fix_modify AtC control momentum glc_displacement \n fix_modify AtC control momentum glc_velocity \n fix_modify AtC control momentum hoover \n fix_modify AtC control momentum flux [faceset face_set_id, interpolate] - face_set_id (string) = id of boundary face set, if not specified (or not possible when the atomic domain does not line up with mesh boundaries) defaults to an atomic-quadrature approximate evaulation\n \section examples fix_modify AtC control momentum glc_velocity \n fix_modify AtC control momentum flux faceset bndy_faces \n \section description \section restrictions only to be used with specific transfers : elastic \n rescale not valid with time filtering activated \section related \section default none */ boundaryIntegrationType_ = NO_QUADRATURE; howOften_ = 1; if (strcmp(arg[argIndex],"none")==0) { // restore defaults regulatorTarget_ = NONE; couplingMode_ = UNCOUPLED; foundMatch = true; } else if (strcmp(arg[argIndex],"glc_displacement")==0) { regulatorTarget_ = FIELD; couplingMode_ = FIXED; foundMatch = true; } else if (strcmp(arg[argIndex],"glc_velocity")==0) { regulatorTarget_ = DERIVATIVE; couplingMode_ = FIXED; foundMatch = true; } else if (strcmp(arg[argIndex],"hoover")==0) { regulatorTarget_ = DYNAMICS; couplingMode_ = FIXED; foundMatch = true; } else if (strcmp(arg[argIndex],"flux")==0) { regulatorTarget_ = DYNAMICS; couplingMode_ = FLUX; argIndex++; boundaryIntegrationType_ = atc_->parse_boundary_integration(narg-argIndex,&arg[argIndex],boundaryFaceSet_); foundMatch = true; } else if (strcmp(arg[argIndex],"ghost_flux")==0) { regulatorTarget_ = DYNAMICS; couplingMode_ = GHOST_FLUX; foundMatch = true; } } if (!foundMatch) foundMatch = AtomicRegulator::modify(narg,arg); if (foundMatch) needReset_ = true; return foundMatch; } //-------------------------------------------------------- // reset_lambda_contribution // resets the kinetostat generated force to a // prescribed value //-------------------------------------------------------- void Kinetostat::reset_lambda_contribution(const DENS_MAT & target) { DENS_MAN * lambdaForceFiltered = regulator_data("LambdaForceFiltered",nsd_); lambdaForceFiltered->set_quantity() = target; } //-------------------------------------------------------- // initialize: // sets up methods before a run // dependence, but in general there is also a // time integrator dependence. In general the // precedence order is: // time filter -> time integrator -> kinetostat // In the future this may need to be added if // different types of time integrators can be // specified. //-------------------------------------------------------- void Kinetostat::construct_methods() { // get data associated with stages 1 & 2 of ATC_Method::initialize AtomicRegulator::construct_methods(); if (atc_->reset_methods()) { // eliminate existing methods delete_method(); DENS_MAT nodalGhostForceFiltered; TimeIntegrator::TimeIntegrationType myIntegrationType = (atc_->time_integrator(VELOCITY))->time_integration_type(); TimeFilterManager * timeFilterManager = atc_->time_filter_manager(); if (timeFilterManager->end_equilibrate() && regulatorTarget_==AtomicRegulator::DYNAMICS) { StressFlux * myMethod; myMethod = dynamic_cast<StressFlux *>(regulatorMethod_); nodalGhostForceFiltered = (myMethod->filtered_ghost_force()).quantity(); } // update time filter if (timeFilterManager->need_reset()) { timeFilter_ = timeFilterManager->construct(TimeFilterManager::IMPLICIT_UPDATE); } if (timeFilterManager->filter_dynamics()) { switch (regulatorTarget_) { case NONE: { regulatorMethod_ = new RegulatorMethod(this); break; } case FIELD: { regulatorMethod_ = new DisplacementGlcFiltered(this); break; } case DERIVATIVE: { regulatorMethod_ = new VelocityGlcFiltered(this); break; } case DYNAMICS: { throw ATC_Error("Kinetostat::initialize - force based kinetostats not yet implemented with time filtering"); regulatorMethod_ = new StressFluxFiltered(this); if (timeFilterManager->end_equilibrate()) { StressFlux * myMethod; myMethod = dynamic_cast<StressFlux *>(regulatorMethod_); myMethod->reset_filtered_ghost_force(nodalGhostForceFiltered); } break; } default: throw ATC_Error("Unknown kinetostat type in Kinetostat::initialize"); } } else { switch (regulatorTarget_) { case NONE: { regulatorMethod_ = new RegulatorMethod(this); break; } case FIELD: { regulatorMethod_ = new DisplacementGlc(this); break; } case DERIVATIVE: { regulatorMethod_ = new VelocityGlc(this); break; } case DYNAMICS: { if (myIntegrationType == TimeIntegrator::FRACTIONAL_STEP) { if (couplingMode_ == GHOST_FLUX) { regulatorMethod_ = new KinetostatFluxGhost(this); } else if (couplingMode_ == FIXED) { regulatorMethod_ = new KinetostatFixed(this); } else if (couplingMode_ == FLUX) { regulatorMethod_ = new KinetostatFlux(this); } break; } if (myIntegrationType == TimeIntegrator::GEAR) { if (couplingMode_ == FIXED) { regulatorMethod_ = new KinetostatFixed(this); } else if (couplingMode_ == FLUX) { regulatorMethod_ = new KinetostatFlux(this); } break; } else { if (couplingMode_ == GHOST_FLUX) { regulatorMethod_ = new StressFluxGhost(this); } else { regulatorMethod_ = new StressFlux(this); } break; } } default: throw ATC_Error("Unknown kinetostat type in Kinetostat::initialize"); } AtomicRegulator::reset_method(); } } else { set_all_data_to_used(); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class KinetostatShapeFunction //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- KinetostatShapeFunction::KinetostatShapeFunction(Kinetostat *kinetostat, const string & regulatorPrefix) : RegulatorShapeFunction(kinetostat,regulatorPrefix), kinetostat_(kinetostat), timeFilter_(atomicRegulator_->time_filter()), nodalAtomicLambdaForce_(NULL), lambdaForceFiltered_(NULL), atomKinetostatForce_(NULL), atomVelocities_(NULL), atomMasses_(NULL) { // data associated with stage 3 in ATC_Method::initialize lambda_ = kinetostat->regulator_data(regulatorPrefix_+"LambdaMomentum",nsd_); lambdaForceFiltered_ = kinetostat_->regulator_data("LambdaForceFiltered",nsd_); } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void KinetostatShapeFunction::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // needed fundamental quantities atomVelocities_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_VELOCITY); atomMasses_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_MASS); // base class transfers RegulatorShapeFunction::construct_transfers(); // lambda interpolated to the atomic coordinates atomLambdas_ = new FtaShapeFunctionProlongation(atc_, lambda_, interscaleManager.per_atom_sparse_matrix("Interpolant")); interscaleManager.add_per_atom_quantity(atomLambdas_, regulatorPrefix_+"AtomLambdaMomentum"); } //-------------------------------------------------------- // set_weights // sets diagonal weighting matrix used in // solve_for_lambda //-------------------------------------------------------- void KinetostatShapeFunction::set_weights() { if (this->use_local_shape_functions()) { ConstantQuantityMapped<double> * myWeights = new ConstantQuantityMapped<double>(atc_,1.,lambdaAtomMap_); weights_ = myWeights; (atc_->interscale_manager()).add_per_atom_quantity(myWeights, "AtomOnesMapped"); } else { weights_ = (atc_->interscale_manager()).per_atom_quantity("AtomicOnes"); if (!weights_) { weights_ = new ConstantQuantity<double>(atc_,1.); (atc_->interscale_manager()).add_per_atom_quantity(weights_, "AtomicOnes"); } } } //-------------------------------------------------------- //-------------------------------------------------------- // Class GlcKinetostat //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- GlcKinetostat::GlcKinetostat(Kinetostat *kinetostat) : KinetostatShapeFunction(kinetostat), mdMassMatrix_(atc_->set_mass_mat_md(VELOCITY)), atomPositions_(NULL) { // do nothing } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void GlcKinetostat::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // needed fundamental quantities atomPositions_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_POSITION); // base class transfers KinetostatShapeFunction::construct_transfers(); } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void GlcKinetostat::initialize() { KinetostatShapeFunction::initialize(); // set up list of nodes using Hoover coupling // (a) nodes with prescribed values PrescribedDataManager * prescribedDataMgr(atc_->prescribed_data_manager()); for (int i = 0; i < nNodes_; ++i) for (int j = 0; j < nsd_; ++j) if (prescribedDataMgr->is_fixed(i,VELOCITY,j)) hooverNodes_.insert(pair<int,int>(i,j)); // (b) AtC coupling nodes if (atomicRegulator_->coupling_mode()==AtomicRegulator::FIXED) { InterscaleManager & interscaleManager(atc_->interscale_manager()); const INT_ARRAY & nodeType((interscaleManager.dense_matrix_int("NodalGeometryType"))->quantity()); if (atomicRegulator_->use_localized_lambda()) { for (int i = 0; i < nNodes_; ++i) { if (nodeType(i,0)==BOUNDARY) { for (int j = 0; j < nsd_; ++j) { hooverNodes_.insert(pair<int,int>(i,j)); } } } } else { for (int i = 0; i < nNodes_; ++i) { if (nodeType(i,0)==BOUNDARY || nodeType(i,0)==MD_ONLY) { for (int j = 0; j < nsd_; ++j) { hooverNodes_.insert(pair<int,int>(i,j)); } } } } } } //-------------------------------------------------------- // apply_lambda_to_atoms // uses existing lambda to modify given // atomic quantity //-------------------------------------------------------- void GlcKinetostat::apply_to_atoms(PerAtomQuantity<double> * quantity, const DENS_MAT & lambdaAtom, double dt) { *quantity -= lambdaAtom; } //-------------------------------------------------------- //-------------------------------------------------------- // Class DisplacementGlc //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- DisplacementGlc::DisplacementGlc(Kinetostat * kinetostat) : GlcKinetostat(kinetostat), nodalAtomicMassWeightedDisplacement_(NULL), nodalDisplacements_(atc_->field(DISPLACEMENT)) { // do nothing } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void DisplacementGlc::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // set up node mappings create_node_maps(); // set up shape function matrix if (this->use_local_shape_functions()) { lambdaAtomMap_ = new AtomToElementset(atc_,elementMask_); interscaleManager.add_per_atom_int_quantity(lambdaAtomMap_, regulatorPrefix_+"LambdaAtomMap"); shapeFunctionMatrix_ = new LocalLambdaCouplingMatrix(atc_, lambdaAtomMap_, nodeToOverlapMap_); } else { shapeFunctionMatrix_ = new LambdaCouplingMatrix(atc_,nodeToOverlapMap_); } interscaleManager.add_per_atom_sparse_matrix(shapeFunctionMatrix_, regulatorPrefix_+"LambdaCouplingMatrixMomentum"); // set linear solver strategy if (atomicRegulator_->use_lumped_lambda_solve()) { linearSolverType_ = AtomicRegulator::RSL_SOLVE; } else { linearSolverType_ = AtomicRegulator::CG_SOLVE; } // base class transfers GlcKinetostat::construct_transfers(); // atomic force induced by kinetostat atomKinetostatForce_ = new AtomicKinetostatForceDisplacement(atc_); interscaleManager.add_per_atom_quantity(atomKinetostatForce_, regulatorPrefix_+"AtomKinetostatForce"); // restricted force due to kinetostat nodalAtomicLambdaForce_ = new AtfShapeFunctionRestriction(atc_, atomKinetostatForce_, interscaleManager.per_atom_sparse_matrix("Interpolant")); interscaleManager.add_dense_matrix(nodalAtomicLambdaForce_, regulatorPrefix_+"NodalAtomicLambdaForce"); // nodal displacement restricted from atoms nodalAtomicMassWeightedDisplacement_ = interscaleManager.dense_matrix("NodalAtomicMassWeightedDisplacement"); } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void DisplacementGlc::initialize() { GlcKinetostat::initialize(); // sets up time filter for cases where variables temporally filtered TimeFilterManager * timeFilterManager = atc_->time_filter_manager(); if (!timeFilterManager->end_equilibrate()) { *lambdaForceFiltered_ = 0.; timeFilter_->initialize(lambdaForceFiltered_->quantity()); } } //-------------------------------------------------------- // apply: // apply the kinetostat to the atoms //-------------------------------------------------------- void DisplacementGlc::apply_post_predictor(double dt) { compute_kinetostat(dt); } //-------------------------------------------------------- // compute_kinetostat // manages the solution and application of the // kinetostat equations and variables //-------------------------------------------------------- void DisplacementGlc::compute_kinetostat(double dt) { // initial filtering update apply_pre_filtering(dt); // set up rhs DENS_MAT rhs(nNodes_,nsd_); set_kinetostat_rhs(rhs,dt); // solve linear system for lambda solve_for_lambda(rhs,lambda_->set_quantity()); // compute nodal atomic power compute_nodal_lambda_force(dt); // apply kinetostat to atoms apply_to_atoms(atomPositions_,atomLambdas_->quantity()); } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the right-hand side of the // kinetostat equations //-------------------------------------------------------- void DisplacementGlc::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // form rhs : sum_a (hatN_Ia * x_ai) - (Upsilon)_Ii rhs = nodalAtomicMassWeightedDisplacement_->quantity(); rhs -= ((atc_->mass_mat_md(VELOCITY)).quantity())*(nodalDisplacements_.quantity()); } //-------------------------------------------------------- // compute_nodal_lambda_force // compute the effective FE force applied // by the kinetostat //-------------------------------------------------------- void DisplacementGlc::compute_nodal_lambda_force(double dt) { const DENS_MAT & myNodalAtomicLambdaForce(nodalAtomicLambdaForce_->quantity()); timeFilter_->apply_post_step1(lambdaForceFiltered_->set_quantity(), myNodalAtomicLambdaForce,dt); // update FE displacements for localized thermostats apply_localization_correction(myNodalAtomicLambdaForce, nodalDisplacements_.set_quantity(), dt*dt); } //-------------------------------------------------------- // apply_pre_filtering // applies first step of filtering to // relevant variables //-------------------------------------------------------- void DisplacementGlc::apply_pre_filtering(double dt) { // apply time filtered lambda force DENS_MAT lambdaZero(nNodes_,nsd_); timeFilter_->apply_pre_step1(lambdaForceFiltered_->set_quantity(),(-1./dt/dt)*lambdaZero,dt); } //-------------------------------------------------------- // set_weights // sets diagonal weighting matrix used in // solve_for_lambda //-------------------------------------------------------- void DisplacementGlc::set_weights() { if (lambdaAtomMap_) { MappedAtomQuantity * myWeights = new MappedAtomQuantity(atc_,atomMasses_,lambdaAtomMap_); weights_ = myWeights; (atc_->interscale_manager()).add_per_atom_quantity(myWeights, "AtomMassesMapped"); } else { weights_ = atomMasses_; } } //-------------------------------------------------------- // apply_localization_correction // corrects for localized kinetostats only // solving kinetostat equations on a subset // of the MD region //-------------------------------------------------------- void DisplacementGlc::apply_localization_correction(const DENS_MAT & source, DENS_MAT & nodalField, double weight) { DENS_MAT nodalLambdaRoc(nNodes_,nsd_); atc_->apply_inverse_mass_matrix(source, nodalLambdaRoc, VELOCITY); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { nodalLambdaRoc(iter->first,iter->second) = 0.; } nodalField += weight*nodalLambdaRoc; } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void DisplacementGlc::output(OUTPUT_LIST & outputData) { _nodalAtomicLambdaForceOut_ = nodalAtomicLambdaForce_->quantity(); DENS_MAT & lambda(lambda_->set_quantity()); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &lambda; outputData[regulatorPrefix_+"NodalLambdaForce"] = &(_nodalAtomicLambdaForceOut_); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class DisplacementGlcFiltered //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- DisplacementGlcFiltered::DisplacementGlcFiltered(Kinetostat * kinetostat) : DisplacementGlc(kinetostat), nodalAtomicDisplacements_(atc_->nodal_atomic_field(DISPLACEMENT)) { // do nothing } //-------------------------------------------------------- // apply_pre_filtering // applies first step of filtering to // relevant variables //-------------------------------------------------------- void DisplacementGlcFiltered::apply_pre_filtering(double dt) { // apply time filtered lambda to atomic fields DisplacementGlc::apply_pre_filtering(dt); DENS_MAT nodalAcceleration(nNodes_,nsd_); atc_->apply_inverse_md_mass_matrix(lambdaForceFiltered_->set_quantity(), nodalAcceleration, VELOCITY); nodalAtomicDisplacements_ += dt*dt*nodalAcceleration; } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the right-hand side of the // kinetostat equations //-------------------------------------------------------- void DisplacementGlcFiltered::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // form rhs : sum_a (hatN_Ia * x_ai) - (Upsilon)_Ii double coef = 1./(timeFilter_->unfiltered_coefficient_pre_s1(dt)); rhs = coef*((atc_->mass_mat_md(VELOCITY)).quantity())*(nodalAtomicDisplacements_.quantity() - nodalDisplacements_.quantity()); } //-------------------------------------------------------- // compute_nodal_lambda_force // compute the effective FE force applied // by the kinetostat //-------------------------------------------------------- void DisplacementGlcFiltered::compute_nodal_lambda_force(double dt) { const DENS_MAT & myNodalAtomicLambdaForce(nodalAtomicLambdaForce_->quantity()); DENS_MAT & myLambdaForceFiltered(lambdaForceFiltered_->set_quantity()); timeFilter_->apply_post_step1(myLambdaForceFiltered, myNodalAtomicLambdaForce,dt); // update filtered atomic displacements DENS_MAT nodalLambdaRoc(myNodalAtomicLambdaForce.nRows(),myNodalAtomicLambdaForce.nCols()); atc_->apply_inverse_md_mass_matrix(myNodalAtomicLambdaForce, nodalLambdaRoc, VELOCITY); timeFilter_->apply_post_step1(nodalAtomicDisplacements_.set_quantity(),dt*dt*nodalLambdaRoc,dt); // update FE displacements for localized thermostats apply_localization_correction(myLambdaForceFiltered, nodalDisplacements_.set_quantity(), dt*dt); } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void DisplacementGlcFiltered::output(OUTPUT_LIST & outputData) { DENS_MAT & lambda(lambda_->set_quantity()); DENS_MAT & lambdaForceFiltered(lambdaForceFiltered_->set_quantity()); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &lambda; outputData[regulatorPrefix_+"NodalLambdaForce"] = &lambdaForceFiltered; } } //-------------------------------------------------------- //-------------------------------------------------------- // Class VelocityGlc //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- VelocityGlc::VelocityGlc(Kinetostat * kinetostat) : GlcKinetostat(kinetostat), nodalAtomicMomentum_(NULL), nodalVelocities_(atc_->field(VELOCITY)) { // do nothing } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void VelocityGlc::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // set up node mappings create_node_maps(); // set up shape function matrix if (this->use_local_shape_functions()) { lambdaAtomMap_ = new AtomToElementset(atc_,elementMask_); interscaleManager.add_per_atom_int_quantity(lambdaAtomMap_, regulatorPrefix_+"LambdaAtomMap"); shapeFunctionMatrix_ = new LocalLambdaCouplingMatrix(atc_, lambdaAtomMap_, nodeToOverlapMap_); } else { shapeFunctionMatrix_ = new LambdaCouplingMatrix(atc_,nodeToOverlapMap_); } interscaleManager.add_per_atom_sparse_matrix(shapeFunctionMatrix_, regulatorPrefix_+"LambdaCouplingMatrixMomentum"); // set linear solver strategy if (atomicRegulator_->use_lumped_lambda_solve()) { linearSolverType_ = AtomicRegulator::RSL_SOLVE; } else { linearSolverType_ = AtomicRegulator::CG_SOLVE; } // base class transfers GlcKinetostat::construct_transfers(); // atomic force induced by kinetostat atomKinetostatForce_ = new AtomicKinetostatForceVelocity(atc_); interscaleManager.add_per_atom_quantity(atomKinetostatForce_, regulatorPrefix_+"AtomKinetostatForce"); // restricted force due to kinetostat nodalAtomicLambdaForce_ = new AtfShapeFunctionRestriction(atc_, atomKinetostatForce_, interscaleManager.per_atom_sparse_matrix("Interpolant")); interscaleManager.add_dense_matrix(nodalAtomicLambdaForce_, regulatorPrefix_+"NodalAtomicLambdaForce"); // nodal momentum restricted from atoms nodalAtomicMomentum_ = interscaleManager.dense_matrix("NodalAtomicMomentum"); } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void VelocityGlc::initialize() { GlcKinetostat::initialize(); // sets up time filter for cases where variables temporally filtered TimeFilterManager * timeFilterManager = atc_->time_filter_manager(); if (!timeFilterManager->end_equilibrate()) { lambdaForceFiltered_->set_quantity() = 0.; timeFilter_->initialize(lambdaForceFiltered_->quantity()); } } //-------------------------------------------------------- // apply_mid_corrector: // apply the kinetostat during the middle of the // predictor phase //-------------------------------------------------------- void VelocityGlc::apply_mid_predictor(double dt) { double dtLambda = 0.5*dt; compute_kinetostat(dtLambda); } //-------------------------------------------------------- // apply_post_corrector: // apply the kinetostat after the corrector phase //-------------------------------------------------------- void VelocityGlc::apply_post_corrector(double dt) { double dtLambda = 0.5*dt; compute_kinetostat(dtLambda); } //-------------------------------------------------------- // apply_pre_filtering // applies first step of filtering to // relevant variables //-------------------------------------------------------- void VelocityGlc::apply_pre_filtering(double dt) { // apply time filtered lambda to atomic fields DENS_MAT lambdaZero(nNodes_,nsd_); timeFilter_->apply_pre_step1(lambdaForceFiltered_->set_quantity(),(-1./dt)*lambdaZero,dt); } //-------------------------------------------------------- // compute_kinetostat // manages the solution and application of the // kinetostat equations and variables //-------------------------------------------------------- void VelocityGlc::compute_kinetostat(double dt) { // initial filtering update apply_pre_filtering(dt); // set up rhs DENS_MAT rhs(nNodes_,nsd_); set_kinetostat_rhs(rhs,dt); // solve linear system for lambda solve_for_lambda(rhs,lambda_->set_quantity()); // compute nodal atomic power compute_nodal_lambda_force(dt); // apply kinetostat to atoms apply_to_atoms(atomVelocities_,atomLambdas_->quantity()); } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the right-hand side of the // kinetostat equations //-------------------------------------------------------- void VelocityGlc::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // form rhs : sum_a (hatN_Ia * x_ai) - (\dot{Upsilon})_Ii rhs = nodalAtomicMomentum_->quantity(); rhs -= ((atc_->mass_mat_md(VELOCITY)).quantity())*(nodalVelocities_.quantity()); } //-------------------------------------------------------- // compute_nodal_lambda_force // compute the effective FE force applied // by the kinetostat //-------------------------------------------------------- void VelocityGlc::compute_nodal_lambda_force(double dt) { const DENS_MAT & myNodalAtomicLambdaForce(nodalAtomicLambdaForce_->quantity()); timeFilter_->apply_pre_step1(lambdaForceFiltered_->set_quantity(), myNodalAtomicLambdaForce,dt); // update FE displacements for localized thermostats apply_localization_correction(myNodalAtomicLambdaForce, nodalVelocities_.set_quantity(), dt); } //-------------------------------------------------------- // set_weights // sets diagonal weighting matrix used in // solve_for_lambda //-------------------------------------------------------- void VelocityGlc::set_weights() { if (lambdaAtomMap_) { MappedAtomQuantity * myWeights = new MappedAtomQuantity(atc_,atomMasses_,lambdaAtomMap_); weights_ = myWeights; (atc_->interscale_manager()).add_per_atom_quantity(myWeights, "AtomMassesMapped"); } else { weights_ = atomMasses_; } } //-------------------------------------------------------- // apply_localization_correction // corrects for localized kinetostats only // solving kinetostat equations on a subset // of the MD region //-------------------------------------------------------- void VelocityGlc::apply_localization_correction(const DENS_MAT & source, DENS_MAT & nodalField, double weight) { DENS_MAT nodalLambdaRoc(nNodes_,nsd_); atc_->apply_inverse_mass_matrix(source, nodalLambdaRoc, VELOCITY); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { nodalLambdaRoc(iter->first,iter->second) = 0.; } nodalField += weight*nodalLambdaRoc; } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void VelocityGlc::output(OUTPUT_LIST & outputData) { _nodalAtomicLambdaForceOut_ = nodalAtomicLambdaForce_->quantity(); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &(lambda_->set_quantity()); outputData[regulatorPrefix_+"NodalLambdaForce"] = &(_nodalAtomicLambdaForceOut_); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class VelocityGlcFiltered //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- VelocityGlcFiltered::VelocityGlcFiltered(Kinetostat *kinetostat) : VelocityGlc(kinetostat), nodalAtomicVelocities_(atc_->nodal_atomic_field(VELOCITY)) { // do nothing } //-------------------------------------------------------- // apply_pre_filtering // applies first step of filtering to // relevant variables //-------------------------------------------------------- void VelocityGlcFiltered::apply_pre_filtering(double dt) { // apply time filtered lambda to atomic fields VelocityGlc::apply_pre_filtering(dt); DENS_MAT nodalAcceleration(nNodes_,nsd_); atc_->apply_inverse_md_mass_matrix(lambdaForceFiltered_->quantity(), nodalAcceleration, VELOCITY); nodalAtomicVelocities_ += dt*nodalAcceleration; } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the right-hand side of the // kinetostat equations //-------------------------------------------------------- void VelocityGlcFiltered::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // form rhs : sum_a (hatN_Ia * x_ai) - (Upsilon)_Ii double coef = 1./(timeFilter_->unfiltered_coefficient_pre_s1(dt)); rhs = coef*((atc_->mass_mat_md(VELOCITY)).quantity())*(nodalAtomicVelocities_.quantity() - nodalVelocities_.quantity()); } //-------------------------------------------------------- // compute_nodal_lambda_force // compute the effective FE force applied // by the kinetostat //-------------------------------------------------------- void VelocityGlcFiltered::compute_nodal_lambda_force(double dt) { const DENS_MAT & myNodalAtomicLambdaForce(nodalAtomicLambdaForce_->quantity()); DENS_MAT & myLambdaForceFiltered(lambdaForceFiltered_->set_quantity()); timeFilter_->apply_post_step1(myLambdaForceFiltered,myNodalAtomicLambdaForce,dt); // update filtered atomic displacements DENS_MAT nodalLambdaRoc(myNodalAtomicLambdaForce.nRows(),myNodalAtomicLambdaForce.nCols()); atc_->apply_inverse_md_mass_matrix(myNodalAtomicLambdaForce, nodalLambdaRoc, VELOCITY); timeFilter_->apply_post_step1(nodalAtomicVelocities_.set_quantity(),dt*nodalLambdaRoc,dt); // update FE displacements for localized thermostats apply_localization_correction(myLambdaForceFiltered, nodalVelocities_.set_quantity(), dt); } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void VelocityGlcFiltered::output(OUTPUT_LIST & outputData) { if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &(lambda_->set_quantity()); outputData[regulatorPrefix_+"NodalLambdaForce"] = &(lambdaForceFiltered_->set_quantity()); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class StressFlux //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- StressFlux::StressFlux(Kinetostat * kinetostat) : GlcKinetostat(kinetostat), nodalForce_(atc_->field_rhs(VELOCITY)), nodalAtomicForce_(NULL), nodalGhostForce_(NULL), momentumSource_(atc_->atomic_source(VELOCITY)) { // flag for performing boundary flux calculation fieldMask_(VELOCITY,FLUX) = true; } StressFlux::~StressFlux() { // do nothing } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void StressFlux::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // set up node mappings create_node_maps(); // set up shape function matrix if (this->use_local_shape_functions()) { lambdaAtomMap_ = new AtomToElementset(atc_,elementMask_); interscaleManager.add_per_atom_int_quantity(lambdaAtomMap_, regulatorPrefix_+"LambdaAtomMap"); shapeFunctionMatrix_ = new LocalLambdaCouplingMatrix(atc_, lambdaAtomMap_, nodeToOverlapMap_); } else { shapeFunctionMatrix_ = new LambdaCouplingMatrix(atc_,nodeToOverlapMap_); } interscaleManager.add_per_atom_sparse_matrix(shapeFunctionMatrix_, regulatorPrefix_+"LambdaCouplingMatrixMomentum"); // set linear solver strategy if (atomicRegulator_->use_lumped_lambda_solve()) { linearSolverType_ = AtomicRegulator::RSL_SOLVE; } else { linearSolverType_ = AtomicRegulator::CG_SOLVE; } // base class transfers GlcKinetostat::construct_transfers(); // force at nodes due to atoms nodalAtomicForce_ = interscaleManager.dense_matrix("NodalAtomicForce"); // atomic force induced by kinetostat atomKinetostatForce_ = new AtomicKinetostatForceStress(atc_,atomLambdas_); interscaleManager.add_per_atom_quantity(atomKinetostatForce_, regulatorPrefix_+"AtomKinetostatForce"); // restricted force due to kinetostat nodalAtomicLambdaForce_ = new AtfShapeFunctionRestriction(atc_, atomKinetostatForce_, interscaleManager.per_atom_sparse_matrix("Interpolant")); interscaleManager.add_dense_matrix(nodalAtomicLambdaForce_, regulatorPrefix_+"NodalAtomicLambdaForce"); // sets up space for ghost force related variables if (atc_->groupbit_ghost()) { GhostCouplingMatrix * shapeFunctionGhost = new GhostCouplingMatrix(atc_,interscaleManager.per_atom_sparse_matrix("InterpolantGhost"), regulatedNodes_,nodeToOverlapMap_); interscaleManager.add_sparse_matrix(shapeFunctionGhost, regulatorPrefix_+"GhostCouplingMatrix"); FundamentalAtomQuantity * atomGhostForce = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_FORCE, GHOST); nodalGhostForce_ = new AtfShapeFunctionRestriction(atc_,atomGhostForce, shapeFunctionGhost); interscaleManager.add_dense_matrix(nodalGhostForce_, regulatorPrefix_+"NodalGhostForce"); nodalGhostForceFiltered_.reset(nNodes_,nsd_); } } //-------------------------------------------------------- // compute_boundary_flux: // computes the boundary flux to be consistent with // the controller //-------------------------------------------------------- void StressFlux::compute_boundary_flux(FIELDS & fields) { GlcKinetostat::compute_boundary_flux(fields); } //-------------------------------------------------------- // apply_pre_predictor: // apply the kinetostat to the atoms in the // mid-predictor integration phase //-------------------------------------------------------- void StressFlux::apply_pre_predictor(double dt) { double dtLambda = 0.5*dt; // apply lambda force to atoms apply_to_atoms(atomVelocities_,atomKinetostatForce_->quantity(),dtLambda); } //-------------------------------------------------------- // apply_post_corrector: // apply the kinetostat to the atoms in the // post-corrector integration phase //-------------------------------------------------------- void StressFlux::apply_post_corrector(double dt) { double dtLambda = 0.5*dt; // apply lambda force to atoms apply_to_atoms(atomVelocities_,atomKinetostatForce_->quantity(),dtLambda); } //-------------------------------------------------------- // compute_kinetostat // manages the solution and application of the // kinetostat equations and variables //-------------------------------------------------------- void StressFlux::compute_kinetostat(double dt) { // initial filtering update apply_pre_filtering(dt); // set up rhs DENS_MAT rhs(nNodes_,nsd_); set_kinetostat_rhs(rhs,dt); // solve linear system for lambda solve_for_lambda(rhs,lambda_->set_quantity()); // compute nodal atomic power compute_nodal_lambda_force(dt); } //-------------------------------------------------------- // apply_pre_filtering // applies first step of filtering to // relevant variables //-------------------------------------------------------- void StressFlux::apply_pre_filtering(double dt) { // apply time filtered lambda force DENS_MAT lambdaZero(nNodes_,nsd_); timeFilter_->apply_pre_step1(lambdaForceFiltered_->set_quantity(),lambdaZero,dt); if (nodalGhostForce_) { timeFilter_->apply_pre_step1(nodalGhostForceFiltered_.set_quantity(), nodalGhostForce_->quantity(),dt); } } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void StressFlux::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // (a) for flux based : // form rhs : \int N_I r dV - \sum_g N_Ig^* f_g // sources are set in ATC transfer rhs.reset(nNodes_,nsd_); rhs = momentumSource_.quantity(); if (nodalGhostForce_) { rhs -= nodalGhostForce_->quantity(); } // (b) for ess. bcs // form rhs : {sum_a (N_Ia * f_ia) - M_md * (ddupsilon/dt)_I} DENS_MAT rhsPrescribed = -1.*nodalForce_.quantity(); atc_->apply_inverse_mass_matrix(rhsPrescribed,VELOCITY); rhsPrescribed = (mdMassMatrix_.quantity())*rhsPrescribed; rhsPrescribed += nodalAtomicForce_->quantity(); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { rhs(iter->first,iter->second) = rhsPrescribed(iter->first,iter->second); } } //-------------------------------------------------------- // compute_nodal_lambda_force // computes the force induced on the FE // by applying lambdaForce on the atoms //-------------------------------------------------------- void StressFlux::compute_nodal_lambda_force(double dt) { DENS_MAT myNodalAtomicLambdaForce = nodalAtomicLambdaForce_->quantity(); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { myNodalAtomicLambdaForce(iter->first,iter->second) = 0.; } timeFilter_->apply_post_step1(lambdaForceFiltered_->set_quantity(), myNodalAtomicLambdaForce,dt); } //-------------------------------------------------------- // add_to_rhs: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void StressFlux::add_to_rhs(FIELDS & rhs) { // compute the kinetostat force compute_kinetostat(atc_->dt()); rhs[VELOCITY] += nodalAtomicLambdaForce_->quantity() + boundaryFlux_[VELOCITY].quantity(); } //-------------------------------------------------------- // apply_lambda_to_atoms // uses existing lambda to modify given // atomic quantity //-------------------------------------------------------- void StressFlux::apply_to_atoms(PerAtomQuantity<double> * atomVelocities, const DENS_MAT & lambdaForce, double dt) { _deltaVelocity_ = lambdaForce; _deltaVelocity_ /= atomMasses_->quantity(); _deltaVelocity_ *= dt; *atomVelocities += _deltaVelocity_; } //-------------------------------------------------------- // reset_filtered_ghost_force: // resets the kinetostat generated ghost force to a // prescribed value //-------------------------------------------------------- void StressFlux::reset_filtered_ghost_force(DENS_MAT & target) { nodalGhostForceFiltered_ = target; } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void StressFlux::output(OUTPUT_LIST & outputData) { _nodalAtomicLambdaForceOut_ = nodalAtomicLambdaForce_->quantity(); DENS_MAT & lambda(lambda_->set_quantity()); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &lambda; outputData[regulatorPrefix_+"NodalLambdaForce"] = &(_nodalAtomicLambdaForceOut_); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class StressFluxGhost //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- StressFluxGhost::StressFluxGhost(Kinetostat * kinetostat) : StressFlux(kinetostat) { // flag for performing boundary flux calculation fieldMask_(VELOCITY,FLUX) = false; } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void StressFluxGhost::construct_transfers() { StressFlux::construct_transfers(); if (!nodalGhostForce_) { throw ATC_Error("StressFluxGhost::StressFluxGhost - ghost atoms must be specified"); } } //-------------------------------------------------------- // compute_boundary_flux: // computes the boundary flux to be consistent with // the controller //-------------------------------------------------------- void StressFluxGhost::compute_boundary_flux(FIELDS & fields) { // This is only used in computation of atomic sources boundaryFlux_[VELOCITY] = 0.; } //-------------------------------------------------------- // add_to_rhs: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void StressFluxGhost::add_to_rhs(FIELDS & rhs) { // compute the kinetostat force compute_kinetostat(atc_->dt()); // uses ghost force as the boundary flux to add to the RHS rhs[VELOCITY] += nodalAtomicLambdaForce_->quantity() + nodalGhostForce_->quantity(); } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void StressFluxGhost::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // (a) for flux based : // form rhs : \int N_I r dV - \sum_g N_Ig^* f_g // sources are set in ATC transfer rhs.reset(nNodes_,nsd_); rhs = momentumSource_.quantity(); // (b) for ess. bcs // form rhs : {sum_a (N_Ia * f_ia) - M_md * (ddupsilon/dt)_I} DENS_MAT rhsPrescribed = -1.*nodalForce_.quantity(); atc_->apply_inverse_mass_matrix(rhsPrescribed,VELOCITY); rhsPrescribed = (mdMassMatrix_.quantity())*rhsPrescribed; rhsPrescribed += nodalAtomicForce_->quantity(); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { rhs(iter->first,iter->second) = rhsPrescribed(iter->first,iter->second); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class StressFluxFiltered //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor //-------------------------------------------------------- StressFluxFiltered::StressFluxFiltered(Kinetostat * kinetostat) : StressFlux(kinetostat), nodalAtomicVelocity_(atc_->nodal_atomic_field(VELOCITY)) { // do nothing } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void StressFluxFiltered::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // set basic terms // (a) for flux based : // form rhs : \int N_I r dV - \sum_g N_Ig^* f_g // sources are set in ATC transfer rhs.reset(nNodes_,nsd_); rhs = momentumSource_.quantity() - nodalGhostForceFiltered_.quantity(); // (b) for ess. bcs // form rhs : {sum_a (N_Ia * f_ia) - M_md * (ddupsilon/dt)_I} DENS_MAT rhsPrescribed = -1.*nodalForce_.quantity(); atc_->apply_inverse_mass_matrix(rhsPrescribed,VELOCITY); rhsPrescribed = (mdMassMatrix_.quantity())*rhsPrescribed; rhsPrescribed += nodalAtomicForce_->quantity(); set<pair<int,int> >::const_iterator iter; for (iter = hooverNodes_.begin(); iter != hooverNodes_.end(); ++iter) { rhs(iter->first,iter->second) = rhsPrescribed(iter->first,iter->second); } // adjust for application of current lambda force rhs += lambdaForceFiltered_->quantity(); // correct for time filtering rhs *= 1./(timeFilter_->unfiltered_coefficient_pre_s1(dt)); } //-------------------------------------------------------- // apply_lambda_to_atoms // uses existing lambda to modify given // atomic quantity //-------------------------------------------------------- void StressFluxFiltered::apply_to_atoms(PerAtomQuantity<double> * atomVelocities, const DENS_MAT & lambdaForce, double dt) { StressFlux::apply_to_atoms(atomVelocities,lambdaForce,dt); // add in corrections to filtered nodal atomice velocity DENS_MAT velocityRoc(nNodes_,nsd_); atc_->apply_inverse_md_mass_matrix(lambdaForceFiltered_->quantity(), velocityRoc, VELOCITY); nodalAtomicVelocity_ += dt*velocityRoc; } //-------------------------------------------------------- // add_to_rhs: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void StressFluxFiltered::add_to_rhs(FIELDS & rhs) { // compute kinetostat forces compute_kinetostat(atc_->dt()); rhs[VELOCITY] += lambdaForceFiltered_->quantity() + boundaryFlux_[VELOCITY].quantity(); } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void StressFluxFiltered::output(OUTPUT_LIST & outputData) { DENS_MAT & lambda(lambda_->set_quantity()); DENS_MAT & lambdaForceFiltered(lambdaForceFiltered_->set_quantity()); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &lambda; outputData[regulatorPrefix_+"NodalLambdaForce"] = &lambdaForceFiltered; } } //-------------------------------------------------------- //-------------------------------------------------------- // Class KinetostatGlcFs //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- KinetostatGlcFs::KinetostatGlcFs(Kinetostat * kinetostat, const string & regulatorPrefix) : KinetostatShapeFunction(kinetostat,regulatorPrefix), velocity_(atc_->field(VELOCITY)) { // constuct/obtain data corresponding to stage 3 of ATC_Method::initialize nodalAtomicLambdaForce_ = kinetostat_->regulator_data(regulatorPrefix_+"NodalAtomicLambdaForce",nsd_); } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void KinetostatGlcFs::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // base class transfers KinetostatShapeFunction::construct_transfers(); // get data from manager nodalAtomicMomentum_ = interscaleManager.dense_matrix("NodalAtomicMomentum"); // atomic force induced by kinetostat PerAtomQuantity<double> * atomLambdas = interscaleManager.per_atom_quantity(regulatorPrefix_+"AtomLambdaMomentum"); atomKinetostatForce_ = new AtomicKinetostatForceStress(atc_,atomLambdas); interscaleManager.add_per_atom_quantity(atomKinetostatForce_, regulatorPrefix_+"AtomKinetostatForce"); } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void KinetostatGlcFs::initialize() { KinetostatShapeFunction::initialize(); // set up workspaces _deltaMomentum_.reset(nNodes_,nsd_); _lambdaForceOutput_.reset(nNodes_,nsd_); TimeFilterManager * timeFilterManager = atc_->time_filter_manager(); if (!timeFilterManager->end_equilibrate()) { // we should reset lambda and lambdaForce to zero in this case // implies an initial condition of 0 for the filtered nodal lambda power // initial conditions will always be needed when using time filtering // however, the fractional step scheme must assume the instantaneous // nodal lambda power is 0 initially because all quantities are in delta form *lambda_ = 0.; // ensures initial lambda force is zero *nodalAtomicLambdaForce_ = 0.; // momentum change due to kinetostat *lambdaForceFiltered_ = 0.; // filtered momentum change due to kinetostats } else { // we can grab lambda power variables using time integrator and atc transfer in cases for equilibration } // sets up time filter for cases where variables temporally filtered if (timeFilterManager->need_reset()) { // the form of this integrator implies no time filters that require history data can be used timeFilter_->initialize(nodalAtomicLambdaForce_->quantity()); } compute_rhs_map(); } //-------------------------------------------------------- // compute_rhs_map // creates mapping from all nodes to those to which // the kinetostat applies //-------------------------------------------------------- void KinetostatGlcFs::compute_rhs_map() { rhsMap_.resize(overlapToNodeMap_->nRows(),1); DENS_MAT rhsMapGlobal(nNodes_,1); const set<int> & applicationNodes(applicationNodes_->quantity()); for (int i = 0; i < nNodes_; i++) { if (applicationNodes.find(i) != applicationNodes.end()) { rhsMapGlobal(i,0) = 1.; } else { rhsMapGlobal(i,0) = 0.; } } map_unique_to_overlap(rhsMapGlobal,rhsMap_); } //-------------------------------------------------------- // apply_pre_predictor: // apply the kinetostat to the atoms in the // pre-predictor integration phase //-------------------------------------------------------- void KinetostatGlcFs::apply_pre_predictor(double dt) { DENS_MAT & lambdaForceFiltered(lambdaForceFiltered_->set_quantity()); DENS_MAT & nodalAtomicLambdaForce(nodalAtomicLambdaForce_->set_quantity()); // update filtered forces timeFilter_->apply_pre_step1(lambdaForceFiltered,nodalAtomicLambdaForce,dt); // apply lambda force to atoms and compute instantaneous lambda force this->apply_to_atoms(atomVelocities_,nodalAtomicMomentum_, atomKinetostatForce_->quantity(), nodalAtomicLambdaForce,0.5*dt); // update nodal variables for first half of timestep this->add_to_momentum(nodalAtomicLambdaForce,_deltaMomentum_,0.5*dt); atc_->apply_inverse_mass_matrix(_deltaMomentum_,VELOCITY); velocity_ += _deltaMomentum_; // start update of filtered lambda force nodalAtomicLambdaForce = 0.; timeFilter_->apply_post_step1(lambdaForceFiltered,nodalAtomicLambdaForce,dt); } //-------------------------------------------------------- // apply_post_corrector: // apply the kinetostat to the atoms in the // post-corrector integration phase //-------------------------------------------------------- void KinetostatGlcFs::apply_post_corrector(double dt) { // compute the kinetostat equation and update lambda this->compute_lambda(dt); DENS_MAT & lambdaForceFiltered(lambdaForceFiltered_->set_quantity()); DENS_MAT & nodalAtomicLambdaForce(nodalAtomicLambdaForce_->set_quantity()); // update filtered force timeFilter_->apply_pre_step1(lambdaForceFiltered,nodalAtomicLambdaForce,dt); // apply lambda force to atoms and compute instantaneous lambda force this->apply_to_atoms(atomVelocities_,nodalAtomicMomentum_, atomKinetostatForce_->quantity(), nodalAtomicLambdaForce,0.5*dt); // update nodal variables for first half of timestep this->add_to_momentum(nodalAtomicLambdaForce,_deltaMomentum_,0.5*dt); nodalAtomicLambdaForce *= 2./dt; atc_->apply_inverse_mass_matrix(_deltaMomentum_,VELOCITY); velocity_ += _deltaMomentum_; // start update of filtered lambda force timeFilter_->apply_post_step2(lambdaForceFiltered,nodalAtomicLambdaForce,dt); } //-------------------------------------------------------- // compute_kinetostat // manages the solution and application of the // kinetostat equations and variables //-------------------------------------------------------- void KinetostatGlcFs::compute_lambda(double dt) { // set up rhs for lambda equation this->set_kinetostat_rhs(rhs_,0.5*dt); // solve linear system for lambda DENS_MAT & lambda(lambda_->set_quantity()); solve_for_lambda(rhs_,lambda); } //-------------------------------------------------------- // apply_lambda_to_atoms // uses existing lambda to modify given // atomic quantity //-------------------------------------------------------- void KinetostatGlcFs::apply_to_atoms(PerAtomQuantity<double> * atomVelocity, const DENS_MAN * nodalAtomicMomentum, const DENS_MAT & lambdaForce, DENS_MAT & nodalAtomicLambdaForce, double dt) { // compute initial contributions to lambda force nodalAtomicLambdaForce = nodalAtomicMomentum->quantity(); nodalAtomicLambdaForce *= -1.; // apply lambda force to atoms _velocityDelta_ = lambdaForce; _velocityDelta_ /= atomMasses_->quantity(); _velocityDelta_ *= dt; (*atomVelocity) += _velocityDelta_; // finalize lambda force nodalAtomicLambdaForce += nodalAtomicMomentum->quantity(); } //-------------------------------------------------------- // output: // adds all relevant output to outputData //-------------------------------------------------------- void KinetostatGlcFs::output(OUTPUT_LIST & outputData) { _lambdaForceOutput_ = nodalAtomicLambdaForce_->quantity(); // approximate value for lambda force double dt = LammpsInterface::instance()->dt(); _lambdaForceOutput_ *= (2./dt); DENS_MAT & lambda(lambda_->set_quantity()); if ((atc_->lammps_interface())->rank_zero()) { outputData[regulatorPrefix_+"Lambda"] = &lambda; outputData[regulatorPrefix_+"NodalLambdaForce"] = &(_lambdaForceOutput_); } } //-------------------------------------------------------- //-------------------------------------------------------- // Class KinetostatFlux //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- KinetostatFlux::KinetostatFlux(Kinetostat * kinetostat, const string & regulatorPrefix) : KinetostatGlcFs(kinetostat,regulatorPrefix), momentumSource_(atc_->atomic_source(VELOCITY)), nodalGhostForce_(NULL), nodalGhostForceFiltered_(NULL) { // flag for performing boundary flux calculation fieldMask_(VELOCITY,FLUX) = true; // constuct/obtain data corresponding to stage 3 of ATC_Method::initialize nodalGhostForceFiltered_ = kinetostat_->regulator_data(regulatorPrefix_+"NodalGhostForceFiltered",nsd_); } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void KinetostatFlux::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // set up node mappings create_node_maps(); // set up linear solver // set up data for linear solver shapeFunctionMatrix_ = new LambdaCouplingMatrix(atc_,nodeToOverlapMap_); interscaleManager.add_per_atom_sparse_matrix(shapeFunctionMatrix_, regulatorPrefix_+"LambdaCouplingMatrixMomentum"); if (elementMask_) { lambdaAtomMap_ = new AtomToElementset(atc_,elementMask_); interscaleManager.add_per_atom_int_quantity(lambdaAtomMap_, regulatorPrefix_+"LambdaAtomMap"); } if (atomicRegulator_->use_localized_lambda()) { linearSolverType_ = AtomicRegulator::RSL_SOLVE; } else { linearSolverType_ = AtomicRegulator::CG_SOLVE; } // base class transfers KinetostatGlcFs::construct_transfers(); // sets up space for ghost force related variables if (atc_->groupbit_ghost()) { MatrixDependencyManager<DenseMatrix, int> * nodeToOverlapMap = interscaleManager.dense_matrix_int(regulatorPrefix_+"NodeToOverlapMap"); GhostCouplingMatrix * shapeFunctionGhost = new GhostCouplingMatrix(atc_,interscaleManager.per_atom_sparse_matrix("InterpolantGhost"), regulatedNodes_, nodeToOverlapMap); interscaleManager.add_sparse_matrix(shapeFunctionGhost, regulatorPrefix_+"GhostCouplingMatrix"); FundamentalAtomQuantity * atomGhostForce = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_FORCE, GHOST); nodalGhostForce_ = new AtfShapeFunctionRestriction(atc_,atomGhostForce, shapeFunctionGhost); interscaleManager.add_dense_matrix(nodalGhostForce_, regulatorPrefix_+"NodalGhostForce"); } } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void KinetostatFlux::initialize() { KinetostatGlcFs::initialize(); TimeFilterManager * timeFilterManager = atc_->time_filter_manager(); if (!timeFilterManager->end_equilibrate()) { // we should reset lambda and lambdaForce to zero in this case // implies an initial condition of 0 for the filtered nodal lambda power // initial conditions will always be needed when using time filtering // however, the fractional step scheme must assume the instantaneous // nodal lambda power is 0 initially because all quantities are in delta form *nodalGhostForceFiltered_ = 0.; // filtered force from ghost atoms } else { // we can grab lambda power variables using time integrator and atc transfer in cases for equilibration } } //-------------------------------------------------------- // construct_regulated_nodes: // constructs the set of nodes being regulated //-------------------------------------------------------- void KinetostatFlux::construct_regulated_nodes() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // matrix requires all entries even if localized for correct lumping regulatedNodes_ = new RegulatedNodes(atc_); interscaleManager.add_set_int(regulatedNodes_, regulatorPrefix_+"KinetostatRegulatedNodes"); // if localized monitor nodes with applied fluxes if (atomicRegulator_->use_localized_lambda()) { if ((kinetostat_->coupling_mode() == Kinetostat::FLUX) && (atomicRegulator_->boundary_integration_type() != NO_QUADRATURE)) { // include boundary nodes applicationNodes_ = new FluxBoundaryNodes(atc_); boundaryNodes_ = new BoundaryNodes(atc_); interscaleManager.add_set_int(boundaryNodes_, regulatorPrefix_+"KinetostatBoundaryNodes"); } else { // fluxed nodes only applicationNodes_ = new FluxNodes(atc_); } interscaleManager.add_set_int(applicationNodes_, regulatorPrefix_+"KinetostatApplicationNodes"); } else { applicationNodes_ = regulatedNodes_; } // special set of boundary elements for boundary flux quadrature if ((atomicRegulator_->boundary_integration_type() == FE_INTERPOLATION) && (atomicRegulator_->use_localized_lambda())) { elementMask_ = new ElementMaskNodeSet(atc_,applicationNodes_); interscaleManager.add_dense_matrix_bool(elementMask_, regulatorPrefix_+"BoundaryElementMask"); } } //-------------------------------------------------------- // apply_pre_predictor: // apply the kinetostat to the atoms in the // pre-predictor integration phase //-------------------------------------------------------- void KinetostatFlux::apply_pre_predictor(double dt) { // update filtered forces if (nodalGhostForce_) { timeFilter_->apply_pre_step1(nodalGhostForceFiltered_->set_quantity(), nodalGhostForce_->quantity(),dt); } KinetostatGlcFs::apply_pre_predictor(dt); } //-------------------------------------------------------- // apply_post_corrector: // apply the kinetostat to the atoms in the // post-corrector integration phase //-------------------------------------------------------- void KinetostatFlux::apply_post_corrector(double dt) { // update filtered ghost force if (nodalGhostForce_) { timeFilter_->apply_post_step1(nodalGhostForceFiltered_->set_quantity(), nodalGhostForce_->quantity(),dt); } // compute the kinetostat equation and update lambda KinetostatGlcFs::apply_post_corrector(dt); } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void KinetostatFlux::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // (a) for flux based : // form rhs : \int N_I r dV - \sum_g N_Ig^* f_g // sources are set in ATC transfer rhs.reset(nNodes_,nsd_); const DENS_MAT & momentumSource(momentumSource_.quantity()); const set<int> & applicationNodes(applicationNodes_->quantity()); set<int>::const_iterator iNode; for (iNode = applicationNodes.begin(); iNode != applicationNodes.end(); iNode++) { for (int j = 0; j < nsd_; j++) { rhs(*iNode,j) = momentumSource(*iNode,j); } } // add ghost forces, if needed if (nodalGhostForce_) { const DENS_MAT & nodalGhostForce(nodalGhostForce_->quantity()); for (iNode = applicationNodes.begin(); iNode != applicationNodes.end(); iNode++) { for (int j = 0; j < nsd_; j++) { rhs(*iNode,j) -= nodalGhostForce(*iNode,j); } } } } //-------------------------------------------------------- // add_to_momentum: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void KinetostatFlux::add_to_momentum(const DENS_MAT & nodalLambdaForce, DENS_MAT & deltaMomentum, double dt) { deltaMomentum.resize(nNodes_,nsd_); const DENS_MAT & boundaryFlux(boundaryFlux_[VELOCITY].quantity()); for (int i = 0; i < nNodes_; i++) { for (int j = 0; j < nsd_; j++) { deltaMomentum(i,j) = nodalLambdaForce(i,j) + dt*boundaryFlux(i,j); } } } //-------------------------------------------------------- // reset_filtered_ghost_force: // resets the kinetostat generated ghost force to a // prescribed value //-------------------------------------------------------- void KinetostatFlux::reset_filtered_ghost_force(DENS_MAT & target) { (*nodalGhostForceFiltered_) = target; } //-------------------------------------------------------- //-------------------------------------------------------- // Class KinetostatFluxGhost //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- KinetostatFluxGhost::KinetostatFluxGhost(Kinetostat * kinetostat, const string & regulatorPrefix) : KinetostatFlux(kinetostat,regulatorPrefix) { // flag for performing boundary flux calculation fieldMask_(VELOCITY,FLUX) = false; } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void KinetostatFluxGhost::construct_transfers() { KinetostatFlux::construct_transfers(); if (!nodalGhostForce_) { throw ATC_Error("StressFluxGhost::StressFluxGhost - ghost atoms must be specified"); } } //-------------------------------------------------------- // compute_boundary_flux: // computes the boundary flux to be consistent with // the controller //-------------------------------------------------------- void KinetostatFluxGhost::compute_boundary_flux(FIELDS & fields) { // This is only used in computation of atomic sources boundaryFlux_[VELOCITY] = 0.; } //-------------------------------------------------------- // add_to_momentum: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void KinetostatFluxGhost::add_to_momentum(const DENS_MAT & nodalLambdaForce, DENS_MAT & deltaMomentum, double dt) { deltaMomentum.resize(nNodes_,nsd_); const DENS_MAT & boundaryFlux(nodalGhostForce_->quantity()); for (int i = 0; i < nNodes_; i++) { for (int j = 0; j < nsd_; j++) { deltaMomentum(i,j) = nodalLambdaForce(i,j) + dt*boundaryFlux(i,j); } } } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void KinetostatFluxGhost::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // (a) for flux based : // form rhs : \int N_I r dV - \sum_g N_Ig^* f_g // sources are set in ATC transfer rhs.reset(nNodes_,nsd_); const DENS_MAT & momentumSource(momentumSource_.quantity()); const set<int> & applicationNodes(applicationNodes_->quantity()); set<int>::const_iterator iNode; for (iNode = applicationNodes.begin(); iNode != applicationNodes.end(); iNode++) { for (int j = 0; j < nsd_; j++) { rhs(*iNode,j) = momentumSource(*iNode,j); } } } //-------------------------------------------------------- //-------------------------------------------------------- // Class KinetostatFixed //-------------------------------------------------------- //-------------------------------------------------------- //-------------------------------------------------------- // Constructor // Grab references to ATC and kinetostat data //-------------------------------------------------------- KinetostatFixed::KinetostatFixed(Kinetostat * kinetostat, const string & regulatorPrefix) : KinetostatGlcFs(kinetostat,regulatorPrefix), mdMassMatrix_(atc_->set_mass_mat_md(VELOCITY)), isFirstTimestep_(true) { // do nothing } //-------------------------------------------------------- // constructor_transfers // instantiates or obtains all dependency managed data //-------------------------------------------------------- void KinetostatFixed::construct_transfers() { InterscaleManager & interscaleManager(atc_->interscale_manager()); // set up node mappings create_node_maps(); // determine if map is needed and set up if so if (this->use_local_shape_functions()) { lambdaAtomMap_ = new AtomToElementset(atc_,elementMask_); interscaleManager.add_per_atom_int_quantity(lambdaAtomMap_, regulatorPrefix_+"LambdaAtomMap"); shapeFunctionMatrix_ = new LocalLambdaCouplingMatrix(atc_, lambdaAtomMap_, nodeToOverlapMap_); } else { shapeFunctionMatrix_ = new LambdaCouplingMatrix(atc_,nodeToOverlapMap_); } interscaleManager.add_per_atom_sparse_matrix(shapeFunctionMatrix_, regulatorPrefix_+"LambdaCouplingMatrixMomentum"); linearSolverType_ = AtomicRegulator::CG_SOLVE; // base class transfers KinetostatGlcFs::construct_transfers(); } //-------------------------------------------------------- // initialize // initializes all method data //-------------------------------------------------------- void KinetostatFixed::initialize() { KinetostatGlcFs::initialize(); // reset data to zero deltaFeMomentum_.reset(nNodes_,nsd_); deltaNodalAtomicMomentum_.reset(nNodes_,nsd_); } //-------------------------------------------------------- // halve_force: // flag to halve the lambda force for improved // accuracy //-------------------------------------------------------- bool KinetostatFixed::halve_force() { if (isFirstTimestep_ || ((atc_->atom_to_element_map_type() == EULERIAN) && (atc_->atom_to_element_map_frequency() > 1) && (atc_->step() % atc_->atom_to_element_map_frequency() == 1))) { return true; } return false; } //-------------------------------------------------------- // construct_regulated_nodes: // constructs the set of nodes being regulated //-------------------------------------------------------- void KinetostatFixed::construct_regulated_nodes() { InterscaleManager & interscaleManager(atc_->interscale_manager()); if (!atomicRegulator_->use_localized_lambda()) { regulatedNodes_ = new RegulatedNodes(atc_); } else if (kinetostat_->coupling_mode() == Kinetostat::FLUX) { regulatedNodes_ = new FixedNodes(atc_); } else if (kinetostat_->coupling_mode() == Kinetostat::FIXED) { // include boundary nodes regulatedNodes_ = new FixedBoundaryNodes(atc_); } else { throw ATC_Error("ThermostatFixed::construct_regulated_nodes - couldn't determine set of regulated nodes"); } interscaleManager.add_set_int(regulatedNodes_, regulatorPrefix_+"RegulatedNodes"); applicationNodes_ = regulatedNodes_; // special set of boundary elements for defining regulated atoms if (atomicRegulator_->use_localized_lambda()) { elementMask_ = new ElementMaskNodeSet(atc_,applicationNodes_); interscaleManager.add_dense_matrix_bool(elementMask_, regulatorPrefix_+"BoundaryElementMask"); } } //-------------------------------------------------------- // initialize_delta_nodal_atomic_momentum: // initializes storage for the variable tracking // the change in the nodal atomic momentum // that has occured over the past timestep //-------------------------------------------------------- void KinetostatFixed::initialize_delta_nodal_atomic_momentum(double dt) { // initialize delta energy const DENS_MAT & myNodalAtomicMomentum(nodalAtomicMomentum_->quantity()); initialNodalAtomicMomentum_ = myNodalAtomicMomentum; initialNodalAtomicMomentum_ *= -1.; // initially stored as negative for efficiency timeFilter_->apply_pre_step1(nodalAtomicMomentumFiltered_.set_quantity(), myNodalAtomicMomentum,dt); } //-------------------------------------------------------- // compute_delta_nodal_atomic_momentum: // computes the change in the nodal atomic momentum // that has occured over the past timestep //-------------------------------------------------------- void KinetostatFixed::compute_delta_nodal_atomic_momentum(double dt) { // set delta energy based on predicted atomic velocities const DENS_MAT & myNodalAtomicMomentum(nodalAtomicMomentum_->quantity()); timeFilter_->apply_post_step1(nodalAtomicMomentumFiltered_.set_quantity(), myNodalAtomicMomentum,dt); deltaNodalAtomicMomentum_ = initialNodalAtomicMomentum_; deltaNodalAtomicMomentum_ += myNodalAtomicMomentum; } //-------------------------------------------------------- // apply_pre_predictor: // apply the kinetostat to the atoms in the // pre-predictor integration phase //-------------------------------------------------------- void KinetostatFixed::apply_pre_predictor(double dt) { // initialize values to be track change in finite element energy over the timestep initialize_delta_nodal_atomic_momentum(dt); initialFeMomentum_ = -1.*((mdMassMatrix_.quantity())*(velocity_.quantity())); // initially stored as negative for efficiency KinetostatGlcFs::apply_pre_predictor(dt); } //-------------------------------------------------------- // apply_post_corrector: // apply the kinetostat to the atoms in the // post-corrector integration phase //-------------------------------------------------------- void KinetostatFixed::apply_post_corrector(double dt) { KinetostatGlcFs::apply_post_corrector(dt); // update filtered momentum with lambda force DENS_MAT & myNodalAtomicLambdaForce(nodalAtomicLambdaForce_->set_quantity()); timeFilter_->apply_post_step2(nodalAtomicMomentumFiltered_.set_quantity(), myNodalAtomicLambdaForce,dt); if (halve_force()) { // Halve lambda force due to fixed temperature constraints // 1) makes up for poor initial condition // 2) accounts for possibly large value of lambda when atomic shape function values change // from eulerian mapping after more than 1 timestep // avoids unstable oscillations arising from // thermostat having to correct for error introduced in lambda changing the // shape function matrices *lambda_ *= 0.5; } isFirstTimestep_ = false; } //-------------------------------------------------------- // compute_kinetostat // manages the solution and application of the // kinetostat equations and variables //-------------------------------------------------------- void KinetostatFixed::compute_lambda(double dt) { // compute predicted changes in nodal atomic momentum compute_delta_nodal_atomic_momentum(dt); // change in finite element momentum deltaFeMomentum_ = initialFeMomentum_; deltaFeMomentum_ += (mdMassMatrix_.quantity())*(velocity_.quantity()); // set up rhs for lambda equation KinetostatGlcFs::compute_lambda(dt); } //-------------------------------------------------------- // set_kinetostat_rhs // sets up the RHS of the kinetostat equations // for the coupling parameter lambda //-------------------------------------------------------- void KinetostatFixed::set_kinetostat_rhs(DENS_MAT & rhs, double dt) { // for essential bcs (fixed nodes) : // form rhs : (delUpsV - delUps)/dt const set<int> & regulatedNodes(regulatedNodes_->quantity()); double factor = (1./dt); for (int i = 0; i < nNodes_; i++) { if (regulatedNodes.find(i) != regulatedNodes.end()) { for (int j = 0; j < nsd_; j++) { rhs(i,j) = factor*(deltaNodalAtomicMomentum_(i,j) - deltaFeMomentum_(i,j)); } } else { for (int j = 0; j < nsd_; j++) { rhs(i,j) = 0.; } } } } //-------------------------------------------------------- // add_to_momentum: // determines what if any contributions to the // finite element equations are needed for // consistency with the kinetostat //-------------------------------------------------------- void KinetostatFixed::add_to_momentum(const DENS_MAT & nodalLambdaForce, DENS_MAT & deltaMomentum, double dt) { deltaMomentum.resize(nNodes_,nsd_); const set<int> & regulatedNodes(regulatedNodes_->quantity()); for (int i = 0; i < nNodes_; i++) { if (regulatedNodes.find(i) != regulatedNodes.end()) { for (int j = 0; j < nsd_; j++) { deltaMomentum(i,j) = 0.; } } else { for (int j = 0; j < nsd_; j++) { deltaMomentum(i,j) = nodalLambdaForce(i,j); } } } } };
sradl1981/LIGGGHTS-PUBLIC-ParScale
lib/atc/Kinetostat.cpp
C++
gpl-2.0
89,062
// vm_ppc.c // ppc dynamic compiler #include "vm_local.h" #pragma opt_pointer_analysis off typedef enum { R_REAL_STACK = 1, // registers 3-11 are the parameter passing registers // state R_STACK = 3, // local R_OPSTACK, // global // constants R_MEMBASE, // global R_MEMMASK, R_ASMCALL, // global R_INSTRUCTIONS, // global R_NUM_INSTRUCTIONS, // global R_CVM, // currentVM // temps R_TOP = 12, R_SECOND = 13, R_EA = 14 // effective address calculation } regNums_t; #define RG_REAL_STACK r1 #define RG_STACK r3 #define RG_OPSTACK r4 #define RG_MEMBASE r5 #define RG_MEMMASK r6 #define RG_ASMCALL r7 #define RG_INSTRUCTIONS r8 #define RG_NUM_INSTRUCTIONS r9 #define RG_CVM r10 #define RG_TOP r12 #define RG_SECOND r13 #define RG_EA r14 // this doesn't have the low order bits set for instructions i'm not using... typedef enum { PPC_TDI = 0x08000000, PPC_TWI = 0x0c000000, PPC_MULLI = 0x1c000000, PPC_SUBFIC = 0x20000000, PPC_CMPI = 0x28000000, PPC_CMPLI = 0x2c000000, PPC_ADDIC = 0x30000000, PPC_ADDIC_ = 0x34000000, PPC_ADDI = 0x38000000, PPC_ADDIS = 0x3c000000, PPC_BC = 0x40000000, PPC_SC = 0x44000000, PPC_B = 0x48000000, PPC_MCRF = 0x4c000000, PPC_BCLR = 0x4c000020, PPC_RFID = 0x4c000000, PPC_CRNOR = 0x4c000000, PPC_RFI = 0x4c000000, PPC_CRANDC = 0x4c000000, PPC_ISYNC = 0x4c000000, PPC_CRXOR = 0x4c000000, PPC_CRNAND = 0x4c000000, PPC_CREQV = 0x4c000000, PPC_CRORC = 0x4c000000, PPC_CROR = 0x4c000000, //------------ PPC_BCCTR = 0x4c000420, PPC_RLWIMI = 0x50000000, PPC_RLWINM = 0x54000000, PPC_RLWNM = 0x5c000000, PPC_ORI = 0x60000000, PPC_ORIS = 0x64000000, PPC_XORI = 0x68000000, PPC_XORIS = 0x6c000000, PPC_ANDI_ = 0x70000000, PPC_ANDIS_ = 0x74000000, PPC_RLDICL = 0x78000000, PPC_RLDICR = 0x78000000, PPC_RLDIC = 0x78000000, PPC_RLDIMI = 0x78000000, PPC_RLDCL = 0x78000000, PPC_RLDCR = 0x78000000, PPC_CMP = 0x7c000000, PPC_TW = 0x7c000000, PPC_SUBFC = 0x7c000010, PPC_MULHDU = 0x7c000000, PPC_ADDC = 0x7c000014, PPC_MULHWU = 0x7c000000, PPC_MFCR = 0x7c000000, PPC_LWAR = 0x7c000000, PPC_LDX = 0x7c000000, PPC_LWZX = 0x7c00002e, PPC_SLW = 0x7c000030, PPC_CNTLZW = 0x7c000000, PPC_SLD = 0x7c000000, PPC_AND = 0x7c000038, PPC_CMPL = 0x7c000040, PPC_SUBF = 0x7c000050, PPC_LDUX = 0x7c000000, //------------ PPC_DCBST = 0x7c000000, PPC_LWZUX = 0x7c00006c, PPC_CNTLZD = 0x7c000000, PPC_ANDC = 0x7c000000, PPC_TD = 0x7c000000, PPC_MULHD = 0x7c000000, PPC_MULHW = 0x7c000000, PPC_MTSRD = 0x7c000000, PPC_MFMSR = 0x7c000000, PPC_LDARX = 0x7c000000, PPC_DCBF = 0x7c000000, PPC_LBZX = 0x7c0000ae, PPC_NEG = 0x7c000000, PPC_MTSRDIN = 0x7c000000, PPC_LBZUX = 0x7c000000, PPC_NOR = 0x7c0000f8, PPC_SUBFE = 0x7c000000, PPC_ADDE = 0x7c000000, PPC_MTCRF = 0x7c000000, PPC_MTMSR = 0x7c000000, PPC_STDX = 0x7c000000, PPC_STWCX_ = 0x7c000000, PPC_STWX = 0x7c00012e, PPC_MTMSRD = 0x7c000000, PPC_STDUX = 0x7c000000, PPC_STWUX = 0x7c00016e, PPC_SUBFZE = 0x7c000000, PPC_ADDZE = 0x7c000000, PPC_MTSR = 0x7c000000, PPC_STDCX_ = 0x7c000000, PPC_STBX = 0x7c0001ae, PPC_SUBFME = 0x7c000000, PPC_MULLD = 0x7c000000, //------------ PPC_ADDME = 0x7c000000, PPC_MULLW = 0x7c0001d6, PPC_MTSRIN = 0x7c000000, PPC_DCBTST = 0x7c000000, PPC_STBUX = 0x7c000000, PPC_ADD = 0x7c000214, PPC_DCBT = 0x7c000000, PPC_LHZX = 0x7c00022e, PPC_EQV = 0x7c000000, PPC_TLBIE = 0x7c000000, PPC_ECIWX = 0x7c000000, PPC_LHZUX = 0x7c000000, PPC_XOR = 0x7c000278, PPC_MFSPR = 0x7c0002a6, PPC_LWAX = 0x7c000000, PPC_LHAX = 0x7c000000, PPC_TLBIA = 0x7c000000, PPC_MFTB = 0x7c000000, PPC_LWAUX = 0x7c000000, PPC_LHAUX = 0x7c000000, PPC_STHX = 0x7c00032e, PPC_ORC = 0x7c000338, PPC_SRADI = 0x7c000000, PPC_SLBIE = 0x7c000000, PPC_ECOWX = 0x7c000000, PPC_STHUX = 0x7c000000, PPC_OR = 0x7c000378, PPC_DIVDU = 0x7c000000, PPC_DIVWU = 0x7c000396, PPC_MTSPR = 0x7c0003a6, PPC_DCBI = 0x7c000000, PPC_NAND = 0x7c000000, PPC_DIVD = 0x7c000000, //------------ PPC_DIVW = 0x7c0003d6, PPC_SLBIA = 0x7c000000, PPC_MCRXR = 0x7c000000, PPC_LSWX = 0x7c000000, PPC_LWBRX = 0x7c000000, PPC_LFSX = 0x7c000000, PPC_SRW = 0x7c000430, PPC_SRD = 0x7c000000, PPC_TLBSYNC = 0x7c000000, PPC_LFSUX = 0x7c000000, PPC_MFSR = 0x7c000000, PPC_LSWI = 0x7c000000, PPC_SYNC = 0x7c000000, PPC_LFDX = 0x7c000000, PPC_LFDUX = 0x7c000000, PPC_MFSRIN = 0x7c000000, PPC_STSWX = 0x7c000000, PPC_STWBRX = 0x7c000000, PPC_STFSX = 0x7c000000, PPC_STFSUX = 0x7c000000, PPC_STSWI = 0x7c000000, PPC_STFDX = 0x7c000000, PPC_DCBA = 0x7c000000, PPC_STFDUX = 0x7c000000, PPC_LHBRX = 0x7c000000, PPC_SRAW = 0x7c000630, PPC_SRAD = 0x7c000000, PPC_SRAWI = 0x7c000000, PPC_EIEIO = 0x7c000000, PPC_STHBRX = 0x7c000000, PPC_EXTSH = 0x7c000734, PPC_EXTSB = 0x7c000774, PPC_ICBI = 0x7c000000, //------------ PPC_STFIWX = 0x7c0007ae, PPC_EXTSW = 0x7c000000, PPC_DCBZ = 0x7c000000, PPC_LWZ = 0x80000000, PPC_LWZU = 0x84000000, PPC_LBZ = 0x88000000, PPC_LBZU = 0x8c000000, PPC_STW = 0x90000000, PPC_STWU = 0x94000000, PPC_STB = 0x98000000, PPC_STBU = 0x9c000000, PPC_LHZ = 0xa0000000, PPC_LHZU = 0xa4000000, PPC_LHA = 0xa8000000, PPC_LHAU = 0xac000000, PPC_STH = 0xb0000000, PPC_STHU = 0xb4000000, PPC_LMW = 0xb8000000, PPC_STMW = 0xbc000000, PPC_LFS = 0xc0000000, PPC_LFSU = 0xc4000000, PPC_LFD = 0xc8000000, PPC_LFDU = 0xcc000000, PPC_STFS = 0xd0000000, PPC_STFSU = 0xd4000000, PPC_STFD = 0xd8000000, PPC_STFDU = 0xdc000000, PPC_LD = 0xe8000000, PPC_LDU = 0xe8000001, PPC_LWA = 0xe8000002, PPC_FDIVS = 0xec000024, PPC_FSUBS = 0xec000028, PPC_FADDS = 0xec00002a, //------------ PPC_FSQRTS = 0xec000000, PPC_FRES = 0xec000000, PPC_FMULS = 0xec000032, PPC_FMSUBS = 0xec000000, PPC_FMADDS = 0xec000000, PPC_FNMSUBS = 0xec000000, PPC_FNMADDS = 0xec000000, PPC_STD = 0xf8000000, PPC_STDU = 0xf8000001, PPC_FCMPU = 0xfc000000, PPC_FRSP = 0xfc000018, PPC_FCTIW = 0xfc000000, PPC_FCTIWZ = 0xfc00001e, PPC_FDIV = 0xfc000000, PPC_FSUB = 0xfc000028, PPC_FADD = 0xfc000000, PPC_FSQRT = 0xfc000000, PPC_FSEL = 0xfc000000, PPC_FMUL = 0xfc000000, PPC_FRSQRTE = 0xfc000000, PPC_FMSUB = 0xfc000000, PPC_FMADD = 0xfc000000, PPC_FNMSUB = 0xfc000000, PPC_FNMADD = 0xfc000000, PPC_FCMPO = 0xfc000000, PPC_MTFSB1 = 0xfc000000, PPC_FNEG = 0xfc000050, PPC_MCRFS = 0xfc000000, PPC_MTFSB0 = 0xfc000000, PPC_FMR = 0xfc000000, PPC_MTFSFI = 0xfc000000, PPC_FNABS = 0xfc000000, PPC_FABS = 0xfc000000, //------------ PPC_MFFS = 0xfc000000, PPC_MTFSF = 0xfc000000, PPC_FCTID = 0xfc000000, PPC_FCTIDZ = 0xfc000000, PPC_FCFID = 0xfc000000 } ppcOpcodes_t; // the newly generated code static unsigned *buf; static int compiledOfs; // in dwords // fromt the original bytecode static byte *code; static int pc; void AsmCall( void ); double itofConvert[2]; static int Constant4( void ) { int v; v = code[pc] | (code[pc+1]<<8) | (code[pc+2]<<16) | (code[pc+3]<<24); pc += 4; return v; } static int Constant1( void ) { int v; v = code[pc]; pc += 1; return v; } static void Emit4( int i ) { buf[ compiledOfs ] = i; compiledOfs++; } static void Inst( int opcode, int destReg, int aReg, int bReg ) { unsigned r; r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) ; buf[ compiledOfs ] = r; compiledOfs++; } static void Inst4( int opcode, int destReg, int aReg, int bReg, int cReg ) { unsigned r; r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) | ( cReg << 6 ); buf[ compiledOfs ] = r; compiledOfs++; } static void InstImm( int opcode, int destReg, int aReg, int immediate ) { unsigned r; if ( immediate > 32767 || immediate < -32768 ) { Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range, opcode %x,%d,%d", immediate, opcode, destReg, aReg ); } r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff ); buf[ compiledOfs ] = r; compiledOfs++; } static void InstImmU( int opcode, int destReg, int aReg, int immediate ) { unsigned r; if ( immediate > 0xffff || immediate < 0 ) { Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range", immediate ); } r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff ); buf[ compiledOfs ] = r; compiledOfs++; } static qboolean rtopped; static int pop0, pop1, oc0, oc1; static vm_t *tvm; static int instruction; static byte *jused; static int pass; static void ltop() { if (rtopped == qfalse) { InstImm( PPC_LWZ, R_TOP, R_OPSTACK, 0 ); // get value from opstack } } static void ltopandsecond() { if (pass>=0 && buf[compiledOfs-1] == (PPC_STWU | R_TOP<<21 | R_OPSTACK<<16 | 4 ) && jused[instruction]==0 ) { compiledOfs--; if (!pass) { tvm->instructionPointers[instruction] = compiledOfs * 4; } InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); } else if (pass>=0 && buf[compiledOfs-1] == (PPC_STW | R_TOP<<21 | R_OPSTACK<<16 | 0 ) && jused[instruction]==0 ) { compiledOfs--; if (!pass) { tvm->instructionPointers[instruction] = compiledOfs * 4; } InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 ); } else { ltop(); // get value from opstack InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 ); } rtopped = qfalse; } // TJW: Unused #if 0 static void fltop() { if (rtopped == qfalse) { InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack } } #endif static void fltopandsecond() { InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_LFS, R_SECOND, R_OPSTACK, -4 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 ); rtopped = qfalse; return; } /* ================= VM_Compile ================= */ void VM_Compile( vm_t *vm, vmHeader_t *header ) { int op; int maxLength; int v; int i; // set up the into-to-float variables ((int *)itofConvert)[0] = 0x43300000; ((int *)itofConvert)[1] = 0x80000000; ((int *)itofConvert)[2] = 0x43300000; // allocate a very large temp buffer, we will shrink it later maxLength = header->codeLength * 8; buf = Z_Malloc( maxLength,qfalse ); jused = Z_Malloc(header->instructionCount + 2,qfalse); Com_Memset(jused, 0, header->instructionCount+2); // compile everything twice, so the second pass will have valid instruction // pointers for branches for ( pass = -1 ; pass < 2 ; pass++ ) { rtopped = qfalse; // translate all instructions pc = 0; pop0 = 343545; pop1 = 2443545; oc0 = -2343535; oc1 = 24353454; tvm = vm; code = (byte *)header + header->codeOffset; compiledOfs = 0; #ifndef __GNUC__ // metrowerks seems to require this header in front of functions Emit4( (int)(buf+2) ); Emit4( 0 ); #endif for ( instruction = 0 ; instruction < header->instructionCount ; instruction++ ) { if ( compiledOfs*4 > maxLength - 16 ) { Com_Error( ERR_DROP, "VM_Compile: maxLength exceeded" ); } op = code[ pc ]; if ( !pass ) { vm->instructionPointers[ instruction ] = compiledOfs * 4; } pc++; switch ( op ) { case 0: break; case OP_BREAK: InstImmU( PPC_ADDI, R_TOP, 0, 0 ); InstImm( PPC_LWZ, R_TOP, R_TOP, 0 ); // *(int *)0 to crash to debugger rtopped = qfalse; break; case OP_ENTER: InstImm( PPC_ADDI, R_STACK, R_STACK, -Constant4() ); // sub R_STACK, R_STACK, imm rtopped = qfalse; break; case OP_CONST: v = Constant4(); if (code[pc] == OP_LOAD4 || code[pc] == OP_LOAD2 || code[pc] == OP_LOAD1) { v &= vm->dataMask; } if ( v < 32768 && v >= -32768 ) { InstImmU( PPC_ADDI, R_TOP, 0, v & 0xffff ); } else { InstImmU( PPC_ADDIS, R_TOP, 0, (v >> 16)&0xffff ); if ( v & 0xffff ) { InstImmU( PPC_ORI, R_TOP, R_TOP, v & 0xffff ); } } if (code[pc] == OP_LOAD4) { Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } else if (code[pc] == OP_LOAD2) { Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } else if (code[pc] == OP_LOAD1) { Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } if (code[pc] == OP_STORE4) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } else if (code[pc] == OP_STORE2) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } else if (code[pc] == OP_STORE1) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } if (code[pc] == OP_JUMP) { jused[v] = 1; } InstImm( PPC_STWU, R_TOP, R_OPSTACK, 4 ); rtopped = qtrue; break; case OP_LOCAL: oc0 = oc1; oc1 = Constant4(); if (code[pc] == OP_LOAD4 || code[pc] == OP_LOAD2 || code[pc] == OP_LOAD1) { oc1 &= vm->dataMask; } InstImm( PPC_ADDI, R_TOP, R_STACK, oc1 ); if (code[pc] == OP_LOAD4) { Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } else if (code[pc] == OP_LOAD2) { Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } else if (code[pc] == OP_LOAD1) { Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base pc++; instruction++; } if (code[pc] == OP_STORE4) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } else if (code[pc] == OP_STORE2) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } else if (code[pc] == OP_STORE1) { InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base pc++; instruction++; rtopped = qfalse; break; } InstImm( PPC_STWU, R_TOP, R_OPSTACK, 4 ); rtopped = qtrue; break; case OP_ARG: ltop(); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); InstImm( PPC_ADDI, R_EA, R_STACK, Constant1() ); // location to put it Inst( PPC_STWX, R_TOP, R_EA, R_MEMBASE ); rtopped = qfalse; break; case OP_CALL: Inst( PPC_MFSPR, R_SECOND, 8, 0 ); // move from link register InstImm( PPC_STWU, R_SECOND, R_REAL_STACK, -16 ); // save off the old return address Inst( PPC_MTSPR, R_ASMCALL, 9, 0 ); // move to count register Inst( PPC_BCCTR | 1, 20, 0, 0 ); // jump and link to the count register InstImm( PPC_LWZ, R_SECOND, R_REAL_STACK, 0 ); // fetch the old return address InstImm( PPC_ADDI, R_REAL_STACK, R_REAL_STACK, 16 ); Inst( PPC_MTSPR, R_SECOND, 8, 0 ); // move to link register rtopped = qfalse; break; case OP_PUSH: InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, 4 ); rtopped = qfalse; break; case OP_POP: InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); rtopped = qfalse; break; case OP_LEAVE: InstImm( PPC_ADDI, R_STACK, R_STACK, Constant4() ); // add R_STACK, R_STACK, imm Inst( PPC_BCLR, 20, 0, 0 ); // branch unconditionally to link register rtopped = qfalse; break; case OP_LOAD4: ltop(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); rtopped = qtrue; break; case OP_LOAD2: ltop(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); rtopped = qtrue; break; case OP_LOAD1: ltop(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); rtopped = qtrue; break; case OP_STORE4: ltopandsecond(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base rtopped = qfalse; break; case OP_STORE2: ltopandsecond(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base rtopped = qfalse; break; case OP_STORE1: ltopandsecond(); // get value from opstack //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base rtopped = qfalse; break; case OP_EQ: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; InstImm( PPC_BC, 4, 2, 8 ); if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } Emit4(PPC_B | (v&0x3ffffff) ); rtopped = qfalse; break; case OP_NE: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; InstImm( PPC_BC, 12, 2, 8 ); if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } Emit4(PPC_B | (unsigned int)(v&0x3ffffff) ); // InstImm( PPC_BC, 4, 2, v ); rtopped = qfalse; break; case OP_LTI: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; InstImm( PPC_BC, 4, 0, 8 ); if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } Emit4(PPC_B | (unsigned int)(v&0x3ffffff) ); // InstImm( PPC_BC, 12, 0, v ); rtopped = qfalse; break; case OP_LEI: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; InstImm( PPC_BC, 12, 1, 8 ); if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } Emit4(PPC_B | (unsigned int)(v&0x3ffffff) ); // InstImm( PPC_BC, 4, 1, v ); rtopped = qfalse; break; case OP_GTI: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; InstImm( PPC_BC, 4, 1, 8 ); if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } Emit4(PPC_B | (unsigned int)(v&0x3ffffff) ); // InstImm( PPC_BC, 12, 1, v ); rtopped = qfalse; break; case OP_GEI: ltopandsecond(); // get value from opstack Inst( PPC_CMP, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 0, v ); rtopped = qfalse; break; case OP_LTU: ltopandsecond(); // get value from opstack Inst( PPC_CMPL, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 12, 0, v ); rtopped = qfalse; break; case OP_LEU: ltopandsecond(); // get value from opstack Inst( PPC_CMPL, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 1, v ); rtopped = qfalse; break; case OP_GTU: ltopandsecond(); // get value from opstack Inst( PPC_CMPL, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 12, 1, v ); rtopped = qfalse; break; case OP_GEU: ltopandsecond(); // get value from opstack Inst( PPC_CMPL, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 0, v ); rtopped = qfalse; break; case OP_EQF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_TOP, R_SECOND ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 12, 2, v ); rtopped = qfalse; break; case OP_NEF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_TOP, R_SECOND ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 2, v ); rtopped = qfalse; break; case OP_LTF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 12, 0, v ); rtopped = qfalse; break; case OP_LEF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 1, v ); rtopped = qfalse; break; case OP_GTF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 12, 1, v ); rtopped = qfalse; break; case OP_GEF: fltopandsecond(); // get value from opstack Inst( PPC_FCMPU, 0, R_SECOND, R_TOP ); i = Constant4(); jused[i] = 1; if ( pass==1 ) { v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs]; } else { v = 0; } InstImm( PPC_BC, 4, 0, v ); rtopped = qfalse; break; case OP_NEGI: ltop(); // get value from opstack InstImm( PPC_SUBFIC, R_TOP, R_TOP, 0 ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_ADD: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_ADD, R_TOP, R_TOP, R_SECOND ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_SUB: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_SUBF, R_TOP, R_TOP, R_SECOND ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_DIVI: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_DIVW, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_DIVU: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_DIVWU, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_MODI: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_DIVW, R_EA, R_SECOND, R_TOP ); Inst( PPC_MULLW, R_EA, R_TOP, R_EA ); Inst( PPC_SUBF, R_TOP, R_EA, R_SECOND ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_MODU: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_DIVWU, R_EA, R_SECOND, R_TOP ); Inst( PPC_MULLW, R_EA, R_TOP, R_EA ); Inst( PPC_SUBF, R_TOP, R_EA, R_SECOND ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_MULI: case OP_MULU: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_MULLW, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_BAND: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_AND, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_BOR: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_OR, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_BXOR: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_XOR, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_BCOM: ltop(); // get value from opstack Inst( PPC_NOR, R_TOP, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_LSH: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_SLW, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_RSHI: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_SRAW, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_RSHU: ltop(); // get value from opstack InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_SRW, R_SECOND, R_TOP, R_TOP ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qtrue; break; case OP_NEGF: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack Inst( PPC_FNEG, R_TOP, 0, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_ADDF: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_FADDS, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_SUBF: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_FSUBS, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_DIVF: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst( PPC_FDIVS, R_TOP, R_SECOND, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_MULF: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack Inst4( PPC_FMULS, R_TOP, R_SECOND, 0, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_CVIF: v = (int)&itofConvert; InstImmU( PPC_ADDIS, R_EA, 0, (v >> 16)&0xffff ); InstImmU( PPC_ORI, R_EA, R_EA, v & 0xffff ); InstImm( PPC_LWZ, R_TOP, R_OPSTACK, 0 ); // get value from opstack InstImmU( PPC_XORIS, R_TOP, R_TOP, 0x8000 ); InstImm( PPC_STW, R_TOP, R_EA, 12 ); InstImm( PPC_LFD, R_TOP, R_EA, 0 ); InstImm( PPC_LFD, R_SECOND, R_EA, 8 ); Inst( PPC_FSUB, R_TOP, R_SECOND, R_TOP ); // Inst( PPC_FRSP, R_TOP, 0, R_TOP ); InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack rtopped = qfalse; break; case OP_CVFI: InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack Inst( PPC_FCTIWZ, R_TOP, 0, R_TOP ); Inst( PPC_STFIWX, R_TOP, 0, R_OPSTACK ); // save value to opstack rtopped = qfalse; break; case OP_SEX8: ltop(); // get value from opstack Inst( PPC_EXTSB, R_TOP, R_TOP, 0 ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); rtopped = qtrue; break; case OP_SEX16: ltop(); // get value from opstack Inst( PPC_EXTSH, R_TOP, R_TOP, 0 ); InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); rtopped = qtrue; break; case OP_BLOCK_COPY: v = Constant4() >> 2; ltop(); // source InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // dest InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 ); InstImmU( PPC_ADDI, R_EA, 0, v ); // count // FIXME: range check Inst( PPC_MTSPR, R_EA, 9, 0 ); // move to count register Inst( PPC_ADD, R_TOP, R_TOP, R_MEMBASE ); InstImm( PPC_ADDI, R_TOP, R_TOP, -4 ); Inst( PPC_ADD, R_SECOND, R_SECOND, R_MEMBASE ); InstImm( PPC_ADDI, R_SECOND, R_SECOND, -4 ); InstImm( PPC_LWZU, R_EA, R_TOP, 4 ); // source InstImm( PPC_STWU, R_EA, R_SECOND, 4 ); // dest Inst( PPC_BC | 0xfff8 , 16, 0, 0 ); // loop rtopped = qfalse; break; case OP_JUMP: ltop(); // get value from opstack InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 ); Inst( PPC_RLWINM | ( 29 << 1 ), R_TOP, R_TOP, 2 ); // FIXME: range check Inst( PPC_LWZX, R_TOP, R_TOP, R_INSTRUCTIONS ); Inst( PPC_MTSPR, R_TOP, 9, 0 ); // move to count register Inst( PPC_BCCTR, 20, 0, 0 ); // jump to the count register rtopped = qfalse; break; default: Com_Error( ERR_DROP, "VM_CompilePPC: bad opcode %i at instruction %i, offset %i", op, instruction, pc ); } pop0 = pop1; pop1 = op; } Com_Printf( "VM file %s pass %d compiled to %i bytes of code\n", vm->name, (pass+1), compiledOfs*4 ); if ( pass == 0 ) { // copy to an exact size buffer on the hunk vm->codeLength = compiledOfs * 4; vm->codeBase = Hunk_Alloc( vm->codeLength, h_low ); Com_Memcpy( vm->codeBase, buf, vm->codeLength ); Z_Free( buf ); // offset all the instruction pointers for the new location for ( i = 0 ; i < header->instructionCount ; i++ ) { vm->instructionPointers[i] += (int)vm->codeBase; } // go back over it in place now to fixup reletive jump targets buf = (unsigned *)vm->codeBase; } } Z_Free( jused ); } /* ============== VM_CallCompiled This function is called directly by the generated code ============== */ int VM_CallCompiled( vm_t *vm, int *args ) { int stack[1024]; int programStack; int stackOnEntry; byte *image; currentVM = vm; // interpret the code vm->currentlyInterpreting = qtrue; // we might be called recursively, so this might not be the very top programStack = vm->programStack; stackOnEntry = programStack; image = vm->dataBase; // set up the stack frame programStack -= 48; *(int *)&image[ programStack + 44] = args[9]; *(int *)&image[ programStack + 40] = args[8]; *(int *)&image[ programStack + 36] = args[7]; *(int *)&image[ programStack + 32] = args[6]; *(int *)&image[ programStack + 28] = args[5]; *(int *)&image[ programStack + 24] = args[4]; *(int *)&image[ programStack + 20] = args[3]; *(int *)&image[ programStack + 16] = args[2]; *(int *)&image[ programStack + 12] = args[1]; *(int *)&image[ programStack + 8 ] = args[0]; *(int *)&image[ programStack + 4 ] = 0; // return stack *(int *)&image[ programStack ] = -1; // will terminate the loop on return // off we go into generated code... // the PPC calling standard says the parms will all go into R3 - R11, so // no special asm code is needed here #ifdef __GNUC__ ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))( programStack, (int)&stack, (int)image, vm->dataMask, (int)&AsmCall, (int)vm->instructionPointers, vm->instructionPointersLength, (int)vm ); #else ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))( programStack, (int)&stack, (int)image, vm->dataMask, *(int *)&AsmCall /* skip function pointer header */, (int)vm->instructionPointers, vm->instructionPointersLength, (int)vm ); #endif vm->programStack = stackOnEntry; vm->currentlyInterpreting = qfalse; return stack[1]; } /* ================== AsmCall Put this at end of file because gcc messes up debug line numbers ================== */ #ifdef __GNUC__ void AsmCall( void ) { asm (" // pop off the destination instruction lwz r12,0(r4) // RG_TOP, 0(RG_OPSTACK) addi r4,r4,-4 // RG_OPSTACK, RG_OPSTACK, -4 // see if it is a system trap cmpwi r12,0 // RG_TOP, 0 bc 12,0, systemTrap // calling another VM function, so lookup in instructionPointers slwi r12,r12,2 // RG_TOP,RG_TOP,2 // FIXME: range check lwzx r12, r8, r12 // RG_TOP, RG_INSTRUCTIONS(RG_TOP) mtctr r12 // RG_TOP "); #if defined(MACOS_X) && defined(__OPTIMIZE__) // On Mac OS X, gcc doesn't push a frame when we are optimized, so trying to tear it down results in grave disorder. #warning Mac OS X optimization on, not popping GCC AsmCall frame #else // Mac OS X Server and unoptimized compiles include a GCC AsmCall frame asm (" lwz r1,0(r1) // pop off the GCC AsmCall frame lmw r30,-8(r1) "); #endif asm (" bcctr 20,0 // when it hits a leave, it will branch to the current link register // calling a system trap systemTrap: // convert to positive system call number subfic r12,r12,-1 // save all our registers, including the current link register mflr r13 // RG_SECOND // copy off our link register addi r1,r1,-92 // required 24 byets of linkage, 32 bytes of parameter, plus our saves stw r3,56(r1) // RG_STACK, -36(REAL_STACK) stw r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK) stw r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK) stw r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK) stw r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK) stw r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK) stw r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK) stw r10,84(r1) // RG_VM, 28(RG_REAL_STACK) stw r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK) // link register // save the vm stack position to allow recursive VM entry addi r13,r3,-4 // RG_TOP, RG_STACK, -4 stw r13,0(r10) //RG_TOP, VM_OFFSET_PROGRAM_STACK(RG_VM) // save the system call number as the 0th parameter add r3,r3,r5 // r3, RG_STACK, RG_MEMBASE // r3 is the first parameter to vm->systemCalls stwu r12,4(r3) // RG_TOP, 4(r3) // make the system call with the address of all the VM parms as a parameter // vm->systemCalls( &parms ) lwz r12,4(r10) // RG_TOP, VM_OFFSET_SYSTEM_CALL(RG_VM) mtctr r12 // RG_TOP bcctrl 20,0 mr r12,r3 // RG_TOP, r3 // pop our saved registers lwz r3,56(r1) // RG_STACK, 0(RG_REAL_STACK) lwz r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK) lwz r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK) lwz r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK) lwz r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK) lwz r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK) lwz r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK) lwz r10,84(r1) // RG_VM, 28(RG_REAL_STACK) lwz r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK) addi r1,r1,92 // RG_REAL_STACK, RG_REAL_STACK, 36 // restore the old link register mtlr r13 // RG_SECOND // save off the return value stwu r12,4(r4) // RG_TOP, 0(RG_OPSTACK) // GCC adds its own prolog / epliog code " ); } #endif
ouned/JK2-1.04
qcommon/vm_ppc.cpp
C++
gpl-2.0
43,229
/* * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Shadowmoon_Valley SD%Complete: 100 SDComment: Quest support: 10583, 10601, 10804, 10854, 10458, 10481, 10480, 10781, 10451. Vendor Drake Dealer Hurlunk. SDCategory: Shadowmoon Valley EndScriptData */ /* ContentData npc_invis_infernal_caster npc_infernal_attacker npc_mature_netherwing_drake npc_enslaved_netherwing_drake npc_drake_dealer_hurlunk npcs_flanis_swiftwing_and_kagrosh npc_karynaku npc_earthmender_wilda npc_torloth_the_magnificent npc_illidari_spawn npc_lord_illidan_stormrage go_crystal_prison npc_enraged_spirit EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Group.h" #include "SpellScript.h" #include "Player.h" #include "WorldSession.h" /*##### # npc_invis_infernal_caster #####*/ enum InvisInfernalCaster { EVENT_CAST_SUMMON_INFERNAL = 1, NPC_INFERNAL_ATTACKER = 21419, MODEL_INVISIBLE = 20577, MODEL_INFERNAL = 17312, SPELL_SUMMON_INFERNAL = 37277, TYPE_INFERNAL = 1, DATA_DIED = 1 }; class npc_invis_infernal_caster : public CreatureScript { public: npc_invis_infernal_caster() : CreatureScript("npc_invis_infernal_caster") { } struct npc_invis_infernal_casterAI : public ScriptedAI { npc_invis_infernal_casterAI(Creature* creature) : ScriptedAI(creature) { ground = 0.f; } void Reset() override { ground = me->GetMap()->GetHeight(me->GetPositionX(), me->GetPositionY(), me->GetPositionZMinusOffset()); SummonInfernal(); events.ScheduleEvent(EVENT_CAST_SUMMON_INFERNAL, urand(1000, 3000)); } void SetData(uint32 id, uint32 data) override { if (id == TYPE_INFERNAL && data == DATA_DIED) SummonInfernal(); } void SummonInfernal() { Creature* infernal = me->SummonCreature(NPC_INFERNAL_ATTACKER, me->GetPositionX(), me->GetPositionY(), ground + 0.05f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); infernalGUID = infernal->GetGUID(); } void UpdateAI(uint32 diff) override { events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CAST_SUMMON_INFERNAL: { if (Unit* infernal = ObjectAccessor::GetUnit(*me, infernalGUID)) if (infernal->GetDisplayId() == MODEL_INVISIBLE) me->CastSpell(infernal, SPELL_SUMMON_INFERNAL, true); events.ScheduleEvent(EVENT_CAST_SUMMON_INFERNAL, 12000); break; } default: break; } } } private: EventMap events; ObjectGuid infernalGUID; float ground; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_invis_infernal_casterAI(creature); } }; /*##### # npc_infernal_attacker #####*/ class npc_infernal_attacker : public CreatureScript { public: npc_infernal_attacker() : CreatureScript("npc_infernal_attacker") { } struct npc_infernal_attackerAI : public ScriptedAI { npc_infernal_attackerAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { me->SetDisplayId(MODEL_INVISIBLE); me->GetMotionMaster()->MoveRandom(5.0f); } void IsSummonedBy(Unit* summoner) override { if (summoner->ToCreature()) casterGUID = summoner->ToCreature()->GetGUID();; } void JustDied(Unit* /*killer*/) override { if (Creature* caster = ObjectAccessor::GetCreature(*me, casterGUID)) caster->AI()->SetData(TYPE_INFERNAL, DATA_DIED); } void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override { if (spell->Id == SPELL_SUMMON_INFERNAL) { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_PACIFIED | UNIT_FLAG_NOT_SELECTABLE); me->SetDisplayId(MODEL_INFERNAL); } } void UpdateAI(uint32 /*diff*/) override { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } private: ObjectGuid casterGUID; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_infernal_attackerAI(creature); } }; /*##### # npc_mature_netherwing_drake #####*/ enum MatureNetherwing { SAY_JUST_EATEN = 0, SPELL_PLACE_CARCASS = 38439, SPELL_JUST_EATEN = 38502, SPELL_NETHER_BREATH = 38467, POINT_ID = 1, GO_CARCASS = 185155, QUEST_KINDNESS = 10804, NPC_EVENT_PINGER = 22131 }; class npc_mature_netherwing_drake : public CreatureScript { public: npc_mature_netherwing_drake() : CreatureScript("npc_mature_netherwing_drake") { } CreatureAI* GetAI(Creature* creature) const override { return new npc_mature_netherwing_drakeAI(creature); } struct npc_mature_netherwing_drakeAI : public ScriptedAI { npc_mature_netherwing_drakeAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { uiPlayerGUID.Clear(); bCanEat = false; bIsEating = false; EatTimer = 5000; CastTimer = 5000; } ObjectGuid uiPlayerGUID; bool bCanEat; bool bIsEating; uint32 EatTimer; uint32 CastTimer; void Reset() override { Initialize(); } void SpellHit(Unit* pCaster, SpellInfo const* spell) override { if (bCanEat || bIsEating) return; if (pCaster->GetTypeId() == TYPEID_PLAYER && spell->Id == SPELL_PLACE_CARCASS && !me->HasAura(SPELL_JUST_EATEN)) { uiPlayerGUID = pCaster->GetGUID(); bCanEat = true; } } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE) return; if (id == POINT_ID) { bIsEating = true; EatTimer = 7000; me->HandleEmoteCommand(EMOTE_ONESHOT_ATTACK_UNARMED); } } void UpdateAI(uint32 diff) override { if (bCanEat || bIsEating) { if (EatTimer <= diff) { if (bCanEat && !bIsEating) { if (Unit* unit = ObjectAccessor::GetUnit(*me, uiPlayerGUID)) { if (GameObject* go = unit->FindNearestGameObject(GO_CARCASS, 10)) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MoveIdle(); me->StopMoving(); me->GetMotionMaster()->MovePoint(POINT_ID, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()); } } bCanEat = false; } else if (bIsEating) { DoCast(me, SPELL_JUST_EATEN); Talk(SAY_JUST_EATEN); if (Player* player = ObjectAccessor::GetPlayer(*me, uiPlayerGUID)) { player->KilledMonsterCredit(NPC_EVENT_PINGER); if (GameObject* go = player->FindNearestGameObject(GO_CARCASS, 10)) go->Delete(); } Reset(); me->GetMotionMaster()->Clear(); } } else EatTimer -= diff; return; } if (!UpdateVictim()) return; if (CastTimer <= diff) { DoCastVictim(SPELL_NETHER_BREATH); CastTimer = 5000; } else CastTimer -= diff; DoMeleeAttackIfReady(); } }; }; /*### # npc_enslaved_netherwing_drake ####*/ enum EnshlavedNetherwingDrake { // Factions FACTION_DEFAULT = 62, FACTION_FRIENDLY = 1840, // Not sure if this is correct, it was taken off of Mordenai. // Spells SPELL_HIT_FORCE_OF_NELTHARAKU = 38762, SPELL_FORCE_OF_NELTHARAKU = 38775, // Creatures NPC_DRAGONMAW_SUBJUGATOR = 21718, NPC_ESCAPE_DUMMY = 22317 }; class npc_enslaved_netherwing_drake : public CreatureScript { public: npc_enslaved_netherwing_drake() : CreatureScript("npc_enslaved_netherwing_drake") { } CreatureAI* GetAI(Creature* creature) const override { return new npc_enslaved_netherwing_drakeAI(creature); } struct npc_enslaved_netherwing_drakeAI : public ScriptedAI { npc_enslaved_netherwing_drakeAI(Creature* creature) : ScriptedAI(creature) { Tapped = false; Reset(); } ObjectGuid PlayerGUID; uint32 FlyTimer; bool Tapped; void Reset() override { if (!Tapped) me->setFaction(FACTION_DEFAULT); FlyTimer = 10000; me->SetDisableGravity(false); me->SetVisible(true); } void SpellHit(Unit* caster, const SpellInfo* spell) override { if (!caster) return; if (caster->GetTypeId() == TYPEID_PLAYER && spell->Id == SPELL_HIT_FORCE_OF_NELTHARAKU && !Tapped) { Tapped = true; PlayerGUID = caster->GetGUID(); me->setFaction(FACTION_FRIENDLY); DoCast(caster, SPELL_FORCE_OF_NELTHARAKU, true); Unit* Dragonmaw = me->FindNearestCreature(NPC_DRAGONMAW_SUBJUGATOR, 50); if (Dragonmaw) { me->AddThreat(Dragonmaw, 100000.0f); AttackStart(Dragonmaw); } HostileReference* ref = me->getThreatManager().getOnlineContainer().getReferenceByTarget(caster); if (ref) ref->removeReference(); } } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE) return; if (id == 1) { if (!PlayerGUID.IsEmpty()) { Unit* player = ObjectAccessor::GetUnit(*me, PlayerGUID); if (player) DoCast(player, SPELL_FORCE_OF_NELTHARAKU, true); PlayerGUID.Clear(); } me->SetVisible(false); me->SetDisableGravity(false); me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); me->RemoveCorpse(); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) { if (Tapped) { if (FlyTimer <= diff) { Tapped = false; if (!PlayerGUID.IsEmpty()) { Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID); if (player && player->GetQuestStatus(10854) == QUEST_STATUS_INCOMPLETE) { DoCast(player, SPELL_FORCE_OF_NELTHARAKU, true); /* float x, y, z; me->GetPosition(x, y, z); float dx, dy, dz; me->GetRandomPoint(x, y, z, 20, dx, dy, dz); dz += 20; // so it's in the air, not ground*/ Position pos; if (Unit* EscapeDummy = me->FindNearestCreature(NPC_ESCAPE_DUMMY, 30)) pos = EscapeDummy->GetPosition(); else { pos = me->GetRandomNearPosition(20); pos.m_positionZ += 25; } me->SetDisableGravity(true); me->GetMotionMaster()->MovePoint(1, pos); } } } else FlyTimer -= diff; } return; } DoMeleeAttackIfReady(); } }; }; /*##### # npc_dragonmaw_peon #####*/ class npc_dragonmaw_peon : public CreatureScript { public: npc_dragonmaw_peon() : CreatureScript("npc_dragonmaw_peon") { } CreatureAI* GetAI(Creature* creature) const override { return new npc_dragonmaw_peonAI(creature); } struct npc_dragonmaw_peonAI : public ScriptedAI { npc_dragonmaw_peonAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { PlayerGUID.Clear(); Tapped = false; PoisonTimer = 0; } ObjectGuid PlayerGUID; bool Tapped; uint32 PoisonTimer; void Reset() override { Initialize(); } void SpellHit(Unit* caster, const SpellInfo* spell) override { if (!caster) return; if (caster->GetTypeId() == TYPEID_PLAYER && spell->Id == 40468 && !Tapped) { PlayerGUID = caster->GetGUID(); Tapped = true; float x, y, z; caster->GetClosePoint(x, y, z, me->GetObjectSize()); me->SetWalk(false); me->GetMotionMaster()->MovePoint(1, x, y, z); } } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE) return; if (id) { me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_EAT); PoisonTimer = 15000; } } void UpdateAI(uint32 diff) override { if (PoisonTimer) { if (PoisonTimer <= diff) { if (!PlayerGUID.IsEmpty()) { Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID); if (player && player->GetQuestStatus(11020) == QUEST_STATUS_INCOMPLETE) player->KilledMonsterCredit(23209); } PoisonTimer = 0; me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } else PoisonTimer -= diff; } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; /*###### ## npc_drake_dealer_hurlunk ######*/ class npc_drake_dealer_hurlunk : public CreatureScript { public: npc_drake_dealer_hurlunk() : CreatureScript("npc_drake_dealer_hurlunk") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_TRADE) player->GetSession()->SendListInventory(creature->GetGUID()); return true; } bool OnGossipHello(Player* player, Creature* creature) override { if (creature->IsVendor() && player->GetReputationRank(1015) == REP_EXALTED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; /*###### ## npc_flanis_swiftwing_and_kagrosh ######*/ #define GOSSIP_HSK1 "Take Flanis's Pack" #define GOSSIP_HSK2 "Take Kagrosh's Pack" class npcs_flanis_swiftwing_and_kagrosh : public CreatureScript { public: npcs_flanis_swiftwing_and_kagrosh() : CreatureScript("npcs_flanis_swiftwing_and_kagrosh") { } bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) { ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 30658, 1, NULL); if (msg == EQUIP_ERR_OK) { player->StoreNewItem(dest, 30658, true); player->PlayerTalkClass->ClearMenus(); } } if (action == GOSSIP_ACTION_INFO_DEF+2) { ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 30659, 1, NULL); if (msg == EQUIP_ERR_OK) { player->StoreNewItem(dest, 30659, true); player->PlayerTalkClass->ClearMenus(); } } return true; } bool OnGossipHello(Player* player, Creature* creature) override { if (player->GetQuestStatus(10583) == QUEST_STATUS_INCOMPLETE && !player->HasItemCount(30658, 1, true)) player->ADD_GOSSIP_ITEM(0, GOSSIP_HSK1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); if (player->GetQuestStatus(10601) == QUEST_STATUS_INCOMPLETE && !player->HasItemCount(30659, 1, true)) player->ADD_GOSSIP_ITEM(0, GOSSIP_HSK2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; /*###### # npc_karynaku ####*/ enum Karynaku { QUEST_ALLY_OF_NETHER = 10870, QUEST_ZUHULED_THE_WACK = 10866, NPC_ZUHULED_THE_WACKED = 11980, TAXI_PATH_ID = 649, }; class npc_karynaku : public CreatureScript { public: npc_karynaku() : CreatureScript("npc_karynaku") { } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override { if (quest->GetQuestId() == QUEST_ALLY_OF_NETHER) player->ActivateTaxiPathTo(TAXI_PATH_ID); if (quest->GetQuestId() == QUEST_ZUHULED_THE_WACK) creature->SummonCreature(NPC_ZUHULED_THE_WACKED, -4204.94f, 316.397f, 122.508f, 1.309f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 300000); return true; } }; /*#### # npc_earthmender_wilda ####*/ enum Earthmender { SAY_WIL_START = 0, SAY_WIL_AGGRO = 1, SAY_WIL_PROGRESS1 = 2, SAY_WIL_PROGRESS2 = 3, SAY_WIL_FIND_EXIT = 4, SAY_WIL_JUST_AHEAD = 5, SAY_WIL_END = 6, SPELL_CHAIN_LIGHTNING = 16006, SPELL_EARTHBING_TOTEM = 15786, SPELL_FROST_SHOCK = 12548, SPELL_HEALING_WAVE = 12491, QUEST_ESCAPE_COILSCAR = 10451, NPC_COILSKAR_ASSASSIN = 21044, FACTION_EARTHEN = 1726 //guessed }; class npc_earthmender_wilda : public CreatureScript { public: npc_earthmender_wilda() : CreatureScript("npc_earthmender_wilda") { } bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) override { if (quest->GetQuestId() == QUEST_ESCAPE_COILSCAR) { creature->AI()->Talk(SAY_WIL_START, player); creature->setFaction(FACTION_EARTHEN); if (npc_earthmender_wildaAI* pEscortAI = CAST_AI(npc_earthmender_wilda::npc_earthmender_wildaAI, creature->AI())) pEscortAI->Start(false, false, player->GetGUID(), quest); } return true; } CreatureAI* GetAI(Creature* creature) const override { return new npc_earthmender_wildaAI(creature); } struct npc_earthmender_wildaAI : public npc_escortAI { npc_earthmender_wildaAI(Creature* creature) : npc_escortAI(creature) { Initialize(); } void Initialize() { m_uiHealingTimer = 0; } uint32 m_uiHealingTimer; void Reset() override { Initialize(); } void WaypointReached(uint32 waypointId) override { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 13: Talk(SAY_WIL_PROGRESS1, player); DoSpawnAssassin(); break; case 14: DoSpawnAssassin(); break; case 15: Talk(SAY_WIL_FIND_EXIT, player); break; case 19: DoRandomSay(); break; case 20: DoSpawnAssassin(); break; case 26: DoRandomSay(); break; case 27: DoSpawnAssassin(); break; case 33: DoRandomSay(); break; case 34: DoSpawnAssassin(); break; case 37: DoRandomSay(); break; case 38: DoSpawnAssassin(); break; case 39: Talk(SAY_WIL_JUST_AHEAD, player); break; case 43: DoRandomSay(); break; case 44: DoSpawnAssassin(); break; case 50: Talk(SAY_WIL_END, player); player->GroupEventHappens(QUEST_ESCAPE_COILSCAR, me); break; } } void JustSummoned(Creature* summoned) override { if (summoned->GetEntry() == NPC_COILSKAR_ASSASSIN) summoned->AI()->AttackStart(me); } //this is very unclear, random say without no real relevance to script/event void DoRandomSay() { Talk(SAY_WIL_PROGRESS2); } void DoSpawnAssassin() { //unknown where they actually appear DoSummon(NPC_COILSKAR_ASSASSIN, me, 15.0f, 5000, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT); } void EnterCombat(Unit* who) override { //don't always use if (rand32() % 5) return; //only aggro text if not player if (who->GetTypeId() != TYPEID_PLAYER) { //appears to be random if (urand(0, 1)) Talk(SAY_WIL_AGGRO); } } void UpdateAI(uint32 uiDiff) override { npc_escortAI::UpdateAI(uiDiff); if (!UpdateVictim()) return; /// @todo add more abilities if (!HealthAbovePct(30)) { if (m_uiHealingTimer <= uiDiff) { DoCast(me, SPELL_HEALING_WAVE); m_uiHealingTimer = 15000; } else m_uiHealingTimer -= uiDiff; } } }; }; /*##### # Quest: Battle of the crimson watch #####*/ /* ContentData Battle of the crimson watch - creatures, gameobjects and defines npc_illidari_spawn : Adds that are summoned in the Crimson Watch battle. npc_torloth_the_magnificent : Final Creature that players have to face before quest is completed npc_lord_illidan_stormrage : Creature that controls the event. go_crystal_prison : GameObject that begins the event and hands out quest EndContentData */ #define QUEST_BATTLE_OF_THE_CRIMSON_WATCH 10781 #define EVENT_AREA_RADIUS 65 //65yds #define EVENT_COOLDOWN 30000 //in ms. appear after event completed or failed (should be = Adds despawn time) struct TorlothCinematic { uint32 creature, Timer; }; // Creature 0 - Torloth, 1 - Illidan static TorlothCinematic TorlothAnim[]= { {0, 2000}, {1, 7000}, {0, 3000}, {0, 2000}, // Torloth stand {0, 1000}, {0, 3000}, {0, 0} }; //Cordinates for Spawns static Position SpawnLocation[]= { //Cords used for: {-4615.8556f, 1342.2532f, 139.9f, 1.612f}, //Illidari Soldier {-4598.9365f, 1377.3182f, 139.9f, 3.917f}, //Illidari Soldier {-4598.4697f, 1360.8999f, 139.9f, 2.427f}, //Illidari Soldier {-4589.3599f, 1369.1061f, 139.9f, 3.165f}, //Illidari Soldier {-4608.3477f, 1386.0076f, 139.9f, 4.108f}, //Illidari Soldier {-4633.1889f, 1359.8033f, 139.9f, 0.949f}, //Illidari Soldier {-4623.5791f, 1351.4574f, 139.9f, 0.971f}, //Illidari Soldier {-4607.2988f, 1351.6099f, 139.9f, 2.416f}, //Illidari Soldier {-4633.7764f, 1376.0417f, 139.9f, 5.608f}, //Illidari Soldier {-4600.2461f, 1369.1240f, 139.9f, 3.056f}, //Illidari Mind Breaker {-4631.7808f, 1367.9459f, 139.9f, 0.020f}, //Illidari Mind Breaker {-4600.2461f, 1369.1240f, 139.9f, 3.056f}, //Illidari Highlord {-4631.7808f, 1367.9459f, 139.9f, 0.020f}, //Illidari Highlord {-4615.5586f, 1353.0031f, 139.9f, 1.540f}, //Illidari Highlord {-4616.4736f, 1384.2170f, 139.9f, 4.971f}, //Illidari Highlord {-4627.1240f, 1378.8752f, 139.9f, 2.544f} //Torloth The Magnificent }; struct WaveData { uint8 SpawnCount, UsedSpawnPoint; uint32 CreatureId, SpawnTimer, YellTimer; }; static WaveData WavesInfo[]= { {9, 0, 22075, 10000, 7000}, //Illidari Soldier {2, 9, 22074, 10000, 7000}, //Illidari Mind Breaker {4, 11, 19797, 10000, 7000}, //Illidari Highlord {1, 15, 22076, 10000, 7000} //Torloth The Magnificent }; struct SpawnSpells { uint32 Timer1, Timer2, SpellId; }; static SpawnSpells SpawnCast[]= { {10000, 15000, 35871}, // Illidari Soldier Cast - Spellbreaker {10000, 10000, 38985}, // Illidari Mind Breake Cast - Focused Bursts {35000, 35000, 22884}, // Illidari Mind Breake Cast - Psychic Scream {20000, 20000, 17194}, // Illidari Mind Breake Cast - Mind Blast {8000, 15000, 38010}, // Illidari Highlord Cast - Curse of Flames {12000, 20000, 16102}, // Illidari Highlord Cast - Flamestrike {10000, 15000, 15284}, // Torloth the Magnificent Cast - Cleave {18000, 20000, 39082}, // Torloth the Magnificent Cast - Shadowfury {25000, 28000, 33961} // Torloth the Magnificent Cast - Spell Reflection }; /*###### # npc_torloth_the_magnificent #####*/ class npc_torloth_the_magnificent : public CreatureScript { public: npc_torloth_the_magnificent() : CreatureScript("npc_torloth_the_magnificent") { } CreatureAI* GetAI(Creature* c) const override { return new npc_torloth_the_magnificentAI(c); } struct npc_torloth_the_magnificentAI : public ScriptedAI { npc_torloth_the_magnificentAI(Creature* creature) : ScriptedAI(creature) { Initialize(); SpellTimer1 = 0; SpellTimer2 = 0; SpellTimer3 = 0; } void Initialize() { AnimationTimer = 4000; AnimationCount = 0; LordIllidanGUID.Clear(); AggroTargetGUID.Clear(); Timers = false; } uint32 AnimationTimer, SpellTimer1, SpellTimer2, SpellTimer3; uint8 AnimationCount; ObjectGuid LordIllidanGUID; ObjectGuid AggroTargetGUID; bool Timers; void Reset() override { Initialize(); me->AddUnitState(UNIT_STATE_ROOT); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->SetTarget(ObjectGuid::Empty); } void EnterCombat(Unit* /*who*/) override { } void HandleAnimation() { Creature* creature = me; if (TorlothAnim[AnimationCount].creature == 1) { creature = (ObjectAccessor::GetCreature(*me, LordIllidanGUID)); if (!creature) return; } AnimationTimer = TorlothAnim[AnimationCount].Timer; switch (AnimationCount) { case 0: me->SetUInt32Value(UNIT_FIELD_BYTES_1, 8); break; case 3: me->RemoveFlag(UNIT_FIELD_BYTES_1, 8); break; case 5: if (Player* AggroTarget = ObjectAccessor::GetPlayer(*me, AggroTargetGUID)) { me->SetTarget(AggroTarget->GetGUID()); me->AddThreat(AggroTarget, 1); me->HandleEmoteCommand(EMOTE_ONESHOT_POINT); } break; case 6: if (Player* AggroTarget = ObjectAccessor::GetPlayer(*me, AggroTargetGUID)) { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->ClearUnitState(UNIT_STATE_ROOT); float x, y, z; AggroTarget->GetPosition(x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); } break; } ++AnimationCount; } void UpdateAI(uint32 diff) override { if (AnimationTimer) { if (AnimationTimer <= diff) { HandleAnimation(); } else AnimationTimer -= diff; } if (AnimationCount < 6) { me->CombatStop(); } else if (!Timers) { SpellTimer1 = SpawnCast[6].Timer1; SpellTimer2 = SpawnCast[7].Timer1; SpellTimer3 = SpawnCast[8].Timer1; Timers = true; } if (Timers) { if (SpellTimer1 <= diff) { DoCastVictim(SpawnCast[6].SpellId);//Cleave SpellTimer1 = SpawnCast[6].Timer2 + (rand32() % 10 * 1000); } else SpellTimer1 -= diff; if (SpellTimer2 <= diff) { DoCastVictim(SpawnCast[7].SpellId);//Shadowfury SpellTimer2 = SpawnCast[7].Timer2 + (rand32() % 5 * 1000); } else SpellTimer2 -= diff; if (SpellTimer3 <= diff) { DoCast(me, SpawnCast[8].SpellId); SpellTimer3 = SpawnCast[8].Timer2 + (rand32() % 7 * 1000);//Spell Reflection } else SpellTimer3 -= diff; } DoMeleeAttackIfReady(); } void JustDied(Unit* killer) override { switch (killer->GetTypeId()) { case TYPEID_UNIT: if (Unit* owner = killer->GetOwner()) if (Player* player = owner->ToPlayer()) player->GroupEventHappens(QUEST_BATTLE_OF_THE_CRIMSON_WATCH, me); break; case TYPEID_PLAYER: if (Player* player = killer->ToPlayer()) player->GroupEventHappens(QUEST_BATTLE_OF_THE_CRIMSON_WATCH, me); break; default: break; } if (Creature* LordIllidan = (ObjectAccessor::GetCreature(*me, LordIllidanGUID))) LordIllidan->AI()->EnterEvadeMode(); } }; }; /*##### # npc_lord_illidan_stormrage #####*/ class npc_lord_illidan_stormrage : public CreatureScript { public: npc_lord_illidan_stormrage() : CreatureScript("npc_lord_illidan_stormrage") { } CreatureAI* GetAI(Creature* c) const override { return new npc_lord_illidan_stormrageAI(c); } struct npc_lord_illidan_stormrageAI : public ScriptedAI { npc_lord_illidan_stormrageAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { PlayerGUID.Clear(); WaveTimer = 10000; AnnounceTimer = 7000; LiveCount = 0; WaveCount = 0; EventStarted = false; Announced = false; Failed = false; } ObjectGuid PlayerGUID; uint32 WaveTimer; uint32 AnnounceTimer; int8 LiveCount; uint8 WaveCount; bool EventStarted; bool Announced; bool Failed; void Reset() override { Initialize(); me->SetVisible(false); } void EnterCombat(Unit* /*who*/) override { } void MoveInLineOfSight(Unit* /*who*/) override { } void AttackStart(Unit* /*who*/) override { } void SummonNextWave(); void CheckEventFail() { Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID); if (!player) return; if (Group* EventGroup = player->GetGroup()) { uint8 GroupMemberCount = 0; uint8 DeadMemberCount = 0; uint8 FailedMemberCount = 0; Group::MemberSlotList const& members = EventGroup->GetMemberSlots(); for (Group::member_citerator itr = members.begin(); itr!= members.end(); ++itr) { Player* GroupMember = ObjectAccessor::GetPlayer(*me, itr->guid); if (!GroupMember) continue; if (!GroupMember->IsWithinDistInMap(me, EVENT_AREA_RADIUS) && GroupMember->GetQuestStatus(QUEST_BATTLE_OF_THE_CRIMSON_WATCH) == QUEST_STATUS_INCOMPLETE) { GroupMember->FailQuest(QUEST_BATTLE_OF_THE_CRIMSON_WATCH); ++FailedMemberCount; } ++GroupMemberCount; if (GroupMember->isDead()) ++DeadMemberCount; } if (GroupMemberCount == FailedMemberCount) { Failed = true; } if (GroupMemberCount == DeadMemberCount) { for (Group::member_citerator itr = members.begin(); itr!= members.end(); ++itr) { if (Player* groupMember = ObjectAccessor::GetPlayer(*me, itr->guid)) if (groupMember->GetQuestStatus(QUEST_BATTLE_OF_THE_CRIMSON_WATCH) == QUEST_STATUS_INCOMPLETE) groupMember->FailQuest(QUEST_BATTLE_OF_THE_CRIMSON_WATCH); } Failed = true; } } else if (player->isDead() || !player->IsWithinDistInMap(me, EVENT_AREA_RADIUS)) { player->FailQuest(QUEST_BATTLE_OF_THE_CRIMSON_WATCH); Failed = true; } } void LiveCounter() { --LiveCount; if (!LiveCount) Announced = false; } void UpdateAI(uint32 diff) override { if (!PlayerGUID || !EventStarted) return; if (!LiveCount && WaveCount < 4) { if (!Announced && AnnounceTimer <= diff) { Announced = true; } else AnnounceTimer -= diff; if (WaveTimer <= diff) { SummonNextWave(); } else WaveTimer -= diff; } CheckEventFail(); if (Failed) EnterEvadeMode(); } }; }; /*###### # npc_illidari_spawn ######*/ class npc_illidari_spawn : public CreatureScript { public: npc_illidari_spawn() : CreatureScript("npc_illidari_spawn") { } CreatureAI* GetAI(Creature* c) const override { return new npc_illidari_spawnAI(c); } struct npc_illidari_spawnAI : public ScriptedAI { npc_illidari_spawnAI(Creature* creature) : ScriptedAI(creature) { Initialize(); SpellTimer1 = 0; SpellTimer2 = 0; SpellTimer3 = 0; } void Initialize() { LordIllidanGUID.Clear(); Timers = false; } ObjectGuid LordIllidanGUID; uint32 SpellTimer1, SpellTimer2, SpellTimer3; bool Timers; void Reset() override { Initialize(); } void EnterCombat(Unit* /*who*/) override { } void JustDied(Unit* /*killer*/) override { me->RemoveCorpse(); if (Creature* LordIllidan = (ObjectAccessor::GetCreature(*me, LordIllidanGUID))) if (LordIllidan) ENSURE_AI(npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI, LordIllidan->AI())->LiveCounter(); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (!Timers) { if (me->GetEntry() == 22075)//Illidari Soldier { SpellTimer1 = SpawnCast[0].Timer1 + (rand32() % 4 * 1000); } if (me->GetEntry() == 22074)//Illidari Mind Breaker { SpellTimer1 = SpawnCast[1].Timer1 + (rand32() % 10 * 1000); SpellTimer2 = SpawnCast[2].Timer1 + (rand32() % 4 * 1000); SpellTimer3 = SpawnCast[3].Timer1 + (rand32() % 4 * 1000); } if (me->GetEntry() == 19797)// Illidari Highlord { SpellTimer1 = SpawnCast[4].Timer1 + (rand32() % 4 * 1000); SpellTimer2 = SpawnCast[5].Timer1 + (rand32() % 4 * 1000); } Timers = true; } //Illidari Soldier if (me->GetEntry() == 22075) { if (SpellTimer1 <= diff) { DoCastVictim(SpawnCast[0].SpellId);//Spellbreaker SpellTimer1 = SpawnCast[0].Timer2 + (rand32() % 5 * 1000); } else SpellTimer1 -= diff; } //Illidari Mind Breaker if (me->GetEntry() == 22074) { if (SpellTimer1 <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { if (target->GetTypeId() == TYPEID_PLAYER) { DoCast(target, SpawnCast[1].SpellId); //Focused Bursts SpellTimer1 = SpawnCast[1].Timer2 + (rand32() % 5 * 1000); } else SpellTimer1 = 2000; } } else SpellTimer1 -= diff; if (SpellTimer2 <= diff) { DoCastVictim(SpawnCast[2].SpellId);//Psychic Scream SpellTimer2 = SpawnCast[2].Timer2 + (rand32() % 13 * 1000); } else SpellTimer2 -= diff; if (SpellTimer3 <= diff) { DoCastVictim(SpawnCast[3].SpellId);//Mind Blast SpellTimer3 = SpawnCast[3].Timer2 + (rand32() % 8 * 1000); } else SpellTimer3 -= diff; } //Illidari Highlord if (me->GetEntry() == 19797) { if (SpellTimer1 <= diff) { DoCastVictim(SpawnCast[4].SpellId);//Curse Of Flames SpellTimer1 = SpawnCast[4].Timer2 + (rand32() % 10 * 1000); } else SpellTimer1 -= diff; if (SpellTimer2 <= diff) { DoCastVictim(SpawnCast[5].SpellId);//Flamestrike SpellTimer2 = SpawnCast[5].Timer2 + (rand32() % 7 * 13000); } else SpellTimer2 -= diff; } DoMeleeAttackIfReady(); } }; }; void npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI::SummonNextWave() { uint8 count = WavesInfo[WaveCount].SpawnCount; uint8 locIndex = WavesInfo[WaveCount].UsedSpawnPoint; uint8 FelguardCount = 0; uint8 DreadlordCount = 0; for (uint8 i = 0; i < count; ++i) { Creature* Spawn = me->SummonCreature(WavesInfo[WaveCount].CreatureId, SpawnLocation[locIndex + i], TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); ++LiveCount; if (Spawn) { Spawn->LoadCreaturesAddon(); if (WaveCount == 0)//1 Wave { if (rand32() % 3 == 1 && FelguardCount<2) { Spawn->SetDisplayId(18654); ++FelguardCount; } else if (DreadlordCount < 3) { Spawn->SetDisplayId(19991); ++DreadlordCount; } else if (FelguardCount<2) { Spawn->SetDisplayId(18654); ++FelguardCount; } } if (WaveCount < 3)//1-3 Wave { if (!PlayerGUID.IsEmpty()) { if (Player* target = ObjectAccessor::GetPlayer(*me, PlayerGUID)) { float x, y, z; target->GetPosition(x, y, z); Spawn->GetMotionMaster()->MovePoint(0, x, y, z); } } ENSURE_AI(npc_illidari_spawn::npc_illidari_spawnAI, Spawn->AI())->LordIllidanGUID = me->GetGUID(); } if (WavesInfo[WaveCount].CreatureId == 22076) // Torloth { ENSURE_AI(npc_torloth_the_magnificent::npc_torloth_the_magnificentAI, Spawn->AI())->LordIllidanGUID = me->GetGUID(); if (!PlayerGUID.IsEmpty()) ENSURE_AI(npc_torloth_the_magnificent::npc_torloth_the_magnificentAI, Spawn->AI())->AggroTargetGUID = PlayerGUID; } } } ++WaveCount; WaveTimer = WavesInfo[WaveCount].SpawnTimer; AnnounceTimer = WavesInfo[WaveCount].YellTimer; } /*##### # go_crystal_prison ######*/ class go_crystal_prison : public GameObjectScript { public: go_crystal_prison() : GameObjectScript("go_crystal_prison") { } bool OnQuestAccept(Player* player, GameObject* /*go*/, Quest const* quest) override { if (quest->GetQuestId() == QUEST_BATTLE_OF_THE_CRIMSON_WATCH) { Creature* Illidan = player->FindNearestCreature(22083, 50); if (Illidan && !ENSURE_AI(npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI, Illidan->AI())->EventStarted) { ENSURE_AI(npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI, Illidan->AI())->PlayerGUID = player->GetGUID(); ENSURE_AI(npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI, Illidan->AI())->LiveCount = 0; ENSURE_AI(npc_lord_illidan_stormrage::npc_lord_illidan_stormrageAI, Illidan->AI())->EventStarted = true; } } return true; } }; /*#### # npc_enraged_spirits ####*/ enum Enraged_Dpirits { // QUESTS QUEST_ENRAGED_SPIRITS_FIRE_EARTH = 10458, QUEST_ENRAGED_SPIRITS_AIR = 10481, QUEST_ENRAGED_SPIRITS_WATER = 10480, // Totem ENTRY_TOTEM_OF_SPIRITS = 21071, RADIUS_TOTEM_OF_SPIRITS = 15, // SPIRITS NPC_ENRAGED_EARTH_SPIRIT = 21050, NPC_ENRAGED_FIRE_SPIRIT = 21061, NPC_ENRAGED_AIR_SPIRIT = 21060, NPC_ENRAGED_WATER_SPIRIT = 21059, // SOULS NPC_EARTHEN_SOUL = 21073, NPC_FIERY_SOUL = 21097, NPC_ENRAGED_AIRY_SOUL = 21116, NPC_ENRAGED_WATERY_SOUL = 21109, // wrong model // SPELL KILLCREDIT - not working!?! - using KilledMonsterCredit SPELL_EARTHEN_SOUL_CAPTURED_CREDIT = 36108, SPELL_FIERY_SOUL_CAPTURED_CREDIT = 36117, SPELL_AIRY_SOUL_CAPTURED_CREDIT = 36182, SPELL_WATERY_SOUL_CAPTURED_CREDIT = 36171, // KilledMonsterCredit Workaround NPC_CREDIT_FIRE = 21094, NPC_CREDIT_WATER = 21095, NPC_CREDIT_AIR = 21096, NPC_CREDIT_EARTH = 21092, // Captured Spell / Buff SPELL_SOUL_CAPTURED = 36115, // Factions FACTION_ENRAGED_SOUL_FRIENDLY = 35, FACTION_ENRAGED_SOUL_HOSTILE = 14 }; class npc_enraged_spirit : public CreatureScript { public: npc_enraged_spirit() : CreatureScript("npc_enraged_spirit") { } CreatureAI* GetAI(Creature* creature) const override { return new npc_enraged_spiritAI(creature); } struct npc_enraged_spiritAI : public ScriptedAI { npc_enraged_spiritAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { } void EnterCombat(Unit* /*who*/) override { } void JustDied(Unit* /*killer*/) override { // always spawn spirit on death // if totem around // move spirit to totem and cast kill count uint32 entry = 0; uint32 credit = 0; switch (me->GetEntry()) { case NPC_ENRAGED_FIRE_SPIRIT: entry = NPC_FIERY_SOUL; //credit = SPELL_FIERY_SOUL_CAPTURED_CREDIT; credit = NPC_CREDIT_FIRE; break; case NPC_ENRAGED_EARTH_SPIRIT: entry = NPC_EARTHEN_SOUL; //credit = SPELL_EARTHEN_SOUL_CAPTURED_CREDIT; credit = NPC_CREDIT_EARTH; break; case NPC_ENRAGED_AIR_SPIRIT: entry = NPC_ENRAGED_AIRY_SOUL; //credit = SPELL_AIRY_SOUL_CAPTURED_CREDIT; credit = NPC_CREDIT_AIR; break; case NPC_ENRAGED_WATER_SPIRIT: entry = NPC_ENRAGED_WATERY_SOUL; //credit = SPELL_WATERY_SOUL_CAPTURED_CREDIT; credit = NPC_CREDIT_WATER; break; default: break; } // Spawn Soul on Kill ALWAYS! Creature* Summoned = NULL; Unit* totemOspirits = NULL; if (entry != 0) Summoned = DoSpawnCreature(entry, 0, 0, 1, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 5000); // FIND TOTEM, PROCESS QUEST if (Summoned) { totemOspirits = me->FindNearestCreature(ENTRY_TOTEM_OF_SPIRITS, RADIUS_TOTEM_OF_SPIRITS); if (totemOspirits) { Summoned->setFaction(FACTION_ENRAGED_SOUL_FRIENDLY); Summoned->GetMotionMaster()->MovePoint(0, totemOspirits->GetPositionX(), totemOspirits->GetPositionY(), Summoned->GetPositionZ()); if (Unit* owner = totemOspirits->GetOwner()) if (Player* player = owner->ToPlayer()) player->KilledMonsterCredit(credit); DoCast(totemOspirits, SPELL_SOUL_CAPTURED); } } } }; }; enum ZuluhedChains { NPC_KARYNAKU = 22112, }; class spell_unlocking_zuluheds_chains : public SpellScriptLoader { public: spell_unlocking_zuluheds_chains() : SpellScriptLoader("spell_unlocking_zuluheds_chains") { } class spell_unlocking_zuluheds_chains_SpellScript : public SpellScript { PrepareSpellScript(spell_unlocking_zuluheds_chains_SpellScript); void HandleAfterHit() { if (Player* caster = GetCaster()->ToPlayer()) if (Creature* karynaku = caster->FindNearestCreature(NPC_KARYNAKU, 15.0f)) caster->KilledMonsterCredit(NPC_KARYNAKU, karynaku->GetGUID()); } void Register() override { AfterHit += SpellHitFn(spell_unlocking_zuluheds_chains_SpellScript::HandleAfterHit); } }; SpellScript* GetSpellScript() const override { return new spell_unlocking_zuluheds_chains_SpellScript(); } }; enum ShadowMoonTuberEnum { SPELL_WHISTLE = 36652, SPELL_SHADOWMOON_TUBER = 36462, NPC_BOAR_ENTRY = 21195, GO_SHADOWMOON_TUBER_MOUND = 184701, POINT_TUBER = 1, TYPE_BOAR = 1, DATA_BOAR = 1 }; class npc_shadowmoon_tuber_node : public CreatureScript { public: npc_shadowmoon_tuber_node() : CreatureScript("npc_shadowmoon_tuber_node") { } struct npc_shadowmoon_tuber_nodeAI : public ScriptedAI { npc_shadowmoon_tuber_nodeAI(Creature* creature) : ScriptedAI(creature) { } void SetData(uint32 id, uint32 data) override { if (id == TYPE_BOAR && data == DATA_BOAR) { // Spawn chest GO DoCast(SPELL_SHADOWMOON_TUBER); // Despawn the tuber if (GameObject* tuber = me->FindNearestGameObject(GO_SHADOWMOON_TUBER_MOUND, 5.0f)) { tuber->SetLootState(GO_JUST_DEACTIVATED); me->DespawnOrUnsummon(); } } } void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override { if (spell->Id == SPELL_WHISTLE) { if (Creature* boar = me->FindNearestCreature(NPC_BOAR_ENTRY, 30.0f)) { boar->SetWalk(false); boar->GetMotionMaster()->MovePoint(POINT_TUBER, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ()); } } } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_shadowmoon_tuber_nodeAI(creature); } }; void AddSC_shadowmoon_valley() { new npc_invis_infernal_caster(); new npc_infernal_attacker(); new npc_mature_netherwing_drake(); new npc_enslaved_netherwing_drake(); new npc_dragonmaw_peon(); new npc_drake_dealer_hurlunk(); new npcs_flanis_swiftwing_and_kagrosh(); new npc_karynaku(); new npc_earthmender_wilda(); new npc_lord_illidan_stormrage(); new go_crystal_prison(); new npc_illidari_spawn(); new npc_torloth_the_magnificent(); new npc_enraged_spirit(); new spell_unlocking_zuluheds_chains(); new npc_shadowmoon_tuber_node(); }
oneluiz/TrinityCore
src/server/scripts/Outland/zone_shadowmoon_valley.cpp
C++
gpl-2.0
53,182
/* The IGEN simulator generator for GDB, the GNU Debugger. Copyright 2002, 2007 Free Software Foundation, Inc. Contributed by Andrew Cagney. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ void print_idecode_issue_function_header (lf *file, const char *processor, function_decl_type decl_type, int nr_prefetched_words); void print_idecode_globals (lf *file); void print_idecode_lookups (lf *file, gen_entry *table, cache_entry *cache_rules); void print_idecode_body (lf *file, gen_entry *table, const char *result); /* Output code to do any final checks on the decoded instruction. This includes things like verifying any on decoded fields have the correct value and checking that (for floating point) floating point hardware isn't disabled */ extern void print_idecode_validate (lf *file, insn_entry * instruction, insn_opcodes *opcode_paths);
ghmajx/asuswrt-merlin
release/src/router/gdb/sim/igen/gen-idecode.h
C
gpl-2.0
1,512
<?php $date_format = array( 'mdy' => 'mm/dd/yy', 'mdy_dash' => 'mm-dd-yy', 'mdy_dot' => 'mm.dd.yy', 'dmy' => 'dd/mm/yy', 'dmy_dash' => 'dd-mm-yy', 'dmy_dot' => 'dd.mm.yy', 'ymd_slash' => 'yy/mm/dd', 'ymd_dash' => 'yy-mm-dd', 'ymd_dot' => 'yy.mm.dd', 'dMy' => 'dd/M/yy', 'dMy_dash' => 'dd-M-yy', 'fjy' => 'MM d, yy', 'fjsy' => 'MM d, yy', 'y' => 'yy' ); $date_format = apply_filters( 'pods_form_ui_field_date_js_formats', $date_format ); wp_enqueue_script( 'jquery-ui-datepicker' ); wp_enqueue_style( 'jquery-ui' ); $attributes = array(); $type = 'text'; if ( 1 == pods_var( $form_field_type . '_html5', $options ) ) $type = $form_field_type; $attributes[ 'type' ] = $type; $attributes[ 'tabindex' ] = 2; $format = PodsForm::field_method( 'date', 'format', $options ); $method = 'datepicker'; $args = array( 'dateFormat' => $date_format[ pods_var( $form_field_type . '_format', $options, 'mdy', null, true ) ], 'changeMonth' => true, 'changeYear' => true ); $html5_format = 'Y-m-d'; $date = PodsForm::field_method( 'date', 'createFromFormat', $format, (string) $value ); $date_default = PodsForm::field_method( 'date', 'createFromFormat', 'Y-m-d', (string) $value ); $formatted_date = $value; if ( 1 == pods_var( $form_field_type . '_allow_empty', $options, 1 ) && in_array( $value, array( '', '0000-00-00', '0000-00-00 00:00:00', '00:00:00' ) ) ) $formatted_date = $value = ''; elseif ( 'text' != $type ) { $formatted_date = $value; if ( false !== $date ) $value = $date->format( $html5_format ); elseif ( false !== $date_default ) $value = $date_default->format( $html5_format ); elseif ( !empty( $value ) ) $value = date_i18n( $html5_format, strtotime( (string) $value ) ); else $value = date_i18n( $html5_format ); } $args = apply_filters( 'pods_form_ui_field_date_args', $args, $type, $options, $attributes, $name, $form_field_type ); $attributes[ 'value' ] = $value; $attributes = PodsForm::merge_attributes( $attributes, $name, $form_field_type, $options ); ?> <input<?php PodsForm::attributes( $attributes, $name, $form_field_type, $options ); ?> /> <script> jQuery( function () { var <?php echo pods_clean_name( $attributes[ 'id' ] ); ?>_args = <?php echo json_encode( $args ); ?>; <?php if ( 'text' != $type ) { ?> if ( 'undefined' == typeof pods_test_date_field_<?php echo $type; ?> ) { // Test whether or not the browser supports date inputs function pods_test_date_field_<?php echo $type; ?> () { var input = jQuery( '<input/>', { 'type' : '<?php echo $type; ?>', css : { position : 'absolute', display : 'none' } } ); jQuery( 'body' ).append( input ); var bool = input.prop( 'type' ) !== 'text'; if ( bool ) { var smile = ":)"; input.val( smile ); return (input.val() != smile); } } } if ( !pods_test_date_field_<?php echo $type; ?>() ) { jQuery( 'input#<?php echo $attributes[ 'id' ]; ?>' ).val( '<?php echo $formatted_date; ?>' ); jQuery( 'input#<?php echo $attributes[ 'id' ]; ?>' ).<?php echo $method; ?>( <?php echo pods_clean_name( $attributes[ 'id' ] ); ?>_args ); } <?php } else { ?> jQuery( 'input#<?php echo $attributes[ 'id' ]; ?>' ).<?php echo $method; ?>( <?php echo pods_clean_name( $attributes[ 'id' ] ); ?>_args ); <?php } ?> } ); </script>
nbrouse-deep/chefmatefrontburner_com
wp-content/plugins/pods/ui/fields/date.php
PHP
gpl-2.0
4,099
/* * Version macros. * * This file is part of libswresample * * libswresample is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * libswresample is distributed in the hope that 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 libswresample; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWRESAMPLE_VERSION_H #define SWRESAMPLE_VERSION_H /** * @file * Libswresample version macros */ #include "libavutil/avutil.h" #define LIBSWRESAMPLE_VERSION_MAJOR 2 #define LIBSWRESAMPLE_VERSION_MINOR 4 #define LIBSWRESAMPLE_VERSION_MICRO 100 #define LIBSWRESAMPLE_VERSION_INT AV_VERSION_INT(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_VERSION AV_VERSION(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_BUILD LIBSWRESAMPLE_VERSION_INT #define LIBSWRESAMPLE_IDENT "SwR" AV_STRINGIFY(LIBSWRESAMPLE_VERSION) #endif /* SWRESAMPLE_VERSION_H */
ztwireless/obs-studio
win_deps_vs2015/win64/include/libswresample/version.h
C
gpl-2.0
1,718
#logo { background-image: url("/images/logo.png"); } * html #logo { background-image: url("/images/logo.gif"); }
benlimdesign/benlimdesign
wp-content/themes/hi-response-single/inc/wp-sass/phpsass/tests/mixin-content.css
CSS
gpl-2.0
114
#!/usr/bin/python # Generate GLib GInterfaces from the Telepathy specification. # The master copy of this program is in the telepathy-glib repository - # please make any changes there. # # Copyright (C) 2006, 2007 Collabora Limited # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import sys import xml.dom.minidom from libglibcodegen import escape_as_identifier, \ get_docstring, \ NS_TP, \ Signature, \ type_to_gtype, \ xml_escape def types_to_gtypes(types): return [type_to_gtype(t)[1] for t in types] class GTypesGenerator(object): def __init__(self, dom, output, mixed_case_prefix): self.dom = dom self.Prefix = mixed_case_prefix self.PREFIX_ = self.Prefix.upper() + '_' self.prefix_ = self.Prefix.lower() + '_' self.header = open(output + '.h', 'w') self.body = open(output + '-body.h', 'w') self.docs = open(output + '-gtk-doc.h', 'w') for f in (self.header, self.body, self.docs): f.write('/* Auto-generated, do not edit.\n *\n' ' * This file may be distributed under the same terms\n' ' * as the specification from which it was generated.\n' ' */\n\n') # keys are e.g. 'sv', values are the key escaped self.need_mappings = {} # keys are the contents of the struct (e.g. 'sssu'), values are the # key escaped self.need_structs = {} # keys are the contents of the struct (e.g. 'sssu'), values are the # key escaped self.need_struct_arrays = {} # keys are the contents of the array (unlike need_struct_arrays!), # values are the key escaped self.need_other_arrays = {} def h(self, code): self.header.write(code.encode("utf-8")) def c(self, code): self.body.write(code.encode("utf-8")) def d(self, code): self.docs.write(code.encode('utf-8')) def do_mapping_header(self, mapping): members = mapping.getElementsByTagNameNS(NS_TP, 'member') assert len(members) == 2 impl_sig = ''.join([elt.getAttribute('type') for elt in members]) esc_impl_sig = escape_as_identifier(impl_sig) name = (self.PREFIX_ + 'HASH_TYPE_' + mapping.getAttribute('name').upper()) impl = self.prefix_ + 'type_dbus_hash_' + esc_impl_sig docstring = get_docstring(mapping) or '(Undocumented)' self.d('/**\n * %s:\n *\n' % name) self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' * This macro expands to a call to a function\n') self.d(' * that returns the #GType of a #GHashTable\n') self.d(' * appropriate for representing a D-Bus\n') self.d(' * dictionary of signature\n') self.d(' * <literal>a{%s}</literal>.\n' % impl_sig) self.d(' *\n') key, value = members self.d(' * Keys (D-Bus type <literal>%s</literal>,\n' % key.getAttribute('type')) tp_type = key.getAttributeNS(NS_TP, 'type') if tp_type: self.d(' * type <literal>%s</literal>,\n' % tp_type) self.d(' * named <literal>%s</literal>):\n' % key.getAttribute('name')) docstring = get_docstring(key) or '(Undocumented)' self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' * Values (D-Bus type <literal>%s</literal>,\n' % value.getAttribute('type')) tp_type = value.getAttributeNS(NS_TP, 'type') if tp_type: self.d(' * type <literal>%s</literal>,\n' % tp_type) self.d(' * named <literal>%s</literal>):\n' % value.getAttribute('name')) docstring = get_docstring(value) or '(Undocumented)' self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' */\n') self.h('#define %s (%s ())\n\n' % (name, impl)) self.need_mappings[impl_sig] = esc_impl_sig array_name = mapping.getAttribute('array-name') if array_name: gtype_name = self.PREFIX_ + 'ARRAY_TYPE_' + array_name.upper() contents_sig = 'a{' + impl_sig + '}' esc_contents_sig = escape_as_identifier(contents_sig) impl = self.prefix_ + 'type_dbus_array_of_' + esc_contents_sig self.d('/**\n * %s:\n\n' % gtype_name) self.d(' * Expands to a call to a function\n') self.d(' * that returns the #GType of a #GPtrArray\n') self.d(' * of #%s.\n' % name) self.d(' */\n\n') self.h('#define %s (%s ())\n\n' % (gtype_name, impl)) self.need_other_arrays[contents_sig] = esc_contents_sig def do_struct_header(self, struct): members = struct.getElementsByTagNameNS(NS_TP, 'member') impl_sig = ''.join([elt.getAttribute('type') for elt in members]) esc_impl_sig = escape_as_identifier(impl_sig) name = (self.PREFIX_ + 'STRUCT_TYPE_' + struct.getAttribute('name').upper()) impl = self.prefix_ + 'type_dbus_struct_' + esc_impl_sig docstring = struct.getElementsByTagNameNS(NS_TP, 'docstring') if docstring: docstring = docstring[0].toprettyxml() if docstring.startswith('<tp:docstring>'): docstring = docstring[14:] if docstring.endswith('</tp:docstring>\n'): docstring = docstring[:-16] if docstring.strip() in ('<tp:docstring/>', ''): docstring = '(Undocumented)' else: docstring = '(Undocumented)' self.d('/**\n * %s:\n\n' % name) self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' * This macro expands to a call to a function\n') self.d(' * that returns the #GType of a #GValueArray\n') self.d(' * appropriate for representing a D-Bus struct\n') self.d(' * with signature <literal>(%s)</literal>.\n' % impl_sig) self.d(' *\n') for i, member in enumerate(members): self.d(' * Member %d (D-Bus type ' '<literal>%s</literal>,\n' % (i, member.getAttribute('type'))) tp_type = member.getAttributeNS(NS_TP, 'type') if tp_type: self.d(' * type <literal>%s</literal>,\n' % tp_type) self.d(' * named <literal>%s</literal>):\n' % member.getAttribute('name')) docstring = get_docstring(member) or '(Undocumented)' self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' */\n\n') self.h('#define %s (%s ())\n\n' % (name, impl)) array_name = struct.getAttribute('array-name') if array_name != '': array_name = (self.PREFIX_ + 'ARRAY_TYPE_' + array_name.upper()) impl = self.prefix_ + 'type_dbus_array_' + esc_impl_sig self.d('/**\n * %s:\n\n' % array_name) self.d(' * Expands to a call to a function\n') self.d(' * that returns the #GType of a #GPtrArray\n') self.d(' * of #%s.\n' % name) self.d(' */\n\n') self.h('#define %s (%s ())\n\n' % (array_name, impl)) self.need_struct_arrays[impl_sig] = esc_impl_sig self.need_structs[impl_sig] = esc_impl_sig def __call__(self): mappings = self.dom.getElementsByTagNameNS(NS_TP, 'mapping') structs = self.dom.getElementsByTagNameNS(NS_TP, 'struct') for mapping in mappings: self.do_mapping_header(mapping) for sig in self.need_mappings: self.h('GType %stype_dbus_hash_%s (void);\n\n' % (self.prefix_, self.need_mappings[sig])) self.c('GType\n%stype_dbus_hash_%s (void)\n{\n' % (self.prefix_, self.need_mappings[sig])) self.c(' static GType t = 0;\n\n') self.c(' if (G_UNLIKELY (t == 0))\n') # FIXME: translate sig into two GTypes items = tuple(Signature(sig)) gtypes = types_to_gtypes(items) self.c(' t = dbus_g_type_get_map ("GHashTable", ' '%s, %s);\n' % (gtypes[0], gtypes[1])) self.c(' return t;\n') self.c('}\n\n') for struct in structs: self.do_struct_header(struct) for sig in self.need_structs: self.h('GType %stype_dbus_struct_%s (void);\n\n' % (self.prefix_, self.need_structs[sig])) self.c('GType\n%stype_dbus_struct_%s (void)\n{\n' % (self.prefix_, self.need_structs[sig])) self.c(' static GType t = 0;\n\n') self.c(' if (G_UNLIKELY (t == 0))\n') self.c(' t = dbus_g_type_get_struct ("GValueArray",\n') items = tuple(Signature(sig)) gtypes = types_to_gtypes(items) for gtype in gtypes: self.c(' %s,\n' % gtype) self.c(' G_TYPE_INVALID);\n') self.c(' return t;\n') self.c('}\n\n') for sig in self.need_struct_arrays: self.h('GType %stype_dbus_array_%s (void);\n\n' % (self.prefix_, self.need_struct_arrays[sig])) self.c('GType\n%stype_dbus_array_%s (void)\n{\n' % (self.prefix_, self.need_struct_arrays[sig])) self.c(' static GType t = 0;\n\n') self.c(' if (G_UNLIKELY (t == 0))\n') self.c(' t = dbus_g_type_get_collection ("GPtrArray", ' '%stype_dbus_struct_%s ());\n' % (self.prefix_, self.need_struct_arrays[sig])) self.c(' return t;\n') self.c('}\n\n') for sig in self.need_other_arrays: self.h('GType %stype_dbus_array_of_%s (void);\n\n' % (self.prefix_, self.need_other_arrays[sig])) self.c('GType\n%stype_dbus_array_of_%s (void)\n{\n' % (self.prefix_, self.need_other_arrays[sig])) self.c(' static GType t = 0;\n\n') self.c(' if (G_UNLIKELY (t == 0))\n') if sig[:2] == 'a{' and sig[-1:] == '}': # array of mappings self.c(' t = dbus_g_type_get_collection (' '"GPtrArray", ' '%stype_dbus_hash_%s ());\n' % (self.prefix_, escape_as_identifier(sig[2:-1]))) elif sig[:2] == 'a(' and sig[-1:] == ')': # array of arrays of struct self.c(' t = dbus_g_type_get_collection (' '"GPtrArray", ' '%stype_dbus_array_%s ());\n' % (self.prefix_, escape_as_identifier(sig[2:-1]))) elif sig[:1] == 'a': # array of arrays of non-struct self.c(' t = dbus_g_type_get_collection (' '"GPtrArray", ' '%stype_dbus_array_of_%s ());\n' % (self.prefix_, escape_as_identifier(sig[1:]))) else: raise AssertionError("array of '%s' not supported" % sig) self.c(' return t;\n') self.c('}\n\n') if __name__ == '__main__': argv = sys.argv[1:] dom = xml.dom.minidom.parse(argv[0]) GTypesGenerator(dom, argv[1], argv[2])()
JGulic/empathy
tools/glib-gtypes-generator.py
Python
gpl-2.0
12,522
/* * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <stdlib.h> #include "jni_util.h" #include "math.h" #include "GraphicsPrimitiveMgr.h" #include "Region.h" #include "sun_java2d_loops_TransformHelper.h" #include "java_awt_image_AffineTransformOp.h" /* * The stub functions replace the bilinear and bicubic interpolation * functions with NOP versions so that the performance of the helper * functions that fetch the data can be more directly tested. They * are not compiled or enabled by default. Change the following * #undef to a #define to build the stub functions. * * When compiled, they are enabled by the environment variable TXSTUB. * When compiled, there is also code to disable the VIS versions and * use the C versions in this file in their place by defining the TXNOVIS * environment variable. */ #undef MAKE_STUBS /* The number of IntArgbPre samples to store in the temporary buffer. */ #define LINE_SIZE 2048 /* The size of a stack allocated buffer to hold edge coordinates (see below). */ #define MAXEDGES 1024 /* Declare the software interpolation functions. */ static TransformInterpFunc BilinearInterp; static TransformInterpFunc BicubicInterp; #ifdef MAKE_STUBS /* Optionally Declare the stub interpolation functions. */ static TransformInterpFunc BilinearInterpStub; static TransformInterpFunc BicubicInterpStub; #endif /* MAKE_STUBS */ /* * Initially choose the software interpolation functions. * These choices can be overridden by platform code that runs during the * primitive registration phase of initialization by storing pointers to * better functions in these pointers. * Compiling the stubs also turns on code below that can re-install the * software functions or stub functions on the first call to this primitive. */ TransformInterpFunc *pBilinearFunc = BilinearInterp; TransformInterpFunc *pBicubicFunc = BicubicInterp; /* * The dxydxy parameters of the inverse transform determine how * quickly we step through the source image. For tiny scale * factors (on the order of 1E-16 or so) the stepping distances * are huge. The image has been scaled so small that stepping * a single pixel in device space moves the sampling point by * billions (or more) pixels in the source image space. These * huge stepping values can overflow the whole part of the longs * we use for the fixed point stepping equations and so we need * a more robust solution. We could simply iterate over every * device pixel, use the inverse transform to transform it back * into the source image coordinate system and then test it for * being in range and sample pixel-by-pixel, but that is quite * a bit more expensive. Fortunately, if the scale factors are * so tiny that we overflow our long values then the number of * pixels we are planning to visit should be very tiny. The only * exception to that rule is if the scale factor along one * dimension is tiny (creating the huge stepping values), and * the scale factor along the other dimension is fairly regular * or an up-scale. In that case we have a lot of pixels along * the direction of the larger axis to sample, but few along the * smaller axis. Though, pessimally, with an added shear factor * such a linearly tiny image could have bounds that cover a large * number of pixels. Such odd transformations should be very * rare and the absolute limit on calculations would involve a * single reverse transform of every pixel in the output image * which is not fast, but it should not cause an undue stall * of the rendering software. * * The specific test we will use is to calculate the inverse * transformed values of every corner of the destination bounds * (in order to be user-clip independent) and if we can * perform a fixed-point-long inverse transform of all of * those points without overflowing we will use the fast * fixed point algorithm. Otherwise we will use the safe * per-pixel transform algorithm. * The 4 corners are 0,0, 0,dsth, dstw,0, dstw,dsth * Transformed they are: * tx, ty * tx +dxdy*H, ty +dydy*H * tx+dxdx*W, ty+dydx*W * tx+dxdx*W+dxdy*H, ty+dydx*W+dydy*H */ /* We reject coordinates not less than 1<<30 so that the distance between */ /* any 2 of them is less than 1<<31 which would overflow into the sign */ /* bit of a signed long value used to represent fixed point coordinates. */ #define TX_FIXED_UNSAFE(v) (fabs(v) >= (1<<30)) static jboolean checkOverflow(jint dxoff, jint dyoff, SurfaceDataBounds *pBounds, TransformInfo *pItxInfo, jdouble *retx, jdouble *rety) { jdouble x, y; x = dxoff+pBounds->x1+0.5; /* Center of pixel x1 */ y = dyoff+pBounds->y1+0.5; /* Center of pixel y1 */ Transform_transform(pItxInfo, &x, &y); *retx = x; *rety = y; if (TX_FIXED_UNSAFE(x) || TX_FIXED_UNSAFE(y)) { return JNI_TRUE; } x = dxoff+pBounds->x2-0.5; /* Center of pixel x2-1 */ y = dyoff+pBounds->y1+0.5; /* Center of pixel y1 */ Transform_transform(pItxInfo, &x, &y); if (TX_FIXED_UNSAFE(x) || TX_FIXED_UNSAFE(y)) { return JNI_TRUE; } x = dxoff+pBounds->x1+0.5; /* Center of pixel x1 */ y = dyoff+pBounds->y2-0.5; /* Center of pixel y2-1 */ Transform_transform(pItxInfo, &x, &y); if (TX_FIXED_UNSAFE(x) || TX_FIXED_UNSAFE(y)) { return JNI_TRUE; } x = dxoff+pBounds->x2-0.5; /* Center of pixel x2-1 */ y = dyoff+pBounds->y2-0.5; /* Center of pixel y2-1 */ Transform_transform(pItxInfo, &x, &y); if (TX_FIXED_UNSAFE(x) || TX_FIXED_UNSAFE(y)) { return JNI_TRUE; } return JNI_FALSE; } /* * Fill the edge buffer with pairs of coordinates representing the maximum * left and right pixels of the destination surface that should be processed * on each scanline, clipped to the bounds parameter. * The number of scanlines to calculate is implied by the bounds parameter. * Only pixels that map back through the specified (inverse) transform to a * source coordinate that falls within the (0, 0, sw, sh) bounds of the * source image should be processed. * pEdges points to an array of jints that holds 2 + numedges*2 values where * numedges should match (pBounds->y2 - pBounds->y1). * The first two jints in pEdges should be set to y1 and y2 and every pair * of jints after that represent the xmin,xmax of all pixels in range of * the transformed blit for the corresponding scanline. */ static void calculateEdges(jint *pEdges, SurfaceDataBounds *pBounds, TransformInfo *pItxInfo, jlong xbase, jlong ybase, juint sw, juint sh) { jlong dxdxlong, dydxlong; jlong dxdylong, dydylong; jlong drowxlong, drowylong; jint dx1, dy1, dx2, dy2; dxdxlong = DblToLong(pItxInfo->dxdx); dydxlong = DblToLong(pItxInfo->dydx); dxdylong = DblToLong(pItxInfo->dxdy); dydylong = DblToLong(pItxInfo->dydy); dx1 = pBounds->x1; dy1 = pBounds->y1; dx2 = pBounds->x2; dy2 = pBounds->y2; *pEdges++ = dy1; *pEdges++ = dy2; drowxlong = (dx2-dx1-1) * dxdxlong; drowylong = (dx2-dx1-1) * dydxlong; while (dy1 < dy2) { jlong xlong, ylong; dx1 = pBounds->x1; dx2 = pBounds->x2; xlong = xbase; ylong = ybase; while (dx1 < dx2 && (((juint) WholeOfLong(ylong)) >= sh || ((juint) WholeOfLong(xlong)) >= sw)) { dx1++; xlong += dxdxlong; ylong += dydxlong; } xlong = xbase + drowxlong; ylong = ybase + drowylong; while (dx2 > dx1 && (((juint) WholeOfLong(ylong)) >= sh || ((juint) WholeOfLong(xlong)) >= sw)) { dx2--; xlong -= dxdxlong; ylong -= dydxlong; } *pEdges++ = dx1; *pEdges++ = dx2; /* Increment to next scanline */ xbase += dxdylong; ybase += dydylong; dy1++; } } static void Transform_SafeHelper(JNIEnv *env, SurfaceDataOps *srcOps, SurfaceDataOps *dstOps, SurfaceDataRasInfo *pSrcInfo, SurfaceDataRasInfo *pDstInfo, NativePrimitive *pMaskBlitPrim, CompositeInfo *pCompInfo, TransformHelperFunc *pHelperFunc, TransformInterpFunc *pInterpFunc, RegionData *pClipInfo, TransformInfo *pItxInfo, jint *pData, jint *pEdges, jint dxoff, jint dyoff, jint sw, jint sh); /* * Class: sun_java2d_loops_TransformHelper * Method: Transform * Signature: (Lsun/java2d/loops/MaskBlit;Lsun/java2d/SurfaceData;Lsun/java2d/SurfaceData;Ljava/awt/Composite;Lsun/java2d/pipe/Region;Ljava/awt/geom/AffineTransform;IIIIIIIII[I)V */ JNIEXPORT void JNICALL Java_sun_java2d_loops_TransformHelper_Transform (JNIEnv *env, jobject self, jobject maskblit, jobject srcData, jobject dstData, jobject comp, jobject clip, jobject itxform, jint txtype, jint sx1, jint sy1, jint sx2, jint sy2, jint dx1, jint dy1, jint dx2, jint dy2, jintArray edgeArray, jint dxoff, jint dyoff) { SurfaceDataOps *srcOps; SurfaceDataOps *dstOps; SurfaceDataRasInfo srcInfo; SurfaceDataRasInfo dstInfo; NativePrimitive *pHelperPrim; NativePrimitive *pMaskBlitPrim; CompositeInfo compInfo; RegionData clipInfo; TransformInfo itxInfo; jint maxlinepix; TransformHelperFunc *pHelperFunc; TransformInterpFunc *pInterpFunc; jdouble xorig, yorig; jint numedges; jint *pEdges; jint edgebuf[2 + MAXEDGES * 2]; union { jlong align; jint data[LINE_SIZE]; } rgb; #ifdef MAKE_STUBS static int th_initialized; /* For debugging only - used to swap in alternate funcs for perf testing */ if (!th_initialized) { if (getenv("TXSTUB") != 0) { pBilinearFunc = BilinearInterpStub; pBicubicFunc = BicubicInterpStub; } else if (getenv("TXNOVIS") != 0) { pBilinearFunc = BilinearInterp; pBicubicFunc = BicubicInterp; } th_initialized = 1; } #endif /* MAKE_STUBS */ pHelperPrim = GetNativePrim(env, self); if (pHelperPrim == NULL) { /* Should never happen... */ return; } pMaskBlitPrim = GetNativePrim(env, maskblit); if (pMaskBlitPrim == NULL) { /* Exception was thrown by GetNativePrim */ return; } if (pMaskBlitPrim->pCompType->getCompInfo != NULL) { (*pMaskBlitPrim->pCompType->getCompInfo)(env, &compInfo, comp); } if (Region_GetInfo(env, clip, &clipInfo)) { return; } srcOps = SurfaceData_GetOps(env, srcData); dstOps = SurfaceData_GetOps(env, dstData); if (srcOps == 0 || dstOps == 0) { return; } /* * Grab the appropriate pointer to the helper and interpolation * routines and calculate the maximum number of destination pixels * that can be processed in one intermediate buffer based on the * size of the buffer and the number of samples needed per pixel. */ switch (txtype) { case java_awt_image_AffineTransformOp_TYPE_NEAREST_NEIGHBOR: pHelperFunc = pHelperPrim->funcs.transformhelpers->nnHelper; pInterpFunc = NULL; maxlinepix = LINE_SIZE; break; case java_awt_image_AffineTransformOp_TYPE_BILINEAR: pHelperFunc = pHelperPrim->funcs.transformhelpers->blHelper; pInterpFunc = pBilinearFunc; maxlinepix = LINE_SIZE / 4; break; case java_awt_image_AffineTransformOp_TYPE_BICUBIC: pHelperFunc = pHelperPrim->funcs.transformhelpers->bcHelper; pInterpFunc = pBicubicFunc; maxlinepix = LINE_SIZE / 16; break; } srcInfo.bounds.x1 = sx1; srcInfo.bounds.y1 = sy1; srcInfo.bounds.x2 = sx2; srcInfo.bounds.y2 = sy2; dstInfo.bounds.x1 = dx1; dstInfo.bounds.y1 = dy1; dstInfo.bounds.x2 = dx2; dstInfo.bounds.y2 = dy2; SurfaceData_IntersectBounds(&dstInfo.bounds, &clipInfo.bounds); if (srcOps->Lock(env, srcOps, &srcInfo, pHelperPrim->srcflags) != SD_SUCCESS) { /* edgeArray should already contain zeros for min/maxy */ return; } if (dstOps->Lock(env, dstOps, &dstInfo, pMaskBlitPrim->dstflags) != SD_SUCCESS) { SurfaceData_InvokeUnlock(env, srcOps, &srcInfo); /* edgeArray should already contain zeros for min/maxy */ return; } Region_IntersectBounds(&clipInfo, &dstInfo.bounds); numedges = (dstInfo.bounds.y2 - dstInfo.bounds.y1); if (numedges > MAXEDGES) { pEdges = malloc((2 + 2 * numedges) * sizeof (*pEdges)); if (pEdges == NULL) { SurfaceData_InvokeUnlock(env, dstOps, &dstInfo); SurfaceData_InvokeUnlock(env, srcOps, &srcInfo); /* edgeArray should already contain zeros for min/maxy */ return; } } else { pEdges = edgebuf; } Transform_GetInfo(env, itxform, &itxInfo); if (!Region_IsEmpty(&clipInfo)) { srcOps->GetRasInfo(env, srcOps, &srcInfo); dstOps->GetRasInfo(env, dstOps, &dstInfo); if (srcInfo.rasBase == NULL || dstInfo.rasBase == NULL) { pEdges[0] = pEdges[1] = 0; } else if (checkOverflow(dxoff, dyoff, &dstInfo.bounds, &itxInfo, &xorig, &yorig)) { Transform_SafeHelper(env, srcOps, dstOps, &srcInfo, &dstInfo, pMaskBlitPrim, &compInfo, pHelperFunc, pInterpFunc, &clipInfo, &itxInfo, rgb.data, pEdges, dxoff, dyoff, sx2-sx1, sy2-sy1); } else { SurfaceDataBounds span; jlong dxdxlong, dydxlong; jlong dxdylong, dydylong; jlong xbase, ybase; dxdxlong = DblToLong(itxInfo.dxdx); dydxlong = DblToLong(itxInfo.dydx); dxdylong = DblToLong(itxInfo.dxdy); dydylong = DblToLong(itxInfo.dydy); xbase = DblToLong(xorig); ybase = DblToLong(yorig); calculateEdges(pEdges, &dstInfo.bounds, &itxInfo, xbase, ybase, sx2-sx1, sy2-sy1); Region_StartIteration(env, &clipInfo); while (Region_NextIteration(&clipInfo, &span)) { jlong rowxlong, rowylong; void *pDst; dy1 = span.y1; dy2 = span.y2; rowxlong = xbase + (dy1 - dstInfo.bounds.y1) * dxdylong; rowylong = ybase + (dy1 - dstInfo.bounds.y1) * dydylong; while (dy1 < dy2) { jlong xlong, ylong; /* Note - process at most one scanline at a time. */ dx1 = pEdges[(dy1 - dstInfo.bounds.y1) * 2 + 2]; dx2 = pEdges[(dy1 - dstInfo.bounds.y1) * 2 + 3]; if (dx1 < span.x1) dx1 = span.x1; if (dx2 > span.x2) dx2 = span.x2; /* All pixels from dx1 to dx2 have centers in bounds */ while (dx1 < dx2) { /* Can process at most one buffer full at a time */ jint numpix = dx2 - dx1; if (numpix > maxlinepix) { numpix = maxlinepix; } xlong = rowxlong + ((dx1 - dstInfo.bounds.x1) * dxdxlong); ylong = rowylong + ((dx1 - dstInfo.bounds.x1) * dydxlong); /* Get IntArgbPre pixel data from source */ (*pHelperFunc)(&srcInfo, rgb.data, numpix, xlong, dxdxlong, ylong, dydxlong); /* Interpolate result pixels if needed */ if (pInterpFunc) { (*pInterpFunc)(rgb.data, numpix, FractOfLong(xlong-LongOneHalf), FractOfLong(dxdxlong), FractOfLong(ylong-LongOneHalf), FractOfLong(dydxlong)); } /* Store/Composite interpolated pixels into dest */ pDst = PtrCoord(dstInfo.rasBase, dx1, dstInfo.pixelStride, dy1, dstInfo.scanStride); (*pMaskBlitPrim->funcs.maskblit)(pDst, rgb.data, 0, 0, 0, numpix, 1, &dstInfo, &srcInfo, pMaskBlitPrim, &compInfo); /* Increment to next buffer worth of input pixels */ dx1 += maxlinepix; } /* Increment to next scanline */ rowxlong += dxdylong; rowylong += dydylong; dy1++; } } Region_EndIteration(env, &clipInfo); } SurfaceData_InvokeRelease(env, dstOps, &dstInfo); SurfaceData_InvokeRelease(env, srcOps, &srcInfo); } else { pEdges[0] = pEdges[1] = 0; } SurfaceData_InvokeUnlock(env, dstOps, &dstInfo); SurfaceData_InvokeUnlock(env, srcOps, &srcInfo); if (!JNU_IsNull(env, edgeArray)) { (*env)->SetIntArrayRegion(env, edgeArray, 0, 2+numedges*2, pEdges); } if (pEdges != edgebuf) { free(pEdges); } } static void Transform_SafeHelper(JNIEnv *env, SurfaceDataOps *srcOps, SurfaceDataOps *dstOps, SurfaceDataRasInfo *pSrcInfo, SurfaceDataRasInfo *pDstInfo, NativePrimitive *pMaskBlitPrim, CompositeInfo *pCompInfo, TransformHelperFunc *pHelperFunc, TransformInterpFunc *pInterpFunc, RegionData *pClipInfo, TransformInfo *pItxInfo, jint *pData, jint *pEdges, jint dxoff, jint dyoff, jint sw, jint sh) { SurfaceDataBounds span; jint dx1, dx2; jint dy1, dy2; jint i, iy; dy1 = pDstInfo->bounds.y1; dy2 = pDstInfo->bounds.y2; dx1 = pDstInfo->bounds.x1; dx2 = pDstInfo->bounds.x2; pEdges[0] = dy1; pEdges[1] = dy2; for (iy = dy1; iy < dy2; iy++) { jint i = (iy - dy1) * 2; /* row spans are set to max,min until we find a pixel in range below */ pEdges[i + 2] = dx2; pEdges[i + 3] = dx1; } Region_StartIteration(env, pClipInfo); while (Region_NextIteration(pClipInfo, &span)) { dy1 = span.y1; dy2 = span.y2; while (dy1 < dy2) { dx1 = span.x1; dx2 = span.x2; i = (dy1 - pDstInfo->bounds.y1) * 2; while (dx1 < dx2) { jdouble x, y; jlong xlong, ylong; x = dxoff + dx1 + 0.5; y = dyoff + dy1 + 0.5; Transform_transform(pItxInfo, &x, &y); xlong = DblToLong(x); ylong = DblToLong(y); /* Process only pixels with centers in bounds * Test double values to avoid overflow in conversion * to long values and then also test the long values * in case they rounded up and out of bounds during * the conversion. */ if (x >= 0 && y >= 0 && x < sw && y < sh && WholeOfLong(xlong) < sw && WholeOfLong(ylong) < sh) { void *pDst; if (pEdges[i + 2] > dx1) { pEdges[i + 2] = dx1; } if (pEdges[i + 3] <= dx1) { pEdges[i + 3] = dx1 + 1; } /* Get IntArgbPre pixel data from source */ (*pHelperFunc)(pSrcInfo, pData, 1, xlong, 0, ylong, 0); /* Interpolate result pixels if needed */ if (pInterpFunc) { (*pInterpFunc)(pData, 1, FractOfLong(xlong-LongOneHalf), 0, FractOfLong(ylong-LongOneHalf), 0); } /* Store/Composite interpolated pixels into dest */ pDst = PtrCoord(pDstInfo->rasBase, dx1, pDstInfo->pixelStride, dy1, pDstInfo->scanStride); (*pMaskBlitPrim->funcs.maskblit)(pDst, pData, 0, 0, 0, 1, 1, pDstInfo, pSrcInfo, pMaskBlitPrim, pCompInfo); } /* Increment to next input pixel */ dx1++; } /* Increment to next scanline */ dy1++; } } Region_EndIteration(env, pClipInfo); } #define BL_INTERP_V1_to_V2_by_F(v1, v2, f) \ (((v1)<<8) + ((v2)-(v1))*(f)) #define BL_ACCUM(comp) \ do { \ jint c1 = ((jubyte *) pRGB)[comp]; \ jint c2 = ((jubyte *) pRGB)[comp+4]; \ jint cR = BL_INTERP_V1_to_V2_by_F(c1, c2, xfactor); \ c1 = ((jubyte *) pRGB)[comp+8]; \ c2 = ((jubyte *) pRGB)[comp+12]; \ c2 = BL_INTERP_V1_to_V2_by_F(c1, c2, xfactor); \ cR = BL_INTERP_V1_to_V2_by_F(cR, c2, yfactor); \ ((jubyte *)pRes)[comp] = (jubyte) ((cR + (1<<15)) >> 16); \ } while (0) static void BilinearInterp(jint *pRGB, jint numpix, jint xfract, jint dxfract, jint yfract, jint dyfract) { jint j; jint *pRes = pRGB; for (j = 0; j < numpix; j++) { jint xfactor; jint yfactor; xfactor = URShift(xfract, 32-8); yfactor = URShift(yfract, 32-8); BL_ACCUM(0); BL_ACCUM(1); BL_ACCUM(2); BL_ACCUM(3); pRes++; pRGB += 4; xfract += dxfract; yfract += dyfract; } } #define SAT(val, max) \ do { \ val &= ~(val >> 31); /* negatives become 0 */ \ val -= max; /* only overflows are now positive */ \ val &= (val >> 31); /* positives become 0 */ \ val += max; /* range is now [0 -> max] */ \ } while (0) #ifdef __sparc /* For sparc, floating point multiplies are faster than integer */ #define BICUBIC_USE_DBL_LUT #else /* For x86, integer multiplies are faster than floating point */ /* Note that on x86 Linux the choice of best algorithm varies * depending on the compiler optimization and the processor type. * Currently, the sun/awt x86 Linux builds are not optimized so * all the variations produce mediocre performance. * For now we will use the choice that works best for the Windows * build until the (lack of) optimization issues on Linux are resolved. */ #define BICUBIC_USE_INT_MATH #endif #ifdef BICUBIC_USE_DBL_CAST #define BC_DblToCoeff(v) (v) #define BC_COEFF_ONE 1.0 #define BC_TYPE jdouble #define BC_V_HALF 0.5 #define BC_CompToV(v) ((jdouble) (v)) #define BC_STORE_COMPS(pRes) \ do { \ jint a = (jint) accumA; \ jint r = (jint) accumR; \ jint g = (jint) accumG; \ jint b = (jint) accumB; \ SAT(a, 255); \ SAT(r, a); \ SAT(g, a); \ SAT(b, a); \ *pRes = ((a << 24) | (r << 16) | (g << 8) | (b)); \ } while (0) #endif /* BICUBIC_USE_DBL_CAST */ #ifdef BICUBIC_USE_DBL_LUT #define ItoD1(v) ((jdouble) (v)) #define ItoD4(v) ItoD1(v), ItoD1(v+1), ItoD1(v+2), ItoD1(v+3) #define ItoD16(v) ItoD4(v), ItoD4(v+4), ItoD4(v+8), ItoD4(v+12) #define ItoD64(v) ItoD16(v), ItoD16(v+16), ItoD16(v+32), ItoD16(v+48) static jdouble ItoD_table[] = { ItoD64(0), ItoD64(64), ItoD64(128), ItoD64(192) }; #define BC_DblToCoeff(v) (v) #define BC_COEFF_ONE 1.0 #define BC_TYPE jdouble #define BC_V_HALF 0.5 #define BC_CompToV(v) ItoD_table[v] #define BC_STORE_COMPS(pRes) \ do { \ jint a = (jint) accumA; \ jint r = (jint) accumR; \ jint g = (jint) accumG; \ jint b = (jint) accumB; \ SAT(a, 255); \ SAT(r, a); \ SAT(g, a); \ SAT(b, a); \ *pRes = ((a << 24) | (r << 16) | (g << 8) | (b)); \ } while (0) #endif /* BICUBIC_USE_DBL_LUT */ #ifdef BICUBIC_USE_INT_MATH #define BC_DblToCoeff(v) ((jint) ((v) * 256)) #define BC_COEFF_ONE 256 #define BC_TYPE jint #define BC_V_HALF (1 << 15) #define BC_CompToV(v) ((jint) v) #define BC_STORE_COMPS(pRes) \ do { \ accumA >>= 16; \ accumR >>= 16; \ accumG >>= 16; \ accumB >>= 16; \ SAT(accumA, 255); \ SAT(accumR, accumA); \ SAT(accumG, accumA); \ SAT(accumB, accumA); \ *pRes = ((accumA << 24) | (accumR << 16) | (accumG << 8) | (accumB)); \ } while (0) #endif /* BICUBIC_USE_INT_MATH */ #define BC_ACCUM(index, ycindex, xcindex) \ do { \ BC_TYPE factor = bicubic_coeff[xcindex] * bicubic_coeff[ycindex]; \ int rgb; \ rgb = pRGB[index]; \ accumB += BC_CompToV((rgb >> 0) & 0xff) * factor; \ accumG += BC_CompToV((rgb >> 8) & 0xff) * factor; \ accumR += BC_CompToV((rgb >> 16) & 0xff) * factor; \ accumA += BC_CompToV((rgb >> 24) & 0xff) * factor; \ } while (0) static BC_TYPE bicubic_coeff[513]; static jboolean bicubictableinited; static void init_bicubic_table(jdouble A) { /* * The following formulas are designed to give smooth * results when 'A' is -0.5 or -1.0. */ int i; for (i = 0; i < 256; i++) { /* r(x) = (A + 2)|x|^3 - (A + 3)|x|^2 + 1 , 0 <= |x| < 1 */ jdouble x = i / 256.0; x = ((A+2)*x - (A+3))*x*x + 1; bicubic_coeff[i] = BC_DblToCoeff(x); } for (; i < 384; i++) { /* r(x) = A|x|^3 - 5A|x|^2 + 8A|x| - 4A , 1 <= |x| < 2 */ jdouble x = i / 256.0; x = ((A*x - 5*A)*x + 8*A)*x - 4*A; bicubic_coeff[i] = BC_DblToCoeff(x); } bicubic_coeff[384] = (BC_COEFF_ONE - bicubic_coeff[128]*2) / 2; for (i++; i <= 512; i++) { bicubic_coeff[i] = BC_COEFF_ONE - (bicubic_coeff[512-i] + bicubic_coeff[i-256] + bicubic_coeff[768-i]); } bicubictableinited = JNI_TRUE; } static void BicubicInterp(jint *pRGB, jint numpix, jint xfract, jint dxfract, jint yfract, jint dyfract) { jint i; jint *pRes = pRGB; if (!bicubictableinited) { init_bicubic_table(-0.5); } for (i = 0; i < numpix; i++) { BC_TYPE accumA, accumR, accumG, accumB; jint xfactor, yfactor; xfactor = URShift(xfract, 32-8); yfactor = URShift(yfract, 32-8); accumA = accumR = accumG = accumB = BC_V_HALF; BC_ACCUM(0, yfactor+256, xfactor+256); BC_ACCUM(1, yfactor+256, xfactor+ 0); BC_ACCUM(2, yfactor+256, 256-xfactor); BC_ACCUM(3, yfactor+256, 512-xfactor); BC_ACCUM(4, yfactor+ 0, xfactor+256); BC_ACCUM(5, yfactor+ 0, xfactor+ 0); BC_ACCUM(6, yfactor+ 0, 256-xfactor); BC_ACCUM(7, yfactor+ 0, 512-xfactor); BC_ACCUM(8, 256-yfactor, xfactor+256); BC_ACCUM(9, 256-yfactor, xfactor+ 0); BC_ACCUM(10, 256-yfactor, 256-xfactor); BC_ACCUM(11, 256-yfactor, 512-xfactor); BC_ACCUM(12, 512-yfactor, xfactor+256); BC_ACCUM(13, 512-yfactor, xfactor+ 0); BC_ACCUM(14, 512-yfactor, 256-xfactor); BC_ACCUM(15, 512-yfactor, 512-xfactor); BC_STORE_COMPS(pRes); pRes++; pRGB += 16; xfract += dxfract; yfract += dyfract; } } #ifdef MAKE_STUBS static void BilinearInterpStub(jint *pRGBbase, jint numpix, jint xfract, jint dxfract, jint yfract, jint dyfract) { jint *pRGB = pRGBbase; while (--numpix >= 0) { *pRGBbase = *pRGB; pRGBbase += 1; pRGB += 4; } } static void BicubicInterpStub(jint *pRGBbase, jint numpix, jint xfract, jint dxfract, jint yfract, jint dyfract) { jint *pRGB = pRGBbase+5; while (--numpix >= 0) { *pRGBbase = *pRGB; pRGBbase += 1; pRGB += 16; } } #endif /* MAKE_STUBS */
kgilmer/openjdk-7-mermaid
src/share/native/sun/java2d/loops/TransformHelper.c
C
gpl-2.0
30,901
/** * Copyright (c) 2009--2012 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.frontend.servlets; import com.redhat.rhn.common.conf.ConfigDefaults; import com.redhat.rhn.manager.session.SessionManager; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; /** * A PxtCookieManager creates, retrieves, and parses pxt cookies. For a general overview of * the pxt cookie, see * <a href="http://wiki.rhndev.redhat.com/wiki/SSO#What_is_the_pxt_cookie.3F"> * What is the pxt cookie? * </a> * * <br/><br/> * * This class is thread-safe. * * @version $Rev$ */ public class PxtCookieManager { /** * The name of the pxt session cookie */ public static final String PXT_SESSION_COOKIE_NAME = "pxt-session-cookie"; public static final String DEFAULT_PATH = "/"; /** * Creates a new pxt cookie with the specified session id and timeout. * * @param pxtSessionId The id of the pxt session for which the cookie is being created. * * @param request The current request. * * @param timeout The max age of the cookie in seconds. * * @return a new pxt cookie. */ public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request, int timeout) { String cookieName = PXT_SESSION_COOKIE_NAME; String cookieValue = pxtSessionId + "x" + SessionManager.generateSessionKey(pxtSessionId.toString()); Cookie pxtCookie = new Cookie(cookieName, cookieValue); // BZ #454876 // when not using setDomain, default "Host" will be set for the cookie // there's no need to use domain and besides that it causes trouble, // when accessing the server within the local network (without FQDN) // pxtCookie.setDomain(request.getServerName()); if (!userAgentContains(request, "msie")) { pxtCookie.setMaxAge(timeout); } pxtCookie.setPath(DEFAULT_PATH); pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable()); return pxtCookie; } private boolean userAgentContains(HttpServletRequest request, String browserId) { String userAgent = request.getHeader("User-Agent"); if (userAgent != null) { return userAgent.toLowerCase().contains(browserId); } return false; } /** * Retrieves the pxt cookie from the request if one is included in the request. * * @param request The current request. * * @return The pxt cookie included in the request, or <code>null</code> if no cookie is * found. */ public Cookie getPxtCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } String pxtCookieName = PXT_SESSION_COOKIE_NAME; for (int i = 0; i < cookies.length; ++i) { if (pxtCookieName.equals(cookies[i].getName())) { return cookies[i]; } } return null; } }
aronparsons/spacewalk
java/code/src/com/redhat/rhn/frontend/servlets/PxtCookieManager.java
Java
gpl-2.0
3,631
<?php /** * * Please see single-event.php in this directory for detailed instructions on how to use and modify these templates. * */ ?> <script type="text/html" id="tribe_tmpl_month_mobile_day_header"> <div class="tribe-mobile-day" data-day="[[=date]]">[[ if(date_name.length) { ]] <h3 class="tribe-mobile-day-heading">Events for <span>[[=raw date_name]]</span></h3>[[ } ]] </div> </script> <script type="text/html" id="tribe_tmpl_month_mobile"> <div class="tribe-events-mobile hentry vevent tribe-clearfix tribe-events-mobile-event-[[=eventId]][[ if(categoryClasses.length) { ]] [[= categoryClasses]][[ } ]]"> <h4 class="summary"> <a class="url" href="[[=permalink]]" title="[[=title]]" rel="bookmark">[[=title]]</a> </h4> <div class="tribe-events-event-body"> <div class="updated published time-details"> <span class="date-start dtstart">[[=startTime]] </span> [[ if(endTime.length) { ]] -<span class="date-end dtend"> [[=endTime]]</span> [[ } ]] </div> [[ if(imageSrc.length) { ]] <div class="tribe-events-event-image"> <a href="[[=permalink]]" title="[[=title]]"> <img src="[[=imageSrc]]" alt="[[=title]]" title="[[=title]]"> </a> </div> [[ } ]] [[ if(excerpt.length) { ]] <p class="entry-summary description">[[=raw excerpt]]</p> [[ } ]] <a href="[[=permalink]]" class="tribe-events-read-more" rel="bookmark">Find out more »</a> </div> </div> </script>
Owchzzz/Militiatoday
wp-content/plugins/the-events-calendar/views/month/mobile.php
PHP
gpl-2.0
1,443
/* * Copyright (C) 2007-2009 Sourcefire, Inc. * * Authors: Tomasz Kojm * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __MANAGER_H #define __MANAGER_H #include "shared/optparser.h" int scanmanager(const struct optstruct *opts); #endif
rhuitl/uClinux
user/clamav/clamscan/manager.h
C
gpl-2.0
878
<?php class RevSliderAdmin extends UniteBaseAdminClassRev{ const DEFAULT_VIEW = "sliders"; const VIEW_SLIDER = "slider"; const VIEW_SLIDER_TEMPLATE = "slider_template"; const VIEW_SLIDERS = "sliders"; const VIEW_SLIDES = "slides"; const VIEW_SLIDE = "slide"; /** * * the constructor */ public function __construct($mainFilepath){ parent::__construct($mainFilepath,$this,self::DEFAULT_VIEW); //set table names GlobalsRevSlider::$table_sliders = self::$table_prefix.GlobalsRevSlider::TABLE_SLIDERS_NAME; GlobalsRevSlider::$table_slides = self::$table_prefix.GlobalsRevSlider::TABLE_SLIDES_NAME; GlobalsRevSlider::$table_settings = self::$table_prefix.GlobalsRevSlider::TABLE_SETTINGS_NAME; GlobalsRevSlider::$table_css = self::$table_prefix.GlobalsRevSlider::TABLE_CSS_NAME; GlobalsRevSlider::$table_layer_anims = self::$table_prefix.GlobalsRevSlider::TABLE_LAYER_ANIMS_NAME; GlobalsRevSlider::$filepath_backup = self::$path_plugin."backup/"; GlobalsRevSlider::$filepath_captions = self::$path_plugin."rs-plugin/css/captions.css"; GlobalsRevSlider::$urlCaptionsCSS = self::$url_plugin."rs-plugin/css/captions.php"; GlobalsRevSlider::$urlStaticCaptionsCSS = self::$url_plugin."rs-plugin/css/static-captions.css"; GlobalsRevSlider::$filepath_dynamic_captions = self::$path_plugin."rs-plugin/css/dynamic-captions.css"; GlobalsRevSlider::$filepath_static_captions = self::$path_plugin."rs-plugin/css/static-captions.css"; GlobalsRevSlider::$filepath_captions_original = self::$path_plugin."rs-plugin/css/captions-original.css"; GlobalsRevSlider::$urlExportZip = self::$path_plugin."export.zip"; $this->init(); } /** * * init all actions */ private function init(){ //$this->checkCopyCaptionsCSS(); //self::setDebugMode(); self::createDBTables(); //include general settings self::requireSettings("general_settings"); //set role $generalSettings = self::getSettings("general"); $role = $generalSettings->getSettingValue("role",UniteBaseAdminClassRev::ROLE_ADMIN); self::setMenuRole($role); self::addMenuPage('Revolution Slider', "adminPages"); $this->addSliderMetaBox('post'); //add common scripts there //self::addAction(self::ACTION_ADMIN_INIT, "onAdminInit"); //ajax response to save slider options. self::addActionAjax("ajax_action", "onAjaxAction"); } /** * * add wildcards metabox variables to posts */ private function addSliderMetaBox($postTypes = null){ //null = all, post = only posts try{ $settings = RevOperations::getWildcardsSettings(); self::addMetaBox("Revolution Slider Options",$settings,array("RevSliderAdmin","customPostFieldsOutput"),$postTypes); }catch(Exception $e){ } } /** * custom output function */ public static function customPostFieldsOutput(UniteSettingsProductSidebarRev $output){ //$settings = $output->getArrSettingNames(); ?> <ul class="revslider_settings"> <?php $output->drawSettingsByNames("slide_template"); ?> </ul> <?php } /** * a must function. please don't remove it. * process activate event - install the db (with delta). */ public static function onActivate(){ self::createDBTables(); } /** * * create db tables */ public static function createDBTables(){ self::createTable(GlobalsRevSlider::TABLE_SLIDERS_NAME); self::createTable(GlobalsRevSlider::TABLE_SLIDES_NAME); self::createTable(GlobalsRevSlider::TABLE_SETTINGS_NAME); self::createTable(GlobalsRevSlider::TABLE_CSS_NAME); self::createTable(GlobalsRevSlider::TABLE_LAYER_ANIMS_NAME); } /** * if caption file don't exists - copy it from the original file. */ public static function checkCopyCaptionsCSS(){ if(file_exists(GlobalsRevSlider::$filepath_captions) == false) copy(GlobalsRevSlider::$filepath_captions_original,GlobalsRevSlider::$filepath_captions); if(!file_exists(GlobalsRevSlider::$filepath_captions) == true){ self::setStartupError("Can't copy <b>captions-original.css </b> to <b>captions.css</b> in <b> plugins/revslider/rs-plugin/css </b> folder. Please try to copy the file by hand or turn to support."); } } /** * * a must function. adds scripts on the page * add all page scripts and styles here. * pelase don't remove this function * common scripts even if the plugin not load, use this function only if no choise. */ public static function onAddScripts(){ self::addStyle("edit_layers","edit_layers"); //add google font //$urlGoogleFont = "http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700"; //self::addStyleAbsoluteUrl($urlGoogleFont,"google-font-pt-sans-narrow"); self::addScriptCommon("edit_layers","unite_layers"); self::addScriptCommon("css_editor","unite_css_editor"); self::addScript("rev_admin"); //include all media upload scripts self::addMediaUploadIncludes(); //add rs css: self::addStyle("settings","rs-plugin-settings","rs-plugin/css"); //if(is_admin()){ self::addDynamicStyle("captions","rs-plugin-captions","rs-plugin/css"); /*}else{ self::addStyle("dynamic-captions","rs-plugin-captions","rs-plugin/css"); }*/ self::addStyle("static-captions","rs-plugin-static","rs-plugin/css"); } /** * * admin main page function. */ public static function adminPages(){ parent::adminPages(); //require styles by view switch(self::$view){ case self::VIEW_SLIDERS: case self::VIEW_SLIDER: case self::VIEW_SLIDER_TEMPLATE: self::requireSettings("slider_settings"); break; case self::VIEW_SLIDES: break; case self::VIEW_SLIDE: break; } self::setMasterView("master_view"); self::requireView(self::$view); } /** * * craete tables */ public static function createTable($tableName){ global $wpdb; $parseCssToDb = false; $checkIfTableExists = $wpdb->get_row("SELECT COUNT(*) AS exist FROM information_schema.tables WHERE table_schema = '".DB_NAME."' AND table_name = '".self::$table_prefix.GlobalsRevSlider::TABLE_CSS_NAME."';"); if($checkIfTableExists->exist > 0){ //check if database is empty $result = $wpdb->get_row("SELECT COUNT( DISTINCT id ) AS NumberOfEntrys FROM ".self::$table_prefix.GlobalsRevSlider::TABLE_CSS_NAME); if($result->NumberOfEntrys == 0) $parseCssToDb = true; } if($parseCssToDb){ $revOperations = new RevOperations(); $revOperations->importCaptionsCssContentArray(); $revOperations->moveOldCaptionsCss(); $revOperations->updateDynamicCaptions(true); } //if table exists - don't create it. $tableRealName = self::$table_prefix.$tableName; if(UniteFunctionsWPRev::isDBTableExists($tableRealName)) return(false); $charset_collate = ''; if(method_exists($wpdb, "get_charset_collate")) $charset_collate = $wpdb->get_charset_collate(); else{ if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate"; } switch($tableName){ case GlobalsRevSlider::TABLE_SLIDERS_NAME: $sql = "CREATE TABLE " .self::$table_prefix.$tableName ." ( id int(9) NOT NULL AUTO_INCREMENT, title tinytext NOT NULL, alias tinytext, params text NOT NULL, PRIMARY KEY (id) )$charset_collate;"; break; case GlobalsRevSlider::TABLE_SLIDES_NAME: $sql = "CREATE TABLE " .self::$table_prefix.$tableName ." ( id int(9) NOT NULL AUTO_INCREMENT, slider_id int(9) NOT NULL, slide_order int not NULL, params text NOT NULL, layers text NOT NULL, PRIMARY KEY (id) )$charset_collate;"; break; case GlobalsRevSlider::TABLE_SETTINGS_NAME: $sql = "CREATE TABLE " .self::$table_prefix.$tableName ." ( id int(9) NOT NULL AUTO_INCREMENT, general TEXT NOT NULL, params TEXT NOT NULL, PRIMARY KEY (id) )$charset_collate;"; break; case GlobalsRevSlider::TABLE_CSS_NAME: $sql = "CREATE TABLE " .self::$table_prefix.$tableName ." ( id int(9) NOT NULL AUTO_INCREMENT, handle TEXT NOT NULL, settings TEXT, hover TEXT, params TEXT NOT NULL, PRIMARY KEY (id) )$charset_collate;"; $parseCssToDb = true; break; case GlobalsRevSlider::TABLE_LAYER_ANIMS_NAME: $sql = "CREATE TABLE " .self::$table_prefix.$tableName ." ( id int(9) NOT NULL AUTO_INCREMENT, handle TEXT NOT NULL, params TEXT NOT NULL, PRIMARY KEY (id) )$charset_collate;"; break; default: UniteFunctionsRev::throwError("table: $tableName not found"); break; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); if($parseCssToDb){ $revOperations = new RevOperations(); $revOperations->importCaptionsCssContentArray(); $revOperations->moveOldCaptionsCss(); $revOperations->updateDynamicCaptions(true); } } /** * * import slideer handle (not ajax response) */ private static function importSliderHandle($viewBack = null, $updateAnim = true, $updateStatic = true){ dmp(__("importing slider setings and data...",REVSLIDER_TEXTDOMAIN)); $slider = new RevSlider(); $response = $slider->importSliderFromPost($updateAnim, $updateStatic); $sliderID = $response["sliderID"]; if(empty($viewBack)){ $viewBack = self::getViewUrl(self::VIEW_SLIDER,"id=".$sliderID); if(empty($sliderID)) $viewBack = self::getViewUrl(self::VIEW_SLIDERS); } //handle error if($response["success"] == false){ $message = $response["error"]; dmp("<b>Error: ".$message."</b>"); echo UniteFunctionsRev::getHtmlLink($viewBack, __("Go Back",REVSLIDER_TEXTDOMAIN)); } else{ //handle success, js redirect. dmp(__("Slider Import Success, redirecting...",REVSLIDER_TEXTDOMAIN)); echo "<script>location.href='$viewBack'</script>"; } exit(); } /** * * onAjax action handler */ public static function onAjaxAction(){ $slider = new RevSlider(); $slide = new RevSlide(); $operations = new RevOperations(); $action = self::getPostGetVar("client_action"); $data = self::getPostGetVar("data"); $nonce = self::getPostGetVar("nonce"); try{ //verify the nonce $isVerified = wp_verify_nonce($nonce, "revslider_actions"); if($isVerified == false) UniteFunctionsRev::throwError("Wrong request"); switch($action){ case "export_slider": $sliderID = self::getGetVar("sliderid"); $dummy = self::getGetVar("dummy"); $slider->initByID($sliderID); $slider->exportSlider($dummy); break; case "import_slider": $updateAnim = self::getPostGetVar("update_animations"); $updateStatic = self::getPostGetVar("update_static_captions"); self::importSliderHandle(null, $updateAnim, $updateStatic); break; case "import_slider_slidersview": $viewBack = self::getViewUrl(self::VIEW_SLIDERS); $updateAnim = self::getPostGetVar("update_animations"); $updateStatic = self::getPostGetVar("update_static_captions"); self::importSliderHandle($viewBack, $updateAnim, $updateStatic); break; case "create_slider": self::requireSettings("slider_settings"); $settingsMain = self::getSettings("slider_main"); $settingsParams = self::getSettings("slider_params"); $data = $operations->modifyCustomSliderParams($data); $newSliderID = $slider->createSliderFromOptions($data,$settingsMain,$settingsParams); self::ajaxResponseSuccessRedirect( __("The slider successfully created",REVSLIDER_TEXTDOMAIN), self::getViewUrl("sliders")); break; case "update_slider": self::requireSettings("slider_settings"); $settingsMain = self::getSettings("slider_main"); $settingsParams = self::getSettings("slider_params"); $data = $operations->modifyCustomSliderParams($data); $slider->updateSliderFromOptions($data,$settingsMain,$settingsParams); self::ajaxResponseSuccess(__("Slider updated",REVSLIDER_TEXTDOMAIN)); break; case "delete_slider": $isDeleted = $slider->deleteSliderFromData($data); if(is_array($isDeleted)){ $isDeleted = implode(', ', $isDeleted); self::ajaxResponseError("Template can't be deleted, it is still being used by the following Sliders: ".$isDeleted); }else{ self::ajaxResponseSuccessRedirect( __("The slider deleted",REVSLIDER_TEXTDOMAIN), self::getViewUrl(self::VIEW_SLIDERS)); } break; case "duplicate_slider": $slider->duplicateSliderFromData($data); self::ajaxResponseSuccessRedirect( __("The duplicate successfully, refreshing page...",REVSLIDER_TEXTDOMAIN), self::getViewUrl(self::VIEW_SLIDERS)); break; case "add_slide": $numSlides = $slider->createSlideFromData($data); $sliderID = $data["sliderid"]; if($numSlides == 1){ $responseText = __("Slide Created",REVSLIDER_TEXTDOMAIN); } else $responseText = $numSlides . " ".__("Slides Created",REVSLIDER_TEXTDOMAIN); $urlRedirect = self::getViewUrl(self::VIEW_SLIDES,"id=$sliderID"); self::ajaxResponseSuccessRedirect($responseText,$urlRedirect); break; case "add_slide_fromslideview": $slideID = $slider->createSlideFromData($data,true); $urlRedirect = self::getViewUrl(self::VIEW_SLIDE,"id=$slideID"); $responseText = __("Slide Created, redirecting...",REVSLIDER_TEXTDOMAIN); self::ajaxResponseSuccessRedirect($responseText,$urlRedirect); break; case "update_slide": require self::getSettingsFilePath("slide_settings"); $slide->updateSlideFromData($data,$slideSettings); self::ajaxResponseSuccess(__("Slide updated",REVSLIDER_TEXTDOMAIN)); break; case "delete_slide": $isPost = $slide->deleteSlideFromData($data); if($isPost) $message = __("Post Deleted Successfully",REVSLIDER_TEXTDOMAIN); else $message = __("Slide Deleted Successfully",REVSLIDER_TEXTDOMAIN); $sliderID = UniteFunctionsRev::getVal($data, "sliderID"); self::ajaxResponseSuccessRedirect( $message, self::getViewUrl(self::VIEW_SLIDES,"id=$sliderID")); break; case "duplicate_slide": $sliderID = $slider->duplicateSlideFromData($data); self::ajaxResponseSuccessRedirect( __("Slide Duplicated Successfully",REVSLIDER_TEXTDOMAIN), self::getViewUrl(self::VIEW_SLIDES,"id=$sliderID")); break; case "copy_move_slide": $sliderID = $slider->copyMoveSlideFromData($data); self::ajaxResponseSuccessRedirect( __("The operation successfully, refreshing page...",REVSLIDER_TEXTDOMAIN), self::getViewUrl(self::VIEW_SLIDES,"id=$sliderID")); break; case "get_static_css": $contentCSS = $operations->getStaticCss(); self::ajaxResponseData($contentCSS); break; case "get_dynamic_css": $contentCSS = $operations->getDynamicCss(); self::ajaxResponseData($contentCSS); break; case "insert_captions_css": $arrCaptions = $operations->insertCaptionsContentData($data); self::ajaxResponseSuccess(__("CSS saved succesfully!",REVSLIDER_TEXTDOMAIN),array("arrCaptions"=>$arrCaptions)); break; case "update_captions_css": $arrCaptions = $operations->updateCaptionsContentData($data); self::ajaxResponseSuccess(__("CSS saved succesfully!",REVSLIDER_TEXTDOMAIN),array("arrCaptions"=>$arrCaptions)); break; case "delete_captions_css": $arrCaptions = $operations->deleteCaptionsContentData($data); self::ajaxResponseSuccess(__("Style deleted succesfully!",REVSLIDER_TEXTDOMAIN),array("arrCaptions"=>$arrCaptions)); break; case "update_static_css": $staticCss = $operations->updateStaticCss($data); self::ajaxResponseSuccess(__("CSS saved succesfully!",REVSLIDER_TEXTDOMAIN),array("css"=>$staticCss)); break; case "insert_custom_anim": $arrAnims = $operations->insertCustomAnim($data); //$arrCaptions = self::ajaxResponseSuccess(__("Animation saved succesfully!",REVSLIDER_TEXTDOMAIN), $arrAnims); //,array("arrCaptions"=>$arrCaptions) break; case "update_custom_anim": $arrAnims = $operations->updateCustomAnim($data); self::ajaxResponseSuccess(__("Animation saved succesfully!",REVSLIDER_TEXTDOMAIN), $arrAnims); //,array("arrCaptions"=>$arrCaptions) break; case "delete_custom_anim": $arrAnims = $operations->deleteCustomAnim($data); self::ajaxResponseSuccess(__("Animation saved succesfully!",REVSLIDER_TEXTDOMAIN), $arrAnims); //,array("arrCaptions"=>$arrCaptions) break; case "update_slides_order": $slider->updateSlidesOrderFromData($data); self::ajaxResponseSuccess(__("Order updated successfully",REVSLIDER_TEXTDOMAIN)); break; case "change_slide_image": $slide->updateSlideImageFromData($data); $sliderID = UniteFunctionsRev::getVal($data, "slider_id"); self::ajaxResponseSuccessRedirect( __("Slide Changed Successfully",REVSLIDER_TEXTDOMAIN), self::getViewUrl(self::VIEW_SLIDES,"id=$sliderID")); break; case "preview_slide": $operations->putSlidePreviewByData($data); break; case "preview_slider": $sliderID = UniteFunctionsRev::getPostGetVariable("sliderid"); $operations->previewOutput($sliderID); break; case "toggle_slide_state": $currentState = $slide->toggleSlideStatFromData($data); self::ajaxResponseData(array("state"=>$currentState)); break; case "slide_lang_operation": $responseData = $slide->doSlideLangOperation($data); self::ajaxResponseData($responseData); break; case "update_plugin": self::updatePlugin(self::DEFAULT_VIEW); break; case "update_text": self::updateSettingsText(); self::ajaxResponseSuccess(__("All files successfully updated",REVSLIDER_TEXTDOMAIN)); break; case "update_general_settings": $operations->updateGeneralSettings($data); self::ajaxResponseSuccess(__("General settings updated",REVSLIDER_TEXTDOMAIN)); break; case "update_posts_sortby": $slider->updatePostsSortbyFromData($data); self::ajaxResponseSuccess(__("Sortby updated",REVSLIDER_TEXTDOMAIN)); break; case "replace_image_urls": $slider->replaceImageUrlsFromData($data); self::ajaxResponseSuccess(__("Image urls replaced",REVSLIDER_TEXTDOMAIN)); break; case "reset_slide_settings": $slider->resetSlideSettings($data); self::ajaxResponseSuccess(__("Settings in all Slides changed",REVSLIDER_TEXTDOMAIN)); break; default: self::ajaxResponseError("wrong ajax action: $action "); break; } } catch(Exception $e){ $message = $e->getMessage(); if($action == "preview_slide" || $action == "preview_slider"){ echo $message; exit(); } self::ajaxResponseError($message); } //it's an ajax action, so exit self::ajaxResponseError("No response output on <b> $action </b> action. please check with the developer."); exit(); } } ?>
DigitalBrainSwitch/liveserver
wp-content/plugins/revslider/revslider_admin.php
PHP
gpl-2.0
20,042
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telegram.messenger.exoplayer.text; import android.annotation.TargetApi; import android.graphics.Color; import android.graphics.Typeface; import android.view.accessibility.CaptioningManager; import android.view.accessibility.CaptioningManager.CaptionStyle; import org.telegram.messenger.exoplayer.util.Util; /** * A compatibility wrapper for {@link CaptionStyle}. */ public final class CaptionStyleCompat { /** * Edge type value specifying no character edges. */ public static final int EDGE_TYPE_NONE = 0; /** * Edge type value specifying uniformly outlined character edges. */ public static final int EDGE_TYPE_OUTLINE = 1; /** * Edge type value specifying drop-shadowed character edges. */ public static final int EDGE_TYPE_DROP_SHADOW = 2; /** * Edge type value specifying raised bevel character edges. */ public static final int EDGE_TYPE_RAISED = 3; /** * Edge type value specifying depressed bevel character edges. */ public static final int EDGE_TYPE_DEPRESSED = 4; /** * Use color setting specified by the track and fallback to default caption style. */ public static final int USE_TRACK_COLOR_SETTINGS = 1; /** * Default caption style. */ public static final CaptionStyleCompat DEFAULT = new CaptionStyleCompat( Color.WHITE, Color.BLACK, Color.TRANSPARENT, EDGE_TYPE_NONE, Color.WHITE, null); /** * The preferred foreground color. */ public final int foregroundColor; /** * The preferred background color. */ public final int backgroundColor; /** * The preferred window color. */ public final int windowColor; /** * The preferred edge type. One of: * <ul> * <li>{@link #EDGE_TYPE_NONE} * <li>{@link #EDGE_TYPE_OUTLINE} * <li>{@link #EDGE_TYPE_DROP_SHADOW} * <li>{@link #EDGE_TYPE_RAISED} * <li>{@link #EDGE_TYPE_DEPRESSED} * </ul> */ public final int edgeType; /** * The preferred edge color, if using an edge type other than {@link #EDGE_TYPE_NONE}. */ public final int edgeColor; /** * The preferred typeface. */ public final Typeface typeface; /** * Creates a {@link CaptionStyleCompat} equivalent to a provided {@link CaptionStyle}. * * @param captionStyle A {@link CaptionStyle}. * @return The equivalent {@link CaptionStyleCompat}. */ @TargetApi(19) public static CaptionStyleCompat createFromCaptionStyle( CaptioningManager.CaptionStyle captionStyle) { if (Util.SDK_INT >= 21) { return createFromCaptionStyleV21(captionStyle); } else { // Note - Any caller must be on at least API level 19 or greater (because CaptionStyle did // not exist in earlier API levels). return createFromCaptionStyleV19(captionStyle); } } /** * @param foregroundColor See {@link #foregroundColor}. * @param backgroundColor See {@link #backgroundColor}. * @param windowColor See {@link #windowColor}. * @param edgeType See {@link #edgeType}. * @param edgeColor See {@link #edgeColor}. * @param typeface See {@link #typeface}. */ public CaptionStyleCompat(int foregroundColor, int backgroundColor, int windowColor, int edgeType, int edgeColor, Typeface typeface) { this.foregroundColor = foregroundColor; this.backgroundColor = backgroundColor; this.windowColor = windowColor; this.edgeType = edgeType; this.edgeColor = edgeColor; this.typeface = typeface; } @TargetApi(19) private static CaptionStyleCompat createFromCaptionStyleV19( CaptioningManager.CaptionStyle captionStyle) { return new CaptionStyleCompat( captionStyle.foregroundColor, captionStyle.backgroundColor, Color.TRANSPARENT, captionStyle.edgeType, captionStyle.edgeColor, captionStyle.getTypeface()); } @TargetApi(21) private static CaptionStyleCompat createFromCaptionStyleV21( CaptioningManager.CaptionStyle captionStyle) { return new CaptionStyleCompat( captionStyle.hasForegroundColor() ? captionStyle.foregroundColor : DEFAULT.foregroundColor, captionStyle.hasBackgroundColor() ? captionStyle.backgroundColor : DEFAULT.backgroundColor, captionStyle.hasWindowColor() ? captionStyle.windowColor : DEFAULT.windowColor, captionStyle.hasEdgeType() ? captionStyle.edgeType : DEFAULT.edgeType, captionStyle.hasEdgeColor() ? captionStyle.edgeColor : DEFAULT.edgeColor, captionStyle.getTypeface()); } }
Puja-Mishra/Android_FreeChat
Telegram-master/TMessagesProj/src/main/java/org/telegram/messenger/exoplayer/text/CaptionStyleCompat.java
Java
gpl-2.0
5,086
#include "disablepostprocessing.h" bool Settings::DisablePostProcessing::enabled = false; void DisablePostProcessing::BeginFrame() { *s_bOverridePostProcessingDisable = Settings::DisablePostProcessing::enabled; }
DankPaster/SlashHook
src/Hacks/disablepostprocessing.cpp
C++
gpl-3.0
216
@media screen { .markItUpHeader{text-align:left} .float-l{float:left} .form-suggest{height:200px;background:#DEE2D0;vertical-align:top} .form-input input{font-size:10px} } @media print { .hide{display:none} } @media screen { .form-input textarea{font-size:11px;width:350px} .form-label{font-size:10px;font-weight:700;line-height:25px;padding-right:10px;text-align:right;width:100px;color:#39738F} .font-9{font-size:9px} .form-topic{font-weight:700} .form-error{color:red} .inline{display:inline} .space-10{clear:both;font-size:10px;height:10px;line-height:10px} .suggest-success{color:green;padding-left:10px;font-size:11px;font-weight:700} .top{vertical-align:top} table td{padding:3px} a:link,a:active,a:visited,a.postlink{color:#069;text-decoration:none} a:hover{color:#DD6900} a.admin:hover,a.mod:hover{color:#DD6900} a.but,a.but:hover,a.but:visited{color:#000;text-decoration:none} a.topictitle:visited{color:#5493B4} a.topictitle:hover{color:#DD6900} body{color:#000;font:11px Verdana,Arial,Helvetica,sans-serif;margin:0 10px 10px;padding:0;overflow:auto} font,th,td,p{font:12px Verdana,Arial,Helvetica,sans-serif} form{display:inline} hr{border:0 solid #FFF;border-top-width:1px;height:0} img{border:0 solid} input{font:11px Verdana,Arial,Helvetica,sans-serif} input.button,input.liteoption,.fakebut{background:#FAFAFA;border:1px solid #000;font-size:11px} input.catbutton{background:#FAFAFA;border:1px solid #000;font-size:10px} input.mainoption{background:#FAFAFA;border:1px solid #000;font-size:11px;font-weight:700} input.post,textarea.post{background:#FFF;border:1px solid #000;font:11px Verdana,Arial,Helvetica,sans-serif;padding-bottom:2px;padding-left:2px} select{background:#FFF;font:11px Verdana,Arial,Helvetica,sans-serif} table{text-align:left} td{vertical-align:middle} td.cat{background-color:#C2C6BA;font-weight:700;height:20px;letter-spacing:1px;text-indent:4px} td.genmed,.genmed{font-size:11px} td.rowpic{background:#C2C6BA} td.spacerow{background:#E5E6E2} th{background-color:#FADD31;background-repeat:repeat-x;color:#68685E;font-size:11px;font-weight:700;line-height:16px;height:16px;padding-left:8px;padding-right:8px;text-align:center;white-space:nowrap} .admin,.mod{font-size:11px;font-weight:700} .admin,a.admin,a.admin:visited{color:#FFA34F} .bodyline{background:#FFF;border:1px solid #98AAB1} .center{text-align:center} .code{background:#FAFAFA;border:1px solid #D1D7DC;color:#060;font:12px Courier,"Courier New",sans-serif;padding:5px} .errorline{background:#E5E6E2;border:1px solid #8F8B8B;color:#D92A2A} .explaintitle{color:#5C81B1;font-size:11px;font-weight:700} .forumline{background:#FFF} .gensmall{font-size:10px} .h1-font{color:#069;display:inline;font:bold 13px Verdana,Arial,Helvetica,sans-serif;margin:.3em;text-decoration:none} .h2-font{display:inline;font:11px Verdana,Arial,Helvetica,sans-serif} .height1{height:1px} .height22{height:22px} .height25{height:25px} .height28{height:28px} .height30{height:30px} .height40{height:40px} .helpline{border:0 solid;font-size:10px} .imgfolder{margin:1px 4px} .imgspace{margin-left:1px;margin-right:2px} .imgtopic,.imgicon{margin-left:3px} .left{text-align:left} .maintitle,h1,h2{color:#5C81B1;font:bold 20px/120% "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;text-decoration:none} .maxwidth{width:100%} .mod,a.mod,a.mod:visited{color:#060} .name{font-size:11px;font-weight:700} .nav{font-size:11px;font-weight:700} .nowrap{white-space:nowrap} .postbody{font-size:12px;line-height:125%} .postbody a{text-decoration:underline} .postdetails{color:#00396A;font-size:10px} .quote{background:#F3F3EF;border:1px solid #C2C6BA;color:#069;font-size:11px;line-height:125%} .right{text-align:right} .row1{background:#F0F0EB} .row2,.helpline{background:#E5E6E2} .row3{background:#DBDBD4} .subtitle,h2{font:bold 18px/180% "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;text-decoration:none} .topictitle{color:#000;font-size:11px;font-weight:700} .underline{text-decoration:underline} .top{vertical-align:top} .image-hspace{margin-right:3px} .clear{clear:both} .degrade{background-color:#777;background:-webkit-gradient(linear,left top,left bottom,from(#999),to(#666));background-image:-moz-linear-gradient(top,#999,#666);filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#999999',endColorstr='#666666');filter:progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=146,Strength=5);-ms-filter:"progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#999999',endColorstr='#666666')";filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ff999999',endColorstr='#ff666666')} } @media print { .degrade{background:none} }
phenix-factory/fci-obedience
plugins-dist/compresseur/tests/css/expected_more_screen.css
CSS
gpl-3.0
4,682
#!/bin/sh set -eu platform="$1" env cd ~/ if [ "${platform}" = "freebsd" ]; then while true; do env ASSUME_ALWAYS_YES=YES pkg bootstrap && \ pkg install -y \ bash \ curl \ gtar \ python \ py27-Jinja2 \ py27-virtualenv \ py27-cryptography \ sudo \ && break echo "Failed to install packages. Sleeping before trying again..." sleep 10 done pip --version 2>/dev/null || curl --silent --show-error https://bootstrap.pypa.io/get-pip.py | python elif [ "${platform}" = "rhel" ]; then while true; do yum install -y \ gcc \ python-devel \ python-jinja2 \ python-virtualenv \ python2-cryptography \ && break echo "Failed to install packages. Sleeping before trying again..." sleep 10 done pip --version 2>/dev/null || curl --silent --show-error https://bootstrap.pypa.io/get-pip.py | python fi if [ "${platform}" = "freebsd" ] || [ "${platform}" = "osx" ]; then pip install virtualenv # Tests assume loopback addresses other than 127.0.0.1 will work. # Add aliases for loopback addresses used by tests. for i in 3 4 254; do ifconfig lo0 alias "127.0.0.${i}" up done ifconfig lo0 fi # Since tests run as root, we also need to be able to ssh to localhost as root. sed -i= 's/^# *PermitRootLogin.*$/PermitRootLogin yes/;' /etc/ssh/sshd_config if [ "${platform}" = "freebsd" ]; then # Restart sshd for configuration changes and loopback aliases to work. service sshd restart fi # Generate our ssh key and add it to our authorized_keys file. # We also need to add localhost's server keys to known_hosts. if [ ! -f "${HOME}/.ssh/id_rsa.pub" ]; then ssh-keygen -q -t rsa -N '' -f "${HOME}/.ssh/id_rsa" cp "${HOME}/.ssh/id_rsa.pub" "${HOME}/.ssh/authorized_keys" for key in /etc/ssh/ssh_host_*_key.pub; do pk=$(cat "${key}") echo "localhost ${pk}" >> "${HOME}/.ssh/known_hosts" done fi # Improve prompts on remote host for interactive use. # shellcheck disable=SC1117 cat << EOF > ~/.bashrc alias ls='ls -G' export PS1='\[\e]0;\u@\h: \w\a\]\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' EOF # Make sure ~/ansible/ is the starting directory for interactive shells. if [ "${platform}" = "osx" ]; then echo "cd ~/ansible/" >> ~/.bashrc fi
trondhindenes/ansible
test/runner/setup/remote.sh
Shell
gpl-3.0
2,489
<?php return [ 'user:add' => [ 'description' => 'Füge einen lokalen Benutzer hinzu. Sie können sich nur einloggen wenn die Authentifizierung auf MySQL gesetzt ist', 'arguments' => [ 'username' => 'Die Authentifizierung mit der sich der Benutzer einloggt', ], 'options' => [ 'descr' => 'Beschreibung', 'email' => 'E-Mail', 'password' => 'Passwort des Benutzers. Wenn nicht angegeben werden Sie danach gefragt', 'full-name' => 'Voller Name des Benutzers', 'role' => 'Deklariere dem Benutzer die Rolle :roles', ], 'password-request' => 'Definieren Sie ein Benutzerpasswort', 'success' => 'Benutzer :username erfolgreich hinzugefügt', 'wrong-auth' => 'Achtung! Sie können sich nicht mit diesem Benutzernamen einloggen wenn die Authentifizierung nicht auf MySQL gesetzt ist', ], ];
nwautomator/librenms
resources/lang/de/commands.php
PHP
gpl-3.0
926
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2012-2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM is distributed in the hope that 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // inline Foam::cellShapeControlMesh& Foam::cellShapeControl::shapeControlMesh() { return shapeControlMesh_; } inline const Foam::cellShapeControlMesh& Foam::cellShapeControl::shapeControlMesh() const { return shapeControlMesh_; } inline const Foam::scalar& Foam::cellShapeControl::defaultCellSize() const { return defaultCellSize_; } inline const Foam::cellAspectRatioControl& Foam::cellShapeControl::aspectRatio() const { return aspectRatio_; } inline const Foam::cellSizeAndAlignmentControls& Foam::cellShapeControl::sizeAndAlignment() const { return sizeAndAlignment_; } inline const Foam::scalar& Foam::cellShapeControl::minimumCellSize() const { return minimumCellSize_; } // ************************************************************************* //
adrcad/OpenFOAM-2.3.x
applications/utilities/mesh/generation/foamyHexMesh/conformalVoronoiMesh/cellShapeControl/cellShapeControl/cellShapeControlI.H
C++
gpl-3.0
2,031
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Chegourt, R.K. -- Type: Outpost Conquest Guards -- @pos -295 16 418 119 ------------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; -------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ARAGONEU; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
Igdra/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Chegourt_RK.lua
Lua
gpl-3.0
3,350
package com.temenos.interaction.core.hypermedia; /* * #%L * interaction-core * %% * Copyright (C) 2012 - 2013 Temenos Holdings N.V. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ public class TestBean { TestBean(String s, int i) { stringField = s; intField = i; } private String stringField; private int intField; public String getStringField() { return stringField; } public int getIntField() { return intField; } }
schwadorf/IRIS
interaction-core/src/test/java/com/temenos/interaction/core/hypermedia/TestBean.java
Java
agpl-3.0
1,065
odoo.define('iap.CrashManager', function (require) { "use strict"; var ajax = require('web.ajax'); var core = require('web.core'); var CrashManager = require('web.CrashManager'); var Dialog = require('web.Dialog'); var _t = core._t; var QWeb = core.qweb; CrashManager.include({ /** * @override */ rpc_error: function (error) { if (error.data.name === "odoo.addons.iap.models.iap.InsufficientCreditError") { var error_data = JSON.parse(error.data.message); ajax.jsonRpc('/web/dataset/call_kw', 'call', { model: 'iap.account', method: 'get_credits_url', args: [], kwargs: { base_url: error_data.base_url, service_name: error_data.service_name, credit: error_data.credit, } }).then(function (url) { var content = $(QWeb.render('iap.redirect_to_odoo_credit', { data: error_data, })) if (error_data.body) { content.css('padding', 0); } new Dialog(this, { size: 'large', title: error_data.title || _t("Insufficient Balance"), $content: content, buttons: [ {text: _t('Buy credits at Odoo'), classes : "btn-primary", click: function() { window.open(url, '_blank'); }, close:true}, {text: _t("Cancel"), close: true} ], }).open(); }); } else { this._super.apply(this, arguments); } }, }); });
maxive/erp
addons/iap/static/src/js/crash_manager.js
JavaScript
agpl-3.0
1,778
# -*- coding: utf-8 -*- import json from odoo import fields def monkey_patch(cls): """ Return a method decorator to monkey-patch the given class. """ def decorate(func): name = func.__name__ func.super = getattr(cls, name, None) setattr(cls, name, func) return func return decorate # # Implement sparse fields by monkey-patching fields.Field # fields.Field.__doc__ += """ .. _field-sparse: .. rubric:: Sparse fields Sparse fields have a very small probability of being not null. Therefore many such fields can be serialized compactly into a common location, the latter being a so-called "serialized" field. :param sparse: the name of the field where the value of this field must be stored. """ @monkey_patch(fields.Field) def _get_attrs(self, model, name): attrs = _get_attrs.super(self, model, name) if attrs.get('sparse'): # by default, sparse fields are not stored and not copied attrs['store'] = False attrs['copy'] = attrs.get('copy', False) attrs['compute'] = self._compute_sparse if not attrs.get('readonly'): attrs['inverse'] = self._inverse_sparse return attrs @monkey_patch(fields.Field) def _compute_sparse(self, records): for record in records: values = record[self.sparse] record[self.name] = values.get(self.name) if self.relational: for record in records: record[self.name] = record[self.name].exists() @monkey_patch(fields.Field) def _inverse_sparse(self, records): for record in records: values = record[self.sparse] value = self.convert_to_read(record[self.name], record, use_name_get=False) if value: if values.get(self.name) != value: values[self.name] = value record[self.sparse] = values else: if self.name in values: values.pop(self.name) record[self.sparse] = values # # Definition and implementation of serialized fields # class Serialized(fields.Field): """ Serialized fields provide the storage for sparse fields. """ type = 'serialized' _slots = { 'prefetch': False, # not prefetched by default } column_type = ('text', 'text') def convert_to_column(self, value, record, values=None): return json.dumps(value) def convert_to_cache(self, value, record, validate=True): # cache format: dict value = value or {} return value if isinstance(value, dict) else json.loads(value) fields.Serialized = Serialized
Aravinthu/odoo
addons/base_sparse_field/models/fields.py
Python
agpl-3.0
2,668
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.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.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------- * Hour.java * --------- * (C) Copyright 2001-2014, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-Oct-2001 : Version 1 (DG); * 18-Dec-2001 : Changed order of parameters in constructor (DG); * 19-Dec-2001 : Added a new constructor as suggested by Paul English (DG); * 14-Feb-2002 : Fixed bug in Hour(Date) constructor (DG); * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to * evaluate with reference to a particular time zone (DG); * 15-Mar-2002 : Changed API (DG); * 16-Apr-2002 : Fixed small time zone bug in constructor (DG); * 10-Sep-2002 : Added getSerialIndex() method (DG); * 07-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 10-Jan-2003 : Changed base class and method names (DG); * 13-Mar-2003 : Moved to com.jrefinery.data.time package, and implemented * Serializable (DG); * 21-Oct-2003 : Added hashCode() method, and new constructor for * convenience (DG); * 30-Sep-2004 : Replaced getTime().getTime() with getTimeInMillis() (DG); * 04-Nov-2004 : Reverted change of 30-Sep-2004, because it won't work for * JDK 1.3 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 05-Oct-2006 : Updated API docs (DG); * 06-Oct-2006 : Refactored to cache first and last millisecond values (DG); * 04-Apr-2007 : In Hour(Date, TimeZone), peg milliseconds using specified * time zone (DG); * 16-Sep-2008 : Deprecated DEFAULT_TIME_ZONE (DG); * 02-Mar-2009 : Added new constructor with Locale (DG); * 05-Jul-2012 : Replaced getTime().getTime() with getTimeInMillis() (DG); * 03-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.jfree.chart.util.ParamChecks; /** * Represents an hour in a specific day. This class is immutable, which is a * requirement for all {@link RegularTimePeriod} subclasses. */ public class Hour extends RegularTimePeriod implements Serializable { /** For serialization. */ private static final long serialVersionUID = -835471579831937652L; /** Useful constant for the first hour in the day. */ public static final int FIRST_HOUR_IN_DAY = 0; /** Useful constant for the last hour in the day. */ public static final int LAST_HOUR_IN_DAY = 23; /** The day. */ private Day day; /** The hour. */ private byte hour; /** The first millisecond. */ private long firstMillisecond; /** The last millisecond. */ private long lastMillisecond; /** * Constructs a new Hour, based on the system date/time. */ public Hour() { this(new Date()); } /** * Constructs a new Hour. * * @param hour the hour (in the range 0 to 23). * @param day the day (<code>null</code> not permitted). */ public Hour(int hour, Day day) { ParamChecks.nullNotPermitted(day, "day"); this.hour = (byte) hour; this.day = day; peg(Calendar.getInstance()); } /** * Creates a new hour. * * @param hour the hour (0-23). * @param day the day (1-31). * @param month the month (1-12). * @param year the year (1900-9999). */ public Hour(int hour, int day, int month, int year) { this(hour, new Day(day, month, year)); } /** * Constructs a new instance, based on the supplied date/time and * the default time zone. * * @param time the date-time (<code>null</code> not permitted). * * @see #Hour(Date, TimeZone) */ public Hour(Date time) { // defer argument checking... this(time, TimeZone.getDefault(), Locale.getDefault()); } /** * Constructs a new instance, based on the supplied date/time evaluated * in the specified time zone. * * @param time the date-time (<code>null</code> not permitted). * @param zone the time zone (<code>null</code> not permitted). * * @deprecated As of 1.0.13, use the constructor that specifies the locale * also. */ public Hour(Date time, TimeZone zone) { this(time, zone, Locale.getDefault()); } /** * Constructs a new instance, based on the supplied date/time evaluated * in the specified time zone. * * @param time the date-time (<code>null</code> not permitted). * @param zone the time zone (<code>null</code> not permitted). * @param locale the locale (<code>null</code> not permitted). * * @since 1.0.13 */ public Hour(Date time, TimeZone zone, Locale locale) { ParamChecks.nullNotPermitted(time, "time"); ParamChecks.nullNotPermitted(zone, "zone"); ParamChecks.nullNotPermitted(locale, "locale"); Calendar calendar = Calendar.getInstance(zone, locale); calendar.setTime(time); this.hour = (byte) calendar.get(Calendar.HOUR_OF_DAY); this.day = new Day(time, zone, locale); peg(calendar); } /** * Returns the hour. * * @return The hour (0 &lt;= hour &lt;= 23). */ public int getHour() { return this.hour; } /** * Returns the day in which this hour falls. * * @return The day. */ public Day getDay() { return this.day; } /** * Returns the year in which this hour falls. * * @return The year. */ public int getYear() { return this.day.getYear(); } /** * Returns the month in which this hour falls. * * @return The month. */ public int getMonth() { return this.day.getMonth(); } /** * Returns the day-of-the-month in which this hour falls. * * @return The day-of-the-month. */ public int getDayOfMonth() { return this.day.getDayOfMonth(); } /** * Returns the first millisecond of the hour. This will be determined * relative to the time zone specified in the constructor, or in the * calendar instance passed in the most recent call to the * {@link #peg(Calendar)} method. * * @return The first millisecond of the hour. * * @see #getLastMillisecond() */ @Override public long getFirstMillisecond() { return this.firstMillisecond; } /** * Returns the last millisecond of the hour. This will be * determined relative to the time zone specified in the constructor, or * in the calendar instance passed in the most recent call to the * {@link #peg(Calendar)} method. * * @return The last millisecond of the hour. * * @see #getFirstMillisecond() */ @Override public long getLastMillisecond() { return this.lastMillisecond; } /** * Recalculates the start date/time and end date/time for this time period * relative to the supplied calendar (which incorporates a time zone). * * @param calendar the calendar (<code>null</code> not permitted). * * @since 1.0.3 */ @Override public void peg(Calendar calendar) { this.firstMillisecond = getFirstMillisecond(calendar); this.lastMillisecond = getLastMillisecond(calendar); } /** * Returns the hour preceding this one. * * @return The hour preceding this one. */ @Override public RegularTimePeriod previous() { Hour result; if (this.hour != FIRST_HOUR_IN_DAY) { result = new Hour(this.hour - 1, this.day); } else { // we are at the first hour in the day... Day prevDay = (Day) this.day.previous(); if (prevDay != null) { result = new Hour(LAST_HOUR_IN_DAY, prevDay); } else { result = null; } } return result; } /** * Returns the hour following this one. * * @return The hour following this one. */ @Override public RegularTimePeriod next() { Hour result; if (this.hour != LAST_HOUR_IN_DAY) { result = new Hour(this.hour + 1, this.day); } else { // we are at the last hour in the day... Day nextDay = (Day) this.day.next(); if (nextDay != null) { result = new Hour(FIRST_HOUR_IN_DAY, nextDay); } else { result = null; } } return result; } /** * Returns a serial index number for the hour. * * @return The serial index number. */ @Override public long getSerialIndex() { return this.day.getSerialIndex() * 24L + this.hour; } /** * Returns the first millisecond of the hour. * * @param calendar the calendar/timezone (<code>null</code> not permitted). * * @return The first millisecond. * * @throws NullPointerException if <code>calendar</code> is * <code>null</code>. */ @Override public long getFirstMillisecond(Calendar calendar) { int year = this.day.getYear(); int month = this.day.getMonth() - 1; int dom = this.day.getDayOfMonth(); calendar.set(year, month, dom, this.hour, 0, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTimeInMillis(); } /** * Returns the last millisecond of the hour. * * @param calendar the calendar/timezone (<code>null</code> not permitted). * * @return The last millisecond. * * @throws NullPointerException if <code>calendar</code> is * <code>null</code>. */ @Override public long getLastMillisecond(Calendar calendar) { int year = this.day.getYear(); int month = this.day.getMonth() - 1; int dom = this.day.getDayOfMonth(); calendar.set(year, month, dom, this.hour, 59, 59); calendar.set(Calendar.MILLISECOND, 999); return calendar.getTimeInMillis(); } /** * Tests the equality of this object against an arbitrary Object. * <P> * This method will return true ONLY if the object is an Hour object * representing the same hour as this instance. * * @param obj the object to compare (<code>null</code> permitted). * * @return <code>true</code> if the hour and day value of the object * is the same as this. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Hour)) { return false; } Hour that = (Hour) obj; if (this.hour != that.hour) { return false; } if (!this.day.equals(that.day)) { return false; } return true; } /** * Returns a string representation of this instance, for debugging * purposes. * * @return A string. */ @Override public String toString() { return "[" + this.hour + "," + getDayOfMonth() + "/" + getMonth() + "/" + getYear() + "]"; } /** * Returns a hash code for this object instance. The approach described by * Joshua Bloch in "Effective Java" has been used here: * <p> * <code>http://developer.java.sun.com/developer/Books/effectivejava * /Chapter3.pdf</code> * * @return A hash code. */ @Override public int hashCode() { int result = 17; result = 37 * result + this.hour; result = 37 * result + this.day.hashCode(); return result; } /** * Returns an integer indicating the order of this Hour object relative to * the specified object: * * negative == before, zero == same, positive == after. * * @param o1 the object to compare. * * @return negative == before, zero == same, positive == after. */ @Override public int compareTo(Object o1) { int result; // CASE 1 : Comparing to another Hour object // ----------------------------------------- if (o1 instanceof Hour) { Hour h = (Hour) o1; result = getDay().compareTo(h.getDay()); if (result == 0) { result = this.hour - h.getHour(); } } // CASE 2 : Comparing to another TimePeriod object // ----------------------------------------------- else if (o1 instanceof RegularTimePeriod) { // more difficult case - evaluate later... result = 0; } // CASE 3 : Comparing to a non-TimePeriod object // --------------------------------------------- else { // consider time periods to be ordered after general objects result = 1; } return result; } /** * Creates an Hour instance by parsing a string. The string is assumed to * be in the format "YYYY-MM-DD HH", perhaps with leading or trailing * whitespace. * * @param s the hour string to parse. * * @return <code>null</code> if the string is not parseable, the hour * otherwise. */ public static Hour parseHour(String s) { Hour result = null; s = s.trim(); String daystr = s.substring(0, Math.min(10, s.length())); Day day = Day.parseDay(daystr); if (day != null) { String hourstr = s.substring( Math.min(daystr.length() + 1, s.length()), s.length() ); hourstr = hourstr.trim(); int hour = Integer.parseInt(hourstr); // if the hour is 0 - 23 then create an hour if ((hour >= FIRST_HOUR_IN_DAY) && (hour <= LAST_HOUR_IN_DAY)) { result = new Hour(hour, day); } } return result; } }
sebkur/JFreeChart
src/main/java/org/jfree/data/time/Hour.java
Java
lgpl-3.0
15,848
package com.netflix.exhibitor.core.automanage; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.netflix.exhibitor.core.Exhibitor; import com.netflix.exhibitor.core.config.IntConfigs; import com.netflix.exhibitor.core.entities.ServerStatus; import com.netflix.exhibitor.core.state.ServerList; import com.netflix.exhibitor.core.state.ServerSpec; import com.netflix.exhibitor.core.state.ServerType; import com.netflix.exhibitor.core.state.UsState; import java.util.List; import java.util.Set; class FlexibleEnsembleBuilder implements EnsembleBuilder { private final Exhibitor exhibitor; private final ClusterState clusterState; private final UsState usState; FlexibleEnsembleBuilder(Exhibitor exhibitor, ClusterState clusterState) { this.exhibitor = exhibitor; this.clusterState = clusterState; usState = new UsState(exhibitor); } @SuppressWarnings("RedundantIfStatement") @Override public boolean newEnsembleNeeded() { if ( (usState.getUs() == null) || clusterState.hasDeadInstances() ) { return true; } return false; } public ServerList createPotentialServerList() { ServerList configuredServerList = clusterState.getConfiguredServerList(); int existingMaxId = getExistingMaxId(configuredServerList); List<ServerSpec> newList = Lists.newArrayList(); Set<String> addedHostnames = Sets.newHashSet(); for ( ServerStatus status : clusterState.getLiveInstances() ) { ServerSpec spec = configuredServerList.getSpec(status.getHostname()); if ( spec == null ) { spec = new ServerSpec(status.getHostname(), ++existingMaxId, ServerType.STANDARD); addedHostnames.add(spec.getHostname()); } newList.add(spec); } if ( usState.getUs() == null ) { ServerSpec spec = new ServerSpec(exhibitor.getThisJVMHostname(), ++existingMaxId, ServerType.STANDARD); addedHostnames.add(spec.getHostname()); newList.add(spec); } int standardTypeCount = 0; for ( ServerSpec spec : newList ) { if ( spec.getServerType() == ServerType.STANDARD ) { ++standardTypeCount; } } int observerThreshold = exhibitor.getConfigManager().getConfig().getInt(IntConfigs.OBSERVER_THRESHOLD); if ( observerThreshold > 0 ) { for ( int i = 0; (standardTypeCount >= observerThreshold) && (i < newList.size()); ++i ) { ServerSpec spec = newList.get(i); if ( addedHostnames.contains(spec.getHostname()) ) // i.e. don't change existing instances to observer { newList.set(i, new ServerSpec(spec.getHostname(), spec.getServerId(), ServerType.OBSERVER)); --standardTypeCount; } } } return new ServerList(newList); } static int getExistingMaxId(ServerList existingList) { int existingMaxId = 0; for ( ServerSpec spec : existingList.getSpecs() ) { if ( spec.getServerId() > existingMaxId ) { existingMaxId = spec.getServerId(); } } return existingMaxId; } }
robzienert/exhibitor
exhibitor-core/src/main/java/com/netflix/exhibitor/core/automanage/FlexibleEnsembleBuilder.java
Java
apache-2.0
3,513
/* ********************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************************** */ package io.seldon.spark.features import java.nio.ByteBuffer import java.util.{Random => JavaRandom} import scala.util.hashing.MurmurHash3 /** * This class implements a XORShift random number generator algorithm * Source: * Marsaglia, G. (2003). Xorshift RNGs. Journal of Statistical Software, Vol. 8, Issue 14. * @see <a href="http://www.jstatsoft.org/v08/i14/paper">Paper</a> * This implementation is approximately 3.5 times faster than * {@link java.util.Random java.util.Random}, partly because of the algorithm, but also due * to renouncing thread safety. JDK's implementation uses an AtomicLong seed, this class * uses a regular Long. We can forgo thread safety since we use a new instance of the RNG * for each thread. */ class XORShiftRandom(init: Long) extends JavaRandom(init) { def this() = this(System.nanoTime) private var seed = XORShiftRandom.hashSeed(init) // we need to just override next - this will be called by nextInt, nextDouble, // nextGaussian, nextLong, etc. override protected def next(bits: Int): Int = { var nextSeed = seed ^ (seed << 21) nextSeed ^= (nextSeed >>> 35) nextSeed ^= (nextSeed << 4) seed = nextSeed (nextSeed & ((1L << bits) -1)).asInstanceOf[Int] } override def setSeed(s: Long) { seed = XORShiftRandom.hashSeed(s) } } /** Contains benchmark method and main method to run benchmark of the RNG */ object XORShiftRandom { /** Hash seeds to have 0/1 bits throughout. */ private def hashSeed(seed: Long): Long = { val bytes = ByteBuffer.allocate(java.lang.Long.SIZE).putLong(seed).array() MurmurHash3.bytesHash(bytes) } /** * Main method for running benchmark * @param args takes one argument - the number of random numbers to generate */ def main(args: Array[String]): Unit = { if (args.length != 1) { println("Benchmark of XORShiftRandom vis-a-vis java.util.Random") println("Usage: XORShiftRandom number_of_random_numbers_to_generate") System.exit(1) } } }
guiquanz/seldon-server
offline-jobs/spark/src/main/scala/io/seldon/spark/features/XORShiftRandom.scala
Scala
apache-2.0
2,787
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.css; import junit.framework.TestCase; /** * Test for the delegating CSS class substitution map which handles compound * class names. * * @author dgajda@google.com (Damian Gajda) */ public class SplittingSubstitutionMapTest extends TestCase { public void testGet() throws Exception { SubstitutionMap map = new SplittingSubstitutionMap( new SimpleSubstitutionMap()); assertEquals("a_", map.get("a")); assertEquals("a_-b_", map.get("a-b")); assertEquals("a_-b_-c_", map.get("a-b-c")); assertEquals("a_-b_-c_-d_", map.get("a-b-c-d")); } public void testSameObjectReturnedIfNoDash() { // Manually force a non-interned string so that we can prove we got back // the same one we meant. If we just used a String literal, it would be // less convincing. String input = new String("abc"); SubstitutionMap map = new SplittingSubstitutionMap( new PassThroughSubstitutionMap()); assertSame(input, map.get(input)); } private static class PassThroughSubstitutionMap implements SubstitutionMap { @Override public String get(String key) { return key; } } }
varshluck/closure-stylesheets
tests/com/google/common/css/SplittingSubstitutionMapTest.java
Java
apache-2.0
1,762
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.sdb.core; import org.apache.jena.sdb.SDB ; import org.apache.jena.sdb.SDBException ; import org.apache.jena.sparql.util.Symbol ; public class SDBConstants { // Not "Integer.MIN_VALUE" which is meaningful to MySQL. public static final int jdbcFetchSizeOff = -1 ; public static Symbol allocSymbol(String shortName) { if ( shortName.matches("^[a-zA-Z]*:") ) throw new SDBException("Symbol short name begins URI scheme") ; return Symbol.create(SDB.symbolSpace+shortName) ; } }
CesarPantoja/jena
jena-sdb/src/main/java/org/apache/jena/sdb/core/SDBConstants.java
Java
apache-2.0
1,368
package io.dropwizard.jetty; import com.codahale.metrics.Timer; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.util.component.ContainerLifeCycle; import java.util.List; /** * A version {@link com.codahale.metrics.jetty9.InstrumentedConnectionFactory}, which supports Jetty 9.3 API. * NOTE: This class could be replaced, when <strong>dropwizard-metrics-jetty9</strong> will support Jetty 9.3. */ public class Jetty93InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { private final ConnectionFactory connectionFactory; private final Timer timer; public Jetty93InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { this.connectionFactory = connectionFactory; this.timer = timer; addBean(connectionFactory); } public ConnectionFactory getConnectionFactory() { return connectionFactory; } public Timer getTimer() { return timer; } @Override public String getProtocol() { return connectionFactory.getProtocol(); } @Override public List<String> getProtocols() { return connectionFactory.getProtocols(); } @Override public Connection newConnection(Connector connector, EndPoint endPoint) { final Connection connection = connectionFactory.newConnection(connector, endPoint); connection.addListener(new Connection.Listener() { private Timer.Context context; @Override public void onOpened(Connection connection) { this.context = timer.time(); } @Override public void onClosed(Connection connection) { context.stop(); } }); return connection; } }
shawnsmith/dropwizard
dropwizard-jetty/src/main/java/io/dropwizard/jetty/Jetty93InstrumentedConnectionFactory.java
Java
apache-2.0
1,938
/*<license> Copyright 2004, PeopleWare n.v. NO RIGHTS ARE GRANTED FOR THE USE OF THIS SOFTWARE, EXCEPT, IN WRITING, TO SELECTED PARTIES. </license>*/ package be.peopleware.jsf_II.i18n; import java.io.Serializable; import java.util.MissingResourceException; import java.util.ResourceBundle; import be.peopleware.i18n_I.ResourceBundleLoadStrategy; import be.peopleware.jsf_II.FatalFacesException; import be.peopleware.jsf_II.RobustCurrent; /** * <p>Strategy pattern to load i18n resource bundles for JSF.</p> * * @author Ren� Clerckx * @author PeopleWare n.v. */ public class JsfResourceBundleLoadStrategy implements ResourceBundleLoadStrategy, Serializable { /* <section name="Meta Information"> */ //------------------------------------------------------------------ /** {@value} */ public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_STATE = "$State$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$ /* </section> */ // Default constructor /** * The {@link ResourceBundle} with name <code>basename</code> is loaded * with the {@link RobustCurrent#locale() current locale from the UI view} * and the {@link ClassLoader} of the {@link Thread current thread}. * If no matching resource bundle can be found with this strategy, * <code>null</code> is returned. * * @see ResourceBundleLoadStrategy#loadResourceBundle(String) * @throws FatalFacesException * RobustCurrent.locale(); */ public ResourceBundle loadResourceBundle(final String basename) throws FatalFacesException { ResourceBundle result = null; if ((basename != null) && !(basename.equals(""))) { try { result = ResourceBundle.getBundle(basename, RobustCurrent.locale(), Thread.currentThread().getContextClassLoader()); } catch (MissingResourceException mrExc) { return null; } } return result; } }
jandppw/ppwcode-recovered-from-google-code
_purgatory/java/jsf/trunk/src/java/be/peopleware/jsf_II/i18n/JsfResourceBundleLoadStrategy.java
Java
apache-2.0
2,141
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpCompiler : CommonCompiler { internal const string ResponseFileName = "csc.rsp"; private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; private readonly string _tempDirectory; protected CSharpCompiler(CSharpCommandLineParser parser, string responseFile, string[] args, BuildPaths buildPaths, string additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader) : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader) { _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); _tempDirectory = buildPaths.TempDirectory; } public override DiagnosticFormatter DiagnosticFormatter { get { return _diagnosticFormatter; } } protected internal new CSharpCommandLineArguments Arguments { get { return (CSharpCommandLineArguments)base.Arguments; } } public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger) { var parseOptions = Arguments.ParseOptions; // We compute script parse options once so we don't have to do it repeatedly in // case there are many script files. var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); bool hadErrors = false; var sourceFiles = Arguments.SourceFiles; var trees = new SyntaxTree[sourceFiles.Length]; var normalizedFilePaths = new string[sourceFiles.Length]; var diagnosticBag = DiagnosticBag.GetInstance(); if (Arguments.CompilationOptions.ConcurrentBuild) { Parallel.For(0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { //NOTE: order of trees is important!! trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); })); } else { for (int i = 0; i < sourceFiles.Length; i++) { //NOTE: order of trees is important!! trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); } } // If errors had been reported in ParseFile, while trying to read files, then we should simply exit. if (hadErrors) { Debug.Assert(diagnosticBag.HasAnyErrors()); ReportErrors(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger); return null; } else { Debug.Assert(diagnosticBag.IsEmptyWithoutResolution); diagnosticBag.Free(); } var diagnostics = new List<DiagnosticInfo>(); var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sourceFiles.Length; i++) { var normalizedFilePath = normalizedFilePaths[i]; Debug.Assert(normalizedFilePath != null); Debug.Assert(PathUtilities.IsAbsolute(normalizedFilePath)); if (!uniqueFilePaths.Add(normalizedFilePath)) { // warning CS2002: Source file '{0}' specified multiple times diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded, Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath))); trees[i] = null; } } if (Arguments.TouchedFilesPath != null) { foreach (var path in uniqueFilePaths) { touchedFilesLogger.AddRead(path); } } var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; var appConfigPath = this.Arguments.AppConfigPath; if (appConfigPath != null) { try { using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } if (touchedFilesLogger != null) { touchedFilesLogger.AddRead(appConfigPath); } } catch (Exception ex) { diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message)); } } var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger); var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger); MetadataReferenceResolver referenceDirectiveResolver; var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver); if (ReportErrors(diagnostics, consoleOutput, errorLogger)) { return null; } var strongNameProvider = new LoggingStrongNameProvider(Arguments.KeyFileSearchPaths, touchedFilesLogger, _tempDirectory); var compilation = CSharpCompilation.Create( Arguments.CompilationName, trees.WhereNotNull(), resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithStrongNameProvider(strongNameProvider). WithXmlReferenceResolver(xmlFileResolver). WithSourceReferenceResolver(sourceFileResolver)); return compilation; } private SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string normalizedFilePath) { var fileDiagnostics = new List<DiagnosticInfo>(); var content = TryReadFileContent(file, fileDiagnostics, out normalizedFilePath); if (content == null) { foreach (var info in fileDiagnostics) { diagnostics.Add(MessageProvider.CreateDiagnostic(info)); } fileDiagnostics.Clear(); addedDiagnostics = true; return null; } else { Debug.Assert(fileDiagnostics.Count == 0); return ParseFile(parseOptions, scriptParseOptions, content, file); } } private static SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) { var tree = SyntaxFactory.ParseSyntaxTree( content, file.IsScript ? scriptParseOptions : parseOptions, file.Path); // prepopulate line tables. // we will need line tables anyways and it is better to not wait until we are in emit // where things run sequentially. bool isHiddenDummy; tree.GetMappedLineSpanAndVisibility(default(TextSpan), out isHiddenDummy); return tree; } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output. /// 2) The path of the assembly/module file. /// 3) The path of the pdb file. /// /// When csc produces an executable, but the name of the resulting assembly /// is not specified using the "/out" switch, the name is taken from the name /// of the file (note: file, not class) containing the assembly entrypoint /// (as determined by binding and the "/main" switch). /// /// For example, if the command is "csc /target:exe a.cs b.cs" and b.cs contains the /// entrypoint, then csc will produce "b.exe" and "b.pdb" in the output directory, /// with assembly name "b" and module name "b.exe" embedded in the file. /// </summary> protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { if (Arguments.OutputFileName == null) { Debug.Assert(Arguments.CompilationOptions.OutputKind.IsApplication()); var comp = (CSharpCompilation)compilation; Symbol entryPoint = comp.ScriptClass; if ((object)entryPoint == null) { var method = comp.GetEntryPoint(cancellationToken); if ((object)method != null) { entryPoint = method.PartialImplementationPart ?? method; } } if ((object)entryPoint != null) { string entryPointFileName = PathUtilities.GetFileName(entryPoint.Locations.First().SourceTree.FilePath); return Path.ChangeExtension(entryPointFileName, ".exe"); } else { // no entrypoint found - an error will be reported and the compilation won't be emitted return "error"; } } else { return base.GetOutputFileName(compilation, cancellationToken); } } internal override bool SuppressDefaultResponseFile(IEnumerable<string> args) { return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); } /// <summary> /// Print compiler logo /// </summary> /// <param name="consoleOutput"></param> public override void PrintLogo(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, Culture), GetToolName(), GetAssemblyFileVersion()); consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, Culture)); consoleOutput.WriteLine(); } internal override Type Type { get { // We do not use this.GetType() so that we don't break mock subtypes return typeof(CSharpCompiler); } } internal override string GetToolName() { return ErrorFacts.GetMessage(MessageID.IDS_ToolName, Culture); } /// <summary> /// Print Commandline help message (up to 80 English characters per line) /// </summary> /// <param name="consoleOutput"></param> public override void PrintHelp(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, Culture)); } protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) { return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); } protected override ImmutableArray<DiagnosticAnalyzer> ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider) { return Arguments.ResolveAnalyzersFromArguments(LanguageNames.CSharp, diagnostics, messageProvider, AssemblyLoader); } protected override void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, IList<Diagnostic> diagnostics) { foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives( d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) { string path = (string)directive.File.Value; if (path == null) { continue; } string resolvedPath = resolver.ResolveReference(path, tree.FilePath); if (resolvedPath == null) { diagnostics.Add( MessageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, directive.File.GetLocation(), path, CSharpResources.CouldNotFindFile)); continue; } embeddedFiles.Add(resolvedPath); } } } }
bbarry/roslyn
src/Compilers/CSharp/Portable/CommandLine/CSharpCompiler.cs
C#
apache-2.0
14,211
// rustfmt-indent_style: Block // Function arguments layout fn lorem() {} fn lorem(ipsum: usize) {} fn lorem(ipsum: usize, dolor: usize, sit: usize, amet: usize, consectetur: usize, adipiscing: usize, elit: usize) { // body } // #1441 extern "system" { pub fn GetConsoleHistoryInfo(console_history_info: *mut ConsoleHistoryInfo) -> Boooooooooooooool; } // rustfmt should not add trailing comma for variadic function. See #1623. extern "C" { pub fn variadic_fn(first_parameter: FirstParameterType, second_parameter: SecondParameterType, ...); } // #1652 fn deconstruct(foo: Bar) -> (SocketAddr, Header, Method, RequestUri, HttpVersion, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) { }
graydon/rust
src/tools/rustfmt/tests/source/configs/indent_style/block_args.rs
Rust
apache-2.0
760
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.consul.endpoint; import com.orbitz.consul.Consul; import com.orbitz.consul.EventClient; import com.orbitz.consul.option.EventOptions; import com.orbitz.consul.option.QueryOptions; import org.apache.camel.InvokeOnHeader; import org.apache.camel.Message; import org.apache.camel.component.consul.ConsulConfiguration; import org.apache.camel.component.consul.ConsulConstants; import org.apache.camel.component.consul.ConsulEndpoint; public final class ConsulEventProducer extends AbstractConsulProducer<EventClient> { public ConsulEventProducer(ConsulEndpoint endpoint, ConsulConfiguration configuration) { super(endpoint, configuration, Consul::eventClient); } @InvokeOnHeader(ConsulEventActions.FIRE) protected void fire(Message message) throws Exception { setBodyAndResult( message, getClient().fireEvent( getMandatoryHeader(message, ConsulConstants.CONSUL_KEY, getConfiguration().getKey(), String.class), message.getHeader(ConsulConstants.CONSUL_OPTIONS, EventOptions.BLANK, EventOptions.class), message.getBody(String.class) ) ); } @InvokeOnHeader(ConsulEventActions.LIST) protected void list(Message message) throws Exception { setBodyAndResult( message, getClient().listEvents( message.getHeader(ConsulConstants.CONSUL_KEY, getConfiguration().getKey(), String.class), message.getHeader(ConsulConstants.CONSUL_OPTIONS, QueryOptions.BLANK, QueryOptions.class) ) ); } }
punkhorn/camel-upstream
components/camel-consul/src/main/java/org/apache/camel/component/consul/endpoint/ConsulEventProducer.java
Java
apache-2.0
2,439
/***************************************************************************//** * @file * @brief Peripheral Reflex System (PRS) peripheral API ******************************************************************************* * # License * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ******************************************************************************/ #ifndef EM_PRS_H #define EM_PRS_H #include "em_device.h" #include "em_gpio.h" #include <stdbool.h> #include <stddef.h> #if defined(PRS_COUNT) && (PRS_COUNT > 0) #ifdef __cplusplus extern "C" { #endif /***************************************************************************//** * @addtogroup emlib * @{ ******************************************************************************/ /***************************************************************************//** * @addtogroup PRS * @{ ******************************************************************************/ /******************************************************************************* ******************************* DEFINES *********************************** ******************************************************************************/ #if defined(_SILICON_LABS_32B_SERIES_2) #define PRS_SYNC_CHAN_COUNT PRS_SYNC_CH_NUM #define PRS_ASYNC_CHAN_COUNT PRS_ASYNC_CH_NUM #elif defined(_EFM32_GECKO_FAMILY) #define PRS_SYNC_CHAN_COUNT PRS_CHAN_COUNT #define PRS_ASYNC_CHAN_COUNT 0 #else #define PRS_SYNC_CHAN_COUNT PRS_CHAN_COUNT #define PRS_ASYNC_CHAN_COUNT PRS_CHAN_COUNT #endif #if !defined(_EFM32_GECKO_FAMILY) #define PRS_ASYNC_SUPPORTED 1 #endif /* Some devices have renamed signals so we map some of these signals to common names. */ #if defined(PRS_USART0_RXDATAV) #define PRS_USART0_RXDATA PRS_USART0_RXDATAV #endif #if defined(PRS_USART1_RXDATAV) #define PRS_USART1_RXDATA PRS_USART1_RXDATAV #endif #if defined(PRS_USART2_RXDATAV) #define PRS_USART2_RXDATA PRS_USART2_RXDATAV #endif #if defined(PRS_BURTC_OVERFLOW) #define PRS_BURTC_OF PRS_BURTC_OVERFLOW #endif #if defined(PRS_BURTC_COMP0) #define PRS_BURTC_COMP PRS_BURTC_COMP0 #endif /******************************************************************************* ******************************** ENUMS ************************************ ******************************************************************************/ /** PRS Channel type. */ typedef enum { prsTypeAsync, /**< Asynchronous channel type. */ prsTypeSync /**< Synchronous channel type.*/ } PRS_ChType_t; /** Edge detection type. */ typedef enum { prsEdgeOff, /**< Leave signal as is. */ prsEdgePos, /**< Generate pulses on positive edge. */ prsEdgeNeg, /**< Generate pulses on negative edge. */ prsEdgeBoth /**< Generate pulses on both edges. */ } PRS_Edge_TypeDef; #if defined(_PRS_ASYNC_CH_CTRL_FNSEL_MASK) /** Logic functions that can be used when combining two PRS channels. */ typedef enum { prsLogic_Zero = _PRS_ASYNC_CH_CTRL_FNSEL_LOGICAL_ZERO, prsLogic_A_NOR_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_NOR_B, prsLogic_NOT_A_AND_B = _PRS_ASYNC_CH_CTRL_FNSEL_NOT_A_AND_B, prsLogic_NOT_A = _PRS_ASYNC_CH_CTRL_FNSEL_NOT_A, prsLogic_A_AND_NOT_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_AND_NOT_B, prsLogic_NOT_B = _PRS_ASYNC_CH_CTRL_FNSEL_NOT_B, prsLogic_A_XOR_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_XOR_B, prsLogic_A_NAND_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_NAND_B, prsLogic_A_AND_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_AND_B, prsLogic_A_XNOR_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_XNOR_B, prsLogic_B = _PRS_ASYNC_CH_CTRL_FNSEL_B, prsLogic_A_OR_NOT_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_OR_NOT_B, prsLogic_A = _PRS_ASYNC_CH_CTRL_FNSEL_A, prsLogic_NOT_A_OR_B = _PRS_ASYNC_CH_CTRL_FNSEL_NOT_A_OR_B, prsLogic_A_OR_B = _PRS_ASYNC_CH_CTRL_FNSEL_A_OR_B, prsLogic_One = _PRS_ASYNC_CH_CTRL_FNSEL_LOGICAL_ONE, } PRS_Logic_t; #endif /** PRS Signal. */ typedef enum { prsSignalNone = 0x0, /* Timer Signals */ #if defined(TIMER0) prsSignalTIMER0_UF = PRS_TIMER0_UF, /**< TIMER0 underflow Signal. */ prsSignalTIMER0_OF = PRS_TIMER0_OF, /**< TIMER0 overflow Signal. */ prsSignalTIMER0_CC0 = PRS_TIMER0_CC0, /**< TIMER0 capture/compare channel 0 Signal. */ prsSignalTIMER0_CC1 = PRS_TIMER0_CC1, /**< TIMER0 capture/compare channel 1 Signal. */ prsSignalTIMER0_CC2 = PRS_TIMER0_CC2, /**< TIMER0 capture/compare channel 2 Signal. */ #endif #if defined(TIMER1) prsSignalTIMER1_UF = PRS_TIMER1_UF, /**< TIMER1 underflow Signal. */ prsSignalTIMER1_OF = PRS_TIMER1_OF, /**< TIMER1 overflow Signal. */ prsSignalTIMER1_CC0 = PRS_TIMER1_CC0, /**< TIMER1 capture/compare channel 0 Signal. */ prsSignalTIMER1_CC1 = PRS_TIMER1_CC1, /**< TIMER1 capture/compare channel 1 Signal. */ prsSignalTIMER1_CC2 = PRS_TIMER1_CC2, /**< TIMER1 capture/compare channel 2 Signal. */ #endif #if defined(TIMER2) prsSignalTIMER2_UF = PRS_TIMER2_UF, /**< TIMER2 underflow Signal. */ prsSignalTIMER2_OF = PRS_TIMER2_OF, /**< TIMER2 overflow Signal. */ prsSignalTIMER2_CC0 = PRS_TIMER2_CC0, /**< TIMER2 capture/compare channel 0 Signal. */ prsSignalTIMER2_CC1 = PRS_TIMER2_CC1, /**< TIMER2 capture/compare channel 1 Signal. */ prsSignalTIMER2_CC2 = PRS_TIMER2_CC2, /**< TIMER2 capture/compare channel 2 Signal. */ #endif #if defined(TIMER3) prsSignalTIMER3_UF = PRS_TIMER3_UF, /**< TIMER3 underflow Signal. */ prsSignalTIMER3_OF = PRS_TIMER3_OF, /**< TIMER3 overflow Signal. */ prsSignalTIMER3_CC0 = PRS_TIMER3_CC0, /**< TIMER3 capture/compare channel 0 Signal. */ prsSignalTIMER3_CC1 = PRS_TIMER3_CC1, /**< TIMER3 capture/compare channel 1 Signal. */ prsSignalTIMER3_CC2 = PRS_TIMER3_CC2, /**< TIMER3 capture/compare channel 2 Signal. */ #endif #if defined(PRS_LETIMER0_CH0) prsSignalLETIMER0_CH0 = PRS_LETIMER0_CH0, /**< LETIMER0 channel 0 Signal. */ prsSignalLETIMER0_CH1 = PRS_LETIMER0_CH1, /**< LETIMER0 channel 1 Signal. */ #endif /* RTC/RTCC/BURTC Signals */ #if defined(RTCC) prsSignalRTCC_CCV0 = PRS_RTCC_CCV0, /**< RTCC capture/compare channel 0 Signal. */ prsSignalRTCC_CCV1 = PRS_RTCC_CCV1, /**< RTCC capture/compare channel 1 Signal. */ prsSignalRTCC_CCV2 = PRS_RTCC_CCV2, /**< RTCC capture/compare channel 2 Signal. */ #endif #if defined(BURTC) prsSignalBURTC_COMP = PRS_BURTC_COMP, /**< BURTC compare Signal. */ prsSignalBURTC_OF = PRS_BURTC_OF, /**< BURTC overflow Signal. */ #endif /* ACMP Signals */ #if defined(ACMP0) prsSignalACMP0_OUT = PRS_ACMP0_OUT, /**< ACMP0 Signal. */ #endif #if defined(ACMP1) prsSignalACMP1_OUT = PRS_ACMP1_OUT, /**< ACMP1 output Signal. */ #endif /* USART Signals */ #if defined(USART0) prsSignalUSART0_IRTX = PRS_USART0_IRTX, /**< USART0 IR tx Signal. */ prsSignalUSART0_TXC = PRS_USART0_TXC, /**< USART0 tx complete Signal. */ prsSignalUSART0_RXDATA = PRS_USART0_RXDATA, /**< USART0 rx data available Signal. */ #if (_SILICON_LABS_32B_SERIES > 0) prsSignalUSART0_RTS = PRS_USART0_RTS, /**< USART0 RTS Signal. */ prsSignalUSART0_TX = PRS_USART0_TX, /**< USART0 tx Signal. */ prsSignalUSART0_CS = PRS_USART0_CS, /**< USART0 chip select Signal. */ #endif #endif #if defined(USART1) prsSignalUSART1_TXC = PRS_USART1_TXC, /**< USART1 tx complete Signal. */ prsSignalUSART1_RXDATA = PRS_USART1_RXDATA, /**< USART1 rx data available Signal. */ #if defined(PRS_USART1_IRTX) prsSignalUSART1_IRTX = PRS_USART1_IRTX, /**< USART1 IR tx Signal. */ #endif #if (_SILICON_LABS_32B_SERIES > 0) prsSignalUSART1_RTS = PRS_USART1_RTS, /**< USART1 RTS Signal. */ prsSignalUSART1_TX = PRS_USART1_TX, /**< USART1 tx Signal. */ prsSignalUSART1_CS = PRS_USART1_CS, /**< USART1 chip select Signal. */ #endif #endif #if defined(USART2) prsSignalUSART2_TXC = PRS_USART2_TXC, /**< USART2 tx complete Signal. */ prsSignalUSART2_RXDATA = PRS_USART2_RXDATA, /**< USART2 rx data available Signal. */ #if defined(PRS_USART2_IRTX) prsSignalUSART2_IRTX = PRS_USART2_IRTX, /**< USART2 IR tx Signal. */ #endif #if (_SILICON_LABS_32B_SERIES > 0) prsSignalUSART2_RTS = PRS_USART2_RTS, /**< USART2 RTS Signal. */ prsSignalUSART2_TX = PRS_USART2_TX, /**< USART2 tx Signal. */ prsSignalUSART2_CS = PRS_USART2_CS, /**< USART2 chip select Signal. */ #endif #endif /* ADC Signals */ #if defined(IADC0) prsSignalIADC0_SCANENTRY = PRS_IADC0_SCANENTRYDONE, /**< IADC0 scan entry Signal. */ prsSignalIADC0_SCANTABLE = PRS_IADC0_SCANTABLEDONE, /**< IADC0 scan table Signal. */ prsSignalIADC0_SINGLE = PRS_IADC0_SINGLEDONE, /**< IADC0 single Signal. */ #endif /* GPIO pin Signals */ prsSignalGPIO_PIN0 = PRS_GPIO_PIN0, /**< GPIO Pin 0 Signal. */ prsSignalGPIO_PIN1 = PRS_GPIO_PIN1, /**< GPIO Pin 1 Signal. */ prsSignalGPIO_PIN2 = PRS_GPIO_PIN2, /**< GPIO Pin 2 Signal. */ prsSignalGPIO_PIN3 = PRS_GPIO_PIN3, /**< GPIO Pin 3 Signal. */ prsSignalGPIO_PIN4 = PRS_GPIO_PIN4, /**< GPIO Pin 4 Signal. */ prsSignalGPIO_PIN5 = PRS_GPIO_PIN5, /**< GPIO Pin 5 Signal. */ prsSignalGPIO_PIN6 = PRS_GPIO_PIN6, /**< GPIO Pin 6 Signal. */ prsSignalGPIO_PIN7 = PRS_GPIO_PIN7, /**< GPIO Pin 7 Signal. */ #if defined(PRS_GPIO_PIN15) prsSignalGPIO_PIN8 = PRS_GPIO_PIN8, /**< GPIO Pin 8 Signal. */ prsSignalGPIO_PIN9 = PRS_GPIO_PIN9, /**< GPIO Pin 9 Signal. */ prsSignalGPIO_PIN10 = PRS_GPIO_PIN10, /**< GPIO Pin 10 Signal. */ prsSignalGPIO_PIN11 = PRS_GPIO_PIN11, /**< GPIO Pin 11 Signal. */ prsSignalGPIO_PIN12 = PRS_GPIO_PIN12, /**< GPIO Pin 12 Signal. */ prsSignalGPIO_PIN13 = PRS_GPIO_PIN13, /**< GPIO Pin 13 Signal. */ prsSignalGPIO_PIN14 = PRS_GPIO_PIN14, /**< GPIO Pin 14 Signal. */ prsSignalGPIO_PIN15 = PRS_GPIO_PIN15, /**< GPIO Pin 15 Signal. */ #endif } PRS_Signal_t; #if defined(_SILICON_LABS_32B_SERIES_2) /** PRS Consumers. */ typedef enum { prsConsumerNone = 0x000, /**< No PRS consumer */ prsConsumerCMU_CALDN = offsetof(PRS_TypeDef, CONSUMER_CMU_CALDN), /**< CMU calibration down consumer. */ prsConsumerCMU_CALUP = offsetof(PRS_TypeDef, CONSUMER_CMU_CALUP), /**< CMU calibration up consumer. */ prsConsumerIADC0_SCANTRIGGER = offsetof(PRS_TypeDef, CONSUMER_IADC0_SCANTRIGGER), /**< IADC0 scan trigger consumer. */ prsConsumerIADC0_SINGLETRIGGER = offsetof(PRS_TypeDef, CONSUMER_IADC0_SINGLETRIGGER), /**< IADC0 single trigger consumer. */ prsConsumerLDMA_REQUEST0 = offsetof(PRS_TypeDef, CONSUMER_LDMAXBAR_DMAREQ0), /**< LDMA Request 0 consumer. */ prsConsumerLDMA_REQUEST1 = offsetof(PRS_TypeDef, CONSUMER_LDMAXBAR_DMAREQ1), /**< LDMA Request 1 consumer. */ prsConsumerLETIMER0_CLEAR = offsetof(PRS_TypeDef, CONSUMER_LETIMER0_CLEAR), /**< LETIMER0 clear consumer. */ prsConsumerLETIMER0_START = offsetof(PRS_TypeDef, CONSUMER_LETIMER0_START), /**< LETIMER0 start consumer. */ prsConsumerLETIMER0_STOP = offsetof(PRS_TypeDef, CONSUMER_LETIMER0_STOP), /**< LETIMER0 stop consumer. */ prsConsumerTIMER0_CC0 = offsetof(PRS_TypeDef, CONSUMER_TIMER0_CC0), /**< TIMER0 capture/compare channel 0 consumer. */ prsConsumerTIMER0_CC1 = offsetof(PRS_TypeDef, CONSUMER_TIMER0_CC1), /**< TIMER0 capture/compare channel 1 consumer. */ prsConsumerTIMER0_CC2 = offsetof(PRS_TypeDef, CONSUMER_TIMER0_CC2), /**< TIMER0 capture/compare channel 2 consumer. */ prsConsumerTIMER1_CC0 = offsetof(PRS_TypeDef, CONSUMER_TIMER1_CC0), /**< TIMER1 capture/compare channel 0 consumer. */ prsConsumerTIMER1_CC1 = offsetof(PRS_TypeDef, CONSUMER_TIMER1_CC1), /**< TIMER1 capture/compare channel 1 consumer. */ prsConsumerTIMER1_CC2 = offsetof(PRS_TypeDef, CONSUMER_TIMER1_CC2), /**< TIMER1 capture/compare channel 2 consumer. */ prsConsumerTIMER2_CC0 = offsetof(PRS_TypeDef, CONSUMER_TIMER2_CC0), /**< TIMER2 capture/compare channel 0 consumer. */ prsConsumerTIMER2_CC1 = offsetof(PRS_TypeDef, CONSUMER_TIMER2_CC1), /**< TIMER2 capture/compare channel 1 consumer. */ prsConsumerTIMER2_CC2 = offsetof(PRS_TypeDef, CONSUMER_TIMER2_CC2), /**< TIMER2 capture/compare channel 2 consumer. */ prsConsumerTIMER3_CC0 = offsetof(PRS_TypeDef, CONSUMER_TIMER3_CC0), /**< TIMER3 capture/compare channel 0 consumer. */ prsConsumerTIMER3_CC1 = offsetof(PRS_TypeDef, CONSUMER_TIMER3_CC1), /**< TIMER3 capture/compare channel 1 consumer. */ prsConsumerTIMER3_CC2 = offsetof(PRS_TypeDef, CONSUMER_TIMER3_CC2), /**< TIMER3 capture/compare channel 2 consumer. */ prsConsumerUSART0_CLK = offsetof(PRS_TypeDef, CONSUMER_USART0_CLK), /**< USART0 clock consumer. */ prsConsumerUSART0_IR = offsetof(PRS_TypeDef, CONSUMER_USART0_IR), /**< USART0 IR consumer. */ prsConsumerUSART0_RX = offsetof(PRS_TypeDef, CONSUMER_USART0_RX), /**< USART0 rx consumer. */ prsConsumerUSART0_TRIGGER = offsetof(PRS_TypeDef, CONSUMER_USART0_TRIGGER), /**< USART0 trigger consumer. */ prsConsumerUSART1_CLK = offsetof(PRS_TypeDef, CONSUMER_USART1_CLK), /**< USART1 clock consumer. */ prsConsumerUSART1_IR = offsetof(PRS_TypeDef, CONSUMER_USART1_IR), /**< USART1 IR consumer. */ prsConsumerUSART1_RX = offsetof(PRS_TypeDef, CONSUMER_USART1_RX), /**< USART1 rx consumer. */ prsConsumerUSART1_TRIGGER = offsetof(PRS_TypeDef, CONSUMER_USART1_TRIGGER), /**< USART1 trigger consumer. */ #if USART_COUNT > 2 prsConsumerUSART2_CLK = offsetof(PRS_TypeDef, CONSUMER_USART2_CLK), /**< USART2 clock consumer. */ prsConsumerUSART2_IR = offsetof(PRS_TypeDef, CONSUMER_USART2_IR), /**< USART2 IR consumer. */ prsConsumerUSART2_RX = offsetof(PRS_TypeDef, CONSUMER_USART2_RX), /**< USART2 rx consumer. */ prsConsumerUSART2_TRIGGER = offsetof(PRS_TypeDef, CONSUMER_USART2_TRIGGER), /**< USART2 trigger consumer. */ #endif prsConsumerWDOG0_SRC0 = offsetof(PRS_TypeDef, CONSUMER_WDOG0_SRC0), /**< WDOG0 source 0 consumer. */ prsConsumerWDOG0_SRC1 = offsetof(PRS_TypeDef, CONSUMER_WDOG0_SRC1), /**< WDOG0 source 1 consumer. */ #if WDOG_COUNT > 1 prsConsumerWDOG1_SRC0 = offsetof(PRS_TypeDef, CONSUMER_WDOG1_SRC0), /**< WDOG1 source 0 consumer. */ prsConsumerWDOG1_SRC1 = offsetof(PRS_TypeDef, CONSUMER_WDOG1_SRC1), /**< WDOG1 source 1 consumer. */ #endif #if defined(EUART0) prsConsumerEUART0_RX = offsetof(PRS_TypeDef, CONSUMER_EUART0_RX), /**< EUART0 RX consumer. */ prsConsumerEUART0_TRIGGER = offsetof(PRS_TypeDef, CONSUMER_EUART0_TRIGGER), /**< EUART0 TRIGGER Consumer. */ #endif } PRS_Consumer_t; #endif /******************************************************************************* ***************************** PROTOTYPES ********************************** ******************************************************************************/ /***************************************************************************//** * @brief * Set level control bit for one or more channels. * * @details * The level value for a channel is XORed with both the pulse possibly issued * by PRS_PulseTrigger() and the PRS input signal selected for the channel(s). * * @cond DOXYDOC_S2_DEVICE * @note * Note that software level control is only available for asynchronous * channels on Series 2 devices. * @endcond * * @param[in] level * Level to use for channels indicated by @p mask. Use logical OR combination * of PRS_SWLEVEL_CHnLEVEL defines for channels to set high level, otherwise 0. * * @param[in] mask * Mask indicating which channels to set level for. Use logical OR combination * of PRS_SWLEVEL_CHnLEVEL defines. ******************************************************************************/ __STATIC_INLINE void PRS_LevelSet(uint32_t level, uint32_t mask) { #if defined(_PRS_SWLEVEL_MASK) PRS->SWLEVEL = (PRS->SWLEVEL & ~mask) | (level & mask); #else PRS->ASYNC_SWLEVEL = (PRS->ASYNC_SWLEVEL & ~mask) | (level & mask); #endif } /***************************************************************************//** * @brief * Get level control bit for all channels. * * @return * The current software level configuration. ******************************************************************************/ __STATIC_INLINE uint32_t PRS_LevelGet(void) { #if defined(_PRS_SWLEVEL_MASK) return PRS->SWLEVEL; #else return PRS->ASYNC_SWLEVEL; #endif } #if defined(_PRS_ASYNC_PEEK_MASK) || defined(_PRS_PEEK_MASK) /***************************************************************************//** * @brief * Get the PRS channel values for all channels. * * @param[in] type * PRS channel type. This can be either @ref prsTypeAsync or * @ref prsTypeSync. * * @return * The current PRS channel output values for all channels as a bitset. ******************************************************************************/ __STATIC_INLINE uint32_t PRS_Values(PRS_ChType_t type) { #if defined(_PRS_ASYNC_PEEK_MASK) if (type == prsTypeAsync) { return PRS->ASYNC_PEEK; } else { return PRS->SYNC_PEEK; } #else (void) type; return PRS->PEEK; #endif } /***************************************************************************//** * @brief * Get the PRS channel value for a single channel. * * @param[in] ch * PRS channel number. * * @param[in] type * PRS channel type. This can be either @ref prsTypeAsync or * @ref prsTypeSync. * * @return * The current PRS channel output value. This is either 0 or 1. ******************************************************************************/ __STATIC_INLINE bool PRS_ChannelValue(unsigned int ch, PRS_ChType_t type) { return (PRS_Values(type) >> ch) & 0x1U; } #endif /***************************************************************************//** * @brief * Trigger a high pulse (one HFPERCLK) for one or more channels. * * @details * Setting a bit for a channel causes the bit in the register to remain high * for one HFPERCLK cycle. Pulse is XORed with both the corresponding bit * in PRS SWLEVEL register and the PRS input signal selected for the * channel(s). * * @param[in] channels * Logical ORed combination of channels to trigger a pulse for. Use * PRS_SWPULSE_CHnPULSE defines. ******************************************************************************/ __STATIC_INLINE void PRS_PulseTrigger(uint32_t channels) { #if defined(_PRS_SWPULSE_MASK) PRS->SWPULSE = channels & _PRS_SWPULSE_MASK; #else PRS->ASYNC_SWPULSE = channels & _PRS_ASYNC_SWPULSE_MASK; #endif } /***************************************************************************//** * @brief * Set the PRS channel level for one asynchronous PRS channel. * * @param[in] ch * PRS channel number. * * @param[in] level * true to set the level high (1) and false to set the level low (0). ******************************************************************************/ __STATIC_INLINE void PRS_ChannelLevelSet(unsigned int ch, bool level) { PRS_LevelSet(level << ch, 0x1U << ch); } /***************************************************************************//** * @brief * Trigger a pulse on one PRS channel. * * @param[in] ch * PRS channel number. ******************************************************************************/ __STATIC_INLINE void PRS_ChannelPulse(unsigned int ch) { PRS_PulseTrigger(0x1U << ch); } void PRS_SourceSignalSet(unsigned int ch, uint32_t source, uint32_t signal, PRS_Edge_TypeDef edge); #if defined(PRS_ASYNC_SUPPORTED) void PRS_SourceAsyncSignalSet(unsigned int ch, uint32_t source, uint32_t signal); #endif #if defined(_PRS_ROUTELOC0_MASK) || (_PRS_ROUTE_MASK) void PRS_GpioOutputLocation(unsigned int ch, unsigned int location); #endif int PRS_GetFreeChannel(PRS_ChType_t type); void PRS_Reset(void); void PRS_ConnectSignal(unsigned int ch, PRS_ChType_t type, PRS_Signal_t signal); #if defined(_SILICON_LABS_32B_SERIES_2) void PRS_ConnectConsumer(unsigned int ch, PRS_ChType_t type, PRS_Consumer_t consumer); void PRS_PinOutput(unsigned int ch, PRS_ChType_t type, GPIO_Port_TypeDef port, uint8_t pin); void PRS_Combine(unsigned int chA, unsigned int chB, PRS_Logic_t logic); #endif /** @} (end addtogroup PRS) */ /** @} (end addtogroup emlib) */ #ifdef __cplusplus } #endif #endif /* defined(PRS_COUNT) && (PRS_COUNT > 0) */ #endif /* EM_PRS_H */
mbedmicro/mbed
targets/TARGET_Silicon_Labs/TARGET_EFM32/emlib/inc/em_prs.h
C
apache-2.0
22,065
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2000 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef FormAssociatedElement_h #define FormAssociatedElement_h #include "core/CoreExport.h" #include "platform/heap/Handle.h" #include "wtf/WeakPtr.h" #include "wtf/text/WTFString.h" namespace blink { class ContainerNode; class Document; class FormAttributeTargetObserver; class FormDataList; class HTMLElement; class HTMLFormElement; class Node; class ValidityState; class CORE_EXPORT FormAssociatedElement : public WillBeGarbageCollectedMixin { public: virtual ~FormAssociatedElement(); #if !ENABLE(OILPAN) void ref() { refFormAssociatedElement(); } void deref() { derefFormAssociatedElement(); } #endif static HTMLFormElement* findAssociatedForm(const HTMLElement*); HTMLFormElement* form() const { return m_form.get(); } ValidityState* validity(); virtual bool isFormControlElement() const = 0; virtual bool isFormControlElementWithState() const; virtual bool isEnumeratable() const = 0; virtual bool isLabelElement() const { return false; } // Returns the 'name' attribute value. If this element has no name // attribute, it returns an empty string instead of null string. // Note that the 'name' IDL attribute doesn't use this function. virtual const AtomicString& name() const; // Override in derived classes to get the encoded name=value pair for submitting. // Return true for a successful control (see HTML4-17.13.2). virtual bool appendFormData(FormDataList&, bool) { return false; } void resetFormOwner(); void formRemovedFromTree(const Node& formRoot); // ValidityState attribute implementations bool customError() const; // Override functions for patterMismatch, rangeOverflow, rangerUnderflow, // stepMismatch, tooLong, tooShort and valueMissing must call willValidate method. virtual bool hasBadInput() const; virtual bool patternMismatch() const; virtual bool rangeOverflow() const; virtual bool rangeUnderflow() const; virtual bool stepMismatch() const; virtual bool tooLong() const; virtual bool tooShort() const; virtual bool typeMismatch() const; virtual bool valueMissing() const; virtual String validationMessage() const; bool valid() const; virtual void setCustomValidity(const String&); void formAttributeTargetChanged(); typedef WillBeHeapVector<RawPtrWillBeMember<FormAssociatedElement>> List; DECLARE_VIRTUAL_TRACE(); protected: FormAssociatedElement(); void insertedInto(ContainerNode*); void removedFrom(ContainerNode*); void didMoveToNewDocument(Document& oldDocument); // FIXME: Remove usage of setForm. resetFormOwner should be enough, and // setForm is confusing. void setForm(HTMLFormElement*); void associateByParser(HTMLFormElement*); void formAttributeChanged(); // If you add an override of willChangeForm() or didChangeForm() to a class // derived from this one, you will need to add a call to setForm(0) to the // destructor of that class. virtual void willChangeForm(); virtual void didChangeForm(); String customValidationMessage() const; private: #if !ENABLE(OILPAN) virtual void refFormAssociatedElement() = 0; virtual void derefFormAssociatedElement() = 0; #endif void setFormAttributeTargetObserver(PassOwnPtrWillBeRawPtr<FormAttributeTargetObserver>); void resetFormAttributeTargetObserver(); OwnPtrWillBeMember<FormAttributeTargetObserver> m_formAttributeTargetObserver; #if ENABLE(OILPAN) Member<HTMLFormElement> m_form; #else WeakPtr<HTMLFormElement> m_form; #endif OwnPtrWillBeMember<ValidityState> m_validityState; String m_customValidationMessage; // Non-Oilpan: Even if m_formWasSetByParser is true, m_form can be null // because parentNode is not a strong reference and |this| and m_form don't // die together. // Oilpan: If m_formWasSetByParser is true, m_form is always non-null. bool m_formWasSetByParser; }; HTMLElement* toHTMLElement(FormAssociatedElement*); HTMLElement& toHTMLElement(FormAssociatedElement&); const HTMLElement* toHTMLElement(const FormAssociatedElement*); const HTMLElement& toHTMLElement(const FormAssociatedElement&); } // namespace #endif // FormAssociatedElement_h
weolar/miniblink49
third_party/WebKit/Source/core/html/FormAssociatedElement.h
C
apache-2.0
5,279
# PnP Unit Test report for OnPremCred on Monday, July 6, 2015 # This page is showing the results of the PnP unit test run. ## Test configuration ## This report contains the unit test results from the following run: Parameter | Value ----------|------ PnP Unit Test configuration | OnPremCred Test run date | Monday, July 6, 2015 Test run time | 9:00 PM PnP branch | dev Visual Studio build configuration | debug15 ## Test summary ## During this test run 239 tests have been executed with following outcome: Parameter | Value ----------|------ Executed tests | 239 Elapsed time | 0h 17m 39s Passed tests | 215 Failed tests | **7** Skipped tests | 17 Was canceled | False Was aborted | False Error | ## Test run details ## ### Failed tests ### <table> <tr> <td><b>Test name</b></td> <td><b>Test outcome</b></td> <td><b>Duration</b></td> <td><b>Message</b></td> </tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectListInstanceTests.CanProvisionObjects</td><td>Failed</td><td>0h 0m 1s</td><td>Assert.IsTrue failed. </td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectListInstanceTests.CanCreateEntities</td><td>Failed</td><td>0h 0m 4s</td><td>Test method OfficeDevPnP.Core.Tests.Framework.ObjectHandlers.ObjectListInstanceTests.CanCreateEntities threw exception: System.NotSupportedException: Specified method is not supported.</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeToXml</td><td>Failed</td><td>0h 0m 6s</td><td>Test method OfficeDevPnP.Core.Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeToXml threw exception: System.NotSupportedException: Specified method is not supported.</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectWithJsonFormatter</td><td>Failed</td><td>0h 0m 0s</td><td>Test method OfficeDevPnP.Core.Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectWithJsonFormatter threw exception: Newtonsoft.Json.JsonSerializationException: XmlNodeConverter can only convert JSON that begins with an object.</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanHandleDomainObjectWithJsonFormatter</td><td>Failed</td><td>0h 0m 0s</td><td>Test method OfficeDevPnP.Core.Tests.Framework.ProvisioningTemplates.DomainModelTests.CanHandleDomainObjectWithJsonFormatter threw exception: Newtonsoft.Json.JsonSerializationException: XmlNodeConverter can only convert JSON that begins with an object.</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.GetRemoteTemplateTest</td><td>Failed</td><td>0h 0m 6s</td><td>Test method OfficeDevPnP.Core.Tests.Framework.ProvisioningTemplates.DomainModelTests.GetRemoteTemplateTest threw exception: System.NotSupportedException: Specified method is not supported.</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetProvisioningTemplateTest</td><td>Failed</td><td>0h 0m 7s</td><td>Test method Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetProvisioningTemplateTest threw exception: System.NotSupportedException: Specified method is not supported.</td></tr> </table> ### Skipped tests ### <table> <tr> <td><b>Test name</b></td> <td><b>Test outcome</b></td> <td><b>Duration</b></td> <td><b>Message</b></td> </tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFile1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFile2Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFiles1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFiles2Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFileBytes1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorGetFileBytes2Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorSaveStream1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorSaveStream2Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorSaveStream3Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorDelete1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorAzureTests.AzureConnectorDelete2Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Providers.BaseTemplateTests.DumpBaseTemplates</td><td>Skipped</td><td>0h 0m 0s</td><td></td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLAzureStorageGetTemplatesTest</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLAzureStorageGetTemplate1Test</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLAzureStorageGetTemplate2SecureTest</td><td>Skipped</td><td>0h 0m 0s</td><td>Assert.Inconclusive failed. No Azure Storage Key defined in App.Config, so can't test</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.InstallSolutionTest</td><td>Skipped</td><td>0h 0m 0s</td><td></td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.UninstallSolutionTest</td><td>Skipped</td><td>0h 0m 0s</td><td></td></tr> </table> ### Passed tests ### <table> <tr> <td><b>Test name</b></td> <td><b>Test outcome</b></td> <td><b>Duration</b></td> </tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.CanUploadHtmlPageLayoutAndConvertItToAspxVersionTest</td><td>Passed</td><td>0h 1m 16s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.CanUploadPageLayoutTest</td><td>Passed</td><td>0h 0m 43s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.CanUploadPageLayoutWithPathTest</td><td>Passed</td><td>0h 0m 34s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.AllowAllPageLayoutsTest</td><td>Passed</td><td>0h 0m 42s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.DeployThemeAndCreateComposedLookTest</td><td>Passed</td><td>0h 0m 41s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.ComposedLookExistsTest</td><td>Passed</td><td>0h 0m 40s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.GetCurrentComposedLookTest</td><td>Passed</td><td>0h 0m 50s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.CreateComposedLookShouldWorkTest</td><td>Passed</td><td>0h 0m 40s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.CreateComposedLookByNameShouldWorkTest</td><td>Passed</td><td>0h 0m 40s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.SetComposedLookInheritsTest</td><td>Passed</td><td>0h 1m 1s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.SetComposedLookResetInheritanceTest</td><td>Passed</td><td>0h 1m 18s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.SeattleMasterPageIsUnchangedTest</td><td>Passed</td><td>0h 0m 40s</td></tr> <tr><td>Tests.AppModelExtensions.BrandingExtensionsTests.IsSubsiteTest</td><td>Passed</td><td>0h 0m 40s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.ActivateSiteFeatureTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.ActivateWebFeatureTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.DeactivateSiteFeatureTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.DeactivateWebFeatureTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.IsSiteFeatureActiveTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FeatureExtensionsTests.IsWebFeatureActiveTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CreateFieldTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CanAddContentTypeToListByName</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CanRemoveContentTypeFromListByName</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CanRemoveContentTypeFromListById</td><td>Passed</td><td>0h 0m 5s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CreateExistingFieldTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.GetContentTypeByIdTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.RemoveFieldByInternalNameThrowsOnNoMatchTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CreateFieldFromXmlTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByNameTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByIdTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByNameInSubWebTest</td><td>Passed</td><td>0h 0m 9s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByIdInSubWebTest</td><td>Passed</td><td>0h 0m 8s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByNameSearchInSiteHierarchyTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ContentTypeExistsByIdSearchInSiteHierarchyTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.AddFieldToContentTypeTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.AddFieldToContentTypeMakeRequiredTest</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.SetDefaultContentTypeToListTest</td><td>Passed</td><td>0h 0m 5s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.ReorderContentTypesTest</td><td>Passed</td><td>0h 0m 6s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.FieldAndContentTypeExtensionsTests.CreateContentTypeByXmlTest</td><td>Passed</td><td>0h 0m 5s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsLinkToWebTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsLinkToSiteTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsLinkIEnumerableToWebTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsLinkIEnumerableToSiteTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.DeleteJsLinkFromWebTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.DeleteJsLinkFromSiteTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsBlockToWebTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.JavaScriptExtensionsTests.AddJsBlockToSiteTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.ListExtensionsTests.CreateListTest</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.ListExtensionsTests.SetDefaultColumnValuesTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.ListRatingExtensionTest.EnableRatingExperienceTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.ListRatingExtensionTest.EnableLikesExperienceTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Tests.AppModelExtensions.SearchExtensionsTests.SetSiteCollectionSearchCenterUrlTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.GetAdministratorsTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddAdministratorsTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddGroupTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.GroupExistsTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddPermissionLevelToGroupTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddPermissionLevelByRoleDefToGroupTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddPermissionLevelToUserTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddPermissionLevelToUserTestByRoleDefTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.SecurityExtensionsTests.AddReaderAccessToEveryoneTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.StructuralNavigationExtensionsTests.GetNavigationSettingsTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.StructuralNavigationExtensionsTests.UpdateNavigationSettingsTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.StructuralNavigationExtensionsTests.UpdateNavigationSettings2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.CreateTaxonomyFieldTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.CreateTaxonomyFieldMultiValueTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.SetTaxonomyFieldValueTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.CreateTaxonomyFieldLinkedToTermSetTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.CreateTaxonomyFieldLinkedToTermTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTaxonomySessionTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetDefaultKeywordsTermStoreTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetDefaultSiteCollectionTermStoreTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTermSetsByNameTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTermGroupByNameTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTermGroupByIdTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTermByNameTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.GetTaxonomyItemByPathTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.AddTermToTermsetTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.AddTermToTermsetWithTermIdTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ImportTermsTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ImportTermsToTermStoreTest</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ImportTermSetSampleShouldCreateSetTest</td><td>Passed</td><td>0h 0m 5s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ImportTermSetShouldUpdateSetTest</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ImportTermSetShouldUpdateByGuidTest</td><td>Passed</td><td>0h 0m 3s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ExportTermSetTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ExportTermSetFromTermstoreTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.TaxonomyExtensionsTests.ExportAllTermsTest</td><td>Passed</td><td>0h 0m 41s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.CheckOutFileTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.CheckInFileTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.UploadFileTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.UploadFileWebDavTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.VerifyIfUploadRequiredTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.SetFilePropertiesTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.GetFileTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.EnsureSiteFolderTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.EnsureLibraryFolderTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.FileFolderExtensionsTests.EnsureLibraryFolderRecursiveTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.AppModelExtensions.Tenant15ExtensionsTests.CreateDeleteSiteCollectionTest</td><td>Passed</td><td>0h 0m 36s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.AddTopNavigationNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.AddQuickLaunchNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.AddSearchNavigationNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.DeleteTopNavigationNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.DeleteQuickLaunchNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.DeleteSearchNavigationNodeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.NavigationExtensionsTests.DeleteAllQuickLaunchNodesTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFile1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFile2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFile3Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFiles1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFiles2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorGetFileBytes1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorSaveStream1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorSaveStream2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorSaveStream3Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorDelete1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorFileSystemTests.FileConnectorDelete2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFile1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFile2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFiles1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFiles2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFiles3Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFileBytes1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorGetFileBytes2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorSaveStream1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorSaveStream2Test</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorSaveStream3Test</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorDelete1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Connectors.ConnectorSharePointTests.SharePointConnectorDelete2Test</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ExtensibilityCallOut.ExtensibilityTests.CanProviderCallOut</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ExtensibilityCallOut.ExtensibilityTests.ProviderCallOutThrowsException</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ExtensibilityCallOut.ExtensibilityTests.ProviderAssemblyMissingThrowsAgrumentException</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ExtensibilityCallOut.ExtensibilityTests.ProviderTypeNameMissingThrowsAgrumentException</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ExtensibilityCallOut.ExtensibilityTests.ProviderClientCtxIsNullThrowsAgrumentNullException</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectComposedLookTests.CanCreateComposedLooks</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectTermGroupsTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectPagesTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectPagesTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectSiteSecurityTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectSiteSecurityTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectPropertyBagEntryTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectPropertyBagEntryTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFilesTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFilesTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFeaturesTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFeaturesTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectCustomActionsTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectCustomActionsTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFieldTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectFieldTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectContentTypeTests.CanProvisionObjects</td><td>Passed</td><td>0h 0m 2s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.ObjectContentTypeTests.CanCreateEntities</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.Framework.ObjectHandlers.TokenParserTests.ParseTests</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.BaseTemplateTests.GetBaseTemplateForCurrentSiteTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLFileSystemGetTemplatesTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLFileSystemGetTemplate1Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLFileSystemGetTemplate2Test</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLFileSystemConvertTemplatesFromV201503toV201505</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.ResolveSchemaFormatV201503</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.ResolveSchemaFormatV201505</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLResolveValidXInclude</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.Providers.XMLProvidersTests.XMLResolveInvalidXInclude</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanDeserializeXMLToDomainObject1</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXML1</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXMLStream1</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanDeserializeXMLToDomainObject2</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXML2</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetTemplateNameandVersion</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetPropertyBagEntries</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetOwners</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetAdministrators</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetMembers</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetVistors</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetFeatures</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanGetCustomActions</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeToJSon</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.ValidateFullProvisioningSchema5</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.ValidateSharePointProvisioningSchema6</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanDeserializeXMLToDomainObject5</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanDeserializeXMLToDomainObject6</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXML6</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXML5ByIdentifier</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.CanSerializeDomainObjectToXML5ByFileLink</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Framework.ProvisioningTemplates.DomainModelTests.AreTemplatesEqual</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Utilities.Tests.JsonUtilityTests.SerializeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Utilities.Tests.JsonUtilityTests.DeserializeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Utilities.Tests.JsonUtilityTests.DeserializeListTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Utilities.Tests.JsonUtilityTests.DeserializeListIsNotFixedSizeTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Utilities.Tests.JsonUtilityTests.DeserializeListNoDataStillWorksTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Utilities.EncryptionUtilityTests.ToSecureStringTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Utilities.EncryptionUtilityTests.ToInSecureStringTest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Utilities.EncryptionUtilityTests.EncryptStringWithDPAPITest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.Utilities.EncryptionUtilityTests.DecryptStringWithDPAPITest</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.UrlUtilityTests.ContainsInvalidCharsReturnsFalseForValidString</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.UrlUtilityTests.ContainsInvalidUrlCharsReturnsTrueForInvalidString</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.UrlUtilityTests.StripInvalidUrlCharsReturnsStrippedString</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Tests.AppModelExtensions.UrlUtilityTests.ReplaceInvalidUrlCharsReturnsStrippedString</td><td>Passed</td><td>0h 0m 0s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.SetPropertyBagValueIntTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.SetPropertyBagValueStringTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.SetPropertyBagValueMultipleRunsTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.RemovePropertyBagValueTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetPropertyBagValueIntTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetPropertyBagValueStringTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.PropertyBagContainsKeyTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetIndexedPropertyBagKeysTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.AddIndexedPropertyBagKeyTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.RemoveIndexedPropertyBagKeyTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.GetAppInstancesTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Microsoft.SharePoint.Client.Tests.WebExtensionsTests.RemoveAppInstanceByTitleTest</td><td>Passed</td><td>0h 0m 1s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CanAddLayoutToWikiPageTest</td><td>Passed</td><td>0h 0m 5s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CanAddHtmlToWikiPageTest</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.ProveThatWeCanAddHtmlToPageAfterChangingLayoutTest</td><td>Passed</td><td>0h 0m 4s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CanCreatePublishingPageTest</td><td>Passed</td><td>0h 0m 14s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.PublishingPageWithInvalidCharsIsCorrectlyCreatedTest</td><td>Passed</td><td>0h 0m 13s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CanCreatePublishedPublishingPageWhenModerationIsEnabledTest</td><td>Passed</td><td>0h 0m 14s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CanCreatePublishedPublishingPageWhenModerationIsDisabledTest</td><td>Passed</td><td>0h 0m 14s</td></tr> <tr><td>Tests.AppModelExtensions.PageExtensionsTests.CreatedPublishingPagesSetsTitleCorrectlyTest</td><td>Passed</td><td>0h 0m 15s</td></tr> </table>
baldswede/PnP
OfficeDevPnP.Core/UnitTestResults/PnPUnitTestResults-20150706-OnPremCred-635718204412088183.md
Markdown
apache-2.0
35,317
package dockerclient import ( "bytes" "crypto/tls" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "sync/atomic" "time" ) const ( APIVersion = "v1.15" ) var ( ErrNotFound = errors.New("Not found") defaultTimeout = 30 * time.Second ) type DockerClient struct { URL *url.URL HTTPClient *http.Client TLSConfig *tls.Config monitorEvents int32 } type Error struct { StatusCode int Status string msg string } func (e Error) Error() string { return fmt.Sprintf("%s: %s", e.Status, e.msg) } func NewDockerClient(daemonUrl string, tlsConfig *tls.Config) (*DockerClient, error) { return NewDockerClientTimeout(daemonUrl, tlsConfig, time.Duration(defaultTimeout)) } func NewDockerClientTimeout(daemonUrl string, tlsConfig *tls.Config, timeout time.Duration) (*DockerClient, error) { u, err := url.Parse(daemonUrl) if err != nil { return nil, err } if u.Scheme == "" || u.Scheme == "tcp" { if tlsConfig == nil { u.Scheme = "http" } else { u.Scheme = "https" } } httpClient := newHTTPClient(u, tlsConfig, timeout) return &DockerClient{u, httpClient, tlsConfig, 0}, nil } func (client *DockerClient) doRequest(method string, path string, body []byte, headers map[string]string) ([]byte, error) { b := bytes.NewBuffer(body) req, err := http.NewRequest(method, client.URL.String()+path, b) if err != nil { return nil, err } req.Header.Add("Content-Type", "application/json") if headers != nil { for header, value := range headers { req.Header.Add(header, value) } } resp, err := client.HTTPClient.Do(req) if err != nil { if !strings.Contains(err.Error(), "connection refused") && client.TLSConfig == nil { return nil, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err) } return nil, err } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, ErrNotFound } if resp.StatusCode >= 400 { return nil, Error{StatusCode: resp.StatusCode, Status: resp.Status, msg: string(data)} } return data, nil } func (client *DockerClient) Info() (*Info, error) { uri := fmt.Sprintf("/%s/info", APIVersion) data, err := client.doRequest("GET", uri, nil, nil) if err != nil { return nil, err } ret := &Info{} err = json.Unmarshal(data, &ret) if err != nil { return nil, err } return ret, nil } func (client *DockerClient) ListContainers(all bool, size bool, filters string) ([]Container, error) { argAll := 0 if all == true { argAll = 1 } showSize := 0 if size == true { showSize = 1 } uri := fmt.Sprintf("/%s/containers/json?all=%d&size=%d", APIVersion, argAll, showSize) if filters != "" { uri += "&filters=" + filters } data, err := client.doRequest("GET", uri, nil, nil) if err != nil { return nil, err } ret := []Container{} err = json.Unmarshal(data, &ret) if err != nil { return nil, err } return ret, nil } func (client *DockerClient) InspectContainer(id string) (*ContainerInfo, error) { uri := fmt.Sprintf("/%s/containers/%s/json", APIVersion, id) data, err := client.doRequest("GET", uri, nil, nil) if err != nil { return nil, err } info := &ContainerInfo{} err = json.Unmarshal(data, info) if err != nil { return nil, err } return info, nil } func (client *DockerClient) CreateContainer(config *ContainerConfig, name string) (string, error) { data, err := json.Marshal(config) if err != nil { return "", err } uri := fmt.Sprintf("/%s/containers/create", APIVersion) if name != "" { v := url.Values{} v.Set("name", name) uri = fmt.Sprintf("%s?%s", uri, v.Encode()) } data, err = client.doRequest("POST", uri, data, nil) if err != nil { return "", err } result := &RespContainersCreate{} err = json.Unmarshal(data, result) if err != nil { return "", err } return result.Id, nil } func (client *DockerClient) ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error) { v := url.Values{} v.Add("follow", strconv.FormatBool(options.Follow)) v.Add("stdout", strconv.FormatBool(options.Stdout)) v.Add("stderr", strconv.FormatBool(options.Stderr)) v.Add("timestamps", strconv.FormatBool(options.Timestamps)) if options.Tail > 0 { v.Add("tail", strconv.FormatInt(options.Tail, 10)) } uri := fmt.Sprintf("/%s/containers/%s/logs?%s", APIVersion, id, v.Encode()) req, err := http.NewRequest("GET", client.URL.String()+uri, nil) if err != nil { return nil, err } req.Header.Add("Content-Type", "application/json") resp, err := client.HTTPClient.Do(req) if err != nil { return nil, err } return resp.Body, nil } func (client *DockerClient) StartContainer(id string, config *HostConfig) error { data, err := json.Marshal(config) if err != nil { return err } uri := fmt.Sprintf("/%s/containers/%s/start", APIVersion, id) _, err = client.doRequest("POST", uri, data, nil) if err != nil { return err } return nil } func (client *DockerClient) StopContainer(id string, timeout int) error { uri := fmt.Sprintf("/%s/containers/%s/stop?t=%d", APIVersion, id, timeout) _, err := client.doRequest("POST", uri, nil, nil) if err != nil { return err } return nil } func (client *DockerClient) RestartContainer(id string, timeout int) error { uri := fmt.Sprintf("/%s/containers/%s/restart?t=%d", APIVersion, id, timeout) _, err := client.doRequest("POST", uri, nil, nil) if err != nil { return err } return nil } func (client *DockerClient) KillContainer(id, signal string) error { uri := fmt.Sprintf("/%s/containers/%s/kill?signal=%s", APIVersion, id, signal) _, err := client.doRequest("POST", uri, nil, nil) if err != nil { return err } return nil } func (client *DockerClient) StartMonitorEvents(cb Callback, ec chan error, args ...interface{}) { atomic.StoreInt32(&client.monitorEvents, 1) go client.getEvents(cb, ec, args...) } func (client *DockerClient) getEvents(cb Callback, ec chan error, args ...interface{}) { uri := fmt.Sprintf("%s/%s/events", client.URL.String(), APIVersion) resp, err := client.HTTPClient.Get(uri) if err != nil { ec <- err return } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) for atomic.LoadInt32(&client.monitorEvents) > 0 { var event *Event if err := dec.Decode(&event); err != nil { ec <- err return } cb(event, ec, args...) } } func (client *DockerClient) StopAllMonitorEvents() { atomic.StoreInt32(&client.monitorEvents, 0) } func (client *DockerClient) Version() (*Version, error) { uri := fmt.Sprintf("/%s/version", APIVersion) data, err := client.doRequest("GET", uri, nil, nil) if err != nil { return nil, err } version := &Version{} err = json.Unmarshal(data, version) if err != nil { return nil, err } return version, nil } func (client *DockerClient) PullImage(name string, auth *AuthConfig) error { v := url.Values{} v.Set("fromImage", name) uri := fmt.Sprintf("/%s/images/create?%s", APIVersion, v.Encode()) req, err := http.NewRequest("POST", client.URL.String()+uri, nil) if auth != nil { req.Header.Add("X-Registry-Auth", auth.encode()) } resp, err := client.HTTPClient.Do(req) if err != nil { return err } defer resp.Body.Close() var finalObj map[string]interface{} for decoder := json.NewDecoder(resp.Body); err == nil; err = decoder.Decode(&finalObj) { } if err != io.EOF { return err } if err, ok := finalObj["error"]; ok { return fmt.Errorf("%v", err) } return nil } func (client *DockerClient) RemoveContainer(id string, force, volumes bool) error { argForce := 0 argVolumes := 0 if force == true { argForce = 1 } if volumes == true { argVolumes = 1 } args := fmt.Sprintf("force=%d&v=%d", argForce, argVolumes) uri := fmt.Sprintf("/%s/containers/%s?%s", APIVersion, id, args) _, err := client.doRequest("DELETE", uri, nil, nil) return err } func (client *DockerClient) ListImages() ([]*Image, error) { uri := fmt.Sprintf("/%s/images/json", APIVersion) data, err := client.doRequest("GET", uri, nil, nil) if err != nil { return nil, err } var images []*Image if err := json.Unmarshal(data, &images); err != nil { return nil, err } return images, nil } func (client *DockerClient) RemoveImage(name string) error { uri := fmt.Sprintf("/%s/images/%s", APIVersion, name) _, err := client.doRequest("DELETE", uri, nil, nil) return err } func (client *DockerClient) PauseContainer(id string) error { uri := fmt.Sprintf("/%s/containers/%s/pause", APIVersion, id) _, err := client.doRequest("POST", uri, nil, nil) if err != nil { return err } return nil } func (client *DockerClient) UnpauseContainer(id string) error { uri := fmt.Sprintf("/%s/containers/%s/unpause", APIVersion, id) _, err := client.doRequest("POST", uri, nil, nil) if err != nil { return err } return nil } func (client *DockerClient) Exec(config *ExecConfig) (string, error) { data, err := json.Marshal(config) if err != nil { return "", err } uri := fmt.Sprintf("/containers/%s/exec", config.Container) resp, err := client.doRequest("POST", uri, data, nil) if err != nil { return "", err } var createExecResp struct { Id string } if err = json.Unmarshal(resp, &createExecResp); err != nil { return "", err } uri = fmt.Sprintf("/exec/%s/start", createExecResp.Id) resp, err = client.doRequest("POST", uri, data, nil) if err != nil { return "", err } return createExecResp.Id, nil }
iamjakob/shipyard
controller/Godeps/_workspace/src/github.com/samalba/dockerclient/dockerclient.go
GO
apache-2.0
9,453
package fakegit // import "github.com/docker/docker/internal/test/fakegit" import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "github.com/docker/docker/internal/test" "github.com/docker/docker/internal/test/fakecontext" "github.com/docker/docker/internal/test/fakestorage" "github.com/gotestyourself/gotestyourself/assert" ) type testingT interface { assert.TestingT logT skipT Fatal(args ...interface{}) Fatalf(string, ...interface{}) } type logT interface { Logf(string, ...interface{}) } type skipT interface { Skip(reason string) } type gitServer interface { URL() string Close() error } type localGitServer struct { *httptest.Server } func (r *localGitServer) Close() error { r.Server.Close() return nil } func (r *localGitServer) URL() string { return r.Server.URL } // FakeGit is a fake git server type FakeGit struct { root string server gitServer RepoURL string } // Close closes the server, implements Closer interface func (g *FakeGit) Close() { g.server.Close() os.RemoveAll(g.root) } // New create a fake git server that can be used for git related tests func New(c testingT, name string, files map[string]string, enforceLocalServer bool) *FakeGit { if ht, ok := c.(test.HelperT); ok { ht.Helper() } ctx := fakecontext.New(c, "", fakecontext.WithFiles(files)) defer ctx.Close() curdir, err := os.Getwd() if err != nil { c.Fatal(err) } defer os.Chdir(curdir) if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil { c.Fatalf("error trying to init repo: %s (%s)", err, output) } err = os.Chdir(ctx.Dir) if err != nil { c.Fatal(err) } if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil { c.Fatalf("error trying to set 'user.name': %s (%s)", err, output) } if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil { c.Fatalf("error trying to set 'user.email': %s (%s)", err, output) } if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil { c.Fatalf("error trying to add files to repo: %s (%s)", err, output) } if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil { c.Fatalf("error trying to commit to repo: %s (%s)", err, output) } root, err := ioutil.TempDir("", "docker-test-git-repo") if err != nil { c.Fatal(err) } repoPath := filepath.Join(root, name+".git") if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil { os.RemoveAll(root) c.Fatalf("error trying to clone --bare: %s (%s)", err, output) } err = os.Chdir(repoPath) if err != nil { os.RemoveAll(root) c.Fatal(err) } if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil { os.RemoveAll(root) c.Fatalf("error trying to git update-server-info: %s (%s)", err, output) } err = os.Chdir(curdir) if err != nil { os.RemoveAll(root) c.Fatal(err) } var server gitServer if !enforceLocalServer { // use fakeStorage server, which might be local or remote (at test daemon) server = fakestorage.New(c, root) } else { // always start a local http server on CLI test machine httpServer := httptest.NewServer(http.FileServer(http.Dir(root))) server = &localGitServer{httpServer} } return &FakeGit{ root: root, server: server, RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name), } }
anpingli/origin
vendor/github.com/docker/docker/internal/test/fakegit/fakegit.go
GO
apache-2.0
3,527
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.exhibitor.servlet; import com.netflix.exhibitor.core.Exhibitor; import com.netflix.exhibitor.core.rest.UIContext; import com.netflix.exhibitor.core.rest.jersey.JerseySupport; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Map; import java.util.Set; public class ExhibitorResourceConfig extends ResourceConfig { @SuppressWarnings("FieldCanBeLocal") private final Logger log = LoggerFactory.getLogger(getClass()); private final DefaultResourceConfig config; public ExhibitorResourceConfig(@Context ServletContext context) { DefaultResourceConfig localConfig; Exhibitor exhibitor = (Exhibitor)context.getAttribute(ExhibitorServletContextListener.class.getName()); if ( exhibitor != null ) { log.info("Adding Exhibitor Jersey resources"); localConfig = JerseySupport.newApplicationConfig(new UIContext(exhibitor)); } else { log.info("Using DefaultResourceConfig"); localConfig = new DefaultResourceConfig(); } config = localConfig; } @Override public Set<Class<?>> getClasses() { return config.getClasses(); } @Override public Set<Object> getSingletons() { return config.getSingletons(); } @Override public Map<String, MediaType> getMediaTypeMappings() { return config.getMediaTypeMappings(); } @Override public Map<String, String> getLanguageMappings() { return config.getLanguageMappings(); } @Override public Map<String, Object> getExplicitRootResources() { return config.getExplicitRootResources(); } @Override public Map<String, Boolean> getFeatures() { return config.getFeatures(); } @Override public boolean getFeature(String featureName) { return config.getFeature(featureName); } @Override public Map<String, Object> getProperties() { return config.getProperties(); } @Override public Object getProperty(String propertyName) { return config.getProperty(propertyName); } @Override public void validate() { config.validate(); } @Override public Set<Class<?>> getRootResourceClasses() { return config.getRootResourceClasses(); } @Override public Set<Class<?>> getProviderClasses() { return config.getProviderClasses(); } @Override public Set<Object> getRootResourceSingletons() { return config.getRootResourceSingletons(); } @Override public Set<Object> getProviderSingletons() { return config.getProviderSingletons(); } @Override public List getContainerRequestFilters() { return config.getContainerRequestFilters(); } @Override public List getContainerResponseFilters() { return config.getContainerResponseFilters(); } @Override public List getResourceFilterFactories() { return config.getResourceFilterFactories(); } @Override public void setPropertiesAndFeatures(Map<String, Object> entries) { config.setPropertiesAndFeatures(entries); } @Override public void add(Application app) { config.add(app); } @SuppressWarnings("CloneDoesntCallSuperClone") @Override public ResourceConfig clone() { return config.clone(); } }
wfxiang08/exhibitor
exhibitor-standalone/src/main/java/com/netflix/exhibitor/servlet/ExhibitorResourceConfig.java
Java
apache-2.0
4,452
#!/usr/bin/env python # Copyright 2015 Netflix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import getpass import os from flask_script.commands import ShowUrls, Clean from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from sleepypuppy.admin.admin.models import Administrator from sleepypuppy import app, db from js_strings import default_script, alert_box, console_log, default_without_screenshot, generic_collector manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app) @manager.command def create_db(): """ Creates a database with all of the tables defined in your Alchemy models """ db.create_all() @manager.command def drop_db(): """ Drops a database with all of the tables defined in your Alchemy models """ db.drop_all() @manager.command def create_login(login): """ Seed the database with an admin user. """ print 'creating admin user' if Administrator.query.filter_by(login=login).count(): print 'user already exists!' return # Check env for credentials (used by docker) docker_admin_pass = os.getenv('DOCKER_ADMIN_PASS', None) if docker_admin_pass: admin_user = Administrator(login=login, password=docker_admin_pass) else: # else, ask on stdin: while True: print "{}, enter your password!\n ".format(login) pw1 = getpass.getpass() pw2 = getpass.getpass(prompt="Confirm: ") if pw1 == pw2: admin_user = Administrator(login=login, password=pw1) break else: print 'passwords do not match!' db.session.add(admin_user) db.session.commit() print 'user: ' + login + ' created!' @manager.command def default_login(): """ Seed the database with some inital values """ existing_admin = Administrator.query.filter( Administrator.login == 'admin').first() if existing_admin: print "Admin account (admin) already exists, skipping." else: admin_user = Administrator(login='admin', password='admin') print 'user: ' + 'admin' + ' created!' db.session.add(admin_user) db.session.commit() return from collections import namedtuple DefaultPayload = namedtuple( 'DefaultPayload', ['payload', 'notes', 'snooze', 'run_once']) DEFAULT_PAYLOADS = [ DefaultPayload('<script src=$1></script>', None, False, False), DefaultPayload('</script><script src=$1>', None, False, False), DefaultPayload( '&lt;script src=$1&gt;&lt;/script&gt;', None, False, False), DefaultPayload('&lt;/script&gt;&lt;script src=$1&gt;', None, False, False), DefaultPayload('''" onload="var s=document.createElement('script');s.src='$1';document.getElementsByTagName('head')[0].appendChild(s);" garbage="''', None, False, False), # noqa DefaultPayload("""'"><img src=x onerror="var s=document.createElement('script');s.src='$1';document.getElementsByTagName('head')[0].appendChild(s);">""", None, False, False), # noqa DefaultPayload("""Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 '"><img src=x onerror="var s=document.createElement('script');s.src='$1';document.getElementsByTagName('head')[0].appendChild(s);">""", None, False, False) # noqa ] DefaultPuppyscript = namedtuple('DefaultPuppyscript', ['name', 'code', 'notes']) DEFAULT_JAVASCRIPTS = [ DefaultPuppyscript('Default', default_script, 'Default collects metadata for capture table including a screenshot'), DefaultPuppyscript('Default Without Screenshot', default_without_screenshot, 'Generating a screenshot can be CPU intensive and even in some cases cause browser instability, so for some assessments this may be a better option. '), DefaultPuppyscript( 'Alert Box', alert_box, 'Generates an alert box for notification purposes'), DefaultPuppyscript( 'Console Log', console_log, 'Log a message in the browser\'s console'), DefaultPuppyscript('Generic Collector: IP Address', generic_collector, 'Example showing how you can create generic JavaScripts for collecting any text data you choose. In this example we use ajax to determine IP address and record the value. ') ] @manager.command def create_bootstrap_assessment(name="General", add_default_payloads=True): """ Creates an assessment and attaches a few default payloads. """ from sleepypuppy.admin.assessment.models import Assessment from sleepypuppy.admin.payload.models import Payload from sleepypuppy.admin.puppyscript.models import Puppyscript assessment = Assessment.query.filter(Assessment.name == name).first() if assessment: print("Assessment with name", name, "already exists, exiting.") return else: assessment = Assessment( name=name, access_log_enabled=False, snooze=False, run_once=False) # add assessment db.session.add(assessment) db.session.commit() existing_payload = Payload.query.filter(Payload.id == 1).first() if existing_payload: print("Payloads already exists, exiting.") else: if add_default_payloads: for payload in DEFAULT_PAYLOADS: payload = Payload( payload=payload.payload, notes=payload.notes, ordering=u'1' ) db.session.add(payload) db.session.commit() existing_puppyscript = Puppyscript.query.filter(Puppyscript.id == 1).first() if existing_puppyscript: print("Puppyscripts already exists, exiting.") else: for puppyscript in DEFAULT_JAVASCRIPTS: puppyscript = Puppyscript( name=puppyscript.name, code=puppyscript.code, notes=puppyscript.notes ) db.session.add(puppyscript) db.session.commit() @manager.command def setup_sleepy_puppy(): create_db() create_bootstrap_assessment() create_login('admin') @manager.command def list_routes(): func_list = {} for rule in app.url_map.iter_rules(): if rule.endpoint != 'static': func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__ from pprint import pprint pprint(func_list) if __name__ == "__main__": manager.add_command("clean", Clean()) manager.add_command("show_urls", ShowUrls()) manager.run()
Netflix/sleepy-puppy
manage.py
Python
apache-2.0
7,364
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "file_exists.h" #include <sys/stat.h> IGL_INLINE bool igl::file_exists(const std::string filename) { struct stat status; return (stat(filename.c_str(),&status)==0); }
ygling2008/direct_edge_imu
thirdparty/igl/file_exists.cpp
C++
apache-2.0
528
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This class is designed to get accurate profiles for programs #include "tensorflow/core/platform/profile_utils/cpu_utils.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/profile_utils/clock_cycle_profiler.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace profile_utils { static constexpr bool DBG = false; class CpuUtilsTest : public ::testing::Test { protected: void SetUp() override { CpuUtils::EnableClockCycleProfiling(true); } }; TEST_F(CpuUtilsTest, SetUpTestCase) {} TEST_F(CpuUtilsTest, TearDownTestCase) {} TEST_F(CpuUtilsTest, CheckGetCurrentClockCycle) { static constexpr int LOOP_COUNT = 10; const uint64 start_clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GT(start_clock_count, 0); uint64 prev_clock_count = start_clock_count; for (int i = 0; i < LOOP_COUNT; ++i) { const uint64 clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GE(clock_count, prev_clock_count); prev_clock_count = clock_count; } const uint64 end_clock_count = CpuUtils::GetCurrentClockCycle(); if (DBG) { LOG(INFO) << "start clock = " << start_clock_count; LOG(INFO) << "end clock = " << end_clock_count; LOG(INFO) << "average clock = " << ((end_clock_count - start_clock_count) / LOOP_COUNT); } } TEST_F(CpuUtilsTest, CheckCycleCounterFrequency) { #if defined(__powerpc__) || defined(__ppc__) && ( __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) const uint64 cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, unsigned(CpuUtils::INVALID_FREQUENCY)); #else const int64 cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, CpuUtils::INVALID_FREQUENCY); #endif if (DBG) { LOG(INFO) << "Cpu frequency = " << cpu_frequency; } } TEST_F(CpuUtilsTest, CheckMicroSecPerClock) { const double micro_sec_per_clock = CpuUtils::GetMicroSecPerClock(); CHECK_GT(micro_sec_per_clock, 0.0); if (DBG) { LOG(INFO) << "Micro sec per clock = " << micro_sec_per_clock; } } TEST_F(CpuUtilsTest, SimpleUsageOfClockCycleProfiler) { static constexpr int LOOP_COUNT = 10; ClockCycleProfiler prof; for (int i = 0; i < LOOP_COUNT; ++i) { prof.Start(); prof.Stop(); } EXPECT_EQ(LOOP_COUNT, static_cast<int>(prof.GetCount() + 0.5)); if (DBG) { prof.DumpStatistics("CpuUtilsTest"); } } } // namespace profile_utils } // namespace tensorflow
npuichigo/ttsflow
third_party/tensorflow/tensorflow/core/platform/profile_utils/cpu_utils_test.cc
C++
apache-2.0
3,195
package build import ( "testing" "time" kapi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" buildapi "github.com/openshift/origin/pkg/build/api" ) func TestBuildStrategy(t *testing.T) { ctx := kapi.NewDefaultContext() if !Strategy.NamespaceScoped() { t.Errorf("Build is namespace scoped") } if Strategy.AllowCreateOnUpdate() { t.Errorf("Build should not allow create on update") } build := &buildapi.Build{ ObjectMeta: kapi.ObjectMeta{Name: "buildid", Namespace: "default"}, Spec: buildapi.BuildSpec{ Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://github.com/my/repository", }, ContextDir: "context", }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{}, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "repository/data", }, }, }, } Strategy.PrepareForCreate(build) if len(build.Status.Phase) == 0 || build.Status.Phase != buildapi.BuildPhaseNew { t.Errorf("Build phase is not New") } errs := Strategy.Validate(ctx, build) if len(errs) != 0 { t.Errorf("Unexpected error validating %v", errs) } build.ResourceVersion = "foo" errs = Strategy.ValidateUpdate(ctx, build, build) if len(errs) != 0 { t.Errorf("Unexpected error validating %v", errs) } invalidBuild := &buildapi.Build{} errs = Strategy.Validate(ctx, invalidBuild) if len(errs) == 0 { t.Errorf("Expected error validating") } } func TestBuildDecorator(t *testing.T) { build := &buildapi.Build{ ObjectMeta: kapi.ObjectMeta{Name: "buildid", Namespace: "default"}, Spec: buildapi.BuildSpec{ Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://github.com/my/repository", }, ContextDir: "context", }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{}, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "repository/data", }, }, }, Status: buildapi.BuildStatus{ Phase: buildapi.BuildPhaseNew, }, } now := unversioned.Now() startTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute)) build.Status.StartTimestamp = &startTime err := Decorator(build) if err != nil { t.Errorf("Unexpected error decorating build") } if build.Status.Duration <= 0 { t.Errorf("Build duration should be greater than zero") } }
rhuss/gofabric8
vendor/github.com/openshift/origin/pkg/build/registry/build/strategy_test.go
GO
apache-2.0
2,459
/* * Copyright (c) 2018, NXP Semiconductors, Inc. * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #include "fsl_tempmon.h" /******************************************************************************* * Definitions ******************************************************************************/ /* Component ID definition, used by tools. */ #ifndef FSL_COMPONENT_ID #define FSL_COMPONENT_ID "platform.drivers.tempmon" #endif /*! @brief TEMPMON calibration data mask. */ #define TEMPMON_HOTTEMPMASK 0xFFU #define TEMPMON_HOTTEMPSHIFT 0x00U #define TEMPMON_HOTCOUNTMASK 0xFFF00U #define TEMPMON_HOTCOUNTSHIFT 0X08U #define TEMPMON_ROOMCOUNTMASK 0xFFF00000U #define TEMPMON_ROOMCOUNTSHIFT 0x14U /*! @brief the room temperature. */ #define TEMPMON_ROOMTEMP 25.0 /******************************************************************************* * Prototypes ******************************************************************************/ /******************************************************************************* * Variables ******************************************************************************/ static uint32_t s_hotTemp; /*!< The value of TEMPMON_TEMPSENSE0[TEMP_VALUE] at room temperature .*/ static uint32_t s_hotCount; /*!< The value of TEMPMON_TEMPSENSE0[TEMP_VALUE] at the hot temperature.*/ static float s_hotT_ROOM; /*!< The value of s_hotTemp minus room temperature(25¡æ).*/ static uint32_t s_roomC_hotC; /*!< The value of s_roomCount minus s_hotCount.*/ /******************************************************************************* * Code ******************************************************************************/ /*! * brief Initializes the TEMPMON module. * * param base TEMPMON base pointer * param config Pointer to configuration structure. */ void TEMPMON_Init(TEMPMON_Type *base, const tempmon_config_t *config) { assert(NULL != config); uint32_t calibrationData; uint32_t roomCount; /* Power on the temperature sensor*/ base->TEMPSENSE0 &= ~TEMPMON_TEMPSENSE0_POWER_DOWN_MASK; /* Set temperature monitor frequency */ base->TEMPSENSE1 = TEMPMON_TEMPSENSE1_MEASURE_FREQ(config->frequency); /* ready to read calibration data */ calibrationData = OCOTP->ANA1; s_hotTemp = (uint32_t)(calibrationData & TEMPMON_HOTTEMPMASK) >> TEMPMON_HOTTEMPSHIFT; s_hotCount = (uint32_t)(calibrationData & TEMPMON_HOTCOUNTMASK) >> TEMPMON_HOTCOUNTSHIFT; roomCount = (uint32_t)(calibrationData & TEMPMON_ROOMCOUNTMASK) >> TEMPMON_ROOMCOUNTSHIFT; s_hotT_ROOM = s_hotTemp - TEMPMON_ROOMTEMP; s_roomC_hotC = roomCount - s_hotCount; /* Set alarm temperature */ TEMPMON_SetTempAlarm(base, config->highAlarmTemp, kTEMPMON_HighAlarmMode); TEMPMON_SetTempAlarm(base, config->panicAlarmTemp, kTEMPMON_PanicAlarmMode); TEMPMON_SetTempAlarm(base, config->lowAlarmTemp, kTEMPMON_LowAlarmMode); } /*! * brief Deinitializes the TEMPMON module. * * param base TEMPMON base pointer */ void TEMPMON_Deinit(TEMPMON_Type *base) { base->TEMPSENSE0 |= TEMPMON_TEMPSENSE0_POWER_DOWN_MASK; } /*! * brief Gets the default configuration structure. * * This function initializes the TEMPMON configuration structure to a default value. The default * values are: * tempmonConfig->frequency = 0x02U; * tempmonConfig->highAlarmTemp = 44U; * tempmonConfig->panicAlarmTemp = 90U; * tempmonConfig->lowAlarmTemp = 39U; * * param config Pointer to a configuration structure. */ void TEMPMON_GetDefaultConfig(tempmon_config_t *config) { assert(config); /* Initializes the configure structure to zero. */ memset(config, 0, sizeof(*config)); /* Default measure frequency */ config->frequency = 0x03U; /* Default high alarm temperature */ config->highAlarmTemp = 40U; /* Default panic alarm temperature */ config->panicAlarmTemp = 90U; /* Default low alarm temperature */ config->lowAlarmTemp = 20U; } /*! * brief Get current temperature with the fused temperature calibration data. * * param base TEMPMON base pointer * return current temperature with degrees Celsius. */ float TEMPMON_GetCurrentTemperature(TEMPMON_Type *base) { /* Check arguments */ assert(NULL != base); uint32_t nmeas; float tmeas; while (!(base->TEMPSENSE0 & TEMPMON_TEMPSENSE0_FINISHED_MASK)) { } /* ready to read temperature code value */ nmeas = (base->TEMPSENSE0 & TEMPMON_TEMPSENSE0_TEMP_CNT_MASK) >> TEMPMON_TEMPSENSE0_TEMP_CNT_SHIFT; /* Calculate temperature */ tmeas = s_hotTemp - (float)((nmeas - s_hotCount) * s_hotT_ROOM / s_roomC_hotC); return tmeas; } /*! * brief Set the temperature count (raw sensor output) that will generate an alarm interrupt. * * param base TEMPMON base pointer * param tempVal The alarm temperature with degrees Celsius * param alarmMode The alarm mode. */ void TEMPMON_SetTempAlarm(TEMPMON_Type *base, uint32_t tempVal, tempmon_alarm_mode alarmMode) { /* Check arguments */ assert(NULL != base); uint32_t tempCodeVal; /* Calculate alarm temperature code value */ tempCodeVal = (uint32_t)(s_hotCount + (s_hotTemp - tempVal) * s_roomC_hotC / s_hotT_ROOM); switch (alarmMode) { case kTEMPMON_HighAlarmMode: /* Set high alarm temperature code value */ base->TEMPSENSE0 |= TEMPMON_TEMPSENSE0_ALARM_VALUE(tempCodeVal); break; case kTEMPMON_PanicAlarmMode: /* Set panic alarm temperature code value */ base->TEMPSENSE2 |= TEMPMON_TEMPSENSE2_PANIC_ALARM_VALUE(tempCodeVal); break; case kTEMPMON_LowAlarmMode: /* Set low alarm temperature code value */ base->TEMPSENSE2 |= TEMPMON_TEMPSENSE2_LOW_ALARM_VALUE(tempCodeVal); break; default: assert(false); break; } }
explora26/zephyr
ext/hal/nxp/mcux/drivers/imx/fsl_tempmon.c
C
apache-2.0
5,923
/** * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.process.instance; import java.util.Collection; import org.kie.internal.process.CorrelationKey; import org.kie.api.runtime.process.ProcessInstance; public interface ProcessInstanceManager { ProcessInstance getProcessInstance(long id); ProcessInstance getProcessInstance(long id, boolean readOnly); ProcessInstance getProcessInstance(CorrelationKey correlationKey); Collection<ProcessInstance> getProcessInstances(); void addProcessInstance(ProcessInstance processInstance, CorrelationKey correlationKey); void internalAddProcessInstance(ProcessInstance processInstance); void removeProcessInstance(ProcessInstance processInstance); void internalRemoveProcessInstance(ProcessInstance processInstance); void clearProcessInstances(); void clearProcessInstancesState(); }
OnePaaS/jbpm
jbpm-flow/src/main/java/org/jbpm/process/instance/ProcessInstanceManager.java
Java
apache-2.0
1,454
/* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include <string.h> #include "CellularDevice.h" #include "FileHandle_stub.h" #include "myCellularDevice.h" #include "CellularStateMachine_stub.h" using namespace mbed; // AStyle ignored as the definition is not clear due to preprocessor usage // *INDENT-OFF* class TestCellularDevice : public testing::Test { protected: void SetUp() { CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; CellularStateMachine_stub::get_current_target_state = STATE_INIT; CellularStateMachine_stub::get_current_current_state = STATE_INIT; CellularStateMachine_stub::bool_value = false; } void TearDown() { } }; // *INDENT-ON* TEST_F(TestCellularDevice, test_create_delete) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); delete dev; dev = NULL; CellularDevice *dev1 = CellularDevice::get_default_instance(); EXPECT_FALSE(dev1); } TEST_F(TestCellularDevice, test_set_sim_pin) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); // MAX_PIN_SIZE = 8; so let's try a longer one dev->set_sim_pin("123480375462074360276407"); dev->set_sim_pin(NULL); dev->set_sim_pin("1234"); delete dev; } TEST_F(TestCellularDevice, test_set_plmn) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); // MAX_PLMN_SIZE = 16; so let's try a longer one dev->set_plmn("123480327465023746502734602736073264076340"); dev->set_plmn("1234"); dev->set_plmn(NULL); delete dev; } TEST_F(TestCellularDevice, test_set_device_ready) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; ASSERT_EQ(dev->set_device_ready(), NSAPI_ERROR_NO_MEMORY); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->set_device_ready(), NSAPI_ERROR_OK); CellularStateMachine_stub::get_current_current_state = STATE_SIM_PIN; CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->set_device_ready(), NSAPI_ERROR_ALREADY); CellularStateMachine_stub::bool_value = true; CellularStateMachine_stub::get_current_target_state = STATE_SIM_PIN; CellularStateMachine_stub::get_current_current_state = STATE_POWER_ON; ASSERT_EQ(dev->set_device_ready(), NSAPI_ERROR_IN_PROGRESS); delete dev; } TEST_F(TestCellularDevice, test_set_sim_ready) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; ASSERT_EQ(dev->set_sim_ready(), NSAPI_ERROR_NO_MEMORY); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->set_sim_ready(), NSAPI_ERROR_OK); CellularStateMachine_stub::get_current_current_state = STATE_REGISTERING_NETWORK; CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->set_sim_ready(), NSAPI_ERROR_ALREADY); CellularStateMachine_stub::bool_value = true; CellularStateMachine_stub::get_current_target_state = STATE_REGISTERING_NETWORK; CellularStateMachine_stub::get_current_current_state = STATE_POWER_ON; ASSERT_EQ(dev->set_sim_ready(), NSAPI_ERROR_IN_PROGRESS); delete dev; } TEST_F(TestCellularDevice, test_register_to_network) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; ASSERT_EQ(dev->register_to_network(), NSAPI_ERROR_NO_MEMORY); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->register_to_network(), NSAPI_ERROR_OK); CellularStateMachine_stub::get_current_current_state = STATE_ATTACHING_NETWORK; CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->register_to_network(), NSAPI_ERROR_ALREADY); CellularStateMachine_stub::bool_value = true; CellularStateMachine_stub::get_current_target_state = STATE_ATTACHING_NETWORK; CellularStateMachine_stub::get_current_current_state = STATE_POWER_ON; ASSERT_EQ(dev->register_to_network(), NSAPI_ERROR_IN_PROGRESS); delete dev; } TEST_F(TestCellularDevice, test_attach_to_network) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; ASSERT_EQ(dev->attach_to_network(), NSAPI_ERROR_NO_MEMORY); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->attach_to_network(), NSAPI_ERROR_OK); CellularStateMachine_stub::get_current_current_state = STATE_ATTACHING_NETWORK; CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->attach_to_network(), NSAPI_ERROR_ALREADY); CellularStateMachine_stub::bool_value = true; CellularStateMachine_stub::get_current_target_state = STATE_ATTACHING_NETWORK; CellularStateMachine_stub::get_current_current_state = STATE_POWER_ON; ASSERT_EQ(dev->attach_to_network(), NSAPI_ERROR_IN_PROGRESS); delete dev; } TEST_F(TestCellularDevice, test_get_context_list) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularContext *ctx = dev->create_context(); EXPECT_TRUE(dev->get_context_list()); delete dev; dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); EXPECT_FALSE(dev->get_context_list()); delete dev; } TEST_F(TestCellularDevice, test_cellular_callback) { FileHandle_stub fh1; myCellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); ASSERT_EQ(dev->attach_to_network(), NSAPI_ERROR_OK); cell_callback_data_t data; dev->cellular_callback((nsapi_event_t)CellularRegistrationStatusChanged, (intptr_t)&data); data.error = NSAPI_ERROR_OK; dev->set_plmn("1234"); dev->cellular_callback((nsapi_event_t)CellularDeviceReady, (intptr_t)&data); dev->set_sim_pin("1234"); data.status_data = CellularDevice::SimStatePinNeeded; dev->cellular_callback((nsapi_event_t)CellularSIMStatusChanged, (intptr_t)&data); CellularContext *ctx = dev->create_context(); dev->cellular_callback(NSAPI_EVENT_CONNECTION_STATUS_CHANGE, NSAPI_STATUS_DISCONNECTED); delete dev; } TEST_F(TestCellularDevice, test_shutdown) { FileHandle_stub fh1; CellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; ASSERT_EQ(dev->shutdown(), NSAPI_ERROR_OK); delete dev; } TEST_F(TestCellularDevice, test_timeout_array) { FileHandle_stub fh1; myCellularDevice *dev = new myCellularDevice(&fh1); EXPECT_TRUE(dev); CellularStateMachine_stub::nsapi_error_value = NSAPI_ERROR_OK; // Max size uint16_t set_timeouts[CELLULAR_RETRY_ARRAY_SIZE + 1]; for (int i = 0; i < CELLULAR_RETRY_ARRAY_SIZE; i++) { set_timeouts[i] = i + 100; } dev->set_retry_timeout_array(set_timeouts, CELLULAR_RETRY_ARRAY_SIZE); uint16_t verify_timeouts[CELLULAR_RETRY_ARRAY_SIZE + 1]; for (int i = 0; i < CELLULAR_RETRY_ARRAY_SIZE; i++) { verify_timeouts[i] = i + 100; } dev->verify_timeout_array(verify_timeouts, CELLULAR_RETRY_ARRAY_SIZE); // Empty dev->set_retry_timeout_array(NULL, 0); dev->verify_timeout_array(NULL, 0); // Oversize (returns only CELLULAR_RETRY_ARRAY_SIZE) dev->set_retry_timeout_array(set_timeouts, CELLULAR_RETRY_ARRAY_SIZE + 1); dev->verify_timeout_array(verify_timeouts, CELLULAR_RETRY_ARRAY_SIZE); delete dev; }
mbedmicro/mbed
connectivity/cellular/tests/UNITTESTS/framework/device/cellulardevice/cellulardevicetest.cpp
C++
apache-2.0
8,498
package deploymentconfig import ( "fmt" "github.com/golang/glog" kerrors "k8s.io/apimachinery/pkg/api/errors" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" klabels "k8s.io/apimachinery/pkg/labels" kschema "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" kutilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/client-go/tools/record" "k8s.io/kubernetes/pkg/api/v1" kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/clientset" kcontroller "k8s.io/kubernetes/pkg/controller" ) // RSControlInterface is an interface that knows how to add or delete // ReplicationControllers, as well as increment or decrement them. It is used // by the DeploymentConfig controller to ease testing of actions that it takes. type RCControlInterface interface { PatchReplicationController(namespace, name string, data []byte) error } // RealRCControl is the default implementation of RCControlInterface. type RealRCControl struct { KubeClient kclientset.Interface Recorder record.EventRecorder } // To make sure RealRCControl implements RCControlInterface var _ RCControlInterface = &RealRCControl{} // PatchReplicationController executes a strategic merge patch contained in 'data' on RC specified by 'namespace' and 'name' func (r RealRCControl) PatchReplicationController(namespace, name string, data []byte) error { _, err := r.KubeClient.Core().ReplicationControllers(namespace).Patch(name, types.StrategicMergePatchType, data) return err } type RCControllerRefManager struct { kcontroller.BaseControllerRefManager controllerKind kschema.GroupVersionKind rcControl RCControlInterface } // NewRCControllerRefManager returns a RCControllerRefManager that exposes // methods to manage the controllerRef of ReplicationControllers. // // The CanAdopt() function can be used to perform a potentially expensive check // (such as a live GET from the API server) prior to the first adoption. // It will only be called (at most once) if an adoption is actually attempted. // If CanAdopt() returns a non-nil error, all adoptions will fail. // // NOTE: Once CanAdopt() is called, it will not be called again by the same // RCControllerRefManager instance. Create a new instance if it // makes sense to check CanAdopt() again (e.g. in a different sync pass). func NewRCControllerRefManager( rcControl RCControlInterface, controller kmetav1.Object, selector klabels.Selector, controllerKind kschema.GroupVersionKind, canAdopt func() error, ) *RCControllerRefManager { return &RCControllerRefManager{ BaseControllerRefManager: kcontroller.BaseControllerRefManager{ Controller: controller, Selector: selector, CanAdoptFunc: canAdopt, }, controllerKind: controllerKind, rcControl: rcControl, } } // ClaimReplicationController tries to take ownership of a ReplicationController. // // It will reconcile the following: // * Adopt the ReplicationController if it's an orphan. // * Release owned ReplicationController if the selector no longer matches. // // A non-nil error is returned if some form of reconciliation was attempted and // failed. Usually, controllers should try again later in case reconciliation // is still needed. // // If the error is nil, either the reconciliation succeeded, or no // reconciliation was necessary. The returned boolean indicates whether you now // own the object. func (m *RCControllerRefManager) ClaimReplicationController(rc *v1.ReplicationController) (bool, error) { match := func(obj kmetav1.Object) bool { return m.Selector.Matches(klabels.Set(obj.GetLabels())) } adopt := func(obj kmetav1.Object) error { return m.AdoptReplicationController(obj.(*v1.ReplicationController)) } release := func(obj kmetav1.Object) error { return m.ReleaseReplicationController(obj.(*v1.ReplicationController)) } return m.ClaimObject(rc, match, adopt, release) } // ClaimReplicationControllers tries to take ownership of a list of ReplicationControllers. // // It will reconcile the following: // * Adopt orphans if the selector matches. // * Release owned objects if the selector no longer matches. // // A non-nil error is returned if some form of reconciliation was attempted and // failed. Usually, controllers should try again later in case reconciliation // is still needed. // // If the error is nil, either the reconciliation succeeded, or no // reconciliation was necessary. The list of ReplicationControllers that you now own is // returned. func (m *RCControllerRefManager) ClaimReplicationControllers(rcs []*v1.ReplicationController) ([]*v1.ReplicationController, error) { var claimed []*v1.ReplicationController var errlist []error for _, rc := range rcs { ok, err := m.ClaimReplicationController(rc) if err != nil { errlist = append(errlist, err) continue } if ok { claimed = append(claimed, rc) } } return claimed, kutilerrors.NewAggregate(errlist) } // AdoptReplicationController sends a patch to take control of the ReplicationController. It returns the error if // the patching fails. func (m *RCControllerRefManager) AdoptReplicationController(rs *v1.ReplicationController) error { if err := m.CanAdopt(); err != nil { return fmt.Errorf("can't adopt ReplicationController %s/%s (%s): %v", rs.Namespace, rs.Name, rs.UID, err) } // Note that ValidateOwnerReferences() will reject this patch if another // OwnerReference exists with controller=true. addControllerPatch := fmt.Sprintf( `{"metadata":{ "ownerReferences":[{"apiVersion":"%s","kind":"%s","name":"%s","uid":"%s","controller":true,"blockOwnerDeletion":true}], "uid":"%s" } }`, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName(), m.Controller.GetUID(), rs.UID) return m.rcControl.PatchReplicationController(rs.Namespace, rs.Name, []byte(addControllerPatch)) } // ReleaseReplicationController sends a patch to free the ReplicationController from the control of the Deployment controller. // It returns the error if the patching fails. 404 and 422 errors are ignored. func (m *RCControllerRefManager) ReleaseReplicationController(rc *v1.ReplicationController) error { glog.V(4).Infof("patching ReplicationController %s/%s to remove its controllerRef to %s/%s:%s", rc.Namespace, rc.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName()) deleteOwnerRefPatch := fmt.Sprintf(`{"metadata":{"ownerReferences":[{"$patch":"delete","uid":"%s"}],"uid":"%s"}}`, m.Controller.GetUID(), rc.UID) err := m.rcControl.PatchReplicationController(rc.Namespace, rc.Name, []byte(deleteOwnerRefPatch)) if err != nil { if kerrors.IsNotFound(err) { // If the ReplicationController no longer exists, ignore it. return nil } if kerrors.IsInvalid(err) { // Invalid error will be returned in two cases: 1. the ReplicationController // has no owner reference, 2. the uid of the ReplicationController doesn't // match, which means the ReplicationController is deleted and then recreated. // In both cases, the error can be ignored. return nil } } return err }
cdrage/kedge
vendor/github.com/openshift/origin/pkg/apps/controller/deploymentconfig/controller_ref_manager.go
GO
apache-2.0
7,081
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest_ppapi/gtest_instance.h" #include "gtest_ppapi/gtest_runner.h" #include "ppapi/cpp/var.h" #if defined(WIN32) #undef PostMessage #endif GTestInstance::GTestInstance(PP_Instance instance) : pp::Instance(instance) { } GTestInstance::~GTestInstance() { } bool GTestInstance::Init(uint32_t /* argc */, const char* /* argn */[], const char* /* argv */[]) { // Create a GTestRunner thread/singleton. int local_argc = 0; GTestRunner::CreateGTestRunnerThread(this, local_argc, NULL); return true; } void GTestInstance::HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) { PostMessage("Invalid message"); return; } std::string message = var_message.AsString(); if (message == "RunGTest") { // This is our signal to start running the tests. Results from the tests // are posted through GTestEventListener. GTestRunner::gtest_runner()->RunAllTests(); } else { std::string return_var; return_var = "Unknown message "; return_var += message; PostMessage(return_var); } }
plxaye/chromium
src/native_client_sdk/src/libraries/gtest_ppapi/gtest_instance.cc
C++
apache-2.0
1,254
// // Test robustness about JS injection in different place // // This assume malicious document arrive to the frontend. // casper.notebook_test(function () { var messages = []; this.on('remote.alert', function (msg) { messages.push(msg); }); this.evaluate(function () { var cell = IPython.notebook.get_cell(0); var json = cell.toJSON(); json.execution_count = "<script> alert('hello from input prompts !')</script>"; cell.fromJSON(json); }); this.then(function () { this.test.assert(messages.length == 0, "Captured log message from script tag injection !"); }); });
unnikrishnankgs/va
venv/lib/python3.5/site-packages/notebook/tests/notebook/inject_js.js
JavaScript
bsd-2-clause
650
cask 'pdfpenpro' do version '923.0,1510025685' sha256 'bcd9073dfce0b083d1ccd0e33deb5f60e6db4303608ac9d676bbe8537a66226b' url "https://dl.smilesoftware.com/com.smileonmymac.PDFpenPro/#{version.before_comma}/#{version.after_comma}/PDFpenPro-#{version.before_comma}.zip" appcast 'https://updates.smilesoftware.com/com.smileonmymac.PDFpenPro.xml', checkpoint: '9496222a3d75bb49c66d2875fc3274875ed3524bf0b4af4a660ae953fb2e1099' name 'PDFpenPro' homepage 'https://smilesoftware.com/PDFpenPro' app 'PDFpenPro.app' end
wKovacs64/homebrew-cask
Casks/pdfpenpro.rb
Ruby
bsd-2-clause
537
// Copyright 2006-2013 the V8 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. // This module contains the architecture-specific code. This make the rest of // the code less dependent on differences between different processor // architecture. // The classes have the same definition for all architectures. The // implementation for a particular architecture is put in cpu_<arch>.cc. // The build system then uses the implementation for the target architecture. // #ifndef V8_BASE_CPU_H_ #define V8_BASE_CPU_H_ #include "src/base/macros.h" namespace v8 { namespace base { // ---------------------------------------------------------------------------- // CPU // // Query information about the processor. // // This class also has static methods for the architecture specific functions. // Add methods here to cope with differences between the supported // architectures. For each architecture the file cpu_<arch>.cc contains the // implementation of these static functions. class CPU FINAL { public: CPU(); // x86 CPUID information const char* vendor() const { return vendor_; } int stepping() const { return stepping_; } int model() const { return model_; } int ext_model() const { return ext_model_; } int family() const { return family_; } int ext_family() const { return ext_family_; } int type() const { return type_; } // arm implementer/part information int implementer() const { return implementer_; } static const int ARM = 0x41; static const int NVIDIA = 0x4e; static const int QUALCOMM = 0x51; int architecture() const { return architecture_; } int variant() const { return variant_; } static const int NVIDIA_DENVER = 0x0; int part() const { return part_; } // ARM-specific part codes static const int ARM_CORTEX_A5 = 0xc05; static const int ARM_CORTEX_A7 = 0xc07; static const int ARM_CORTEX_A8 = 0xc08; static const int ARM_CORTEX_A9 = 0xc09; static const int ARM_CORTEX_A12 = 0xc0c; static const int ARM_CORTEX_A15 = 0xc0f; // PPC-specific part codes enum { PPC_POWER5, PPC_POWER6, PPC_POWER7, PPC_POWER8, PPC_G4, PPC_G5, PPC_PA6T }; // General features bool has_fpu() const { return has_fpu_; } // x86 features bool has_cmov() const { return has_cmov_; } bool has_sahf() const { return has_sahf_; } bool has_mmx() const { return has_mmx_; } bool has_sse() const { return has_sse_; } bool has_sse2() const { return has_sse2_; } bool has_sse3() const { return has_sse3_; } bool has_ssse3() const { return has_ssse3_; } bool has_sse41() const { return has_sse41_; } bool has_sse42() const { return has_sse42_; } bool has_osxsave() const { return has_osxsave_; } bool has_avx() const { return has_avx_; } bool has_fma3() const { return has_fma3_; } bool is_atom() const { return is_atom_; } // arm features bool has_idiva() const { return has_idiva_; } bool has_neon() const { return has_neon_; } bool has_thumb2() const { return has_thumb2_; } bool has_vfp() const { return has_vfp_; } bool has_vfp3() const { return has_vfp3_; } bool has_vfp3_d32() const { return has_vfp3_d32_; } // mips features bool is_fp64_mode() const { return is_fp64_mode_; } private: char vendor_[13]; int stepping_; int model_; int ext_model_; int family_; int ext_family_; int type_; int implementer_; int architecture_; int variant_; int part_; bool has_fpu_; bool has_cmov_; bool has_sahf_; bool has_mmx_; bool has_sse_; bool has_sse2_; bool has_sse3_; bool has_ssse3_; bool has_sse41_; bool has_sse42_; bool is_atom_; bool has_osxsave_; bool has_avx_; bool has_fma3_; bool has_idiva_; bool has_neon_; bool has_thumb2_; bool has_vfp_; bool has_vfp3_; bool has_vfp3_d32_; bool is_fp64_mode_; }; } } // namespace v8::base #endif // V8_BASE_CPU_H_
CTSRD-SOAAP/chromium-42.0.2311.135
v8/src/base/cpu.h
C
bsd-3-clause
3,950
<!DOCTYPE html> <html> <head> <title>Test asynchronous setServerCertificate while running garbage collection</title> <script src="encrypted-media-utils.js"></script> <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> </head> <body> <script> // Run garbage collection continuously. setInterval(asyncGC, 0); promise_test(function(test) { return navigator.requestMediaKeySystemAccess('org.w3.clearkey', getSimpleConfiguration()).then(function(access) { return access.createMediaKeys(); }).then(function(mediaKeys) { var cert = new Uint8Array(200); return mediaKeys.setServerCertificate(cert); }).then(function(result) { assert_false(result); }); }, 'Test asynchronous setServerCertificate while running garbage collection.'); </script> </body> </html>
scheib/chromium
third_party/blink/web_tests/media/encrypted-media/encrypted-media-async-setcert-with-gc.html
HTML
bsd-3-clause
1,083
package org.jbehave.core.steps; import java.util.Map; /** * Represents a row in an {@link ExamplesTable}. */ public interface Row { /** * Returns the values as a Map, where the key is the column name and the value is the row value. * * @return The Map of values */ Map<String, String> values(); }
jeremiehuchet/jbehave-core
jbehave-core/src/main/java/org/jbehave/core/steps/Row.java
Java
bsd-3-clause
331
extern const char g_GIT_SHA1[];
mtCarto/PDAL
include/pdal/gitsha.h
C
bsd-3-clause
31
<!DOCTYPE html> <style> #myheader { position: fixed; top: 20px; } </style> <script> function runTest() { if (window.testRunner) testRunner.setPrinting(); } </script> <body onload="runTest()"> <div id="myheader"> <div align="center"> crbug.com/652449: Fixed-position object should be repeated on each page and positioned relative to top of page even when scrolled. <hr/> </div> </div> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> <p>Filler lines</p> </body>
scheib/chromium
third_party/blink/web_tests/printing/fixed-positioned-scrolled-expected.html
HTML
bsd-3-clause
2,236
# encoding: utf-8 from django.core.management.base import NoArgsCommand from optparse import make_option from video.management.commands.sub_commands.AddVideo import AddVideo class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--video-link',action='store',dest='video-link', help="link to the video, use --list-types to see a list of supported link types"), make_option('--list-types',action='store_true',dest='list-types', help="list supported video link types and formats"), make_option('--object-type',action='store',dest='object-type', help="set the object type, currently only member is supported"), make_option('--object-id',action='store',dest='object-id', help="set the object id that the video will be related to"), make_option('--sticky',action='store_true',dest='is_sticky', help="set the video as sticky"), ) def handle_noargs(self, **options): if options.get('list-types',False): print """Supported link formats: youtube - http://www.youtube.com/watch?v=2sASREICzqY""" else: av=AddVideo(options) av.run() print av.ans
noamelf/Open-Knesset
video/management/commands/add_video.py
Python
bsd-3-clause
1,246
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* ** This program is based on ZeusBench V1.0 written by Adam Twiss ** which is Copyright (c) 1996 by Zeus Technology Ltd. http://www.zeustech.net/ ** ** This software is provided "as is" and any express or implied waranties, ** including but not limited to, the implied warranties of merchantability and ** fitness for a particular purpose are disclaimed. In no event shall ** Zeus Technology Ltd. be liable for any direct, indirect, incidental, special, ** exemplary, or consequential damaged (including, but not limited to, ** procurement of substitute good or services; loss of use, data, or profits; ** or business interruption) however caused and on 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. ** */ /* ** HISTORY: ** - Originally written by Adam Twiss <adam@zeus.co.uk>, March 1996 ** with input from Mike Belshe <mbelshe@netscape.com> and ** Michael Campanella <campanella@stevms.enet.dec.com> ** - Enhanced by Dean Gaudet <dgaudet@apache.org>, November 1997 ** - Cleaned up by Ralf S. Engelschall <rse@apache.org>, March 1998 ** - POST and verbosity by Kurt Sussman <kls@merlot.com>, August 1998 ** - HTML table output added by David N. Welton <davidw@prosa.it>, January 1999 ** - Added Cookie, Arbitrary header and auth support. <dirkx@webweaving.org>, April 1999 ** Version 1.3d ** - Increased version number - as some of the socket/error handling has ** fundamentally changed - and will give fundamentally different results ** in situations where a server is dropping requests. Therefore you can ** no longer compare results of AB as easily. Hence the inc of the version. ** They should be closer to the truth though. Sander & <dirkx@covalent.net>, End 2000. ** - Fixed proxy functionality, added median/mean statistics, added gnuplot ** output option, added _experimental/rudimentary_ SSL support. Added ** confidence guestimators and warnings. Sander & <dirkx@covalent.net>, End 2000 ** - Fixed serious int overflow issues which would cause realistic (longer ** than a few minutes) run's to have wrong (but believable) results. Added ** trapping of connection errors which influenced measurements. ** Contributed by Sander Temme, Early 2001 ** Version 1.3e ** - Changed timeout behavour during write to work whilst the sockets ** are filling up and apr_write() does writes a few - but not all. ** This will potentially change results. <dirkx@webweaving.org>, April 2001 ** Version 2.0.36-dev ** Improvements to concurrent processing: ** - Enabled non-blocking connect()s. ** - Prevent blocking calls to apr_socket_recv() (thereby allowing AB to ** manage its entire set of socket descriptors). ** - Any error returned from apr_socket_recv() that is not EAGAIN or EOF ** is now treated as fatal. ** Contributed by Aaron Bannert, April 24, 2002 ** ** Version 2.0.36-2 ** Internalized the version string - this string is part ** of the Agent: header and the result output. ** ** Version 2.0.37-dev ** Adopted SSL code by Madhu Mathihalli <madhusudan_mathihalli@hp.com> ** [PATCH] ab with SSL support Posted Wed, 15 Aug 2001 20:55:06 GMT ** Introduces four 'if (int == value)' tests per non-ssl request. ** ** Version 2.0.40-dev ** Switched to the new abstract pollset API, allowing ab to ** take advantage of future apr_pollset_t scalability improvements. ** Contributed by Brian Pane, August 31, 2002 ** ** Version 2.3 ** SIGINT now triggers output_results(). ** Contributed by colm, March 30, 2006 **/ /* Note: this version string should start with \d+[\d\.]* and be a valid * string for an HTTP Agent: header when prefixed with 'ApacheBench/'. * It should reflect the version of AB - and not that of the apache server * it happens to accompany. And it should be updated or changed whenever * the results are no longer fundamentally comparable to the results of * a previous version of ab. Either due to a change in the logic of * ab - or to due to a change in the distribution it is compiled with * (such as an APR change in for example b * printf("ok\n");locking). */ #define AP_AB_BASEREVISION "2.3" /* * BUGS: * * - uses strcpy/etc. * - has various other poor buffer attacks related to the lazy parsing of * response headers from the server * - doesn't implement much of HTTP/1.x, only accepts certain forms of * responses * - (performance problem) heavy use of strstr shows up top in profile * only an issue for loopback usage */ /* -------------------------------------------------------------------- */ #if 'A' != 0x41 /* Hmmm... This source code isn't being compiled in ASCII. * In order for data that flows over the network to make * sense, we need to translate to/from ASCII. */ #define NOT_ASCII #endif /* affects include files on Solaris */ #define BSD_COMP #include "apr.h" #include "apr_signal.h" #include "apr_strings.h" #include "apr_network_io.h" #include "apr_file_io.h" #include "apr_time.h" #include "apr_getopt.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_portable.h" #include "ap_release.h" #include "apr_poll.h" #define APR_WANT_STRFUNC #include "apr_want.h" #include "apr_base64.h" #ifdef NOT_ASCII #include "apr_xlate.h" #endif #if APR_HAVE_STDIO_H #include <stdio.h> #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for getpid() */ #endif #if !defined(WIN32) && !defined(NETWARE) #include "ap_config_auto.h" #endif #if defined(HAVE_SSLC) /* Libraries for RSA SSL-C */ #include <rsa.h> #include <x509.h> #include <pem.h> #include <err.h> #include <ssl.h> #include <r_rand.h> #include <sslc.h> #define USE_SSL #define RSAREF #define SK_NUM(x) sk_num(x) #define SK_VALUE(x,y) sk_value(x,y) typedef STACK X509_STACK_TYPE; #elif defined(HAVE_OPENSSL) /* Libraries on most systems.. */ #include <openssl/rsa.h> #include <openssl/crypto.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/rand.h> #define USE_SSL #define SK_NUM(x) sk_X509_num(x) #define SK_VALUE(x,y) sk_X509_value(x,y) typedef STACK_OF(X509) X509_STACK_TYPE; #endif #if defined(USE_SSL) #if (OPENSSL_VERSION_NUMBER >= 0x00909000) #define AB_SSL_METHOD_CONST const #else #define AB_SSL_METHOD_CONST #endif #if (OPENSSL_VERSION_NUMBER >= 0x0090707f) #define AB_SSL_CIPHER_CONST const #else #define AB_SSL_CIPHER_CONST #endif #ifdef SSL_OP_NO_TLSv1_2 #define HAVE_TLSV1_X #endif #endif #include <math.h> #if APR_HAVE_CTYPE_H #include <ctype.h> #endif #if APR_HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_MTCP #include <mtcp_api.h> #include <sched.h> #include "apr_mtcp.h" #endif #include <assert.h> /* ------------------- DEFINITIONS -------------------------- */ #ifndef LLONG_MAX #define AB_MAX APR_INT64_C(0x7fffffffffffffff) #else #define AB_MAX LLONG_MAX #endif /* maximum number of requests on a time limited test */ #define MAX_REQUESTS (INT_MAX > 50000 ? 50000 : INT_MAX) /* good old state hostname */ #define STATE_UNCONNECTED 0 #define STATE_CONNECTING 1 /* TCP connect initiated, but we don't * know if it worked yet */ #define STATE_CONNECTED 2 /* we know TCP connect completed */ #define STATE_READ 3 #define CBUFFSIZE (2048) #define MAX_FILE_NAME 1024 struct connection { apr_pool_t *ctx; apr_socket_t *aprsock; int state; apr_size_t read; /* amount of bytes read */ apr_size_t bread; /* amount of body read */ apr_size_t rwrite, rwrote; /* keep pointers in what we write - across * EAGAINs */ apr_size_t length; /* Content-Length value used for keep-alive */ char cbuff[CBUFFSIZE]; /* a buffer to store server response header */ int cbx; /* offset in cbuffer */ int keepalive; /* non-zero if a keep-alive request */ int keepalive_cnt; int gotheader; /* non-zero if we have the entire header in * cbuff */ apr_time_t start, /* Start of connection */ connect, /* Connected, start writing */ endwrite, /* Request written */ beginread, /* First byte of input */ done; /* Connection closed */ int socknum; #ifdef USE_SSL SSL *ssl; #endif }; struct data { apr_time_t starttime; /* start time of connection */ apr_interval_time_t waittime; /* between request and reading response */ apr_interval_time_t ctime; /* time to connect */ apr_interval_time_t time; /* time for connection */ }; #define ap_min(a,b) ((a)<(b))?(a):(b) #define ap_max(a,b) ((a)>(b))?(a):(b) #define ap_round_ms(a) ((apr_time_t)((a) + 500)/1000) #define ap_double_ms(a) ((double)(a)/1000.0) #define MAX_CONCURRENCY 200000 #define MAX_CPUS 16 /* --------------------- GLOBALS ---------------------------- */ /* Static Options */ int verbosity = 0; /* no verbosity by default */ int recverrok = 0; /* ok to proceed after socket receive errors */ int posting = 0; /* GET by default */ int requests = 1; /* Number of requests to make */ int request_append = 0; /* Whether extra data needs to be appended to requests */ int heartbeatres = 100; /* How often do we say we're alive */ int concurrency = 1; /* Number of multiple requests to make */ int percentile = 1; /* Show percentile served */ int confidence = 1; /* Show confidence estimator and warnings */ int tlimit = 0; /* time limit in secs */ int keepalive = 0; /* try and do keepalive connections */ int keepalive_cnt = 0; #ifdef HAVE_MTCP int windowsize = 8*1024; #else int windowsize = 0; /* we use the OS default window size */ #endif char servername[1024]; /* name that server reports */ char *hostname; /* host name from URL */ char *host_field; /* value of "Host:" header field */ char *path; /* path name */ char postfile[1024]; /* name of file containing post data */ char *postdata; /* *buffer containing data from postfile */ char *reqdata; /* *buffer containing data from request file */ char *req_p; /* pointer to position in request data */ apr_size_t postlen = 0; /* length of data to be POSTed */ apr_size_t append_req_len = 0; /* length of request data to be appended */ char content_type[1024];/* content type to put in POST header */ char *cookie, /* optional cookie line */ *auth, /* optional (basic/uuencoded) auhentication */ *hdrs; /* optional arbitrary headers */ apr_port_t port; /* port number */ char proxyhost[1024]; /* proxy host name */ int proxyport = 0; /* proxy port */ char *connecthost; apr_port_t connectport; char *gnuplot; /* GNUplot file */ char *csvperc; /* CSV Percentile file */ char url[1024]; char * fullurl, * colonhost; int isproxy = 0; apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */ int use_html = 0; /* use html in the report */ apr_sockaddr_t *destsa; apr_pool_t *cntxt; const char *tablestring; const char *trstring; const char *tdstring; /* overrides for ab-generated common headers */ int opt_host = 0; /* was an optional "Host:" header specified? */ int opt_useragent = 0; /* was an optional "User-Agent:" header specified? */ int opt_accept = 0; /* was an optional "Accept:" header specified? */ /* Global variables for statistics */ apr_size_t doclen = 0; apr_int64_t totalread = 0; /* total number of bytes read */ apr_int64_t totalbread = 0; /* totoal amount of entity body read */ apr_int64_t totalposted = 0; /* total number of bytes posted, inc. headers */ int started = 0; /* number of requests started, so no excess */ int done = 0; /* number of requests we have done */ int doneka = 0; /* number of keep alive connections done */ int good = 0, bad = 0; /* number of good and bad requests */ int epipe = 0; /* number of broken pipe writes */ int err_length = 0; /* requests failed due to response length */ int err_conn = 0; /* requests failed due to connection drop */ int err_recv = 0; /* requests failed due to broken read */ int err_except = 0; /* requests failed due to exception */ int err_response = 0; /* requests with invalid or non-200 response */ /* Thread local variables for statistics */ __thread apr_size_t _doclen = 0; __thread apr_int64_t _totalread = 0; /* total number of bytes read */ __thread apr_int64_t _totalbread = 0; /* totoal amount of entity body read */ __thread apr_int64_t _totalposted = 0; /* total number of bytes posted, inc. headers */ __thread int _started = 0; /* number of requests started, so no excess */ __thread int _done = 0; /* number of requests we have done */ __thread int _doneka = 0; /* number of keep alive connections done */ __thread int _good = 0; __thread apr_time_t _lasttime; /* Thread local variables */ __thread struct connection *con; /* connection array */ __thread struct data *_stats; __thread apr_pollset_t *readbits; __thread int _requests=1; __thread int _concurrency = 1; __thread char buffer[8192]; /* per-thread throw-away buffer to read stuff into */ __thread int _cpu; __thread apr_pool_t *_cntxt; __thread apr_port_t _connectport; __thread apr_sockaddr_t *_destsa; int num_ports =1; int _num_cpus = 1; int thread_cpu[MAX_CPUS]; pthread_t app_thread[MAX_CPUS]; static pthread_mutex_t stat_mutex; static pthread_mutex_t err_mutex; static pthread_mutex_t *lock_cs; static long *lock_count; #ifdef USE_SSL int is_ssl; SSL_CTX *ssl_ctx; char *ssl_cipher = NULL; char *ssl_info = NULL; BIO *bio_out,*bio_err; #endif apr_time_t start, lasttime, stoptime; /* global request (and its length) */ char _request[2048]; char *request = _request; apr_size_t reqlen; /* interesting percentiles */ int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100}; struct data *stats; /* data for each request */ #ifdef NOT_ASCII apr_xlate_t *from_ascii, *to_ascii; #endif static void write_request(struct connection * c); static void close_connection(struct connection * c); /* --------------------------------------------------------- */ /* simple little function to write an error string and exit */ static void err(char *s) { fprintf(stderr, "%s\n", s); /*if (_done){ printf("%d trying to acquire stat_mutex\n", _cpu); pthread_mutex_lock(&stat_mutex); int i; for (i = 0; i < _done; i++){ memcpy(&stats[done+i], &_stats[i], sizeof(struct data)); } done += _done; pthread_mutex_unlock(&stat_mutex); printf("Total of %d requests completed\n" , done); }*/ exit(1); } /* simple little function to write an APR error string and exit */ static void apr_err(char *s, apr_status_t rv) { char buf[120]; fprintf(stderr, "%s: %s (%d)\n", s, apr_strerror(rv, buf, sizeof buf), rv); /*if (_done){ printf("%d trying to acquire stat_mutex\n", _cpu); pthread_mutex_lock(&stat_mutex); int i; for (i = 0; i < _done; i++){ memcpy(&stats[done+i], &_stats[i], sizeof(struct data)); } done += _done; pthread_mutex_unlock(&stat_mutex); printf("Total of %d requests completed\n" , done); }*/ exit(rv); } /* --------------------------------------------------------- */ /* write out request to a connection - assumes we can write * (small) request out in one go into our new socket buffer * */ #ifdef USE_SSL static long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret) { BIO *out; out=(BIO *)BIO_get_callback_arg(bio); if (out == NULL) return(ret); if (cmd == (BIO_CB_READ|BIO_CB_RETURN)) { BIO_printf(out,"read from %p [%p] (%d bytes => %ld (0x%lX))\n", bio, argp, argi, ret, ret); BIO_dump(out,(char *)argp,(int)ret); return(ret); } else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN)) { BIO_printf(out,"write to %p [%p] (%d bytes => %ld (0x%lX))\n", bio, argp, argi, ret, ret); BIO_dump(out,(char *)argp,(int)ret); } return ret; } static void ssl_state_cb(const SSL *s, int w, int r) { if (w & SSL_CB_ALERT) { BIO_printf(bio_err, "SSL/TLS Alert [%s] %s:%s\n", (w & SSL_CB_READ ? "read" : "write"), SSL_alert_type_string_long(r), SSL_alert_desc_string_long(r)); } else if (w & SSL_CB_LOOP) { BIO_printf(bio_err, "SSL/TLS State [%s] %s\n", (SSL_in_connect_init((SSL*)s) ? "connect" : "-"), SSL_state_string_long(s)); } else if (w & (SSL_CB_HANDSHAKE_START|SSL_CB_HANDSHAKE_DONE)) { BIO_printf(bio_err, "SSL/TLS Handshake [%s] %s\n", (w & SSL_CB_HANDSHAKE_START ? "Start" : "Done"), SSL_state_string_long(s)); } } #ifndef RAND_MAX #define RAND_MAX INT_MAX #endif static int ssl_rand_choosenum(int l, int h) { int i; char buf[50]; srand((unsigned int)time(NULL)); apr_snprintf(buf, sizeof(buf), "%.0f", (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l))); i = atoi(buf)+1; if (i < l) i = l; if (i > h) i = h; return i; } static void ssl_rand_seed(void) { int nDone = 0; int n, l; time_t t; pid_t pid; unsigned char stackdata[256]; /* * seed in the current time (usually just 4 bytes) */ t = time(NULL); l = sizeof(time_t); RAND_seed((unsigned char *)&t, l); nDone += l; /* * seed in the current process id (usually just 4 bytes) */ pid = getpid(); l = sizeof(pid_t); RAND_seed((unsigned char *)&pid, l); nDone += l; /* * seed in some current state of the run-time stack (128 bytes) */ n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1); RAND_seed(stackdata+n, 128); nDone += 128; } static int ssl_print_connection_info(BIO *bio, SSL *ssl) { AB_SSL_CIPHER_CONST SSL_CIPHER *c; int alg_bits,bits; BIO_printf(bio,"Transport Protocol :%s\n", SSL_get_version(ssl)); c = SSL_get_current_cipher(ssl); BIO_printf(bio,"Cipher Suite Protocol :%s\n", SSL_CIPHER_get_version(c)); BIO_printf(bio,"Cipher Suite Name :%s\n",SSL_CIPHER_get_name(c)); bits = SSL_CIPHER_get_bits(c,&alg_bits); BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits); return(1); } static void ssl_print_cert_info(BIO *bio, X509 *cert) { X509_NAME *dn; char buf[1024]; BIO_printf(bio, "Certificate version: %ld\n", X509_get_version(cert)+1); BIO_printf(bio,"Valid from: "); ASN1_UTCTIME_print(bio, X509_get_notBefore(cert)); BIO_printf(bio,"\n"); BIO_printf(bio,"Valid to : "); ASN1_UTCTIME_print(bio, X509_get_notAfter(cert)); BIO_printf(bio,"\n"); BIO_printf(bio,"Public key is %d bits\n", EVP_PKEY_bits(X509_get_pubkey(cert))); dn = X509_get_issuer_name(cert); X509_NAME_oneline(dn, buf, sizeof(buf)); BIO_printf(bio,"The issuer name is %s\n", buf); dn=X509_get_subject_name(cert); X509_NAME_oneline(dn, buf, sizeof(buf)); BIO_printf(bio,"The subject name is %s\n", buf); /* dump the extension list too */ BIO_printf(bio, "Extension Count: %d\n", X509_get_ext_count(cert)); } static void ssl_print_info(struct connection *c) { X509_STACK_TYPE *sk; X509 *cert; int count; BIO_printf(bio_err, "\n"); sk = SSL_get_peer_cert_chain(c->ssl); if ((count = SK_NUM(sk)) > 0) { int i; for (i=1; i<count; i++) { cert = (X509 *)SK_VALUE(sk, i); ssl_print_cert_info(bio_out, cert); X509_free(cert); } } cert = SSL_get_peer_certificate(c->ssl); if (cert == NULL) { BIO_printf(bio_out, "Anon DH\n"); } else { BIO_printf(bio_out, "Peer certificate\n"); ssl_print_cert_info(bio_out, cert); X509_free(cert); } ssl_print_connection_info(bio_err,c->ssl); SSL_SESSION_print(bio_err, SSL_get_session(c->ssl)); } static void ssl_proceed_handshake(struct connection *c) { int do_next = 1; while (do_next) { int ret, ecode; apr_pollfd_t new_pollfd; ret = SSL_do_handshake(c->ssl); ecode = SSL_get_error(c->ssl, ret); switch (ecode) { case SSL_ERROR_NONE: if (verbosity >= 2) ssl_print_info(c); if (ssl_info == NULL) { AB_SSL_CIPHER_CONST SSL_CIPHER *ci; X509 *cert; int sk_bits, pk_bits, swork; ci = SSL_get_current_cipher(c->ssl); sk_bits = SSL_CIPHER_get_bits(ci, &swork); cert = SSL_get_peer_certificate(c->ssl); if (cert) pk_bits = EVP_PKEY_bits(X509_get_pubkey(cert)); else pk_bits = 0; /* Anon DH */ ssl_info = malloc(128); apr_snprintf(ssl_info, 128, "%s,%s,%d,%d", SSL_get_version(c->ssl), SSL_CIPHER_get_name(ci), pk_bits, sk_bits); } write_request(c); do_next = 0; break; case SSL_ERROR_WANT_READ: new_pollfd.desc_type = APR_POLL_SOCKET; new_pollfd.reqevents = APR_POLLIN; new_pollfd.desc.s = c->aprsock; new_pollfd.client_data = c; apr_pollset_add(readbits, &new_pollfd); do_next = 0; break; case SSL_ERROR_WANT_WRITE: /* Try again */ do_next = 1; break; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_SSL: case SSL_ERROR_SYSCALL: /* Unexpected result */ BIO_printf(bio_err, "SSL handshake failed (%d).\n", ecode); ERR_print_errors(bio_err); close_connection(c); do_next = 0; break; } } } #endif /* USE_SSL */ int core_affinitize(int core){ cpu_set_t *cmask; int n; int ret; /*For NUMA setting*/ struct bitmask *bmask; FILE *fp; char sysfname[MAX_FILE_NAME]; int phy_id; n = numa_num_configured_cpus(); if (core < 0 || core >= (int) n) { errno = -EINVAL; return -1; } if((cmask = CPU_ALLOC(n)) == NULL) perror("CPU ALLOC"); CPU_ZERO_S(n, cmask); CPU_SET_S(core, n, cmask); ret = sched_setaffinity(0, n, cmask); CPU_FREE(cmask); /* TODO: Setting NUMA nodes * Occasionally dies */ /* if(numa_max_node() == 0){ return ret; } bmask = numa_bitmask_alloc(n); assert(bmask); snprintf(sysfname, MAX_FILE_NAME -1, "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", core); fp = fopen(sysfname, "r"); if (!fp) { perror(sysfname); errno = EFAULT; return -1; } fscanf(fp, "%d", &phy_id); printf("%d: got phy_id %d\n", core, phy_id); numa_bitmask_setbit(bmask, phy_id); printf("%d: bitmask_setbit\n", core); numa_set_membind(bmask); printf("%d: set_membind\n", core); numa_bitmask_free(bmask); */ printf("%d: core affinitized\n", core); return ret; } /* Open a file containing lines to append to each request * For -R option. */ static int open_request_file(const char *rfile) { apr_file_t *reqfd; apr_finfo_t finfo; apr_status_t rv; char errmsg[120]; rv = apr_file_open(&reqfd, rfile, APR_READ, APR_OS_DEFAULT, cntxt); if (rv != APR_SUCCESS) { fprintf(stderr, "ab: Could not open POST data file (%s): %s\n", rfile, apr_strerror(rv, errmsg, sizeof errmsg)); return rv; } apr_file_info_get(&finfo, APR_FINFO_NORM, reqfd); append_req_len = (apr_size_t)finfo.size; reqdata = malloc(append_req_len+2); if (!reqdata) { fprintf(stderr, "ab: Could not allocate request data buffer\n"); return APR_ENOMEM; } rv = apr_file_read_full(reqfd, reqdata, append_req_len, NULL); if (rv != APR_SUCCESS) { fprintf(stderr, "ab: Could not read request data file: %s\n", apr_strerror(rv, errmsg, sizeof errmsg)); return rv; } apr_file_close(reqfd); if (*(reqdata + append_req_len-1) != '\n') *(reqdata + (append_req_len++) - 1) = '\n'; *(reqdata + append_req_len) = '\0'; return 0; } static void write_request(struct connection * c) { int loop =0; char *eol; char path_append[1024]; int snprintf_res; /* modify request each time to append data from request file */ if (request_append == 1) { eol = strchr(req_p, '\n'); /* end of current line */ if (eol == NULL) eol = reqdata + append_req_len; /* end of reqdata */ apr_snprintf(path_append, eol-req_p+1, "%s", req_p); req_p = eol + 1; /* next line */ if (req_p >= (reqdata + append_req_len)) req_p = reqdata; /* back to start of request data */ if (posting <= 0) { snprintf_res = apr_snprintf(request, sizeof(_request), "%s %s%s HTTP/1.0\r\n" "User-Agent: ApacheBench/%s\r\n" "%s" "%s" "%s" "Host: %s%s\r\n" "Accept: */*\r\n" "%s" "\r\n", (posting == 0) ? "GET" : "HEAD", (isproxy) ? fullurl : path, path_append, AP_AB_BASEREVISION, keepalive ? "Connection: Keep-Alive\r\n" : "", cookie, auth, host_field, colonhost, hdrs); } else { snprintf_res = apr_snprintf(request, sizeof(_request), "POST %s%s HTTP/1.0\r\n" "User-Agent: ApacheBench/%s\r\n" "%s" "%s" "%s" "Host: %s%s\r\n" "Accept: */*\r\n" "Content-length: %" APR_SIZE_T_FMT "\r\n" "Content-type: %s\r\n" "%s" "\r\n", (isproxy) ? fullurl : path, path_append, AP_AB_BASEREVISION, keepalive ? "Connection: Keep-Alive\r\n" : "", cookie, auth, host_field, colonhost, postlen, (content_type[0]) ? content_type : "text/plain", hdrs); } if (snprintf_res >= sizeof(_request)) { err("Request too long\n"); } if (verbosity >= 2 && !request_append) printf("INFO: POST header == \n---\n%s\n---\n", request); reqlen = strlen(request); } do { apr_time_t tnow; apr_size_t l = c->rwrite; apr_status_t e = APR_SUCCESS; /* prevent gcc warning */ tnow = _lasttime = apr_time_now(); /* * First time round ? */ if (c->rwrite == 0) { apr_socket_timeout_set(c->aprsock, 0); c->connect = tnow; c->rwrote = 0; c->rwrite = reqlen; if (posting) c->rwrite += postlen; } else if (tnow > c->connect + aprtimeout) { printf("Send request timed out!\n"); close_connection(c); return; } #ifdef USE_SSL if (c->ssl) { apr_size_t e_ssl; e_ssl = SSL_write(c->ssl,request + c->rwrote, l); if (e_ssl != l) { BIO_printf(bio_err, "SSL write failed - closing connection\n"); ERR_print_errors(bio_err); close_connection (c); return; } l = e_ssl; e = APR_SUCCESS; } else #endif e = apr_socket_send(c->aprsock, request + c->rwrote, &l); if (e != APR_SUCCESS && !APR_STATUS_IS_EAGAIN(e)) { pthread_mutex_lock(&err_mutex); epipe++; pthread_mutex_unlock(&err_mutex); close_connection(c); return; } _totalposted += l; c->rwrote += l; c->rwrite -= l; loop++; } while (c->rwrite); c->state = STATE_READ; c->endwrite = _lasttime = apr_time_now(); #ifndef HAVE_MTCP { apr_pollfd_t new_pollfd; new_pollfd.desc_type = APR_POLL_SOCKET; new_pollfd.reqevents = APR_POLLIN; new_pollfd.desc.s = c->aprsock; new_pollfd.client_data = c; apr_pollset_add(readbits, &new_pollfd); } #endif } /* --------------------------------------------------------- */ /* calculate and output results */ static int compradre(struct data * a, struct data * b) { if ((a->ctime) < (b->ctime)) return -1; if ((a->ctime) > (b->ctime)) return +1; return 0; } static int comprando(struct data * a, struct data * b) { if ((a->time) < (b->time)) return -1; if ((a->time) > (b->time)) return +1; return 0; } static int compri(struct data * a, struct data * b) { apr_interval_time_t p = a->time - a->ctime; apr_interval_time_t q = b->time - b->ctime; if (p < q) return -1; if (p > q) return +1; return 0; } static int compwait(struct data * a, struct data * b) { if ((a->waittime) < (b->waittime)) return -1; if ((a->waittime) > (b->waittime)) return 1; return 0; } static void output_results(int sig) { double timetaken; /*if (sig) { lasttime = apr_time_now(); }*/ timetaken = (double) (lasttime - start) / APR_USEC_PER_SEC; printf("\n\n"); printf("Server Software: %s\n", servername); printf("Server Hostname: %s\n", hostname); printf("Server Port: %hu\n", port); #ifdef USE_SSL if (is_ssl && ssl_info) { printf("SSL/TLS Protocol: %s\n", ssl_info); } #endif printf("\n"); printf("Document Path: %s\n", path); printf("Document Length: %" APR_SIZE_T_FMT " bytes\n", doclen); printf("\n"); printf("Number of Cores: %d\n", _num_cpus); printf("Concurrency Level: %d\n", concurrency); printf("Time taken for tests: %.3f seconds\n", timetaken); printf("Complete requests: %d\n", done); printf("Failed requests: %d\n", bad); if (bad) printf(" (Connect: %d, Receive: %d, Length: %d, Exceptions: %d)\n", err_conn, err_recv, err_length, err_except); printf("Write errors: %d\n", epipe); if (err_response) printf("Non-2xx responses: %d\n", err_response); if (keepalive) printf("Keep-Alive requests: %d\n", doneka); printf("Total transferred: %" APR_INT64_T_FMT " bytes\n", totalread); if (posting == 1) printf("Total POSTed: %" APR_INT64_T_FMT "\n", totalposted); if (posting == 2) printf("Total PUT: %" APR_INT64_T_FMT "\n", totalposted); printf("HTML transferred: %" APR_INT64_T_FMT " bytes\n", totalbread); /* avoid divide by zero */ if (timetaken && done) { printf("Requests per second: %.2f [#/sec] (mean)\n", (double) done / timetaken); printf("Time per request: %.3f [ms] (mean)\n", (double) concurrency * timetaken * 1000 / done); printf("Time per request: %.3f [ms] (mean, across all concurrent requests)\n", (double) timetaken * 1000 / done); printf("Transfer rate: %.2f [Kbytes/sec] received\n", (double) totalread / 1024 / timetaken); if (posting > 0) { printf(" %.2f kb/s sent\n", (double) totalposted / timetaken / 1024); printf(" %.2f kb/s total\n", (double) (totalread + totalposted) / timetaken / 1024); } } if (done > 0) { /* work out connection times */ int i; apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0; apr_time_t meancon, meantot, meand, meanwait; apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX, minwait = AB_MAX; apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0; apr_interval_time_t mediancon = 0, mediantot = 0, mediand = 0, medianwait = 0; double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0; for (i = 0; i < done; i++) { struct data *s = &stats[i]; mincon = ap_min(mincon, s->ctime); mintot = ap_min(mintot, s->time); mind = ap_min(mind, s->time - s->ctime); minwait = ap_min(minwait, s->waittime); maxcon = ap_max(maxcon, s->ctime); maxtot = ap_max(maxtot, s->time); maxd = ap_max(maxd, s->time - s->ctime); maxwait = ap_max(maxwait, s->waittime); totalcon += s->ctime; total += s->time; totald += s->time - s->ctime; totalwait += s->waittime; } meancon = totalcon / done; meantot = total / done; meand = totald / done; meanwait = totalwait / done; /* calculating the sample variance: the sum of the squared deviations, divided by n-1 */ for (i = 0; i < done; i++) { struct data *s = &stats[i]; double a; a = ((double)s->time - meantot); sdtot += a * a; a = ((double)s->ctime - meancon); sdcon += a * a; a = ((double)s->time - (double)s->ctime - meand); sdd += a * a; a = ((double)s->waittime - meanwait); sdwait += a * a; } sdtot = (done > 1) ? sqrt(sdtot / (done - 1)) : 0; sdcon = (done > 1) ? sqrt(sdcon / (done - 1)) : 0; sdd = (done > 1) ? sqrt(sdd / (done - 1)) : 0; sdwait = (done > 1) ? sqrt(sdwait / (done - 1)) : 0; /* * XXX: what is better; this hideous cast of the compradre function; or * the four warnings during compile ? dirkx just does not know and * hates both/ */ qsort(stats, done, sizeof(struct data), (int (*) (const void *, const void *)) compradre); if ((done > 1) && (done % 2)) mediancon = (stats[done / 2].ctime + stats[done / 2 + 1].ctime) / 2; else mediancon = stats[done / 2].ctime; qsort(stats, done, sizeof(struct data), (int (*) (const void *, const void *)) compri); if ((done > 1) && (done % 2)) mediand = (stats[done / 2].time + stats[done / 2 + 1].time \ -stats[done / 2].ctime - stats[done / 2 + 1].ctime) / 2; else mediand = stats[done / 2].time - stats[done / 2].ctime; qsort(stats, done, sizeof(struct data), (int (*) (const void *, const void *)) compwait); if ((done > 1) && (done % 2)) medianwait = (stats[done / 2].waittime + stats[done / 2 + 1].waittime) / 2; else medianwait = stats[done / 2].waittime; qsort(stats, done, sizeof(struct data), (int (*) (const void *, const void *)) comprando); if ((done > 1) && (done % 2)) mediantot = (stats[done / 2].time + stats[done / 2 + 1].time) / 2; else mediantot = stats[done / 2].time; printf("\nConnection Times (ms)\n"); /* * Reduce stats from apr time to milliseconds */ mincon = ap_round_ms(mincon); mind = ap_round_ms(mind); minwait = ap_round_ms(minwait); mintot = ap_round_ms(mintot); meancon = ap_round_ms(meancon); meand = ap_round_ms(meand); meanwait = ap_round_ms(meanwait); meantot = ap_round_ms(meantot); mediancon = ap_round_ms(mediancon); mediand = ap_round_ms(mediand); medianwait = ap_round_ms(medianwait); mediantot = ap_round_ms(mediantot); maxcon = ap_round_ms(maxcon); maxd = ap_round_ms(maxd); maxwait = ap_round_ms(maxwait); maxtot = ap_round_ms(maxtot); sdcon = ap_double_ms(sdcon); sdd = ap_double_ms(sdd); sdwait = ap_double_ms(sdwait); sdtot = ap_double_ms(sdtot); if (confidence) { #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4" APR_TIME_T_FMT " %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n" printf(" min mean[+/-sd] median max\n"); printf("Connect: " CONF_FMT_STRING, mincon, meancon, sdcon, mediancon, maxcon); printf("Processing: " CONF_FMT_STRING, mind, meand, sdd, mediand, maxd); printf("Waiting: " CONF_FMT_STRING, minwait, meanwait, sdwait, medianwait, maxwait); printf("Total: " CONF_FMT_STRING, mintot, meantot, sdtot, mediantot, maxtot); #undef CONF_FMT_STRING #define SANE(what,mean,median,sd) \ { \ double d = (double)mean - median; \ if (d < 0) d = -d; \ if (d > 2 * sd ) \ printf("ERROR: The median and mean for " what " are more than twice the standard\n" \ " deviation apart. These results are NOT reliable.\n"); \ else if (d > sd ) \ printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \ " These results are probably not that reliable.\n"); \ } SANE("the initial connection time", meancon, mediancon, sdcon); SANE("the processing time", meand, mediand, sdd); SANE("the waiting time", meanwait, medianwait, sdwait); SANE("the total time", meantot, mediantot, sdtot); } else { printf(" min avg max\n"); #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n" printf("Connect: " CONF_FMT_STRING, mincon, meancon, maxcon); printf("Processing: " CONF_FMT_STRING, mintot - mincon, meantot - meancon, maxtot - maxcon); printf("Total: " CONF_FMT_STRING, mintot, meantot, maxtot); #undef CONF_FMT_STRING } /* Sorted on total connect times */ if (percentile && (done > 1)) { printf("\nPercentage of the requests served within a certain time (ms)\n"); for (i = 0; i < sizeof(percs) / sizeof(int); i++) { if (percs[i] <= 0) printf(" 0%% <0> (never)\n"); else if (percs[i] >= 100) printf(" 100%% %5" APR_TIME_T_FMT " (longest request)\n", ap_round_ms(stats[done - 1].time)); else printf(" %d%% %5" APR_TIME_T_FMT "\n", percs[i], ap_round_ms(stats[(int) (done * percs[i] / 100)].time)); } } if (csvperc) { FILE *out = fopen(csvperc, "w"); if (!out) { perror("Cannot open CSV output file"); exit(1); } fprintf(out, "" "Percentage served" "," "Time in ms" "\n"); for (i = 0; i < 100; i++) { double t; if (i == 0) t = ap_double_ms(stats[0].time); else if (i == 100) t = ap_double_ms(stats[done - 1].time); else t = ap_double_ms(stats[(int) (0.5 + done * i / 100.0)].time); fprintf(out, "%d,%.3f\n", i, t); } fclose(out); } if (gnuplot) { FILE *out = fopen(gnuplot, "w"); char tmstring[APR_CTIME_LEN]; if (!out) { perror("Cannot open gnuplot output file"); exit(1); } fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n"); for (i = 0; i < done; i++) { (void) apr_ctime(tmstring, stats[i].starttime); fprintf(out, "%s\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\n", tmstring, apr_time_sec(stats[i].starttime), ap_round_ms(stats[i].ctime), ap_round_ms(stats[i].time - stats[i].ctime), ap_round_ms(stats[i].time), ap_round_ms(stats[i].waittime)); } fclose(out); } } if (sig) { exit(1); } } /* --------------------------------------------------------- */ /* calculate and output results in HTML */ static void output_html_results(void) { double timetaken = (double) (lasttime - start) / APR_USEC_PER_SEC; printf("\n\n<table %s>\n", tablestring); printf("<tr %s><th colspan=2 %s>Server Software:</th>" "<td colspan=2 %s>%s</td></tr>\n", trstring, tdstring, tdstring, servername); printf("<tr %s><th colspan=2 %s>Server Hostname:</th>" "<td colspan=2 %s>%s</td></tr>\n", trstring, tdstring, tdstring, hostname); printf("<tr %s><th colspan=2 %s>Server Port:</th>" "<td colspan=2 %s>%hu</td></tr>\n", trstring, tdstring, tdstring, port); printf("<tr %s><th colspan=2 %s>Document Path:</th>" "<td colspan=2 %s>%s</td></tr>\n", trstring, tdstring, tdstring, path); printf("<tr %s><th colspan=2 %s>Document Length:</th>" "<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n", trstring, tdstring, tdstring, doclen); printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>" "<td colspan=2 %s>%d</td></tr>\n", trstring, tdstring, tdstring, concurrency); printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>" "<td colspan=2 %s>%.3f seconds</td></tr>\n", trstring, tdstring, tdstring, timetaken); printf("<tr %s><th colspan=2 %s>Complete requests:</th>" "<td colspan=2 %s>%d</td></tr>\n", trstring, tdstring, tdstring, done); printf("<tr %s><th colspan=2 %s>Failed requests:</th>" "<td colspan=2 %s>%d</td></tr>\n", trstring, tdstring, tdstring, bad); if (bad) printf("<tr %s><td colspan=4 %s > (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n", trstring, tdstring, err_conn, err_length, err_except); if (err_response) printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>" "<td colspan=2 %s>%d</td></tr>\n", trstring, tdstring, tdstring, err_response); if (keepalive) printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>" "<td colspan=2 %s>%d</td></tr>\n", trstring, tdstring, tdstring, doneka); printf("<tr %s><th colspan=2 %s>Total transferred:</th>" "<td colspan=2 %s>%" APR_INT64_T_FMT " bytes</td></tr>\n", trstring, tdstring, tdstring, totalread); if (posting == 1) printf("<tr %s><th colspan=2 %s>Total POSTed:</th>" "<td colspan=2 %s>%" APR_INT64_T_FMT "</td></tr>\n", trstring, tdstring, tdstring, totalposted); if (posting == 2) printf("<tr %s><th colspan=2 %s>Total PUT:</th>" "<td colspan=2 %s>%" APR_INT64_T_FMT "</td></tr>\n", trstring, tdstring, tdstring, totalposted); printf("<tr %s><th colspan=2 %s>HTML transferred:</th>" "<td colspan=2 %s>%" APR_INT64_T_FMT " bytes</td></tr>\n", trstring, tdstring, tdstring, totalbread); /* avoid divide by zero */ if (timetaken) { printf("<tr %s><th colspan=2 %s>Requests per second:</th>" "<td colspan=2 %s>%.2f</td></tr>\n", trstring, tdstring, tdstring, (double) done * 1000 / timetaken); printf("<tr %s><th colspan=2 %s>Transfer rate:</th>" "<td colspan=2 %s>%.2f kb/s received</td></tr>\n", trstring, tdstring, tdstring, (double) totalread / timetaken); if (posting > 0) { printf("<tr %s><td colspan=2 %s>&nbsp;</td>" "<td colspan=2 %s>%.2f kb/s sent</td></tr>\n", trstring, tdstring, tdstring, (double) totalposted / timetaken); printf("<tr %s><td colspan=2 %s>&nbsp;</td>" "<td colspan=2 %s>%.2f kb/s total</td></tr>\n", trstring, tdstring, tdstring, (double) (totalread + totalposted) / timetaken); } } { /* work out connection times */ int i; apr_interval_time_t totalcon = 0, total = 0; apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX; apr_interval_time_t maxcon = 0, maxtot = 0; for (i = 0; i < done; i++) { struct data *s = &stats[i]; mincon = ap_min(mincon, s->ctime); mintot = ap_min(mintot, s->time); maxcon = ap_max(maxcon, s->ctime); maxtot = ap_max(maxtot, s->time); totalcon += s->ctime; total += s->time; } /* * Reduce stats from apr time to milliseconds */ mincon = ap_round_ms(mincon); mintot = ap_round_ms(mintot); maxcon = ap_round_ms(maxcon); maxtot = ap_round_ms(maxtot); totalcon = ap_round_ms(totalcon); total = ap_round_ms(total); if (done > 0) { /* avoid division by zero (if 0 done) */ printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n", trstring, tdstring); printf("<tr %s><th %s>&nbsp;</th> <th %s>min</th> <th %s>avg</th> <th %s>max</th></tr>\n", trstring, tdstring, tdstring, tdstring, tdstring); printf("<tr %s><th %s>Connect:</th>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n", trstring, tdstring, tdstring, mincon, tdstring, totalcon / done, tdstring, maxcon); printf("<tr %s><th %s>Processing:</th>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n", trstring, tdstring, tdstring, mintot - mincon, tdstring, (total / done) - (totalcon / done), tdstring, maxtot - maxcon); printf("<tr %s><th %s>Total:</th>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td>" "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n", trstring, tdstring, tdstring, mintot, tdstring, total / done, tdstring, maxtot); } printf("</table>\n"); } } /* --------------------------------------------------------- */ /* start asnchronous non-blocking connection */ static void start_connect(struct connection * c) { apr_status_t rv; int sock_fd; if (!(_started < _requests)) return; c->read = 0; c->bread = 0; c->keepalive = 0; c->keepalive_cnt = 0; c->cbx = 0; c->gotheader = 0; c->rwrite = 0; if (c->ctx) apr_pool_clear(c->ctx); else apr_pool_create(&c->ctx, cntxt); if ((rv = apr_socket_create(&c->aprsock, _destsa->family, SOCK_STREAM, 0, c->ctx)) != APR_SUCCESS) { apr_err("socket", rv); } #ifndef HAVE_MTCP if (windowsize != 0) { rv = apr_socket_opt_set(c->aprsock, APR_SO_SNDBUF, windowsize); if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) { apr_err("socket send buffer", rv); } rv = apr_socket_opt_set(c->aprsock, APR_SO_RCVBUF, windowsize); if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) { apr_err("socket receive buffer", rv); } } #endif if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1)) != APR_SUCCESS) { apr_err("socket nonblock", rv); } c->start = _lasttime = apr_time_now(); #ifdef USE_SSL if (is_ssl) { BIO *bio; apr_os_sock_t fd; if ((c->ssl = SSL_new(ssl_ctx)) == NULL) { BIO_printf(bio_err, "SSL_new failed.\n"); ERR_print_errors(bio_err); exit(1); } ssl_rand_seed(); apr_os_sock_get(&fd, c->aprsock); bio = BIO_new_socket(fd, BIO_NOCLOSE); SSL_set_bio(c->ssl, bio, bio); SSL_set_connect_state(c->ssl); if (verbosity >= 4) { BIO_set_callback(bio, ssl_print_cb); BIO_set_callback_arg(bio, (void *)bio_err); } } else { c->ssl = NULL; } #endif if ((rv = apr_socket_connect(c->aprsock, _destsa)) != APR_SUCCESS) { if (APR_STATUS_IS_EINPROGRESS(rv)) { apr_pollfd_t new_pollfd; c->state = STATE_CONNECTING; c->rwrite = 0; new_pollfd.desc_type = APR_POLL_SOCKET; new_pollfd.reqevents = APR_POLLOUT; new_pollfd.desc.s = c->aprsock; new_pollfd.client_data = c; apr_pollset_add(readbits, &new_pollfd); return; } else { apr_pollfd_t remove_pollfd; remove_pollfd.desc_type = APR_POLL_SOCKET; remove_pollfd.desc.s = c->aprsock; apr_pollset_remove(readbits, &remove_pollfd); apr_socket_close(c->aprsock); if (bad > 100) { fprintf(stderr, "\nTest aborted after 100 failures\n\n"); apr_err("apr_socket_connect()", rv); } pthread_mutex_lock(&err_mutex); err_conn++; bad++; pthread_mutex_unlock(&err_mutex); c->state = STATE_UNCONNECTED; start_connect(c); return; } } /* connected first time */ c->state = STATE_CONNECTED; _started++; #ifdef USE_SSL if (c->ssl) { ssl_proceed_handshake(c); } else #endif { write_request(c); } } /* --------------------------------------------------------- */ /* close down connection and save stats */ static void close_connection(struct connection * c) { int i; int sock_fd; apr_os_sock_get(&sock_fd, c->aprsock); c->keepalive_cnt = 0; if (c->read == 0 && c->keepalive) { /* * server has legitimately shut down an idle keep alive request */ if (_good) _good--; /* connection never happened */ } else { if (_good == 1) { /* first time here */ _doclen = c->bread; } else if (c->bread != _doclen) { pthread_mutex_lock(&err_mutex); bad++; err_length++; pthread_mutex_unlock(&err_mutex); } /* save out time */ if (_done < _requests) { struct data *s = &_stats[_done]; _done++; c->done = _lasttime = apr_time_now(); s->starttime = c->start; s->ctime = ap_max(0, c->connect - c->start); s->time = ap_max(0, c->done - c->start); s->waittime = ap_max(0, c->beginread - c->endwrite); if (heartbeatres && !(_done % heartbeatres)) { fprintf(stderr, "CPU%d: Completed %d requests\n", _cpu, _done); fflush(stderr); } } } { apr_pollfd_t remove_pollfd; remove_pollfd.desc_type = APR_POLL_SOCKET; remove_pollfd.desc.s = c->aprsock; apr_pollset_remove(readbits, &remove_pollfd); #ifdef USE_SSL if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); c->ssl = NULL; } #endif apr_socket_close(c->aprsock); } c->state = STATE_UNCONNECTED; /* connect again */ start_connect(c); return; } /* --------------------------------------------------------- */ /* read data from connection */ static void read_connection(struct connection * c) { apr_size_t r; apr_status_t status; char *part; char respcode[4]; /* 3 digits and null */ r = sizeof(buffer); #ifdef USE_SSL if (c->ssl) { status = SSL_read(c->ssl, buffer, r); if (status <= 0) { int scode = SSL_get_error(c->ssl, status); if (scode == SSL_ERROR_ZERO_RETURN) { /* connection closed cleanly: */ _good++; close_connection(c); } else if (scode != SSL_ERROR_WANT_WRITE && scode != SSL_ERROR_WANT_READ) { /* some fatal error: */ c->read = 0; BIO_printf(bio_err, "SSL read failed - closing connection\n"); ERR_print_errors(bio_err); close_connection(c); } return; } r = status; } else #endif { status = apr_socket_recv(c->aprsock, buffer, &r); if (APR_STATUS_IS_EAGAIN(status)) return; else if (r == 0 && APR_STATUS_IS_EOF(status)) { _good++; close_connection(c); return; } /* catch legitimate fatal apr_socket_recv errors */ else if (status != APR_SUCCESS) { pthread_mutex_lock(&err_mutex); err_recv++; pthread_mutex_unlock(&err_mutex); if (recverrok) { pthread_mutex_lock(&err_mutex); bad++; pthread_mutex_unlock(&err_mutex); close_connection(c); if (verbosity >= 1) { char buf[120]; fprintf(stderr,"%s: %s (%d)\n", "apr_socket_recv", apr_strerror(status, buf, sizeof buf), status); } return; } else { apr_err("apr_socket_recv", status); } } } _totalread += r; if (c->read == 0) { c->beginread = apr_time_now(); } c->read += r; if (!c->gotheader) { char *s; int l = 4; apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */ int tocopy = (space < r) ? space : r; #ifdef NOT_ASCII apr_size_t inbytes_left = space, outbytes_left = space; status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left, c->cbuff + c->cbx, &outbytes_left); if (status || inbytes_left || outbytes_left) { fprintf(stderr, "only simple translation is supported (%d/%" APR_SIZE_T_FMT "/%" APR_SIZE_T_FMT ")\n", status, inbytes_left, outbytes_left); exit(1); } #else memcpy(c->cbuff + c->cbx, buffer, space); #endif /* NOT_ASCII */ c->cbx += tocopy; space -= tocopy; c->cbuff[c->cbx] = 0; /* terminate for benefit of strstr */ if (verbosity >= 2) { printf("LOG: header received:\n%s\n", c->cbuff); } s = strstr(c->cbuff, "\r\n\r\n"); /* * this next line is so that we talk to NCSA 1.5 which blatantly * breaks the http specifaction */ if (!s) { s = strstr(c->cbuff, "\n\n"); l = 2; } if (!s) { /* read rest next time */ if (space) { return; } else { /* header is in invalid or too big - close connection */ apr_pollfd_t remove_pollfd; remove_pollfd.desc_type = APR_POLL_SOCKET; remove_pollfd.desc.s = c->aprsock; apr_pollset_remove(readbits, &remove_pollfd); apr_socket_close(c->aprsock); if (bad > 100) { err("\nTest aborted after 100 failures\n\n"); } printf("%d trying to acquire err_mutex\n", _cpu); pthread_mutex_lock(&err_mutex); err_response++; bad++; pthread_mutex_unlock(&err_mutex); start_connect(c); } } else { /* have full header */ if (!_good) { /* * this is first time, extract some interesting info */ char *p, *q; p = strstr(c->cbuff, "Server:"); q = servername; if (p) { p += 8; while (*p > 32) *q++ = *p++; } *q = 0; } /* * XXX: this parsing isn't even remotely HTTP compliant... but in * the interest of speed it doesn't totally have to be, it just * needs to be extended to handle whatever servers folks want to * test against. -djg */ /* check response code */ part = strstr(c->cbuff, "HTTP"); /* really HTTP/1.x_ */ if (part && strlen(part) > strlen("HTTP/1.x_")) { strncpy(respcode, (part + strlen("HTTP/1.x_")), 3); respcode[3] = '\0'; } else { strcpy(respcode, "500"); } if (respcode[0] != '2') { pthread_mutex_lock(&err_mutex); err_response++; pthread_mutex_unlock(&err_mutex); if (verbosity >= 2) printf("WARNING: Response code not 2xx (%s)\n", respcode); } else if (verbosity >= 3) { printf("LOG: Response code = %s\n", respcode); } c->gotheader = 1; *s = 0; /* terminate at end of header */ if (keepalive && (strstr(c->cbuff, "Keep-Alive") || strstr(c->cbuff, "keep-alive"))) { /* for benefit of MSIIS */ char *cl; cl = strstr(c->cbuff, "Content-Length:"); /* handle NCSA, which sends Content-length: */ if (!cl) cl = strstr(c->cbuff, "Content-length:"); if (cl) { c->keepalive = 1; /* response to HEAD doesn't have entity body */ c->length = posting >= 0 ? atoi(cl + 16) : 0; } /* The response may not have a Content-Length header */ if (!cl) { c->keepalive = 1; c->length = 0; } } c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy; _totalbread += c->bread; } } else { /* outside header, everything we have read is entity body */ c->bread += r; _totalbread += r; } if (c->keepalive && (c->bread >= c->length)) { /* finished a keep-alive connection */ _good++; /* save out time */ if (_good == 1) { /* first time here */ _doclen = c->bread; } else if (c->bread != _doclen) { pthread_mutex_lock(&err_mutex); bad++; err_length++; pthread_mutex_unlock(&err_mutex); } if (_done < _requests) { struct data *s = &_stats[_done]; _done++; _doneka++; c->done = apr_time_now(); s->starttime = c->start; s->ctime = ap_max(0, c->connect - c->start); s->time = ap_max(0, c->done - c->start); s->waittime = ap_max(0, c->beginread - c->endwrite); if (heartbeatres && !(_done % heartbeatres)) { fprintf(stderr, "CPU%d:Completed %d requests\n", _cpu, _done); fflush(stderr); } } if(keepalive_cnt > 0){ c->keepalive_cnt++; int sock_fd; apr_os_sock_get(&sock_fd, c->aprsock); /*printf("CPU%d-Socket%d: %d/%d\n", _cpu, sock_fd, c->keepalive_cnt, keepalive_cnt);*/ if(c->keepalive_cnt >= keepalive_cnt){ c->keepalive = 0; close_connection(c); return; } } c->keepalive = 0; c->length = 0; c->gotheader = 0; c->cbx = 0; c->read = c->bread = 0; /* zero connect time with keep-alive */ c->start = c->connect = _lasttime = apr_time_now(); write_request(c); } } /* ------------------------------------------------------- */ /* Thread setup and cleanup functions */ #ifdef USE_SSL void pthreads_locking_callback(int mode, int type, char *file, int line){ if(mode & CRYPTO_LOCK){ pthread_mutex_lock(&(lock_cs[type])); lock_count[type]++; } else { pthread_mutex_unlock(&(lock_cs[type])); } } unsigned long pthreads_thread_id(void){ unsigned long ret; ret = (unsigned long)pthread_self(); return ret; } #endif void thread_setup(void){ int i; pthread_mutex_init(&stat_mutex, NULL); pthread_mutex_init(&err_mutex, NULL); #ifdef USE_SSL lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long)); for(i = 0; i < CRYPTO_num_locks(); i++){ lock_count[i] = 0; pthread_mutex_init(&(lock_cs[i]), NULL); } CRYPTO_set_id_callback((unsigned long (*)())pthreads_thread_id); CRYPTO_set_locking_callback((void(*)())pthreads_locking_callback); #endif } void thread_cleanup(void){ int i; pthread_mutex_destroy(&stat_mutex); pthread_mutex_destroy(&err_mutex); #ifdef USE_SSL CRYPTO_set_locking_callback(NULL); for(i = 0; i < CRYPTO_num_locks(); i++){ pthread_mutex_destroy(&(lock_cs[i])); } OPENSSL_free(lock_cs); OPENSSL_free(lock_count); #endif } /* --------------------------------------------------------- */ /* run the tests */ void *testMain(void *arg){ _cpu = *(int *)arg; int i; apr_int16_t rv; apr_status_t status; printf("%d:testMain\n", _cpu); _concurrency = concurrency / _num_cpus; if(_cpu < (concurrency % _num_cpus)) _concurrency++; _requests = requests / _num_cpus; if(_cpu < (requests % _num_cpus)) _requests++; if (isproxy) { connecthost = apr_pstrdup(cntxt, proxyhost); _connectport = proxyport; } else { connecthost = apr_pstrdup(cntxt, hostname); _connectport = port; if(num_ports != 1){ _connectport += (_cpu % num_ports); } } /* This only needs to be done once */ if ((rv = apr_sockaddr_info_get(&_destsa, connecthost, APR_UNSPEC, _connectport, 0, cntxt)) != APR_SUCCESS) { char buf[120]; apr_snprintf(buf, sizeof(buf), "apr_sockaddr_info_get() for %s", connecthost); apr_err(buf, rv); } printf("CPU%d connecting to port %d\n", _cpu, _connectport); #ifdef HAVE_MTCP mtcp_core_affinitize(_cpu); g_mctx[_cpu] = mtcp_create_context(_cpu); if (g_mctx[_cpu] == NULL){ perror("mtcp_create_context"); return NULL; } mtcp_init_rss(g_mctx[_cpu], INADDR_ANY, 1, _destsa->sa.sin.sin_addr.s_addr, _destsa->sa.sin.sin_port); #else core_affinitize(_cpu); #endif apr_pool_create(&_cntxt, cntxt); readbits = NULL; if ((status = apr_pollset_create(&readbits, _concurrency*4, _cntxt, APR_POLLSET_THREADSAFE)) != APR_SUCCESS) { apr_err("apr_pollset_create failed", status); } _lasttime = apr_time_now(); con = calloc(_concurrency, sizeof(struct connection)); _stats = calloc(_requests, sizeof(struct data)); /* initialise lots of requests */ for (i = 0; i < _concurrency; i++) { con[i].socknum = i; start_connect(&con[i]); } if (request_append == 1) req_p = reqdata; do { apr_int32_t n; const apr_pollfd_t *pollresults; n = _concurrency; do { status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults); } while (APR_STATUS_IS_EINTR(status)); if (status != APR_SUCCESS) apr_err("apr_poll", status); if (!n) { err("\nServer timed out\n\n"); } for (i = 0; i < n; i++) { const apr_pollfd_t *next_fd = &(pollresults[i]); struct connection *c; c = next_fd->client_data; /* * If the connection isn't connected how can we check it? */ if (c->state == STATE_UNCONNECTED){ continue; } rv = next_fd->rtnevents; #ifdef USE_SSL if (c->state == STATE_CONNECTED && c->ssl && SSL_in_init(c->ssl)) { ssl_proceed_handshake(c); continue; } #endif /* * Notes: APR_POLLHUP is set after FIN is received on some * systems, so treat that like APR_POLLIN so that we try to read * again. * * Some systems return APR_POLLERR with APR_POLLHUP. We need to * call read_connection() for APR_POLLHUP, so check for * APR_POLLHUP first so that a closed connection isn't treated * like an I/O error. If it is, we never figure out that the * connection is done and we loop here endlessly calling * apr_poll(). */ if ((rv & APR_POLLIN) || (rv & APR_POLLPRI) || (rv & APR_POLLHUP)) read_connection(c); if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) { pthread_mutex_lock(&err_mutex); bad++; err_except++; pthread_mutex_unlock(&err_mutex); start_connect(c); continue; } if (rv & APR_POLLOUT) { if (c->state == STATE_CONNECTING) { apr_pollfd_t remove_pollfd; rv = apr_socket_connect(c->aprsock, _destsa); remove_pollfd.desc_type = APR_POLL_SOCKET; remove_pollfd.desc.s = c->aprsock; apr_pollset_remove(readbits, &remove_pollfd); if (rv != APR_SUCCESS) { if (bad> 100) { fprintf(stderr, "\nTest aborted after 100 failures\n\n"); apr_err("apr_socket_connect()", rv); } pthread_mutex_lock(&err_mutex); bad++; err_conn++; pthread_mutex_unlock(&err_mutex); c->state = STATE_UNCONNECTED; start_connect(c); continue; } else { c->state = STATE_CONNECTED; _started++; #ifdef USE_SSL if (c->ssl) ssl_proceed_handshake(c); else #endif write_request(c); } } else { write_request(c); } } /* * When using a select based poll every time we check the bits * are reset. In 1.3's ab we copied the FD_SET's each time * through, but here we're going to check the state and if the * connection is in STATE_READ or STATE_CONNECTING we'll add the * socket back in as APR_POLLIN. */ if (c->state == STATE_READ) { apr_pollfd_t new_pollfd; new_pollfd.desc_type = APR_POLL_SOCKET; new_pollfd.reqevents = APR_POLLIN; new_pollfd.desc.s = c->aprsock; new_pollfd.client_data = c; apr_pollset_add(readbits, &new_pollfd); } } } while (_lasttime < stoptime && _done < _requests); printf("%d:End of main loop. %d %d\n", _cpu, _requests, _done); pthread_mutex_lock(&stat_mutex); for(i = 0; i < _done; i++){ memcpy(&stats[done+i], &_stats[i], sizeof(struct data)); } totalread += _totalread; totalbread += _totalbread; totalposted += _totalposted; started += _started; done += _done; doneka += _doneka; good += _good; lasttime = _lasttime; doclen = _doclen; pthread_mutex_unlock(&stat_mutex); printf("Total done:%d\n", done); #ifdef HAVE_MTCP mtcp_destroy_context(g_mctx[_cpu]); #endif return NULL; } static void test(void) { int i; apr_int16_t rv; apr_status_t status; int snprintf_res = 0; #ifdef NOT_ASCII apr_size_t inbytes_left, outbytes_left; #endif #ifdef HAVE_MTCP mtcp_init("config/mtcp.conf"); #endif if (!use_html) { printf("Benchmarking %s ", hostname); if (isproxy) printf("[through %s:%d] ", proxyhost, proxyport); printf("(be patient)%s", (heartbeatres ? "\n" : "...\n")); fflush(stdout); } stats = calloc(requests, sizeof(struct data)); /* add default headers if necessary */ if (!opt_host) { /* Host: header not overridden, add default value to hdrs */ hdrs = apr_pstrcat(cntxt, hdrs, "Host: ", host_field, colonhost, "\r\n", NULL); } else { /* Header overridden, no need to add, as it is already in hdrs */ } if (!opt_useragent) { /* User-Agent: header not overridden, add default value to hdrs */ hdrs = apr_pstrcat(cntxt, hdrs, "User-Agent: ApacheBench/", AP_AB_BASEREVISION, "\r\n", NULL); } else { /* Header overridden, no need to add, as it is already in hdrs */ } if (!opt_accept) { /* Accept: header not overridden, add default value to hdrs */ hdrs = apr_pstrcat(cntxt, hdrs, "Accept: */*\r\n", NULL); } else { /* Header overridden, no need to add, as it is already in hdrs */ } /* setup request */ if (posting <= 0) { snprintf_res = apr_snprintf(request, sizeof(_request), "%s %s HTTP/1.0\r\n" "%s" "%s" "%s" "%s" "\r\n", (posting == 0) ? "GET" : "HEAD", (isproxy) ? fullurl : path, keepalive ? "Connection: Keep-Alive\r\n" : "", cookie, auth, hdrs); } else { snprintf_res = apr_snprintf(request, sizeof(_request), "%s %s HTTP/1.0\r\n" "%s" "%s" "%s" "Content-length: %" APR_SIZE_T_FMT "\r\n" "Content-type: %s\r\n" "%s" "\r\n", (posting == 1) ? "POST" : "PUT", (isproxy) ? fullurl : path, keepalive ? "Connection: Keep-Alive\r\n" : "", cookie, auth, postlen, (content_type[0]) ? content_type : "text/plain", hdrs); } if (snprintf_res >= sizeof(_request)) { err("Request too long\n"); } if (verbosity >= 2) printf("INFO: %s header == \n---\n%s\n---\n", (posting == 2) ? "PUT" : "POST", request); reqlen = strlen(request); /* * Combine headers and (optional) post file into one contineous buffer */ if (posting >= 1) { char *buff = malloc(postlen + reqlen + 1); if (!buff) { fprintf(stderr, "error creating request buffer: out of memory\n"); return; } strcpy(buff, request); memcpy(buff + reqlen, postdata, postlen); request = buff; } #ifdef NOT_ASCII inbytes_left = outbytes_left = reqlen; status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left, request, &outbytes_left); if (status || inbytes_left || outbytes_left) { fprintf(stderr, "only simple translation is supported (%d/%" APR_SIZE_T_FMT "/%" APR_SIZE_T_FMT ")\n", status, inbytes_left, outbytes_left); exit(1); } #endif /* NOT_ASCII */ /* ok - lets start */ start = lasttime = apr_time_now(); stoptime = tlimit ? (start + apr_time_from_sec(tlimit)) : AB_MAX; #ifdef SIGINT /* Output the results if the user terminates the run early. */ #ifdef HAVE_MTCP mtcp_register_signal(SIGINT, output_results); #else apr_signal(SIGINT, output_results); #endif #endif thread_setup(); /* Allocate connections to each thread * and create threads*/ for(i = 0; i < _num_cpus; i++){ thread_cpu[i] = i; if(pthread_create(&app_thread[i], NULL, testMain, (void *)&thread_cpu[i])){ perror("pthread_create"); exit(-1); } } for(i = 0; i < _num_cpus; i++){ pthread_join(app_thread[i], NULL); } thread_cleanup(); if (heartbeatres) fprintf(stderr, "Finished %d requests\n", done); else printf("..done\n"); if (use_html) output_html_results(); else output_results(0); #ifdef HAVE_MTCP mtcp_destroy(); #endif } /* ------------------------------------------------------- */ /* display copyright information */ static void copyright(void) { if (!use_html) { printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 655654 $>"); printf("Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n"); printf("Licensed to The Apache Software Foundation, http://www.apache.org/\n"); printf("\n"); } else { printf("<p>\n"); printf(" This is ApacheBench, Version %s <i>&lt;%s&gt;</i><br>\n", AP_AB_BASEREVISION, "$Revision: 655654 $"); printf(" Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n"); printf(" Licensed to The Apache Software Foundation, http://www.apache.org/<br>\n"); printf("</p>\n<p>\n"); } } /* display usage information */ static void usage(const char *progname) { fprintf(stderr, "Usage: %s [options] [http" #ifdef USE_SSL "[s]" #endif "://]hostname[:port]/path\n", progname); /* 80 column ruler: ******************************************************************************** */ fprintf(stderr, "Options are:\n"); fprintf(stderr, " -n requests Number of requests to perform\n"); fprintf(stderr, " -c concurrency Number of multiple requests to make\n"); fprintf(stderr, " -t timelimit Seconds to max. wait for responses\n"); fprintf(stderr, " -N cpus Number of cpus to use\n"); fprintf(stderr, " -l ports Number of ports to use. (Port number starts from 80)\n"); fprintf(stderr, " -b windowsize Size of TCP send/receive buffer, in bytes\n"); fprintf(stderr, " -p postfile File containing data to POST. Remember also to set -T\n"); fprintf(stderr, " -R reqfile File containing lines to append to each request URL\n"); fprintf(stderr, " -u putfile File containing data to PUT. Remember also to set -T\n"); fprintf(stderr, " -T content-type Content-type header for POSTing, eg.\n"); fprintf(stderr, " 'application/x-www-form-urlencoded'\n"); fprintf(stderr, " Default is 'text/plain'\n"); fprintf(stderr, " -v verbosity How much troubleshooting info to print\n"); fprintf(stderr, " -w Print out results in HTML tables\n"); fprintf(stderr, " -i Use HEAD instead of GET\n"); fprintf(stderr, " -x attributes String to insert as table attributes\n"); fprintf(stderr, " -y attributes String to insert as tr attributes\n"); fprintf(stderr, " -z attributes String to insert as td or th attributes\n"); fprintf(stderr, " -C attribute Add cookie, eg. 'Apache=1234. (repeatable)\n"); fprintf(stderr, " -H attribute Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n"); fprintf(stderr, " Inserted after all normal header lines. (repeatable)\n"); fprintf(stderr, " -A attribute Add Basic WWW Authentication, the attributes\n"); fprintf(stderr, " are a colon separated username and password.\n"); fprintf(stderr, " -P attribute Add Basic Proxy Authentication, the attributes\n"); fprintf(stderr, " are a colon separated username and password.\n"); fprintf(stderr, " -X proxy:port Proxyserver and port number to use\n"); fprintf(stderr, " -V Print version number and exit\n"); fprintf(stderr, " -k reqs/conn Use HTTP KeepAlive feature. 0 indicates no limit in reqs/conn.\n"); fprintf(stderr, " -d Do not show percentiles served table.\n"); fprintf(stderr, " -S Do not show confidence estimators and warnings.\n"); fprintf(stderr, " -g filename Output collected data to gnuplot format file.\n"); fprintf(stderr, " -e filename Output CSV file with percentages served\n"); fprintf(stderr, " -r Don't exit on socket receive errors.\n"); fprintf(stderr, " -h Display usage information (this message)\n"); #ifdef USE_SSL #ifndef OPENSSL_NO_SSL2 #define SSL2_HELP_MSG "SSL2, " #else #define SSL2_HELP_MSG "" #endif #ifdef HAVE_TLSV1_X #define TLS1_X_HELP_MSG ", TLS1.1, TLS1.2" #else #define TLS1_X_HELP_MSG "" #endif fprintf(stderr, " -Z ciphersuite Specify SSL/TLS cipher suite (See openssl ciphers)\n"); fprintf(stderr, " -f protocol Specify SSL/TLS protocol\n"); fprintf(stderr, " (" SSL2_HELP_MSG "SSL3, TLS1" TLS1_X_HELP_MSG " or ALL)\n"); #endif exit(EINVAL); } /* ------------------------------------------------------- */ /* split URL into parts */ static int parse_url(char *url) { char *cp; char *h; char *scope_id; apr_status_t rv; /* Save a copy for the proxy */ fullurl = apr_pstrdup(cntxt, url); if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) { url += 7; #ifdef USE_SSL is_ssl = 0; #endif } else #ifdef USE_SSL if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) { url += 8; is_ssl = 1; } #else if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) { fprintf(stderr, "SSL not compiled in; no https support\n"); exit(1); } #endif if ((cp = strchr(url, '/')) == NULL) return 1; h = apr_palloc(cntxt, cp - url + 1); memcpy(h, url, cp - url); h[cp - url] = '\0'; rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt); if (rv != APR_SUCCESS || !hostname || scope_id) { return 1; } path = apr_pstrdup(cntxt, cp); *cp = '\0'; if (*url == '[') { /* IPv6 numeric address string */ host_field = apr_psprintf(cntxt, "[%s]", hostname); } else { host_field = hostname; } if (port == 0) { /* no port specified */ #ifdef USE_SSL if (is_ssl) port = 443; else #endif port = 80; } if (( #ifdef USE_SSL is_ssl && (port != 443)) || (!is_ssl && #endif (port != 80))) { colonhost = apr_psprintf(cntxt,":%d",port); } else colonhost = ""; return 0; } /* ------------------------------------------------------- */ /* read data to POST from file, save contents and length */ static int open_postfile(const char *pfile) { apr_file_t *postfd; apr_finfo_t finfo; apr_status_t rv; char errmsg[120]; rv = apr_file_open(&postfd, pfile, APR_READ, APR_OS_DEFAULT, cntxt); if (rv != APR_SUCCESS) { fprintf(stderr, "ab: Could not open POST data file (%s): %s\n", pfile, apr_strerror(rv, errmsg, sizeof errmsg)); return rv; } rv = apr_file_info_get(&finfo, APR_FINFO_NORM, postfd); if (rv != APR_SUCCESS) { fprintf(stderr, "ab: Could not stat POST data file (%s): %s\n", pfile, apr_strerror(rv, errmsg, sizeof errmsg)); return rv; } postlen = (apr_size_t)finfo.size; postdata = malloc(postlen); if (!postdata) { fprintf(stderr, "ab: Could not allocate POST data buffer\n"); return APR_ENOMEM; } rv = apr_file_read_full(postfd, postdata, postlen, NULL); if (rv != APR_SUCCESS) { fprintf(stderr, "ab: Could not read POST data file: %s\n", apr_strerror(rv, errmsg, sizeof errmsg)); return rv; } apr_file_close(postfd); return 0; } /* ------------------------------------------------------- */ /* sort out command-line args and call test */ int main(int argc, const char * const argv[]) { int r, l; char tmp[1024]; apr_status_t status; apr_getopt_t *opt; const char *optarg; char c; #ifdef USE_SSL AB_SSL_METHOD_CONST SSL_METHOD *meth = SSLv23_client_method(); #endif /* table defaults */ tablestring = ""; trstring = ""; tdstring = "bgcolor=white"; cookie = ""; auth = ""; proxyhost[0] = '\0'; hdrs = ""; apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); apr_pool_create(&cntxt, NULL); #ifdef NOT_ASCII status = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, cntxt); if (status) { fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status); exit(1); } status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO-8859-1", cntxt); if (status) { fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status); exit(1); } status = apr_base64init_ebcdic(to_ascii, from_ascii); if (status) { fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status); exit(1); } #endif apr_getopt_init(&opt, cntxt, argc, argv); while ((status = apr_getopt(opt, "n:c:t:N:l:b:T:p:u:v:k:rVhwix:y:z:C:H:P:A:g:X:de:SqR:" #ifdef USE_SSL "Z:f:" #endif ,&c, &optarg)) == APR_SUCCESS) { switch (c) { case 'n': requests = atoi(optarg); if (requests <= 0) { err("Invalid number of requests\n"); } break; case 'k': keepalive_cnt = atoi(optarg); keepalive = 1; break; case 'q': heartbeatres = 0; break; case 'c': concurrency = atoi(optarg); break; case 'b': windowsize = atoi(optarg); break; case 'N': _num_cpus = atoi(optarg); break; case 'l': num_ports = atoi(optarg); break; case 'i': if (posting > 0) err("Cannot mix POST/PUT and HEAD\n"); posting = -1; break; case 'g': gnuplot = strdup(optarg); break; case 'd': percentile = 0; break; case 'e': csvperc = strdup(optarg); break; case 'S': confidence = 0; break; case 'p': if (posting != 0) err("Cannot mix POST and HEAD\n"); if (0 == (r = open_postfile(optarg))) { posting = 1; } else if (postdata) { exit(r); } break; case 'u': if (posting != 0) err("Cannot mix PUT and HEAD\n"); if (0 == (r = open_postfile(optarg))) { posting = 2; } else if (postdata) { exit(r); } break; case 'r': recverrok = 1; break; case 'v': verbosity = atoi(optarg); break; case 't': tlimit = atoi(optarg); requests = MAX_REQUESTS; /* need to size data array on * something */ break; case 'T': strcpy(content_type, optarg); break; case 'C': cookie = apr_pstrcat(cntxt, "Cookie: ", optarg, "\r\n", NULL); break; case 'A': /* * assume username passwd already to be in colon separated form. * Ready to be uu-encoded. */ while (apr_isspace(*optarg)) optarg++; if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) { err("Authentication credentials too long\n"); } l = apr_base64_encode(tmp, optarg, strlen(optarg)); tmp[l] = '\0'; auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp, "\r\n", NULL); break; case 'P': /* * assume username passwd already to be in colon separated form. */ while (apr_isspace(*optarg)) optarg++; if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) { err("Proxy credentials too long\n"); } l = apr_base64_encode(tmp, optarg, strlen(optarg)); tmp[l] = '\0'; auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ", tmp, "\r\n", NULL); break; case 'R': // if (posting > 0) // err("-R only applicable for non-POST requests\n"); if (0 == (r = open_request_file(optarg))) { request_append = 1; } else { exit(r); } break; case 'H': hdrs = apr_pstrcat(cntxt, hdrs, optarg, "\r\n", NULL); /* * allow override of some of the common headers that ab adds */ if (strncasecmp(optarg, "Host:", 5) == 0) { opt_host = 1; } else if (strncasecmp(optarg, "Accept:", 7) == 0) { opt_accept = 1; } else if (strncasecmp(optarg, "User-Agent:", 11) == 0) { opt_useragent = 1; } break; case 'w': use_html = 1; break; /* * if any of the following three are used, turn on html output * automatically */ case 'x': use_html = 1; tablestring = optarg; break; case 'X': { char *p; /* * assume proxy-name[:port] */ if ((p = strchr(optarg, ':'))) { *p = '\0'; p++; proxyport = atoi(p); } strcpy(proxyhost, optarg); isproxy = 1; } break; case 'y': use_html = 1; trstring = optarg; break; case 'z': use_html = 1; tdstring = optarg; break; case 'h': usage(argv[0]); break; case 'V': copyright(); return 0; #ifdef USE_SSL case 'Z': ssl_cipher = strdup(optarg); break; case 'f': if (strncasecmp(optarg, "ALL", 3) == 0) { meth = SSLv23_client_method(); #ifndef OPENSSL_NO_SSL2 } else if (strncasecmp(optarg, "SSL2", 4) == 0) { meth = SSLv2_client_method(); #endif } else if (strncasecmp(optarg, "SSL3", 4) == 0) { meth = SSLv3_client_method(); #ifdef HAVE_TLSV1_X } else if (strncasecmp(optarg, "TLS1.1", 6) == 0) { meth = TLSv1_1_client_method(); } else if (strncasecmp(optarg, "TLS1.2", 6) == 0) { meth = TLSv1_2_client_method(); #endif } else if (strncasecmp(optarg, "TLS1", 4) == 0) { meth = TLSv1_client_method(); } break; #endif } } if (opt->ind != argc - 1) { fprintf(stderr, "%s: wrong number of arguments\n", argv[0]); usage(argv[0]); } if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) { fprintf(stderr, "%s: invalid URL\n", argv[0]); usage(argv[0]); } if ((concurrency < 0) || (concurrency > MAX_CONCURRENCY)) { fprintf(stderr, "%s: Invalid Concurrency [Range 0..%d]\n", argv[0], MAX_CONCURRENCY); usage(argv[0]); } if (concurrency > requests) { fprintf(stderr, "%s: Cannot use concurrency level greater than " "total number of requests\n", argv[0]); usage(argv[0]); } if (_num_cpus > concurrency) { fprintf(stderr, "%s: Cannot use cpus more than " "the concurrency level\n", argv[0]); usage(argv[0]); } if (keepalive_cnt < 0) { fprintf(stderr, "%s: #reqs/connection should be grater than 0.\n" "0 indicates no limit in #reqs/connection\n", argv[0]); usage(argv[0]); } if ((heartbeatres) && (requests > 150)) { heartbeatres = requests / 10; /* Print line every 10% of requests */ if (heartbeatres < 100) heartbeatres = 100; /* but never more often than once every 100 * connections. */ } else heartbeatres = 0; #ifdef USE_SSL #ifdef RSAREF R_malloc_init(); #else CRYPTO_malloc_init(); #endif SSL_load_error_strings(); SSL_library_init(); bio_out=BIO_new_fp(stdout,BIO_NOCLOSE); bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); if (!(ssl_ctx = SSL_CTX_new(meth))) { BIO_printf(bio_err, "Could not initialize SSL Context.\n"); ERR_print_errors(bio_err); exit(1); } SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL); if (ssl_cipher != NULL) { if (!SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher)) { fprintf(stderr, "error setting cipher list [%s]\n", ssl_cipher); ERR_print_errors_fp(stderr); exit(1); } } if (verbosity >= 3) { SSL_CTX_set_info_callback(ssl_ctx, ssl_state_cb); } #endif #ifdef SIGPIPE apr_signal(SIGPIPE, SIG_IGN); /* Ignore writes to connections that * have been closed at the other end. */ #endif copyright(); test(); apr_pool_destroy(cntxt); return 0; }
chyyuu/mtcp
apps/apache_benchmark_deprecated/support/ab-multiple-files.c
C
bsd-3-clause
91,857
<?php $I = new CliGuy($scenario); $I->wantTo('overwrite a file with CopyDir task'); $I->amInPath(codecept_data_dir() . 'sandbox'); $I->seeDirFound('some'); $I->seeFileFound('existing_file', 'some'); $I->taskCopyDir(['some' => 'some_destination']) ->run(); $I->seeFileFound('existing_file', 'some_destination/deeply'); $I->openFile('some_destination/deeply/existing_file'); $I->seeInThisFile('some existing file');
shaynekasai/ft
vendor/codegyre/robo/tests/cli/CopyDirOverwritesFilesCept.php
PHP
bsd-3-clause
419
/* 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/. */ /* * This file deals with PKCS #11 passwords and authentication. */ #include "seccomon.h" #include "secmod.h" #include "secmodi.h" #include "secmodti.h" #include "pkcs11t.h" #include "pk11func.h" #include "secitem.h" #include "secerr.h" #include "pkim.h" /************************************************************* * local static and global data *************************************************************/ /* * This structure keeps track of status that spans all the Slots. * NOTE: This is a global data structure. It semantics expect thread crosstalk * be very careful when you see it used. * It's major purpose in life is to allow the user to log in one PER * Tranaction, even if a transaction spans threads. The problem is the user * may have to enter a password one just to be able to look at the * personalities/certificates (s)he can use. Then if Auth every is one, they * may have to enter the password again to use the card. See PK11_StartTransac * and PK11_EndTransaction. */ static struct PK11GlobalStruct { int transaction; PRBool inTransaction; char *(PR_CALLBACK *getPass)(PK11SlotInfo *,PRBool,void *); PRBool (PR_CALLBACK *verifyPass)(PK11SlotInfo *,void *); PRBool (PR_CALLBACK *isLoggedIn)(PK11SlotInfo *,void *); } PK11_Global = { 1, PR_FALSE, NULL, NULL, NULL }; /*********************************************************** * Password Utilities ***********************************************************/ /* * Check the user's password. Log into the card if it's correct. * succeed if the user is already logged in. */ static SECStatus pk11_CheckPassword(PK11SlotInfo *slot, CK_SESSION_HANDLE session, char *pw, PRBool alreadyLocked, PRBool contextSpecific) { int len = 0; CK_RV crv; SECStatus rv; PRTime currtime = PR_Now(); PRBool mustRetry; int retry = 0; if (slot->protectedAuthPath) { len = 0; pw = NULL; } else if (pw == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } else { len = PORT_Strlen(pw); } do { if (!alreadyLocked) PK11_EnterSlotMonitor(slot); crv = PK11_GETTAB(slot)->C_Login(session, contextSpecific ? CKU_CONTEXT_SPECIFIC : CKU_USER, (unsigned char *)pw,len); slot->lastLoginCheck = 0; mustRetry = PR_FALSE; if (!alreadyLocked) PK11_ExitSlotMonitor(slot); switch (crv) { /* if we're already logged in, we're good to go */ case CKR_OK: /* TODO If it was for CKU_CONTEXT_SPECIFIC should we do this */ slot->authTransact = PK11_Global.transaction; /* Fall through */ case CKR_USER_ALREADY_LOGGED_IN: slot->authTime = currtime; rv = SECSuccess; break; case CKR_PIN_INCORRECT: PORT_SetError(SEC_ERROR_BAD_PASSWORD); rv = SECWouldBlock; /* everything else is ok, only the pin is bad */ break; /* someone called reset while we fetched the password, try again once * if the token is still there. */ case CKR_SESSION_HANDLE_INVALID: case CKR_SESSION_CLOSED: if (session != slot->session) { /* don't bother retrying, we were in a middle of an operation, * which is now lost. Just fail. */ PORT_SetError(PK11_MapError(crv)); rv = SECFailure; break; } if (retry++ == 0) { rv = PK11_InitToken(slot,PR_FALSE); if (rv == SECSuccess) { if (slot->session != CK_INVALID_SESSION) { session = slot->session; /* we should have * a new session now */ mustRetry = PR_TRUE; } else { PORT_SetError(PK11_MapError(crv)); rv = SECFailure; } } break; } /* Fall through */ default: PORT_SetError(PK11_MapError(crv)); rv = SECFailure; /* some failure we can't fix by retrying */ } } while (mustRetry); return rv; } /* * Check the user's password. Logout before hand to make sure that * we are really checking the password. */ SECStatus PK11_CheckUserPassword(PK11SlotInfo *slot, const char *pw) { int len = 0; CK_RV crv; SECStatus rv; PRTime currtime = PR_Now(); if (slot->protectedAuthPath) { len = 0; pw = NULL; } else if (pw == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } else { len = PORT_Strlen(pw); } /* * If the token doesn't need a login, don't try to relogin because the * effect is undefined. It's not clear what it means to check a non-empty * password with such a token, so treat that as an error. */ if (!slot->needLogin) { if (len == 0) { rv = SECSuccess; } else { PORT_SetError(SEC_ERROR_BAD_PASSWORD); rv = SECFailure; } return rv; } /* force a logout */ PK11_EnterSlotMonitor(slot); PK11_GETTAB(slot)->C_Logout(slot->session); crv = PK11_GETTAB(slot)->C_Login(slot->session,CKU_USER, (unsigned char *)pw,len); slot->lastLoginCheck = 0; PK11_ExitSlotMonitor(slot); switch (crv) { /* if we're already logged in, we're good to go */ case CKR_OK: slot->authTransact = PK11_Global.transaction; slot->authTime = currtime; rv = SECSuccess; break; case CKR_PIN_INCORRECT: PORT_SetError(SEC_ERROR_BAD_PASSWORD); rv = SECWouldBlock; /* everything else is ok, only the pin is bad */ break; default: PORT_SetError(PK11_MapError(crv)); rv = SECFailure; /* some failure we can't fix by retrying */ } return rv; } SECStatus PK11_Logout(PK11SlotInfo *slot) { CK_RV crv; /* force a logout */ PK11_EnterSlotMonitor(slot); crv = PK11_GETTAB(slot)->C_Logout(slot->session); slot->lastLoginCheck = 0; PK11_ExitSlotMonitor(slot); if (crv != CKR_OK) { PORT_SetError(PK11_MapError(crv)); return SECFailure; } return SECSuccess; } /* * transaction stuff is for when we test for the need to do every * time auth to see if we already did it for this slot/transaction */ void PK11_StartAuthTransaction(void) { PK11_Global.transaction++; PK11_Global.inTransaction = PR_TRUE; } void PK11_EndAuthTransaction(void) { PK11_Global.transaction++; PK11_Global.inTransaction = PR_FALSE; } /* * before we do a private key op, we check to see if we * need to reauthenticate. */ void PK11_HandlePasswordCheck(PK11SlotInfo *slot,void *wincx) { int askpw = slot->askpw; PRBool NeedAuth = PR_FALSE; if (!slot->needLogin) return; if ((slot->defaultFlags & PK11_OWN_PW_DEFAULTS) == 0) { PK11SlotInfo *def_slot = PK11_GetInternalKeySlot(); if (def_slot) { askpw = def_slot->askpw; PK11_FreeSlot(def_slot); } } /* timeouts are handled by isLoggedIn */ if (!PK11_IsLoggedIn(slot,wincx)) { NeedAuth = PR_TRUE; } else if (askpw == -1) { if (!PK11_Global.inTransaction || (PK11_Global.transaction != slot->authTransact)) { PK11_EnterSlotMonitor(slot); PK11_GETTAB(slot)->C_Logout(slot->session); slot->lastLoginCheck = 0; PK11_ExitSlotMonitor(slot); NeedAuth = PR_TRUE; } } if (NeedAuth) PK11_DoPassword(slot, slot->session, PR_TRUE, wincx, PR_FALSE, PR_FALSE); } void PK11_SlotDBUpdate(PK11SlotInfo *slot) { SECMOD_UpdateModule(slot->module); } /* * set new askpw and timeout values */ void PK11_SetSlotPWValues(PK11SlotInfo *slot,int askpw, int timeout) { slot->askpw = askpw; slot->timeout = timeout; slot->defaultFlags |= PK11_OWN_PW_DEFAULTS; PK11_SlotDBUpdate(slot); } /* * Get the askpw and timeout values for this slot */ void PK11_GetSlotPWValues(PK11SlotInfo *slot,int *askpw, int *timeout) { *askpw = slot->askpw; *timeout = slot->timeout; if ((slot->defaultFlags & PK11_OWN_PW_DEFAULTS) == 0) { PK11SlotInfo *def_slot = PK11_GetInternalKeySlot(); if (def_slot) { *askpw = def_slot->askpw; *timeout = def_slot->timeout; PK11_FreeSlot(def_slot); } } } /* * Returns true if the token is needLogin and isn't logged in. * This function is used to determine if authentication is needed * before attempting a potentially privelleged operation. */ PRBool pk11_LoginStillRequired(PK11SlotInfo *slot, void *wincx) { return slot->needLogin && !PK11_IsLoggedIn(slot,wincx); } /* * make sure a slot is authenticated... * This function only does the authentication if it is needed. */ SECStatus PK11_Authenticate(PK11SlotInfo *slot, PRBool loadCerts, void *wincx) { if (pk11_LoginStillRequired(slot,wincx)) { return PK11_DoPassword(slot, slot->session, loadCerts, wincx, PR_FALSE, PR_FALSE); } return SECSuccess; } /* * Authenticate to "unfriendly" tokens (tokens which need to be logged * in to find the certs. */ SECStatus pk11_AuthenticateUnfriendly(PK11SlotInfo *slot, PRBool loadCerts, void *wincx) { SECStatus rv = SECSuccess; if (!PK11_IsFriendly(slot)) { rv = PK11_Authenticate(slot, loadCerts, wincx); } return rv; } /* * NOTE: this assumes that we are logged out of the card before hand */ SECStatus PK11_CheckSSOPassword(PK11SlotInfo *slot, char *ssopw) { CK_SESSION_HANDLE rwsession; CK_RV crv; SECStatus rv = SECFailure; int len = 0; /* get a rwsession */ rwsession = PK11_GetRWSession(slot); if (rwsession == CK_INVALID_SESSION) { PORT_SetError(SEC_ERROR_BAD_DATA); return rv; } if (slot->protectedAuthPath) { len = 0; ssopw = NULL; } else if (ssopw == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } else { len = PORT_Strlen(ssopw); } /* check the password */ crv = PK11_GETTAB(slot)->C_Login(rwsession,CKU_SO, (unsigned char *)ssopw,len); slot->lastLoginCheck = 0; switch (crv) { /* if we're already logged in, we're good to go */ case CKR_OK: rv = SECSuccess; break; case CKR_PIN_INCORRECT: PORT_SetError(SEC_ERROR_BAD_PASSWORD); rv = SECWouldBlock; /* everything else is ok, only the pin is bad */ break; default: PORT_SetError(PK11_MapError(crv)); rv = SECFailure; /* some failure we can't fix by retrying */ } PK11_GETTAB(slot)->C_Logout(rwsession); slot->lastLoginCheck = 0; /* release rwsession */ PK11_RestoreROSession(slot,rwsession); return rv; } /* * make sure the password conforms to your token's requirements. */ SECStatus PK11_VerifyPW(PK11SlotInfo *slot,char *pw) { int len = PORT_Strlen(pw); if ((slot->minPassword > len) || (slot->maxPassword < len)) { PORT_SetError(SEC_ERROR_BAD_DATA); return SECFailure; } return SECSuccess; } /* * initialize a user PIN Value */ SECStatus PK11_InitPin(PK11SlotInfo *slot, const char *ssopw, const char *userpw) { CK_SESSION_HANDLE rwsession = CK_INVALID_SESSION; CK_RV crv; SECStatus rv = SECFailure; int len; int ssolen; if (userpw == NULL) userpw = ""; if (ssopw == NULL) ssopw = ""; len = PORT_Strlen(userpw); ssolen = PORT_Strlen(ssopw); /* get a rwsession */ rwsession = PK11_GetRWSession(slot); if (rwsession == CK_INVALID_SESSION) { PORT_SetError(SEC_ERROR_BAD_DATA); slot->lastLoginCheck = 0; return rv; } if (slot->protectedAuthPath) { len = 0; ssolen = 0; ssopw = NULL; userpw = NULL; } /* check the password */ crv = PK11_GETTAB(slot)->C_Login(rwsession,CKU_SO, (unsigned char *)ssopw,ssolen); slot->lastLoginCheck = 0; if (crv != CKR_OK) { PORT_SetError(PK11_MapError(crv)); goto done; } crv = PK11_GETTAB(slot)->C_InitPIN(rwsession,(unsigned char *)userpw,len); if (crv != CKR_OK) { PORT_SetError(PK11_MapError(crv)); } else { rv = SECSuccess; } done: PK11_GETTAB(slot)->C_Logout(rwsession); slot->lastLoginCheck = 0; PK11_RestoreROSession(slot,rwsession); if (rv == SECSuccess) { /* update our view of the world */ PK11_InitToken(slot,PR_TRUE); if (slot->needLogin) { PK11_EnterSlotMonitor(slot); PK11_GETTAB(slot)->C_Login(slot->session,CKU_USER, (unsigned char *)userpw,len); slot->lastLoginCheck = 0; PK11_ExitSlotMonitor(slot); } } return rv; } /* * Change an existing user password */ SECStatus PK11_ChangePW(PK11SlotInfo *slot, const char *oldpw, const char *newpw) { CK_RV crv; SECStatus rv = SECFailure; int newLen = 0; int oldLen = 0; CK_SESSION_HANDLE rwsession; /* use NULL values to trigger the protected authentication path */ if (!slot->protectedAuthPath) { if (newpw == NULL) newpw = ""; if (oldpw == NULL) oldpw = ""; } if (newpw) newLen = PORT_Strlen(newpw); if (oldpw) oldLen = PORT_Strlen(oldpw); /* get a rwsession */ rwsession = PK11_GetRWSession(slot); if (rwsession == CK_INVALID_SESSION) { PORT_SetError(SEC_ERROR_BAD_DATA); return rv; } crv = PK11_GETTAB(slot)->C_SetPIN(rwsession, (unsigned char *)oldpw,oldLen,(unsigned char *)newpw,newLen); if (crv == CKR_OK) { rv = SECSuccess; } else { PORT_SetError(PK11_MapError(crv)); } PK11_RestoreROSession(slot,rwsession); /* update our view of the world */ PK11_InitToken(slot,PR_TRUE); return rv; } static char * pk11_GetPassword(PK11SlotInfo *slot, PRBool retry, void * wincx) { if (PK11_Global.getPass == NULL) return NULL; return (*PK11_Global.getPass)(slot, retry, wincx); } void PK11_SetPasswordFunc(PK11PasswordFunc func) { PK11_Global.getPass = func; } void PK11_SetVerifyPasswordFunc(PK11VerifyPasswordFunc func) { PK11_Global.verifyPass = func; } void PK11_SetIsLoggedInFunc(PK11IsLoggedInFunc func) { PK11_Global.isLoggedIn = func; } /* * authenticate to a slot. This loops until we can't recover, the user * gives up, or we succeed. If we're already logged in and this function * is called we will still prompt for a password, but we will probably * succeed no matter what the password was (depending on the implementation * of the PKCS 11 module. */ SECStatus PK11_DoPassword(PK11SlotInfo *slot, CK_SESSION_HANDLE session, PRBool loadCerts, void *wincx, PRBool alreadyLocked, PRBool contextSpecific) { SECStatus rv = SECFailure; char * password; PRBool attempt = PR_FALSE; if (PK11_NeedUserInit(slot)) { PORT_SetError(SEC_ERROR_IO); return SECFailure; } /* * Central server type applications which control access to multiple * slave applications to single crypto devices need to virtuallize the * login state. This is done by a callback out of PK11_IsLoggedIn and * here. If we are actually logged in, then we got here because the * higher level code told us that the particular client application may * still need to be logged in. If that is the case, we simply tell the * server code that it should now verify the clients password and tell us * the results. */ if (PK11_IsLoggedIn(slot,NULL) && (PK11_Global.verifyPass != NULL)) { if (!PK11_Global.verifyPass(slot,wincx)) { PORT_SetError(SEC_ERROR_BAD_PASSWORD); return SECFailure; } return SECSuccess; } /* get the password. This can drop out of the while loop * for the following reasons: * (1) the user refused to enter a password. * (return error to caller) * (2) the token user password is disabled [usually due to * too many failed authentication attempts]. * (return error to caller) * (3) the password was successful. */ while ((password = pk11_GetPassword(slot, attempt, wincx)) != NULL) { /* if the token has a protectedAuthPath, the application may have * already issued the C_Login as part of it's pk11_GetPassword call. * In this case the application will tell us what the results were in * the password value (retry or the authentication was successful) so * we can skip our own C_Login call (which would force the token to * try to login again). * * Applications that don't know about protectedAuthPath will return a * password, which we will ignore and trigger the token to * 'authenticate' itself anyway. Hopefully the blinking display on * the reader, or the flashing light under the thumbprint reader will * attract the user's attention */ attempt = PR_TRUE; if (slot->protectedAuthPath) { /* application tried to authenticate and failed. it wants to try * again, continue looping */ if (strcmp(password, PK11_PW_RETRY) == 0) { rv = SECWouldBlock; PORT_Free(password); continue; } /* applicaton tried to authenticate and succeeded we're done */ if (strcmp(password, PK11_PW_AUTHENTICATED) == 0) { rv = SECSuccess; PORT_Free(password); break; } } rv = pk11_CheckPassword(slot, session, password, alreadyLocked, contextSpecific); PORT_Memset(password, 0, PORT_Strlen(password)); PORT_Free(password); if (rv != SECWouldBlock) break; } if (rv == SECSuccess) { if (!PK11_IsFriendly(slot)) { nssTrustDomain_UpdateCachedTokenCerts(slot->nssToken->trustDomain, slot->nssToken); } } else if (!attempt) PORT_SetError(SEC_ERROR_BAD_PASSWORD); return rv; } void PK11_LogoutAll(void) { SECMODListLock *lock = SECMOD_GetDefaultModuleListLock(); SECMODModuleList *modList; SECMODModuleList *mlp = NULL; int i; /* NSS is not initialized, there are not tokens to log out */ if (lock == NULL) { return; } SECMOD_GetReadLock(lock); modList = SECMOD_GetDefaultModuleList(); /* find the number of entries */ for (mlp = modList; mlp != NULL; mlp = mlp->next) { for (i=0; i < mlp->module->slotCount; i++) { PK11_Logout(mlp->module->slots[i]); } } SECMOD_ReleaseReadLock(lock); } int PK11_GetMinimumPwdLength(PK11SlotInfo *slot) { return ((int)slot->minPassword); } /* Does this slot have a protected pin path? */ PRBool PK11_ProtectedAuthenticationPath(PK11SlotInfo *slot) { return slot->protectedAuthPath; } /* * we can initialize the password if 1) The toke is not inited * (need login == true and see need UserInit) or 2) the token has * a NULL password. (slot->needLogin = false & need user Init = false). */ PRBool PK11_NeedPWInitForSlot(PK11SlotInfo *slot) { if (slot->needLogin && PK11_NeedUserInit(slot)) { return PR_TRUE; } if (!slot->needLogin && !PK11_NeedUserInit(slot)) { return PR_TRUE; } return PR_FALSE; } PRBool PK11_NeedPWInit() { PK11SlotInfo *slot = PK11_GetInternalKeySlot(); PRBool ret = PK11_NeedPWInitForSlot(slot); PK11_FreeSlot(slot); return ret; } PRBool pk11_InDelayPeriod(PRIntervalTime lastTime, PRIntervalTime delayTime, PRIntervalTime *retTime) { PRIntervalTime time; *retTime = time = PR_IntervalNow(); return (PRBool) (lastTime) && ((time-lastTime) < delayTime); } /* * Determine if the token is logged in. We have to actually query the token, * because it's state can change without intervention from us. */ PRBool PK11_IsLoggedIn(PK11SlotInfo *slot,void *wincx) { CK_SESSION_INFO sessionInfo; int askpw = slot->askpw; int timeout = slot->timeout; CK_RV crv; PRIntervalTime curTime; static PRIntervalTime login_delay_time = 0; if (login_delay_time == 0) { login_delay_time = PR_SecondsToInterval(1); } /* If we don't have our own password default values, use the system * ones */ if ((slot->defaultFlags & PK11_OWN_PW_DEFAULTS) == 0) { PK11SlotInfo *def_slot = PK11_GetInternalKeySlot(); if (def_slot) { askpw = def_slot->askpw; timeout = def_slot->timeout; PK11_FreeSlot(def_slot); } } if ((wincx != NULL) && (PK11_Global.isLoggedIn != NULL) && (*PK11_Global.isLoggedIn)(slot, wincx) == PR_FALSE) { return PR_FALSE; } /* forget the password if we've been inactive too long */ if (askpw == 1) { PRTime currtime = PR_Now(); PRTime result; PRTime mult; LL_I2L(result, timeout); LL_I2L(mult, 60*1000*1000); LL_MUL(result,result,mult); LL_ADD(result, result, slot->authTime); if (LL_CMP(result, <, currtime) ) { PK11_EnterSlotMonitor(slot); PK11_GETTAB(slot)->C_Logout(slot->session); slot->lastLoginCheck = 0; PK11_ExitSlotMonitor(slot); } else { slot->authTime = currtime; } } PK11_EnterSlotMonitor(slot); if (pk11_InDelayPeriod(slot->lastLoginCheck,login_delay_time, &curTime)) { sessionInfo.state = slot->lastState; crv = CKR_OK; } else { crv = PK11_GETTAB(slot)->C_GetSessionInfo(slot->session,&sessionInfo); if (crv == CKR_OK) { slot->lastState = sessionInfo.state; slot->lastLoginCheck = curTime; } } PK11_ExitSlotMonitor(slot); /* if we can't get session info, something is really wrong */ if (crv != CKR_OK) { slot->session = CK_INVALID_SESSION; return PR_FALSE; } switch (sessionInfo.state) { case CKS_RW_PUBLIC_SESSION: case CKS_RO_PUBLIC_SESSION: default: break; /* fail */ case CKS_RW_USER_FUNCTIONS: case CKS_RW_SO_FUNCTIONS: case CKS_RO_USER_FUNCTIONS: return PR_TRUE; } return PR_FALSE; }
wangscript/libjingle-1
trunk/third_party/nss/nss/lib/pk11wrap/pk11auth.c
C
bsd-3-clause
21,182
# Phalcon PHP Benchmarking Test This is the Phalcon PHP portion of a [benchmarking test suite](../) comparing a variety of web development platforms. ### JSON Encoding Test Uses the PHP standard [JSON encoder](http://www.php.net/manual/en/function.json-encode.php). * [JSON test controller](app/controllers/BenchController.php) ### Data-Store/Database Mapping Test Uses the built-in ORM/ODM of Phalcon PHP * MySQL: [DB test controller](app/controllers/BenchController.php) * MongoDB: [DB test controller](app/controllers/MongobenchController.php) ### Template Test Uses Phalcons template engine 'Volt' * [Template test controller](app/controllers/BenchController.php) ## Infrastructure Software Versions The tests were run with: * [Phalcon 4](http://phalconphp.com/) * [PHP Version 7.4](http://www.php.net/) with FPM, OPcache and Phalcon extension * [nginx 1.16](http://nginx.org/) * [MySQL 8](https://dev.mysql.com/) * [MongoDB 4](https://mongodb.org/) ## Test URLs ### JSON Encoding Test http://localhost/json ### Data-Store/Database Mapping Test MySQL: http://localhost/db MongoDB: http://localhost/mongodb/db ### Variable Query Test MySQL: http://localhost/queries?queries=2 MongoDB: http://localhost/mongodb/queries?queries=2 ### Update Test MySQL: http://localhost/update http://localhost/fortunes ### Plaintext Test http://localhost/plaintext ### Fortunes Test MySQL: http://localhost/fortunes MongoDB: http://localhost/mongodb/fortunes
lneves/FrameworkBenchmarks
frameworks/PHP/phalcon/README.md
Markdown
bsd-3-clause
1,480
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/lazy_instance_helpers.h" #include "base/at_exit.h" #include "base/atomicops.h" #include "base/threading/platform_thread.h" namespace base { namespace internal { bool NeedsLazyInstance(subtle::AtomicWord* state) { // Try to create the instance, if we're the first, will go from 0 to // kLazyInstanceStateCreating, otherwise we've already been beaten here. // The memory access has no memory ordering as state 0 and // kLazyInstanceStateCreating have no associated data (memory barriers are // all about ordering of memory accesses to *associated* data). if (subtle::NoBarrier_CompareAndSwap(state, 0, kLazyInstanceStateCreating) == 0) { // Caller must create instance return true; } // It's either in the process of being created, or already created. Spin. // The load has acquire memory ordering as a thread which sees // state_ == STATE_CREATED needs to acquire visibility over // the associated data (buf_). Pairing Release_Store is in // CompleteLazyInstance(). if (subtle::Acquire_Load(state) == kLazyInstanceStateCreating) { const base::TimeTicks start = base::TimeTicks::Now(); do { const base::TimeDelta elapsed = base::TimeTicks::Now() - start; // Spin with YieldCurrentThread for at most one ms - this ensures maximum // responsiveness. After that spin with Sleep(1ms) so that we don't burn // excessive CPU time - this also avoids infinite loops due to priority // inversions (https://crbug.com/797129). if (elapsed < TimeDelta::FromMilliseconds(1)) PlatformThread::YieldCurrentThread(); else PlatformThread::Sleep(TimeDelta::FromMilliseconds(1)); } while (subtle::Acquire_Load(state) == kLazyInstanceStateCreating); } // Someone else created the instance. return false; } void CompleteLazyInstance(subtle::AtomicWord* state, subtle::AtomicWord new_instance, void (*destructor)(void*), void* destructor_arg) { // Instance is created, go from CREATING to CREATED (or reset it if // |new_instance| is null). Releases visibility over |private_buf_| to // readers. Pairing Acquire_Load is in NeedsLazyInstance(). subtle::Release_Store(state, new_instance); // Make sure that the lazily instantiated object will get destroyed at exit. if (new_instance && destructor) AtExitManager::RegisterCallback(destructor, destructor_arg); } } // namespace internal } // namespace base
endlessm/chromium-browser
base/lazy_instance_helpers.cc
C++
bsd-3-clause
2,679
// Type definitions for karma-remap-coverage 0.1 // Project: https://github.com/sshev/karma-remap-coverage#readme // Definitions by: Piotr Błażejewicz (Peter Blazejewicz) <https://github.com/peterblazejewicz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.2 /// <reference types="karma-coverage" /> import 'karma'; declare module 'karma' { interface ConfigOptions { /** * Key-value pairs where key is report type and value - path to file/dir where to save it. * Reporters like `text-summary`, `text-lcov` and `teamcity` can print out to console as well * - in this case just provide any falsy value instead of path. * * @example * ```ts * 'text-summary': null, // to show summary in console * html: './coverage/html', * ``` * * {@link https://github.com/sshev/karma-remap-coverage#remapcoveragereporter-format } */ remapCoverageReporter?: KarmaRemapCoverageReporter | undefined; } // remapped reporter types to key-value pairs type KarmaRemapCoverageReporter = Partial<Record<ReporterType, string | null | undefined>>; }
markogresak/DefinitelyTyped
types/karma-remap-coverage/index.d.ts
TypeScript
mit
1,212
<div> <table class="table table-striped" cellspacing="0 "> <thead> <tr data-bind="foreach: columns"> <th data-bind="text: headerText"></th> </tr> </thead> <tbody class="table table-hover" data-bind="foreach: itemsOnCurrentPage"> <tr data-bind="foreach: $parent.columns"> <td data-bind="text: typeof rowText == 'function' ? rowText($parent) : $parent[rowText]"></td> </tr> </tbody> </table> <div class="pagination"> <ul> <!-- ko foreach: ko.utils.range(0, maxPageIndex) --> <li> <a href="#" data-bind="text: $data + 1, click: function () { $root.currentPageIndex($data); }"></a> </li> <!-- /ko --> </ul> </div> </div>
welldone-software/gulp-durandal
test/fixtures/HTML Samples/app/ko/pagedGrid/simpleGrid.html
HTML
mit
827
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Hero } from '../model/hero'; import { HeroService } from '../model/hero.service'; // #docregion prototype @Injectable() export class HeroDetailService { constructor(private heroService: HeroService) { } // #enddocregion prototype // Returns a clone which caller may modify safely getHero(id: number | string): Observable<Hero> { if (typeof id === 'string') { id = parseInt(id, 10); } return this.heroService.getHero(id).pipe( map(hero => { return hero ? Object.assign({}, hero) : null; // clone or null }) ); } saveHero(hero: Hero) { return this.heroService.updateHero(hero); } // #docregion prototype } // #enddocregion prototype
wKoza/angular
aio/content/examples/testing/src/app/hero/hero-detail.service.ts
TypeScript
mit
821
# Adding a newssection or blog Now that we've covered the main topics, let's have a look at some extra utilities bundles we've prepared. Since quite a lot of the sites we make need some kind of news section - with news authors, news pages and a news overview page - we decided to create a bundle to make implementing these a lot easier. ## Generating the articles skeleton code First up is the article generator : bin/console kuma:generate:article This will first ask for the bundle namespace (you can accept the default - `MyProject/WebsiteBundle`), then it will ask for a name (enter `News`), and finally it will ask for the table name prefix, so enter `myproject_websitebundle_` as before. The basic code skeleton should now be generated, so go ahead and create (and apply) a migration for the database changes : bin/console doctrine:migrations:diff && bin/console doctrine:migrations:migrate As you can see, 3 new tables will be generated. One contains details for the authors, one will contain news overview pages and the last one will contain the actual news page. When you have a look at the admin section (`/app_dev.php/en/admin/`), you'll notice that there 2 new menu options (News and News Authors) have been added to the Modules menu. These menu items will allow you to add news articles and authors respectively, but you will not be able to add articles as no NewsOverviewPage has been created yet. Since we would like to be able to add a News page in the main navigation on the homepage, we first have to enable this, so go ahead and open `src/MyProject/WebsiteBundle/Entity/Pages/HomePage.php` and add the NewsOverviewPage to `getPossibleChildTypes` : ```php /** * @return array */ public function getPossibleChildTypes() { return array( ... ), array( 'name' => 'News Overview Page', 'class'=> 'MyProject\WebsiteBundle\Entity\News\NewsOverviewPage' ) ); } ``` After adding this snippet, you should be able to add a news overview page on the homepage in the backend, so go ahead and do that - and make sure you publish it after it is created. That's it! Your news overview page is created, and when you add (and publish!) news articles in the backend, you should see them appearing on your news overview page. If needed you can add extra fields to the generated entities as you see fit (don't forget to create and apply migrations afterwards!). 2) Summary ---------- Adding support for news articles to your site is as simple as this : bin/console kuma:generate:article 3) Under the hood ----------------- *Note:* The following paths assume you entered 'News' as name in the generator. - `src/YourVendor/YourWebsiteBundle/AdminList/News/` contains the admin lists for news authors and news pages (articles). - `src/YourVendor/YourWebsiteBundle/Controller/News/` contains the controllers for the admin lists for news authors and news pages (articles). - `src/YourVendor/YourWebsiteBundle/Entity/News/` contains all generated entities (ie. entities for the news overview page, news detail page and news author). - `src/YourVendor/YourWebsiteBundle/Form/News/` contains all form AdminType definitions generated by the article generator (ie. for the news overview page, news detail page and news author). - `src/YourVendor/YourWebsiteBundle/Helper/Menu/NewsMenuAdaptor.php` contains the menu adaptor that adds the extra menu options to the Modules menu. - `src/YourVendor/YourWebsiteBundle/PagePartAdmin/News/` contains the page part admin configurators for the news overview and news detail page (these determine the page parts that can be added to these pages). - `src/YourVendor/YourWebsiteBundle/Repository/` contains repositories for the generated entities. - `src/YourVendor/YourWebsiteBundle/Resources/views/AdminList/` contains a Twig view for the News page admin list. - `src/YourVendor/YourWebsiteBundle/Resources/views/News/`
jverdeyen/KunstmaanBundlesCMS
docs/content-management/adding-a-newssection-or-blog.md
Markdown
mit
3,933
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: DriveInfo ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Exposes routines for exploring a drive. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32; using System.Security.Permissions; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { // Matches Win32's DRIVE_XXX #defines from winbase.h [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum DriveType { Unknown = 0, NoRootDirectory = 1, Removable = 2, Fixed = 3, Network = 4, CDRom = 5, Ram = 6 } // Ideally we'll get a better security permission, but possibly // not for Whidbey. [Serializable] [ComVisible(true)] public sealed class DriveInfo : ISerializable { private String _name; private const String NameField = "_name"; // For serialization [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public DriveInfo(String driveName) { if (driveName == null) throw new ArgumentNullException("driveName"); Contract.EndContractBlock(); if (driveName.Length == 1) _name = driveName + ":\\"; else { // GetPathRoot does not check all invalid characters Path.CheckInvalidPathChars(driveName); _name = Path.GetPathRoot(driveName); // Disallow null or empty drive letters and UNC paths if (_name == null || _name.Length == 0 || _name.StartsWith("\\\\", StringComparison.Ordinal)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir")); } // We want to normalize to have a trailing backslash so we don't have two equivalent forms and // because some Win32 API don't work without it. if (_name.Length == 2 && _name[1] == ':') { _name = _name + "\\"; } // Now verify that the drive letter could be a real drive name. // On Windows this means it's between A and Z, ignoring case. // On a Unix platform, perhaps this should be a device name with // a partition like /dev/hdc0, or possibly a mount point. char letter = driveName[0]; if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir")); // Now do a security check. String demandPath = _name + '.'; new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand(); } [System.Security.SecurityCritical] // auto-generated private DriveInfo(SerializationInfo info, StreamingContext context) { // Need to add in a security check here once it has been spec'ed. _name = (String) info.GetValue(NameField, typeof(String)); // Now do a security check. String demandPath = _name + '.'; new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand(); } public String Name { get { return _name; } } public DriveType DriveType { [System.Security.SecuritySafeCritical] // auto-generated get { // GetDriveType can't fail return (DriveType) Win32Native.GetDriveType(Name); } } public String DriveFormat { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); if (!r) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIODriveError(Name, errorCode); } } finally { Win32Native.SetErrorMode(oldMode); } return fileSystemName.ToString(); } } public bool IsReady { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] get { return Directory.InternalExists(Name); } } public long AvailableFreeSpace { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { long userBytes, totalBytes, freeBytes; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) __Error.WinIODriveError(Name); } finally { Win32Native.SetErrorMode(oldMode); } return userBytes; } } public long TotalFreeSpace { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { long userBytes, totalBytes, freeBytes; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) __Error.WinIODriveError(Name); } finally { Win32Native.SetErrorMode(oldMode); } return freeBytes; } } public long TotalSize { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { // Don't cache this, to handle variable sized floppy drives // or other various removable media drives. long userBytes, totalBytes, freeBytes; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) __Error.WinIODriveError(Name); } finally { Win32Native.SetErrorMode(oldMode); } return totalBytes; } } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static DriveInfo[] GetDrives() { // Directory.GetLogicalDrives demands unmanaged code permission String[] drives = Directory.GetLogicalDrives(); DriveInfo[] di = new DriveInfo[drives.Length]; for(int i=0; i<drives.Length; i++) di[i] = new DriveInfo(drives[i]); return di; } public DirectoryInfo RootDirectory { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { return new DirectoryInfo(Name); } } // Null is a valid volume label. public String VolumeLabel { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { // NTFS uses a limit of 32 characters for the volume label, // as of Windows Server 2003. const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); if (!r) { int errorCode = Marshal.GetLastWin32Error(); // Win9x appears to return ERROR_INVALID_DATA when a // drive doesn't exist. if (errorCode == Win32Native.ERROR_INVALID_DATA) errorCode = Win32Native.ERROR_INVALID_DRIVE; __Error.WinIODriveError(Name, errorCode); } } finally { Win32Native.SetErrorMode(oldMode); } return volumeName.ToString(); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] set { String demandPath = _name + '.'; new FileIOPermission(FileIOPermissionAccess.Write, demandPath).Demand(); int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool r = Win32Native.SetVolumeLabel(Name, value); if (!r) { int errorCode = Marshal.GetLastWin32Error(); // Provide better message if (errorCode == Win32Native.ERROR_ACCESS_DENIED) throw new UnauthorizedAccessException(Environment.GetResourceString("InvalidOperation_SetVolumeLabelFailed")); __Error.WinIODriveError(Name, errorCode); } } finally { Win32Native.SetErrorMode(oldMode); } } } public override String ToString() { return Name; } #if FEATURE_SERIALIZATION /// <internalonly/> [System.Security.SecurityCritical] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // No need for an additional security check - everything is public. info.AddValue(NameField, _name, typeof(String)); } #endif } }
sekcheong/referencesource
mscorlib/system/io/driveinfo.cs
C#
mit
12,108
// // Mail.cpp // // $Id: //poco/svn/Net/samples/SMTPLogger/src/SMTPLogger.cpp#1 $ // // This sample demonstrates the SMTPChannel class. // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/Net/MailMessage.h" #include "Poco/Net/SMTPChannel.h" #include "Poco/Logger.h" #include "Poco/Path.h" #include "Poco/AutoPtr.h" #include "Poco/Exception.h" #include <iostream> using Poco::Net::SMTPChannel; using Poco::Logger; using Poco::Path; using Poco::AutoPtr; using Poco::Exception; #if defined(POCO_OS_FAMILY_UNIX) const std::string fileName = "${POCO_BASE}/Net/samples/SMTPLogger/res/logo.gif"; #elif defined(POCO_OS_FAMILY_WINDOWS) const std::string fileName = "%POCO_BASE%/Net/samples/SMTPLogger/res/logo.gif"; #endif int main(int argc, char** argv) { if (argc != 4) { Path p(argv[0]); std::cerr << "usage: " << p.getBaseName() << " <mailhost> <sender> <recipient>" << std::endl; std::cerr << " Send an email log entry from <sender> to <recipient>," << std::endl; std::cerr << " the SMTP server at <mailhost>." << std::endl; return 1; } std::string mailhost(argv[1]); std::string sender(argv[2]); std::string recipient(argv[3]); std::string attachment = Path::expand(fileName); try { AutoPtr<SMTPChannel> pSMTPChannel = new SMTPChannel(mailhost, sender, recipient); pSMTPChannel->setProperty("attachment", attachment); pSMTPChannel->setProperty("type", "image/gif"); pSMTPChannel->setProperty("delete", "false"); pSMTPChannel->setProperty("throw", "true"); Logger& logger = Logger::get("POCO Sample SMTP Logger"); logger.setChannel(pSMTPChannel.get()); logger.critical("Critical message"); } catch (Exception& exc) { std::cerr << exc.displayText() << std::endl; return 1; } return 0; }
weinzierl-engineering/baos
thirdparty/poco/Net/samples/SMTPLogger/src/SMTPLogger.cpp
C++
mit
1,855
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; function waitForElement(selector: string) { const EC = ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); } describe('animation example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { const URL = '/animation/dsl/'; it('should list out the current collection of items', () => { browser.get(URL); waitForElement('.toggle-container'); expect(element.all(by.css('.toggle-container')).get(0).getText()).toEqual('Look at this box'); }); }); });
JiaLiPassion/angular
packages/examples/core/animation/ts/dsl/e2e_test/animation_example_spec.ts
TypeScript
mit
936
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Shared.cs // // <OWNER>[....]</OWNER> // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace System.Linq.Parallel { /// <summary> /// A very simple primitive that allows us to share a value across multiple threads. /// </summary> /// <typeparam name="T"></typeparam> internal class Shared<T> { internal T Value; internal Shared(T value) { this.Value = value; } } }
sekcheong/referencesource
System.Core/System/Linq/Parallel/Utils/Shared.cs
C#
mit
676
// # Surrounds given text with Markdown syntax /*global $, CodeMirror, Showdown, moment */ (function () { 'use strict'; var Markdown = { init : function (options, elem) { var self = this; self.elem = elem; self.style = (typeof options === 'string') ? options : options.style; self.options = $.extend({}, CodeMirror.prototype.addMarkdown.options, options); self.replace(); }, replace: function () { var text = this.elem.getSelection(), pass = true, cursor = this.elem.getCursor(), line = this.elem.getLine(cursor.line), md, word, letterCount, converter, textIndex, position; switch (this.style) { case 'h1': this.elem.setLine(cursor.line, '# ' + line); this.elem.setCursor(cursor.line, cursor.ch + 2); pass = false; break; case 'h2': this.elem.setLine(cursor.line, '## ' + line); this.elem.setCursor(cursor.line, cursor.ch + 3); pass = false; break; case 'h3': this.elem.setLine(cursor.line, '### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 4); pass = false; break; case 'h4': this.elem.setLine(cursor.line, '#### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 5); pass = false; break; case 'h5': this.elem.setLine(cursor.line, '##### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 6); pass = false; break; case 'h6': this.elem.setLine(cursor.line, '###### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 7); pass = false; break; case 'link': md = this.options.syntax.link.replace('$1', text); this.elem.replaceSelection(md, 'end'); if (!text) { this.elem.setCursor(cursor.line, cursor.ch + 1); } else { textIndex = line.indexOf(text, cursor.ch - text.length); position = textIndex + md.length - 1; this.elem.setSelection({line: cursor.line, ch: position - 7}, {line: cursor.line, ch: position}); } pass = false; break; case 'image': md = this.options.syntax.image.replace('$1', text); if (line !== '') { md = "\n\n" + md; } this.elem.replaceSelection(md, "end"); cursor = this.elem.getCursor(); this.elem.setSelection({line: cursor.line, ch: cursor.ch - 8}, {line: cursor.line, ch: cursor.ch - 1}); pass = false; break; case 'uppercase': md = text.toLocaleUpperCase(); break; case 'lowercase': md = text.toLocaleLowerCase(); break; case 'titlecase': md = text.toTitleCase(); break; case 'selectword': word = this.elem.getTokenAt(cursor); if (!/\w$/g.test(word.string)) { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end - 1}); } else { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end}); } break; case 'copyHTML': converter = new Showdown.converter(); if (text) { md = converter.makeHtml(text); } else { md = converter.makeHtml(this.elem.getValue()); } $(".modal-copyToHTML-content").text(md).selectText(); pass = false; break; case 'list': md = text.replace(/^(\s*)(\w\W*)/gm, '$1* $2'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'currentDate': md = moment(new Date()).format('D MMMM YYYY'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'newLine': if (line !== "") { this.elem.setLine(cursor.line, line + "\n\n"); } pass = false; break; default: if (this.options.syntax[this.style]) { md = this.options.syntax[this.style].replace('$1', text); } } if (pass && md) { this.elem.replaceSelection(md, 'end'); if (!text) { letterCount = md.length; this.elem.setCursor({line: cursor.line, ch: cursor.ch - (letterCount / 2)}); } } } }; CodeMirror.prototype.addMarkdown = function (options) { var markdown = Object.create(Markdown); markdown.init(options, this); }; CodeMirror.prototype.addMarkdown.options = { style: null, syntax: { bold: '**$1**', italic: '*$1*', strike: '~~$1~~', code: '`$1`', link: '[$1](http://)', image: '![$1](http://)', blockquote: '> $1' } }; }());
jamesyothers/Ghost
core/clientold/markdown-actions.js
JavaScript
mit
5,697
// // EchoServer.cpp // // $Id: //poco/1.4/Net/testsuite/src/EchoServer.cpp#1 $ // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "EchoServer.h" #include "Poco/Net/StreamSocket.h" #include "Poco/Net/SocketAddress.h" #include "Poco/Timespan.h" #include <iostream> using Poco::Net::Socket; using Poco::Net::StreamSocket; using Poco::Net::SocketAddress; EchoServer::EchoServer(): _socket(SocketAddress()), _thread("EchoServer"), _stop(false) { _thread.start(*this); _ready.wait(); } EchoServer::~EchoServer() { _stop = true; _thread.join(); } Poco::UInt16 EchoServer::port() const { return _socket.address().port(); } void EchoServer::run() { _ready.set(); Poco::Timespan span(250000); while (!_stop) { if (_socket.poll(span, Socket::SELECT_READ)) { StreamSocket ss = _socket.acceptConnection(); try { char buffer[256]; int n = ss.receiveBytes(buffer, sizeof(buffer)); while (n > 0 && !_stop) { ss.sendBytes(buffer, n); n = ss.receiveBytes(buffer, sizeof(buffer)); } } catch (Poco::Exception& exc) { std::cerr << "EchoServer: " << exc.displayText() << std::endl; } } } }
weinzierl-engineering/baos
thirdparty/poco/Net/testsuite/src/EchoServer.cpp
C++
mit
1,255
#ifndef __SVM_H #define __SVM_H enum { INTERCEPT_INTR, INTERCEPT_NMI, INTERCEPT_SMI, INTERCEPT_INIT, INTERCEPT_VINTR, INTERCEPT_SELECTIVE_CR0, INTERCEPT_STORE_IDTR, INTERCEPT_STORE_GDTR, INTERCEPT_STORE_LDTR, INTERCEPT_STORE_TR, INTERCEPT_LOAD_IDTR, INTERCEPT_LOAD_GDTR, INTERCEPT_LOAD_LDTR, INTERCEPT_LOAD_TR, INTERCEPT_RDTSC, INTERCEPT_RDPMC, INTERCEPT_PUSHF, INTERCEPT_POPF, INTERCEPT_CPUID, INTERCEPT_RSM, INTERCEPT_IRET, INTERCEPT_INTn, INTERCEPT_INVD, INTERCEPT_PAUSE, INTERCEPT_HLT, INTERCEPT_INVLPG, INTERCEPT_INVLPGA, INTERCEPT_IOIO_PROT, INTERCEPT_MSR_PROT, INTERCEPT_TASK_SWITCH, INTERCEPT_FERR_FREEZE, INTERCEPT_SHUTDOWN, INTERCEPT_VMRUN, INTERCEPT_VMMCALL, INTERCEPT_VMLOAD, INTERCEPT_VMSAVE, INTERCEPT_STGI, INTERCEPT_CLGI, INTERCEPT_SKINIT, INTERCEPT_RDTSCP, INTERCEPT_ICEBP, INTERCEPT_WBINVD, }; struct __attribute__ ((__packed__)) vmcb_control_area { u16 intercept_cr_read; u16 intercept_cr_write; u16 intercept_dr_read; u16 intercept_dr_write; u32 intercept_exceptions; u64 intercept; u8 reserved_1[44]; u64 iopm_base_pa; u64 msrpm_base_pa; u64 tsc_offset; u32 asid; u8 tlb_ctl; u8 reserved_2[3]; u32 int_ctl; u32 int_vector; u32 int_state; u8 reserved_3[4]; u32 exit_code; u32 exit_code_hi; u64 exit_info_1; u64 exit_info_2; u32 exit_int_info; u32 exit_int_info_err; u64 nested_ctl; u8 reserved_4[16]; u32 event_inj; u32 event_inj_err; u64 nested_cr3; u64 lbr_ctl; u8 reserved_5[832]; }; #define TLB_CONTROL_DO_NOTHING 0 #define TLB_CONTROL_FLUSH_ALL_ASID 1 #define V_TPR_MASK 0x0f #define V_IRQ_SHIFT 8 #define V_IRQ_MASK (1 << V_IRQ_SHIFT) #define V_INTR_PRIO_SHIFT 16 #define V_INTR_PRIO_MASK (0x0f << V_INTR_PRIO_SHIFT) #define V_IGN_TPR_SHIFT 20 #define V_IGN_TPR_MASK (1 << V_IGN_TPR_SHIFT) #define V_INTR_MASKING_SHIFT 24 #define V_INTR_MASKING_MASK (1 << V_INTR_MASKING_SHIFT) #define SVM_INTERRUPT_SHADOW_MASK 1 #define SVM_IOIO_STR_SHIFT 2 #define SVM_IOIO_REP_SHIFT 3 #define SVM_IOIO_SIZE_SHIFT 4 #define SVM_IOIO_ASIZE_SHIFT 7 #define SVM_IOIO_TYPE_MASK 1 #define SVM_IOIO_STR_MASK (1 << SVM_IOIO_STR_SHIFT) #define SVM_IOIO_REP_MASK (1 << SVM_IOIO_REP_SHIFT) #define SVM_IOIO_SIZE_MASK (7 << SVM_IOIO_SIZE_SHIFT) #define SVM_IOIO_ASIZE_MASK (7 << SVM_IOIO_ASIZE_SHIFT) struct __attribute__ ((__packed__)) vmcb_seg { u16 selector; u16 attrib; u32 limit; u64 base; }; struct __attribute__ ((__packed__)) vmcb_save_area { struct vmcb_seg es; struct vmcb_seg cs; struct vmcb_seg ss; struct vmcb_seg ds; struct vmcb_seg fs; struct vmcb_seg gs; struct vmcb_seg gdtr; struct vmcb_seg ldtr; struct vmcb_seg idtr; struct vmcb_seg tr; u8 reserved_1[43]; u8 cpl; u8 reserved_2[4]; u64 efer; u8 reserved_3[112]; u64 cr4; u64 cr3; u64 cr0; u64 dr7; u64 dr6; u64 rflags; u64 rip; u8 reserved_4[88]; u64 rsp; u8 reserved_5[24]; u64 rax; u64 star; u64 lstar; u64 cstar; u64 sfmask; u64 kernel_gs_base; u64 sysenter_cs; u64 sysenter_esp; u64 sysenter_eip; u64 cr2; u8 reserved_6[32]; u64 g_pat; u64 dbgctl; u64 br_from; u64 br_to; u64 last_excp_from; u64 last_excp_to; }; struct __attribute__ ((__packed__)) vmcb { struct vmcb_control_area control; struct vmcb_save_area save; }; #define SVM_CPUID_FEATURE_SHIFT 2 #define SVM_CPUID_FUNC 0x8000000a #define MSR_EFER_SVME_MASK (1ULL << 12) #define MSR_VM_HSAVE_PA 0xc0010117ULL #define SVM_SELECTOR_S_SHIFT 4 #define SVM_SELECTOR_DPL_SHIFT 5 #define SVM_SELECTOR_P_SHIFT 7 #define SVM_SELECTOR_AVL_SHIFT 8 #define SVM_SELECTOR_L_SHIFT 9 #define SVM_SELECTOR_DB_SHIFT 10 #define SVM_SELECTOR_G_SHIFT 11 #define SVM_SELECTOR_TYPE_MASK (0xf) #define SVM_SELECTOR_S_MASK (1 << SVM_SELECTOR_S_SHIFT) #define SVM_SELECTOR_DPL_MASK (3 << SVM_SELECTOR_DPL_SHIFT) #define SVM_SELECTOR_P_MASK (1 << SVM_SELECTOR_P_SHIFT) #define SVM_SELECTOR_AVL_MASK (1 << SVM_SELECTOR_AVL_SHIFT) #define SVM_SELECTOR_L_MASK (1 << SVM_SELECTOR_L_SHIFT) #define SVM_SELECTOR_DB_MASK (1 << SVM_SELECTOR_DB_SHIFT) #define SVM_SELECTOR_G_MASK (1 << SVM_SELECTOR_G_SHIFT) #define SVM_SELECTOR_WRITE_MASK (1 << 1) #define SVM_SELECTOR_READ_MASK SVM_SELECTOR_WRITE_MASK #define SVM_SELECTOR_CODE_MASK (1 << 3) #define INTERCEPT_CR0_MASK 1 #define INTERCEPT_CR3_MASK (1 << 3) #define INTERCEPT_CR4_MASK (1 << 4) #define INTERCEPT_DR0_MASK 1 #define INTERCEPT_DR1_MASK (1 << 1) #define INTERCEPT_DR2_MASK (1 << 2) #define INTERCEPT_DR3_MASK (1 << 3) #define INTERCEPT_DR4_MASK (1 << 4) #define INTERCEPT_DR5_MASK (1 << 5) #define INTERCEPT_DR6_MASK (1 << 6) #define INTERCEPT_DR7_MASK (1 << 7) #define SVM_EVTINJ_VEC_MASK 0xff #define SVM_EVTINJ_TYPE_SHIFT 8 #define SVM_EVTINJ_TYPE_MASK (7 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_TYPE_INTR (0 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_TYPE_NMI (2 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_TYPE_EXEPT (3 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_TYPE_SOFT (4 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_VALID (1 << 31) #define SVM_EVTINJ_VALID_ERR (1 << 11) #define SVM_EXITINTINFO_VEC_MASK SVM_EVTINJ_VEC_MASK #define SVM_EXITINTINFO_TYPE_INTR SVM_EVTINJ_TYPE_INTR #define SVM_EXITINTINFO_TYPE_NMI SVM_EVTINJ_TYPE_NMI #define SVM_EXITINTINFO_TYPE_EXEPT SVM_EVTINJ_TYPE_EXEPT #define SVM_EXITINTINFO_TYPE_SOFT SVM_EVTINJ_TYPE_SOFT #define SVM_EXITINTINFO_VALID SVM_EVTINJ_VALID #define SVM_EXITINTINFO_VALID_ERR SVM_EVTINJ_VALID_ERR #define SVM_EXIT_READ_CR0 0x000 #define SVM_EXIT_READ_CR3 0x003 #define SVM_EXIT_READ_CR4 0x004 #define SVM_EXIT_READ_CR8 0x008 #define SVM_EXIT_WRITE_CR0 0x010 #define SVM_EXIT_WRITE_CR3 0x013 #define SVM_EXIT_WRITE_CR4 0x014 #define SVM_EXIT_WRITE_CR8 0x018 #define SVM_EXIT_READ_DR0 0x020 #define SVM_EXIT_READ_DR1 0x021 #define SVM_EXIT_READ_DR2 0x022 #define SVM_EXIT_READ_DR3 0x023 #define SVM_EXIT_READ_DR4 0x024 #define SVM_EXIT_READ_DR5 0x025 #define SVM_EXIT_READ_DR6 0x026 #define SVM_EXIT_READ_DR7 0x027 #define SVM_EXIT_WRITE_DR0 0x030 #define SVM_EXIT_WRITE_DR1 0x031 #define SVM_EXIT_WRITE_DR2 0x032 #define SVM_EXIT_WRITE_DR3 0x033 #define SVM_EXIT_WRITE_DR4 0x034 #define SVM_EXIT_WRITE_DR5 0x035 #define SVM_EXIT_WRITE_DR6 0x036 #define SVM_EXIT_WRITE_DR7 0x037 #define SVM_EXIT_EXCP_BASE 0x040 #define SVM_EXIT_INTR 0x060 #define SVM_EXIT_NMI 0x061 #define SVM_EXIT_SMI 0x062 #define SVM_EXIT_INIT 0x063 #define SVM_EXIT_VINTR 0x064 #define SVM_EXIT_CR0_SEL_WRITE 0x065 #define SVM_EXIT_IDTR_READ 0x066 #define SVM_EXIT_GDTR_READ 0x067 #define SVM_EXIT_LDTR_READ 0x068 #define SVM_EXIT_TR_READ 0x069 #define SVM_EXIT_IDTR_WRITE 0x06a #define SVM_EXIT_GDTR_WRITE 0x06b #define SVM_EXIT_LDTR_WRITE 0x06c #define SVM_EXIT_TR_WRITE 0x06d #define SVM_EXIT_RDTSC 0x06e #define SVM_EXIT_RDPMC 0x06f #define SVM_EXIT_PUSHF 0x070 #define SVM_EXIT_POPF 0x071 #define SVM_EXIT_CPUID 0x072 #define SVM_EXIT_RSM 0x073 #define SVM_EXIT_IRET 0x074 #define SVM_EXIT_SWINT 0x075 #define SVM_EXIT_INVD 0x076 #define SVM_EXIT_PAUSE 0x077 #define SVM_EXIT_HLT 0x078 #define SVM_EXIT_INVLPG 0x079 #define SVM_EXIT_INVLPGA 0x07a #define SVM_EXIT_IOIO 0x07b #define SVM_EXIT_MSR 0x07c #define SVM_EXIT_TASK_SWITCH 0x07d #define SVM_EXIT_FERR_FREEZE 0x07e #define SVM_EXIT_SHUTDOWN 0x07f #define SVM_EXIT_VMRUN 0x080 #define SVM_EXIT_VMMCALL 0x081 #define SVM_EXIT_VMLOAD 0x082 #define SVM_EXIT_VMSAVE 0x083 #define SVM_EXIT_STGI 0x084 #define SVM_EXIT_CLGI 0x085 #define SVM_EXIT_SKINIT 0x086 #define SVM_EXIT_RDTSCP 0x087 #define SVM_EXIT_ICEBP 0x088 #define SVM_EXIT_WBINVD 0x089 #define SVM_EXIT_NPF 0x400 #define SVM_EXIT_ERR -1 #define SVM_CR0_SELECTIVE_MASK (1 << 3 | 1) // TS and MP #define SVM_VMLOAD ".byte 0x0f, 0x01, 0xda" #define SVM_VMRUN ".byte 0x0f, 0x01, 0xd8" #define SVM_VMSAVE ".byte 0x0f, 0x01, 0xdb" #define SVM_CLGI ".byte 0x0f, 0x01, 0xdd" #define SVM_STGI ".byte 0x0f, 0x01, 0xdc" #define SVM_INVLPGA ".byte 0x0f, 0x01, 0xdf" #endif
impedimentToProgress/UCI-BlueChip
snapgear_linux/linux-2.6.21.1/drivers/kvm/svm.h
C
mit
7,902
/* * QtWebKit-powered headless test runner using PhantomJS * * PhantomJS binaries: http://phantomjs.org/download.html * Requires PhantomJS 1.6+ (1.7+ recommended) * * Run with: * phantomjs runner.js [url-of-your-qunit-testsuite] * * e.g. * phantomjs runner.js http://localhost/qunit/test/index.html */ /*global phantom:false, require:false, console:false, window:false, QUnit:false */ (function() { 'use strict'; var url, page, timeout, args = require('system').args; // arg[0]: scriptName, args[1...]: arguments if (args.length < 2 || args.length > 3) { console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite] [timeout-in-seconds]'); phantom.exit(1); } url = args[1]; page = require('webpage').create(); page.settings.clearMemoryCaches = true; if (args[2] !== undefined) { timeout = parseInt(args[2], 10); } // Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`) page.onConsoleMessage = function(msg) { console.log(msg); }; page.onInitialized = function() { page.evaluate(addLogging); }; page.onCallback = function(message) { var result, failed; if (message) { if (message.name === 'QUnit.done') { result = message.data; failed = !result || !result.total || result.failed; if (!result.total) { console.error('No tests were executed. Are you loading tests asynchronously?'); } phantom.exit(failed ? 1 : 0); } } }; page.open(url, function(status) { if (status !== 'success') { console.error('Unable to access network: ' + status); phantom.exit(1); } else { // Cannot do this verification with the 'DOMContentLoaded' handler because it // will be too late to attach it if a page does not have any script tags. var qunitMissing = page.evaluate(function() { return (typeof QUnit === 'undefined' || !QUnit); }); if (qunitMissing) { console.error('The `QUnit` object is not present on this page.'); phantom.exit(1); } // Set a timeout on the test running, otherwise tests with async problems will hang forever if (typeof timeout === 'number') { setTimeout(function() { console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...'); phantom.exit(1); }, timeout * 1000); } // Do nothing... the callback mechanism will handle everything! } }); function addLogging() { window.document.addEventListener('DOMContentLoaded', function() { var currentTestAssertions = []; QUnit.log(function(details) { var response; // Ignore passing assertions if (details.result) { return; } response = details.message || ''; if (typeof details.expected !== 'undefined') { if (response) { response += ', '; } response += 'expected: ' + details.expected + ', but was: ' + details.actual; } if (details.source) { response += "\n" + details.source; } currentTestAssertions.push('Failed assertion: ' + response); }); QUnit.testDone(function(result) { var i, len, name = result.module + ': ' + result.name; if (result.failed) { console.log('Test failed: ' + name); for (i = 0, len = currentTestAssertions.length; i < len; i++) { console.log(' ' + currentTestAssertions[i]); } } currentTestAssertions.length = 0; }); QUnit.done(function(result) { console.log('Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.'); if (typeof window.callPhantom === 'function') { window.callPhantom({ 'name': 'QUnit.done', 'data': result }); } }); }, false); } })();
greyhwndz/ember-sync
tests/runner.js
JavaScript
mit
3,753
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.nest.internal.data; import java.util.Date; import java.util.List; /** * The data for the camera. * * @author David Bennett - Initial contribution * @author Wouter Born - Add equals and hashCode methods */ public class Camera extends BaseNestDevice { private Boolean isStreaming; private Boolean isAudioInputEnabled; private Date lastIsOnlineChange; private Boolean isVideoHistoryEnabled; private String webUrl; private String appUrl; private Boolean isPublicShareEnabled; private List<ActivityZone> activityZones; private String publicShareUrl; private String snapshotUrl; private CameraEvent lastEvent; public Boolean isStreaming() { return isStreaming; } public Boolean isAudioInputEnabled() { return isAudioInputEnabled; } public Date getLastIsOnlineChange() { return lastIsOnlineChange; } public Boolean isVideoHistoryEnabled() { return isVideoHistoryEnabled; } public String getWebUrl() { return webUrl; } public String getAppUrl() { return appUrl; } public Boolean isPublicShareEnabled() { return isPublicShareEnabled; } public List<ActivityZone> getActivityZones() { return activityZones; } public String getPublicShareUrl() { return publicShareUrl; } public String getSnapshotUrl() { return snapshotUrl; } public CameraEvent getLastEvent() { return lastEvent; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Camera other = (Camera) obj; if (activityZones == null) { if (other.activityZones != null) { return false; } } else if (!activityZones.equals(other.activityZones)) { return false; } if (appUrl == null) { if (other.appUrl != null) { return false; } } else if (!appUrl.equals(other.appUrl)) { return false; } if (isAudioInputEnabled == null) { if (other.isAudioInputEnabled != null) { return false; } } else if (!isAudioInputEnabled.equals(other.isAudioInputEnabled)) { return false; } if (isPublicShareEnabled == null) { if (other.isPublicShareEnabled != null) { return false; } } else if (!isPublicShareEnabled.equals(other.isPublicShareEnabled)) { return false; } if (isStreaming == null) { if (other.isStreaming != null) { return false; } } else if (!isStreaming.equals(other.isStreaming)) { return false; } if (isVideoHistoryEnabled == null) { if (other.isVideoHistoryEnabled != null) { return false; } } else if (!isVideoHistoryEnabled.equals(other.isVideoHistoryEnabled)) { return false; } if (lastEvent == null) { if (other.lastEvent != null) { return false; } } else if (!lastEvent.equals(other.lastEvent)) { return false; } if (lastIsOnlineChange == null) { if (other.lastIsOnlineChange != null) { return false; } } else if (!lastIsOnlineChange.equals(other.lastIsOnlineChange)) { return false; } if (publicShareUrl == null) { if (other.publicShareUrl != null) { return false; } } else if (!publicShareUrl.equals(other.publicShareUrl)) { return false; } if (snapshotUrl == null) { if (other.snapshotUrl != null) { return false; } } else if (!snapshotUrl.equals(other.snapshotUrl)) { return false; } if (webUrl == null) { if (other.webUrl != null) { return false; } } else if (!webUrl.equals(other.webUrl)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((activityZones == null) ? 0 : activityZones.hashCode()); result = prime * result + ((appUrl == null) ? 0 : appUrl.hashCode()); result = prime * result + ((isAudioInputEnabled == null) ? 0 : isAudioInputEnabled.hashCode()); result = prime * result + ((isPublicShareEnabled == null) ? 0 : isPublicShareEnabled.hashCode()); result = prime * result + ((isStreaming == null) ? 0 : isStreaming.hashCode()); result = prime * result + ((isVideoHistoryEnabled == null) ? 0 : isVideoHistoryEnabled.hashCode()); result = prime * result + ((lastEvent == null) ? 0 : lastEvent.hashCode()); result = prime * result + ((lastIsOnlineChange == null) ? 0 : lastIsOnlineChange.hashCode()); result = prime * result + ((publicShareUrl == null) ? 0 : publicShareUrl.hashCode()); result = prime * result + ((snapshotUrl == null) ? 0 : snapshotUrl.hashCode()); result = prime * result + ((webUrl == null) ? 0 : webUrl.hashCode()); return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Camera [isStreaming=").append(isStreaming).append(", isAudioInputEnabled=") .append(isAudioInputEnabled).append(", lastIsOnlineChange=").append(lastIsOnlineChange) .append(", isVideoHistoryEnabled=").append(isVideoHistoryEnabled).append(", webUrl=").append(webUrl) .append(", appUrl=").append(appUrl).append(", isPublicShareEnabled=").append(isPublicShareEnabled) .append(", activityZones=").append(activityZones).append(", publicShareUrl=").append(publicShareUrl) .append(", snapshotUrl=").append(snapshotUrl).append(", lastEvent=").append(lastEvent) .append(", getId()=").append(getId()).append(", getName()=").append(getName()) .append(", getDeviceId()=").append(getDeviceId()).append(", getLastConnection()=") .append(getLastConnection()).append(", isOnline()=").append(isOnline()).append(", getNameLong()=") .append(getNameLong()).append(", getSoftwareVersion()=").append(getSoftwareVersion()) .append(", getStructureId()=").append(getStructureId()).append(", getWhereId()=").append(getWhereId()) .append("]"); return builder.toString(); } }
theoweiss/openhab2
bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/data/Camera.java
Java
epl-1.0
7,310
#ifndef BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_ROUTE_HPP #define BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_ROUTE_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // polymorphic_oarchive_route.hpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is 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 updates, documentation, and revision history. #include <string> #include <ostream> #include <cstddef> // size_t #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::size_t; } // namespace std #endif #include <boost/cstdint.hpp> #include <boost/integer_traits.hpp> #include <boost/archive/polymorphic_oarchive.hpp> #include <boost/archive/detail/abi_prefix.hpp> // must be the last header namespace boost { namespace serialization { class extended_type_info; } // namespace serialization namespace archive { namespace detail{ class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_oserializer; class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_pointer_oserializer; #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable : 4511 4512) #endif template<class ArchiveImplementation> class polymorphic_oarchive_route : public polymorphic_oarchive, // note: gcc dynamic cross cast fails if the the derivation below is // not public. I think this is a mistake. public /*protected*/ ArchiveImplementation { private: // these are used by the serialization library. virtual void save_object( const void *x, const detail::basic_oserializer & bos ){ ArchiveImplementation::save_object(x, bos); } virtual void save_pointer( const void * t, const detail::basic_pointer_oserializer * bpos_ptr ){ ArchiveImplementation::save_pointer(t, bpos_ptr); } virtual void save_null_pointer(){ ArchiveImplementation::save_null_pointer(); } // primitive types the only ones permitted by polymorphic archives virtual void save(const bool t){ ArchiveImplementation::save(t); } virtual void save(const char t){ ArchiveImplementation::save(t); } virtual void save(const signed char t){ ArchiveImplementation::save(t); } virtual void save(const unsigned char t){ ArchiveImplementation::save(t); } #ifndef BOOST_NO_CWCHAR #ifndef BOOST_NO_INTRINSIC_WCHAR_T virtual void save(const wchar_t t){ ArchiveImplementation::save(t); } #endif #endif virtual void save(const short t){ ArchiveImplementation::save(t); } virtual void save(const unsigned short t){ ArchiveImplementation::save(t); } virtual void save(const int t){ ArchiveImplementation::save(t); } virtual void save(const unsigned int t){ ArchiveImplementation::save(t); } virtual void save(const long t){ ArchiveImplementation::save(t); } virtual void save(const unsigned long t){ ArchiveImplementation::save(t); } #if defined(BOOST_HAS_LONG_LONG) virtual void save(const boost::long_long_type t){ ArchiveImplementation::save(t); } virtual void save(const boost::ulong_long_type t){ ArchiveImplementation::save(t); } #elif defined(BOOST_HAS_MS_INT64) virtual void save(const boost::int64_t t){ ArchiveImplementation::save(t); } virtual void save(const boost::uint64_t t){ ArchiveImplementation::save(t); } #endif virtual void save(const float t){ ArchiveImplementation::save(t); } virtual void save(const double t){ ArchiveImplementation::save(t); } virtual void save(const std::string & t){ ArchiveImplementation::save(t); } #ifndef BOOST_NO_STD_WSTRING virtual void save(const std::wstring & t){ ArchiveImplementation::save(t); } #endif virtual library_version_type get_library_version() const{ return ArchiveImplementation::get_library_version(); } virtual unsigned int get_flags() const { return ArchiveImplementation::get_flags(); } virtual void save_binary(const void * t, std::size_t size){ ArchiveImplementation::save_binary(t, size); } // used for xml and other tagged formats default does nothing virtual void save_start(const char * name){ ArchiveImplementation::save_start(name); } virtual void save_end(const char * name){ ArchiveImplementation::save_end(name); } virtual void end_preamble(){ ArchiveImplementation::end_preamble(); } virtual void register_basic_serializer(const detail::basic_oserializer & bos){ ArchiveImplementation::register_basic_serializer(bos); } public: // this can't be inheriteded because they appear in mulitple // parents typedef mpl::bool_<false> is_loading; typedef mpl::bool_<true> is_saving; // the << operator template<class T> polymorphic_oarchive & operator<<(T & t){ return polymorphic_oarchive::operator<<(t); } // the & operator template<class T> polymorphic_oarchive & operator&(T & t){ return polymorphic_oarchive::operator&(t); } // register type function template<class T> const basic_pointer_oserializer * register_type(T * t = NULL){ return ArchiveImplementation::register_type(t); } // all current archives take a stream as constructor argument template <class _Elem, class _Tr> polymorphic_oarchive_route( std::basic_ostream<_Elem, _Tr> & os, unsigned int flags = 0 ) : ArchiveImplementation(os, flags) {} virtual ~polymorphic_oarchive_route(){}; }; } // namespace detail } // namespace archive } // namespace boost #ifdef BOOST_MSVC #pragma warning(pop) #endif #include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas #endif // BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_DISPATCH_HPP
Cyberbeing/xy-VSFilter
src/thirdparty/boost_lib/boost/archive/detail/polymorphic_oarchive_route.hpp
C++
gpl-2.0
6,467
/* Functional tests for the "target" attribute and pragma. */ /* { dg-do assemble { target { ! lp64 } } } */ /* { dg-require-effective-target target_attribute } */ /* { dg-options "-save-temps -mdebug -m31 -march=z10 -mtune=z13 -mstack-size=2048 -mstack-guard=16 -mbranch-cost=1 -mwarn-framesize=512 -mno-hard-dfp -mbackchain -msoft-float -mno-vx -mno-htm -mno-packed-stack -msmall-exec -mno-zvector -mmvcle -mesa -mno-warn-dynamicstack" } */ /** ** ** Start ** **/ void fn_default_start (void) { } /* { dg-final { scan-assembler "fn:fn_default_start ar4" } } */ /* { dg-final { scan-assembler "fn:fn_default_start tu7" } } */ /* { dg-final { scan-assembler "fn:fn_default_start ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_default_start sg16" } } */ /* { dg-final { scan-assembler "fn:fn_default_start bc1" } } */ /* { dg-final { scan-assembler "fn:fn_default_start wf512" } } */ /* { dg-final { scan-assembler "fn:fn_default_start hd0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start ba1" } } */ /* { dg-final { scan-assembler "fn:fn_default_start hf0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start vx0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start ht0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start ps0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start se1" } } */ /* { dg-final { scan-assembler "fn:fn_default_start zv0" } } */ /* { dg-final { scan-assembler "fn:fn_default_start mv1" } } */ /* { dg-final { scan-assembler "fn:fn_default_start wd0" } } */ /** ** ** Attribute ** **/ __attribute__ ((target ("no-mvcle"))) void fn_att_0 (void) { } /* { dg-final { scan-assembler "fn:fn_att_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0 wd0" } } */ void fn_att_0_default (void) { } __attribute__ ((target ("mvcle"))) void fn_att_1 (void) { } /* { dg-final { scan-assembler "fn:fn_att_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1 wd0" } } */ void fn_att_1_default (void) { } __attribute__ ((target ("mvcle,no-mvcle"))) void fn_att_1_0 (void) { } /* { dg-final { scan-assembler "fn:fn_att_1_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_1_0 wd0" } } */ __attribute__ ((target ("no-mvcle,mvcle"))) void fn_att_0_1 (void) { } /* { dg-final { scan-assembler "fn:fn_att_0_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_att_0_1 wd0" } } */ /** ** ** Pragma ** **/ #pragma GCC target ("no-mvcle") void fn_pragma_0 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0 wd0" } } */ #pragma GCC reset_options void fn_pragma_0_default (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_0_default ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_default wd0" } } */ #pragma GCC target ("mvcle") void fn_pragma_1 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1 wd0" } } */ #pragma GCC reset_options void fn_pragma_1_default (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_1_default ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_default wd0" } } */ #pragma GCC target ("mvcle") #pragma GCC target ("no-mvcle") void fn_pragma_1_0 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_1_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_0 wd0" } } */ #pragma GCC reset_options #pragma GCC target ("no-mvcle") #pragma GCC target ("mvcle") void fn_pragma_0_1 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_0_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_1 wd0" } } */ #pragma GCC reset_options /** ** ** Pragma and attribute ** **/ #pragma GCC target ("no-mvcle") __attribute__ ((target ("no-mvcle"))) void fn_pragma_0_att_0 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 wd0" } } */ #pragma GCC reset_options #pragma GCC target ("no-mvcle") __attribute__ ((target ("no-mvcle"))) void fn_pragma_1_att_0 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 mv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 wd0" } } */ #pragma GCC reset_options #pragma GCC target ("no-mvcle") __attribute__ ((target ("mvcle"))) void fn_pragma_0_att_1 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 wd0" } } */ #pragma GCC reset_options #pragma GCC target ("no-mvcle") __attribute__ ((target ("mvcle"))) void fn_pragma_1_att_1 (void) { } /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 mv1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ar4" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 tu7" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 sg16" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 bc1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 wf512" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 hd0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ba1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 hf0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 vx0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ht0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ps0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 se1" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 zv0" } } */ /* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 wd0" } } */ #pragma GCC reset_options /** ** ** End ** **/ void fn_default_end (void) { } /* { dg-final { scan-assembler "fn:fn_default_end ar4" } } */ /* { dg-final { scan-assembler "fn:fn_default_end tu7" } } */ /* { dg-final { scan-assembler "fn:fn_default_end ss2048" } } */ /* { dg-final { scan-assembler "fn:fn_default_end sg16" } } */ /* { dg-final { scan-assembler "fn:fn_default_end bc1" } } */ /* { dg-final { scan-assembler "fn:fn_default_end wf512" } } */ /* { dg-final { scan-assembler "fn:fn_default_end hd0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end ba1" } } */ /* { dg-final { scan-assembler "fn:fn_default_end hf0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end vx0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end ht0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end ps0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end se1" } } */ /* { dg-final { scan-assembler "fn:fn_default_end zv0" } } */ /* { dg-final { scan-assembler "fn:fn_default_end mv1" } } */ /* { dg-final { scan-assembler "fn:fn_default_end wd0" } } */
Gurgel100/gcc
gcc/testsuite/gcc.target/s390/target-attribute/tattr-m31-28.c
C
gpl-2.0
17,909
/* vi: set sw=4 ts=4: */ /* * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ #include "libbb.h" #include <math.h> //usage:#define dc_trivial_usage //usage: "EXPRESSION..." //usage: //usage:#define dc_full_usage "\n\n" //usage: "Tiny RPN calculator. Operations:\n" //usage: "+, add, -, sub, *, mul, /, div, %, mod, "IF_FEATURE_DC_LIBM("**, exp, ")"and, or, not, xor,\n" //usage: "p - print top of the stack (without popping),\n" //usage: "f - print entire stack,\n" //usage: "o - pop the value and set output radix (must be 10, 16, 8 or 2).\n" //usage: "Examples: 'dc 2 2 add p' -> 4, 'dc 8 8 mul 2 2 + / p' -> 16" //usage: //usage:#define dc_example_usage //usage: "$ dc 2 2 + p\n" //usage: "4\n" //usage: "$ dc 8 8 \\* 2 2 + / p\n" //usage: "16\n" //usage: "$ dc 0 1 and p\n" //usage: "0\n" //usage: "$ dc 0 1 or p\n" //usage: "1\n" //usage: "$ echo 72 9 div 8 mul p | dc\n" //usage: "64\n" #if 0 typedef unsigned data_t; #define DATA_FMT "" #elif 0 typedef unsigned long data_t; #define DATA_FMT "l" #else typedef unsigned long long data_t; #define DATA_FMT "ll" #endif struct globals { unsigned pointer; unsigned base; double stack[1]; } FIX_ALIASING; enum { STACK_SIZE = (COMMON_BUFSIZE - offsetof(struct globals, stack)) / sizeof(double) }; #define G (*(struct globals*)&bb_common_bufsiz1) #define pointer (G.pointer ) #define base (G.base ) #define stack (G.stack ) #define INIT_G() do { \ base = 10; \ } while (0) static void check_under(void) { if (pointer == 0) bb_error_msg_and_die("stack underflow"); } static void push(double a) { if (pointer >= STACK_SIZE) bb_error_msg_and_die("stack overflow"); stack[pointer++] = a; } static double pop(void) { check_under(); return stack[--pointer]; } static void add(void) { push(pop() + pop()); } static void sub(void) { double subtrahend = pop(); push(pop() - subtrahend); } static void mul(void) { push(pop() * pop()); } #if ENABLE_FEATURE_DC_LIBM static void power(void) { double topower = pop(); push(pow(pop(), topower)); } #endif static void divide(void) { double divisor = pop(); push(pop() / divisor); } static void mod(void) { data_t d = pop(); push((data_t) pop() % d); } static void and(void) { push((data_t) pop() & (data_t) pop()); } static void or(void) { push((data_t) pop() | (data_t) pop()); } static void eor(void) { push((data_t) pop() ^ (data_t) pop()); } static void not(void) { push(~(data_t) pop()); } static void set_output_base(void) { static const char bases[] ALIGN1 = { 2, 8, 10, 16, 0 }; unsigned b = (unsigned)pop(); base = *strchrnul(bases, b); if (base == 0) { bb_error_msg("error, base %u is not supported", b); base = 10; } } static void print_base(double print) { data_t x, i; x = (data_t) print; if (base == 10) { if (x == print) /* exactly representable as unsigned integer */ printf("%"DATA_FMT"u\n", x); else printf("%g\n", print); return; } switch (base) { case 16: printf("%"DATA_FMT"x\n", x); break; case 8: printf("%"DATA_FMT"o\n", x); break; default: /* base 2 */ i = MAXINT(data_t) - (MAXINT(data_t) >> 1); /* i is 100000...00000 */ do { if (x & i) break; i >>= 1; } while (i > 1); do { bb_putchar('1' - !(x & i)); i >>= 1; } while (i); bb_putchar('\n'); } } static void print_stack_no_pop(void) { unsigned i = pointer; while (i) print_base(stack[--i]); } static void print_no_pop(void) { check_under(); print_base(stack[pointer-1]); } struct op { const char name[4]; void (*function) (void); }; static const struct op operators[] = { #if ENABLE_FEATURE_DC_LIBM {"**", power}, {"exp", power}, {"pow", power}, #endif {"%", mod}, {"mod", mod}, {"and", and}, {"or", or}, {"not", not}, {"eor", eor}, {"xor", eor}, {"+", add}, {"add", add}, {"-", sub}, {"sub", sub}, {"*", mul}, {"mul", mul}, {"/", divide}, {"div", divide}, {"p", print_no_pop}, {"f", print_stack_no_pop}, {"o", set_output_base}, }; /* Feed the stack machine */ static void stack_machine(const char *argument) { char *end; double number; const struct op *o; next: number = strtod(argument, &end); if (end != argument) { argument = end; push(number); goto next; } /* We might have matched a digit, eventually advance the argument */ argument = skip_whitespace(argument); if (*argument == '\0') return; o = operators; do { char *after_name = is_prefixed_with(argument, o->name); if (after_name) { argument = after_name; o->function(); goto next; } o++; } while (o != operators + ARRAY_SIZE(operators)); bb_error_msg_and_die("syntax error at '%s'", argument); } int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; int dc_main(int argc UNUSED_PARAM, char **argv) { INIT_G(); argv++; if (!argv[0]) { /* take stuff from stdin if no args are given */ char *line; while ((line = xmalloc_fgetline(stdin)) != NULL) { stack_machine(line); free(line); } } else { do { stack_machine(*argv); } while (*++argv); } return EXIT_SUCCESS; }
insane-adding-machines/busybox
miscutils/dc.c
C
gpl-2.0
5,182
/* * Copyright Gavin Shan, IBM Corporation 2016. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <net/ncsi.h> #include <net/net_namespace.h> #include <net/sock.h> #include <net/genetlink.h> #include "internal.h" #include "ncsi-pkt.h" #include "ncsi-netlink.h" static int ncsi_validate_rsp_pkt(struct ncsi_request *nr, unsigned short payload) { struct ncsi_rsp_pkt_hdr *h; u32 checksum; __be32 *pchecksum; /* Check NCSI packet header. We don't need validate * the packet type, which should have been checked * before calling this function. */ h = (struct ncsi_rsp_pkt_hdr *)skb_network_header(nr->rsp); if (h->common.revision != NCSI_PKT_REVISION) { netdev_dbg(nr->ndp->ndev.dev, "NCSI: unsupported header revision\n"); return -EINVAL; } if (ntohs(h->common.length) != payload) { netdev_dbg(nr->ndp->ndev.dev, "NCSI: payload length mismatched\n"); return -EINVAL; } /* Check on code and reason */ if (ntohs(h->code) != NCSI_PKT_RSP_C_COMPLETED || ntohs(h->reason) != NCSI_PKT_RSP_R_NO_ERROR) { netdev_dbg(nr->ndp->ndev.dev, "NCSI: non zero response/reason code\n"); return -EPERM; } /* Validate checksum, which might be zeroes if the * sender doesn't support checksum according to NCSI * specification. */ pchecksum = (__be32 *)((void *)(h + 1) + payload - 4); if (ntohl(*pchecksum) == 0) return 0; checksum = ncsi_calculate_checksum((unsigned char *)h, sizeof(*h) + payload - 4); if (*pchecksum != htonl(checksum)) { netdev_dbg(nr->ndp->ndev.dev, "NCSI: checksum mismatched\n"); return -EINVAL; } return 0; } static int ncsi_rsp_handler_cis(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_package *np; struct ncsi_channel *nc; unsigned char id; rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, &nc); if (!nc) { if (ndp->flags & NCSI_DEV_PROBED) return -ENXIO; id = NCSI_CHANNEL_INDEX(rsp->rsp.common.channel); nc = ncsi_add_channel(np, id); } return nc ? 0 : -ENODEV; } static int ncsi_rsp_handler_sp(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_package *np; unsigned char id; /* Add the package if it's not existing. Otherwise, * to change the state of its child channels. */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, NULL); if (!np) { if (ndp->flags & NCSI_DEV_PROBED) return -ENXIO; id = NCSI_PACKAGE_INDEX(rsp->rsp.common.channel); np = ncsi_add_package(ndp, id); if (!np) return -ENODEV; } return 0; } static int ncsi_rsp_handler_dp(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_package *np; struct ncsi_channel *nc; unsigned long flags; /* Find the package */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, NULL); if (!np) return -ENODEV; /* Change state of all channels attached to the package */ NCSI_FOR_EACH_CHANNEL(np, nc) { spin_lock_irqsave(&nc->lock, flags); nc->state = NCSI_CHANNEL_INACTIVE; spin_unlock_irqrestore(&nc->lock, flags); } return 0; } static int ncsi_rsp_handler_ec(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; ncm = &nc->modes[NCSI_MODE_ENABLE]; if (ncm->enable) return 0; ncm->enable = 1; return 0; } static int ncsi_rsp_handler_dc(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; int ret; ret = ncsi_validate_rsp_pkt(nr, 4); if (ret) return ret; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; ncm = &nc->modes[NCSI_MODE_ENABLE]; if (!ncm->enable) return 0; ncm->enable = 0; return 0; } static int ncsi_rsp_handler_rc(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; unsigned long flags; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update state for the specified channel */ spin_lock_irqsave(&nc->lock, flags); nc->state = NCSI_CHANNEL_INACTIVE; spin_unlock_irqrestore(&nc->lock, flags); return 0; } static int ncsi_rsp_handler_ecnt(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; ncm = &nc->modes[NCSI_MODE_TX_ENABLE]; if (ncm->enable) return 0; ncm->enable = 1; return 0; } static int ncsi_rsp_handler_dcnt(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; ncm = &nc->modes[NCSI_MODE_TX_ENABLE]; if (!ncm->enable) return 0; ncm->enable = 1; return 0; } static int ncsi_rsp_handler_ae(struct ncsi_request *nr) { struct ncsi_cmd_ae_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if the AEN has been enabled */ ncm = &nc->modes[NCSI_MODE_AEN]; if (ncm->enable) return 0; /* Update to AEN configuration */ cmd = (struct ncsi_cmd_ae_pkt *)skb_network_header(nr->cmd); ncm->enable = 1; ncm->data[0] = cmd->mc_id; ncm->data[1] = ntohl(cmd->mode); return 0; } static int ncsi_rsp_handler_sl(struct ncsi_request *nr) { struct ncsi_cmd_sl_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; cmd = (struct ncsi_cmd_sl_pkt *)skb_network_header(nr->cmd); ncm = &nc->modes[NCSI_MODE_LINK]; ncm->data[0] = ntohl(cmd->mode); ncm->data[1] = ntohl(cmd->oem_mode); return 0; } static int ncsi_rsp_handler_gls(struct ncsi_request *nr) { struct ncsi_rsp_gls_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; unsigned long flags; /* Find the package and channel */ rsp = (struct ncsi_rsp_gls_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; ncm = &nc->modes[NCSI_MODE_LINK]; ncm->data[2] = ntohl(rsp->status); ncm->data[3] = ntohl(rsp->other); ncm->data[4] = ntohl(rsp->oem_status); if (nr->flags & NCSI_REQ_FLAG_EVENT_DRIVEN) return 0; /* Reset the channel monitor if it has been enabled */ spin_lock_irqsave(&nc->lock, flags); nc->monitor.state = NCSI_CHANNEL_MONITOR_START; spin_unlock_irqrestore(&nc->lock, flags); return 0; } static int ncsi_rsp_handler_svf(struct ncsi_request *nr) { struct ncsi_cmd_svf_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_vlan_filter *ncf; unsigned long flags; void *bitmap; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; cmd = (struct ncsi_cmd_svf_pkt *)skb_network_header(nr->cmd); ncf = &nc->vlan_filter; if (cmd->index == 0 || cmd->index > ncf->n_vids) return -ERANGE; /* Add or remove the VLAN filter. Remember HW indexes from 1 */ spin_lock_irqsave(&nc->lock, flags); bitmap = &ncf->bitmap; if (!(cmd->enable & 0x1)) { if (test_and_clear_bit(cmd->index - 1, bitmap)) ncf->vids[cmd->index - 1] = 0; } else { set_bit(cmd->index - 1, bitmap); ncf->vids[cmd->index - 1] = ntohs(cmd->vlan); } spin_unlock_irqrestore(&nc->lock, flags); return 0; } static int ncsi_rsp_handler_ev(struct ncsi_request *nr) { struct ncsi_cmd_ev_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if VLAN mode has been enabled */ ncm = &nc->modes[NCSI_MODE_VLAN]; if (ncm->enable) return 0; /* Update to VLAN mode */ cmd = (struct ncsi_cmd_ev_pkt *)skb_network_header(nr->cmd); ncm->enable = 1; ncm->data[0] = ntohl(cmd->mode); return 0; } static int ncsi_rsp_handler_dv(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if VLAN mode has been enabled */ ncm = &nc->modes[NCSI_MODE_VLAN]; if (!ncm->enable) return 0; /* Update to VLAN mode */ ncm->enable = 0; return 0; } static int ncsi_rsp_handler_sma(struct ncsi_request *nr) { struct ncsi_cmd_sma_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mac_filter *ncf; unsigned long flags; void *bitmap; bool enabled; int index; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* According to NCSI spec 1.01, the mixed filter table * isn't supported yet. */ cmd = (struct ncsi_cmd_sma_pkt *)skb_network_header(nr->cmd); enabled = cmd->at_e & 0x1; ncf = &nc->mac_filter; bitmap = &ncf->bitmap; if (cmd->index == 0 || cmd->index > ncf->n_uc + ncf->n_mc + ncf->n_mixed) return -ERANGE; index = (cmd->index - 1) * ETH_ALEN; spin_lock_irqsave(&nc->lock, flags); if (enabled) { set_bit(cmd->index - 1, bitmap); memcpy(&ncf->addrs[index], cmd->mac, ETH_ALEN); } else { clear_bit(cmd->index - 1, bitmap); memset(&ncf->addrs[index], 0, ETH_ALEN); } spin_unlock_irqrestore(&nc->lock, flags); return 0; } static int ncsi_rsp_handler_ebf(struct ncsi_request *nr) { struct ncsi_cmd_ebf_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the package and channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if broadcast filter has been enabled */ ncm = &nc->modes[NCSI_MODE_BC]; if (ncm->enable) return 0; /* Update to broadcast filter mode */ cmd = (struct ncsi_cmd_ebf_pkt *)skb_network_header(nr->cmd); ncm->enable = 1; ncm->data[0] = ntohl(cmd->mode); return 0; } static int ncsi_rsp_handler_dbf(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if broadcast filter isn't enabled */ ncm = &nc->modes[NCSI_MODE_BC]; if (!ncm->enable) return 0; /* Update to broadcast filter mode */ ncm->enable = 0; ncm->data[0] = 0; return 0; } static int ncsi_rsp_handler_egmf(struct ncsi_request *nr) { struct ncsi_cmd_egmf_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if multicast filter has been enabled */ ncm = &nc->modes[NCSI_MODE_MC]; if (ncm->enable) return 0; /* Update to multicast filter mode */ cmd = (struct ncsi_cmd_egmf_pkt *)skb_network_header(nr->cmd); ncm->enable = 1; ncm->data[0] = ntohl(cmd->mode); return 0; } static int ncsi_rsp_handler_dgmf(struct ncsi_request *nr) { struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if multicast filter has been enabled */ ncm = &nc->modes[NCSI_MODE_MC]; if (!ncm->enable) return 0; /* Update to multicast filter mode */ ncm->enable = 0; ncm->data[0] = 0; return 0; } static int ncsi_rsp_handler_snfc(struct ncsi_request *nr) { struct ncsi_cmd_snfc_pkt *cmd; struct ncsi_rsp_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_mode *ncm; /* Find the channel */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Check if flow control has been enabled */ ncm = &nc->modes[NCSI_MODE_FC]; if (ncm->enable) return 0; /* Update to flow control mode */ cmd = (struct ncsi_cmd_snfc_pkt *)skb_network_header(nr->cmd); ncm->enable = 1; ncm->data[0] = cmd->mode; return 0; } /* Response handler for Broadcom command Get Mac Address */ static int ncsi_rsp_handler_oem_bcm_gma(struct ncsi_request *nr) { struct ncsi_dev_priv *ndp = nr->ndp; struct net_device *ndev = ndp->ndev.dev; const struct net_device_ops *ops = ndev->netdev_ops; struct ncsi_rsp_oem_pkt *rsp; struct sockaddr saddr; int ret = 0; /* Get the response header */ rsp = (struct ncsi_rsp_oem_pkt *)skb_network_header(nr->rsp); saddr.sa_family = ndev->type; ndev->priv_flags |= IFF_LIVE_ADDR_CHANGE; memcpy(saddr.sa_data, &rsp->data[BCM_MAC_ADDR_OFFSET], ETH_ALEN); /* Increase mac address by 1 for BMC's address */ saddr.sa_data[ETH_ALEN - 1]++; ret = ops->ndo_set_mac_address(ndev, &saddr); if (ret < 0) netdev_warn(ndev, "NCSI: 'Writing mac address to device failed\n"); return ret; } /* Response handler for Broadcom card */ static int ncsi_rsp_handler_oem_bcm(struct ncsi_request *nr) { struct ncsi_rsp_oem_bcm_pkt *bcm; struct ncsi_rsp_oem_pkt *rsp; /* Get the response header */ rsp = (struct ncsi_rsp_oem_pkt *)skb_network_header(nr->rsp); bcm = (struct ncsi_rsp_oem_bcm_pkt *)(rsp->data); if (bcm->type == NCSI_OEM_BCM_CMD_GMA) return ncsi_rsp_handler_oem_bcm_gma(nr); return 0; } static struct ncsi_rsp_oem_handler { unsigned int mfr_id; int (*handler)(struct ncsi_request *nr); } ncsi_rsp_oem_handlers[] = { { NCSI_OEM_MFR_MLX_ID, NULL }, { NCSI_OEM_MFR_BCM_ID, ncsi_rsp_handler_oem_bcm } }; /* Response handler for OEM command */ static int ncsi_rsp_handler_oem(struct ncsi_request *nr) { struct ncsi_rsp_oem_handler *nrh = NULL; struct ncsi_rsp_oem_pkt *rsp; unsigned int mfr_id, i; /* Get the response header */ rsp = (struct ncsi_rsp_oem_pkt *)skb_network_header(nr->rsp); mfr_id = ntohl(rsp->mfr_id); /* Check for manufacturer id and Find the handler */ for (i = 0; i < ARRAY_SIZE(ncsi_rsp_oem_handlers); i++) { if (ncsi_rsp_oem_handlers[i].mfr_id == mfr_id) { if (ncsi_rsp_oem_handlers[i].handler) nrh = &ncsi_rsp_oem_handlers[i]; else nrh = NULL; break; } } if (!nrh) { netdev_err(nr->ndp->ndev.dev, "Received unrecognized OEM packet with MFR-ID (0x%x)\n", mfr_id); return -ENOENT; } /* Process the packet */ return nrh->handler(nr); } static int ncsi_rsp_handler_gvi(struct ncsi_request *nr) { struct ncsi_rsp_gvi_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_version *ncv; int i; /* Find the channel */ rsp = (struct ncsi_rsp_gvi_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update to channel's version info */ ncv = &nc->version; ncv->version = ntohl(rsp->ncsi_version); ncv->alpha2 = rsp->alpha2; memcpy(ncv->fw_name, rsp->fw_name, 12); ncv->fw_version = ntohl(rsp->fw_version); for (i = 0; i < ARRAY_SIZE(ncv->pci_ids); i++) ncv->pci_ids[i] = ntohs(rsp->pci_ids[i]); ncv->mf_id = ntohl(rsp->mf_id); return 0; } static int ncsi_rsp_handler_gc(struct ncsi_request *nr) { struct ncsi_rsp_gc_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; size_t size; /* Find the channel */ rsp = (struct ncsi_rsp_gc_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update channel's capabilities */ nc->caps[NCSI_CAP_GENERIC].cap = ntohl(rsp->cap) & NCSI_CAP_GENERIC_MASK; nc->caps[NCSI_CAP_BC].cap = ntohl(rsp->bc_cap) & NCSI_CAP_BC_MASK; nc->caps[NCSI_CAP_MC].cap = ntohl(rsp->mc_cap) & NCSI_CAP_MC_MASK; nc->caps[NCSI_CAP_BUFFER].cap = ntohl(rsp->buf_cap); nc->caps[NCSI_CAP_AEN].cap = ntohl(rsp->aen_cap) & NCSI_CAP_AEN_MASK; nc->caps[NCSI_CAP_VLAN].cap = rsp->vlan_mode & NCSI_CAP_VLAN_MASK; size = (rsp->uc_cnt + rsp->mc_cnt + rsp->mixed_cnt) * ETH_ALEN; nc->mac_filter.addrs = kzalloc(size, GFP_ATOMIC); if (!nc->mac_filter.addrs) return -ENOMEM; nc->mac_filter.n_uc = rsp->uc_cnt; nc->mac_filter.n_mc = rsp->mc_cnt; nc->mac_filter.n_mixed = rsp->mixed_cnt; nc->vlan_filter.vids = kcalloc(rsp->vlan_cnt, sizeof(*nc->vlan_filter.vids), GFP_ATOMIC); if (!nc->vlan_filter.vids) return -ENOMEM; /* Set VLAN filters active so they are cleared in the first * configuration state */ nc->vlan_filter.bitmap = U64_MAX; nc->vlan_filter.n_vids = rsp->vlan_cnt; return 0; } static int ncsi_rsp_handler_gp(struct ncsi_request *nr) { struct ncsi_channel_vlan_filter *ncvf; struct ncsi_channel_mac_filter *ncmf; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_rsp_gp_pkt *rsp; struct ncsi_channel *nc; unsigned short enable; unsigned char *pdata; unsigned long flags; void *bitmap; int i; /* Find the channel */ rsp = (struct ncsi_rsp_gp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Modes with explicit enabled indications */ if (ntohl(rsp->valid_modes) & 0x1) { /* BC filter mode */ nc->modes[NCSI_MODE_BC].enable = 1; nc->modes[NCSI_MODE_BC].data[0] = ntohl(rsp->bc_mode); } if (ntohl(rsp->valid_modes) & 0x2) /* Channel enabled */ nc->modes[NCSI_MODE_ENABLE].enable = 1; if (ntohl(rsp->valid_modes) & 0x4) /* Channel Tx enabled */ nc->modes[NCSI_MODE_TX_ENABLE].enable = 1; if (ntohl(rsp->valid_modes) & 0x8) /* MC filter mode */ nc->modes[NCSI_MODE_MC].enable = 1; /* Modes without explicit enabled indications */ nc->modes[NCSI_MODE_LINK].enable = 1; nc->modes[NCSI_MODE_LINK].data[0] = ntohl(rsp->link_mode); nc->modes[NCSI_MODE_VLAN].enable = 1; nc->modes[NCSI_MODE_VLAN].data[0] = rsp->vlan_mode; nc->modes[NCSI_MODE_FC].enable = 1; nc->modes[NCSI_MODE_FC].data[0] = rsp->fc_mode; nc->modes[NCSI_MODE_AEN].enable = 1; nc->modes[NCSI_MODE_AEN].data[0] = ntohl(rsp->aen_mode); /* MAC addresses filter table */ pdata = (unsigned char *)rsp + 48; enable = rsp->mac_enable; ncmf = &nc->mac_filter; spin_lock_irqsave(&nc->lock, flags); bitmap = &ncmf->bitmap; for (i = 0; i < rsp->mac_cnt; i++, pdata += 6) { if (!(enable & (0x1 << i))) clear_bit(i, bitmap); else set_bit(i, bitmap); memcpy(&ncmf->addrs[i * ETH_ALEN], pdata, ETH_ALEN); } spin_unlock_irqrestore(&nc->lock, flags); /* VLAN filter table */ enable = ntohs(rsp->vlan_enable); ncvf = &nc->vlan_filter; bitmap = &ncvf->bitmap; spin_lock_irqsave(&nc->lock, flags); for (i = 0; i < rsp->vlan_cnt; i++, pdata += 2) { if (!(enable & (0x1 << i))) clear_bit(i, bitmap); else set_bit(i, bitmap); ncvf->vids[i] = ntohs(*(__be16 *)pdata); } spin_unlock_irqrestore(&nc->lock, flags); return 0; } static int ncsi_rsp_handler_gcps(struct ncsi_request *nr) { struct ncsi_rsp_gcps_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_stats *ncs; /* Find the channel */ rsp = (struct ncsi_rsp_gcps_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update HNC's statistics */ ncs = &nc->stats; ncs->hnc_cnt_hi = ntohl(rsp->cnt_hi); ncs->hnc_cnt_lo = ntohl(rsp->cnt_lo); ncs->hnc_rx_bytes = ntohl(rsp->rx_bytes); ncs->hnc_tx_bytes = ntohl(rsp->tx_bytes); ncs->hnc_rx_uc_pkts = ntohl(rsp->rx_uc_pkts); ncs->hnc_rx_mc_pkts = ntohl(rsp->rx_mc_pkts); ncs->hnc_rx_bc_pkts = ntohl(rsp->rx_bc_pkts); ncs->hnc_tx_uc_pkts = ntohl(rsp->tx_uc_pkts); ncs->hnc_tx_mc_pkts = ntohl(rsp->tx_mc_pkts); ncs->hnc_tx_bc_pkts = ntohl(rsp->tx_bc_pkts); ncs->hnc_fcs_err = ntohl(rsp->fcs_err); ncs->hnc_align_err = ntohl(rsp->align_err); ncs->hnc_false_carrier = ntohl(rsp->false_carrier); ncs->hnc_runt_pkts = ntohl(rsp->runt_pkts); ncs->hnc_jabber_pkts = ntohl(rsp->jabber_pkts); ncs->hnc_rx_pause_xon = ntohl(rsp->rx_pause_xon); ncs->hnc_rx_pause_xoff = ntohl(rsp->rx_pause_xoff); ncs->hnc_tx_pause_xon = ntohl(rsp->tx_pause_xon); ncs->hnc_tx_pause_xoff = ntohl(rsp->tx_pause_xoff); ncs->hnc_tx_s_collision = ntohl(rsp->tx_s_collision); ncs->hnc_tx_m_collision = ntohl(rsp->tx_m_collision); ncs->hnc_l_collision = ntohl(rsp->l_collision); ncs->hnc_e_collision = ntohl(rsp->e_collision); ncs->hnc_rx_ctl_frames = ntohl(rsp->rx_ctl_frames); ncs->hnc_rx_64_frames = ntohl(rsp->rx_64_frames); ncs->hnc_rx_127_frames = ntohl(rsp->rx_127_frames); ncs->hnc_rx_255_frames = ntohl(rsp->rx_255_frames); ncs->hnc_rx_511_frames = ntohl(rsp->rx_511_frames); ncs->hnc_rx_1023_frames = ntohl(rsp->rx_1023_frames); ncs->hnc_rx_1522_frames = ntohl(rsp->rx_1522_frames); ncs->hnc_rx_9022_frames = ntohl(rsp->rx_9022_frames); ncs->hnc_tx_64_frames = ntohl(rsp->tx_64_frames); ncs->hnc_tx_127_frames = ntohl(rsp->tx_127_frames); ncs->hnc_tx_255_frames = ntohl(rsp->tx_255_frames); ncs->hnc_tx_511_frames = ntohl(rsp->tx_511_frames); ncs->hnc_tx_1023_frames = ntohl(rsp->tx_1023_frames); ncs->hnc_tx_1522_frames = ntohl(rsp->tx_1522_frames); ncs->hnc_tx_9022_frames = ntohl(rsp->tx_9022_frames); ncs->hnc_rx_valid_bytes = ntohl(rsp->rx_valid_bytes); ncs->hnc_rx_runt_pkts = ntohl(rsp->rx_runt_pkts); ncs->hnc_rx_jabber_pkts = ntohl(rsp->rx_jabber_pkts); return 0; } static int ncsi_rsp_handler_gns(struct ncsi_request *nr) { struct ncsi_rsp_gns_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_stats *ncs; /* Find the channel */ rsp = (struct ncsi_rsp_gns_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update HNC's statistics */ ncs = &nc->stats; ncs->ncsi_rx_cmds = ntohl(rsp->rx_cmds); ncs->ncsi_dropped_cmds = ntohl(rsp->dropped_cmds); ncs->ncsi_cmd_type_errs = ntohl(rsp->cmd_type_errs); ncs->ncsi_cmd_csum_errs = ntohl(rsp->cmd_csum_errs); ncs->ncsi_rx_pkts = ntohl(rsp->rx_pkts); ncs->ncsi_tx_pkts = ntohl(rsp->tx_pkts); ncs->ncsi_tx_aen_pkts = ntohl(rsp->tx_aen_pkts); return 0; } static int ncsi_rsp_handler_gnpts(struct ncsi_request *nr) { struct ncsi_rsp_gnpts_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_channel *nc; struct ncsi_channel_stats *ncs; /* Find the channel */ rsp = (struct ncsi_rsp_gnpts_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, NULL, &nc); if (!nc) return -ENODEV; /* Update HNC's statistics */ ncs = &nc->stats; ncs->pt_tx_pkts = ntohl(rsp->tx_pkts); ncs->pt_tx_dropped = ntohl(rsp->tx_dropped); ncs->pt_tx_channel_err = ntohl(rsp->tx_channel_err); ncs->pt_tx_us_err = ntohl(rsp->tx_us_err); ncs->pt_rx_pkts = ntohl(rsp->rx_pkts); ncs->pt_rx_dropped = ntohl(rsp->rx_dropped); ncs->pt_rx_channel_err = ntohl(rsp->rx_channel_err); ncs->pt_rx_us_err = ntohl(rsp->rx_us_err); ncs->pt_rx_os_err = ntohl(rsp->rx_os_err); return 0; } static int ncsi_rsp_handler_gps(struct ncsi_request *nr) { struct ncsi_rsp_gps_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_package *np; /* Find the package */ rsp = (struct ncsi_rsp_gps_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, NULL); if (!np) return -ENODEV; return 0; } static int ncsi_rsp_handler_gpuuid(struct ncsi_request *nr) { struct ncsi_rsp_gpuuid_pkt *rsp; struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_package *np; /* Find the package */ rsp = (struct ncsi_rsp_gpuuid_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, NULL); if (!np) return -ENODEV; memcpy(np->uuid, rsp->uuid, sizeof(rsp->uuid)); return 0; } static int ncsi_rsp_handler_netlink(struct ncsi_request *nr) { struct ncsi_dev_priv *ndp = nr->ndp; struct ncsi_rsp_pkt *rsp; struct ncsi_package *np; struct ncsi_channel *nc; int ret; /* Find the package */ rsp = (struct ncsi_rsp_pkt *)skb_network_header(nr->rsp); ncsi_find_package_and_channel(ndp, rsp->rsp.common.channel, &np, &nc); if (!np) return -ENODEV; ret = ncsi_send_netlink_rsp(nr, np, nc); return ret; } static struct ncsi_rsp_handler { unsigned char type; int payload; int (*handler)(struct ncsi_request *nr); } ncsi_rsp_handlers[] = { { NCSI_PKT_RSP_CIS, 4, ncsi_rsp_handler_cis }, { NCSI_PKT_RSP_SP, 4, ncsi_rsp_handler_sp }, { NCSI_PKT_RSP_DP, 4, ncsi_rsp_handler_dp }, { NCSI_PKT_RSP_EC, 4, ncsi_rsp_handler_ec }, { NCSI_PKT_RSP_DC, 4, ncsi_rsp_handler_dc }, { NCSI_PKT_RSP_RC, 4, ncsi_rsp_handler_rc }, { NCSI_PKT_RSP_ECNT, 4, ncsi_rsp_handler_ecnt }, { NCSI_PKT_RSP_DCNT, 4, ncsi_rsp_handler_dcnt }, { NCSI_PKT_RSP_AE, 4, ncsi_rsp_handler_ae }, { NCSI_PKT_RSP_SL, 4, ncsi_rsp_handler_sl }, { NCSI_PKT_RSP_GLS, 16, ncsi_rsp_handler_gls }, { NCSI_PKT_RSP_SVF, 4, ncsi_rsp_handler_svf }, { NCSI_PKT_RSP_EV, 4, ncsi_rsp_handler_ev }, { NCSI_PKT_RSP_DV, 4, ncsi_rsp_handler_dv }, { NCSI_PKT_RSP_SMA, 4, ncsi_rsp_handler_sma }, { NCSI_PKT_RSP_EBF, 4, ncsi_rsp_handler_ebf }, { NCSI_PKT_RSP_DBF, 4, ncsi_rsp_handler_dbf }, { NCSI_PKT_RSP_EGMF, 4, ncsi_rsp_handler_egmf }, { NCSI_PKT_RSP_DGMF, 4, ncsi_rsp_handler_dgmf }, { NCSI_PKT_RSP_SNFC, 4, ncsi_rsp_handler_snfc }, { NCSI_PKT_RSP_GVI, 40, ncsi_rsp_handler_gvi }, { NCSI_PKT_RSP_GC, 32, ncsi_rsp_handler_gc }, { NCSI_PKT_RSP_GP, -1, ncsi_rsp_handler_gp }, { NCSI_PKT_RSP_GCPS, 172, ncsi_rsp_handler_gcps }, { NCSI_PKT_RSP_GNS, 172, ncsi_rsp_handler_gns }, { NCSI_PKT_RSP_GNPTS, 172, ncsi_rsp_handler_gnpts }, { NCSI_PKT_RSP_GPS, 8, ncsi_rsp_handler_gps }, { NCSI_PKT_RSP_OEM, -1, ncsi_rsp_handler_oem }, { NCSI_PKT_RSP_PLDM, 0, NULL }, { NCSI_PKT_RSP_GPUUID, 20, ncsi_rsp_handler_gpuuid } }; int ncsi_rcv_rsp(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct ncsi_rsp_handler *nrh = NULL; struct ncsi_dev *nd; struct ncsi_dev_priv *ndp; struct ncsi_request *nr; struct ncsi_pkt_hdr *hdr; unsigned long flags; int payload, i, ret; /* Find the NCSI device */ nd = ncsi_find_dev(dev); ndp = nd ? TO_NCSI_DEV_PRIV(nd) : NULL; if (!ndp) return -ENODEV; /* Check if it is AEN packet */ hdr = (struct ncsi_pkt_hdr *)skb_network_header(skb); if (hdr->type == NCSI_PKT_AEN) return ncsi_aen_handler(ndp, skb); /* Find the handler */ for (i = 0; i < ARRAY_SIZE(ncsi_rsp_handlers); i++) { if (ncsi_rsp_handlers[i].type == hdr->type) { if (ncsi_rsp_handlers[i].handler) nrh = &ncsi_rsp_handlers[i]; else nrh = NULL; break; } } if (!nrh) { netdev_err(nd->dev, "Received unrecognized packet (0x%x)\n", hdr->type); return -ENOENT; } /* Associate with the request */ spin_lock_irqsave(&ndp->lock, flags); nr = &ndp->requests[hdr->id]; if (!nr->used) { spin_unlock_irqrestore(&ndp->lock, flags); return -ENODEV; } nr->rsp = skb; if (!nr->enabled) { spin_unlock_irqrestore(&ndp->lock, flags); ret = -ENOENT; goto out; } /* Validate the packet */ spin_unlock_irqrestore(&ndp->lock, flags); payload = nrh->payload; if (payload < 0) payload = ntohs(hdr->length); ret = ncsi_validate_rsp_pkt(nr, payload); if (ret) { netdev_warn(ndp->ndev.dev, "NCSI: 'bad' packet ignored for type 0x%x\n", hdr->type); if (nr->flags == NCSI_REQ_FLAG_NETLINK_DRIVEN) { if (ret == -EPERM) goto out_netlink; else ncsi_send_netlink_err(ndp->ndev.dev, nr->snd_seq, nr->snd_portid, &nr->nlhdr, ret); } goto out; } /* Process the packet */ ret = nrh->handler(nr); if (ret) netdev_err(ndp->ndev.dev, "NCSI: Handler for packet type 0x%x returned %d\n", hdr->type, ret); out_netlink: if (nr->flags == NCSI_REQ_FLAG_NETLINK_DRIVEN) { ret = ncsi_rsp_handler_netlink(nr); if (ret) { netdev_err(ndp->ndev.dev, "NCSI: Netlink handler for packet type 0x%x returned %d\n", hdr->type, ret); } } out: ncsi_free_request(nr); return ret; }
codeaurora-unoffical/linux-msm
net/ncsi/ncsi-rsp.c
C
gpl-2.0
31,425
/* * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "prims/jvm.h" #include "runtime/os.hpp" #include "utilities/decoder.hpp" #include "utilities/vmError.hpp" #if defined(_WINDOWS) #include "decoder_windows.hpp" #elif defined(__APPLE__) #include "decoder_machO.hpp" #elif defined(AIX) #include "decoder_aix.hpp" #else #include "decoder_elf.hpp" #endif AbstractDecoder* Decoder::_shared_decoder = NULL; AbstractDecoder* Decoder::_error_handler_decoder = NULL; NullDecoder Decoder::_do_nothing_decoder; Mutex* Decoder::_shared_decoder_lock = new Mutex(Mutex::native, "SharedDecoderLock", false, Monitor::_safepoint_check_never); AbstractDecoder* Decoder::get_shared_instance() { assert(_shared_decoder_lock != NULL && _shared_decoder_lock->owned_by_self(), "Require DecoderLock to enter"); if (_shared_decoder == NULL) { _shared_decoder = create_decoder(); } return _shared_decoder; } AbstractDecoder* Decoder::get_error_handler_instance() { if (_error_handler_decoder == NULL) { _error_handler_decoder = create_decoder(); } return _error_handler_decoder; } AbstractDecoder* Decoder::create_decoder() { AbstractDecoder* decoder; #if defined(_WINDOWS) decoder = new (std::nothrow) WindowsDecoder(); #elif defined (__APPLE__) decoder = new (std::nothrow)MachODecoder(); #elif defined(AIX) decoder = new (std::nothrow)AIXDecoder(); #else decoder = new (std::nothrow)ElfDecoder(); #endif if (decoder == NULL || decoder->has_error()) { if (decoder != NULL) { delete decoder; } decoder = &_do_nothing_decoder; } return decoder; } inline bool DecoderLocker::is_first_error_thread() { return (os::current_thread_id() == VMError::get_first_error_tid()); } DecoderLocker::DecoderLocker() : MutexLockerEx(DecoderLocker::is_first_error_thread() ? NULL : Decoder::shared_decoder_lock(), true) { _decoder = is_first_error_thread() ? Decoder::get_error_handler_instance() : Decoder::get_shared_instance(); assert(_decoder != NULL, "null decoder"); } Mutex* Decoder::shared_decoder_lock() { assert(_shared_decoder_lock != NULL, "Just check"); return _shared_decoder_lock; } bool Decoder::decode(address addr, char* buf, int buflen, int* offset, const char* modulepath, bool demangle) { assert(_shared_decoder_lock != NULL, "Just check"); bool error_handling_thread = os::current_thread_id() == VMError::first_error_tid; MutexLockerEx locker(error_handling_thread ? NULL : _shared_decoder_lock, true); AbstractDecoder* decoder = error_handling_thread ? get_error_handler_instance(): get_shared_instance(); assert(decoder != NULL, "null decoder"); return decoder->decode(addr, buf, buflen, offset, modulepath, demangle); } bool Decoder::decode(address addr, char* buf, int buflen, int* offset, const void* base) { assert(_shared_decoder_lock != NULL, "Just check"); bool error_handling_thread = os::current_thread_id() == VMError::first_error_tid; MutexLockerEx locker(error_handling_thread ? NULL : _shared_decoder_lock, true); AbstractDecoder* decoder = error_handling_thread ? get_error_handler_instance(): get_shared_instance(); assert(decoder != NULL, "null decoder"); return decoder->decode(addr, buf, buflen, offset, base); } bool Decoder::demangle(const char* symbol, char* buf, int buflen) { assert(_shared_decoder_lock != NULL, "Just check"); bool error_handling_thread = os::current_thread_id() == VMError::first_error_tid; MutexLockerEx locker(error_handling_thread ? NULL : _shared_decoder_lock, true); AbstractDecoder* decoder = error_handling_thread ? get_error_handler_instance(): get_shared_instance(); assert(decoder != NULL, "null decoder"); return decoder->demangle(symbol, buf, buflen); } bool Decoder::can_decode_C_frame_in_vm() { assert(_shared_decoder_lock != NULL, "Just check"); bool error_handling_thread = os::current_thread_id() == VMError::first_error_tid; MutexLockerEx locker(error_handling_thread ? NULL : _shared_decoder_lock, true); AbstractDecoder* decoder = error_handling_thread ? get_error_handler_instance(): get_shared_instance(); assert(decoder != NULL, "null decoder"); return decoder->can_decode_C_frame_in_vm(); } /* * Shutdown shared decoder and replace it with * _do_nothing_decoder. Do nothing with error handler * instance, since the JVM is going down. */ void Decoder::shutdown() { assert(_shared_decoder_lock != NULL, "Just check"); MutexLockerEx locker(_shared_decoder_lock, true); if (_shared_decoder != NULL && _shared_decoder != &_do_nothing_decoder) { delete _shared_decoder; } _shared_decoder = &_do_nothing_decoder; }
gaoxiaojun/dync
src/share/vm/utilities/decoder.cpp
C++
gpl-2.0
5,823
<?php /** * @package Joomla.Installation * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; jimport('joomla.application.component.view'); /** * The HTML Joomla Core Pre-Install View * * @package Joomla.Installation * @since 1.6 */ class JInstallationViewPreinstall extends JView { /** * Display the view * * @param string * * @return void * @since 1.6 */ public function display($tpl = null) { $this->state = $this->get('State'); $this->settings = $this->get('PhpSettings'); $this->options = $this->get('PhpOptions'); $this->sufficient = $this->get('PhpOptionsSufficient'); $this->version = new JVersion; // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } parent::display($tpl); } }
SuperFamousGuy/AdLib
tmp/install_4f31d69ae5bd9/installation/views/preinstall/view.html.php
PHP
gpl-2.0
965
<?php /** * @package Warp Theme Framework * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl.html GNU/GPL */ // check common $this['check']->checkCommon(); // check writable foreach (array($this['path']->path('cache:'), $this['path']->path('template:')) as $directory) { $this['check']->checkWritable($directory); } // output $critical = $this['check']->getIssues('critical'); $notice = $this['check']->getIssues('notice'); if ($critical || $notice) { $label = array(); if ($critical) { $label[] = count($critical).' critical'; } if ($notice) { $label[] = count($notice).' potential'; } echo '<a href="#" class="systemcheck-link '.($critical ? 'critical' : '').'">'.implode(' and ', $label).' issue(s) detected.</a>'; echo '<ul class="systemcheck">'; echo implode('', array_map(create_function('$message', 'return "<li class=\"critical\">{$message}</li>";'), $critical)); echo implode('', array_map(create_function('$message', 'return "<li>{$message}</li>";'), $notice)); echo '</ul>'; } else { echo "Warp engine operational and ready for take off."; }
theluxdev/dorseys-before
wp-content/themes/yoo_solar_wp/warp/systems/wordpress/config/layouts/fields/check.php
PHP
gpl-2.0
1,164
/* Copyright (c) 2008-2015, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/fb.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/fdtable.h> #include <linux/list.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/dma-buf.h> #include <linux/pm_runtime.h> #include <linux/rbtree.h> #include <linux/ashmem.h> #include <linux/major.h> #include <linux/io.h> #include <linux/mman.h> #include <linux/sort.h> #include <linux/security.h> #include <linux/compat.h> #include <asm/cacheflush.h> #include "kgsl.h" #include "kgsl_debugfs.h" #include "kgsl_cffdump.h" #include "kgsl_log.h" #include "kgsl_sharedmem.h" #include "kgsl_device.h" #include "kgsl_trace.h" #include "kgsl_sync.h" #include "adreno.h" #include "kgsl_compat.h" #undef MODULE_PARAM_PREFIX #define MODULE_PARAM_PREFIX "kgsl." #ifndef arch_mmap_check #define arch_mmap_check(addr, len, flags) (0) #endif #ifndef pgprot_writebackcache #define pgprot_writebackcache(_prot) (_prot) #endif #ifndef pgprot_writethroughcache #define pgprot_writethroughcache(_prot) (_prot) #endif #ifdef CONFIG_ARM_LPAE #define KGSL_DMA_BIT_MASK DMA_BIT_MASK(64) #else #define KGSL_DMA_BIT_MASK DMA_BIT_MASK(32) #endif /* * Define an kmem cache for the memobj structures since we allocate and free * them so frequently */ static struct kmem_cache *memobjs_cache; static char *ksgl_mmu_type; module_param_named(mmutype, ksgl_mmu_type, charp, 0); MODULE_PARM_DESC(ksgl_mmu_type, "Type of MMU to be used for graphics. Valid values are 'iommu' or 'nommu'"); struct kgsl_dma_buf_meta { struct dma_buf_attachment *attach; struct dma_buf *dmabuf; struct sg_table *table; }; static void kgsl_mem_entry_detach_process(struct kgsl_mem_entry *entry); static int kgsl_setup_dma_buf(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, struct kgsl_device *device, struct dma_buf *dmabuf); static const struct file_operations kgsl_fops; static int __kgsl_check_collision(struct kgsl_process_private *private, struct kgsl_mem_entry *entry, unsigned long *gpuaddr, unsigned long len, int flag_top_down); /* * The memfree list contains the last N blocks of memory that have been freed. * On a GPU fault we walk the list to see if the faulting address had been * recently freed and print out a message to that effect */ #define MEMFREE_ENTRIES 512 static DEFINE_SPINLOCK(memfree_lock); struct memfree_entry { unsigned long gpuaddr; unsigned long size; pid_t pid; unsigned int flags; }; static struct { struct memfree_entry *list; int head; int tail; } memfree; static int kgsl_memfree_init(void) { memfree.list = kzalloc(MEMFREE_ENTRIES * sizeof(struct memfree_entry), GFP_KERNEL); return (memfree.list) ? 0 : -ENOMEM; } static void kgsl_memfree_exit(void) { kfree(memfree.list); memset(&memfree, 0, sizeof(memfree)); } int kgsl_memfree_find_entry(pid_t pid, unsigned long *gpuaddr, unsigned long *size, unsigned int *flags) { int ptr; if (memfree.list == NULL) return 0; spin_lock(&memfree_lock); ptr = memfree.head - 1; if (ptr < 0) ptr = MEMFREE_ENTRIES - 1; /* Walk backwards through the list looking for the last match */ while (ptr != memfree.tail) { struct memfree_entry *entry = &memfree.list[ptr]; if ((entry->pid == pid) && (*gpuaddr >= entry->gpuaddr && *gpuaddr < (entry->gpuaddr + entry->size))) { *gpuaddr = entry->gpuaddr; *flags = entry->flags; *size = entry->size; spin_unlock(&memfree_lock); return 1; } ptr = ptr - 1; if (ptr < 0) ptr = MEMFREE_ENTRIES - 1; } spin_unlock(&memfree_lock); return 0; } static void kgsl_memfree_add(pid_t pid, unsigned int gpuaddr, unsigned int size, int flags) { struct memfree_entry *entry; if (memfree.list == NULL) return; spin_lock(&memfree_lock); entry = &memfree.list[memfree.head]; entry->pid = pid; entry->gpuaddr = gpuaddr; entry->size = size; entry->flags = flags; memfree.head = (memfree.head + 1) % MEMFREE_ENTRIES; if (memfree.head == memfree.tail) memfree.tail = (memfree.tail + 1) % MEMFREE_ENTRIES; spin_unlock(&memfree_lock); } int kgsl_readtimestamp(struct kgsl_device *device, void *priv, enum kgsl_timestamp_type type, unsigned int *timestamp) { return device->ftbl->readtimestamp(device, priv, type, timestamp); } EXPORT_SYMBOL(kgsl_readtimestamp); static inline struct kgsl_mem_entry * kgsl_mem_entry_create(void) { struct kgsl_mem_entry *entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (entry) kref_init(&entry->refcount); return entry; } #ifdef CONFIG_DMA_SHARED_BUFFER static void kgsl_destroy_ion(struct kgsl_dma_buf_meta *meta) { if (meta != NULL) { dma_buf_unmap_attachment(meta->attach, meta->table, DMA_FROM_DEVICE); dma_buf_detach(meta->dmabuf, meta->attach); dma_buf_put(meta->dmabuf); kfree(meta); } } #else static void kgsl_destroy_ion(struct kgsl_dma_buf_meta *meta) { } #endif void kgsl_mem_entry_destroy(struct kref *kref) { struct kgsl_mem_entry *entry = container_of(kref, struct kgsl_mem_entry, refcount); unsigned int memtype; if (entry == NULL) return; /* pull out the memtype before the flags get cleared */ memtype = kgsl_memdesc_usermem_type(&entry->memdesc); /* Detach from process list */ kgsl_mem_entry_detach_process(entry); if (memtype != KGSL_MEM_ENTRY_KERNEL) kgsl_driver.stats.mapped -= entry->memdesc.size; /* * Ion takes care of freeing the sglist for us so * clear the sg before freeing the sharedmem so kgsl_sharedmem_free * doesn't try to free it again */ if (memtype == KGSL_MEM_ENTRY_ION) entry->memdesc.sg = NULL; if ((memtype == KGSL_MEM_ENTRY_USER || memtype == KGSL_MEM_ENTRY_ASHMEM) && !(entry->memdesc.flags & KGSL_MEMFLAGS_GPUREADONLY)) { int i = 0, j; struct scatterlist *sg; struct page *page; /* * Mark all of pages in the scatterlist as dirty since they * were writable by the GPU. */ for_each_sg(entry->memdesc.sg, sg, entry->memdesc.sglen, i) { page = sg_page(sg); for (j = 0; j < (sg->length >> PAGE_SHIFT); j++) set_page_dirty(nth_page(page, j)); } } kgsl_sharedmem_free(&entry->memdesc); switch (memtype) { case KGSL_MEM_ENTRY_PMEM: case KGSL_MEM_ENTRY_ASHMEM: if (entry->priv_data) fput(entry->priv_data); break; case KGSL_MEM_ENTRY_ION: kgsl_destroy_ion(entry->priv_data); break; default: break; } kfree(entry); } EXPORT_SYMBOL(kgsl_mem_entry_destroy); /** * kgsl_mem_entry_track_gpuaddr - Insert a mem_entry in the address tree and * assign it with a gpu address space before insertion * @process: the process that owns the memory * @entry: the memory entry * * @returns - 0 on succcess else error code * * Insert the kgsl_mem_entry in to the rb_tree for searching by GPU address. * The assignment of gpu address and insertion into list needs to * happen with the memory lock held to avoid race conditions between * gpu address being selected and some other thread looking through the * rb list in search of memory based on gpuaddr * This function should be called with processes memory spinlock held */ static int kgsl_mem_entry_track_gpuaddr(struct kgsl_process_private *process, struct kgsl_mem_entry *entry) { int ret = 0; struct rb_node **node; struct rb_node *parent = NULL; struct kgsl_pagetable *pagetable = process->pagetable; assert_spin_locked(&process->mem_lock); /* * If cpu=gpu map is used then caller needs to set the * gpu address */ if (kgsl_memdesc_use_cpu_map(&entry->memdesc)) { if (!entry->memdesc.gpuaddr) goto done; } else if (entry->memdesc.gpuaddr) { WARN_ONCE(1, "gpuaddr assigned w/o holding memory lock\n"); ret = -EINVAL; goto done; } if (kgsl_memdesc_is_secured(&entry->memdesc)) pagetable = pagetable->mmu->securepagetable; ret = kgsl_mmu_get_gpuaddr(pagetable, &entry->memdesc); if (ret) goto done; node = &process->mem_rb.rb_node; while (*node) { struct kgsl_mem_entry *cur; parent = *node; cur = rb_entry(parent, struct kgsl_mem_entry, node); if (entry->memdesc.gpuaddr < cur->memdesc.gpuaddr) node = &parent->rb_left; else node = &parent->rb_right; } rb_link_node(&entry->node, parent, node); rb_insert_color(&entry->node, &process->mem_rb); done: return ret; } /** * kgsl_mem_entry_untrack_gpuaddr() - Untrack memory that is previously tracked * process - Pointer to process private to which memory belongs * entry - Memory entry to untrack * * Function just does the opposite of kgsl_mem_entry_track_gpuaddr. Needs to be * called with processes spin lock held */ static void kgsl_mem_entry_untrack_gpuaddr(struct kgsl_process_private *process, struct kgsl_mem_entry *entry) { assert_spin_locked(&process->mem_lock); if (entry->memdesc.gpuaddr) { kgsl_mmu_put_gpuaddr(entry->memdesc.pagetable, &entry->memdesc); rb_erase(&entry->node, &entry->priv->mem_rb); } } /** * kgsl_mem_entry_attach_process - Attach a mem_entry to its owner process * @entry: the memory entry * @process: the owner process * * Attach a newly created mem_entry to its owner process so that * it can be found later. The mem_entry will be added to mem_idr and have * its 'id' field assigned. If the GPU address has been set, the entry * will also be added to the mem_rb tree. * * @returns - 0 on success or error code on failure. */ static int kgsl_mem_entry_attach_process(struct kgsl_mem_entry *entry, struct kgsl_device_private *dev_priv) { int id; int ret; struct kgsl_process_private *process = dev_priv->process_priv; struct kgsl_pagetable *pagetable; ret = kgsl_process_private_get(process); if (!ret) return -EBADF; idr_preload(GFP_KERNEL); spin_lock(&process->mem_lock); id = idr_alloc(&process->mem_idr, entry, 1, 0, GFP_NOWAIT); spin_unlock(&process->mem_lock); idr_preload_end(); if (id < 0) { ret = id; goto err_put_proc_priv; } entry->id = id; entry->priv = process; spin_lock(&process->mem_lock); ret = kgsl_mem_entry_track_gpuaddr(process, entry); if (ret) idr_remove(&process->mem_idr, entry->id); spin_unlock(&process->mem_lock); if (ret) goto err_put_proc_priv; /* map the memory after unlocking if gpuaddr has been assigned */ if (entry->memdesc.gpuaddr) { /* if a secured buffer map it to secure global pagetable */ if (kgsl_memdesc_is_secured(&entry->memdesc)) pagetable = process->pagetable->mmu->securepagetable; else pagetable = process->pagetable; entry->memdesc.pagetable = pagetable; ret = kgsl_mmu_map(pagetable, &entry->memdesc); if (ret) kgsl_mem_entry_detach_process(entry); } return ret; err_put_proc_priv: kgsl_process_private_put(process); return ret; } /* Detach a memory entry from a process and unmap it from the MMU */ static void kgsl_mem_entry_detach_process(struct kgsl_mem_entry *entry) { unsigned int type; if (entry == NULL) return; /* Unmap here so that below we can call kgsl_mmu_put_gpuaddr */ kgsl_mmu_unmap(entry->memdesc.pagetable, &entry->memdesc); spin_lock(&entry->priv->mem_lock); kgsl_mem_entry_untrack_gpuaddr(entry->priv, entry); if (entry->id != 0) idr_remove(&entry->priv->mem_idr, entry->id); entry->id = 0; type = kgsl_memdesc_usermem_type(&entry->memdesc); entry->priv->stats[type].cur -= entry->memdesc.size; spin_unlock(&entry->priv->mem_lock); kgsl_process_private_put(entry->priv); entry->priv = NULL; } /** * kgsl_context_dump() - dump information about a draw context * @device: KGSL device that owns the context * @context: KGSL context to dump information about * * Dump specific information about the context to the kernel log. Used for * fence timeout callbacks */ void kgsl_context_dump(struct kgsl_context *context) { struct kgsl_device *device; if (_kgsl_context_get(context) == 0) return; device = context->device; if (kgsl_context_detached(context)) { dev_err(device->dev, " context[%d]: context detached\n", context->id); } else if (device->ftbl->drawctxt_dump != NULL) device->ftbl->drawctxt_dump(device, context); kgsl_context_put(context); } EXPORT_SYMBOL(kgsl_context_dump); /* Allocate a new context ID */ int _kgsl_get_context_id(struct kgsl_device *device, struct kgsl_context *context) { int id; idr_preload(GFP_KERNEL); write_lock(&device->context_lock); id = idr_alloc(&device->context_idr, context, 1, KGSL_MEMSTORE_MAX, GFP_NOWAIT); write_unlock(&device->context_lock); idr_preload_end(); if (id > 0) context->id = id; return id; } /** * kgsl_context_init() - helper to initialize kgsl_context members * @dev_priv: the owner of the context * @context: the newly created context struct, should be allocated by * the device specific drawctxt_create function. * * This is a helper function for the device specific drawctxt_create * function to initialize the common members of its context struct. * If this function succeeds, reference counting is active in the context * struct and the caller should kgsl_context_put() it on error. * If it fails, the caller should just free the context structure * it passed in. */ int kgsl_context_init(struct kgsl_device_private *dev_priv, struct kgsl_context *context) { struct kgsl_device *device = dev_priv->device; char name[64]; int ret = 0, id; id = _kgsl_get_context_id(device, context); if (id == -ENOSPC) { /* * Before declaring that there are no contexts left try * flushing the event workqueue just in case there are * detached contexts waiting to finish */ mutex_unlock(&device->mutex); flush_workqueue(device->events_wq); mutex_lock(&device->mutex); id = _kgsl_get_context_id(device, context); } if (id < 0) { if (id == -ENOSPC) KGSL_DRV_INFO(device, "cannot have more than %zu contexts due to memstore limitation\n", KGSL_MEMSTORE_MAX); return id; } kref_init(&context->refcount); /* * Get a refernce to the process private so its not destroyed, until * the context is destroyed. This will also prevent the pagetable * from being destroyed */ if (!kgsl_process_private_get(dev_priv->process_priv)) { ret = -EBADF; goto out; } context->device = dev_priv->device; context->dev_priv = dev_priv; context->proc_priv = dev_priv->process_priv; context->tid = task_pid_nr(current); ret = kgsl_sync_timeline_create(context); if (ret) goto out; snprintf(name, sizeof(name), "context-%d", id); kgsl_add_event_group(&context->events, context, name, kgsl_readtimestamp, context); out: if (ret) { write_lock(&device->context_lock); idr_remove(&dev_priv->device->context_idr, id); write_unlock(&device->context_lock); } return ret; } EXPORT_SYMBOL(kgsl_context_init); /** * kgsl_context_detach() - Release the "master" context reference * @context: The context that will be detached * * This is called when a context becomes unusable, because userspace * has requested for it to be destroyed. The context itself may * exist a bit longer until its reference count goes to zero. * Other code referencing the context can detect that it has been * detached by checking the KGSL_CONTEXT_PRIV_DETACHED bit in * context->priv. */ int kgsl_context_detach(struct kgsl_context *context) { int ret; struct kgsl_device *device; if (context == NULL) return -EINVAL; /* * Mark the context as detached to keep others from using * the context before it gets fully removed, and to make sure * we don't try to detach twice. */ if (test_and_set_bit(KGSL_CONTEXT_PRIV_DETACHED, &context->priv)) return -EINVAL; device = context->device; trace_kgsl_context_detach(device, context); /* we need to hold device mutex to detach */ mutex_lock(&device->mutex); ret = context->device->ftbl->drawctxt_detach(context); mutex_unlock(&device->mutex); /* * Cancel all pending events after the device-specific context is * detached, to avoid possibly freeing memory while it is still * in use by the GPU. */ kgsl_cancel_events(device, &context->events); /* Remove the event group from the list */ kgsl_del_event_group(&context->events); kgsl_context_put(context); return ret; } void kgsl_context_destroy(struct kref *kref) { struct kgsl_context *context = container_of(kref, struct kgsl_context, refcount); struct kgsl_device *device = context->device; trace_kgsl_context_destroy(device, context); BUG_ON(!kgsl_context_detached(context)); write_lock(&device->context_lock); if (context->id != KGSL_CONTEXT_INVALID) { /* Clear the timestamps in the memstore during destroy */ kgsl_sharedmem_writel(device, &device->memstore, KGSL_MEMSTORE_OFFSET(context->id, soptimestamp), 0); kgsl_sharedmem_writel(device, &device->memstore, KGSL_MEMSTORE_OFFSET(context->id, eoptimestamp), 0); /* clear device power constraint */ if (context->id == device->pwrctrl.constraint.owner_id) { trace_kgsl_constraint(device, device->pwrctrl.constraint.type, device->pwrctrl.active_pwrlevel, 0); device->pwrctrl.constraint.type = KGSL_CONSTRAINT_NONE; } idr_remove(&device->context_idr, context->id); context->id = KGSL_CONTEXT_INVALID; } write_unlock(&device->context_lock); kgsl_sync_timeline_destroy(context); kgsl_process_private_put(context->proc_priv); device->ftbl->drawctxt_destroy(context); } struct kgsl_device *kgsl_get_device(int dev_idx) { int i; struct kgsl_device *ret = NULL; mutex_lock(&kgsl_driver.devlock); for (i = 0; i < KGSL_DEVICE_MAX; i++) { if (kgsl_driver.devp[i] && kgsl_driver.devp[i]->id == dev_idx) { ret = kgsl_driver.devp[i]; break; } } mutex_unlock(&kgsl_driver.devlock); return ret; } EXPORT_SYMBOL(kgsl_get_device); static struct kgsl_device *kgsl_get_minor(int minor) { struct kgsl_device *ret = NULL; if (minor < 0 || minor >= KGSL_DEVICE_MAX) return NULL; mutex_lock(&kgsl_driver.devlock); ret = kgsl_driver.devp[minor]; mutex_unlock(&kgsl_driver.devlock); return ret; } /** * kgsl_check_timestamp() - return true if the specified timestamp is retired * @device: Pointer to the KGSL device to check * @context: Pointer to the context for the timestamp * @timestamp: The timestamp to compare */ int kgsl_check_timestamp(struct kgsl_device *device, struct kgsl_context *context, unsigned int timestamp) { unsigned int ts_processed; kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &ts_processed); return (timestamp_cmp(ts_processed, timestamp) >= 0); } EXPORT_SYMBOL(kgsl_check_timestamp); static int kgsl_suspend_device(struct kgsl_device *device, pm_message_t state) { int status = -EINVAL; if (!device) return -EINVAL; KGSL_PWR_WARN(device, "suspend start\n"); mutex_lock(&device->mutex); status = kgsl_pwrctrl_change_state(device, KGSL_STATE_SUSPEND); mutex_unlock(&device->mutex); KGSL_PWR_WARN(device, "suspend end\n"); return status; } static int kgsl_resume_device(struct kgsl_device *device) { if (!device) return -EINVAL; KGSL_PWR_WARN(device, "resume start\n"); mutex_lock(&device->mutex); if (device->state == KGSL_STATE_SUSPEND) { kgsl_pwrctrl_change_state(device, KGSL_STATE_SLUMBER); } else if (device->state != KGSL_STATE_INIT) { /* * This is an error situation,so wait for the device * to idle and then put the device to SLUMBER state. * This will put the device to the right state when * we resume. */ if (device->state == KGSL_STATE_ACTIVE) device->ftbl->idle(device); kgsl_pwrctrl_change_state(device, KGSL_STATE_SLUMBER); KGSL_PWR_ERR(device, "resume invoked without a suspend\n"); } mutex_unlock(&device->mutex); KGSL_PWR_WARN(device, "resume end\n"); return 0; } static int kgsl_suspend(struct device *dev) { pm_message_t arg = {0}; struct kgsl_device *device = dev_get_drvdata(dev); return kgsl_suspend_device(device, arg); } static int kgsl_resume(struct device *dev) { struct kgsl_device *device = dev_get_drvdata(dev); return kgsl_resume_device(device); } static int kgsl_runtime_suspend(struct device *dev) { return 0; } static int kgsl_runtime_resume(struct device *dev) { return 0; } const struct dev_pm_ops kgsl_pm_ops = { .suspend = kgsl_suspend, .resume = kgsl_resume, .runtime_suspend = kgsl_runtime_suspend, .runtime_resume = kgsl_runtime_resume, }; EXPORT_SYMBOL(kgsl_pm_ops); int kgsl_suspend_driver(struct platform_device *pdev, pm_message_t state) { struct kgsl_device *device = dev_get_drvdata(&pdev->dev); return kgsl_suspend_device(device, state); } EXPORT_SYMBOL(kgsl_suspend_driver); int kgsl_resume_driver(struct platform_device *pdev) { struct kgsl_device *device = dev_get_drvdata(&pdev->dev); return kgsl_resume_device(device); } EXPORT_SYMBOL(kgsl_resume_driver); /** * kgsl_destroy_process_private() - Cleanup function to free process private * @kref: - Pointer to object being destroyed's kref struct * Free struct object and all other resources attached to it. * Since the function can be used when not all resources inside process * private have been allocated, there is a check to (before each resource * cleanup) see if the struct member being cleaned is in fact allocated or not. * If the value is not NULL, resource is freed. */ static void kgsl_destroy_process_private(struct kref *kref) { struct kgsl_process_private *private = container_of(kref, struct kgsl_process_private, refcount); idr_destroy(&private->mem_idr); idr_destroy(&private->syncsource_idr); kgsl_mmu_putpagetable(private->pagetable); kfree(private); return; } void kgsl_process_private_put(struct kgsl_process_private *private) { if (private) kref_put(&private->refcount, kgsl_destroy_process_private); } /** * kgsl_process_private_find() - Find the process associated with the specified * name * @name: pid_t of the process to search for * Return the process struct for the given ID. */ struct kgsl_process_private *kgsl_process_private_find(pid_t pid) { struct kgsl_process_private *p, *private = NULL; mutex_lock(&kgsl_driver.process_mutex); list_for_each_entry(p, &kgsl_driver.process_list, list) { if (p->pid == pid) { if (kgsl_process_private_get(p)) private = p; break; } } mutex_unlock(&kgsl_driver.process_mutex); return private; } static struct kgsl_process_private *kgsl_process_private_new( struct kgsl_device *device) { struct kgsl_process_private *private; pid_t tgid = task_tgid_nr(current); /* Search in the process list */ list_for_each_entry(private, &kgsl_driver.process_list, list) { if (private->pid == tgid) { if (!kgsl_process_private_get(private)) private = ERR_PTR(-EINVAL); return private; } } /* Create a new object */ private = kzalloc(sizeof(struct kgsl_process_private), GFP_KERNEL); if (private == NULL) return ERR_PTR(-ENOMEM); kref_init(&private->refcount); private->pid = tgid; get_task_comm(private->comm, current->group_leader); private->mem_rb = RB_ROOT; spin_lock_init(&private->mem_lock); spin_lock_init(&private->syncsource_lock); idr_init(&private->mem_idr); idr_init(&private->syncsource_idr); /* Allocate a pagetable for the new process object */ if (kgsl_mmu_enabled()) { private->pagetable = kgsl_mmu_getpagetable(&device->mmu, tgid); if (private->pagetable == NULL) { idr_destroy(&private->mem_idr); idr_destroy(&private->syncsource_idr); kfree(private); private = ERR_PTR(-ENOMEM); } } return private; } static void process_release_memory(struct kgsl_process_private *private) { struct kgsl_mem_entry *entry; int next = 0; while (1) { spin_lock(&private->mem_lock); entry = idr_get_next(&private->mem_idr, &next); if (entry == NULL) { spin_unlock(&private->mem_lock); break; } /* * If the free pending flag is not set it means that user space * did not free it's reference to this entry, in that case * free a reference to this entry, other references are from * within kgsl so they will be freed eventually by kgsl */ if (!entry->pending_free) { entry->pending_free = 1; spin_unlock(&private->mem_lock); kgsl_mem_entry_put(entry); } else { spin_unlock(&private->mem_lock); } next = next + 1; } } static void process_release_sync_sources(struct kgsl_process_private *private) { struct kgsl_syncsource *syncsource; int next = 0; while (1) { spin_lock(&private->syncsource_lock); syncsource = idr_get_next(&private->syncsource_idr, &next); spin_unlock(&private->syncsource_lock); if (syncsource == NULL) break; kgsl_syncsource_put(syncsource); next = next + 1; } } static void kgsl_process_private_close(struct kgsl_device_private *dev_priv, struct kgsl_process_private *private) { mutex_lock(&kgsl_driver.process_mutex); if (--private->fd_count > 0) { mutex_unlock(&kgsl_driver.process_mutex); kgsl_process_private_put(private); return; } /* * If this is the last file on the process take down the debug * directories and garbage collect any outstanding resources */ kgsl_process_uninit_sysfs(private); debugfs_remove_recursive(private->debug_root); process_release_sync_sources(private); kgsl_mmu_detach_pagetable(private->pagetable); /* Remove the process struct from the master list */ list_del(&private->list); /* * Unlock the mutex before releasing the memory - this prevents a * deadlock with the IOMMU mutex if a page fault occurs */ mutex_unlock(&kgsl_driver.process_mutex); process_release_memory(private); kgsl_process_private_put(private); } static struct kgsl_process_private *kgsl_process_private_open( struct kgsl_device *device) { struct kgsl_process_private *private; mutex_lock(&kgsl_driver.process_mutex); private = kgsl_process_private_new(device); if (IS_ERR(private)) goto done; /* * If this is a new process create the debug directories and add it to * the process list */ if (private->fd_count++ == 0) { int ret = kgsl_process_init_sysfs(device, private); if (ret) { kgsl_process_private_put(private); private = ERR_PTR(ret); goto done; } ret = kgsl_process_init_debugfs(private); if (ret) { kgsl_process_uninit_sysfs(private); kgsl_process_private_put(private); private = ERR_PTR(ret); goto done; } list_add(&private->list, &kgsl_driver.process_list); } done: mutex_unlock(&kgsl_driver.process_mutex); return private; } static int kgsl_close_device(struct kgsl_device *device) { int result = 0; mutex_lock(&device->mutex); device->open_count--; if (device->open_count == 0) { /* Wait for the active count to go to 0 */ kgsl_active_count_wait(device, 0); /* Fail if the wait times out */ BUG_ON(atomic_read(&device->active_cnt) > 0); result = kgsl_pwrctrl_change_state(device, KGSL_STATE_INIT); } mutex_unlock(&device->mutex); return result; } static void device_release_contexts(struct kgsl_device_private *dev_priv) { struct kgsl_device *device = dev_priv->device; struct kgsl_context *context; int next = 0; while (1) { read_lock(&device->context_lock); context = idr_get_next(&device->context_idr, &next); read_unlock(&device->context_lock); if (context == NULL) break; if (context->dev_priv == dev_priv) { /* * Hold a reference to the context in case somebody * tries to put it while we are detaching */ if (_kgsl_context_get(context)) { kgsl_context_detach(context); kgsl_context_put(context); } } next = next + 1; } } static int kgsl_release(struct inode *inodep, struct file *filep) { struct kgsl_device_private *dev_priv = filep->private_data; struct kgsl_device *device = dev_priv->device; int result; filep->private_data = NULL; /* Release the contexts for the file */ device_release_contexts(dev_priv); /* Close down the process wide resources for the file */ kgsl_process_private_close(dev_priv, dev_priv->process_priv); kfree(dev_priv); result = kgsl_close_device(device); pm_runtime_put(&device->pdev->dev); return result; } static int kgsl_open_device(struct kgsl_device *device) { int result = 0; mutex_lock(&device->mutex); if (device->open_count == 0) { /* * active_cnt special case: we are starting up for the first * time, so use this sequence instead of the kgsl_pwrctrl_wake() * which will be called by kgsl_active_count_get(). */ atomic_inc(&device->active_cnt); kgsl_sharedmem_set(device, &device->memstore, 0, 0, device->memstore.size); result = device->ftbl->init(device); if (result) goto err; result = device->ftbl->start(device, 0); if (result) goto err; /* * Make sure the gates are open, so they don't block until * we start suspend or FT. */ complete_all(&device->hwaccess_gate); kgsl_pwrctrl_change_state(device, KGSL_STATE_ACTIVE); kgsl_active_count_put(device); } device->open_count++; err: if (result) { kgsl_pwrctrl_change_state(device, KGSL_STATE_INIT); atomic_dec(&device->active_cnt); } mutex_unlock(&device->mutex); return result; } static int kgsl_open(struct inode *inodep, struct file *filep) { int result; struct kgsl_device_private *dev_priv; struct kgsl_device *device; unsigned int minor = iminor(inodep); device = kgsl_get_minor(minor); BUG_ON(device == NULL); result = pm_runtime_get_sync(&device->pdev->dev); if (result < 0) { KGSL_DRV_ERR(device, "Runtime PM: Unable to wake up the device, rc = %d\n", result); return result; } result = 0; dev_priv = kzalloc(sizeof(struct kgsl_device_private), GFP_KERNEL); if (dev_priv == NULL) { result = -ENOMEM; goto err; } dev_priv->device = device; filep->private_data = dev_priv; result = kgsl_open_device(device); if (result) goto err; /* * Get file (per process) private struct. This must be done * after the first start so that the global pagetable mappings * are set up before we create the per-process pagetable. */ dev_priv->process_priv = kgsl_process_private_open(device); if (IS_ERR(dev_priv->process_priv)) { result = PTR_ERR(dev_priv->process_priv); kgsl_close_device(device); goto err; } err: if (result) { filep->private_data = NULL; kfree(dev_priv); pm_runtime_put(&device->pdev->dev); } return result; } /** * kgsl_sharedmem_find_region() - Find a gpu memory allocation * * @private: private data for the process to check. * @gpuaddr: start address of the region * @size: size of the region * * Find a gpu allocation. Caller must kgsl_mem_entry_put() * the returned entry when finished using it. */ struct kgsl_mem_entry * __must_check kgsl_sharedmem_find_region(struct kgsl_process_private *private, unsigned int gpuaddr, size_t size) { struct rb_node *node; if (!private) return NULL; if (!kgsl_mmu_gpuaddr_in_range(private->pagetable, gpuaddr)) return NULL; spin_lock(&private->mem_lock); node = private->mem_rb.rb_node; while (node != NULL) { struct kgsl_mem_entry *entry; entry = rb_entry(node, struct kgsl_mem_entry, node); if (kgsl_gpuaddr_in_memdesc(&entry->memdesc, gpuaddr, size)) { if (!kgsl_mem_entry_get(entry)) break; spin_unlock(&private->mem_lock); return entry; } if (gpuaddr < entry->memdesc.gpuaddr) node = node->rb_left; else if (gpuaddr >= (entry->memdesc.gpuaddr + entry->memdesc.size)) node = node->rb_right; else { spin_unlock(&private->mem_lock); return NULL; } } spin_unlock(&private->mem_lock); return NULL; } EXPORT_SYMBOL(kgsl_sharedmem_find_region); /** * kgsl_sharedmem_find() - Find a gpu memory allocation * * @private: private data for the process to check. * @gpuaddr: start address of the region * * Find a gpu allocation. Caller must kgsl_mem_entry_put() * the returned entry when finished using it. */ static inline struct kgsl_mem_entry * __must_check kgsl_sharedmem_find(struct kgsl_process_private *private, unsigned int gpuaddr) { return kgsl_sharedmem_find_region(private, gpuaddr, 1); } /** * kgsl_sharedmem_region_empty() - Check if an addression region is empty * * @private: private data for the process to check. * @gpuaddr: start address of the region * @size: length of the region. * @collision_entry: Returns pointer to the colliding memory entry, * caller's responsibility to take a refcount on this entry * * Checks that there are no existing allocations within an address * region. This function should be called with processes spin lock * held. */ static int kgsl_sharedmem_region_empty(struct kgsl_process_private *private, unsigned int gpuaddr, size_t size, struct kgsl_mem_entry **collision_entry) { int result = 1; unsigned int gpuaddr_end = gpuaddr + size; struct rb_node *node; assert_spin_locked(&private->mem_lock); if (!kgsl_mmu_gpuaddr_in_range(private->pagetable, gpuaddr)) return 0; /* don't overflow */ if (gpuaddr_end < gpuaddr) return 0; node = private->mem_rb.rb_node; while (node != NULL) { struct kgsl_mem_entry *entry; unsigned int memdesc_start, memdesc_end; entry = rb_entry(node, struct kgsl_mem_entry, node); memdesc_start = entry->memdesc.gpuaddr; memdesc_end = memdesc_start + kgsl_memdesc_mmapsize(&entry->memdesc); if (gpuaddr_end <= memdesc_start) node = node->rb_left; else if (memdesc_end <= gpuaddr) node = node->rb_right; else { if (collision_entry) *collision_entry = entry; result = 0; break; } } return result; } /** * kgsl_sharedmem_find_id() - find a memory entry by id * @process: the owning process * @id: id to find * * @returns - the mem_entry or NULL * * Caller must kgsl_mem_entry_put() the returned entry, when finished using * it. */ static inline struct kgsl_mem_entry * __must_check kgsl_sharedmem_find_id(struct kgsl_process_private *process, unsigned int id) { int result = 0; struct kgsl_mem_entry *entry; spin_lock(&process->mem_lock); entry = idr_find(&process->mem_idr, id); if (entry) result = kgsl_mem_entry_get(entry); spin_unlock(&process->mem_lock); if (!result) return NULL; return entry; } /** * kgsl_mem_entry_unset_pend() - Unset the pending free flag of an entry * @entry - The memory entry */ static inline void kgsl_mem_entry_unset_pend(struct kgsl_mem_entry *entry) { if (entry == NULL) return; spin_lock(&entry->priv->mem_lock); entry->pending_free = 0; spin_unlock(&entry->priv->mem_lock); } /** * kgsl_mem_entry_set_pend() - Set the pending free flag of a memory entry * @entry - The memory entry * * @returns - true if pending flag was 0 else false * * This function will set the pending free flag if it is previously unset. Used * to prevent race condition between ioctls calling free/freememontimestamp * on the same entry. Whichever thread set's the flag first will do the free. */ static inline bool kgsl_mem_entry_set_pend(struct kgsl_mem_entry *entry) { bool ret = false; if (entry == NULL) return false; spin_lock(&entry->priv->mem_lock); if (!entry->pending_free) { entry->pending_free = 1; ret = true; } spin_unlock(&entry->priv->mem_lock); return ret; } /*call all ioctl sub functions with driver locked*/ long kgsl_ioctl_device_getproperty(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_device_getproperty *param = data; switch (param->type) { case KGSL_PROP_VERSION: { struct kgsl_version version; if (param->sizebytes != sizeof(version)) { result = -EINVAL; break; } version.drv_major = KGSL_VERSION_MAJOR; version.drv_minor = KGSL_VERSION_MINOR; version.dev_major = dev_priv->device->ver_major; version.dev_minor = dev_priv->device->ver_minor; if (copy_to_user(param->value, &version, sizeof(version))) result = -EFAULT; break; } case KGSL_PROP_GPU_RESET_STAT: { /* Return reset status of given context and clear it */ uint32_t id; struct kgsl_context *context; if (param->sizebytes != sizeof(unsigned int)) { result = -EINVAL; break; } /* We expect the value passed in to contain the context id */ if (copy_from_user(&id, param->value, sizeof(unsigned int))) { result = -EFAULT; break; } context = kgsl_context_get_owner(dev_priv, id); if (!context) { result = -EINVAL; break; } /* * Copy the reset status to value which also serves as * the out parameter */ if (copy_to_user(param->value, &(context->reset_status), sizeof(unsigned int))) result = -EFAULT; else { /* Clear reset status once its been queried */ context->reset_status = KGSL_CTX_STAT_NO_ERROR; } kgsl_context_put(context); break; } default: if (is_compat_task()) result = dev_priv->device->ftbl->getproperty_compat( dev_priv->device, param->type, param->value, param->sizebytes); else result = dev_priv->device->ftbl->getproperty( dev_priv->device, param->type, param->value, param->sizebytes); } return result; } long kgsl_ioctl_device_setproperty(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; /* The getproperty struct is reused for setproperty too */ struct kgsl_device_getproperty *param = data; /* Reroute to compat version if coming from compat_ioctl */ if (is_compat_task()) result = dev_priv->device->ftbl->setproperty_compat( dev_priv, param->type, param->value, param->sizebytes); else if (dev_priv->device->ftbl->setproperty) result = dev_priv->device->ftbl->setproperty( dev_priv, param->type, param->value, param->sizebytes); return result; } long kgsl_ioctl_device_waittimestamp_ctxtid( struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_device_waittimestamp_ctxtid *param = data; struct kgsl_device *device = dev_priv->device; long result = -EINVAL; unsigned int temp_cur_ts = 0; struct kgsl_context *context; mutex_lock(&device->mutex); context = kgsl_context_get_owner(dev_priv, param->context_id); if (context == NULL) goto out; kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &temp_cur_ts); trace_kgsl_waittimestamp_entry(device, context->id, temp_cur_ts, param->timestamp, param->timeout); result = device->ftbl->waittimestamp(device, context, param->timestamp, param->timeout); kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &temp_cur_ts); trace_kgsl_waittimestamp_exit(device, temp_cur_ts, result); out: kgsl_context_put(context); mutex_unlock(&device->mutex); return result; } /* * KGSL command batch management * A command batch is a single submission from userland. The cmdbatch * encapsulates everything about the submission : command buffers, flags and * sync points. * * Sync points are events that need to expire before the * cmdbatch can be queued to the hardware. For each sync point a * kgsl_cmdbatch_sync_event struct is created and added to a list in the * cmdbatch. There can be multiple types of events both internal ones (GPU * events) and external triggers. As the events expire the struct is deleted * from the list. The GPU will submit the command batch as soon as the list * goes empty indicating that all the sync points have been met. */ void kgsl_dump_syncpoints(struct kgsl_device *device, struct kgsl_cmdbatch *cmdbatch) { struct kgsl_cmdbatch_sync_event *event; /* Print all the pending sync objects */ list_for_each_entry(event, &cmdbatch->synclist, node) { switch (event->type) { case KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP: { unsigned int retired; kgsl_readtimestamp(event->device, event->context, KGSL_TIMESTAMP_RETIRED, &retired); dev_err(device->dev, " [timestamp] context %d timestamp %d (retired %d)\n", event->context->id, event->timestamp, retired); break; } case KGSL_CMD_SYNCPOINT_TYPE_FENCE: if (event->handle) dev_err(device->dev, " fence: [%p] %s\n", event->handle->fence, event->handle->name); else dev_err(device->dev, " fence: invalid\n"); break; } } } static void _kgsl_cmdbatch_timer(unsigned long data) { struct kgsl_device *device; struct kgsl_cmdbatch *cmdbatch = (struct kgsl_cmdbatch *) data; struct kgsl_cmdbatch_sync_event *event; struct adreno_context *drawctxt; if (cmdbatch == NULL || cmdbatch->context == NULL) return; drawctxt = ADRENO_CONTEXT(cmdbatch->context); /* We are in timer context, this can be non-bh */ spin_lock(&drawctxt->lock); set_bit(ADRENO_CONTEXT_CMDBATCH_FLAG_FENCE_LOG, &drawctxt->flags); spin_lock(&cmdbatch->lock); if (list_empty(&cmdbatch->synclist)) goto done; device = cmdbatch->context->device; dev_err(device->dev, "kgsl: possible gpu syncpoint deadlock for context %d timestamp %d\n", cmdbatch->context->id, cmdbatch->timestamp); dev_err(device->dev, " Active sync points:\n"); /* Print all the pending sync objects */ list_for_each_entry(event, &cmdbatch->synclist, node) { switch (event->type) { case KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP: { unsigned int retired; kgsl_readtimestamp(event->device, event->context, KGSL_TIMESTAMP_RETIRED, &retired); dev_err(device->dev, " [timestamp] context %d timestamp %d (retired %d)\n", event->context->id, event->timestamp, retired); break; } case KGSL_CMD_SYNCPOINT_TYPE_FENCE: if (event->handle && event->handle->fence) { set_bit(CMDBATCH_FLAG_FENCE_LOG, &cmdbatch->priv); kgsl_sync_fence_log(event->handle->fence); clear_bit(CMDBATCH_FLAG_FENCE_LOG, &cmdbatch->priv); } else dev_err(device->dev, " fence: invalid\n"); break; } } done: spin_unlock(&cmdbatch->lock); clear_bit(ADRENO_CONTEXT_CMDBATCH_FLAG_FENCE_LOG, &drawctxt->flags); spin_unlock(&drawctxt->lock); } /** * kgsl_cmdbatch_sync_event_destroy() - Destroy a sync event object * @kref: Pointer to the kref structure for this object * * Actually destroy a sync event object. Called from * kgsl_cmdbatch_sync_event_put. */ static void kgsl_cmdbatch_sync_event_destroy(struct kref *kref) { struct kgsl_cmdbatch_sync_event *event = container_of(kref, struct kgsl_cmdbatch_sync_event, refcount); kgsl_cmdbatch_put(event->cmdbatch); kfree(event); } /** * kgsl_cmdbatch_sync_event_put() - Decrement the refcount for a * sync event object * @event: Pointer to the sync event object */ static inline void kgsl_cmdbatch_sync_event_put( struct kgsl_cmdbatch_sync_event *event) { kref_put(&event->refcount, kgsl_cmdbatch_sync_event_destroy); } /** * kgsl_cmdbatch_destroy_object() - Destroy a cmdbatch object * @kref: Pointer to the kref structure for this object * * Actually destroy a command batch object. Called from kgsl_cmdbatch_put */ void kgsl_cmdbatch_destroy_object(struct kref *kref) { struct kgsl_cmdbatch *cmdbatch = container_of(kref, struct kgsl_cmdbatch, refcount); kgsl_context_put(cmdbatch->context); kfree(cmdbatch); } EXPORT_SYMBOL(kgsl_cmdbatch_destroy_object); /* * a generic function to retire a pending sync event and (possibly) * kick the dispatcher */ static void kgsl_cmdbatch_sync_expire(struct kgsl_device *device, struct kgsl_cmdbatch_sync_event *event) { struct kgsl_cmdbatch_sync_event *e, *tmp; int sched = 0; int removed = 0; /* * We may have cmdbatch timer running, which also uses same lock, * take a lock with software interrupt disabled (bh) to avoid * spin lock recursion. */ spin_lock_bh(&event->cmdbatch->lock); /* * sync events that are contained by a cmdbatch which has been * destroyed may have already been removed from the synclist */ list_for_each_entry_safe(e, tmp, &event->cmdbatch->synclist, node) { if (e == event) { list_del_init(&event->node); removed = 1; break; } } sched = list_empty(&event->cmdbatch->synclist) ? 1 : 0; spin_unlock_bh(&event->cmdbatch->lock); /* If the list is empty delete the canary timer */ if (sched) del_timer_sync(&event->cmdbatch->timer); /* * if this is the last event in the list then tell * the GPU device that the cmdbatch can be submitted */ if (sched && device->ftbl->drawctxt_sched) device->ftbl->drawctxt_sched(device, event->cmdbatch->context); /* Put events that have been removed from the synclist */ if (removed) kgsl_cmdbatch_sync_event_put(event); } /* * This function is called by the GPU event when the sync event timestamp * expires */ static void kgsl_cmdbatch_sync_func(struct kgsl_device *device, struct kgsl_event_group *group, void *priv, int result) { struct kgsl_cmdbatch_sync_event *event = priv; trace_syncpoint_timestamp_expire(event->cmdbatch, event->context, event->timestamp); kgsl_cmdbatch_sync_expire(device, event); kgsl_context_put(event->context); /* Put events that have signaled */ kgsl_cmdbatch_sync_event_put(event); } static inline void _free_memobj_list(struct list_head *list) { struct kgsl_memobj_node *mem, *tmpmem; /* Free the cmd mem here */ list_for_each_entry_safe(mem, tmpmem, list, node) { list_del_init(&mem->node); kmem_cache_free(memobjs_cache, mem); } } /** * kgsl_cmdbatch_destroy() - Destroy a cmdbatch structure * @cmdbatch: Pointer to the command batch object to destroy * * Start the process of destroying a command batch. Cancel any pending events * and decrement the refcount. Asynchronous events can still signal after * kgsl_cmdbatch_destroy has returned. */ void kgsl_cmdbatch_destroy(struct kgsl_cmdbatch *cmdbatch) { struct kgsl_cmdbatch_sync_event *event, *tmpsync; LIST_HEAD(cancel_synclist); int sched = 0; /* Zap the canary timer */ del_timer_sync(&cmdbatch->timer); /* non-bh because we just destroyed timer */ spin_lock(&cmdbatch->lock); /* Empty the synclist before canceling events */ list_splice_init(&cmdbatch->synclist, &cancel_synclist); spin_unlock(&cmdbatch->lock); /* * Finish canceling events outside the cmdbatch spinlock and * require the cancel function to return if the event was * successfully canceled meaning that the event is guaranteed * not to signal the callback. This guarantee ensures that * the reference count for the event and cmdbatch is correct. */ list_for_each_entry_safe(event, tmpsync, &cancel_synclist, node) { sched = 1; if (event->type == KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP) { /* * Timestamp events are guaranteed to signal * when canceled */ kgsl_cancel_event(cmdbatch->device, &event->context->events, event->timestamp, kgsl_cmdbatch_sync_func, event); } else if (event->type == KGSL_CMD_SYNCPOINT_TYPE_FENCE) { /* Put events that are successfully canceled */ if (kgsl_sync_fence_async_cancel(event->handle)) kgsl_cmdbatch_sync_event_put(event); } /* Put events that have been removed from the synclist */ list_del_init(&event->node); kgsl_cmdbatch_sync_event_put(event); } /* * Release the the refcount on the mem entry associated with the * cmdbatch profiling buffer */ if (cmdbatch->flags & KGSL_CMDBATCH_PROFILING) kgsl_mem_entry_put(cmdbatch->profiling_buf_entry); /* Destroy the cmdlist we created */ _free_memobj_list(&cmdbatch->cmdlist); /* Destroy the memlist we created */ _free_memobj_list(&cmdbatch->memlist); /* * If we cancelled an event, there's a good chance that the context is * on a dispatcher queue, so schedule to get it removed. */ if (sched && cmdbatch->device->ftbl->drawctxt_sched) cmdbatch->device->ftbl->drawctxt_sched(cmdbatch->device, cmdbatch->context); kgsl_cmdbatch_put(cmdbatch); } EXPORT_SYMBOL(kgsl_cmdbatch_destroy); /* * A callback that gets registered with kgsl_sync_fence_async_wait and is fired * when a fence is expired */ static void kgsl_cmdbatch_sync_fence_func(void *priv) { struct kgsl_cmdbatch_sync_event *event = priv; trace_syncpoint_fence_expire(event->cmdbatch, event->handle ? event->handle->name : "unknown"); kgsl_cmdbatch_sync_expire(event->device, event); /* Put events that have signaled */ kgsl_cmdbatch_sync_event_put(event); } /* kgsl_cmdbatch_add_sync_fence() - Add a new sync fence syncpoint * @device: KGSL device * @cmdbatch: KGSL cmdbatch to add the sync point to * @priv: Private sructure passed by the user * * Add a new fence sync syncpoint to the cmdbatch. */ static int kgsl_cmdbatch_add_sync_fence(struct kgsl_device *device, struct kgsl_cmdbatch *cmdbatch, void *priv) { struct kgsl_cmd_syncpoint_fence *sync = priv; struct kgsl_cmdbatch_sync_event *event; event = kzalloc(sizeof(*event), GFP_KERNEL); if (event == NULL) return -ENOMEM; kref_get(&cmdbatch->refcount); event->type = KGSL_CMD_SYNCPOINT_TYPE_FENCE; event->cmdbatch = cmdbatch; event->device = device; event->context = NULL; /* * Initial kref is to ensure async callback does not free the * event before this function sets the event handle */ kref_init(&event->refcount); /* * Add it to the list first to account for the possiblity that the * callback will happen immediately after the call to * kgsl_sync_fence_async_wait. Decrement the event refcount when * removing from the synclist. */ kref_get(&event->refcount); /* non-bh because, we haven't started cmdbatch timer yet */ spin_lock(&cmdbatch->lock); list_add(&event->node, &cmdbatch->synclist); spin_unlock(&cmdbatch->lock); /* * Increment the reference count for the async callback. * Decrement when the callback is successfully canceled, when * the callback is signaled or if the async wait fails. */ kref_get(&event->refcount); event->handle = kgsl_sync_fence_async_wait(sync->fd, kgsl_cmdbatch_sync_fence_func, event); if (IS_ERR_OR_NULL(event->handle)) { int ret = PTR_ERR(event->handle); event->handle = NULL; /* Failed to add the event to the async callback */ kgsl_cmdbatch_sync_event_put(event); /* Remove event from the synclist */ spin_lock(&cmdbatch->lock); list_del(&event->node); spin_unlock(&cmdbatch->lock); kgsl_cmdbatch_sync_event_put(event); /* Event no longer needed by this function */ kgsl_cmdbatch_sync_event_put(event); /* * If ret == 0 the fence was already signaled - print a trace * message so we can track that */ if (ret == 0) trace_syncpoint_fence_expire(cmdbatch, "signaled"); return ret; } trace_syncpoint_fence(cmdbatch, event->handle->name); /* * Event was successfully added to the synclist, the async * callback and handle to cancel event has been set. */ kgsl_cmdbatch_sync_event_put(event); return 0; } /* kgsl_cmdbatch_add_sync_timestamp() - Add a new sync point for a cmdbatch * @device: KGSL device * @cmdbatch: KGSL cmdbatch to add the sync point to * @priv: Private sructure passed by the user * * Add a new sync point timestamp event to the cmdbatch. */ static int kgsl_cmdbatch_add_sync_timestamp(struct kgsl_device *device, struct kgsl_cmdbatch *cmdbatch, void *priv) { struct kgsl_cmd_syncpoint_timestamp *sync = priv; struct kgsl_context *context = kgsl_context_get(cmdbatch->device, sync->context_id); struct kgsl_cmdbatch_sync_event *event; int ret = -EINVAL; if (context == NULL) return -EINVAL; /* * We allow somebody to create a sync point on their own context. * This has the effect of delaying a command from submitting until the * dependent command has cleared. That said we obviously can't let them * create a sync point on a future timestamp. */ if (context == cmdbatch->context) { unsigned int queued; kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_QUEUED, &queued); if (timestamp_cmp(sync->timestamp, queued) > 0) { KGSL_DRV_ERR(device, "Cannot create syncpoint for future timestamp %d (current %d)\n", sync->timestamp, queued); goto done; } } event = kzalloc(sizeof(*event), GFP_KERNEL); if (event == NULL) { ret = -ENOMEM; goto done; } kref_get(&cmdbatch->refcount); event->type = KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP; event->cmdbatch = cmdbatch; event->context = context; event->timestamp = sync->timestamp; event->device = device; /* * Two krefs are required to support events. The first kref is for * the synclist which holds the event in the cmdbatch. The second * kref is for the callback which can be asynchronous and be called * after kgsl_cmdbatch_destroy. The kref should be put when the event * is removed from the synclist, if the callback is successfully * canceled or when the callback is signaled. */ kref_init(&event->refcount); kref_get(&event->refcount); /* non-bh because, we haven't started cmdbatch timer yet */ spin_lock(&cmdbatch->lock); list_add(&event->node, &cmdbatch->synclist); spin_unlock(&cmdbatch->lock); ret = kgsl_add_event(device, &context->events, sync->timestamp, kgsl_cmdbatch_sync_func, event); if (ret) { spin_lock(&cmdbatch->lock); list_del(&event->node); spin_unlock(&cmdbatch->lock); kgsl_cmdbatch_put(cmdbatch); kfree(event); } else { trace_syncpoint_timestamp(cmdbatch, context, sync->timestamp); } done: if (ret) kgsl_context_put(context); return ret; } /** * kgsl_cmdbatch_add_sync() - Add a sync point to a command batch * @device: Pointer to the KGSL device struct for the GPU * @cmdbatch: Pointer to the cmdbatch * @sync: Pointer to the user-specified struct defining the syncpoint * * Create a new sync point in the cmdbatch based on the user specified * parameters */ int kgsl_cmdbatch_add_sync(struct kgsl_device *device, struct kgsl_cmdbatch *cmdbatch, struct kgsl_cmd_syncpoint *sync) { void *priv; int ret, psize; int (*func)(struct kgsl_device *device, struct kgsl_cmdbatch *cmdbatch, void *priv); switch (sync->type) { case KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP: psize = sizeof(struct kgsl_cmd_syncpoint_timestamp); func = kgsl_cmdbatch_add_sync_timestamp; break; case KGSL_CMD_SYNCPOINT_TYPE_FENCE: psize = sizeof(struct kgsl_cmd_syncpoint_fence); func = kgsl_cmdbatch_add_sync_fence; break; default: KGSL_DRV_ERR(device, "Invalid sync type 0x%x\n", sync->type); return -EINVAL; } if (sync->size != psize) { KGSL_DRV_ERR(device, "Invalid sync size %zd\n", sync->size); return -EINVAL; } priv = kzalloc(sync->size, GFP_KERNEL); if (priv == NULL) return -ENOMEM; if (copy_from_user(priv, sync->priv, sync->size)) { kfree(priv); return -EFAULT; } ret = func(device, cmdbatch, priv); kfree(priv); return ret; } /** * kgsl_cmdbatch_add_memobj() - Add an entry to a command batch * @cmdbatch: Pointer to the cmdbatch * @ibdesc: Pointer to the user-specified struct defining the memory or IB * @preamble: Flag to mark this ibdesc as a preamble (if known) * * Create a new memory entry in the cmdbatch based on the user specified * parameters */ int kgsl_cmdbatch_add_memobj(struct kgsl_cmdbatch *cmdbatch, struct kgsl_ibdesc *ibdesc) { struct kgsl_memobj_node *mem; mem = kmem_cache_alloc(memobjs_cache, GFP_KERNEL); if (mem == NULL) return -ENOMEM; mem->gpuaddr = ibdesc->gpuaddr; mem->sizedwords = ibdesc->sizedwords; mem->priv = 0; /* sanitize the ibdesc ctrl flags */ ibdesc->ctrl &= KGSL_IBDESC_MEMLIST | KGSL_IBDESC_PROFILING_BUFFER; if (cmdbatch->flags & KGSL_CMDBATCH_MEMLIST && ibdesc->ctrl & KGSL_IBDESC_MEMLIST) { /* add to the memlist */ list_add_tail(&mem->node, &cmdbatch->memlist); /* * If the memlist contains a cmdbatch profiling buffer, store * the mem_entry containing the buffer and the gpuaddr at * which the buffer can be found */ if (cmdbatch->flags & KGSL_CMDBATCH_PROFILING && ibdesc->ctrl & KGSL_IBDESC_PROFILING_BUFFER && !cmdbatch->profiling_buf_entry) { cmdbatch->profiling_buf_entry = kgsl_sharedmem_find_region( cmdbatch->context->proc_priv, mem->gpuaddr, mem->sizedwords << 2); if (!cmdbatch->profiling_buf_entry) { WARN_ONCE(1, "No mem entry for profiling buf, gpuaddr=%lx\n", mem->gpuaddr); return 0; } cmdbatch->profiling_buffer_gpuaddr = mem->gpuaddr; } } else { /* set the preamble flag if directed to */ if (cmdbatch->context->flags & KGSL_CONTEXT_PREAMBLE && list_empty(&cmdbatch->cmdlist)) mem->priv = MEMOBJ_PREAMBLE; /* add to the cmd list */ list_add_tail(&mem->node, &cmdbatch->cmdlist); } return 0; } /** * kgsl_cmdbatch_create() - Create a new cmdbatch structure * @device: Pointer to a KGSL device struct * @context: Pointer to a KGSL context struct * @flags: Flags for the cmdbatch * * Allocate an new cmdbatch structure */ static struct kgsl_cmdbatch *kgsl_cmdbatch_create(struct kgsl_device *device, struct kgsl_context *context, unsigned int flags) { struct kgsl_cmdbatch *cmdbatch = kzalloc(sizeof(*cmdbatch), GFP_KERNEL); if (cmdbatch == NULL) return ERR_PTR(-ENOMEM); /* * Increase the reference count on the context so it doesn't disappear * during the lifetime of this command batch */ if (!_kgsl_context_get(context)) { kfree(cmdbatch); return ERR_PTR(-EINVAL); } kref_init(&cmdbatch->refcount); INIT_LIST_HEAD(&cmdbatch->cmdlist); INIT_LIST_HEAD(&cmdbatch->synclist); INIT_LIST_HEAD(&cmdbatch->memlist); spin_lock_init(&cmdbatch->lock); cmdbatch->device = device; cmdbatch->context = context; /* sanitize our flags for cmdbatches */ cmdbatch->flags = flags & (KGSL_CMDBATCH_CTX_SWITCH | KGSL_CMDBATCH_MARKER | KGSL_CMDBATCH_END_OF_FRAME | KGSL_CMDBATCH_SYNC | KGSL_CMDBATCH_PWR_CONSTRAINT | KGSL_CMDBATCH_MEMLIST | KGSL_CMDBATCH_PROFILING); /* Add a timer to help debug sync deadlocks */ setup_timer(&cmdbatch->timer, _kgsl_cmdbatch_timer, (unsigned long) cmdbatch); return cmdbatch; } /** * _kgsl_cmdbatch_verify() - Perform a quick sanity check on a command batch * @device: Pointer to a KGSL instance that owns the command batch * @pagetable: Pointer to the pagetable for the current process * @cmdbatch: Number of indirect buffers to make room for in the cmdbatch * * Do a quick sanity test on the list of indirect buffers in a command batch * verifying that the size and GPU address */ static bool _kgsl_cmdbatch_verify(struct kgsl_device_private *dev_priv, struct kgsl_cmdbatch *cmdbatch) { struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_memobj_node *ib; list_for_each_entry(ib, &cmdbatch->cmdlist, node) { if (ib->sizedwords == 0) { KGSL_DRV_ERR(dev_priv->device, "invalid size ctx %d %lX/%zX\n", cmdbatch->context->id, ib->gpuaddr, ib->sizedwords); return false; } if (!kgsl_mmu_gpuaddr_in_range(private->pagetable, ib->gpuaddr)) { KGSL_DRV_ERR(dev_priv->device, "Invalid address ctx %d %lX/%zX\n", cmdbatch->context->id, ib->gpuaddr, ib->sizedwords); return false; } } return true; } /** * _kgsl_cmdbatch_create_legacy() - Create a cmdbatch from a legacy ioctl struct * @device: Pointer to the KGSL device struct for the GPU * @context: Pointer to the KGSL context that issued the command batch * @param: Pointer to the kgsl_ringbuffer_issueibcmds struct that the user sent * * Create a command batch from the legacy issueibcmds format. */ static struct kgsl_cmdbatch *_kgsl_cmdbatch_create_legacy( struct kgsl_device *device, struct kgsl_context *context, struct kgsl_ringbuffer_issueibcmds *param) { struct kgsl_memobj_node *mem; struct kgsl_cmdbatch *cmdbatch = kgsl_cmdbatch_create(device, context, param->flags); if (IS_ERR(cmdbatch)) return cmdbatch; mem = kmem_cache_alloc(memobjs_cache, GFP_KERNEL); if (mem == NULL) { kgsl_cmdbatch_destroy(cmdbatch); return ERR_PTR(-ENOMEM); } mem->gpuaddr = param->ibdesc_addr; mem->sizedwords = param->numibs; mem->priv = 0; list_add_tail(&mem->node, &cmdbatch->cmdlist); return cmdbatch; } /** * _kgsl_cmdbatch_create() - Create a cmdbatch from a ioctl struct * @device: Pointer to the KGSL device struct for the GPU * @context: Pointer to the KGSL context that issued the command batch * @flags: Flags passed in from the user command * @cmdlist: Pointer to the list of commands from the user * @numcmds: Number of commands in the list * @synclist: Pointer to the list of syncpoints from the user * @numsyncs: Number of syncpoints in the list * * Create a command batch from the standard issueibcmds format sent by the user. */ static struct kgsl_cmdbatch *_kgsl_cmdbatch_create(struct kgsl_device *device, struct kgsl_context *context, unsigned int flags, void __user *cmdlist, unsigned int numcmds, void __user *synclist, unsigned int numsyncs) { struct kgsl_cmdbatch *cmdbatch = kgsl_cmdbatch_create(device, context, flags); int ret = 0, i; if (IS_ERR(cmdbatch)) return cmdbatch; if (is_compat_task()) { ret = kgsl_cmdbatch_create_compat(device, flags, cmdbatch, cmdlist, numcmds, synclist, numsyncs); goto done; } if (!(flags & (KGSL_CMDBATCH_SYNC | KGSL_CMDBATCH_MARKER))) { struct kgsl_ibdesc ibdesc; void __user *uptr = cmdlist; for (i = 0; i < numcmds; i++) { memset(&ibdesc, 0, sizeof(ibdesc)); if (copy_from_user(&ibdesc, uptr, sizeof(ibdesc))) { ret = -EFAULT; goto done; } ret = kgsl_cmdbatch_add_memobj(cmdbatch, &ibdesc); if (ret) goto done; uptr += sizeof(ibdesc); } if (cmdbatch->profiling_buf_entry == NULL) cmdbatch->flags &= ~KGSL_CMDBATCH_PROFILING; } if (synclist && numsyncs) { struct kgsl_cmd_syncpoint sync; void __user *uptr = synclist; for (i = 0; i < numsyncs; i++) { memset(&sync, 0, sizeof(sync)); if (copy_from_user(&sync, uptr, sizeof(sync))) { ret = -EFAULT; goto done; } ret = kgsl_cmdbatch_add_sync(device, cmdbatch, &sync); if (ret) goto done; uptr += sizeof(sync); } } done: if (ret) { kgsl_cmdbatch_destroy(cmdbatch); return ERR_PTR(ret); } return cmdbatch; } long kgsl_ioctl_rb_issueibcmds(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_ringbuffer_issueibcmds *param = data; struct kgsl_device *device = dev_priv->device; struct kgsl_context *context; struct kgsl_cmdbatch *cmdbatch; long result = -EINVAL; /* The legacy functions don't support synchronization commands */ if ((param->flags & (KGSL_CMDBATCH_SYNC | KGSL_CMDBATCH_MARKER))) return -EINVAL; /* Get the context */ context = kgsl_context_get_owner(dev_priv, param->drawctxt_id); if (context == NULL) goto done; if (param->flags & KGSL_CMDBATCH_SUBMIT_IB_LIST) { /* * Do a quick sanity check on the number of IBs in the * submission */ if (param->numibs == 0 || param->numibs > KGSL_MAX_NUMIBS) goto done; cmdbatch = _kgsl_cmdbatch_create(device, context, param->flags, (void __user *)param->ibdesc_addr, param->numibs, 0, 0); } else cmdbatch = _kgsl_cmdbatch_create_legacy(device, context, param); if (IS_ERR(cmdbatch)) { result = PTR_ERR(cmdbatch); goto done; } /* Run basic sanity checking on the command */ if (!_kgsl_cmdbatch_verify(dev_priv, cmdbatch)) goto free_cmdbatch; result = dev_priv->device->ftbl->issueibcmds(dev_priv, context, cmdbatch, &param->timestamp); free_cmdbatch: /* * -EPROTO is a "success" error - it just tells the user that the * context had previously faulted */ if (result && result != -EPROTO) kgsl_cmdbatch_destroy(cmdbatch); done: kgsl_context_put(context); return result; } long kgsl_ioctl_submit_commands(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_submit_commands *param = data; struct kgsl_device *device = dev_priv->device; struct kgsl_context *context; struct kgsl_cmdbatch *cmdbatch; long result = -EINVAL; /* * The SYNC bit is supposed to identify a dummy sync object so warn the * user if they specified any IBs with it. A MARKER command can either * have IBs or not but if the command has 0 IBs it is automatically * assumed to be a marker. If none of the above make sure that the user * specified a sane number of IBs */ if ((param->flags & KGSL_CMDBATCH_SYNC) && param->numcmds) KGSL_DEV_ERR_ONCE(device, "Commands specified with the SYNC flag. They will be ignored\n"); else if (param->numcmds > KGSL_MAX_NUMIBS) return -EINVAL; else if (!(param->flags & KGSL_CMDBATCH_SYNC) && param->numcmds == 0) param->flags |= KGSL_CMDBATCH_MARKER; context = kgsl_context_get_owner(dev_priv, param->context_id); if (context == NULL) return -EINVAL; cmdbatch = _kgsl_cmdbatch_create(device, context, param->flags, param->cmdlist, param->numcmds, param->synclist, param->numsyncs); if (IS_ERR(cmdbatch)) { result = PTR_ERR(cmdbatch); goto done; } /* Run basic sanity checking on the command */ if (!_kgsl_cmdbatch_verify(dev_priv, cmdbatch)) goto free_cmdbatch; result = dev_priv->device->ftbl->issueibcmds(dev_priv, context, cmdbatch, &param->timestamp); free_cmdbatch: /* * -EPROTO is a "success" error - it just tells the user that the * context had previously faulted */ if (result && result != -EPROTO) kgsl_cmdbatch_destroy(cmdbatch); done: kgsl_context_put(context); return result; } long kgsl_ioctl_cmdstream_readtimestamp_ctxtid(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_cmdstream_readtimestamp_ctxtid *param = data; struct kgsl_device *device = dev_priv->device; struct kgsl_context *context; long result = -EINVAL; mutex_lock(&device->mutex); context = kgsl_context_get_owner(dev_priv, param->context_id); if (context) { result = kgsl_readtimestamp(device, context, param->type, &param->timestamp); trace_kgsl_readtimestamp(device, context->id, param->type, param->timestamp); } kgsl_context_put(context); mutex_unlock(&device->mutex); return result; } static void kgsl_freemem_event_cb(struct kgsl_device *device, struct kgsl_event_group *group, void *priv, int result) { struct kgsl_context *context = group->context; struct kgsl_mem_entry *entry = priv; unsigned int timestamp; kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &timestamp); /* Free the memory for all event types */ trace_kgsl_mem_timestamp_free(device, entry, KGSL_CONTEXT_ID(context), timestamp, 0); kgsl_mem_entry_put(entry); } long kgsl_ioctl_cmdstream_freememontimestamp_ctxtid( struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_cmdstream_freememontimestamp_ctxtid *param = data; struct kgsl_device *device = dev_priv->device; struct kgsl_context *context; struct kgsl_mem_entry *entry; int result = -EINVAL; unsigned int temp_cur_ts = 0; /* If the user supplies incorrect type for timestamp, bail. */ if (param->type != KGSL_TIMESTAMP_RETIRED) return -EINVAL; context = kgsl_context_get_owner(dev_priv, param->context_id); if (context == NULL) goto out; entry = kgsl_sharedmem_find(dev_priv->process_priv, param->gpuaddr); if (!entry) { KGSL_DRV_ERR(device, "invalid gpuaddr 0x%08lX\n", param->gpuaddr); goto out; } if (!kgsl_mem_entry_set_pend(entry)) { KGSL_DRV_WARN(device, "Cannot set pending bit for gpuaddr 0x%08lX\n", param->gpuaddr); kgsl_mem_entry_put(entry); result = -EBUSY; goto out; } kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &temp_cur_ts); trace_kgsl_mem_timestamp_queue(device, entry, context->id, temp_cur_ts, param->timestamp); result = kgsl_add_event(dev_priv->device, &context->events, param->timestamp, kgsl_freemem_event_cb, entry); if (result) kgsl_mem_entry_unset_pend(entry); kgsl_mem_entry_put(entry); out: kgsl_context_put(context); return result; } long kgsl_ioctl_drawctxt_create(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_drawctxt_create *param = data; struct kgsl_context *context = NULL; struct kgsl_device *device = dev_priv->device; mutex_lock(&device->mutex); context = device->ftbl->drawctxt_create(dev_priv, &param->flags); if (IS_ERR(context)) { result = PTR_ERR(context); goto done; } trace_kgsl_context_create(dev_priv->device, context, param->flags); param->drawctxt_id = context->id; done: mutex_unlock(&device->mutex); return result; } long kgsl_ioctl_drawctxt_destroy(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_drawctxt_destroy *param = data; struct kgsl_context *context; long result; context = kgsl_context_get_owner(dev_priv, param->drawctxt_id); result = kgsl_context_detach(context); kgsl_context_put(context); return result; } static long _sharedmem_free_entry(struct kgsl_mem_entry *entry) { if (!kgsl_mem_entry_set_pend(entry)) { kgsl_mem_entry_put(entry); return -EBUSY; } trace_kgsl_mem_free(entry); kgsl_memfree_add(entry->priv->pid, entry->memdesc.gpuaddr, entry->memdesc.size, entry->memdesc.flags); /* * First kgsl_mem_entry_put is for the reference that we took in * this function when calling kgsl_sharedmem_find, second one is * to free the memory since this is a free ioctl */ kgsl_mem_entry_put(entry); kgsl_mem_entry_put(entry); return 0; } long kgsl_ioctl_sharedmem_free(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_sharedmem_free *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; entry = kgsl_sharedmem_find(private, param->gpuaddr); if (!entry) { KGSL_MEM_INFO(dev_priv->device, "invalid gpuaddr %08lx\n", param->gpuaddr); return -EINVAL; } return _sharedmem_free_entry(entry); } long kgsl_ioctl_gpumem_free_id(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_gpumem_free_id *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; entry = kgsl_sharedmem_find_id(private, param->id); if (!entry) { KGSL_MEM_INFO(dev_priv->device, "invalid id %d\n", param->id); return -EINVAL; } return _sharedmem_free_entry(entry); } static inline int _check_region(unsigned long start, unsigned long size, uint64_t len) { uint64_t end = ((uint64_t) start) + size; return (end > len); } #ifdef CONFIG_FB static int kgsl_get_phys_file(int fd, unsigned long *start, unsigned long *len, unsigned long *vstart, struct file **filep) { struct file *fbfile; int ret = 0; dev_t rdev; struct fb_info *info; *start = 0; *vstart = 0; *len = 0; *filep = NULL; fbfile = fget(fd); if (fbfile == NULL) { KGSL_CORE_ERR("fget_light failed\n"); return -1; } rdev = fbfile->f_dentry->d_inode->i_rdev; info = MAJOR(rdev) == FB_MAJOR ? registered_fb[MINOR(rdev)] : NULL; if (info) { *start = info->fix.smem_start; *len = info->fix.smem_len; *vstart = (unsigned long)__va(info->fix.smem_start); ret = 0; } else { KGSL_CORE_ERR("framebuffer minor %d not found\n", MINOR(rdev)); ret = -1; } fput(fbfile); return ret; } static int kgsl_setup_phys_file(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, unsigned int fd, size_t offset, size_t size) { int ret; unsigned long phys, virt, len; struct file *filep; ret = kgsl_get_phys_file(fd, &phys, &len, &virt, &filep); if (ret) return ret; ret = -ERANGE; if (phys == 0) goto err; /* Make sure the length of the region, the offset and the desired * size are all page aligned or bail */ if ((len & ~PAGE_MASK) || (offset & ~PAGE_MASK) || (size & ~PAGE_MASK)) { KGSL_CORE_ERR("length offset or size is not page aligned\n"); goto err; } /* The size or offset can never be greater than the PMEM length */ if (offset >= len || size > len) goto err; /* If size is 0, then adjust it to default to the size of the region * minus the offset. If size isn't zero, then make sure that it will * fit inside of the region. */ if (size == 0) size = len - offset; else if (_check_region(offset, size, len)) goto err; entry->priv_data = filep; entry->memdesc.pagetable = pagetable; entry->memdesc.size = size; entry->memdesc.physaddr = phys + offset; entry->memdesc.hostptr = (void *) (virt + offset); /* USE_CPU_MAP is not impemented for PMEM. */ entry->memdesc.flags &= ~KGSL_MEMFLAGS_USE_CPU_MAP; entry->memdesc.flags |= KGSL_MEMFLAGS_USERMEM_PMEM; ret = memdesc_sg_phys(&entry->memdesc, phys + offset, size); if (ret) goto err; return 0; err: return ret; } #else static int kgsl_setup_phys_file(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, unsigned int fd, unsigned int offset, size_t size) { return -EINVAL; } #endif static int check_vma(struct vm_area_struct *vma, struct file *vmfile, struct kgsl_memdesc *memdesc) { if (vma == NULL || vma->vm_file != vmfile) return -EINVAL; /* userspace may not know the size, in which case use the whole vma */ if (memdesc->size == 0) memdesc->size = vma->vm_end - vma->vm_start; /* range checking */ if (vma->vm_start != memdesc->useraddr || (memdesc->useraddr + memdesc->size) != vma->vm_end) return -EINVAL; return 0; } static int memdesc_sg_virt(struct kgsl_memdesc *memdesc, struct file *vmfile) { int ret = 0; long npages = 0, i; unsigned long sglen = memdesc->size / PAGE_SIZE; struct page **pages = NULL; int write = (memdesc->flags & KGSL_MEMFLAGS_GPUREADONLY) != 0; if (sglen == 0 || sglen >= LONG_MAX) return -EINVAL; pages = kgsl_malloc(sglen * sizeof(struct page *)); if (pages == NULL) return -ENOMEM; memdesc->sg = kgsl_malloc(sglen * sizeof(struct scatterlist)); if (memdesc->sg == NULL) { ret = -ENOMEM; goto out; } memdesc->sglen = sglen; sg_init_table(memdesc->sg, sglen); down_read(&current->mm->mmap_sem); /* If we have vmfile, make sure we map the correct vma and map it all */ if (vmfile != NULL) ret = check_vma(find_vma(current->mm, memdesc->useraddr), vmfile, memdesc); if (ret == 0) { npages = get_user_pages(current, current->mm, memdesc->useraddr, sglen, write, 0, pages, NULL); ret = (npages < 0) ? (int)npages : 0; } up_read(&current->mm->mmap_sem); if (ret) goto out; if ((unsigned long) npages != sglen) { ret = -EINVAL; goto out; } for (i = 0; i < npages; i++) sg_set_page(&memdesc->sg[i], pages[i], PAGE_SIZE, 0); out: if (ret) { for (i = 0; i < npages; i++) put_page(pages[i]); kgsl_free(memdesc->sg); memdesc->sg = NULL; } kgsl_free(pages); return ret; } static int match_file(const void *p, struct file *file, unsigned int fd) { /* * We must return fd + 1 because iterate_fd stops searching on * non-zero return, but 0 is a valid fd. */ return (p == file) ? (fd + 1) : 0; } static void _setup_cache_mode(struct kgsl_mem_entry *entry, struct vm_area_struct *vma) { unsigned int mode; pgprot_t pgprot = vma->vm_page_prot; if (pgprot == pgprot_noncached(pgprot)) mode = KGSL_CACHEMODE_UNCACHED; else if (pgprot == pgprot_writecombine(pgprot)) mode = KGSL_CACHEMODE_WRITECOMBINE; else mode = KGSL_CACHEMODE_WRITEBACK; entry->memdesc.flags |= (mode << KGSL_CACHEMODE_SHIFT); } static int kgsl_setup_useraddr(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, void *data, struct kgsl_device *device) { struct kgsl_map_user_mem *param = data; struct dma_buf *dmabuf = NULL; struct vm_area_struct *vma = NULL; if (param->offset != 0 || param->hostptr == 0 || !KGSL_IS_PAGE_ALIGNED(param->hostptr) || !KGSL_IS_PAGE_ALIGNED(param->len)) return -EINVAL; /* * Find the VMA containing this pointer and figure out if it * is a dma-buf. */ down_read(&current->mm->mmap_sem); vma = find_vma(current->mm, param->hostptr); if (vma && vma->vm_file) { int fd; /* * Check to see that this isn't our own memory that we have * already mapped */ if (vma->vm_file->f_op == &kgsl_fops) { up_read(&current->mm->mmap_sem); return -EFAULT; } /* Look for the fd that matches this the vma file */ fd = iterate_fd(current->files, 0, match_file, vma->vm_file); if (fd != 0) dmabuf = dma_buf_get(fd - 1); } up_read(&current->mm->mmap_sem); if (!IS_ERR_OR_NULL(dmabuf)) { int ret = kgsl_setup_dma_buf(entry, pagetable, device, dmabuf); if (ret) dma_buf_put(dmabuf); else { /* Match the cache settings of the vma region */ _setup_cache_mode(entry, vma); /* Set the useraddr to the incoming hostptr */ entry->memdesc.useraddr = param->hostptr; } return ret; } entry->memdesc.pagetable = pagetable; entry->memdesc.size = param->len; entry->memdesc.useraddr = param->hostptr; if (kgsl_memdesc_use_cpu_map(&entry->memdesc)) entry->memdesc.gpuaddr = entry->memdesc.useraddr; entry->memdesc.flags |= KGSL_MEMFLAGS_USERMEM_ADDR; return memdesc_sg_virt(&entry->memdesc, NULL); } #ifdef CONFIG_ASHMEM static int kgsl_setup_ashmem(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, int fd, unsigned long useraddr, size_t size) { int ret; struct file *filep, *vmfile; unsigned long len; if (useraddr == 0 || !KGSL_IS_PAGE_ALIGNED(useraddr) || !KGSL_IS_PAGE_ALIGNED(size)) return -EINVAL; ret = get_ashmem_file(fd, &filep, &vmfile, &len); if (ret) return ret; entry->priv_data = filep; entry->memdesc.pagetable = pagetable; entry->memdesc.size = ALIGN(size, PAGE_SIZE); entry->memdesc.useraddr = useraddr; if (kgsl_memdesc_use_cpu_map(&entry->memdesc)) entry->memdesc.gpuaddr = entry->memdesc.useraddr; entry->memdesc.flags |= KGSL_MEMFLAGS_USERMEM_ASHMEM; ret = memdesc_sg_virt(&entry->memdesc, vmfile); if (ret) put_ashmem_file(filep); return ret; } #else static int kgsl_setup_ashmem(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, int fd, unsigned long useraddr, size_t size) { return -EINVAL; } #endif #ifdef CONFIG_DMA_SHARED_BUFFER static int kgsl_setup_dma_buf(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, struct kgsl_device *device, struct dma_buf *dmabuf) { int ret = 0; struct scatterlist *s; struct sg_table *sg_table; struct dma_buf_attachment *attach = NULL; struct kgsl_dma_buf_meta *meta; meta = kzalloc(sizeof(*meta), GFP_KERNEL); if (!meta) return -ENOMEM; attach = dma_buf_attach(dmabuf, device->dev); if (IS_ERR_OR_NULL(attach)) { ret = attach ? PTR_ERR(attach) : -EINVAL; goto out; } meta->dmabuf = dmabuf; meta->attach = attach; entry->priv_data = meta; entry->memdesc.pagetable = pagetable; entry->memdesc.size = 0; /* USE_CPU_MAP is not impemented for ION. */ entry->memdesc.flags &= ~KGSL_MEMFLAGS_USE_CPU_MAP; entry->memdesc.flags |= KGSL_MEMFLAGS_USERMEM_ION; sg_table = dma_buf_map_attachment(attach, DMA_TO_DEVICE); if (IS_ERR_OR_NULL(sg_table)) { ret = PTR_ERR(sg_table); goto out; } meta->table = sg_table; entry->priv_data = meta; entry->memdesc.sg = sg_table->sgl; /* Calculate the size of the memdesc from the sglist */ entry->memdesc.sglen = 0; for (s = entry->memdesc.sg; s != NULL; s = sg_next(s)) { int priv = (entry->memdesc.priv & KGSL_MEMDESC_SECURE) ? 1 : 0; /* * Check that each chunk of of the sg table matches the secure * flag. */ if (PagePrivate(sg_page(s)) != priv) { ret = -EPERM; goto out; } entry->memdesc.size += s->length; entry->memdesc.sglen++; } entry->memdesc.size = PAGE_ALIGN(entry->memdesc.size); out: if (ret) { if (!IS_ERR_OR_NULL(attach)) dma_buf_detach(dmabuf, attach); kfree(meta); } return ret; } static int kgsl_setup_ion(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, void *data, struct kgsl_device *device) { int ret; struct kgsl_map_user_mem *param = data; int fd = param->fd; struct dma_buf *dmabuf; dmabuf = dma_buf_get(fd); if (IS_ERR_OR_NULL(dmabuf)) return (dmabuf == NULL) ? -EINVAL : PTR_ERR(dmabuf); ret = kgsl_setup_dma_buf(entry, pagetable, device, dmabuf); if (ret) dma_buf_put(dmabuf); return ret; } #else static int kgsl_setup_dma_buf(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, struct kgsl_device *device, struct dma_buf *dmabuf) { return -EINVAL; } static int kgsl_setup_ion(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, void *data, struct kgsl_device *device) { return -EINVAL; } #endif long kgsl_ioctl_map_user_mem(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = -EINVAL; struct kgsl_map_user_mem *param = data; struct kgsl_mem_entry *entry = NULL; struct kgsl_process_private *private = dev_priv->process_priv; unsigned int memtype; /* * If content protection is not enabled and secure buffer * is requested to be mapped return error. */ if (param->flags & KGSL_MEMFLAGS_SECURE) { /* Log message and return if context protection isn't enabled */ if (!kgsl_mmu_is_secured(&dev_priv->device->mmu)) { dev_WARN_ONCE(dev_priv->device->dev, 1, "Secure buffer not supported"); return -EOPNOTSUPP; } /* Can't use CPU map with secure buffers */ if (param->flags & KGSL_MEMFLAGS_USE_CPU_MAP) return -EINVAL; } entry = kgsl_mem_entry_create(); if (entry == NULL) return -ENOMEM; /* * Convert from enum value to KGSL_MEM_ENTRY value, so that * we can use the latter consistently everywhere. */ if (_IOC_SIZE(cmd) == sizeof(struct kgsl_sharedmem_from_pmem)) memtype = KGSL_MEM_ENTRY_PMEM; else memtype = param->memtype + 1; /* * Mask off unknown flags from userspace. This way the caller can * check if a flag is supported by looking at the returned flags. * Note: CACHEMODE is ignored for this call. Caching should be * determined by type of allocation being mapped. */ param->flags &= KGSL_MEMFLAGS_GPUREADONLY | KGSL_MEMTYPE_MASK | KGSL_MEMALIGN_MASK | KGSL_MEMFLAGS_USE_CPU_MAP | KGSL_MEMFLAGS_SECURE; entry->memdesc.flags = param->flags; if (!kgsl_mmu_use_cpu_map(&dev_priv->device->mmu)) entry->memdesc.flags &= ~KGSL_MEMFLAGS_USE_CPU_MAP; if (kgsl_mmu_get_mmutype() == KGSL_MMU_TYPE_IOMMU) entry->memdesc.priv |= KGSL_MEMDESC_GUARD_PAGE; if (param->flags & KGSL_MEMFLAGS_SECURE) entry->memdesc.priv |= KGSL_MEMDESC_SECURE; switch (memtype) { case KGSL_MEM_ENTRY_PMEM: if (param->fd == 0 || param->len == 0) break; result = kgsl_setup_phys_file(entry, private->pagetable, param->fd, param->offset, param->len); break; case KGSL_MEM_ENTRY_USER: if (!kgsl_mmu_enabled()) { KGSL_DRV_ERR(dev_priv->device, "Cannot map paged memory with the " "MMU disabled\n"); break; } if (param->hostptr == 0) break; result = kgsl_setup_useraddr(entry, private->pagetable, data, dev_priv->device); break; case KGSL_MEM_ENTRY_ASHMEM: if (!kgsl_mmu_enabled()) { KGSL_DRV_ERR(dev_priv->device, "Cannot map paged memory with the " "MMU disabled\n"); break; } result = kgsl_setup_ashmem(entry, private->pagetable, param->fd, param->hostptr, param->len); break; case KGSL_MEM_ENTRY_ION: result = kgsl_setup_ion(entry, private->pagetable, data, dev_priv->device); break; default: KGSL_CORE_ERR("Invalid memory type: %x\n", memtype); break; } if (result) goto error; if ((param->flags & KGSL_MEMFLAGS_SECURE) && !IS_ALIGNED(entry->memdesc.size, SZ_1M)) { KGSL_DRV_ERR(dev_priv->device, "Secure buffer size %zx must be 1MB aligned", entry->memdesc.size); result = -EINVAL; goto error_attach; } if (entry->memdesc.size >= SZ_2M) kgsl_memdesc_set_align(&entry->memdesc, ilog2(SZ_2M)); else if (entry->memdesc.size >= SZ_1M) kgsl_memdesc_set_align(&entry->memdesc, ilog2(SZ_1M)); else if (entry->memdesc.size >= SZ_64K) kgsl_memdesc_set_align(&entry->memdesc, ilog2(SZ_64)); /* echo back flags */ param->flags = entry->memdesc.flags; result = kgsl_mem_entry_attach_process(entry, dev_priv); if (result) goto error_attach; /* Adjust the returned value for a non 4k aligned offset */ param->gpuaddr = entry->memdesc.gpuaddr + (param->offset & PAGE_MASK); KGSL_STATS_ADD(param->len, kgsl_driver.stats.mapped, kgsl_driver.stats.mapped_max); kgsl_process_add_stats(private, kgsl_memdesc_usermem_type(&entry->memdesc), param->len); trace_kgsl_mem_map(entry, param->fd); return result; error_attach: switch (memtype) { case KGSL_MEM_ENTRY_PMEM: case KGSL_MEM_ENTRY_ASHMEM: if (entry->priv_data) fput(entry->priv_data); break; case KGSL_MEM_ENTRY_ION: kgsl_destroy_ion(entry->priv_data); entry->memdesc.sg = NULL; break; default: break; } kgsl_sharedmem_free(&entry->memdesc); error: /* Clear gpuaddr here so userspace doesn't get any wrong ideas */ param->gpuaddr = 0; kfree(entry); return result; } static int _kgsl_gpumem_sync_cache(struct kgsl_mem_entry *entry, size_t offset, size_t length, unsigned int op) { int ret = 0; int cacheop; int mode; /* * Flush is defined as (clean | invalidate). If both bits are set, then * do a flush, otherwise check for the individual bits and clean or inv * as requested */ if ((op & KGSL_GPUMEM_CACHE_FLUSH) == KGSL_GPUMEM_CACHE_FLUSH) cacheop = KGSL_CACHE_OP_FLUSH; else if (op & KGSL_GPUMEM_CACHE_CLEAN) cacheop = KGSL_CACHE_OP_CLEAN; else if (op & KGSL_GPUMEM_CACHE_INV) cacheop = KGSL_CACHE_OP_INV; else { ret = -EINVAL; goto done; } if (!(op & KGSL_GPUMEM_CACHE_RANGE)) { offset = 0; length = entry->memdesc.size; } mode = kgsl_memdesc_get_cachemode(&entry->memdesc); if (mode != KGSL_CACHEMODE_UNCACHED && mode != KGSL_CACHEMODE_WRITECOMBINE) { trace_kgsl_mem_sync_cache(entry, offset, length, op); ret = kgsl_cache_range_op(&entry->memdesc, offset, length, cacheop); } done: return ret; } /* New cache sync function - supports both directions (clean and invalidate) */ long kgsl_ioctl_gpumem_sync_cache(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_gpumem_sync_cache *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; long ret; if (param->id != 0) { entry = kgsl_sharedmem_find_id(private, param->id); if (entry == NULL) { KGSL_MEM_INFO(dev_priv->device, "can't find id %d\n", param->id); return -EINVAL; } } else if (param->gpuaddr != 0) { entry = kgsl_sharedmem_find(private, param->gpuaddr); if (entry == NULL) { KGSL_MEM_INFO(dev_priv->device, "can't find gpuaddr %lx\n", param->gpuaddr); return -EINVAL; } } else { return -EINVAL; } ret = _kgsl_gpumem_sync_cache(entry, param->offset, param->length, param->op); kgsl_mem_entry_put(entry); return ret; } static int mem_id_cmp(const void *_a, const void *_b) { const unsigned int *a = _a, *b = _b; if (*a == *b) return 0; return (*a > *b) ? 1 : -1; } #ifdef CONFIG_ARM64 /* Do not support full flush on ARM64 targets */ static inline bool check_full_flush(size_t size, int op) { return false; } #else /* Support full flush if the size is bigger than the threshold */ static inline bool check_full_flush(size_t size, int op) { /* If we exceed the breakeven point, flush the entire cache */ return (kgsl_driver.full_cache_threshold != 0) && (size >= kgsl_driver.full_cache_threshold) && (op == KGSL_GPUMEM_CACHE_FLUSH); } #endif long kgsl_ioctl_gpumem_sync_cache_bulk(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int i; struct kgsl_gpumem_sync_cache_bulk *param = data; struct kgsl_process_private *private = dev_priv->process_priv; unsigned int id, last_id = 0, *id_list = NULL, actual_count = 0; struct kgsl_mem_entry **entries = NULL; long ret = 0; size_t op_size = 0; bool full_flush = false; if (param->id_list == NULL || param->count == 0 || param->count > (PAGE_SIZE / sizeof(unsigned int))) return -EINVAL; id_list = kzalloc(param->count * sizeof(unsigned int), GFP_KERNEL); if (id_list == NULL) return -ENOMEM; entries = kzalloc(param->count * sizeof(*entries), GFP_KERNEL); if (entries == NULL) { ret = -ENOMEM; goto end; } if (copy_from_user(id_list, param->id_list, param->count * sizeof(unsigned int))) { ret = -EFAULT; goto end; } /* sort the ids so we can weed out duplicates */ sort(id_list, param->count, sizeof(*id_list), mem_id_cmp, NULL); for (i = 0; i < param->count; i++) { unsigned int cachemode; struct kgsl_mem_entry *entry = NULL; id = id_list[i]; /* skip 0 ids or duplicates */ if (id == last_id) continue; entry = kgsl_sharedmem_find_id(private, id); if (entry == NULL) continue; /* skip uncached memory */ cachemode = kgsl_memdesc_get_cachemode(&entry->memdesc); if (cachemode != KGSL_CACHEMODE_WRITETHROUGH && cachemode != KGSL_CACHEMODE_WRITEBACK) { kgsl_mem_entry_put(entry); continue; } op_size += entry->memdesc.size; entries[actual_count++] = entry; full_flush = check_full_flush(op_size, param->op); if (full_flush) break; last_id = id; } if (full_flush) { trace_kgsl_mem_sync_full_cache(actual_count, op_size, param->op); flush_cache_all(); } param->op &= ~KGSL_GPUMEM_CACHE_RANGE; for (i = 0; i < actual_count; i++) { if (!full_flush) _kgsl_gpumem_sync_cache(entries[i], 0, entries[i]->memdesc.size, param->op); kgsl_mem_entry_put(entries[i]); } end: kfree(entries); kfree(id_list); return ret; } /* Legacy cache function, does a flush (clean + invalidate) */ long kgsl_ioctl_sharedmem_flush_cache(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_sharedmem_free *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; long ret; entry = kgsl_sharedmem_find(private, param->gpuaddr); if (entry == NULL) { KGSL_MEM_INFO(dev_priv->device, "can't find gpuaddr %lx\n", param->gpuaddr); return -EINVAL; } ret = _kgsl_gpumem_sync_cache(entry, 0, entry->memdesc.size, KGSL_GPUMEM_CACHE_FLUSH); kgsl_mem_entry_put(entry); return ret; } #ifdef CONFIG_ARM64 static int kgsl_filter_cachemode(unsigned int flags) { /* * WRITETHROUGH is not supported in arm64, so we tell the user that we * use WRITEBACK which is the default caching policy. */ if ((flags & KGSL_CACHEMODE_MASK) >> KGSL_CACHEMODE_SHIFT == KGSL_CACHEMODE_WRITETHROUGH) { flags &= ~KGSL_CACHEMODE_MASK; flags |= (KGSL_CACHEMODE_WRITEBACK << KGSL_CACHEMODE_SHIFT) & KGSL_CACHEMODE_MASK; } return flags; } #else static int kgsl_filter_cachemode(unsigned int flags) { return flags; } #endif /* The largest allowable alignment for a GPU object is 32MB */ #define KGSL_MAX_ALIGN (32 * SZ_1M) /* * The common parts of kgsl_ioctl_gpumem_alloc and kgsl_ioctl_gpumem_alloc_id. */ static int _gpumem_alloc(struct kgsl_device_private *dev_priv, struct kgsl_mem_entry **ret_entry, size_t size, unsigned int flags) { int result; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry; int align; /* * Mask off unknown flags from userspace. This way the caller can * check if a flag is supported by looking at the returned flags. */ flags &= KGSL_MEMFLAGS_GPUREADONLY | KGSL_CACHEMODE_MASK | KGSL_MEMTYPE_MASK | KGSL_MEMALIGN_MASK | KGSL_MEMFLAGS_USE_CPU_MAP | KGSL_MEMFLAGS_SECURE; /* If content protection is not enabled force memory to be nonsecure */ if (!kgsl_mmu_is_secured(&dev_priv->device->mmu) && (flags & KGSL_MEMFLAGS_SECURE)) { dev_WARN_ONCE(dev_priv->device->dev, 1, "Secure memory not supported"); return -EOPNOTSUPP; } /* Cap the alignment bits to the highest number we can handle */ align = (flags & KGSL_MEMALIGN_MASK) >> KGSL_MEMALIGN_SHIFT; if (align >= ilog2(KGSL_MAX_ALIGN)) { KGSL_CORE_ERR("Alignment too large; restricting to %dK\n", KGSL_MAX_ALIGN >> 10); flags &= ~KGSL_MEMALIGN_MASK; flags |= (ilog2(KGSL_MAX_ALIGN) << KGSL_MEMALIGN_SHIFT) & KGSL_MEMALIGN_MASK; } flags = kgsl_filter_cachemode(flags); entry = kgsl_mem_entry_create(); if (entry == NULL) return -ENOMEM; if (kgsl_mmu_get_mmutype() == KGSL_MMU_TYPE_IOMMU) entry->memdesc.priv |= KGSL_MEMDESC_GUARD_PAGE; result = kgsl_allocate_user(dev_priv->device, &entry->memdesc, private->pagetable, size, flags); if (result != 0) goto err; *ret_entry = entry; return result; err: kfree(entry); *ret_entry = NULL; return result; } long kgsl_ioctl_gpumem_alloc(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_gpumem_alloc *param = data; struct kgsl_mem_entry *entry = NULL; int result; param->flags &= ~KGSL_MEMFLAGS_USE_CPU_MAP; result = _gpumem_alloc(dev_priv, &entry, param->size, param->flags); if (result) return result; if (param->flags & KGSL_MEMFLAGS_SECURE) entry->memdesc.priv |= KGSL_MEMDESC_SECURE; result = kgsl_mem_entry_attach_process(entry, dev_priv); if (result != 0) goto err; kgsl_process_add_stats(private, kgsl_memdesc_usermem_type(&entry->memdesc), param->size); trace_kgsl_mem_alloc(entry); param->gpuaddr = entry->memdesc.gpuaddr; param->size = entry->memdesc.size; param->flags = entry->memdesc.flags; return result; err: kgsl_sharedmem_free(&entry->memdesc); kfree(entry); return result; } long kgsl_ioctl_gpumem_alloc_id(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_device *device = dev_priv->device; struct kgsl_gpumem_alloc_id *param = data; struct kgsl_mem_entry *entry = NULL; int result; if (!kgsl_mmu_use_cpu_map(&device->mmu)) param->flags &= ~KGSL_MEMFLAGS_USE_CPU_MAP; result = _gpumem_alloc(dev_priv, &entry, param->size, param->flags); if (result != 0) goto err; if (param->flags & KGSL_MEMFLAGS_SECURE) { entry->memdesc.priv |= KGSL_MEMDESC_SECURE; if (param->flags & KGSL_MEMFLAGS_USE_CPU_MAP) { result = -EINVAL; goto err; } } result = kgsl_mem_entry_attach_process(entry, dev_priv); if (result != 0) goto err; kgsl_process_add_stats(private, kgsl_memdesc_usermem_type(&entry->memdesc), param->size); trace_kgsl_mem_alloc(entry); param->id = entry->id; param->flags = entry->memdesc.flags; param->size = entry->memdesc.size; param->mmapsize = kgsl_memdesc_mmapsize(&entry->memdesc); param->gpuaddr = entry->memdesc.gpuaddr; return result; err: if (entry) kgsl_sharedmem_free(&entry->memdesc); kfree(entry); return result; } long kgsl_ioctl_gpumem_get_info(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_gpumem_get_info *param = data; struct kgsl_mem_entry *entry = NULL; int result = 0; if (param->id != 0) { entry = kgsl_sharedmem_find_id(private, param->id); if (entry == NULL) { KGSL_MEM_INFO(dev_priv->device, "can't find id %d\n", param->id); return -EINVAL; } } else if (param->gpuaddr != 0) { entry = kgsl_sharedmem_find(private, param->gpuaddr); if (entry == NULL) { KGSL_MEM_INFO(dev_priv->device, "can't find gpuaddr %lx\n", param->gpuaddr); return -EINVAL; } } else { return -EINVAL; } param->gpuaddr = entry->memdesc.gpuaddr; param->id = entry->id; param->flags = entry->memdesc.flags; param->size = entry->memdesc.size; param->mmapsize = kgsl_memdesc_mmapsize(&entry->memdesc); param->useraddr = entry->memdesc.useraddr; kgsl_mem_entry_put(entry); return result; } long kgsl_ioctl_cff_syncmem(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_cff_syncmem *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; entry = kgsl_sharedmem_find_region(private, param->gpuaddr, param->len); if (!entry) return -EINVAL; kgsl_cffdump_syncmem(dev_priv->device, &entry->memdesc, param->gpuaddr, param->len, true); kgsl_mem_entry_put(entry); return result; } long kgsl_ioctl_cff_user_event(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_cff_user_event *param = data; kgsl_cffdump_user_event(dev_priv->device, param->cff_opcode, param->op1, param->op2, param->op3, param->op4, param->op5); return result; } /** * kgsl_ioctl_timestamp_event - Register a new timestamp event from userspace * @dev_priv - pointer to the private device structure * @cmd - the ioctl cmd passed from kgsl_ioctl * @data - the user data buffer from kgsl_ioctl * @returns 0 on success or error code on failure */ long kgsl_ioctl_timestamp_event(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_timestamp_event *param = data; int ret; switch (param->type) { case KGSL_TIMESTAMP_EVENT_FENCE: ret = kgsl_add_fence_event(dev_priv->device, param->context_id, param->timestamp, param->priv, param->len, dev_priv); break; default: ret = -EINVAL; } return ret; } static const struct kgsl_ioctl kgsl_ioctl_funcs[] = { KGSL_IOCTL_FUNC(IOCTL_KGSL_DEVICE_GETPROPERTY, kgsl_ioctl_device_getproperty), /* IOCTL_KGSL_DEVICE_WAITTIMESTAMP is no longer supported */ KGSL_IOCTL_FUNC(IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, kgsl_ioctl_device_waittimestamp_ctxtid), KGSL_IOCTL_FUNC(IOCTL_KGSL_RINGBUFFER_ISSUEIBCMDS, kgsl_ioctl_rb_issueibcmds), KGSL_IOCTL_FUNC(IOCTL_KGSL_SUBMIT_COMMANDS, kgsl_ioctl_submit_commands), /* IOCTL_KGSL_CMDSTREAM_READTIMESTAMP is no longer supported */ KGSL_IOCTL_FUNC(IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, kgsl_ioctl_cmdstream_readtimestamp_ctxtid), /* IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP is no longer supported */ KGSL_IOCTL_FUNC(IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_CTXTID, kgsl_ioctl_cmdstream_freememontimestamp_ctxtid), KGSL_IOCTL_FUNC(IOCTL_KGSL_DRAWCTXT_CREATE, kgsl_ioctl_drawctxt_create), KGSL_IOCTL_FUNC(IOCTL_KGSL_DRAWCTXT_DESTROY, kgsl_ioctl_drawctxt_destroy), KGSL_IOCTL_FUNC(IOCTL_KGSL_MAP_USER_MEM, kgsl_ioctl_map_user_mem), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FROM_PMEM, kgsl_ioctl_map_user_mem), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FREE, kgsl_ioctl_sharedmem_free), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FLUSH_CACHE, kgsl_ioctl_sharedmem_flush_cache), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_ALLOC, kgsl_ioctl_gpumem_alloc), KGSL_IOCTL_FUNC(IOCTL_KGSL_CFF_SYNCMEM, kgsl_ioctl_cff_syncmem), KGSL_IOCTL_FUNC(IOCTL_KGSL_CFF_USER_EVENT, kgsl_ioctl_cff_user_event), KGSL_IOCTL_FUNC(IOCTL_KGSL_TIMESTAMP_EVENT, kgsl_ioctl_timestamp_event), KGSL_IOCTL_FUNC(IOCTL_KGSL_SETPROPERTY, kgsl_ioctl_device_setproperty), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_ALLOC_ID, kgsl_ioctl_gpumem_alloc_id), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_FREE_ID, kgsl_ioctl_gpumem_free_id), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_GET_INFO, kgsl_ioctl_gpumem_get_info), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_SYNC_CACHE, kgsl_ioctl_gpumem_sync_cache), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_SYNC_CACHE_BULK, kgsl_ioctl_gpumem_sync_cache_bulk), KGSL_IOCTL_FUNC(IOCTL_KGSL_SYNCSOURCE_CREATE, kgsl_ioctl_syncsource_create), KGSL_IOCTL_FUNC(IOCTL_KGSL_SYNCSOURCE_DESTROY, kgsl_ioctl_syncsource_destroy), KGSL_IOCTL_FUNC(IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE, kgsl_ioctl_syncsource_create_fence), KGSL_IOCTL_FUNC(IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE, kgsl_ioctl_syncsource_signal_fence), }; long kgsl_ioctl_helper(struct file *filep, unsigned int cmd, const struct kgsl_ioctl *ioctl_funcs, unsigned int array_size, unsigned long arg) { struct kgsl_device_private *dev_priv = filep->private_data; unsigned int nr; kgsl_ioctl_func_t func; int ret; char ustack[64]; void *uptr = ustack; BUG_ON(dev_priv == NULL); if (cmd == IOCTL_KGSL_TIMESTAMP_EVENT_OLD) cmd = IOCTL_KGSL_TIMESTAMP_EVENT; nr = _IOC_NR(cmd); if (cmd & IOC_INOUT) { if (_IOC_SIZE(cmd) > sizeof(ustack)) { uptr = kzalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (uptr == NULL) { KGSL_MEM_ERR(dev_priv->device, "kzalloc(%d) failed\n", _IOC_SIZE(cmd)); ret = -ENOMEM; goto done; } } if (cmd & IOC_IN) { if (copy_from_user(uptr, (void __user *) arg, _IOC_SIZE(cmd))) { ret = -EFAULT; goto done; } } else memset(uptr, 0, _IOC_SIZE(cmd)); } if (nr < array_size && ioctl_funcs[nr].func != NULL) { /* * Make sure that nobody tried to send us a malformed ioctl code * with a valid NR but bogus flags */ if (ioctl_funcs[nr].cmd != cmd) { KGSL_DRV_ERR(dev_priv->device, "Malformed ioctl code %08x\n", cmd); ret = -ENOIOCTLCMD; goto done; } func = ioctl_funcs[nr].func; } else { if (is_compat_task() && cmd != IOCTL_KGSL_DRAWCTXT_SET_BIN_BASE_OFFSET && cmd != IOCTL_KGSL_PERFCOUNTER_GET && cmd != IOCTL_KGSL_PERFCOUNTER_PUT) func = dev_priv->device->ftbl->compat_ioctl; else func = dev_priv->device->ftbl->ioctl; if (!func) { KGSL_DRV_INFO(dev_priv->device, "invalid ioctl code %08x\n", cmd); ret = -ENOIOCTLCMD; goto done; } } ret = func(dev_priv, cmd, uptr); /* * Still copy back on failure, but assume function took * all necessary precautions sanitizing the return values. */ if (cmd & IOC_OUT) { if (copy_to_user((void __user *) arg, uptr, _IOC_SIZE(cmd))) ret = -EFAULT; } done: if ((cmd & IOC_INOUT) && (uptr != ustack)) kfree(uptr); return ret; } static long kgsl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg) { return kgsl_ioctl_helper(filep, cmd, kgsl_ioctl_funcs, ARRAY_SIZE(kgsl_ioctl_funcs), arg); } static int kgsl_mmap_memstore(struct kgsl_device *device, struct vm_area_struct *vma) { struct kgsl_memdesc *memdesc = &device->memstore; int result; unsigned int vma_size = vma->vm_end - vma->vm_start; /* The memstore can only be mapped as read only */ if (vma->vm_flags & VM_WRITE) return -EPERM; if (memdesc->size != vma_size) { KGSL_MEM_ERR(device, "memstore bad size: %d should be %zd\n", vma_size, memdesc->size); return -EINVAL; } vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); result = remap_pfn_range(vma, vma->vm_start, device->memstore.physaddr >> PAGE_SHIFT, vma_size, vma->vm_page_prot); if (result != 0) KGSL_MEM_ERR(device, "remap_pfn_range failed: %d\n", result); return result; } /* * kgsl_gpumem_vm_open is called whenever a vma region is copied or split. * Increase the refcount to make sure that the accounting stays correct */ static void kgsl_gpumem_vm_open(struct vm_area_struct *vma) { struct kgsl_mem_entry *entry = vma->vm_private_data; if (!kgsl_mem_entry_get(entry)) vma->vm_private_data = NULL; } static int kgsl_gpumem_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct kgsl_mem_entry *entry = vma->vm_private_data; if (!entry) return VM_FAULT_SIGBUS; if (!entry->memdesc.ops || !entry->memdesc.ops->vmfault) return VM_FAULT_SIGBUS; return entry->memdesc.ops->vmfault(&entry->memdesc, vma, vmf); } static void kgsl_gpumem_vm_close(struct vm_area_struct *vma) { struct kgsl_mem_entry *entry = vma->vm_private_data; if (!entry) return; entry->memdesc.useraddr = 0; kgsl_mem_entry_put(entry); } static struct vm_operations_struct kgsl_gpumem_vm_ops = { .open = kgsl_gpumem_vm_open, .fault = kgsl_gpumem_vm_fault, .close = kgsl_gpumem_vm_close, }; static int get_mmap_entry(struct kgsl_process_private *private, struct kgsl_mem_entry **out_entry, unsigned long pgoff, unsigned long len) { int ret = 0; struct kgsl_mem_entry *entry; entry = kgsl_sharedmem_find_id(private, pgoff); if (entry == NULL) entry = kgsl_sharedmem_find(private, pgoff << PAGE_SHIFT); if (!entry) return -EINVAL; if (!entry->memdesc.ops || !entry->memdesc.ops->vmflags || !entry->memdesc.ops->vmfault) { ret = -EINVAL; goto err_put; } if (entry->memdesc.useraddr != 0) { ret = -EBUSY; goto err_put; } if (kgsl_memdesc_use_cpu_map(&entry->memdesc)) { if (len != kgsl_memdesc_mmapsize(&entry->memdesc)) { ret = -ERANGE; goto err_put; } } else if (len != kgsl_memdesc_mmapsize(&entry->memdesc) && len != entry->memdesc.size) { /* * If cpu_map != gpumap then user can map either the * mmapsize or the entry size */ ret = -ERANGE; goto err_put; } *out_entry = entry; return 0; err_put: kgsl_mem_entry_put(entry); return ret; } static inline bool mmap_range_valid(unsigned long addr, unsigned long len) { return ((ULONG_MAX - addr) > len) && ((addr + len) <= KGSL_SVM_UPPER_BOUND) && (addr >= KGSL_SVM_LOWER_BOUND); } /** * __kgsl_check_collision() - Find a non colliding gpuaddr for the process * @private: Process private pointer contaning the list of allocations * @entry: The entry colliding with given address * @gpuaddr: In out parameter. The In parameter contains the desired gpuaddr * if the gpuaddr collides then the out parameter contains the non colliding * address * @len: Length of address range * @flag_top_down: Indicates whether free address range should be checked in * top down or bottom up fashion */ static int __kgsl_check_collision(struct kgsl_process_private *private, struct kgsl_mem_entry *entry, unsigned long *gpuaddr, unsigned long len, int flag_top_down) { int ret = 0; unsigned long addr = *gpuaddr; struct kgsl_mem_entry *collision_entry = entry; struct rb_node *node, *node_first, *node_last; if (!collision_entry) return -ENOENT; node = &(collision_entry->node); node_first = rb_first(&private->mem_rb); node_last = rb_last(&private->mem_rb); while (1) { /* * If top down search then next address to consider * is lower. The highest lower address possible is the * colliding entry address - the length of * allocation */ if (flag_top_down) { addr = collision_entry->memdesc.gpuaddr - len; /* Check for loopback */ if (addr > collision_entry->memdesc.gpuaddr || !addr) { *gpuaddr = KGSL_SVM_UPPER_BOUND; ret = -EAGAIN; break; } if (node == node_first) { collision_entry = NULL; } else { node = rb_prev(&collision_entry->node); collision_entry = container_of(node, struct kgsl_mem_entry, node); } } else { /* * Bottom up mode the next address to consider * is higher. The lowest higher address possible * colliding entry address + the size of the * colliding entry */ addr = collision_entry->memdesc.gpuaddr + kgsl_memdesc_mmapsize( &collision_entry->memdesc); /* overflow check */ if (addr < collision_entry->memdesc.gpuaddr || !mmap_range_valid(addr, len)) { *gpuaddr = KGSL_SVM_UPPER_BOUND; ret = -EAGAIN; break; } if (node == node_last) { collision_entry = NULL; } else { node = rb_next(&collision_entry->node); collision_entry = container_of(node, struct kgsl_mem_entry, node); } } if (!collision_entry || !kgsl_addr_range_overlap(addr, len, collision_entry->memdesc.gpuaddr, kgsl_memdesc_mmapsize(&collision_entry->memdesc))) { /* success */ *gpuaddr = addr; break; } } return ret; } /** * kgsl_check_gpu_addr_collision() - Check if an address range collides with * existing allocations of a process * @private: Pointer to process private * @entry: Memory entry of the memory for which address range is being * considered * @addr: Start address of the address range for which collision is checked * @len: Length of the address range * @gpumap_free_addr: The lowest address from where to look for a free address * range because addresses below this are known to conflict * @flag_top_down: Indicates whether to search for unmapped region in top down * or bottom mode * @align: The alignment requirement of the unmapped region * * Function checks if the given address range collides, and if collision * is found then it keeps incrementing the gpumap_free_addr until it finds * an address that does not collide. This suggested addr can be used by the * caller to check if it's acceptable. */ static int kgsl_check_gpu_addr_collision( struct kgsl_process_private *private, struct kgsl_mem_entry *entry, unsigned long addr, unsigned long len, unsigned long *gpumap_free_addr, bool flag_top_down, unsigned int align) { int ret = -EAGAIN; struct kgsl_mem_entry *collision_entry = NULL; spin_lock(&private->mem_lock); if (kgsl_sharedmem_region_empty(private, addr, len, &collision_entry)) { /* * We found a free memory map, claim it here with * memory lock held */ entry->memdesc.gpuaddr = addr; /* This should never fail */ ret = kgsl_mem_entry_track_gpuaddr(private, entry); spin_unlock(&private->mem_lock); BUG_ON(ret); /* map cannot be called with lock held */ ret = kgsl_mmu_map(private->pagetable, &entry->memdesc); if (ret) { spin_lock(&private->mem_lock); kgsl_mem_entry_untrack_gpuaddr(private, entry); spin_unlock(&private->mem_lock); } } else { trace_kgsl_mem_unmapped_area_collision(entry, addr, len, ret); if (!gpumap_free_addr) { spin_unlock(&private->mem_lock); return ret; } /* * When checking for a free gap make sure the gap is large * enough to accomodate alignment */ len += 1 << align; ret = __kgsl_check_collision(private, collision_entry, &addr, len, flag_top_down); if (!ret || -EAGAIN == ret) { *gpumap_free_addr = addr; ret = -EAGAIN; } spin_unlock(&private->mem_lock); } return ret; } static unsigned long kgsl_get_unmapped_area(struct file *file, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags) { unsigned long ret = 0, orig_len = len; unsigned long vma_offset = pgoff << PAGE_SHIFT; struct kgsl_device_private *dev_priv = file->private_data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_device *device = dev_priv->device; struct kgsl_mem_entry *entry = NULL; unsigned int align; unsigned int retry = 0; struct vm_area_struct *vma; int ret_val; unsigned long gpumap_free_addr = 0; bool flag_top_down = true; struct vm_unmapped_area_info info; if (vma_offset == device->memstore.gpuaddr) return get_unmapped_area(NULL, addr, len, pgoff, flags); ret = get_mmap_entry(private, &entry, pgoff, len); if (ret) return ret; ret = arch_mmap_check(addr, len, flags); if (ret) goto put; /* * If we're not going to use CPU map feature, get an ordinary mapping * with nothing more to be done. */ if (!kgsl_memdesc_use_cpu_map(&entry->memdesc)) { ret = get_unmapped_area(NULL, addr, len, pgoff, flags); goto put; } if (entry->memdesc.gpuaddr != 0) { KGSL_MEM_INFO(device, "pgoff %lx already mapped to gpuaddr %x\n", pgoff, entry->memdesc.gpuaddr); ret = -EBUSY; goto put; } /* special case handling for MAP_FIXED */ if (flags & MAP_FIXED) { if (!mmap_range_valid(addr, len)) { ret = -EFAULT; goto put; } ret = get_unmapped_area(NULL, addr, len, pgoff, flags); if (!ret || IS_ERR_VALUE(ret)) goto put; ret_val = kgsl_check_gpu_addr_collision(private, entry, addr, len, 0, 0, 0); if (ret_val) ret = ret_val; goto put; } align = kgsl_memdesc_get_align(&entry->memdesc); if (align >= ilog2(SZ_2M)) align = ilog2(SZ_2M); else if (align >= ilog2(SZ_1M)) align = ilog2(SZ_1M); else if (align >= ilog2(SZ_64K)) align = ilog2(SZ_64K); else if (align <= PAGE_SHIFT) align = 0; if (align) len += 1 << align; /* * first try to see if the suggested address is accepted by the * system map and our gpu map */ if (mmap_range_valid(addr, len)) { vma = find_vma(current->mm, addr); if (!vma || ((addr + len) <= vma->vm_start)) { if (align) ret = ALIGN(addr, (1 << align)); ret_val = kgsl_check_gpu_addr_collision(private, entry, ret, orig_len, NULL, 0, 0); if (!ret_val) { /* success */ goto put; } else if (((ret_val < 0) && (ret_val != -EAGAIN))) { ret = ret_val; goto put; } } } if (mmap_min_addr >= KGSL_SVM_UPPER_BOUND) return -ERANGE; addr = current->mm->mmap_base; info.length = orig_len; info.align_mask = ((1 << align) - 1); info.align_offset = 0; /* * Loop through the address space to find a address region agreeable to * both system map and gpu map */ while (1) { if (retry) { /* * try the bottom up approach if top down failed */ if (flag_top_down) { flag_top_down = false; addr = max_t(unsigned long, KGSL_SVM_LOWER_BOUND, mmap_min_addr); gpumap_free_addr = 0; ret = 0; retry = 0; continue; } /* * if we are aleady doing bootom up with * alignement then try w/o alignment */ if (align) { align = 0; flag_top_down = true; addr = current->mm->mmap_base; gpumap_free_addr = 0; len = orig_len; ret = 0; retry = 0; info.align_mask = 0; continue; } /* * Out of options future targets may have more address * bits, for now fail */ break; } if (gpumap_free_addr) addr = gpumap_free_addr; if (flag_top_down) { info.flags = VM_UNMAPPED_AREA_TOPDOWN; info.low_limit = max_t(unsigned long, KGSL_SVM_LOWER_BOUND, mmap_min_addr); info.high_limit = (addr > KGSL_SVM_UPPER_BOUND) ? KGSL_SVM_UPPER_BOUND : addr; } else { info.flags = 0; info.low_limit = addr; info.high_limit = KGSL_SVM_UPPER_BOUND; } ret = vm_unmapped_area(&info); if (ret == (unsigned long)-ENOMEM) { retry = 1; continue; } else if (!ret || (~PAGE_MASK & ret)) { ret = -EBUSY; retry = 1; continue; } else if (IS_ERR_VALUE(ret)) { break; } else { unsigned long temp = ret; ret = security_mmap_addr(ret); if (ret) { retry = 1; continue; } ret = temp; } /* make sure there isn't a GPU only mapping at this address */ ret_val = kgsl_check_gpu_addr_collision(private, entry, ret, orig_len, &gpumap_free_addr, flag_top_down, align); if (!ret_val) { /* success */ break; } else if ((ret_val < 0) && (ret_val != -EAGAIN)) { ret = ret_val; break; } /* * The addr hint can be set by userspace to be near * the end of the address space. Make sure we search * the whole address space at least once by wrapping * back around once. */ if (!mmap_range_valid(gpumap_free_addr, len)) { retry = 1; ret = -EBUSY; continue; } } put: if (IS_ERR_VALUE(ret)) KGSL_MEM_ERR(device, "pid %d pgoff %lx len %ld failed error %ld\n", private->pid, pgoff, len, ret); kgsl_mem_entry_put(entry); return ret; } static int kgsl_mmap(struct file *file, struct vm_area_struct *vma) { unsigned int ret, cache; unsigned long vma_offset = vma->vm_pgoff << PAGE_SHIFT; struct kgsl_device_private *dev_priv = file->private_data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; struct kgsl_device *device = dev_priv->device; /* Handle leagacy behavior for memstore */ if (vma_offset == device->memstore.gpuaddr) return kgsl_mmap_memstore(device, vma); /* * The reference count on the entry that we get from * get_mmap_entry() will be held until kgsl_gpumem_vm_close(). */ ret = get_mmap_entry(private, &entry, vma->vm_pgoff, vma->vm_end - vma->vm_start); if (ret) return ret; vma->vm_flags |= entry->memdesc.ops->vmflags; vma->vm_private_data = entry; /* Determine user-side caching policy */ cache = kgsl_memdesc_get_cachemode(&entry->memdesc); switch (cache) { case KGSL_CACHEMODE_UNCACHED: vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); break; case KGSL_CACHEMODE_WRITETHROUGH: vma->vm_page_prot = pgprot_writethroughcache(vma->vm_page_prot); if (vma->vm_page_prot == pgprot_writebackcache(vma->vm_page_prot)) WARN_ONCE(1, "WRITETHROUGH is deprecated for arm64"); break; case KGSL_CACHEMODE_WRITEBACK: vma->vm_page_prot = pgprot_writebackcache(vma->vm_page_prot); break; case KGSL_CACHEMODE_WRITECOMBINE: default: vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); break; } vma->vm_ops = &kgsl_gpumem_vm_ops; if (cache == KGSL_CACHEMODE_WRITEBACK || cache == KGSL_CACHEMODE_WRITETHROUGH) { struct scatterlist *s; int i; int sglen = entry->memdesc.sglen; unsigned long addr = vma->vm_start; for_each_sg(entry->memdesc.sg, s, sglen, i) { int j; for (j = 0; j < (s->length >> PAGE_SHIFT); j++) { struct page *page = sg_page(s); page = nth_page(page, j); vm_insert_page(vma, addr, page); addr += PAGE_SIZE; } } } vma->vm_file = file; entry->memdesc.useraddr = vma->vm_start; trace_kgsl_mem_mmap(entry); return 0; } static irqreturn_t kgsl_irq_handler(int irq, void *data) { struct kgsl_device *device = data; return device->ftbl->irq_handler(device); } static const struct file_operations kgsl_fops = { .owner = THIS_MODULE, .release = kgsl_release, .open = kgsl_open, .mmap = kgsl_mmap, .get_unmapped_area = kgsl_get_unmapped_area, .unlocked_ioctl = kgsl_ioctl, .compat_ioctl = kgsl_compat_ioctl, }; struct kgsl_driver kgsl_driver = { .process_mutex = __MUTEX_INITIALIZER(kgsl_driver.process_mutex), .ptlock = __SPIN_LOCK_UNLOCKED(kgsl_driver.ptlock), .devlock = __MUTEX_INITIALIZER(kgsl_driver.devlock), /* * Full cache flushes are faster than line by line on at least * 8064 and 8974 once the region to be flushed is > 16mb. */ .full_cache_threshold = SZ_16M, }; EXPORT_SYMBOL(kgsl_driver); static void _unregister_device(struct kgsl_device *device) { int minor; mutex_lock(&kgsl_driver.devlock); for (minor = 0; minor < KGSL_DEVICE_MAX; minor++) { if (device == kgsl_driver.devp[minor]) break; } if (minor != KGSL_DEVICE_MAX) { device_destroy(kgsl_driver.class, MKDEV(MAJOR(kgsl_driver.major), minor)); kgsl_driver.devp[minor] = NULL; } mutex_unlock(&kgsl_driver.devlock); } static int _register_device(struct kgsl_device *device) { int minor, ret; dev_t dev; /* Find a minor for the device */ mutex_lock(&kgsl_driver.devlock); for (minor = 0; minor < KGSL_DEVICE_MAX; minor++) { if (kgsl_driver.devp[minor] == NULL) { kgsl_driver.devp[minor] = device; break; } } mutex_unlock(&kgsl_driver.devlock); if (minor == KGSL_DEVICE_MAX) { KGSL_CORE_ERR("minor devices exhausted\n"); return -ENODEV; } /* Create the device */ dev = MKDEV(MAJOR(kgsl_driver.major), minor); device->dev = device_create(kgsl_driver.class, &device->pdev->dev, dev, device, device->name); if (IS_ERR(device->dev)) { mutex_lock(&kgsl_driver.devlock); kgsl_driver.devp[minor] = NULL; mutex_unlock(&kgsl_driver.devlock); ret = PTR_ERR(device->dev); KGSL_CORE_ERR("device_create(%s): %d\n", device->name, ret); return ret; } dev_set_drvdata(&device->pdev->dev, device); return 0; } int kgsl_device_platform_probe(struct kgsl_device *device) { int result; int status = -EINVAL; struct resource *res; status = _register_device(device); if (status) return status; /* Initialize logging first, so that failures below actually print. */ kgsl_device_debugfs_init(device); status = kgsl_pwrctrl_init(device); if (status) goto error; /* Get starting physical address of device registers */ res = platform_get_resource_byname(device->pdev, IORESOURCE_MEM, device->iomemname); if (res == NULL) { KGSL_DRV_ERR(device, "platform_get_resource_byname failed\n"); status = -EINVAL; goto error_pwrctrl_close; } if (res->start == 0 || resource_size(res) == 0) { KGSL_DRV_ERR(device, "dev %d invalid register region\n", device->id); status = -EINVAL; goto error_pwrctrl_close; } device->reg_phys = res->start; device->reg_len = resource_size(res); /* * Check if a shadermemname is defined, and then get shader memory * details including shader memory starting physical address * and shader memory length */ if (device->shadermemname != NULL) { res = platform_get_resource_byname(device->pdev, IORESOURCE_MEM, device->shadermemname); if (res == NULL) { KGSL_DRV_WARN(device, "Shader memory: platform_get_resource_byname failed\n"); } else { device->shader_mem_phys = res->start; device->shader_mem_len = resource_size(res); } if (!devm_request_mem_region(device->dev, device->shader_mem_phys, device->shader_mem_len, device->name)) { KGSL_DRV_WARN(device, "request_mem_region_failed\n"); } } if (!devm_request_mem_region(device->dev, device->reg_phys, device->reg_len, device->name)) { KGSL_DRV_ERR(device, "request_mem_region failed\n"); status = -ENODEV; goto error_pwrctrl_close; } device->reg_virt = devm_ioremap(device->dev, device->reg_phys, device->reg_len); if (device->reg_virt == NULL) { KGSL_DRV_ERR(device, "ioremap failed\n"); status = -ENODEV; goto error_pwrctrl_close; } /*acquire interrupt */ device->pwrctrl.interrupt_num = platform_get_irq_byname(device->pdev, device->pwrctrl.irq_name); if (device->pwrctrl.interrupt_num <= 0) { KGSL_DRV_ERR(device, "platform_get_irq_byname failed: %d\n", device->pwrctrl.interrupt_num); status = -EINVAL; goto error_pwrctrl_close; } status = devm_request_irq(device->dev, device->pwrctrl.interrupt_num, kgsl_irq_handler, IRQF_TRIGGER_HIGH, device->name, device); if (status) { KGSL_DRV_ERR(device, "request_irq(%d) failed: %d\n", device->pwrctrl.interrupt_num, status); goto error_pwrctrl_close; } disable_irq(device->pwrctrl.interrupt_num); KGSL_DRV_INFO(device, "dev_id %d regs phys 0x%08lx size 0x%08x virt %p\n", device->id, device->reg_phys, device->reg_len, device->reg_virt); rwlock_init(&device->context_lock); result = kgsl_drm_init(device->pdev); if (result) goto error_pwrctrl_close; setup_timer(&device->idle_timer, kgsl_timer, (unsigned long) device); status = kgsl_create_device_workqueue(device); if (status) goto error_pwrctrl_close; status = kgsl_mmu_init(device); if (status != 0) { KGSL_DRV_ERR(device, "kgsl_mmu_init failed %d\n", status); goto error_dest_work_q; } /* Check to see if our device can perform DMA correctly */ status = dma_set_coherent_mask(&device->pdev->dev, KGSL_DMA_BIT_MASK); if (status) goto error_close_mmu; status = kgsl_allocate_global(device, &device->memstore, KGSL_MEMSTORE_SIZE, 0, 0); if (status != 0) { KGSL_DRV_ERR(device, "kgsl_allocate_global failed %d\n", status); goto error_close_mmu; } /* * The default request type PM_QOS_REQ_ALL_CORES is * applicable to all CPU cores that are online and * would have a power impact when there are more * number of CPUs. PM_QOS_REQ_AFFINE_IRQ request * type shall update/apply the vote only to that CPU to * which IRQ's affinity is set to. */ #ifdef CONFIG_SMP device->pwrctrl.pm_qos_req_dma.type = PM_QOS_REQ_AFFINE_IRQ; device->pwrctrl.pm_qos_req_dma.irq = device->pwrctrl.interrupt_num; #endif pm_qos_add_request(&device->pwrctrl.pm_qos_req_dma, PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE); device->events_wq = create_workqueue("kgsl-events"); /* Initalize the snapshot engine */ kgsl_device_snapshot_init(device); /* Initialize common sysfs entries */ kgsl_pwrctrl_init_sysfs(device); dev_info(device->dev, "Initialized %s: mmu=%s\n", device->name, kgsl_mmu_enabled() ? "on" : "off"); return 0; error_close_mmu: kgsl_mmu_close(device); error_dest_work_q: destroy_workqueue(device->work_queue); device->work_queue = NULL; error_pwrctrl_close: kgsl_pwrctrl_close(device); error: _unregister_device(device); return status; } EXPORT_SYMBOL(kgsl_device_platform_probe); void kgsl_device_platform_remove(struct kgsl_device *device) { destroy_workqueue(device->events_wq); kgsl_device_snapshot_close(device); kgsl_pwrctrl_uninit_sysfs(device); pm_qos_remove_request(&device->pwrctrl.pm_qos_req_dma); idr_destroy(&device->context_idr); kgsl_free_global(&device->memstore); kgsl_mmu_close(device); if (device->work_queue) { destroy_workqueue(device->work_queue); device->work_queue = NULL; } kgsl_pwrctrl_close(device); _unregister_device(device); } EXPORT_SYMBOL(kgsl_device_platform_remove); static void kgsl_core_exit(void) { kgsl_events_exit(); kgsl_drm_exit(); kgsl_cffdump_destroy(); kgsl_core_debugfs_close(); /* * We call kgsl_sharedmem_uninit_sysfs() and device_unregister() * only if kgsl_driver.virtdev has been populated. * We check at least one member of kgsl_driver.virtdev to * see if it is not NULL (and thus, has been populated). */ if (kgsl_driver.virtdev.class) { kgsl_sharedmem_uninit_sysfs(); device_unregister(&kgsl_driver.virtdev); } if (kgsl_driver.class) { class_destroy(kgsl_driver.class); kgsl_driver.class = NULL; } /* free the memobject cache */ if (memobjs_cache) kmem_cache_destroy(memobjs_cache); kgsl_memfree_exit(); unregister_chrdev_region(kgsl_driver.major, KGSL_DEVICE_MAX); } static int __init kgsl_core_init(void) { int result = 0; /* alloc major and minor device numbers */ result = alloc_chrdev_region(&kgsl_driver.major, 0, KGSL_DEVICE_MAX, "kgsl"); if (result < 0) { KGSL_CORE_ERR("alloc_chrdev_region failed err = %d\n", result); goto err; } cdev_init(&kgsl_driver.cdev, &kgsl_fops); kgsl_driver.cdev.owner = THIS_MODULE; kgsl_driver.cdev.ops = &kgsl_fops; result = cdev_add(&kgsl_driver.cdev, MKDEV(MAJOR(kgsl_driver.major), 0), KGSL_DEVICE_MAX); if (result) { KGSL_CORE_ERR("kgsl: cdev_add() failed, dev_num= %d," " result= %d\n", kgsl_driver.major, result); goto err; } kgsl_driver.class = class_create(THIS_MODULE, "kgsl"); if (IS_ERR(kgsl_driver.class)) { result = PTR_ERR(kgsl_driver.class); KGSL_CORE_ERR("failed to create class for kgsl"); goto err; } /* Make a virtual device for managing core related things in sysfs */ kgsl_driver.virtdev.class = kgsl_driver.class; dev_set_name(&kgsl_driver.virtdev, "kgsl"); result = device_register(&kgsl_driver.virtdev); if (result) { KGSL_CORE_ERR("driver_register failed\n"); goto err; } /* Make kobjects in the virtual device for storing statistics */ kgsl_driver.ptkobj = kobject_create_and_add("pagetables", &kgsl_driver.virtdev.kobj); kgsl_driver.prockobj = kobject_create_and_add("proc", &kgsl_driver.virtdev.kobj); kgsl_core_debugfs_init(); kgsl_sharedmem_init_sysfs(); kgsl_cffdump_init(); INIT_LIST_HEAD(&kgsl_driver.process_list); INIT_LIST_HEAD(&kgsl_driver.pagetable_list); kgsl_mmu_set_mmutype(ksgl_mmu_type); kgsl_events_init(); /* create the memobjs kmem cache */ memobjs_cache = KMEM_CACHE(kgsl_memobj_node, 0); if (memobjs_cache == NULL) { KGSL_CORE_ERR("failed to create memobjs_cache"); result = -ENOMEM; goto err; } kgsl_memfree_init(); return 0; err: kgsl_core_exit(); return result; } module_init(kgsl_core_init); module_exit(kgsl_core_exit); MODULE_AUTHOR("Qualcomm Innovation Center, Inc."); MODULE_DESCRIPTION("MSM GPU driver"); MODULE_LICENSE("GPL");
MoKee/android_kernel_lge_msm8992
drivers/gpu/msm/kgsl.c
C
gpl-2.0
127,230
#Makefile for CIB CAPI2 sources #EXTRA_CFLAGS := -Werror EXTRA_CFLAGS += -DUNDER_LINUX EXTRA_CFLAGS += -DSTACK_wedge obj-$(CONFIG_BRCM_FUSE_RIL_CIB) += \ capi2/cc/ \ capi2/gen/ \ capi2/lcs/ \ capi2/msc/ \ capi2/pch/ \ capi2/phonebk/ \ capi2/sim/ \ capi2/sms/ \ capi2/ss/ \ capi2/test/ \ sysinterface/sysrpc/ \
WinKarbik/android_kernel_samsung_amazing
modules/drivers/char/brcm/fuse_ril/CAPI2_CIB/Makefile
Makefile
gpl-2.0
506
// PR c++/70507 - integer overflow builtins not constant expressions // { dg-do compile { target c++11 } } #define SCHAR_MAX __SCHAR_MAX__ #define SHRT_MAX __SHRT_MAX__ #define INT_MAX __INT_MAX__ #define LONG_MAX __LONG_MAX__ #define LLONG_MAX __LONG_LONG_MAX__ #define SCHAR_MIN (-__SCHAR_MAX__ - 1) #define SHRT_MIN (-__SHRT_MAX__ - 1) #define INT_MIN (-__INT_MAX__ - 1) #define LONG_MIN (-__LONG_MAX__ - 1) #define LLONG_MIN (-__LONG_LONG_MAX__ - 1) #define UCHAR_MAX (SCHAR_MAX * 2U + 1) #define USHRT_MAX (SHRT_MAX * 2U + 1) #define UINT_MAX (INT_MAX * 2U + 1) #define ULONG_MAX (LONG_MAX * 2LU + 1) #define ULLONG_MAX (LLONG_MAX * 2LLU + 1) #define USCHAR_MIN (-__USCHAR_MAX__ - 1) #define USHRT_MIN (-__USHRT_MAX__ - 1) #define UINT_MIN (-__UINT_MAX__ - 1) #define ULONG_MIN (-__ULONG_MAX__ - 1) #define ULLONG_MIN (-__ULONG_LONG_MAX__ - 1) #define Assert(expr) static_assert ((expr), #expr) template <class T> constexpr T add (T x, T y, T z = T ()) { return __builtin_add_overflow (x, y, &z) ? 0 : z; } template <class T> constexpr T sub (T x, T y, T z = T ()) { return __builtin_sub_overflow (x, y, &z) ? 0 : z; } template <class T> constexpr T mul (T x, T y, T z = T ()) { return __builtin_mul_overflow (x, y, &z) ? 0 : z; } #define TEST_ADD(T, x, y, z) Assert (z == add<T>(x, y)) #define TEST_SUB(T, x, y, z) Assert (z == sub<T>(x, y)) #define TEST_MUL(T, x, y, z) Assert (z == mul<T>(x, y)) TEST_ADD (signed char, 0, 0, 0); TEST_ADD (signed char, 0, SCHAR_MAX, SCHAR_MAX); TEST_ADD (signed char, 1, SCHAR_MAX, 0); // overflow TEST_ADD (signed char, SCHAR_MAX, SCHAR_MAX, 0); // overflow TEST_ADD (signed char, 0, SCHAR_MIN, SCHAR_MIN); TEST_ADD (signed char, -1, SCHAR_MIN, 0); // overflow TEST_ADD (short, 0, 0, 0); TEST_ADD (short, 0, SHRT_MAX, SHRT_MAX); TEST_ADD (short, 1, SHRT_MAX, 0); // overflow TEST_ADD (short, SHRT_MAX, SHRT_MAX, 0); // overflow TEST_ADD (short, 0, SHRT_MIN, SHRT_MIN); TEST_ADD (short, -1, SHRT_MIN, 0); // overflow TEST_ADD (short, SHRT_MIN, SHRT_MIN, 0); // overflow TEST_ADD (int, 0, 0, 0); TEST_ADD (int, 0, INT_MAX, INT_MAX); TEST_ADD (int, 1, INT_MAX, 0); // overflow TEST_ADD (int, INT_MAX, INT_MAX, 0); // overflow TEST_ADD (int, 0, INT_MIN, INT_MIN); TEST_ADD (int, -1, INT_MIN, 0); // overflow TEST_ADD (int, INT_MIN, INT_MIN, 0); // overflow TEST_ADD (long, 0, 0, 0); TEST_ADD (long, 0, LONG_MAX, LONG_MAX); TEST_ADD (long, 1, LONG_MAX, 0); // overflow TEST_ADD (long, LONG_MAX, LONG_MAX, 0); // overflow TEST_ADD (long, 0, LONG_MIN, LONG_MIN); TEST_ADD (long, -1, LONG_MIN, 0); // overflow TEST_ADD (long, LONG_MIN, LONG_MIN, 0); // overflow TEST_ADD (long long, 0, 0, 0); TEST_ADD (long long, 0, LLONG_MAX, LLONG_MAX); TEST_ADD (long long, 1, LLONG_MAX, 0); // overflow TEST_ADD (long long, LLONG_MAX, LLONG_MAX, 0); // overflow TEST_ADD (long long, 0, LLONG_MIN, LLONG_MIN); TEST_ADD (long long, -1, LLONG_MIN, 0); // overflow TEST_ADD (long long, LLONG_MIN, LLONG_MIN, 0); // overflow TEST_ADD (unsigned char, 0, 0, 0); TEST_ADD (unsigned char, 0, UCHAR_MAX, UCHAR_MAX); TEST_ADD (unsigned char, 1, UCHAR_MAX, 0); // overflow TEST_ADD (unsigned char, UCHAR_MAX, UCHAR_MAX, 0); // overflow TEST_ADD (unsigned short, 0, 0, 0); TEST_ADD (unsigned short, 0, USHRT_MAX, USHRT_MAX); TEST_ADD (unsigned short, 1, USHRT_MAX, 0); // overflow TEST_ADD (unsigned short, USHRT_MAX, USHRT_MAX, 0); // overflow TEST_ADD (unsigned, 0, 0, 0); TEST_ADD (unsigned, 0, UINT_MAX, UINT_MAX); TEST_ADD (unsigned, 1, UINT_MAX, 0); // overflow TEST_ADD (unsigned, UINT_MAX, UINT_MAX, 0); // overflow TEST_ADD (unsigned long, 0, 0, 0); TEST_ADD (unsigned long, 0, ULONG_MAX, ULONG_MAX); TEST_ADD (unsigned long, 1, ULONG_MAX, 0); // overflow TEST_ADD (unsigned long, ULONG_MAX, ULONG_MAX, 0); // overflow TEST_ADD (unsigned long long, 0, 0, 0); TEST_ADD (unsigned long long, 0, ULLONG_MAX, ULLONG_MAX); TEST_ADD (unsigned long long, 1, ULLONG_MAX, 0); // overflow TEST_ADD (unsigned long long, ULLONG_MAX, ULLONG_MAX, 0); // overflow // Make sure the built-ins are accepted in the following contexts // where constant expressions are required and that they return // the expected overflow value. namespace Enum { enum Add { a0 = __builtin_add_overflow_p ( 1, 1, 0), a1 = __builtin_add_overflow_p (INT_MAX, 1, 0) }; Assert (a0 == 0); Assert (a1 == 1); enum Sub { s0 = __builtin_sub_overflow_p ( 1, 1, 0), s1 = __builtin_sub_overflow_p (INT_MIN, 1, 0) }; Assert (s0 == 0); Assert (s1 == 1); enum Mul { m0 = __builtin_add_overflow_p ( 1, 1, 0), m1 = __builtin_add_overflow_p (INT_MAX, INT_MAX, 0) }; Assert (m0 == 0); Assert (m1 == 1); } // namespace Enum namespace TemplateArg { template <class T, class U, class V, T x, U y, bool v, bool z = __builtin_add_overflow_p (x, y, V ())> struct Add { Assert (z == v); }; template <class T, class U, class V, T x, U y, bool v, bool z = __builtin_sub_overflow_p (x, y, V ())> struct Sub { Assert (z == v); }; template <class T, class U, class V, T x, U y, bool v, bool z = __builtin_mul_overflow_p (x, y, V ())> struct Mul { Assert (z == v); }; template struct Add<int, int, int, 1, 1, false>; template struct Add<int, int, int, 1, INT_MAX, true>; template struct Sub<int, int, int, 1, 1, false>; template struct Sub<int, int, int, -2, INT_MAX, true>; template struct Mul<int, int, int, 1, 1, false>; template struct Mul<int, int, int, 2, INT_MAX / 2 + 1, true>; } // namespace TemplateArg #if __cplusplus >= 201402L namespace Initializer { struct Result { int res; bool vflow; }; constexpr Result add_vflow (int a, int b) { #if 1 Result res = { a + b, __builtin_add_overflow_p (a, b, int ()) }; #else // The following fails to compile because of c++/71391 - error // on aggregate initialization with side-effects in a constexpr // function int c = 0; Result res = { 0, __builtin_add_overflow (a, b, &c) }; res.c = c; #endif return res; } constexpr Result sum = add_vflow (123, 456); Assert (sum.res == 123 + 456); Assert (!sum.vflow); } // namespace Initializer #endif // __cplusplus >= 201402L
mickael-guene/gcc
gcc/testsuite/g++.dg/cpp0x/constexpr-arith-overflow.C
C++
gpl-2.0
7,125
(function ($) { /*jslint undef: false, browser: true, devel: false, eqeqeq: false, bitwise: false, white: false, plusplus: false, regexp: false, nomen: false */ /*global jQuery,setTimeout,projekktor,location,setInterval,YT,clearInterval,pixelentity */ $.pixelentity = $.pixelentity || {version: '1.0.0'}; $.pixelentity.influxSlider = { conf: { api: false, delay: 3000, fade: false, pause: true } }; function PeInfluxSlider(target, conf) { var self = this; var jthis = $(this); var slides = []; var timer; var slider; var index=0; var master; var haveLinks = false; var locked = true; var paused = false; var enabled = true; var links; var nav = ""; function start() { target.bind("enable.pixelentity ",enable); target.bind("disable.pixelentity ",disable); target.addClass("peActiveWidget"); target.children().each(parseSlide); if (slides.length > 0) { addNavigation(); init(); if (conf.pause) { target.bind("mouseenter mouseleave",evHandler); } } } function parseSlide(idx) { var link = false,img = false,parent; var el = $(this); nav += '<li><a id="'+idx+'" href="#">btn</a></li>'; if (this.tagName.toLowerCase() == "img") { img = el; } else { if (el.attr("href")) { img = el.find("img:eq(0)"); if (img.length > 0) { link = el; //link.replaceWith(img); link.before(img); link.css("position","absolute").css("z-index",100).css("display","block").hide(); if ($.browser.msie && $.browser.version < 9) { link.css("opacity",0).css("background-color","black"); } target.prepend(link); haveLinks = true; } } } if (img.length > 0) { slides.push({ image: img, link: link }); if (idx > 0) { img.detach(); } } } function addNavigation() { nav = '<ul class="sliderNav">'+nav+'</ul>'; target.before(nav); nav = target.parent().find(".sliderNav a"); nav.click(evHandler); } function evHandler(e) { if (enabled) { switch (e.type) { case "click": if (!locked) { rotate(parseInt(e.currentTarget.id,10)); timer.reset(); //timer.start(conf.delay); } break; case "mouseenter": case "mouseleave": paused = (e.type == "mouseenter"); timer[paused ? "pause" : "resume"](); break; } } return e.type == "click" ? false : true; } // used to disable timer function noop() { } function init() { links = target.find("a"); slider = slides[0].image.peTransitionHilight({api:true,boost:1,fallback:conf.fade,disabled:true}); slider.bind("ready.pixelentity change.pixelentity",next); timer = conf.delay > 0 ? new $.pixelentity.Timer(rotate) : { start: noop, pause: noop, resume: noop }; } function next(e) { if (e.type == "ready") { if (haveLinks) { links.width(slider.width()).height(slider.height()); } setLink(); } timer.start(conf.delay); if (paused || !enabled) { timer.pause(); } locked = false; } function setLink() { if (haveLinks) { links.hide(); if (slides[index].link) { slides[index].link.show(); } } nav.removeClass("selected").eq(index).addClass("selected").end(); } function rotate(idx) { locked = true; index = idx >=0 ? idx : (index + 1) % slides.length; slider.load(slides[index].image); setLink(index); } function enable() { if (!enabled) { enabled = true; slider.enable(); timer.resume(); } } function disable() { if (enabled) { enabled = false; slider.disable(); timer.pause(); } } $.extend(self, { bind: function(ev,handler) { jthis.bind(ev,handler); }, one: function(ev,handler) { jthis.one(ev,handler); }, enable: enable, disable: disable, destroy: function() { if (jthis) { jthis.remove(); } jthis = self = undefined; target.data("peInfluxSlider", null); target = undefined; } }); start(); } // jQuery plugin implementation $.fn.peInfluxSlider = function(conf) { // return existing instance var api = this.data("peInfluxSlider"); if (api) { return api; } conf = $.extend(true, {}, $.pixelentity.influxSlider.conf, conf); // install peScroll for each entry in jQuery object this.each(function() { api = new PeInfluxSlider($(this), conf); $(this).data("peInfluxSlider", api); }); return conf.api ? api: this; }; }(jQuery));
Melanie27/oakwoodww-staging
wp-content/themes/visia/framework/js/pe/jquery.pixelentity.influxSlider.js
JavaScript
gpl-2.0
4,624
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_ATMOSPHERE_CUSONDE_HPP #define XCSOAR_ATMOSPHERE_CUSONDE_HPP #include "Atmosphere/Temperature.hpp" struct NMEAInfo; struct DerivedInfo; /** * Namespaces that provides simple estimates of thermal heights from lapse rates * derived from temperature trace obtained during flight. */ class CuSonde { public: /** Meters between levels */ static constexpr unsigned HEIGHT_STEP = 100; /** Number of levels */ static constexpr unsigned NUM_LEVELS = 100; struct Level { /** Environmental temperature in K */ Temperature air_temperature; /** DewPoint in K */ Temperature dewpoint; /** Dry temperature in K */ Temperature dry_temperature; /** ThermalIndex in K */ Temperature thermal_index; void UpdateTemps(bool humidity_valid, double humidity, Temperature temperature); void UpdateThermalIndex(double h_agl, Temperature max_ground_temperature); /** Has any data */ bool has_data; /** Has dewpoint data */ bool has_dewpoint; /** Estimated ThermalHeight with data of this level */ double thermal_height; /** Estimated CloudBase with data of this level */ double cloud_base; bool empty() const { return !has_data; } bool dewpoint_empty() const { return !has_dewpoint; } void Reset() { has_data = false; has_dewpoint = false; } }; /** Expected temperature maximum on the ground */ Temperature max_ground_temperature; /** Height of ground above MSL */ double ground_height; unsigned short last_level; Level cslevels[NUM_LEVELS]; /** Estimated ThermailHeight */ double thermal_height; /** Estimated CloudBase */ double cloud_base; void Reset(); void UpdateMeasurements(const NMEAInfo &basic, const DerivedInfo &calculated); void FindCloudBase(unsigned short level); void FindThermalHeight(unsigned short level); void SetForecastTemperature(Temperature temperature); }; #endif
matthewturnbull/xcsoar
src/Atmosphere/CuSonde.hpp
C++
gpl-2.0
2,856
/* * Adaptec AAC series RAID controller driver * (c) Copyright 2001 Red Hat Inc. <alan@redhat.com> * * based on the old aacraid driver that is.. * Adaptec aacraid device driver for Linux. * Copyright (c) 2000 Adaptec, Inc. (aacraid@adaptec.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/types.h> #include <linux/sched.h> #include <linux/pci.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <linux/completion.h> #include <asm/semaphore.h> #include <asm/uaccess.h> #define MAJOR_NR SCSI_DISK0_MAJOR /* For DEVICE_NR() */ #include <linux/blk.h> #include "scsi.h" #include "hosts.h" #include "sd.h" #include "aacraid.h" /* SCSI Commands */ /* TODO: dmb - use the ones defined in include/scsi/scsi.h */ #define SS_TEST 0x00 /* Test unit ready */ #define SS_REZERO 0x01 /* Rezero unit */ #define SS_REQSEN 0x03 /* Request Sense */ #define SS_REASGN 0x07 /* Reassign blocks */ #define SS_READ 0x08 /* Read 6 */ #define SS_WRITE 0x0A /* Write 6 */ #define SS_INQUIR 0x12 /* inquiry */ #define SS_ST_SP 0x1B /* Start/Stop unit */ #define SS_LOCK 0x1E /* prevent/allow medium removal */ #define SS_RESERV 0x16 /* Reserve */ #define SS_RELES 0x17 /* Release */ #define SS_MODESEN 0x1A /* Mode Sense 6 */ #define SS_RDCAP 0x25 /* Read Capacity */ #define SM_READ 0x28 /* Read 10 */ #define SM_WRITE 0x2A /* Write 10 */ #define SS_SEEK 0x2B /* Seek */ /* values for inqd_pdt: Peripheral device type in plain English */ #define INQD_PDT_DA 0x00 /* Direct-access (DISK) device */ #define INQD_PDT_PROC 0x03 /* Processor device */ #define INQD_PDT_CHNGR 0x08 /* Changer (jukebox, scsi2) */ #define INQD_PDT_COMM 0x09 /* Communication device (scsi2) */ #define INQD_PDT_NOLUN2 0x1f /* Unknown Device (scsi2) */ #define INQD_PDT_NOLUN 0x7f /* Logical Unit Not Present */ #define INQD_PDT_DMASK 0x1F /* Peripheral Device Type Mask */ #define INQD_PDT_QMASK 0xE0 /* Peripheral Device Qualifer Mask */ #define TARGET_LUN_TO_CONTAINER(target, lun) (target) #define CONTAINER_TO_TARGET(cont) ((cont)) #define CONTAINER_TO_LUN(cont) (0) #define MAX_FIB_DATA (sizeof(struct hw_fib) - sizeof(FIB_HEADER)) #define MAX_DRIVER_SG_SEGMENT_COUNT 17 /* * Sense keys */ #define SENKEY_NO_SENSE 0x00 #define SENKEY_UNDEFINED 0x01 #define SENKEY_NOT_READY 0x02 #define SENKEY_MEDIUM_ERR 0x03 #define SENKEY_HW_ERR 0x04 #define SENKEY_ILLEGAL 0x05 #define SENKEY_ATTENTION 0x06 #define SENKEY_PROTECTED 0x07 #define SENKEY_BLANK 0x08 #define SENKEY_V_UNIQUE 0x09 #define SENKEY_CPY_ABORT 0x0A #define SENKEY_ABORT 0x0B #define SENKEY_EQUAL 0x0C #define SENKEY_VOL_OVERFLOW 0x0D #define SENKEY_MISCOMP 0x0E #define SENKEY_RESERVED 0x0F /* * Sense codes */ #define SENCODE_NO_SENSE 0x00 #define SENCODE_END_OF_DATA 0x00 #define SENCODE_BECOMING_READY 0x04 #define SENCODE_INIT_CMD_REQUIRED 0x04 #define SENCODE_PARAM_LIST_LENGTH_ERROR 0x1A #define SENCODE_INVALID_COMMAND 0x20 #define SENCODE_LBA_OUT_OF_RANGE 0x21 #define SENCODE_INVALID_CDB_FIELD 0x24 #define SENCODE_LUN_NOT_SUPPORTED 0x25 #define SENCODE_INVALID_PARAM_FIELD 0x26 #define SENCODE_PARAM_NOT_SUPPORTED 0x26 #define SENCODE_PARAM_VALUE_INVALID 0x26 #define SENCODE_RESET_OCCURRED 0x29 #define SENCODE_LUN_NOT_SELF_CONFIGURED_YET 0x3E #define SENCODE_INQUIRY_DATA_CHANGED 0x3F #define SENCODE_SAVING_PARAMS_NOT_SUPPORTED 0x39 #define SENCODE_DIAGNOSTIC_FAILURE 0x40 #define SENCODE_INTERNAL_TARGET_FAILURE 0x44 #define SENCODE_INVALID_MESSAGE_ERROR 0x49 #define SENCODE_LUN_FAILED_SELF_CONFIG 0x4c #define SENCODE_OVERLAPPED_COMMAND 0x4E /* * Additional sense codes */ #define ASENCODE_NO_SENSE 0x00 #define ASENCODE_END_OF_DATA 0x05 #define ASENCODE_BECOMING_READY 0x01 #define ASENCODE_INIT_CMD_REQUIRED 0x02 #define ASENCODE_PARAM_LIST_LENGTH_ERROR 0x00 #define ASENCODE_INVALID_COMMAND 0x00 #define ASENCODE_LBA_OUT_OF_RANGE 0x00 #define ASENCODE_INVALID_CDB_FIELD 0x00 #define ASENCODE_LUN_NOT_SUPPORTED 0x00 #define ASENCODE_INVALID_PARAM_FIELD 0x00 #define ASENCODE_PARAM_NOT_SUPPORTED 0x01 #define ASENCODE_PARAM_VALUE_INVALID 0x02 #define ASENCODE_RESET_OCCURRED 0x00 #define ASENCODE_LUN_NOT_SELF_CONFIGURED_YET 0x00 #define ASENCODE_INQUIRY_DATA_CHANGED 0x03 #define ASENCODE_SAVING_PARAMS_NOT_SUPPORTED 0x00 #define ASENCODE_DIAGNOSTIC_FAILURE 0x80 #define ASENCODE_INTERNAL_TARGET_FAILURE 0x00 #define ASENCODE_INVALID_MESSAGE_ERROR 0x00 #define ASENCODE_LUN_FAILED_SELF_CONFIG 0x00 #define ASENCODE_OVERLAPPED_COMMAND 0x00 #define BYTE0(x) (unsigned char)(x) #define BYTE1(x) (unsigned char)((x) >> 8) #define BYTE2(x) (unsigned char)((x) >> 16) #define BYTE3(x) (unsigned char)((x) >> 24) /*------------------------------------------------------------------------------ * S T R U C T S / T Y P E D E F S *----------------------------------------------------------------------------*/ /* SCSI inquiry data */ struct inquiry_data { u8 inqd_pdt; /* Peripheral qualifier | Peripheral Device Type */ u8 inqd_dtq; /* RMB | Device Type Qualifier */ u8 inqd_ver; /* ISO version | ECMA version | ANSI-approved version */ u8 inqd_rdf; /* AENC | TrmIOP | Response data format */ u8 inqd_len; /* Additional length (n-4) */ u8 inqd_pad1[2]; /* Reserved - must be zero */ u8 inqd_pad2; /* RelAdr | WBus32 | WBus16 | Sync | Linked |Reserved| CmdQue | SftRe */ u8 inqd_vid[8]; /* Vendor ID */ u8 inqd_pid[16]; /* Product ID */ u8 inqd_prl[4]; /* Product Revision Level */ }; struct sense_data { u8 error_code; /* 70h (current errors), 71h(deferred errors) */ u8 valid:1; /* A valid bit of one indicates that the information */ /* field contains valid information as defined in the * SCSI-2 Standard. */ u8 segment_number; /* Only used for COPY, COMPARE, or COPY AND VERIFY Commands */ u8 sense_key:4; /* Sense Key */ u8 reserved:1; u8 ILI:1; /* Incorrect Length Indicator */ u8 EOM:1; /* End Of Medium - reserved for random access devices */ u8 filemark:1; /* Filemark - reserved for random access devices */ u8 information[4]; /* for direct-access devices, contains the unsigned * logical block address or residue associated with * the sense key */ u8 add_sense_len; /* number of additional sense bytes to follow this field */ u8 cmnd_info[4]; /* not used */ u8 ASC; /* Additional Sense Code */ u8 ASCQ; /* Additional Sense Code Qualifier */ u8 FRUC; /* Field Replaceable Unit Code - not used */ u8 bit_ptr:3; /* indicates which byte of the CDB or parameter data * was in error */ u8 BPV:1; /* bit pointer valid (BPV): 1- indicates that * the bit_ptr field has valid value */ u8 reserved2:2; u8 CD:1; /* command data bit: 1- illegal parameter in CDB. * 0- illegal parameter in data. */ u8 SKSV:1; u8 field_ptr[2]; /* byte of the CDB or parameter data in error */ }; /* * M O D U L E G L O B A L S */ static struct fsa_scsi_hba *fsa_dev[MAXIMUM_NUM_ADAPTERS]; /* SCSI Device Instance Pointers */ static struct sense_data sense_data[MAXIMUM_NUM_CONTAINERS]; static void get_sd_devname(int disknum, char *buffer); static unsigned long aac_build_sg(Scsi_Cmnd* scsicmd, struct sgmap* sgmap); static unsigned long aac_build_sg64(Scsi_Cmnd* scsicmd, struct sgmap64* psg); static int aac_send_srb_fib(Scsi_Cmnd* scsicmd); static char *aac_get_status_string(u32 status); /* * Non dasd selection is handled entirely in aachba now */ MODULE_PARM(nondasd, "i"); MODULE_PARM_DESC(nondasd, "Control scanning of hba for nondasd devices. 0=off, 1=on"); MODULE_PARM(paemode, "i"); MODULE_PARM_DESC(paemode, "Control whether dma addressing is using PAE. 0=off, 1=on"); static int nondasd = -1; static int paemode = -1; /** * aac_get_containers - list containers * @common: adapter to probe * * Make a list of all containers on this controller */ int aac_get_containers(struct aac_dev *dev) { struct fsa_scsi_hba *fsa_dev_ptr; u32 index; int status = 0; struct aac_query_mount *dinfo; struct aac_mount *dresp; struct fib * fibptr; unsigned instance; fsa_dev_ptr = &(dev->fsa_dev); instance = dev->scsi_host_ptr->unique_id; if (!(fibptr = fib_alloc(dev))) return -ENOMEM; for (index = 0; index < MAXIMUM_NUM_CONTAINERS; index++) { fib_init(fibptr); dinfo = (struct aac_query_mount *) fib_data(fibptr); dinfo->command = cpu_to_le32(VM_NameServe); dinfo->count = cpu_to_le32(index); dinfo->type = cpu_to_le32(FT_FILESYS); status = fib_send(ContainerCommand, fibptr, sizeof (struct aac_query_mount), FsaNormal, 1, 1, NULL, NULL); if (status < 0 ) { printk(KERN_WARNING "aac_get_containers: SendFIB failed.\n"); break; } dresp = (struct aac_mount *)fib_data(fibptr); if ((le32_to_cpu(dresp->status) == ST_OK) && (le32_to_cpu(dresp->mnt[0].vol) != CT_NONE) && (le32_to_cpu(dresp->mnt[0].state) != FSCS_HIDDEN)) { fsa_dev_ptr->valid[index] = 1; fsa_dev_ptr->type[index] = le32_to_cpu(dresp->mnt[0].vol); fsa_dev_ptr->size[index] = le32_to_cpu(dresp->mnt[0].capacity); if (le32_to_cpu(dresp->mnt[0].state) & FSCS_READONLY) fsa_dev_ptr->ro[index] = 1; } fib_complete(fibptr); /* * If there are no more containers, then stop asking. */ if ((index + 1) >= le32_to_cpu(dresp->count)) break; } fib_free(fibptr); fsa_dev[instance] = fsa_dev_ptr; return status; } /** * aac_get_container_name - get container name */ static int aac_get_container_name(struct aac_dev *dev, int cid, char * pid) { struct fsa_scsi_hba *fsa_dev_ptr; int status = 0; struct aac_get_name *dinfo; struct aac_get_name_resp *dresp; struct fib * fibptr; unsigned instance; fsa_dev_ptr = &(dev->fsa_dev); instance = dev->scsi_host_ptr->unique_id; if (!(fibptr = fib_alloc(dev))) return -ENOMEM; fib_init(fibptr); dinfo = (struct aac_get_name *) fib_data(fibptr); dinfo->command = cpu_to_le32(VM_ContainerConfig); dinfo->type = cpu_to_le32(CT_READ_NAME); dinfo->cid = cpu_to_le32(cid); dinfo->count = cpu_to_le32(sizeof(((struct aac_get_name_resp *)NULL)->data)); status = fib_send(ContainerCommand, fibptr, sizeof (struct aac_get_name), FsaNormal, 1, 1, NULL, NULL); if (status < 0 ) { printk(KERN_WARNING "aac_get_container_name: SendFIB failed.\n"); } else { dresp = (struct aac_get_name_resp *)fib_data(fibptr); status = (le32_to_cpu(dresp->status) != CT_OK) || (dresp->data[0] == '\0'); if (status == 0) { char * sp = dresp->data; char * dp = pid; do { if ((*sp == '\0') || ((dp - pid) >= sizeof(((struct aac_get_name_resp *)NULL)->data))) { *dp = ' '; } else { *dp = *sp++; } } while (++dp < &pid[sizeof(((struct inquiry_data *)NULL)->inqd_pid)]); } } fib_complete(fibptr); fib_free(fibptr); fsa_dev[instance] = fsa_dev_ptr; return status; } /** * probe_container - query a logical volume * @dev: device to query * @cid: container identifier * * Queries the controller about the given volume. The volume information * is updated in the struct fsa_scsi_hba structure rather than returned. */ static int probe_container(struct aac_dev *dev, int cid) { struct fsa_scsi_hba *fsa_dev_ptr; int status; struct aac_query_mount *dinfo; struct aac_mount *dresp; struct fib * fibptr; unsigned instance; fsa_dev_ptr = &(dev->fsa_dev); instance = dev->scsi_host_ptr->unique_id; if (!(fibptr = fib_alloc(dev))) return -ENOMEM; fib_init(fibptr); dinfo = (struct aac_query_mount *)fib_data(fibptr); dinfo->command = cpu_to_le32(VM_NameServe); dinfo->count = cpu_to_le32(cid); dinfo->type = cpu_to_le32(FT_FILESYS); status = fib_send(ContainerCommand, fibptr, sizeof(struct aac_query_mount), FsaNormal, 1, 1, NULL, NULL); if (status < 0) { printk(KERN_WARNING "aacraid: probe_containers query failed.\n"); goto error; } dresp = (struct aac_mount *) fib_data(fibptr); if ((le32_to_cpu(dresp->status) == ST_OK) && (le32_to_cpu(dresp->mnt[0].vol) != CT_NONE) && (le32_to_cpu(dresp->mnt[0].state) != FSCS_HIDDEN)) { fsa_dev_ptr->valid[cid] = 1; fsa_dev_ptr->type[cid] = le32_to_cpu(dresp->mnt[0].vol); fsa_dev_ptr->size[cid] = le32_to_cpu(dresp->mnt[0].capacity); if (le32_to_cpu(dresp->mnt[0].state) & FSCS_READONLY) fsa_dev_ptr->ro[cid] = 1; } error: fib_complete(fibptr); fib_free(fibptr); return status; } /* Local Structure to set SCSI inquiry data strings */ struct scsi_inq { char vid[8]; /* Vendor ID */ char pid[16]; /* Product ID */ char prl[4]; /* Product Revision Level */ }; /** * InqStrCopy - string merge * @a: string to copy from * @b: string to copy to * * Copy a String from one location to another * without copying \0 */ static void inqstrcpy(char *a, char *b) { while(*a != (char)0) *b++ = *a++; } static char *container_types[] = { "None", "Volume", "Mirror", "Stripe", "RAID5", "SSRW", "SSRO", "Morph", "Legacy", "RAID4", "RAID10", "RAID00", "V-MIRRORS", "PSEUDO R4", "RAID50", "Unknown" }; /* Function: setinqstr * * Arguments: [1] pointer to void [1] int * * Purpose: Sets SCSI inquiry data strings for vendor, product * and revision level. Allows strings to be set in platform dependant * files instead of in OS dependant driver source. */ static void setinqstr(int devtype, void *data, int tindex) { struct scsi_inq *str; char *findit; struct aac_driver_ident *mp; mp = aac_get_driver_ident(devtype); str = (struct scsi_inq *)(data); /* cast data to scsi inq block */ inqstrcpy (mp->vname, str->vid); inqstrcpy (mp->model, str->pid); /* last six chars reserved for vol type */ findit = str->pid; for ( ; *findit != ' '; findit++); /* walk till we find a space then incr by 1 */ findit++; if (tindex < (sizeof(container_types)/sizeof(char *))){ inqstrcpy (container_types[tindex], findit); } inqstrcpy ("V1.0", str->prl); } void set_sense(u8 *sense_buf, u8 sense_key, u8 sense_code, u8 a_sense_code, u8 incorrect_length, u8 bit_pointer, u16 field_pointer, u32 residue) { sense_buf[0] = 0xF0; /* Sense data valid, err code 70h (current error) */ sense_buf[1] = 0; /* Segment number, always zero */ if (incorrect_length) { sense_buf[2] = sense_key | 0x20; /* Set ILI bit | sense key */ sense_buf[3] = BYTE3(residue); sense_buf[4] = BYTE2(residue); sense_buf[5] = BYTE1(residue); sense_buf[6] = BYTE0(residue); } else sense_buf[2] = sense_key; /* Sense key */ if (sense_key == SENKEY_ILLEGAL) sense_buf[7] = 10; /* Additional sense length */ else sense_buf[7] = 6; /* Additional sense length */ sense_buf[12] = sense_code; /* Additional sense code */ sense_buf[13] = a_sense_code; /* Additional sense code qualifier */ if (sense_key == SENKEY_ILLEGAL) { sense_buf[15] = 0; if (sense_code == SENCODE_INVALID_PARAM_FIELD) sense_buf[15] = 0x80; /* Std sense key specific field */ /* Illegal parameter is in the parameter block */ if (sense_code == SENCODE_INVALID_CDB_FIELD) sense_buf[15] = 0xc0; /* Std sense key specific field */ /* Illegal parameter is in the CDB block */ sense_buf[15] |= bit_pointer; sense_buf[16] = field_pointer >> 8; /* MSB */ sense_buf[17] = field_pointer; /* LSB */ } } static void aac_io_done(Scsi_Cmnd * scsicmd) { unsigned long cpu_flags; spin_lock_irqsave(&io_request_lock, cpu_flags); scsicmd->scsi_done(scsicmd); spin_unlock_irqrestore(&io_request_lock, cpu_flags); } static void __aac_io_done(Scsi_Cmnd * scsicmd) { scsicmd->scsi_done(scsicmd); } int aac_get_adapter_info(struct aac_dev* dev) { struct fib* fibptr; struct aac_adapter_info* info; int rcode; u32 tmp; if (!(fibptr = fib_alloc(dev))) return -ENOMEM; fib_init(fibptr); info = (struct aac_adapter_info*) fib_data(fibptr); memset(info,0,sizeof(struct aac_adapter_info)); rcode = fib_send(RequestAdapterInfo, fibptr, sizeof(struct aac_adapter_info), FsaNormal, 1, 1, NULL, NULL); memcpy(&dev->adapter_info, info, sizeof(struct aac_adapter_info)); tmp = dev->adapter_info.kernelrev; printk(KERN_INFO "%s%d: kernel %d.%d.%d build %d\n", dev->name, dev->id, tmp>>24,(tmp>>16)&0xff,(tmp>>8)&0xff, dev->adapter_info.kernelbuild); tmp = dev->adapter_info.monitorrev; printk(KERN_INFO "%s%d: monitor %d.%d.%d build %d\n", dev->name, dev->id, tmp>>24,(tmp>>16)&0xff,(tmp>>8)&0xff, dev->adapter_info.monitorbuild); tmp = dev->adapter_info.biosrev; printk(KERN_INFO "%s%d: bios %d.%d.%d build %d\n", dev->name, dev->id, tmp>>24,(tmp>>16)&0xff,(tmp>>8)&0xff, dev->adapter_info.biosbuild); printk(KERN_INFO "%s%d: serial %x%x\n", dev->name, dev->id, dev->adapter_info.serial[0], dev->adapter_info.serial[1]); dev->nondasd_support = 0; dev->raid_scsi_mode = 0; if(dev->adapter_info.options & AAC_OPT_NONDASD){ dev->nondasd_support = 1; } /* * If the firmware supports ROMB RAID/SCSI mode and we are currently * in RAID/SCSI mode, set the flag. For now if in this mode we will * force nondasd support on. If we decide to allow the non-dasd flag * additional changes changes will have to be made to support * RAID/SCSI. the function aac_scsi_cmd in this module will have to be * changed to support the new dev->raid_scsi_mode flag instead of * leaching off of the dev->nondasd_support flag. Also in linit.c the * function aac_detect will have to be modified where it sets up the * max number of channels based on the aac->nondasd_support flag only. */ if ((dev->adapter_info.options & AAC_OPT_SCSI_MANAGED) && (dev->adapter_info.options & AAC_OPT_RAID_SCSI_MODE)) { dev->nondasd_support = 1; dev->raid_scsi_mode = 1; } if (dev->raid_scsi_mode != 0) printk(KERN_INFO "%s%d: ROMB RAID/SCSI mode enabled\n",dev->name, dev->id); if (nondasd != -1) dev->nondasd_support = (nondasd!=0); if(dev->nondasd_support != 0) printk(KERN_INFO "%s%d: Non-DASD support enabled\n",dev->name, dev->id); dev->pae_support = 0; if( (sizeof(dma_addr_t) > 4) && (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64)){ dev->pae_support = 1; } if(paemode != -1) dev->pae_support = (paemode != 0); if(dev->pae_support != 0) { printk(KERN_INFO "%s%d: 64 Bit PAE enabled\n", dev->name, dev->id); pci_set_dma_mask(dev->pdev, (dma_addr_t)0xFFFFFFFFFFFFFFFFULL); } fib_complete(fibptr); fib_free(fibptr); return rcode; } static void read_callback(void *context, struct fib * fibptr) { struct aac_dev *dev; struct aac_read_reply *readreply; Scsi_Cmnd *scsicmd; u32 lba; u32 cid; scsicmd = (Scsi_Cmnd *) context; dev = (struct aac_dev *)scsicmd->host->hostdata; cid =TARGET_LUN_TO_CONTAINER(scsicmd->target, scsicmd->lun); lba = ((scsicmd->cmnd[1] & 0x1F) << 16) | (scsicmd->cmnd[2] << 8) | scsicmd->cmnd[3]; dprintk((KERN_DEBUG "read_callback[cpu %d]: lba = %u, t = %ld.\n", smp_processor_id(), lba, jiffies)); if (fibptr == NULL) BUG(); if(scsicmd->use_sg) pci_unmap_sg(dev->pdev, (struct scatterlist *)scsicmd->buffer, scsicmd->use_sg, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); else if(scsicmd->request_bufflen) pci_unmap_single(dev->pdev, (dma_addr_t)(unsigned long)scsicmd->SCp.ptr, scsicmd->request_bufflen, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); readreply = (struct aac_read_reply *)fib_data(fibptr); if (le32_to_cpu(readreply->status) == ST_OK) scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; else { printk(KERN_WARNING "read_callback: read failed, status = %d\n", readreply->status); scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | CHECK_CONDITION; set_sense((u8 *) &sense_data[cid], SENKEY_HW_ERR, SENCODE_INTERNAL_TARGET_FAILURE, ASENCODE_INTERNAL_TARGET_FAILURE, 0, 0, 0, 0); } fib_complete(fibptr); fib_free(fibptr); aac_io_done(scsicmd); } static void write_callback(void *context, struct fib * fibptr) { struct aac_dev *dev; struct aac_write_reply *writereply; Scsi_Cmnd *scsicmd; u32 lba; u32 cid; scsicmd = (Scsi_Cmnd *) context; dev = (struct aac_dev *)scsicmd->host->hostdata; cid = TARGET_LUN_TO_CONTAINER(scsicmd->target, scsicmd->lun); lba = ((scsicmd->cmnd[1] & 0x1F) << 16) | (scsicmd->cmnd[2] << 8) | scsicmd->cmnd[3]; dprintk((KERN_DEBUG "write_callback[cpu %d]: lba = %u, t = %ld.\n", smp_processor_id(), lba, jiffies)); if (fibptr == NULL) BUG(); if(scsicmd->use_sg) pci_unmap_sg(dev->pdev, (struct scatterlist *)scsicmd->buffer, scsicmd->use_sg, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); else if(scsicmd->request_bufflen) pci_unmap_single(dev->pdev, (dma_addr_t)(unsigned long)scsicmd->SCp.ptr, scsicmd->request_bufflen, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); writereply = (struct aac_write_reply *) fib_data(fibptr); if (le32_to_cpu(writereply->status) == ST_OK) scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; else { printk(KERN_WARNING "write_callback: write failed, status = %d\n", writereply->status); scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | CHECK_CONDITION; set_sense((u8 *) &sense_data[cid], SENKEY_HW_ERR, SENCODE_INTERNAL_TARGET_FAILURE, ASENCODE_INTERNAL_TARGET_FAILURE, 0, 0, 0, 0); } fib_complete(fibptr); fib_free(fibptr); aac_io_done(scsicmd); } int aac_read(Scsi_Cmnd * scsicmd, int cid) { u32 lba; u32 count; int status; u16 fibsize; struct aac_dev *dev; struct fib * cmd_fibcontext; dev = (struct aac_dev *)scsicmd->host->hostdata; /* * Get block address and transfer length */ if (scsicmd->cmnd[0] == SS_READ) /* 6 byte command */ { dprintk((KERN_DEBUG "aachba: received a read(6) command on target %d.\n", cid)); lba = ((scsicmd->cmnd[1] & 0x1F) << 16) | (scsicmd->cmnd[2] << 8) | scsicmd->cmnd[3]; count = scsicmd->cmnd[4]; if (count == 0) count = 256; } else { dprintk((KERN_DEBUG "aachba: received a read(10) command on target %d.\n", cid)); lba = (scsicmd->cmnd[2] << 24) | (scsicmd->cmnd[3] << 16) | (scsicmd->cmnd[4] << 8) | scsicmd->cmnd[5]; count = (scsicmd->cmnd[7] << 8) | scsicmd->cmnd[8]; } dprintk((KERN_DEBUG "aac_read[cpu %d]: lba = %u, t = %ld.\n", smp_processor_id(), lba, jiffies)); /* * Alocate and initialize a Fib */ if (!(cmd_fibcontext = fib_alloc(dev))) { scsicmd->result = DID_ERROR << 16; aac_io_done(scsicmd); return (-1); } fib_init(cmd_fibcontext); if(dev->pae_support == 1){ struct aac_read64 *readcmd; readcmd = (struct aac_read64 *) fib_data(cmd_fibcontext); readcmd->command = cpu_to_le32(VM_CtHostRead64); readcmd->cid = cpu_to_le16(cid); readcmd->sector_count = cpu_to_le16(count); readcmd->block = cpu_to_le32(lba); readcmd->pad = cpu_to_le16(0); readcmd->flags = cpu_to_le16(0); aac_build_sg64(scsicmd, &readcmd->sg); if(readcmd->sg.count > MAX_DRIVER_SG_SEGMENT_COUNT) BUG(); fibsize = sizeof(struct aac_read64) + ((readcmd->sg.count - 1) * sizeof (struct sgentry64)); /* * Now send the Fib to the adapter */ status = fib_send(ContainerCommand64, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) read_callback, (void *) scsicmd); } else { struct aac_read *readcmd; readcmd = (struct aac_read *) fib_data(cmd_fibcontext); readcmd->command = cpu_to_le32(VM_CtBlockRead); readcmd->cid = cpu_to_le32(cid); readcmd->block = cpu_to_le32(lba); readcmd->count = cpu_to_le32(count * 512); if (count * 512 > (64 * 1024)) BUG(); aac_build_sg(scsicmd, &readcmd->sg); if(readcmd->sg.count > MAX_DRIVER_SG_SEGMENT_COUNT) BUG(); fibsize = sizeof(struct aac_read) + ((readcmd->sg.count - 1) * sizeof (struct sgentry)); /* * Now send the Fib to the adapter */ status = fib_send(ContainerCommand, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) read_callback, (void *) scsicmd); } /* * Check that the command queued to the controller */ if (status == -EINPROGRESS) return 0; printk(KERN_WARNING "aac_read: fib_send failed with status: %d.\n", status); /* * For some reason, the Fib didn't queue, return QUEUE_FULL */ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | QUEUE_FULL; aac_io_done(scsicmd); fib_complete(cmd_fibcontext); fib_free(cmd_fibcontext); return -1; } static int aac_write(Scsi_Cmnd * scsicmd, int cid) { u32 lba; u32 count; int status; u16 fibsize; struct aac_dev *dev; struct fib * cmd_fibcontext; dev = (struct aac_dev *)scsicmd->host->hostdata; /* * Get block address and transfer length */ if (scsicmd->cmnd[0] == SS_WRITE) /* 6 byte command */ { lba = ((scsicmd->cmnd[1] & 0x1F) << 16) | (scsicmd->cmnd[2] << 8) | scsicmd->cmnd[3]; count = scsicmd->cmnd[4]; if (count == 0) count = 256; } else { dprintk((KERN_DEBUG "aachba: received a write(10) command on target %d.\n", cid)); lba = (scsicmd->cmnd[2] << 24) | (scsicmd->cmnd[3] << 16) | (scsicmd->cmnd[4] << 8) | scsicmd->cmnd[5]; count = (scsicmd->cmnd[7] << 8) | scsicmd->cmnd[8]; } dprintk((KERN_DEBUG "aac_write[cpu %d]: lba = %u, t = %ld.\n", smp_processor_id(), lba, jiffies)); /* * Allocate and initialize a Fib then setup a BlockWrite command */ if (!(cmd_fibcontext = fib_alloc(dev))) { scsicmd->result = DID_ERROR << 16; aac_io_done(scsicmd); return -1; } fib_init(cmd_fibcontext); if(dev->pae_support == 1) { struct aac_write64 *writecmd; writecmd = (struct aac_write64 *) fib_data(cmd_fibcontext); writecmd->command = cpu_to_le32(VM_CtHostWrite64); writecmd->cid = cpu_to_le16(cid); writecmd->sector_count = cpu_to_le16(count); writecmd->block = cpu_to_le32(lba); writecmd->pad = cpu_to_le16(0); writecmd->flags = cpu_to_le16(0); aac_build_sg64(scsicmd, &writecmd->sg); if(writecmd->sg.count > MAX_DRIVER_SG_SEGMENT_COUNT) BUG(); fibsize = sizeof(struct aac_write64) + ((writecmd->sg.count - 1) * sizeof (struct sgentry64)); /* * Now send the Fib to the adapter */ status = fib_send(ContainerCommand64, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) write_callback, (void *) scsicmd); } else { struct aac_write *writecmd; writecmd = (struct aac_write *) fib_data(cmd_fibcontext); writecmd->command = cpu_to_le32(VM_CtBlockWrite); writecmd->cid = cpu_to_le32(cid); writecmd->block = cpu_to_le32(lba); writecmd->count = cpu_to_le32(count * 512); writecmd->sg.count = cpu_to_le32(1); /* ->stable is not used - it did mean which type of write */ if (count * 512 > (64 * 1024)) BUG(); aac_build_sg(scsicmd, &writecmd->sg); if(writecmd->sg.count > MAX_DRIVER_SG_SEGMENT_COUNT) BUG(); fibsize = sizeof(struct aac_write) + ((writecmd->sg.count - 1) * sizeof (struct sgentry)); /* * Now send the Fib to the adapter */ status = fib_send(ContainerCommand, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) write_callback, (void *) scsicmd); } /* * Check that the command queued to the controller */ if (status == -EINPROGRESS) return 0; printk(KERN_WARNING "aac_write: fib_send failed with status: %d\n", status); /* * For some reason, the Fib didn't queue, return QUEUE_FULL */ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | QUEUE_FULL; aac_io_done(scsicmd); fib_complete(cmd_fibcontext); fib_free(cmd_fibcontext); return -1; } /** * aac_scsi_cmd() - Process SCSI command * @scsicmd: SCSI command block * @wait: 1 if the user wants to await completion * * Emulate a SCSI command and queue the required request for the * aacraid firmware. */ int aac_scsi_cmd(Scsi_Cmnd * scsicmd) { u32 cid = 0; struct fsa_scsi_hba *fsa_dev_ptr; int cardtype; int ret; struct aac_dev *dev = (struct aac_dev *)scsicmd->host->hostdata; cardtype = dev->cardtype; fsa_dev_ptr = fsa_dev[scsicmd->host->unique_id]; /* * If the bus, target or lun is out of range, return fail * Test does not apply to ID 16, the pseudo id for the controller * itself. */ if (scsicmd->target != scsicmd->host->this_id) { if ((scsicmd->channel == 0) ){ if( (scsicmd->target >= AAC_MAX_TARGET) || (scsicmd->lun != 0)){ scsicmd->result = DID_NO_CONNECT << 16; __aac_io_done(scsicmd); return 0; } cid = TARGET_LUN_TO_CONTAINER(scsicmd->target, scsicmd->lun); /* * If the target container doesn't exist, it may have * been newly created */ if (fsa_dev_ptr->valid[cid] == 0) { switch (scsicmd->cmnd[0]) { case SS_INQUIR: case SS_RDCAP: case SS_TEST: spin_unlock_irq(&io_request_lock); probe_container(dev, cid); spin_lock_irq(&io_request_lock); if (fsa_dev_ptr->valid[cid] == 0) { scsicmd->result = DID_NO_CONNECT << 16; __aac_io_done(scsicmd); return 0; } default: break; } } /* * If the target container still doesn't exist, * return failure */ if (fsa_dev_ptr->valid[cid] == 0) { scsicmd->result = DID_BAD_TARGET << 16; __aac_io_done(scsicmd); return -1; } } else { /* check for physical non-dasd devices */ if(dev->nondasd_support == 1){ return aac_send_srb_fib(scsicmd); } else { scsicmd->result = DID_NO_CONNECT << 16; __aac_io_done(scsicmd); return 0; } } } /* * else Command for the controller itself */ else if ((scsicmd->cmnd[0] != SS_INQUIR) && /* only INQUIRY & TUR cmnd supported for controller */ (scsicmd->cmnd[0] != SS_TEST)) { dprintk((KERN_WARNING "Only INQUIRY & TUR command supported for controller, rcvd = 0x%x.\n", scsicmd->cmnd[0])); scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | CHECK_CONDITION; set_sense((u8 *) &sense_data[cid], SENKEY_ILLEGAL, SENCODE_INVALID_COMMAND, ASENCODE_INVALID_COMMAND, 0, 0, 0, 0); __aac_io_done(scsicmd); return -1; } /* Handle commands here that don't really require going out to the adapter */ switch (scsicmd->cmnd[0]) { case SS_INQUIR: { struct inquiry_data *inq_data_ptr; dprintk((KERN_DEBUG "INQUIRY command, ID: %d.\n", scsicmd->target)); inq_data_ptr = (struct inquiry_data *)scsicmd->request_buffer; memset(inq_data_ptr, 0, sizeof (struct inquiry_data)); inq_data_ptr->inqd_ver = 2; /* claim compliance to SCSI-2 */ inq_data_ptr->inqd_rdf = 2; /* A response data format value of two indicates that the data shall be in the format specified in SCSI-2 */ inq_data_ptr->inqd_len = 31; /*Format for "pad2" is RelAdr | WBus32 | WBus16 | Sync | Linked |Reserved| CmdQue | SftRe */ inq_data_ptr->inqd_pad2= 0x32 ; /*WBus16|Sync|CmdQue */ /* * Set the Vendor, Product, and Revision Level * see: <vendor>.c i.e. aac.c */ if (scsicmd->target == scsicmd->host->this_id) { setinqstr(cardtype, (void *) (inq_data_ptr->inqd_vid), (sizeof(container_types)/sizeof(char *))); inq_data_ptr->inqd_pdt = INQD_PDT_PROC; /* Processor device */ } else { setinqstr(cardtype, (void *) (inq_data_ptr->inqd_vid), fsa_dev_ptr->type[cid]); aac_get_container_name(dev, cid, inq_data_ptr->inqd_pid); inq_data_ptr->inqd_pdt = INQD_PDT_DA; /* Direct/random access device */ } scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return 0; } case SS_RDCAP: { int capacity; char *cp; dprintk((KERN_DEBUG "READ CAPACITY command.\n")); capacity = fsa_dev_ptr->size[cid] - 1; cp = scsicmd->request_buffer; cp[0] = (capacity >> 24) & 0xff; cp[1] = (capacity >> 16) & 0xff; cp[2] = (capacity >> 8) & 0xff; cp[3] = (capacity >> 0) & 0xff; cp[4] = 0; cp[5] = 0; cp[6] = 2; cp[7] = 0; scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return 0; } case SS_MODESEN: { char *mode_buf; dprintk((KERN_DEBUG "MODE SENSE command.\n")); mode_buf = scsicmd->request_buffer; mode_buf[0] = 0; /* Mode data length (MSB) */ mode_buf[1] = 6; /* Mode data length (LSB) */ mode_buf[2] = 0; /* Medium type - default */ mode_buf[3] = 0; /* Device-specific param, bit 8: 0/1 = write enabled/protected */ mode_buf[4] = 0; /* reserved */ mode_buf[5] = 0; /* reserved */ mode_buf[6] = 0; /* Block descriptor length (MSB) */ mode_buf[7] = 0; /* Block descriptor length (LSB) */ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return 0; } case SS_REQSEN: dprintk((KERN_DEBUG "REQUEST SENSE command.\n")); memcpy(scsicmd->sense_buffer, &sense_data[cid], sizeof (struct sense_data)); memset(&sense_data[cid], 0, sizeof (struct sense_data)); scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return (0); case SS_LOCK: dprintk((KERN_DEBUG "LOCK command.\n")); if (scsicmd->cmnd[4]) fsa_dev_ptr->locked[cid] = 1; else fsa_dev_ptr->locked[cid] = 0; scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return 0; /* * These commands are all No-Ops */ case SS_TEST: case SS_RESERV: case SS_RELES: case SS_REZERO: case SS_REASGN: case SS_SEEK: case SS_ST_SP: scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | GOOD; __aac_io_done(scsicmd); return (0); } switch (scsicmd->cmnd[0]) { case SS_READ: case SM_READ: /* * Hack to keep track of ordinal number of the device that * corresponds to a container. Needed to convert * containers to /dev/sd device names */ spin_unlock_irq(&io_request_lock); fsa_dev_ptr->devno[cid] = DEVICE_NR(scsicmd->request.rq_dev); ret = aac_read(scsicmd, cid); spin_lock_irq(&io_request_lock); return ret; case SS_WRITE: case SM_WRITE: spin_unlock_irq(&io_request_lock); ret = aac_write(scsicmd, cid); spin_lock_irq(&io_request_lock); return ret; default: /* * Unhandled commands */ printk(KERN_WARNING "Unhandled SCSI Command: 0x%x.\n", scsicmd->cmnd[0]); scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | CHECK_CONDITION; set_sense((u8 *) &sense_data[cid], SENKEY_ILLEGAL, SENCODE_INVALID_COMMAND, ASENCODE_INVALID_COMMAND, 0, 0, 0, 0); __aac_io_done(scsicmd); return 0; } } static int query_disk(struct aac_dev *dev, void *arg) { struct aac_query_disk qd; struct fsa_scsi_hba *fsa_dev_ptr; fsa_dev_ptr = &(dev->fsa_dev); if (copy_from_user(&qd, arg, sizeof (struct aac_query_disk))) return -EFAULT; if (qd.cnum == -1) qd.cnum = TARGET_LUN_TO_CONTAINER(qd.target, qd.lun); else if ((qd.bus == -1) && (qd.target == -1) && (qd.lun == -1)) { if (qd.cnum < 0 || qd.cnum > MAXIMUM_NUM_CONTAINERS) return -EINVAL; qd.instance = dev->scsi_host_ptr->host_no; qd.bus = 0; qd.target = CONTAINER_TO_TARGET(qd.cnum); qd.lun = CONTAINER_TO_LUN(qd.cnum); } else return -EINVAL; qd.valid = fsa_dev_ptr->valid[qd.cnum]; qd.locked = fsa_dev_ptr->locked[qd.cnum]; qd.deleted = fsa_dev_ptr->deleted[qd.cnum]; if (fsa_dev_ptr->devno[qd.cnum] == -1) qd.unmapped = 1; else qd.unmapped = 0; get_sd_devname(fsa_dev_ptr->devno[qd.cnum], qd.name); if (copy_to_user(arg, &qd, sizeof (struct aac_query_disk))) return -EFAULT; return 0; } static void get_sd_devname(int disknum, char *buffer) { if (disknum < 0) { sprintf(buffer, "%s", ""); return; } if (disknum < 26) sprintf(buffer, "sd%c", 'a' + disknum); else { unsigned int min1; unsigned int min2; /* * For larger numbers of disks, we need to go to a new * naming scheme. */ min1 = disknum / 26; min2 = disknum % 26; sprintf(buffer, "sd%c%c", 'a' + min1 - 1, 'a' + min2); } } static int force_delete_disk(struct aac_dev *dev, void *arg) { struct aac_delete_disk dd; struct fsa_scsi_hba *fsa_dev_ptr; fsa_dev_ptr = &(dev->fsa_dev); if (copy_from_user(&dd, arg, sizeof (struct aac_delete_disk))) return -EFAULT; if (dd.cnum > MAXIMUM_NUM_CONTAINERS) return -EINVAL; /* * Mark this container as being deleted. */ fsa_dev_ptr->deleted[dd.cnum] = 1; /* * Mark the container as no longer valid */ fsa_dev_ptr->valid[dd.cnum] = 0; return 0; } static int delete_disk(struct aac_dev *dev, void *arg) { struct aac_delete_disk dd; struct fsa_scsi_hba *fsa_dev_ptr; fsa_dev_ptr = &(dev->fsa_dev); if (copy_from_user(&dd, arg, sizeof (struct aac_delete_disk))) return -EFAULT; if (dd.cnum > MAXIMUM_NUM_CONTAINERS) return -EINVAL; /* * If the container is locked, it can not be deleted by the API. */ if (fsa_dev_ptr->locked[dd.cnum]) return -EBUSY; else { /* * Mark the container as no longer being valid. */ fsa_dev_ptr->valid[dd.cnum] = 0; fsa_dev_ptr->devno[dd.cnum] = -1; return 0; } } int aac_dev_ioctl(struct aac_dev *dev, int cmd, void *arg) { switch (cmd) { case FSACTL_QUERY_DISK: return query_disk(dev, arg); case FSACTL_DELETE_DISK: return delete_disk(dev, arg); case FSACTL_FORCE_DELETE_DISK: return force_delete_disk(dev, arg); case 2131: return aac_get_containers(dev); default: return -ENOTTY; } } /** * * aac_srb_callback * @context: the context set in the fib - here it is scsi cmd * @fibptr: pointer to the fib * * Handles the completion of a scsi command to a non dasd device * */ static void aac_srb_callback(void *context, struct fib * fibptr) { struct aac_dev *dev; struct aac_srb_reply *srbreply; Scsi_Cmnd *scsicmd; scsicmd = (Scsi_Cmnd *) context; dev = (struct aac_dev *)scsicmd->host->hostdata; if (fibptr == NULL) BUG(); srbreply = (struct aac_srb_reply *) fib_data(fibptr); scsicmd->sense_buffer[0] = '\0'; // initialize sense valid flag to false // calculate resid for sg scsicmd->resid = scsicmd->request_bufflen - srbreply->data_xfer_length; if(scsicmd->use_sg) pci_unmap_sg(dev->pdev, (struct scatterlist *)scsicmd->buffer, scsicmd->use_sg, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); else if(scsicmd->request_bufflen) pci_unmap_single(dev->pdev, (ulong)scsicmd->SCp.ptr, scsicmd->request_bufflen, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); /* * First check the fib status */ if (le32_to_cpu(srbreply->status) != ST_OK){ int len; printk(KERN_WARNING "aac_srb_callback: srb failed, status = %d\n", le32_to_cpu(srbreply->status)); len = (srbreply->sense_data_size > sizeof(scsicmd->sense_buffer))? sizeof(scsicmd->sense_buffer):srbreply->sense_data_size; scsicmd->result = DID_ERROR << 16 | COMMAND_COMPLETE << 8 | CHECK_CONDITION; memcpy(scsicmd->sense_buffer, srbreply->sense_data, len); } /* * Next check the srb status */ switch( (le32_to_cpu(srbreply->srb_status))&0x3f){ case SRB_STATUS_ERROR_RECOVERY: case SRB_STATUS_PENDING: case SRB_STATUS_SUCCESS: if(scsicmd->cmnd[0] == INQUIRY ){ u8 b; u8 b1; /* We can't expose disk devices because we can't tell whether they * are the raw container drives or stand alone drives. If they have * the removable bit set then we should expose them though. */ b = (*(u8*)scsicmd->buffer)&0x1f; b1 = ((u8*)scsicmd->buffer)[1]; if( b==TYPE_TAPE || b==TYPE_WORM || b==TYPE_ROM || b==TYPE_MOD|| b==TYPE_MEDIUM_CHANGER || (b==TYPE_DISK && (b1&0x80)) ){ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; /* * We will allow disk devices if in RAID/SCSI mode and * the channel is 2 */ } else if((dev->raid_scsi_mode)&&(scsicmd->channel == 2)){ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; } else { scsicmd->result = DID_NO_CONNECT << 16 | COMMAND_COMPLETE << 8; } } else { scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; } break; case SRB_STATUS_DATA_OVERRUN: switch(scsicmd->cmnd[0]){ case READ_6: case WRITE_6: case READ_10: case WRITE_10: case READ_12: case WRITE_12: if(le32_to_cpu(srbreply->data_xfer_length) < scsicmd->underflow ) { printk(KERN_WARNING"aacraid: SCSI CMD underflow\n"); } else { printk(KERN_WARNING"aacraid: SCSI CMD Data Overrun\n"); } scsicmd->result = DID_ERROR << 16 | COMMAND_COMPLETE << 8; break; case INQUIRY: { u8 b; u8 b1; /* We can't expose disk devices because we can't tell whether they * are the raw container drives or stand alone drives */ b = (*(u8*)scsicmd->buffer)&0x0f; b1 = ((u8*)scsicmd->buffer)[1]; if( b==TYPE_TAPE || b==TYPE_WORM || b==TYPE_ROM || b==TYPE_MOD|| b==TYPE_MEDIUM_CHANGER || (b==TYPE_DISK && (b1&0x80)) ){ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; /* * We will allow disk devices if in RAID/SCSI mode and * the channel is 2 */ } else if((dev->raid_scsi_mode)&&(scsicmd->channel == 2)){ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; } else { scsicmd->result = DID_NO_CONNECT << 16 | COMMAND_COMPLETE << 8; } break; } default: scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8; break; } break; case SRB_STATUS_ABORTED: scsicmd->result = DID_ABORT << 16 | ABORT << 8; break; case SRB_STATUS_ABORT_FAILED: // Not sure about this one - but assuming the hba was trying to abort for some reason scsicmd->result = DID_ERROR << 16 | ABORT << 8; break; case SRB_STATUS_PARITY_ERROR: scsicmd->result = DID_PARITY << 16 | MSG_PARITY_ERROR << 8; break; case SRB_STATUS_NO_DEVICE: case SRB_STATUS_INVALID_PATH_ID: case SRB_STATUS_INVALID_TARGET_ID: case SRB_STATUS_INVALID_LUN: case SRB_STATUS_SELECTION_TIMEOUT: scsicmd->result = DID_NO_CONNECT << 16 | COMMAND_COMPLETE << 8; break; case SRB_STATUS_COMMAND_TIMEOUT: case SRB_STATUS_TIMEOUT: scsicmd->result = DID_TIME_OUT << 16 | COMMAND_COMPLETE << 8; break; case SRB_STATUS_BUSY: scsicmd->result = DID_NO_CONNECT << 16 | COMMAND_COMPLETE << 8; break; case SRB_STATUS_BUS_RESET: scsicmd->result = DID_RESET << 16 | COMMAND_COMPLETE << 8; break; case SRB_STATUS_MESSAGE_REJECTED: scsicmd->result = DID_ERROR << 16 | MESSAGE_REJECT << 8; break; case SRB_STATUS_REQUEST_FLUSHED: case SRB_STATUS_ERROR: case SRB_STATUS_INVALID_REQUEST: case SRB_STATUS_REQUEST_SENSE_FAILED: case SRB_STATUS_NO_HBA: case SRB_STATUS_UNEXPECTED_BUS_FREE: case SRB_STATUS_PHASE_SEQUENCE_FAILURE: case SRB_STATUS_BAD_SRB_BLOCK_LENGTH: case SRB_STATUS_DELAYED_RETRY: case SRB_STATUS_BAD_FUNCTION: case SRB_STATUS_NOT_STARTED: case SRB_STATUS_NOT_IN_USE: case SRB_STATUS_FORCE_ABORT: case SRB_STATUS_DOMAIN_VALIDATION_FAIL: default: printk("aacraid: SRB ERROR(%u) %s scsi cmd 0x%x - scsi status 0x%x\n",le32_to_cpu(srbreply->srb_status&0x3f),aac_get_status_string(le32_to_cpu(srbreply->srb_status)), scsicmd->cmnd[0], le32_to_cpu(srbreply->scsi_status) ); scsicmd->result = DID_ERROR << 16 | COMMAND_COMPLETE << 8; break; } if (le32_to_cpu(srbreply->scsi_status) == 0x02 ){ // Check Condition int len; scsicmd->result |= CHECK_CONDITION; len = (srbreply->sense_data_size > sizeof(scsicmd->sense_buffer))? sizeof(scsicmd->sense_buffer):srbreply->sense_data_size; printk(KERN_WARNING "aac_srb_callback: check condition, status = %d len=%d\n", le32_to_cpu(srbreply->status), len); memcpy(scsicmd->sense_buffer, srbreply->sense_data, len); } /* * OR in the scsi status (already shifted up a bit) */ scsicmd->result |= le32_to_cpu(srbreply->scsi_status); fib_complete(fibptr); fib_free(fibptr); aac_io_done(scsicmd); } /** * * aac_send_scb_fib * @scsicmd: the scsi command block * * This routine will form a FIB and fill in the aac_srb from the * scsicmd passed in. */ static int aac_send_srb_fib(Scsi_Cmnd* scsicmd) { struct fib* cmd_fibcontext; struct aac_dev* dev; int status; struct aac_srb *srbcmd; u16 fibsize; u32 flag; u32 timeout; if( scsicmd->target > 15 || scsicmd->lun > 7) { scsicmd->result = DID_NO_CONNECT << 16; __aac_io_done(scsicmd); return 0; } dev = (struct aac_dev *)scsicmd->host->hostdata; switch(scsicmd->sc_data_direction){ case SCSI_DATA_WRITE: flag = SRB_DataOut; break; case SCSI_DATA_UNKNOWN: flag = SRB_DataIn | SRB_DataOut; break; case SCSI_DATA_READ: flag = SRB_DataIn; break; case SCSI_DATA_NONE: default: flag = SRB_NoDataXfer; break; } /* * Allocate and initialize a Fib then setup a BlockWrite command */ if (!(cmd_fibcontext = fib_alloc(dev))) { scsicmd->result = DID_ERROR << 16; __aac_io_done(scsicmd); return -1; } fib_init(cmd_fibcontext); srbcmd = (struct aac_srb*) fib_data(cmd_fibcontext); srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); srbcmd->channel = cpu_to_le32(aac_logical_to_phys(scsicmd->channel)); srbcmd->target = cpu_to_le32(scsicmd->target); srbcmd->lun = cpu_to_le32(scsicmd->lun); srbcmd->flags = cpu_to_le32(flag); timeout = (scsicmd->timeout-jiffies)/HZ; if(timeout == 0){ timeout = 1; } srbcmd->timeout = cpu_to_le32(timeout); // timeout in seconds srbcmd->retry_limit =cpu_to_le32(0); // Obsolete parameter srbcmd->cdb_size = cpu_to_le32(scsicmd->cmd_len); if( dev->pae_support ==1 ) { aac_build_sg64(scsicmd, (struct sgmap64*) &srbcmd->sg); srbcmd->count = cpu_to_le32(scsicmd->request_bufflen); memset(srbcmd->cdb, 0, sizeof(srbcmd->cdb)); memcpy(srbcmd->cdb, scsicmd->cmnd, scsicmd->cmd_len); /* * Build Scatter/Gather list */ fibsize = sizeof (struct aac_srb) - sizeof (struct sgentry) + ((srbcmd->sg.count & 0xff) * sizeof (struct sgentry64)); /* * Now send the Fib to the adapter */ status = fib_send(ScsiPortCommand64, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) aac_srb_callback, (void *) scsicmd); } else { aac_build_sg(scsicmd, (struct sgmap*)&srbcmd->sg); srbcmd->count = cpu_to_le32(scsicmd->request_bufflen); memset(srbcmd->cdb, 0, sizeof(srbcmd->cdb)); memcpy(srbcmd->cdb, scsicmd->cmnd, scsicmd->cmd_len); /* * Build Scatter/Gather list */ fibsize = sizeof (struct aac_srb) + (((srbcmd->sg.count & 0xff) - 1) * sizeof (struct sgentry)); /* * Now send the Fib to the adapter */ status = fib_send(ScsiPortCommand, cmd_fibcontext, fibsize, FsaNormal, 0, 1, (fib_callback) aac_srb_callback, (void *) scsicmd); } /* * Check that the command queued to the controller */ if (status == -EINPROGRESS){ return 0; } printk(KERN_WARNING "aac_srb: fib_send failed with status: %d\n", status); /* * For some reason, the Fib didn't queue, return QUEUE_FULL */ scsicmd->result = DID_OK << 16 | COMMAND_COMPLETE << 8 | QUEUE_FULL; __aac_io_done(scsicmd); fib_complete(cmd_fibcontext); fib_free(cmd_fibcontext); return -1; } static unsigned long aac_build_sg(Scsi_Cmnd* scsicmd, struct sgmap* psg) { struct aac_dev *dev; unsigned long byte_count = 0; dev = (struct aac_dev *)scsicmd->host->hostdata; // Get rid of old data psg->count = cpu_to_le32(0); psg->sg[0].addr = cpu_to_le32(NULL); psg->sg[0].count = cpu_to_le32(0); if (scsicmd->use_sg) { struct scatterlist *sg; int i; int sg_count; sg = (struct scatterlist *) scsicmd->request_buffer; sg_count = pci_map_sg(dev->pdev, sg, scsicmd->use_sg, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); psg->count = cpu_to_le32(sg_count); byte_count = 0; for (i = 0; i < sg_count; i++) { psg->sg[i].addr = cpu_to_le32(sg_dma_address(sg)); psg->sg[i].count = cpu_to_le32(sg_dma_len(sg)); byte_count += sg_dma_len(sg); sg++; } /* hba wants the size to be exact */ if(byte_count > scsicmd->request_bufflen){ psg->sg[i-1].count -= (byte_count - scsicmd->request_bufflen); byte_count = scsicmd->request_bufflen; } /* Check for command underflow */ if(scsicmd->underflow && (byte_count < scsicmd->underflow)){ printk(KERN_WARNING"aacraid: cmd len %08lX cmd underflow %08X\n", byte_count, scsicmd->underflow); } } else if(scsicmd->request_bufflen) { dma_addr_t addr; addr = pci_map_single(dev->pdev, scsicmd->request_buffer, scsicmd->request_bufflen, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); psg->count = cpu_to_le32(1); psg->sg[0].addr = cpu_to_le32(addr); psg->sg[0].count = cpu_to_le32(scsicmd->request_bufflen); /* Cast to pointer from integer of different size */ scsicmd->SCp.ptr = (void *)addr; byte_count = scsicmd->request_bufflen; } return byte_count; } static unsigned long aac_build_sg64(Scsi_Cmnd* scsicmd, struct sgmap64* psg) { struct aac_dev *dev; unsigned long byte_count = 0; u64 le_addr; dev = (struct aac_dev *)scsicmd->host->hostdata; // Get rid of old data psg->count = cpu_to_le32(0); psg->sg[0].addr[0] = cpu_to_le32(NULL); psg->sg[0].addr[1] = cpu_to_le32(NULL); psg->sg[0].count = cpu_to_le32(0); if (scsicmd->use_sg) { struct scatterlist *sg; int i; int sg_count; sg = (struct scatterlist *) scsicmd->request_buffer; sg_count = pci_map_sg(dev->pdev, sg, scsicmd->use_sg, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); psg->count = cpu_to_le32(sg_count); byte_count = 0; for (i = 0; i < sg_count; i++) { le_addr = cpu_to_le64(sg_dma_address(sg)); psg->sg[i].addr[1] = (u32)(le_addr>>32); psg->sg[i].addr[0] = (u32)(le_addr & 0xffffffff); psg->sg[i].count = cpu_to_le32(sg_dma_len(sg)); byte_count += sg_dma_len(sg); sg++; } /* hba wants the size to be exact */ if(byte_count > scsicmd->request_bufflen){ psg->sg[i-1].count -= (byte_count - scsicmd->request_bufflen); byte_count = scsicmd->request_bufflen; } /* Check for command underflow */ if(scsicmd->underflow && (byte_count < scsicmd->underflow)){ printk(KERN_WARNING"aacraid: cmd len %08lX cmd underflow %08X\n", byte_count, scsicmd->underflow); } } else if(scsicmd->request_bufflen) { dma_addr_t addr; addr = pci_map_single(dev->pdev, scsicmd->request_buffer, scsicmd->request_bufflen, scsi_to_pci_dma_dir(scsicmd->sc_data_direction)); psg->count = cpu_to_le32(1); le_addr = cpu_to_le64(addr); psg->sg[0].addr[1] = (u32)(le_addr>>32); psg->sg[0].addr[0] = (u32)(le_addr & 0xffffffff); psg->sg[0].count = cpu_to_le32(scsicmd->request_bufflen); /* Cast to pointer from integer of different size */ scsicmd->SCp.ptr = (void *)addr; byte_count = scsicmd->request_bufflen; } return byte_count; } struct aac_srb_status_info { u32 status; char *str; }; static struct aac_srb_status_info srb_status_info[] = { { SRB_STATUS_PENDING, "Pending Status"}, { SRB_STATUS_SUCCESS, "Success"}, { SRB_STATUS_ABORTED, "Aborted Command"}, { SRB_STATUS_ABORT_FAILED, "Abort Failed"}, { SRB_STATUS_ERROR, "Error Event"}, { SRB_STATUS_BUSY, "Device Busy"}, { SRB_STATUS_INVALID_REQUEST, "Invalid Request"}, { SRB_STATUS_INVALID_PATH_ID, "Invalid Path ID"}, { SRB_STATUS_NO_DEVICE, "No Device"}, { SRB_STATUS_TIMEOUT, "Timeout"}, { SRB_STATUS_SELECTION_TIMEOUT, "Selection Timeout"}, { SRB_STATUS_COMMAND_TIMEOUT, "Command Timeout"}, { SRB_STATUS_MESSAGE_REJECTED, "Message Rejected"}, { SRB_STATUS_BUS_RESET, "Bus Reset"}, { SRB_STATUS_PARITY_ERROR, "Parity Error"}, { SRB_STATUS_REQUEST_SENSE_FAILED,"Request Sense Failed"}, { SRB_STATUS_NO_HBA, "No HBA"}, { SRB_STATUS_DATA_OVERRUN, "Data Overrun/Data Underrun"}, { SRB_STATUS_UNEXPECTED_BUS_FREE,"Unexpected Bus Free"}, { SRB_STATUS_PHASE_SEQUENCE_FAILURE,"Phase Error"}, { SRB_STATUS_BAD_SRB_BLOCK_LENGTH,"Bad Srb Block Length"}, { SRB_STATUS_REQUEST_FLUSHED, "Request Flushed"}, { SRB_STATUS_DELAYED_RETRY, "Delayed Retry"}, { SRB_STATUS_INVALID_LUN, "Invalid LUN"}, { SRB_STATUS_INVALID_TARGET_ID, "Invalid TARGET ID"}, { SRB_STATUS_BAD_FUNCTION, "Bad Function"}, { SRB_STATUS_ERROR_RECOVERY, "Error Recovery"}, { SRB_STATUS_NOT_STARTED, "Not Started"}, { SRB_STATUS_NOT_IN_USE, "Not In Use"}, { SRB_STATUS_FORCE_ABORT, "Force Abort"}, { SRB_STATUS_DOMAIN_VALIDATION_FAIL,"Domain Validation Failure"}, { 0xff, "Unknown Error"} }; char *aac_get_status_string(u32 status) { int i; for(i=0; i < (sizeof(srb_status_info)/sizeof(struct aac_srb_status_info)); i++ ){ if(srb_status_info[i].status == status){ return srb_status_info[i].str; } } return "Bad Status Code"; }
sensysnetworks/uClinux
linux-2.4.x/drivers/scsi/aacraid/aachba.c
C
gpl-2.0
53,599
/** * Product: Posterita Web-Based POS and Adempiere Plugin * Copyright (C) 2007 Posterita Ltd * This file is part of POSterita * * POSterita is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Created on Sep 11, 2006 by ashley * */ /** @author ashley */ package org.posterita.beans; import java.math.BigDecimal; import org.compiere.util.Env; public class CashSummaryBean extends UDIBean { public CashSummaryBean() { this.setBankAcctTransferAmount(Env.ZERO); this.setChargeAmount(Env.ZERO); this.setDifferenceAmount(Env.ZERO); this.setGeneralExpenseAmount(Env.ZERO); this.setGeneralReceiptsAmount(Env.ZERO); this.setInvoiceAmount(Env.ZERO); } public Integer getCashId() { return cashId; } public void setCashId(Integer cashId) { this.cashId = cashId; } public BigDecimal getBankAcctTransferAmount() { return bankAcctTransferAmount; } public void setBankAcctTransferAmount(BigDecimal bankAcctTransferAmount) { this.bankAcctTransferAmount = bankAcctTransferAmount; } public BigDecimal getChargeAmount() { return chargeAmount; } public void setChargeAmount(BigDecimal chargeAmount) { this.chargeAmount = chargeAmount; } public BigDecimal getDifferenceAmount() { return differenceAmount; } public void setDifferenceAmount(BigDecimal differenceAmount) { this.differenceAmount = differenceAmount; } public BigDecimal getGeneralExpenseAmount() { return generalExpenseAmount; } public void setGeneralExpenseAmount(BigDecimal generalExpenseAmount) { this.generalExpenseAmount = generalExpenseAmount; } public BigDecimal getGeneralReceiptsAmount() { return generalReceiptsAmount; } public void setGeneralReceiptsAmount(BigDecimal generalReceiptsAmount) { this.generalReceiptsAmount = generalReceiptsAmount; } public BigDecimal getInvoiceAmount() { return invoiceAmount; } public void setInvoiceAmount(BigDecimal invoiceAmount) { this.invoiceAmount = invoiceAmount; } /** * @return The beginingBalance */ public BigDecimal getBeginingBalance() { return beginingBalance; } /** * @param beginingBalance The beginingBalance to set */ public void setBeginingBalance(BigDecimal beginingBalance) { this.beginingBalance = beginingBalance; } /** * @return The endingBalance */ public BigDecimal getEndingBalance() { return endingBalance; } /** * @param endingBalance The endingBalance to set */ public void setEndingBalance(BigDecimal endingBalance) { this.endingBalance = endingBalance; } }
erpcya/adempierePOS
posterita/posterita/src/main/org/posterita/beans/CashSummaryBean.java
Java
gpl-2.0
3,298