repo_name
string
path
string
copies
string
size
string
content
string
license
string
firerszd/kbengine
kbe/src/lib/dependencies/openssl/crypto/bio/bio_lib.c
116
13083
/* crypto/bio/bio_lib.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <errno.h> #include <openssl/crypto.h> #include "cryptlib.h" #include <openssl/bio.h> #include <openssl/stack.h> BIO *BIO_new(BIO_METHOD *method) { BIO *ret=NULL; ret=(BIO *)OPENSSL_malloc(sizeof(BIO)); if (ret == NULL) { BIOerr(BIO_F_BIO_NEW,ERR_R_MALLOC_FAILURE); return(NULL); } if (!BIO_set(ret,method)) { OPENSSL_free(ret); ret=NULL; } return(ret); } int BIO_set(BIO *bio, BIO_METHOD *method) { bio->method=method; bio->callback=NULL; bio->cb_arg=NULL; bio->init=0; bio->shutdown=1; bio->flags=0; bio->retry_reason=0; bio->num=0; bio->ptr=NULL; bio->prev_bio=NULL; bio->next_bio=NULL; bio->references=1; bio->num_read=0L; bio->num_write=0L; CRYPTO_new_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data); if (method->create != NULL) if (!method->create(bio)) { CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data); return(0); } return(1); } int BIO_free(BIO *a) { int ret=0,i; if (a == NULL) return(0); i=CRYPTO_add(&a->references,-1,CRYPTO_LOCK_BIO); #ifdef REF_PRINT REF_PRINT("BIO",a); #endif if (i > 0) return(1); #ifdef REF_CHECK if (i < 0) { fprintf(stderr,"BIO_free, bad reference count\n"); abort(); } #endif if ((a->callback != NULL) && ((i=(int)a->callback(a,BIO_CB_FREE,NULL,0,0L,1L)) <= 0)) return(i); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, a, &a->ex_data); if ((a->method == NULL) || (a->method->destroy == NULL)) return(1); ret=a->method->destroy(a); OPENSSL_free(a); return(1); } void BIO_vfree(BIO *a) { BIO_free(a); } void BIO_clear_flags(BIO *b, int flags) { b->flags &= ~flags; } int BIO_test_flags(const BIO *b, int flags) { return (b->flags & flags); } void BIO_set_flags(BIO *b, int flags) { b->flags |= flags; } long (*BIO_get_callback(const BIO *b))(struct bio_st *,int,const char *,int, long,long) { return b->callback; } void BIO_set_callback(BIO *b, long (*cb)(struct bio_st *,int,const char *,int, long,long)) { b->callback = cb; } void BIO_set_callback_arg(BIO *b, char *arg) { b->cb_arg = arg; } char * BIO_get_callback_arg(const BIO *b) { return b->cb_arg; } const char * BIO_method_name(const BIO *b) { return b->method->name; } int BIO_method_type(const BIO *b) { return b->method->type; } int BIO_read(BIO *b, void *out, int outl) { int i; long (*cb)(BIO *,int,const char *,int,long,long); if ((b == NULL) || (b->method == NULL) || (b->method->bread == NULL)) { BIOerr(BIO_F_BIO_READ,BIO_R_UNSUPPORTED_METHOD); return(-2); } cb=b->callback; if ((cb != NULL) && ((i=(int)cb(b,BIO_CB_READ,out,outl,0L,1L)) <= 0)) return(i); if (!b->init) { BIOerr(BIO_F_BIO_READ,BIO_R_UNINITIALIZED); return(-2); } i=b->method->bread(b,out,outl); if (i > 0) b->num_read+=(unsigned long)i; if (cb != NULL) i=(int)cb(b,BIO_CB_READ|BIO_CB_RETURN,out,outl, 0L,(long)i); return(i); } int BIO_write(BIO *b, const void *in, int inl) { int i; long (*cb)(BIO *,int,const char *,int,long,long); if (b == NULL) return(0); cb=b->callback; if ((b->method == NULL) || (b->method->bwrite == NULL)) { BIOerr(BIO_F_BIO_WRITE,BIO_R_UNSUPPORTED_METHOD); return(-2); } if ((cb != NULL) && ((i=(int)cb(b,BIO_CB_WRITE,in,inl,0L,1L)) <= 0)) return(i); if (!b->init) { BIOerr(BIO_F_BIO_WRITE,BIO_R_UNINITIALIZED); return(-2); } i=b->method->bwrite(b,in,inl); if (i > 0) b->num_write+=(unsigned long)i; if (cb != NULL) i=(int)cb(b,BIO_CB_WRITE|BIO_CB_RETURN,in,inl, 0L,(long)i); return(i); } int BIO_puts(BIO *b, const char *in) { int i; long (*cb)(BIO *,int,const char *,int,long,long); if ((b == NULL) || (b->method == NULL) || (b->method->bputs == NULL)) { BIOerr(BIO_F_BIO_PUTS,BIO_R_UNSUPPORTED_METHOD); return(-2); } cb=b->callback; if ((cb != NULL) && ((i=(int)cb(b,BIO_CB_PUTS,in,0,0L,1L)) <= 0)) return(i); if (!b->init) { BIOerr(BIO_F_BIO_PUTS,BIO_R_UNINITIALIZED); return(-2); } i=b->method->bputs(b,in); if (i > 0) b->num_write+=(unsigned long)i; if (cb != NULL) i=(int)cb(b,BIO_CB_PUTS|BIO_CB_RETURN,in,0, 0L,(long)i); return(i); } int BIO_gets(BIO *b, char *in, int inl) { int i; long (*cb)(BIO *,int,const char *,int,long,long); if ((b == NULL) || (b->method == NULL) || (b->method->bgets == NULL)) { BIOerr(BIO_F_BIO_GETS,BIO_R_UNSUPPORTED_METHOD); return(-2); } cb=b->callback; if ((cb != NULL) && ((i=(int)cb(b,BIO_CB_GETS,in,inl,0L,1L)) <= 0)) return(i); if (!b->init) { BIOerr(BIO_F_BIO_GETS,BIO_R_UNINITIALIZED); return(-2); } i=b->method->bgets(b,in,inl); if (cb != NULL) i=(int)cb(b,BIO_CB_GETS|BIO_CB_RETURN,in,inl, 0L,(long)i); return(i); } int BIO_indent(BIO *b,int indent,int max) { if(indent < 0) indent=0; if(indent > max) indent=max; while(indent--) if(BIO_puts(b," ") != 1) return 0; return 1; } long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) { int i; i=iarg; return(BIO_ctrl(b,cmd,larg,(char *)&i)); } char *BIO_ptr_ctrl(BIO *b, int cmd, long larg) { char *p=NULL; if (BIO_ctrl(b,cmd,larg,(char *)&p) <= 0) return(NULL); else return(p); } long BIO_ctrl(BIO *b, int cmd, long larg, void *parg) { long ret; long (*cb)(BIO *,int,const char *,int,long,long); if (b == NULL) return(0); if ((b->method == NULL) || (b->method->ctrl == NULL)) { BIOerr(BIO_F_BIO_CTRL,BIO_R_UNSUPPORTED_METHOD); return(-2); } cb=b->callback; if ((cb != NULL) && ((ret=cb(b,BIO_CB_CTRL,parg,cmd,larg,1L)) <= 0)) return(ret); ret=b->method->ctrl(b,cmd,larg,parg); if (cb != NULL) ret=cb(b,BIO_CB_CTRL|BIO_CB_RETURN,parg,cmd, larg,ret); return(ret); } long BIO_callback_ctrl(BIO *b, int cmd, void (*fp)(struct bio_st *, int, const char *, int, long, long)) { long ret; long (*cb)(BIO *,int,const char *,int,long,long); if (b == NULL) return(0); if ((b->method == NULL) || (b->method->callback_ctrl == NULL)) { BIOerr(BIO_F_BIO_CALLBACK_CTRL,BIO_R_UNSUPPORTED_METHOD); return(-2); } cb=b->callback; if ((cb != NULL) && ((ret=cb(b,BIO_CB_CTRL,(void *)&fp,cmd,0,1L)) <= 0)) return(ret); ret=b->method->callback_ctrl(b,cmd,fp); if (cb != NULL) ret=cb(b,BIO_CB_CTRL|BIO_CB_RETURN,(void *)&fp,cmd, 0,ret); return(ret); } /* It is unfortunate to duplicate in functions what the BIO_(w)pending macros * do; but those macros have inappropriate return type, and for interfacing * from other programming languages, C macros aren't much of a help anyway. */ size_t BIO_ctrl_pending(BIO *bio) { return BIO_ctrl(bio, BIO_CTRL_PENDING, 0, NULL); } size_t BIO_ctrl_wpending(BIO *bio) { return BIO_ctrl(bio, BIO_CTRL_WPENDING, 0, NULL); } /* put the 'bio' on the end of b's list of operators */ BIO *BIO_push(BIO *b, BIO *bio) { BIO *lb; if (b == NULL) return(bio); lb=b; while (lb->next_bio != NULL) lb=lb->next_bio; lb->next_bio=bio; if (bio != NULL) bio->prev_bio=lb; /* called to do internal processing */ BIO_ctrl(b,BIO_CTRL_PUSH,0,NULL); return(b); } /* Remove the first and return the rest */ BIO *BIO_pop(BIO *b) { BIO *ret; if (b == NULL) return(NULL); ret=b->next_bio; BIO_ctrl(b,BIO_CTRL_POP,0,NULL); if (b->prev_bio != NULL) b->prev_bio->next_bio=b->next_bio; if (b->next_bio != NULL) b->next_bio->prev_bio=b->prev_bio; b->next_bio=NULL; b->prev_bio=NULL; return(ret); } BIO *BIO_get_retry_BIO(BIO *bio, int *reason) { BIO *b,*last; b=last=bio; for (;;) { if (!BIO_should_retry(b)) break; last=b; b=b->next_bio; if (b == NULL) break; } if (reason != NULL) *reason=last->retry_reason; return(last); } int BIO_get_retry_reason(BIO *bio) { return(bio->retry_reason); } BIO *BIO_find_type(BIO *bio, int type) { int mt,mask; if(!bio) return NULL; mask=type&0xff; do { if (bio->method != NULL) { mt=bio->method->type; if (!mask) { if (mt & type) return(bio); } else if (mt == type) return(bio); } bio=bio->next_bio; } while (bio != NULL); return(NULL); } BIO *BIO_next(BIO *b) { if(!b) return NULL; return b->next_bio; } void BIO_free_all(BIO *bio) { BIO *b; int ref; while (bio != NULL) { b=bio; ref=b->references; bio=bio->next_bio; BIO_free(b); /* Since ref count > 1, don't free anyone else. */ if (ref > 1) break; } } BIO *BIO_dup_chain(BIO *in) { BIO *ret=NULL,*eoc=NULL,*bio,*new; for (bio=in; bio != NULL; bio=bio->next_bio) { if ((new=BIO_new(bio->method)) == NULL) goto err; new->callback=bio->callback; new->cb_arg=bio->cb_arg; new->init=bio->init; new->shutdown=bio->shutdown; new->flags=bio->flags; /* This will let SSL_s_sock() work with stdin/stdout */ new->num=bio->num; if (!BIO_dup_state(bio,(char *)new)) { BIO_free(new); goto err; } /* copy app data */ if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_BIO, &new->ex_data, &bio->ex_data)) goto err; if (ret == NULL) { eoc=new; ret=eoc; } else { BIO_push(eoc,new); eoc=new; } } return(ret); err: if (ret != NULL) BIO_free(ret); return(NULL); } void BIO_copy_next_retry(BIO *b) { BIO_set_flags(b,BIO_get_retry_flags(b->next_bio)); b->retry_reason=b->next_bio->retry_reason; } int BIO_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) { return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, argl, argp, new_func, dup_func, free_func); } int BIO_set_ex_data(BIO *bio, int idx, void *data) { return(CRYPTO_set_ex_data(&(bio->ex_data),idx,data)); } void *BIO_get_ex_data(BIO *bio, int idx) { return(CRYPTO_get_ex_data(&(bio->ex_data),idx)); } unsigned long BIO_number_read(BIO *bio) { if(bio) return bio->num_read; return 0; } unsigned long BIO_number_written(BIO *bio) { if(bio) return bio->num_write; return 0; } IMPLEMENT_STACK_OF(BIO)
lgpl-3.0
Bang3DEngine/Bang
Compile/CompileDependencies/ThirdParty/freetype-2.4.0/builds/unix/ftsystem.c
428
15306
/***************************************************************************/ /* */ /* ftsystem.c */ /* */ /* Unix-specific FreeType low-level system interface (body). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2008 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. */ /* */ /***************************************************************************/ #include <ft2build.h> /* we use our special ftconfig.h file, not the standard one */ #include <ftconfig.h> #include FT_INTERNAL_DEBUG_H #include FT_SYSTEM_H #include FT_ERRORS_H #include FT_TYPES_H #include FT_INTERNAL_STREAM_H /* memory-mapping includes and definitions */ #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <sys/mman.h> #ifndef MAP_FILE #define MAP_FILE 0x00 #endif #ifdef MUNMAP_USES_VOIDP #define MUNMAP_ARG_CAST void * #else #define MUNMAP_ARG_CAST char * #endif #ifdef NEED_MUNMAP_DECL #ifdef __cplusplus extern "C" #else extern #endif int munmap( char* addr, int len ); #define MUNMAP_ARG_CAST char * #endif /* NEED_DECLARATION_MUNMAP */ #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> /*************************************************************************/ /* */ /* MEMORY MANAGEMENT INTERFACE */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* ft_alloc */ /* */ /* <Description> */ /* The memory allocation function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* size :: The requested size in bytes. */ /* */ /* <Return> */ /* The address of newly allocated block. */ /* */ FT_CALLBACK_DEF( void* ) ft_alloc( FT_Memory memory, long size ) { FT_UNUSED( memory ); return malloc( size ); } /*************************************************************************/ /* */ /* <Function> */ /* ft_realloc */ /* */ /* <Description> */ /* The memory reallocation function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* cur_size :: The current size of the allocated memory block. */ /* */ /* new_size :: The newly requested size in bytes. */ /* */ /* block :: The current address of the block in memory. */ /* */ /* <Return> */ /* The address of the reallocated memory block. */ /* */ FT_CALLBACK_DEF( void* ) ft_realloc( FT_Memory memory, long cur_size, long new_size, void* block ) { FT_UNUSED( memory ); FT_UNUSED( cur_size ); return realloc( block, new_size ); } /*************************************************************************/ /* */ /* <Function> */ /* ft_free */ /* */ /* <Description> */ /* The memory release function. */ /* */ /* <Input> */ /* memory :: A pointer to the memory object. */ /* */ /* block :: The address of block in memory to be freed. */ /* */ FT_CALLBACK_DEF( void ) ft_free( FT_Memory memory, void* block ) { FT_UNUSED( memory ); free( block ); } /*************************************************************************/ /* */ /* RESOURCE MANAGEMENT INTERFACE */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_io /* We use the macro STREAM_FILE for convenience to extract the */ /* system-specific stream handle from a given FreeType stream object */ #define STREAM_FILE( stream ) ( (FILE*)stream->descriptor.pointer ) /*************************************************************************/ /* */ /* <Function> */ /* ft_close_stream_by_munmap */ /* */ /* <Description> */ /* The function to close a stream which is opened by mmap. */ /* */ /* <Input> */ /* stream :: A pointer to the stream object. */ /* */ FT_CALLBACK_DEF( void ) ft_close_stream_by_munmap( FT_Stream stream ) { munmap( (MUNMAP_ARG_CAST)stream->descriptor.pointer, stream->size ); stream->descriptor.pointer = NULL; stream->size = 0; stream->base = 0; } /*************************************************************************/ /* */ /* <Function> */ /* ft_close_stream_by_free */ /* */ /* <Description> */ /* The function to close a stream which is created by ft_alloc. */ /* */ /* <Input> */ /* stream :: A pointer to the stream object. */ /* */ FT_CALLBACK_DEF( void ) ft_close_stream_by_free( FT_Stream stream ) { ft_free( NULL, stream->descriptor.pointer ); stream->descriptor.pointer = NULL; stream->size = 0; stream->base = 0; } /* documentation is in ftobjs.h */ FT_BASE_DEF( FT_Error ) FT_Stream_Open( FT_Stream stream, const char* filepathname ) { int file; struct stat stat_buf; if ( !stream ) return FT_Err_Invalid_Stream_Handle; /* open the file */ file = open( filepathname, O_RDONLY ); if ( file < 0 ) { FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " could not open `%s'\n", filepathname )); return FT_Err_Cannot_Open_Resource; } /* Here we ensure that a "fork" will _not_ duplicate */ /* our opened input streams on Unix. This is critical */ /* since it avoids some (possible) access control */ /* issues and cleans up the kernel file table a bit. */ /* */ #ifdef F_SETFD #ifdef FD_CLOEXEC (void)fcntl( file, F_SETFD, FD_CLOEXEC ); #else (void)fcntl( file, F_SETFD, 1 ); #endif /* FD_CLOEXEC */ #endif /* F_SETFD */ if ( fstat( file, &stat_buf ) < 0 ) { FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " could not `fstat' file `%s'\n", filepathname )); goto Fail_Map; } /* XXX: TODO -- real 64bit platform support */ /* */ /* `stream->size' is typedef'd to unsigned long (in */ /* freetype/ftsystem.h); `stat_buf.st_size', however, is usually */ /* typedef'd to off_t (in sys/stat.h). */ /* On some platforms, the former is 32bit and the latter is 64bit. */ /* To avoid overflow caused by fonts in huge files larger than */ /* 2GB, do a test. Temporary fix proposed by Sean McBride. */ /* */ if ( stat_buf.st_size > LONG_MAX ) { FT_ERROR(( "FT_Stream_Open: file is too big\n" )); goto Fail_Map; } else if ( stat_buf.st_size == 0 ) { FT_ERROR(( "FT_Stream_Open: zero-length file\n" )); goto Fail_Map; } /* This cast potentially truncates a 64bit to 32bit! */ stream->size = (unsigned long)stat_buf.st_size; stream->pos = 0; stream->base = (unsigned char *)mmap( NULL, stream->size, PROT_READ, MAP_FILE | MAP_PRIVATE, file, 0 ); /* on some RTOS, mmap might return 0 */ if ( (long)stream->base != -1 && stream->base != NULL ) stream->close = ft_close_stream_by_munmap; else { ssize_t total_read_count; FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " could not `mmap' file `%s'\n", filepathname )); stream->base = (unsigned char*)ft_alloc( NULL, stream->size ); if ( !stream->base ) { FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " could not `alloc' memory\n" )); goto Fail_Map; } total_read_count = 0; do { ssize_t read_count; read_count = read( file, stream->base + total_read_count, stream->size - total_read_count ); if ( read_count <= 0 ) { if ( read_count == -1 && errno == EINTR ) continue; FT_ERROR(( "FT_Stream_Open:" )); FT_ERROR(( " error while `read'ing file `%s'\n", filepathname )); goto Fail_Read; } total_read_count += read_count; } while ( (unsigned long)total_read_count != stream->size ); stream->close = ft_close_stream_by_free; } close( file ); stream->descriptor.pointer = stream->base; stream->pathname.pointer = (char*)filepathname; stream->read = 0; FT_TRACE1(( "FT_Stream_Open:" )); FT_TRACE1(( " opened `%s' (%d bytes) successfully\n", filepathname, stream->size )); return FT_Err_Ok; Fail_Read: ft_free( NULL, stream->base ); Fail_Map: close( file ); stream->base = NULL; stream->size = 0; stream->pos = 0; return FT_Err_Cannot_Open_Stream; } #ifdef FT_DEBUG_MEMORY extern FT_Int ft_mem_debug_init( FT_Memory memory ); extern void ft_mem_debug_done( FT_Memory memory ); #endif /* documentation is in ftobjs.h */ FT_BASE_DEF( FT_Memory ) FT_New_Memory( void ) { FT_Memory memory; memory = (FT_Memory)malloc( sizeof ( *memory ) ); if ( memory ) { memory->user = 0; memory->alloc = ft_alloc; memory->realloc = ft_realloc; memory->free = ft_free; #ifdef FT_DEBUG_MEMORY ft_mem_debug_init( memory ); #endif } return memory; } /* documentation is in ftobjs.h */ FT_BASE_DEF( void ) FT_Done_Memory( FT_Memory memory ) { #ifdef FT_DEBUG_MEMORY ft_mem_debug_done( memory ); #endif memory->free( memory, memory ); } /* END */
lgpl-3.0
ThreadedThinking/EInk-Street-Sign
TPS65185.c
1
2319
#include <i2c.h> enum tps_registers { TMST_VALUE, ENABLE, VADJ, VCOM1, VCOM2, INT_EN1, INT_EN2, INT1, INT2, UPSEQ0, UPSEQ1, DWNSEQ0, DWNSEQ1, TMST1, TMST2, PG, REVID }; void write_ti(uint8_t reg, uint8_t value) { uint8_t temp; while(i2c_busy()) /* wait */; *I2CCR = 0; // assume being master, thus no addres has to be set *I2CCR = I2C_MEN | I2C_MSTA | I2C_MTX; // start condition is triggered // write out address of slave *I2CDR = 0x68 << 1; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; if (*I2CSR & I2C_RXAK ) { // NO acknoledge byte received printf("*** ERROR I2C: No ack received 1\n"); } if (*I2CSR & I2C_MCF) { *I2CDR = (reg & 0xFF); // clear MIF *I2CSR &= ~I2C_MIF; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; if (*I2CSR & I2C_RXAK) { // NO acknoledge byte received printf("*** ERROR I2C: No ack received 2\n"); } } if (*I2CSR & I2C_MCF) { *I2CDR = (value & 0xFF); // clear MIF *I2CSR &= ~I2C_MIF; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; if (*I2CSR & I2C_RXAK) { // NO acknoledge byte received printf("*** ERROR I2C: No ack received 2\n"); } } *I2CCR &= ~I2C_MSTA; // stop condition //*I2CCR = 0; } void read_ti(uint8_t reg) { uint8_t temp; while(i2c_busy()) /* wait */; // assume being master, thus no addres has to be set *I2CCR |= I2C_MSTA | I2C_MTX | I2C_TXAK; // start condition is triggered // write out address of slave *I2CDR = 0x68 <<1; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; *I2CSR &= ~I2C_MIF; if (*I2CSR & I2C_RXAK ) { // NO acknoledge byte received printf("*** ERROR I2C: No ack received 1\n"); } *I2CDR = (reg & 0xFF); while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; *I2CSR &= ~I2C_MIF; if (*I2CSR & I2C_RXAK) { // NO acknoledge byte received printf("*** ERROR I2C: No ack received 2\n"); } *I2CCR |= I2C_RSTA; // write out address of slave *I2CDR = ((0x68) <<1) | 0x01; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; *I2CSR &= ~I2C_MIF; *I2CCR &= ~I2C_MTX; //*I2CCR &= ~I2C_TXAK; temp = *I2CDR; while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) /*wait*/; *I2CSR &= ~I2C_MIF; *I2CCR &= ~I2C_MSTA; // stop condition temp = *I2CDR; //printf("0x%x\n",temp); }
unlicense
liasica/Karabiner_CN
src/core/kext/KeyCode.cpp
1
6569
#include "Config.hpp" #include "KeyCode.hpp" #include "KeyCodeModifierFlagPairs.hpp" namespace org_pqrs_Karabiner { #include "../../../src/bridge/output/include.kext.keycode.cpp" // ------------------------------------------------------------ bool EventType::isKeyDownOrModifierDown(KeyCode key, Flags flags) const { if (*this == EventType::DOWN) return true; if (*this == EventType::MODIFY) { return flags.isOn(key.getModifierFlag()); } return false; } bool KeyCode::FNKeyHack::remap(KeyCode& key, Flags flags, EventType eventType, bool& active, KeyCode fromKeyCode, KeyCode toKeyCode) { if (key != fromKeyCode) return false; bool isKeyDown = eventType.isKeyDownOrModifierDown(key, flags); if (isKeyDown) { if (!flags.isOn(ModifierFlag::FN)) return false; active = true; } else { if (!active) return false; active = false; } key = toKeyCode; return true; } namespace { KeyCode::FNKeyHack fnkeyhack[] = { KeyCode::FNKeyHack(KeyCode::PAGEUP, KeyCode::CURSOR_UP), KeyCode::FNKeyHack(KeyCode::PAGEDOWN, KeyCode::CURSOR_DOWN), KeyCode::FNKeyHack(KeyCode::HOME, KeyCode::CURSOR_LEFT), KeyCode::FNKeyHack(KeyCode::END, KeyCode::CURSOR_RIGHT), KeyCode::FNKeyHack(KeyCode::ENTER, KeyCode::RETURN), KeyCode::FNKeyHack(KeyCode::FORWARD_DELETE, KeyCode::DELETE), }; } void KeyCode::normalizeKey(KeyCode& key, Flags& flags, EventType eventType, KeyboardType keyboardType) { // We can drop NUMPAD flags, because we'll set these flags at reverseNormalizeKey. flags.stripNUMPAD(); for (unsigned int i = 0; i < sizeof(fnkeyhack) / sizeof(fnkeyhack[0]); ++i) { if (fnkeyhack[i].normalize(key, flags, eventType)) break; } } void KeyCode::reverseNormalizeKey(KeyCode& key, Flags& flags, EventType eventType, KeyboardType keyboardType) { for (unsigned int i = 0; i < sizeof(fnkeyhack) / sizeof(fnkeyhack[0]); ++i) { if (fnkeyhack[i].reverse(key, flags, eventType)) break; } // ------------------------------------------------------------ // Don't add ModifierFlag::FN automatically for F-keys, PageUp/PageDown/Home/End and Forward Delete. // // PageUp/PageDown/Home/End and Forward Delete are entered by fn+arrow, fn+delete normally, // And, from Cocoa Application, F-keys and PageUp,... keys have Fn modifier // even if Fn key is not pressed actually. // So, it's natural adding ModifierFlag::FN to these keys. // However, there is a reason we must not add ModifierFlag::FN to there keys. // // Mission Control may have "fn" as shortcut key. // If we add ModifierFlag::FN here, // "XXX to PageUp" launches Mission Control because Mission Control recognizes fn key was pressed. // // It's not intended behavior from users. // Therefore, we don't add ModifierFlag::FN for these keys. // ------------------------------------------------------------ // set ModifierFlag::NUMPAD flags.stripNUMPAD(); // Note: KEYPAD_CLEAR, KEYPAD_COMMA have no ModifierFlag::NUMPAD bit. if (key == KeyCode::KEYPAD_0 || key == KeyCode::KEYPAD_1 || key == KeyCode::KEYPAD_2 || key == KeyCode::KEYPAD_3 || key == KeyCode::KEYPAD_4 || key == KeyCode::KEYPAD_5 || key == KeyCode::KEYPAD_6 || key == KeyCode::KEYPAD_7 || key == KeyCode::KEYPAD_8 || key == KeyCode::KEYPAD_9 || key == KeyCode::KEYPAD_DOT || key == KeyCode::KEYPAD_MULTIPLY || key == KeyCode::KEYPAD_PLUS || key == KeyCode::KEYPAD_SLASH || key == KeyCode::KEYPAD_MINUS || key == KeyCode::KEYPAD_EQUAL) { flags.add(ModifierFlag::NUMPAD); } if (key == KeyCode::CURSOR_UP || key == KeyCode::CURSOR_DOWN || key == KeyCode::CURSOR_LEFT || key == KeyCode::CURSOR_RIGHT) { flags.add(ModifierFlag::NUMPAD); } } KeyCode ModifierFlag::getKeyCode(void) const { return KeyCodeModifierFlagPairs::getKeyCode(*this, KeyCodeModifierFlagPairs::KeyCodeType::KEYCODE); } unsigned int ModifierFlag::getRawBits(void) const { if (*this == ModifierFlag::CAPSLOCK) { return 0x10000; } if (*this == ModifierFlag::SHIFT_L) { return 0x20002; } if (*this == ModifierFlag::SHIFT_R) { return 0x20004; } if (*this == ModifierFlag::CONTROL_L) { return 0x40001; } if (*this == ModifierFlag::CONTROL_R) { return 0x42000; } if (*this == ModifierFlag::OPTION_L) { return 0x80020; } if (*this == ModifierFlag::OPTION_R) { return 0x80040; } if (*this == ModifierFlag::COMMAND_L) { return 0x100008; } if (*this == ModifierFlag::COMMAND_R) { return 0x100010; } if (*this == ModifierFlag::NUMPAD) { return 0x200000; } if (*this == ModifierFlag::FN) { return 0x800000; } return 0; } Flags& Flags::remove(ModifierFlag flag) { // We consider the following case. // (ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R).remove(ModifierFlag::SHIFT_L). // // The value of SHIFT_L and SHIFT_R is below. // // ModifierFlag::SHIFT_L : 0x20002 // ModifierFlag::SHIFT_R : 0x20004 // // So, the correct value of above case is 0x20004 (SHIFT_R). // // If we remove bits simple way (value_ &= ~flags), // the result value becomes 0x00004. It's not right. // // Therefore, we save the old value, and restore the necessary bits from it. // Flags old = *this; // keep ModifierFlag::NUMPAD. value_ &= ~(flag.getRawBits()); auto& pairs = KeyCodeModifierFlagPairs::getPairs(); for (size_t i = 0; i < pairs.size(); ++i) { ModifierFlag f = pairs[i].getModifierFlag(); if (f == flag) continue; if (!old.isOn(f)) continue; value_ |= f.getRawBits(); } return *this; } ModifierFlag KeyCode::getModifierFlag(void) const { return KeyCodeModifierFlagPairs::getModifierFlag(*this, KeyCodeModifierFlagPairs::KeyCodeType::KEYCODE); } bool ConsumerKeyCode::isRepeatable(void) const { if (*this == ConsumerKeyCode::BRIGHTNESS_DOWN) { return true; } if (*this == ConsumerKeyCode::BRIGHTNESS_UP) { return true; } if (*this == ConsumerKeyCode::KEYBOARDLIGHT_LOW) { return true; } if (*this == ConsumerKeyCode::KEYBOARDLIGHT_HIGH) { return true; } if (*this == ConsumerKeyCode::MUSIC_PREV) { return true; } if (*this == ConsumerKeyCode::MUSIC_NEXT) { return true; } if (*this == ConsumerKeyCode::VOLUME_DOWN) { return true; } if (*this == ConsumerKeyCode::VOLUME_UP) { return true; } return false; } bool DeviceVendor::isApple(void) const { if (*this == DeviceVendor::APPLE_COMPUTER || *this == DeviceVendor::Apple_Bluetooth) { return true; } return false; } }
unlicense
MichaelClerx/libcellml
src/entity.cpp
1
2025
/* Copyright libCellML Contributors 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 "libcellml/entity.h" #include "libcellml/component.h" #include "libcellml/componententity.h" namespace libcellml { using EntityWeakPtr = std::weak_ptr<Entity>; /**< Type definition for weak entity pointer. */ /** * @brief The Entity::EntityImpl struct. * * The private implementation for the Entity class. */ struct Entity::EntityImpl { EntityWeakPtr mParent; /**< Pointer to parent. */ std::string mId; /**< String document identifier for this entity. */ }; Entity::Entity() : mPimpl(new EntityImpl()) { mPimpl->mParent = {}; } Entity::~Entity() { delete mPimpl; } void Entity::setId(const std::string &id) { mPimpl->mId = id; } std::string Entity::id() const { return mPimpl->mId; } EntityPtr Entity::parent() const { return mPimpl->mParent.lock(); } void Entity::setParent(const EntityPtr &parent) { mPimpl->mParent = parent; } void Entity::removeParent() { mPimpl->mParent = {}; } bool Entity::hasParent() const { bool hasParent = false; EntityPtr parent = mPimpl->mParent.lock(); if (parent) { hasParent = true; } return hasParent; } bool Entity::hasAncestor(const EntityPtr &entity) const { bool hasAncestor = false; EntityPtr parent = mPimpl->mParent.lock(); if (parent == entity) { hasAncestor = true; } else if (parent) { hasAncestor = parent->hasAncestor(entity); } return hasAncestor; } } // namespace libcellml
apache-2.0
zherczeg/jerryscript
jerry-core/ecma/builtin-objects/ecma-builtin-global.c
1
22701
/* Copyright JS Foundation and other contributors, http://js.foundation * * 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 "ecma-alloc.h" #include "ecma-builtins.h" #include "ecma-conversion.h" #include "ecma-eval.h" #include "ecma-exceptions.h" #include "ecma-gc.h" #include "ecma-globals.h" #include "ecma-helpers.h" #include "jrt.h" #include "lit-char-helpers.h" #include "lit-magic-strings.h" #include "lit-strings.h" #include "vm.h" #include "jcontext.h" #include "jrt-libc-includes.h" #include "jrt-bit-fields.h" #define ECMA_BUILTINS_INTERNAL #include "ecma-builtins-internal.h" /** * This object has a custom dispatch function. */ #define BUILTIN_CUSTOM_DISPATCH /** * List of built-in routine identifiers. */ enum { ECMA_GLOBAL_ROUTINE_START = 0, /* Note: these 5 routine ids must be in this order */ ECMA_GLOBAL_IS_NAN, ECMA_GLOBAL_IS_FINITE, ECMA_GLOBAL_EVAL, ECMA_GLOBAL_PARSE_INT, ECMA_GLOBAL_PARSE_FLOAT, ECMA_GLOBAL_DECODE_URI, ECMA_GLOBAL_DECODE_URI_COMPONENT, ECMA_GLOBAL_ENCODE_URI, ECMA_GLOBAL_ENCODE_URI_COMPONENT, ECMA_GLOBAL_ESCAPE, ECMA_GLOBAL_UNESCAPE, }; #define BUILTIN_INC_HEADER_NAME "ecma-builtin-global.inc.h" #define BUILTIN_UNDERSCORED_ID global #include "ecma-builtin-internal-routines-template.inc.h" /** \addtogroup ecma ECMA * @{ * * \addtogroup ecmabuiltins * @{ * * \addtogroup global ECMA Global object built-in * @{ */ /** * The Global object's 'eval' routine * * See also: * ECMA-262 v5, 15.1.2.1 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_eval (ecma_value_t x) /**< routine's first argument */ { if (JERRY_UNLIKELY (!ecma_is_value_string (x))) { /* step 1 */ return ecma_copy_value (x); } uint32_t parse_opts = vm_is_direct_eval_form_call () ? ECMA_PARSE_DIRECT_EVAL : ECMA_PARSE_NO_OPTS; /* See also: ECMA-262 v5, 10.1.1 */ if (parse_opts && vm_is_strict_mode ()) { JERRY_ASSERT (parse_opts & ECMA_PARSE_DIRECT_EVAL); parse_opts |= ECMA_PARSE_STRICT_MODE; } #if JERRY_ESNEXT if (vm_is_direct_eval_form_call ()) { parse_opts |= ECMA_GET_LOCAL_PARSE_OPTS (); } #endif /* JERRY_ESNEXT */ /* steps 2 to 8 */ return ecma_op_eval (x, parse_opts); } /* ecma_builtin_global_object_eval */ /** * The Global object's 'isNaN' routine * * See also: * ECMA-262 v5, 15.1.2.4 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_is_nan (ecma_number_t arg_num) /**< routine's first argument */ { return ecma_make_boolean_value (ecma_number_is_nan (arg_num)); } /* ecma_builtin_global_object_is_nan */ /** * The Global object's 'isFinite' routine * * See also: * ECMA-262 v5, 15.1.2.5 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_is_finite (ecma_number_t arg_num) /**< routine's first argument */ { bool is_finite = !(ecma_number_is_nan (arg_num) || ecma_number_is_infinity (arg_num)); return ecma_make_boolean_value (is_finite); } /* ecma_builtin_global_object_is_finite */ /** * Helper function to check whether a character is in a character bitset. * * @return true if the character is in the character bitset. */ static bool ecma_builtin_global_object_character_is_in (uint32_t character, /**< character */ const uint8_t *bitset) /**< character set */ { JERRY_ASSERT (character < 128); return (bitset[character >> 3] & (1u << (character & 0x7))) != 0; } /* ecma_builtin_global_object_character_is_in */ /** * Unescaped URI characters bitset: * One bit for each character between 0 - 127. * Bit is set if the character is in the unescaped URI set. */ static const uint8_t unescaped_uri_set[16] = { 0x0, 0x0, 0x0, 0x0, 0xda, 0xff, 0xff, 0xaf, 0xff, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x47 }; /** * Unescaped URI component characters bitset: * One bit for each character between 0 - 127. * Bit is set if the character is in the unescaped component URI set. */ static const uint8_t unescaped_uri_component_set[16] = { 0x0, 0x0, 0x0, 0x0, 0x82, 0x67, 0xff, 0x3, 0xfe, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x47 }; /** * Format is a percent sign followed by two hex digits. */ #define URI_ENCODED_BYTE_SIZE (3) /** * The Global object's 'decodeURI' and 'decodeURIComponent' routines * * See also: * ECMA-262 v5, 15.1.3.1 * ECMA-262 v5, 15.1.3.2 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_decode_uri_helper (lit_utf8_byte_t *input_start_p, /**< routine's first argument's * string buffer */ lit_utf8_size_t input_size, /**< routine's first argument's * string buffer's size */ const uint8_t *reserved_uri_bitset) /**< reserved characters bitset */ { lit_utf8_byte_t *input_char_p = input_start_p; lit_utf8_byte_t *input_end_p = input_start_p + input_size; ecma_stringbuilder_t builder = ecma_stringbuilder_create (); while (input_char_p < input_end_p) { if (*input_char_p != '%') { ecma_stringbuilder_append_byte (&builder, *input_char_p++); continue; } uint32_t hex_value = lit_char_hex_lookup (input_char_p + 1, input_end_p, 2); if (hex_value == UINT32_MAX) { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Invalid hexadecimal value")); } ecma_char_t decoded_byte = (ecma_char_t) hex_value; input_char_p += URI_ENCODED_BYTE_SIZE; if (decoded_byte <= LIT_UTF8_1_BYTE_CODE_POINT_MAX) { if (ecma_builtin_global_object_character_is_in (decoded_byte, reserved_uri_bitset) && !ecma_builtin_global_object_character_is_in (decoded_byte, unescaped_uri_component_set)) { ecma_stringbuilder_append_char (&builder, LIT_CHAR_PERCENT); input_char_p -= 2; } else { ecma_stringbuilder_append_byte (&builder, (lit_utf8_byte_t) decoded_byte); } } else { uint32_t bytes_count; if ((decoded_byte & LIT_UTF8_2_BYTE_MASK) == LIT_UTF8_2_BYTE_MARKER) { bytes_count = 2; } else if ((decoded_byte & LIT_UTF8_3_BYTE_MASK) == LIT_UTF8_3_BYTE_MARKER) { bytes_count = 3; } else if ((decoded_byte & LIT_UTF8_4_BYTE_MASK) == LIT_UTF8_4_BYTE_MARKER) { bytes_count = 4; } else { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Invalid UTF8 character")); } lit_utf8_byte_t octets[LIT_UTF8_MAX_BYTES_IN_CODE_POINT]; octets[0] = (lit_utf8_byte_t) decoded_byte; bool is_valid = true; for (uint32_t i = 1; i < bytes_count; i++) { if (input_char_p >= input_end_p || *input_char_p != '%') { is_valid = false; break; } else { hex_value = lit_char_hex_lookup (input_char_p + 1, input_end_p, 2); if (hex_value == UINT32_MAX || (hex_value & LIT_UTF8_EXTRA_BYTE_MASK) != LIT_UTF8_EXTRA_BYTE_MARKER) { is_valid = false; break; } input_char_p += URI_ENCODED_BYTE_SIZE; octets[i] = (lit_utf8_byte_t) hex_value; } } if (!is_valid || !lit_is_valid_utf8_string (octets, bytes_count, true)) { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Invalid UTF8 string")); } lit_code_point_t cp; lit_read_code_point_from_utf8 (octets, bytes_count, &cp); if (lit_is_code_point_utf16_high_surrogate (cp) || lit_is_code_point_utf16_low_surrogate (cp)) { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Invalid UTF8 codepoint")); } lit_utf8_byte_t result_chars[LIT_CESU8_MAX_BYTES_IN_CODE_POINT]; lit_utf8_size_t cp_size = lit_code_point_to_cesu8 (cp, result_chars); ecma_stringbuilder_append_raw (&builder, result_chars, cp_size); } } return ecma_make_string_value (ecma_stringbuilder_finalize (&builder)); } /* ecma_builtin_global_object_decode_uri_helper */ /** * Helper function to encode byte as hexadecimal values. */ static void ecma_builtin_global_object_byte_to_hex (lit_utf8_byte_t *dest_p, /**< destination pointer */ uint32_t byte) /**< value */ { JERRY_ASSERT (byte < 256); dest_p[0] = LIT_CHAR_PERCENT; ecma_char_t hex_digit = (ecma_char_t) (byte >> 4); dest_p[1] = (lit_utf8_byte_t) ((hex_digit > 9) ? (hex_digit + ('A' - 10)) : (hex_digit + '0')); hex_digit = (lit_utf8_byte_t) (byte & 0xf); dest_p[2] = (lit_utf8_byte_t) ((hex_digit > 9) ? (hex_digit + ('A' - 10)) : (hex_digit + '0')); } /* ecma_builtin_global_object_byte_to_hex */ /** * The Global object's 'encodeURI' and 'encodeURIComponent' routines * * See also: * ECMA-262 v5, 15.1.3.3 * ECMA-262 v5, 15.1.3.4 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_encode_uri_helper (lit_utf8_byte_t *input_start_p, /**< routine's first argument's * string buffer */ lit_utf8_size_t input_size, /**< routine's first argument's * string buffer's size */ const uint8_t *unescaped_uri_bitset_p) /**< unescaped bitset */ { lit_utf8_byte_t *input_char_p = input_start_p; const lit_utf8_byte_t *input_end_p = input_start_p + input_size; ecma_char_t ch; ecma_stringbuilder_t builder = ecma_stringbuilder_create (); lit_utf8_byte_t octets[LIT_UTF8_MAX_BYTES_IN_CODE_POINT]; memset (octets, LIT_BYTE_NULL, LIT_UTF8_MAX_BYTES_IN_CODE_POINT); while (input_char_p < input_end_p) { input_char_p += lit_read_code_unit_from_cesu8 (input_char_p, &ch); if (lit_is_code_point_utf16_low_surrogate (ch)) { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Unicode surrogate pair missing")); } lit_code_point_t cp = ch; if (lit_is_code_point_utf16_high_surrogate (ch)) { if (input_char_p == input_end_p) { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Unicode surrogate pair missing")); } ecma_char_t next_ch; lit_utf8_size_t read_size = lit_read_code_unit_from_cesu8 (input_char_p, &next_ch); if (lit_is_code_point_utf16_low_surrogate (next_ch)) { cp = lit_convert_surrogate_pair_to_code_point (ch, next_ch); input_char_p += read_size; } else { ecma_stringbuilder_destroy (&builder); return ecma_raise_uri_error (ECMA_ERR_MSG ("Unicode surrogate pair missing")); } } lit_utf8_size_t utf_size = lit_code_point_to_utf8 (cp, octets); lit_utf8_byte_t result_chars[URI_ENCODED_BYTE_SIZE]; if (utf_size == 1) { if (ecma_builtin_global_object_character_is_in (octets[0], unescaped_uri_bitset_p)) { ecma_stringbuilder_append_byte (&builder, octets[0]); } else { ecma_builtin_global_object_byte_to_hex (result_chars, octets[0]); ecma_stringbuilder_append_raw (&builder, result_chars, URI_ENCODED_BYTE_SIZE); } } else { for (uint32_t i = 0; i < utf_size; i++) { JERRY_ASSERT (utf_size <= LIT_UTF8_MAX_BYTES_IN_CODE_POINT); ecma_builtin_global_object_byte_to_hex (result_chars, octets[i]); ecma_stringbuilder_append_raw (&builder, result_chars, URI_ENCODED_BYTE_SIZE); } } } return ecma_make_string_value (ecma_stringbuilder_finalize (&builder)); } /* ecma_builtin_global_object_encode_uri_helper */ #if JERRY_BUILTIN_ANNEXB /** * Maximum value of a byte. */ #define ECMA_ESCAPE_MAXIMUM_BYTE_VALUE (255) /** * Format is a percent sign followed by lowercase u and four hex digits. */ #define ECMA_ESCAPE_ENCODED_UNICODE_CHARACTER_SIZE (6) /** * Escape characters bitset: * One bit for each character between 0 - 127. * Bit is set if the character does not need to be converted to %xx form. * These characters are: a-z A-Z 0-9 @ * _ + - . / */ static const uint8_t ecma_escape_set[16] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0xec, 0xff, 0x3, 0xff, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x7 }; /** * The Global object's 'escape' routine * * See also: * ECMA-262 v5, B.2.1 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_escape (lit_utf8_byte_t *input_start_p, /**< routine's first argument's * string buffer */ lit_utf8_size_t input_size) /**< routine's first argument's * string buffer's size */ { const lit_utf8_byte_t *input_curr_p = input_start_p; const lit_utf8_byte_t *input_end_p = input_start_p + input_size; ecma_stringbuilder_t builder = ecma_stringbuilder_create (); lit_utf8_byte_t result_chars[URI_ENCODED_BYTE_SIZE]; while (input_curr_p < input_end_p) { ecma_char_t chr = lit_cesu8_read_next (&input_curr_p); if (chr <= LIT_UTF8_1_BYTE_CODE_POINT_MAX) { if (ecma_builtin_global_object_character_is_in ((uint32_t) chr, ecma_escape_set)) { ecma_stringbuilder_append_char (&builder, chr); } else { ecma_builtin_global_object_byte_to_hex (result_chars, chr); ecma_stringbuilder_append_raw (&builder, result_chars, URI_ENCODED_BYTE_SIZE); } } else if (chr > ECMA_ESCAPE_MAXIMUM_BYTE_VALUE) { ecma_stringbuilder_append_char (&builder, LIT_CHAR_PERCENT); ecma_stringbuilder_append_char (&builder, LIT_CHAR_LOWERCASE_U); ecma_builtin_global_object_byte_to_hex (result_chars, (chr >> JERRY_BITSINBYTE)); ecma_stringbuilder_append_raw (&builder, result_chars + 1, 2); ecma_builtin_global_object_byte_to_hex (result_chars, (chr & 0xff)); ecma_stringbuilder_append_raw (&builder, result_chars + 1, 2); } else { ecma_builtin_global_object_byte_to_hex (result_chars, chr); ecma_stringbuilder_append_raw (&builder, result_chars, URI_ENCODED_BYTE_SIZE); } } return ecma_make_string_value (ecma_stringbuilder_finalize (&builder)); } /* ecma_builtin_global_object_escape */ /** * Utility method to resolve character sequences for the 'unescape' method. * * Expected formats: %uxxxx or %yy * * @return number of characters processed during the escape resolve */ static uint8_t ecma_builtin_global_object_unescape_resolve_escape (const lit_utf8_byte_t *buffer_p, /**< character buffer */ bool unicode_sequence, /**< true if unescaping unicode sequence */ ecma_char_t *out_result_p) /**< [out] resolved character */ { JERRY_ASSERT (buffer_p != NULL); JERRY_ASSERT (out_result_p != NULL); ecma_char_t unescaped_chr = 0; uint8_t sequence_length = unicode_sequence ? 5 : 2; uint8_t start = unicode_sequence ? 1 : 0; for (uint8_t i = start; i < sequence_length; i++) { const lit_utf8_byte_t current_char = buffer_p[i]; if (!lit_char_is_hex_digit (current_char)) { /* This was not an escape sequence, skip processing */ return 0; } unescaped_chr = (ecma_char_t) ((unescaped_chr << 4) + (ecma_char_t) lit_char_hex_to_int (current_char)); } *out_result_p = unescaped_chr; return sequence_length; } /* ecma_builtin_global_object_unescape_resolve_escape */ /** * The Global object's 'unescape' routine * * See also: * ECMA-262 v5, B.2.2 * ECMA-262 v11, B.2.1.2 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_global_object_unescape (lit_utf8_byte_t *input_start_p, /**< routine's first argument's * string buffer */ lit_utf8_size_t input_size) /**< routine's first argument's * string buffer's size */ { if (input_size == 0) { return ecma_make_magic_string_value (LIT_MAGIC_STRING__EMPTY); } const lit_utf8_byte_t *input_curr_p = input_start_p; const lit_utf8_byte_t *input_end_p = input_start_p + input_size; ecma_stringbuilder_t builder = ecma_stringbuilder_create (); while (input_curr_p < input_end_p) { ecma_char_t chr = lit_cesu8_read_next (&input_curr_p); // potential pattern if (chr == LIT_CHAR_PERCENT) { const lit_utf8_size_t chars_leftover = (lit_utf8_size_t) (input_end_p - input_curr_p); // potential unicode sequence if (chars_leftover >= 5 && input_curr_p[0] == LIT_CHAR_LOWERCASE_U) { input_curr_p += ecma_builtin_global_object_unescape_resolve_escape (input_curr_p, true, &chr); } // potential two hexa sequence else if (chars_leftover >= 2) { input_curr_p += ecma_builtin_global_object_unescape_resolve_escape (input_curr_p, false, &chr); } } ecma_stringbuilder_append_char (&builder, chr); } return ecma_make_string_value (ecma_stringbuilder_finalize (&builder)); } /* ecma_builtin_global_object_unescape */ #endif /* JERRY_BUILTIN_ANNEXB */ /** * Dispatcher of the built-in's routines * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_builtin_global_dispatch_routine (uint8_t builtin_routine_id, /**< built-in wide routine identifier */ ecma_value_t this_arg, /**< 'this' argument value */ const ecma_value_t arguments_list_p[], /**< list of arguments * passed to routine */ uint32_t arguments_number) /**< length of arguments' list */ { JERRY_UNUSED_2 (this_arg, arguments_number); ecma_value_t routine_arg_1 = arguments_list_p[0]; if (builtin_routine_id == ECMA_GLOBAL_EVAL) { return ecma_builtin_global_object_eval (routine_arg_1); } if (builtin_routine_id <= ECMA_GLOBAL_IS_FINITE) { ecma_number_t arg_num; routine_arg_1 = ecma_op_to_number (routine_arg_1, &arg_num); if (!ecma_is_value_empty (routine_arg_1)) { return routine_arg_1; } if (builtin_routine_id == ECMA_GLOBAL_IS_NAN) { return ecma_builtin_global_object_is_nan (arg_num); } JERRY_ASSERT (builtin_routine_id == ECMA_GLOBAL_IS_FINITE); return ecma_builtin_global_object_is_finite (arg_num); } ecma_string_t *str_p = ecma_op_to_string (routine_arg_1); if (JERRY_UNLIKELY (str_p == NULL)) { return ECMA_VALUE_ERROR; } ecma_value_t ret_value; if (builtin_routine_id <= ECMA_GLOBAL_PARSE_FLOAT) { ECMA_STRING_TO_UTF8_STRING (str_p, string_buff, string_buff_size); if (builtin_routine_id == ECMA_GLOBAL_PARSE_INT) { ret_value = ecma_number_parse_int (string_buff, string_buff_size, arguments_list_p[1]); } else { JERRY_ASSERT (builtin_routine_id == ECMA_GLOBAL_PARSE_FLOAT); ret_value = ecma_number_parse_float (string_buff, string_buff_size); } ECMA_FINALIZE_UTF8_STRING (string_buff, string_buff_size); ecma_deref_ecma_string (str_p); return ret_value; } lit_utf8_size_t input_size = ecma_string_get_size (str_p); JMEM_DEFINE_LOCAL_ARRAY (input_start_p, input_size + 1, lit_utf8_byte_t); ecma_string_to_utf8_bytes (str_p, input_start_p, input_size); input_start_p[input_size] = LIT_BYTE_NULL; switch (builtin_routine_id) { #if JERRY_BUILTIN_ANNEXB case ECMA_GLOBAL_ESCAPE: { ret_value = ecma_builtin_global_object_escape (input_start_p, input_size); break; } case ECMA_GLOBAL_UNESCAPE: { ret_value = ecma_builtin_global_object_unescape (input_start_p, input_size); break; } #endif /* JERRY_BUILTIN_ANNEXB */ case ECMA_GLOBAL_DECODE_URI: case ECMA_GLOBAL_DECODE_URI_COMPONENT: { const uint8_t *uri_set = (builtin_routine_id == ECMA_GLOBAL_DECODE_URI ? unescaped_uri_set : unescaped_uri_component_set); ret_value = ecma_builtin_global_object_decode_uri_helper (input_start_p, input_size, uri_set); break; } default: { JERRY_ASSERT (builtin_routine_id == ECMA_GLOBAL_ENCODE_URI || builtin_routine_id == ECMA_GLOBAL_ENCODE_URI_COMPONENT); const uint8_t *uri_set = (builtin_routine_id == ECMA_GLOBAL_ENCODE_URI ? unescaped_uri_set : unescaped_uri_component_set); ret_value = ecma_builtin_global_object_encode_uri_helper (input_start_p, input_size, uri_set); break; } } JMEM_FINALIZE_LOCAL_ARRAY (input_start_p); ecma_deref_ecma_string (str_p); return ret_value; } /* ecma_builtin_global_dispatch_routine */ /** * @} * @} * @} */
apache-2.0
rudkx/swift
lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp
1
25003
//===--- MoveOnlyChecker.cpp ----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-move-only-checker" #include "swift/AST/DiagnosticsSIL.h" #include "swift/Basic/Defer.h" #include "swift/SIL/BasicBlockBits.h" #include "swift/SIL/BasicBlockUtils.h" #include "swift/SIL/DebugUtils.h" #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/OwnershipUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILUndef.h" #include "swift/SIL/SILValue.h" #include "swift/SILOptimizer/Analysis/ClosureScope.h" #include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/Analysis/NonLocalAccessBlockAnalysis.h" #include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/CanonicalOSSALifetime.h" using namespace swift; //===----------------------------------------------------------------------===// // Diagnostic Utilities //===----------------------------------------------------------------------===// template <typename... T, typename... U> static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag, U &&...args) { Context.Diags.diagnose(loc, diag, std::forward<U>(args)...); } //===----------------------------------------------------------------------===// // Copy of Borrowed Projection Checker //===----------------------------------------------------------------------===// namespace { struct LivenessInfo { SmallVector<SILBasicBlock *, 8> discoveredBlocks; PrunedLiveness liveness; PrunedLivenessBoundary livenessBoundary; LivenessInfo() : discoveredBlocks(), liveness(&discoveredBlocks) {} void clear() { discoveredBlocks.clear(); liveness.clear(); livenessBoundary.clear(); } void computeBoundary() { livenessBoundary.compute(liveness); } ArrayRef<SILInstruction *> getLastUsers() const { return livenessBoundary.lastUsers; } }; /// Once we have finished checking that a base owned value is not consumed /// unnecessarily, we need to look at all instances where the owned value was /// borrowed and prove that it was never copied in its borrowed form because the /// borrowed value must be consumed. /// /// As part of this optimization, we flatten the borrowed lifetime and eliminate /// any copies that are only consumed by a destroy_value. If we find that the /// flattened borrowed value needs a copy to extend the lifetime of the value, /// we treat the lifetime extending use as requiring a consuming use. struct CopyOfBorrowedProjectionChecker { SmallVector<SILInstruction *, 4> foundConsumesOfBorrowedSubValues; SmallVector<SILInstruction *, 4> foundCopiesOfBorrowedSubValues; SmallVector<SILInstruction *, 4> foundDestroysOfBorrowedSubValues; SmallVector<SILInstruction *, 4> foundRecursiveBorrows; SmallVector<SILInstruction *, 4> foundRecursiveEndBorrow; SmallVector<ForwardingOperand, 4> foundOwnedForwardingUses; LivenessInfo livenessInfo; LivenessInfo markedValueExtendedLiveRangeInfo; DeadEndBlocks *deBlocks; CopyOfBorrowedProjectionChecker(DeadEndBlocks *deBlocks) : deBlocks(deBlocks) {} /// Performs checking for \p markedValue. Returns true if we were able to /// successfully check/optimize. Returns false if we failed and did not /// perform any work. In such a case, we should bail early even though we did /// not emit a diagnostic so we emit a "checker did not understand" diagnostic /// later. bool check(SILValue markedValue); bool shouldEmitDiagnostic() const { return !foundConsumesOfBorrowedSubValues.empty(); } void clear() { foundConsumesOfBorrowedSubValues.clear(); foundCopiesOfBorrowedSubValues.clear(); foundDestroysOfBorrowedSubValues.clear(); foundRecursiveBorrows.clear(); foundRecursiveEndBorrow.clear(); foundOwnedForwardingUses.clear(); livenessInfo.clear(); markedValueExtendedLiveRangeInfo.clear(); } }; } // namespace /// Walking from defs -> uses, see if \p markedValue has any uses by a borrow /// introducing instruction looking through owned consuming instructions. \p /// foundBorrows contains the resulting borrows that we found. \p /// extendedLiveRangeLiveness is returned having been initialized with the live /// range of markedValue ignoring Owned Forwarding. static void gatherBorrowsToCheckOfMovedValue(SILValue markedValue, SmallVectorImpl<SILValue> &foundBorrows, PrunedLiveness &extendedLiveRangeLiveness) { SmallVector<SILValue, 8> worklist; worklist.push_back(markedValue); extendedLiveRangeLiveness.clear(); extendedLiveRangeLiveness.initializeDefBlock(markedValue->getParentBlock()); while (!worklist.empty()) { auto value = worklist.pop_back_val(); for (auto *use : value->getUses()) { auto *user = use->getUser(); switch (use->getOperandOwnership()) { case OperandOwnership::NonUse: break; case OperandOwnership::TrivialUse: llvm_unreachable("this operand cannot handle ownership"); case OperandOwnership::ForwardingUnowned: case OperandOwnership::PointerEscape: case OperandOwnership::InstantaneousUse: case OperandOwnership::UnownedInstantaneousUse: case OperandOwnership::BitwiseEscape: // We don't care about these. We are looking for borrows and // forwarding consumes! break; case OperandOwnership::ForwardingConsume: if (auto op = ForwardingOperand(use)) { op.visitForwardedValues([&](SILValue v) { worklist.push_back(v); return true; }); break; } extendedLiveRangeLiveness.updateForUse(user, true /*is lifetime ending*/); break; case OperandOwnership::DestroyingConsume: // We do not care about destroying consume uses. extendedLiveRangeLiveness.updateForUse(user, true /*is lifetime ending*/); break; case OperandOwnership::Borrow: { foundBorrows.push_back(cast<BeginBorrowInst>(user)); break; } case OperandOwnership::ForwardingBorrow: case OperandOwnership::InteriorPointer: case OperandOwnership::EndBorrow: case OperandOwnership::Reborrow: llvm_unreachable("Should never see these on owned values"); } } } } bool CopyOfBorrowedProjectionChecker::check(SILValue markedValue) { auto *parentBlock = markedValue->getParentBlock(); if (!parentBlock) return false; auto &liveness = livenessInfo.liveness; liveness.initializeDefBlock(parentBlock); LLVM_DEBUG(llvm::dbgs() << "CopyOfBorrowedProjection. MovedValue: " << markedValue); // Call this utility routine to gather up our worklist of borrows and also the // liveness of the moved value looking through forwarding uses. We use this // liveness info later to determine if we require a copy_value of a subobject // b/c the subobject use is outside the lifetime of the of the marked object. SmallVector<SILValue, 8> worklist; gatherBorrowsToCheckOfMovedValue(markedValue, worklist, markedValueExtendedLiveRangeInfo.liveness); if (worklist.empty()) { LLVM_DEBUG(llvm::dbgs() << "CopyOfBorrowedProjection. No borrows to check! " "No Diagnostic Needed!\n"); return true; } // Ok, we now have our guaranteed values. Looking through guaranteed // forwarding uses, search for a copy_value. If we found one, then we add // it to the consumingUsesNeedingCopy array and use the same processing // below. Otherwise, if we do not find any, then we are truly safe and // continue. while (!worklist.empty()) { SILValue value = worklist.pop_back_val(); LLVM_DEBUG(llvm::dbgs() << "CopyOfBorrowedProjection. Visiting Value: " << value); for (auto *use : value->getUses()) { auto *user = use->getUser(); LLVM_DEBUG(llvm::dbgs() << "CopyOfBorrowedProjection. User: " << *user); LLVM_DEBUG(llvm::dbgs() << "CopyOfBorrowedProjection. Operand Ownership: " << use->getOperandOwnership() << '\n'); switch (use->getOperandOwnership()) { case OperandOwnership::NonUse: break; case OperandOwnership::TrivialUse: llvm_unreachable("this operand cannot handle ownership"); // Conservatively treat a conversion to an unowned value as a pointer // escape. Is it legal to canonicalize ForwardingUnowned? case OperandOwnership::ForwardingUnowned: case OperandOwnership::PointerEscape: // Just add liveness. liveness.updateForUse(user, /*lifetimeEnding*/ false); break; case OperandOwnership::InstantaneousUse: case OperandOwnership::UnownedInstantaneousUse: case OperandOwnership::BitwiseEscape: // Add liveness to be careful around dead end blocks until in OSSA we no // longer use those. liveness.updateForUse(user, /*lifetimeEnding*/ false); // Look through copy_value. if (auto *cvi = dyn_cast<CopyValueInst>(user)) { foundCopiesOfBorrowedSubValues.push_back(cvi); worklist.push_back(cvi); } break; case OperandOwnership::ForwardingConsume: { if (auto op = ForwardingOperand(use)) { // If our user is not directly forwarding, we cannot convert its // ownership to be guaranteed, so we treat it as a true consuming use. if (!op.isDirectlyForwarding()) { foundConsumesOfBorrowedSubValues.push_back(user); liveness.updateForUse(user, /*lifetimeEnding*/ true); break; } // Otherwise, add liveness and recurse into results. foundOwnedForwardingUses.push_back(op); liveness.updateForUse(user, /*lifetimeEnding*/ false); llvm::copy(user->getResults(), std::back_inserter(worklist)); break; } // If we do not have a forwarding operand, treat this like a consume. liveness.updateForUse(user, /*lifetimeEnding*/ true); foundConsumesOfBorrowedSubValues.push_back(user); break; } case OperandOwnership::DestroyingConsume: liveness.updateForUse(user, /*lifetimeEnding*/ true); if (!isa<DestroyValueInst>(user)) { foundConsumesOfBorrowedSubValues.push_back(user); break; } foundDestroysOfBorrowedSubValues.push_back(user); break; case OperandOwnership::Borrow: { auto *bbi = cast<BeginBorrowInst>(user); // Only add borrows to liveness if the borrow isn't lexical. If it is // a lexical borrow, we have created an entirely new source level // binding that should be tracked separately. // // TODO: Is this still true with the changes? if (!bbi->isLexical()) { bool failed = !liveness.updateForBorrowingOperand(use); // If we fail, we will just bail and not eliminate these copies. // Once we have @moveOnly in the SIL type system, this will result // in a diagnostic that says we were not able to eliminate a // copy. But that is in a later pass. if (failed) return false; foundRecursiveBorrows.push_back(bbi); worklist.push_back(bbi); } break; } case OperandOwnership::ForwardingBorrow: // A forwarding borrow is validated as part of its parent borrow. So // just mark it as extending liveness and look through it. liveness.updateForUse(user, /*lifetimeEnding*/ false); assert(OwnershipForwardingMixin::isa(use->getUser())); if (auto *termInst = dyn_cast<OwnershipForwardingTermInst>(use->getUser())) { for (auto argList : termInst->getSuccessorBlockArgumentLists()) { worklist.push_back(argList[use->getOperandNumber()]); } break; } for (auto result : use->getUser()->getResults()) { if (result.getOwnershipKind() == OwnershipKind::Guaranteed) worklist.push_back(result); } break; case OperandOwnership::InteriorPointer: { // We do not care about interior pointer uses. Just propagate // liveness. Should add all address uses as liveness uses. liveness.updateForUse(user, /*lifetimeEnding*/ false); auto ptrOp = InteriorPointerOperand(use); assert(ptrOp); SmallVector<Operand *, 8> foundUses; ptrOp.findTransitiveUses(&foundUses); for (auto *op : foundUses) { liveness.updateForUse(op->getUser(), /*lfietimeEnding*/ false); } break; } case OperandOwnership::EndBorrow: foundRecursiveEndBorrow.push_back(user); liveness.updateForUse(user, /*lifetimeEnding*/ false); break; case OperandOwnership::Reborrow: // Reborrows do not occur this early in the pipeline. llvm_unreachable( "Reborrows do not occur until we optimize later in the pipeline"); } } } // Ok, we have finished processing out worklist. If we found any /real/ // consumes, we are going to error in the caller. So just bail now. if (foundConsumesOfBorrowedSubValues.size()) { LLVM_DEBUG( llvm::dbgs() << "Found consume of borrowed subvalues! Will Emit Diagnostic!\n"); return true; } // Otherwise, the only reason why we could need a copy_value is if the copy is // needed to lifetime extend the sub-object outside of the lifetime of the // parent value. We use the liveness information that we gathered above to do // this. We gathered two forms of liveness info: // // 1. liveness: the complete liveness info looking through copies/borrows. // // 2. markedValueExtendedLiveRangeInfo.liveness: this is the owned liveness // information defined for the marked value looking through owned // forwarding instructions. // // We need to show that the 2nd is within the boundary of the first. // // First though if we do not have any liveness at all, then we did not have // any uses at all. So we can just return success. if (liveness.empty()) { LLVM_DEBUG(llvm::dbgs() << "No liveness requiring uses! No diagnostic needed!\n"); return true; } // If we did not have an extended live range liveness for our value then that // means that we must be post-dominated by dead end blocks since otherwise we // would be leaking. That is illegal in OSSA, so we know that we do not need // any copy_value for lifetime extension since our value must be live until // the end of the function. if (markedValueExtendedLiveRangeInfo.liveness.empty()) { LLVM_DEBUG(llvm::dbgs() << "No marked value extended live range info liveness!"); return true; } // Then see if our underlying markedValue's consuming uses are all not within // the boundary of the uses. If they are within the boundary, then we know // that there is some copy_value that is requiring to lifetime extend due to a // non-consuming use that is after the lifetime of the value has ended. We // need to emit a diagnostic on this. For now, lets just emit it as a // consuming use. // // TODO: Emit a better diagnostic here that talks about the need for lifetime // extension. SWIFT_DEFER { livenessInfo.livenessBoundary.clear(); }; livenessInfo.computeBoundary(); markedValueExtendedLiveRangeInfo.computeBoundary(); LLVM_DEBUG(llvm::dbgs() << "Checking if copy_value needed for lifetime extension!\n"); for (auto *user : markedValueExtendedLiveRangeInfo.getLastUsers()) { if (!liveness.isWithinBoundary(user)) continue; // Ok, we have some use that requires lifetime extension. It is going to be // one of the boundary uses of our liveness query. In order to figure out // which one it actually is, we see which is reachable from this use. In // such a case, we are going to emit a diagnostic so we can use a bit more // compile time since we are going to stop optimizing after codegening. // // TODO: Actually implement this... for now we just error on all boundary // uses. llvm::copy(livenessInfo.getLastUsers(), std::back_inserter(foundConsumesOfBorrowedSubValues)); } // If we are going to emit a diagnostic on a liveness boundary based // copy_value, bail early. if (foundConsumesOfBorrowedSubValues.size()) { LLVM_DEBUG(llvm::dbgs() << "Found copy_value needed for lifetime " "extension! Emitting Diagnostic!\n"); #ifndef NDEBUG for (auto *user : livenessInfo.getLastUsers()) { LLVM_DEBUG(llvm::dbgs() << "User: " << *user); } #endif return true; } // Otherwise, we have success. There aren't any consumes of the underlying // value and all copy_value are balanced by destroy_values (modulo forwarding // uses) or we would have emitted a diagnostic. // // TODO: We should be able to eliminate all copy/destroys that we found above // since we proved that all uses are within the lifetime of the base owned // value. But this at least gets the correct diagnostic in place for // prototyping purposes. LLVM_DEBUG(llvm::dbgs() << "No copy needed! No Diagnostic needed\n"); return true; } //===----------------------------------------------------------------------===// // Main Pass //===----------------------------------------------------------------------===// namespace { struct MoveOnlyChecker { SILFunction *fn; SmallSetVector<MarkMustCheckInst *, 32> moveIntroducersToProcess; CopyOfBorrowedProjectionChecker copyOfBorrowedProjectionChecker; MoveOnlyChecker(SILFunction *fn, DeadEndBlocks *deBlocks) : fn(fn), copyOfBorrowedProjectionChecker(deBlocks) {} bool check(NonLocalAccessBlockAnalysis *accessBlockAnalysis, DominanceInfo *domTree); }; } // namespace bool MoveOnlyChecker::check(NonLocalAccessBlockAnalysis *accessBlockAnalysis, DominanceInfo *domTree) { for (auto &block : *fn) { for (auto &ii : block) { auto *mvi = dyn_cast<MarkMustCheckInst>(&ii); // For now only handle move_only. if (!mvi || !mvi->isNoImplicitCopy()) continue; auto *cvi = dyn_cast<CopyValueInst>(mvi->getOperand()); if (!cvi) continue; auto *bbi = dyn_cast<BeginBorrowInst>(cvi->getOperand()); if (!bbi || !bbi->isLexical()) continue; moveIntroducersToProcess.insert(mvi); } } auto callbacks = InstModCallbacks().onDelete([&](SILInstruction *instToDelete) { if (auto *mvi = dyn_cast<MarkMustCheckInst>(instToDelete)) moveIntroducersToProcess.remove(mvi); instToDelete->eraseFromParent(); }); InstructionDeleter deleter(std::move(callbacks)); bool changed = false; SmallVector<Operand *, 32> consumingUsesNeedingCopy; auto foundConsumingUseNeedingCopy = [&](Operand *use) { consumingUsesNeedingCopy.push_back(use); }; SmallVector<Operand *, 32> consumingUsesNotNeedingCopy; auto foundConsumingUseNotNeedingCopy = [&](Operand *use) { consumingUsesNotNeedingCopy.push_back(use); }; CanonicalizeOSSALifetime canonicalizer( false /*pruneDebugMode*/, false /*poisonRefsMode*/, accessBlockAnalysis, domTree, deleter, foundConsumingUseNeedingCopy, foundConsumingUseNotNeedingCopy); auto &astContext = fn->getASTContext(); auto moveIntroducers = llvm::makeArrayRef(moveIntroducersToProcess.begin(), moveIntroducersToProcess.end()); while (!moveIntroducers.empty()) { SWIFT_DEFER { consumingUsesNeedingCopy.clear(); consumingUsesNotNeedingCopy.clear(); copyOfBorrowedProjectionChecker.clear(); }; SILValue markedValue = moveIntroducers.front(); moveIntroducers = moveIntroducers.drop_front(1); LLVM_DEBUG(llvm::dbgs() << "Visiting: " << *markedValue); changed |= canonicalizer.canonicalizeValueLifetime(markedValue); if (consumingUsesNeedingCopy.empty()) { // If we don't see any situations where we need a direct copy, check if we // have any copy_value from any user of ours that is a borrow // introducer. In such a case, a copy is needed but the user needs to use // _copy to explicit copy the value since they are extracting out a // subvalue. if (!copyOfBorrowedProjectionChecker.check(markedValue) || !copyOfBorrowedProjectionChecker.shouldEmitDiagnostic()) { // If we failed to understand how to perform the check or did not find // any targets... continue. In the former case we want to fail with a // checker did not understand diagnostic later and in the former, we // succeeded. continue; } // Otherwise, emit our diagnostic below. } StringRef varName = "unknown"; if (auto *use = getSingleDebugUse(markedValue)) { DebugVarCarryingInst debugVar(use->getUser()); if (auto varInfo = debugVar.getVarInfo()) { varName = varInfo->Name; } else { if (auto *decl = debugVar.getDecl()) { varName = decl->getBaseName().userFacingName(); } } } diagnose(astContext, markedValue->getDefiningInstruction()->getLoc().getSourceLoc(), diag::sil_moveonlychecker_value_consumed_more_than_once, varName); while (consumingUsesNeedingCopy.size()) { auto *consumingUse = consumingUsesNeedingCopy.pop_back_val(); diagnose(astContext, consumingUse->getUser()->getLoc().getSourceLoc(), diag::sil_moveonlychecker_consuming_use_here); } while (consumingUsesNotNeedingCopy.size()) { auto *consumingUse = consumingUsesNotNeedingCopy.pop_back_val(); diagnose(astContext, consumingUse->getUser()->getLoc().getSourceLoc(), diag::sil_moveonlychecker_consuming_use_here); } auto &foundConsumesOfBorrowedSubValues = copyOfBorrowedProjectionChecker.foundConsumesOfBorrowedSubValues; while (foundConsumesOfBorrowedSubValues.size()) { auto *user = foundConsumesOfBorrowedSubValues.pop_back_val(); auto loc = user->getLoc(); diagnose(astContext, loc.getSourceLoc(), diag::sil_moveonlychecker_consuming_use_here); } } // Ok, we have success. All of our marker instructions were proven as // safe. Now we need to clean up the IR by eliminating our marker instructions // to signify that the checked SIL is correct. // // NOTE: This is enforced in the verifier by only allowing MarkMustCheckInst // in Raw SIL. while (!moveIntroducersToProcess.empty()) { auto *mvi = moveIntroducersToProcess.pop_back_val(); mvi->replaceAllUsesWith(mvi->getOperand()); mvi->eraseFromParent(); changed = true; } return changed; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// namespace { class MoveOnlyCheckerPass : public SILFunctionTransform { void run() override { auto *fn = getFunction(); // Don't rerun diagnostics on deserialized functions. if (getFunction()->wasDeserializedCanonical()) return; assert(fn->getModule().getStage() == SILStage::Raw && "Should only run on Raw SIL"); auto *accessBlockAnalysis = getAnalysis<NonLocalAccessBlockAnalysis>(); auto *dominanceAnalysis = getAnalysis<DominanceAnalysis>(); DominanceInfo *domTree = dominanceAnalysis->get(fn); auto *deAnalysis = getAnalysis<DeadEndBlocksAnalysis>()->get(fn); if (MoveOnlyChecker(getFunction(), deAnalysis) .check(accessBlockAnalysis, domTree)) { invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } } }; } // anonymous namespace SILTransform *swift::createMoveOnlyChecker() { return new MoveOnlyCheckerPass(); }
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-ds/source/model/DirectoryVpcSettings.cpp
1
1816
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ds/model/DirectoryVpcSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DirectoryService { namespace Model { DirectoryVpcSettings::DirectoryVpcSettings() : m_vpcIdHasBeenSet(false), m_subnetIdsHasBeenSet(false) { } DirectoryVpcSettings::DirectoryVpcSettings(JsonView jsonValue) : m_vpcIdHasBeenSet(false), m_subnetIdsHasBeenSet(false) { *this = jsonValue; } DirectoryVpcSettings& DirectoryVpcSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("VpcId")) { m_vpcId = jsonValue.GetString("VpcId"); m_vpcIdHasBeenSet = true; } if(jsonValue.ValueExists("SubnetIds")) { Aws::Utils::Array<JsonView> subnetIdsJsonList = jsonValue.GetArray("SubnetIds"); for(unsigned subnetIdsIndex = 0; subnetIdsIndex < subnetIdsJsonList.GetLength(); ++subnetIdsIndex) { m_subnetIds.push_back(subnetIdsJsonList[subnetIdsIndex].AsString()); } m_subnetIdsHasBeenSet = true; } return *this; } JsonValue DirectoryVpcSettings::Jsonize() const { JsonValue payload; if(m_vpcIdHasBeenSet) { payload.WithString("VpcId", m_vpcId); } if(m_subnetIdsHasBeenSet) { Aws::Utils::Array<JsonValue> subnetIdsJsonList(m_subnetIds.size()); for(unsigned subnetIdsIndex = 0; subnetIdsIndex < subnetIdsJsonList.GetLength(); ++subnetIdsIndex) { subnetIdsJsonList[subnetIdsIndex].AsString(m_subnetIds[subnetIdsIndex]); } payload.WithArray("SubnetIds", std::move(subnetIdsJsonList)); } return payload; } } // namespace Model } // namespace DirectoryService } // namespace Aws
apache-2.0
robertamarton/incubator-trafodion
core/sql/exp/exp_tuple_desc.cpp
1
32573
/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ext_tuple_desc.cpp * Description: * * Created: 7/10/95 * Language: C++ * * * * ***************************************************************************** */ #include "Platform.h" #include "dfs2rec.h" #include "ComPackDefs.h" #include "exp_stdh.h" // Uncomment this line to see the offsets computed. // #define LOG_OFFSETS #if defined( LOG_OFFSETS ) #include <stdlib.h> #endif ExpTupleDesc::ExpTupleDesc(UInt32 num_attrs, Attributes ** attrs, UInt32 tupleDataLength, TupleDataFormat tdataF, TupleDescFormat tdescF, Space * space) : numAttrs_(num_attrs), tupleDataLength_(tupleDataLength), tupleDataFormat_(tdataF), tupleDescFormat_(tdescF), NAVersionedObject(-1) { if ( space != NULL ) { // remember current allocated space size. Used at the end of // generation to find out total tuple desc length allocated. tupleDescLength_ = space->getAllocatedSpaceSize(); flags_ = 0; attrs_ = 0; #ifndef _DEBUG if (tdescF == LONG_FORMAT) #endif { // allocate an array of num_attrs Attributes*. This array follows // 'this' class. attrs_ = (AttributesPtr *) (space->allocateAlignedSpace(num_attrs * sizeof(AttributesPtr))); for (UInt32 i=0; i < num_attrs; i++) { // make a new copy of input attributes. This new attr entry // will follow the attribute array. attrs_[i] = attrs[i]->newCopy(space); } } // and now find out the total length of the generated descriptor tupleDescLength_ = sizeof(*this) + space->getAllocatedSpaceSize() - tupleDescLength_; } else { flags_ = 0; attrs_ = attrs; tupleDescLength_ = 0x0ffff; } str_pad(fillers_, sizeof(fillers_), '\0'); } ExpTupleDesc::ExpTupleDesc(UInt32 num_attrs, AttributesPtr * attrs, UInt32 tupleDataLength, TupleDataFormat tdataF, TupleDescFormat tdescF) : numAttrs_(num_attrs), tupleDataLength_(tupleDataLength), tupleDataFormat_(tdataF), tupleDescFormat_(tdescF), NAVersionedObject(-1) { // special case where space is null, used in ex_rcb.cpp for late bind. flags_ = 0; attrs_ = attrs; tupleDescLength_ = 0x0ffff; } ExpTupleDesc::ExpTupleDesc() : NAVersionedObject(-1) { } ExpTupleDesc::~ExpTupleDesc() { // if ((tupleDescFormat_ == LONG_FORMAT) && (attrs_)) // { // for (Int32 i=0; i < (Int32) numAttrs_; i++) // { // delete attrs_[i]; // } // // delete[] attrs_; // } // // attrs_ = 0; } // // Takes a list of fixed fields and destructively rearranges the fixed fields // such that all the 8-byte fields come first, followed by the 4-byte, then // 2-byte, and then all remaining fields. This is only done for non-added // columns. The added columns follow the original fixed columns and are NOT // ordered on their byte boundary, but put in the list in the order they // were added. NA_EIDPROC static Int16 orderFixedFieldsByAlignment( Attributes ** attrs, NAList<UInt32> * fixedFields ) { Int16 rc = 0; Attributes *attr; NAList<UInt32> align8(4); NAList<UInt32> align4(10); NAList<UInt32> align2(10); NAList<UInt32> align1(4); NAList<UInt32> addedCols(4); UInt32 fieldIdx = 0; UInt32 numFixed = fixedFields->entries(); Int32 alignSz; UInt32 i; for( i = 0; i < numFixed; i++ ) { fixedFields->getFirst( fieldIdx ); attr = attrs[ fieldIdx ]; if (attr->isSpecialField()) // an added column { addedCols.insert( fieldIdx ); continue; } alignSz = attr->getDataAlignmentSize(); if ( alignSz == 8 ) align8.insert( fieldIdx ); else if ( alignSz == 4 ) align4.insert( fieldIdx ); else if ( alignSz == 2 ) align2.insert( fieldIdx ); else align1.insert( fieldIdx ); } fixedFields->clear(); if ( align8.entries() > 0 ) for( i = 0; i < align8.entries(); i++ ) { fixedFields->insert( align8[ i ] ); } // Add all the 4-byte attributes next. if ( align4.entries() > 0 ) for( i = 0; i < align4.entries(); i++ ) { fixedFields->insert( align4[ i ] ); } // Add all the 2-byte attributes next. if ( align2.entries() > 0 ) for( i = 0; i < align2.entries(); i++ ) { fixedFields->insert( align2[ i ] ); } // Add all the remaining attributes if any. if ( align1.entries() > 0 ) for( i = 0; i < align1.entries(); i++ ) { fixedFields->insert( align1[ i ] ); } // Add all the added column attributes in their logical order. if ( addedCols.entries() > 0 ) for( i = 0; i < addedCols.entries(); i++ ) { fixedFields->insert( addedCols[ i ] ); } return rc; } // input is a single attribute Int16 ExpTupleDesc::computeOffsets(Attributes * attr, TupleDataFormat tf, UInt32& datalen, UInt32 start_offset) { ExpTupleDesc::computeOffsets(1, &attr, tf, datalen, start_offset); // start here return 0; } // This code is the same for fixed fields and GuOutput fields. NA_EIDPROC static void computeOffsetOfFixedField(Attributes ** attrs, UInt32 fieldIdx, UInt32 bitmapOffset, UInt32& fixedOffset, UInt32& firstField, UInt32& prevIdx, UInt16& nullBitIdx, ExpHdrInfo * hdrInfo = NULL, NABoolean alignFormat = FALSE) { Attributes *field = attrs[fieldIdx]; if (prevIdx != ExpOffsetMax) attrs[prevIdx]->setNextFieldIndex(fieldIdx); if (alignFormat) fixedOffset = ADJUST(fixedOffset, field->getDataAlignmentSize()); if (firstField == ExpOffsetMax) { // Only the first fixed field will have a VOA offset set. // This is used when writing SQLMX_FORMAT so the proper offset gets // written there. firstField = fixedOffset; if(!alignFormat) field->setVoaOffset(0); if (hdrInfo != NULL) hdrInfo->setFirstFixedOffset( firstField ); } // Relative offet is to the very start of the field - before the null // indicator offset. field->setRelOffset(fixedOffset - firstField); if (field->getNullFlag()) { if (alignFormat) { // The SQLMX_ALIGNED_FORMAT has a null bitmap - 1 bit per nullable field. // Each nullable field has the same null indicator offset that // points to the start of the bitmap and a bit within // the null bitmap that is set if the field is null. field->setNullBitIndex( nullBitIdx++ ); field->setNullIndOffset( bitmapOffset ); } else { // The SQLMX_FORMAT has the 2 byte null indicator field at the start // of the fields data. field->setNullIndOffset(fixedOffset); fixedOffset += field->getNullIndicatorLength(); } } // A varchar could be a fixed field if the forceFixed flag is set. if (field->getVCIndicatorLength() > 0) { field->setVCLenIndOffset(fixedOffset); fixedOffset += field->getVCIndicatorLength(); } field->setOffset(fixedOffset); fixedOffset += field->getLength(); prevIdx = fieldIdx; } // Static method // Input is an array of num_attrs Attributes. Int16 ExpTupleDesc::computeOffsets(UInt32 num_attrs, /* IN */ Attributes ** attrs, /* IN */ TupleDataFormat tf, /* IN */ UInt32 & datalen, /* OUT */ UInt32 startOffset, /* IN */ UInt32 * rtnFlags, /* OUT */ TupleDataFormat * outTf, /* OUT */ ExpHdrInfo * hdrInfo, /* OUT */ UInt32 * headerSizePtr, /* OUT */ UInt32 * varSizePtr) /* OUT */ { // start at startOffset. UInt32 offset = startOffset; UInt32 attrStartOffset; // The first fixecd field needs to add in the pad bytes if the data length // is extended and for Aligned Format. // This only needs to be done if there are no variable length fields present // and there is a hdrInfo passed in. Data rows with a variable length field // adjust the data len at runtime. NABoolean adjustFirstFixed = FALSE; datalen = 0; if (outTf) *outTf = tf; // Compute length of tuple and assign offset to attributes. switch (tf) { case PACKED_FORMAT: { Int16 varchar_seen = 0; for (UInt32 i=0; i < num_attrs; i++) { attrStartOffset = offset; // set format in attrs attrs[i]->setTupleFormat(tf); attrs[i]->setDefaultFieldNum(i); if (attrs[i]->getNullFlag()) attrs[i]->setNullIndicatorLength(NULL_INDICATOR_LENGTH); if (attrs[i]->getVCIndicatorLength() > 0) attrs[i]->setVCIndicatorLength(VC_ACTUAL_LENGTH); // all fields except char/varchar fields may need alignment // at runtime. if ((attrs[i]->getDatatype() < REC_MIN_CHARACTER) || (attrs[i]->getDatatype() > REC_MAX_CHARACTER)) attrs[i]->needDataAlignment(); if (varchar_seen) { // this field follows a varchar field. Cannot // determine offset at compile time. Remember // the position of this field (as a negative number // coz all positive values could be valid offsets). attrs[i]->setSpecialField(); attrs[i]->setOffset(ExpOffsetMax); attrs[i]->setRelOffset(i); // For rows that have varchars in them, set datalen // to be the max datalen. Set 'offset' variable to reflect this. // Offset is used later to find // out the total length. offset += attrs[i]->getStorageLength(); } else { if (attrs[i]->getVCIndicatorLength() > 0) { *rtnFlags = ExpTupleDesc::VAR_FIELD_PRESENT; varchar_seen = -1; } if (attrs[i]->getNullFlag()) { attrs[i]->setNullIndOffset((Int32)offset); offset += attrs[i]->getNullIndicatorLength(); } if (attrs[i]->getVCIndicatorLength() > 0) { attrs[i]->setVCLenIndOffset(offset); offset += attrs[i]->getVCIndicatorLength(); } attrs[i]->setOffset(offset); offset += attrs[i]->getLength(); if (attrs[i]->getRowsetSize() > 0) { if (!(attrs[i]->getUseTotalRowsetSize())) { // The space used by a rowset consists of four bytes to hold // the number of entries, plus the space used by each array // entry times the number of elements attrs[i]->setOffset(attrStartOffset); offset = (attrStartOffset + ((offset - attrStartOffset) * attrs[i]->getRowsetSize()) + sizeof(Int32)); } } } // none of the previous fields is a varchar } // for } break; case SQLMX_KEY_FORMAT: { for (UInt32 i=0; i < num_attrs; i++) { attrStartOffset = offset; // set format in attrs attrs[i]->setTupleFormat(tf); if (attrs[i]->getNullFlag()) attrs[i]->setNullIndicatorLength( KEY_NULL_INDICATOR_LENGTH ); if (attrs[i]->getVCIndicatorLength() > 0) attrs[i]->setVCIndicatorLength( VC_ACTUAL_LENGTH ); // all fields except char/varchar fields may need alignment // at runtime. if ((attrs[i]->getDatatype() < REC_MIN_CHARACTER) || (attrs[i]->getDatatype() > REC_MAX_CHARACTER)) attrs[i]->needDataAlignment(); if (attrs[i]->getNullFlag()) { #pragma nowarn(1506) // warning elimination attrs[i]->setNullIndOffset(offset); #pragma warn(1506) // warning elimination offset += attrs[i]->getNullIndicatorLength(); } if (attrs[i]->getVCIndicatorLength() > 0) { attrs[i]->setVCLenIndOffset(offset); offset += attrs[i]->getVCIndicatorLength(); } attrs[i]->setOffset(offset); offset += attrs[i]->getLength(); // returns max len for varchars if (attrs[i]->getRowsetSize() > 0) { if (!(attrs[i]->getUseTotalRowsetSize())) { // The space used by a rowset consists of four bytes to hold the // number of entries, plus the space used by each array entry // times the number of elements attrs[i]->setOffset(attrStartOffset); offset = (attrStartOffset + ((offset - attrStartOffset) * attrs[i]->getRowsetSize()) + sizeof(Int32)); } } } } break; case SQLARK_EXPLODED_FORMAT: { for (UInt32 i=0; i < num_attrs; i++) { attrStartOffset = offset; // set format in attrs attrs[i]->setTupleFormat(tf); UInt32 nullIndicatorOffset = 0; UInt32 vcIndicatorOffset = 0; offset = ExpTupleDesc::sqlarkExplodedOffsets(offset, (UInt32) attrs[i]->getDataAlignmentSize(), attrs[i]->getDatatype(), attrs[i]->getNullFlag(), &nullIndicatorOffset, &vcIndicatorOffset, attrs[i]->getVCIndicatorLength() ? attrs[i]->getVCIndicatorLength() : ExpTupleDesc::VC_ACTUAL_LENGTH); if (attrs[i]->getNullFlag()) { attrs[i]->setNullIndOffset((Int32)nullIndicatorOffset); } // All datatypes, if not aligned and if we don't move // them to an aligned buffer at runtime, will trap and then // get aligned by the system. // This trap & alignement doesn't work for IEEE float datatypes // which *must* be aligned at runtime before doing any float // operations on them. // Any row which is of the format, SQLARK_EXPLODED_FORMAT, should // always start on an 8-byte boundary. But some operators do // not do this correctly and that causes float operations on // fields inside of that row to fail. // Set the needDataAlignment flag out here for ieee float // datatypes. // This is not done if this is a rowsets as values inside // of a rowset are already aligned. if ((attrs[i]->getRowsetSize() == 0) && ((attrs[i]->getDatatype() == REC_FLOAT32) || (attrs[i]->getDatatype() == REC_FLOAT64))) attrs[i]->needDataAlignment(); if (attrs[i]->getVCIndicatorLength() > 0) { attrs[i]->setVCLenIndOffset(vcIndicatorOffset); } attrs[i]->setOffset(offset); offset += attrs[i]->getLength(); if (attrs[i]->getRowsetSize() > 0) { if (!(attrs[i]->getUseTotalRowsetSize())) { UInt32 elementDataLen = 0; // The space used by a rowset consists of four bytes to hold the // number of entries, plus the space used by each array entry // times the number of elements attrs[i]->setOffset(attrStartOffset); // For rowsets, the nullIndOffset_ and vcLenIndOffset_ has to be // set to match the code in CliExpExchange.cpp for input and // output. // The offsets for rowset COBOL VARCHAR attributes is set as // follows: // - offset_ points to the start of the rowset info followed // by four bytes of the rowset size // - nullIndOffset_ (if nullIndicatorLength_ is not set to 0) // points to (offset_+4). // - vcLenIndOffset_ (if vcIndicatorLength_ is not set to 0) // points to (offset_+nullIndicatorLength_) // - The first data value starts at // (offset_+nullIndicatorLength_+vcIndicatorLength_) or // (offset_+vcIndicatorLength_) depending on whether // - nullIndicatorLength_ is valid or not. // Note vcIndicatorLength_ is set to sizeof(Int16) for rowset // SQLVarChars. if (attrs[i]->getNullFlag()){ #pragma nowarn(1506) // warning elimination attrs[i]->setNullIndOffset(attrStartOffset+sizeof(Int32)); #pragma warn(1506) // warning elimination elementDataLen += attrs[i]->getNullIndicatorLength(); if (attrs[i]->getVCIndicatorLength() > 0){ attrs[i]->setVCLenIndOffset(attrStartOffset+ attrs[i]->getNullIndicatorLength()+sizeof(Int32)); elementDataLen += attrs[i]->getVCIndicatorLength(); } } else { if (attrs[i]->getVCIndicatorLength() > 0){ attrs[i]->setVCLenIndOffset(attrStartOffset+sizeof(Int32)); elementDataLen += attrs[i]->getVCIndicatorLength(); } } elementDataLen += attrs[i]->getLength(); offset = (attrStartOffset + (elementDataLen * attrs[i]->getRowsetSize()) + sizeof(Int32)); } } } } break; case SQLMX_ALIGNED_FORMAT: case SQLMX_FORMAT: { // Loop through all attributes processing the variable length fields // first to determine how many VOA[] (variable offset array) // entries there are. The first fixed field is directly after the VOA. // The first variable length field is "saved" so the actual offset can // be set since this offset is directly after all fixed field offsets. // All other variable length fields will be computed when writing the // data to disk and the respective VOA[i] will be written to disk too. // The fixed fields are processed after all variable length fields. // Fixed field offsets are relative offsets added to the VOA[0] // value read at runtime. This is to support add column in a lazy // fashion (ie. added columns only exist when data is actually // inserted and not for old data). NABoolean alignedFormat = (tf == SQLMX_ALIGNED_FORMAT); UInt32 voaIdxOff = startOffset; UInt32 varLen = 0; UInt32 i = 0; UInt32 nullableCnt = 0; // assign a bit for each nullable field Int16 nullIndLen = (Int16)(alignedFormat ? 0 : NULL_INDICATOR_LENGTH); Int16 varIndLen = (Int16)(alignedFormat ? (Int16) ExpAlignedFormat::OFFSET_SIZE : (Int16) SQLMX_VC_ACTUAL_LENGTH); UInt32 voaSz = (alignedFormat ? ExpAlignedFormat::OFFSET_SIZE : ExpVoaSize); // Keep a handle on the first variable length field. Attributes *firstVarField = NULL; // Lists to accumulate fixed and variable fields so we can process // them in their respective groups. // GU attributes are materialized view columns that are projected out // during an update. // Variable length fields get their VOA offset set here too. NAList<UInt32> fixedColumns(10); NAList<UInt32> varFields(10); NAList<UInt32> guFields(3); NAList<UInt32> *fixedFields = &fixedColumns; *rtnFlags = 0; for ( i = 0; i < num_attrs; i++ ) { // set format in attrs attrs[i]->setTupleFormat(tf); if (attrs[i]->getNullFlag()) { // Aligned format has the null bitmap at the start of the data // thus the length is 0 for each field. // The null indicator offset will be the offset to the bitmap // within the data record. The actual bit index within the bitmap // will be stored in a new field. attrs[i]->setNullIndicatorLength( nullIndLen ); nullableCnt++; } // all fields except char/varchar fields may need to be aligned // at runtime if ((attrs[i]->getDatatype() < REC_MIN_CHARACTER) || (attrs[i]->getDatatype() > REC_MAX_CHARACTER)) attrs[i]->needDataAlignment(); // Handle variable length fields. Some varchars (aggregates) // are treated as a fixed field if the forceFixed flag is // set. if ( attrs[i]->getVCIndicatorLength() > 0 && !attrs[i]->isForceFixed()) { // Variable length fields get their VOA offset set here, // and the first variable field is saved since this variable // fields offset can be calculated and set, where as accessing // all other variable fields is done via their VOA offset. if (firstVarField == NULL) { firstVarField = attrs[i]; *rtnFlags |= ExpTupleDesc::VAR_FIELD_PRESENT; } // Different size for Packed and Aligned formats ... attrs[i]->setVCIndicatorLength( varIndLen ); attrs[i]->setVoaOffset(voaIdxOff); voaIdxOff += voaSz; // get the total storage space (Null and VC ind. len's) varLen += attrs[i]->getStorageLength(); varFields.insert(i); } else if ( attrs[i]->getVCIndicatorLength() > 0 && attrs[i]->isForceFixed()) { // Varchars that are forceFixed are treated as fixed fields. // Different size for Packed and Aligned formats ... attrs[i]->setVCIndicatorLength( varIndLen ); fixedFields->insert(i); } else if (attrs[i]->isGuOutput()) guFields.insert(i); else // have a fixed field, add it to list to process next fixedFields->insert(i); if (attrs[i]->isSpecialField()) { *rtnFlags |= ExpTupleDesc::ADDED_COLUMN; // If the added column is nullable and using Aligned format, // then there's the possibility that the key may have shifted // since the bitmap array may need to grow to accomodate this. // This is very conservative approach and we can fine-tune this // by counting the number of nullable columns and only when the // null bitmap array needs to grow set this flag. // OR if the added column is a varchar then the key may be shifted // for short rows. This is true for both formats. // OR if this is the first fixed field and it is an added column // then the key was a varchar and thus it is shifted now. if ( (attrs[i]->getNullFlag() && alignedFormat) || (attrs[i]->getVCIndicatorLength() > 0) || (fixedFields->entries() == 1) ) *rtnFlags |= ExpTupleDesc::KEY_SHIFT; } } if (varSizePtr != NULL) { *varSizePtr = varLen; } if ( alignedFormat ) { // This call destructively rearranges the list of fixed fields. orderFixedFieldsByAlignment( attrs, fixedFields ); // No variable fields present so adjust the first fixed for the // pad bytes. if ( (NULL != hdrInfo) && (varFields.entries() == 0) ) adjustFirstFixed = TRUE; } // Next, set the offsets for the accumulated fixed length fields. // The offset values are absolute offsets from the beginning of the // record. // Also setup a relative offset for Add Column support. The relative // offset is used to determine if there are missing added column values. // This relative offset is relative to VOA[0] (the first fixed offset). Attributes *field = NULL; UInt32 firstField = ExpOffsetMax; UInt32 fieldIdx = 0; UInt32 prevIdx = ExpOffsetMax; UInt16 nullBitIdx = 0; UInt32 bitmapOffset= 0; // bitmap offset value UInt32 hdrSz; // size in bytes of header UInt32 fixedOffset; // first fixed offset value Int32 ffAlignSize = (fixedFields->entries() ? attrs[fixedFields->at(0)]->getDataAlignmentSize() : -1); fixedOffset = computeFirstFixedOffset(ffAlignSize, startOffset, voaIdxOff, tf, nullableCnt, hdrInfo, hdrSz, bitmapOffset); if (headerSizePtr) *headerSizePtr = fixedOffset; // Set offsets for all the fixed fields ... while( fixedFields->entries() ) { fixedFields->getFirst( fieldIdx ); computeOffsetOfFixedField(attrs, fieldIdx, bitmapOffset, fixedOffset, firstField, prevIdx, nullBitIdx, hdrInfo, alignedFormat); } // Set offsets for all the variable length fields ... firstField = ExpOffsetMax; while( varFields.entries() ) { varFields.getFirst( fieldIdx ); field = attrs[fieldIdx]; if (prevIdx != ExpOffsetMax) attrs[prevIdx]->setNextFieldIndex(fieldIdx); // bump each voa offset by the header size field->setVoaOffset( hdrSz + field->getVoaOffset() ); // The first variable length field handled like a fixed field // since the offset can be computed at compile time. if (firstField == ExpOffsetMax) { UInt32 firstVarOffset; firstField = fieldIdx; // set the first variable length field's offset to a // valid offset (at the end of all fixed fields) firstVarOffset = fixedOffset; if (field->getNullFlag() && (NOT alignedFormat) ) { field->setNullIndOffset( firstVarOffset ); firstVarOffset += field->getNullIndicatorLength(); } field->setVCLenIndOffset(firstVarOffset); firstVarOffset += field->getVCIndicatorLength(); field->setOffset(firstVarOffset); } if ( field->getNullFlag() && alignedFormat ) { // Each nullable field in the aligned format // has the same null indicator offset that // points to the start of the bitmap and a bit within // the null bitmap that is set if the field is null. field->setNullBitIndex( nullBitIdx++ ); field->setNullIndOffset( bitmapOffset ); } prevIdx = fieldIdx; } // Repeat the fixed field treatment for GuOutput fields. while( guFields.entries() ) { guFields.getFirst( fieldIdx ); computeOffsetOfFixedField(attrs, fieldIdx, bitmapOffset, fixedOffset, firstField, prevIdx, nullBitIdx); } // add in the max length of exploded variable length fields // since we must allocate space for maximum field values offset = fixedOffset + varLen; // Align format may have to pad the record out 1 - 3 bytes to // ensure each record starts on a 4-byte boundary. if (alignedFormat) { if (adjustFirstFixed) { offset = hdrInfo->adjustFirstFixed( offset ); } else { offset = ADJUST(offset, ExpAlignedFormat::ALIGNMENT); } } nullBitIdx = 0; for ( i = 0; i < num_attrs; i++ ) { if (attrs[i]->getNullFlag()) { attrs[i]->setNullBitIndex(nullBitIdx++ ); } } if(fixedFields->entries() && ((*rtnFlags & ADDED_COLUMN) > 0)) *rtnFlags |= ExpTupleDesc::ADDED_FIXED_PRESENT; #if defined( LOG_OFFSETS ) fprintf(stderr, "RowLen: %d \n", offset); for(Int32 k = 0; k < (Int32)num_attrs; k++) { Attributes *attr = attrs[k]; fprintf(stderr, " Attr(%d): dataType: %d nullable: %d variable: %d " "offset: %d voaOff: %d align: %d\n", k, attr->getDatatype(), attr->getNullFlag(), (attr->getVCIndicatorLength() > 0 ? 1 : 0), attr->getOffset(), attr->getVoaOffset(), attr->getDataAlignmentSize()); } #endif } break; default: break; } // switch tf datalen = offset - startOffset; return 0; } UInt32 ExpTupleDesc::sqlarkExplodedOffsets( UInt32 offset, UInt32 length, Int16 dataType, NABoolean isNullable, UInt32 * nullIndicatorOffset, UInt32 * vcIndicatorOffset, UInt32 vcIndicatorSize) { if (isNullable) { offset = ADJUST(offset, ExpTupleDesc::NULL_INDICATOR_LENGTH); if (nullIndicatorOffset) *nullIndicatorOffset = offset; offset += ExpTupleDesc::NULL_INDICATOR_LENGTH; } if (DFS2REC::isAnyVarChar(dataType)) { offset = ADJUST(offset, vcIndicatorSize); if (vcIndicatorOffset) *vcIndicatorOffset = offset; offset += vcIndicatorSize; } // column value alignment if (DFS2REC::isNumeric(dataType)) offset = ADJUST(offset, length); return offset; } Long ExpTupleDesc::pack(void * space) { if (! packed()) { #pragma nowarn(1506) // warning elimination if (attrs_) attrs_.pack(space, numAttrs_); #pragma warn(1506) // warning elimination } flags_ |= PACKED; return NAVersionedObject::pack(space); } Int32 ExpTupleDesc::unpack(void * base, void * reallocator) { if (packed()) { if (attrs_) #pragma nowarn(1506) // warning elimination if (attrs_.unpack(base, numAttrs_, reallocator)) return -1; #pragma warn(1506) // warning elimination flags_ &= ~PACKED; } return NAVersionedObject::unpack(base, reallocator); } Int16 ExpTupleDesc::operator==(ExpTupleDesc * other) { if ((numAttrs_ != other->numAttrs_) || (tupleDataFormat_ != other->tupleDataFormat_)) return 0; for (UInt32 i = 0; i < numAttrs_; i++) { if (! (*getAttr(i) == *other->getAttr(i))) return 0; } return -1; } // assigns the atp and atp_index value to all attributes void ExpTupleDesc::assignAtpAndIndex(Int16 atp, Int16 atp_index) { // attributes must be unpacked before they could be referenced if ((attrs_) && (! packed())) { for (UInt32 i=0; i < numAttrs_; i++) { attrs_[i]->setAtp(atp); attrs_[i]->setAtpIndex(atp_index); } } } void ExpTupleDesc::display(const char* title) { if (title) cout << title; else cout << "ExpTupleDesc::display()"; cout << endl; UInt32 attrs = numAttrs(); cout << "this=" << this << ", num of attrs=" << attrs << endl; for (Int32 j=0; j<attrs; j++) { Attributes* attr = getAttr(j); Int16 dt = attr->getDatatype(); UInt32 len = attr->getLength(); cout << j << "th attr: dt=" << dt << ", len=" << len << endl; } }
apache-2.0
apaprocki/bde
groups/bdl/bdlt/bdlt_datetz.t.cpp
2
90559
// bdlt_datetz.t.cpp -*-C++-*- #include <bdlt_datetz.h> #include <bdlt_date.h> #include <bdlt_datetime.h> #include <bslim_testutil.h> #include <bslma_testallocator.h> #include <bsls_assert.h> #include <bsls_asserttest.h> #include <bslx_byteinstream.h> #include <bslx_byteoutstream.h> #include <bslx_instreamfunctions.h> #include <bslx_outstreamfunctions.h> #include <bslx_testinstream.h> #include <bslx_testinstreamexception.h> #include <bslx_testoutstream.h> #include <bslx_versionfunctions.h> #include <bsl_cstdlib.h> // 'atoi' #include <bsl_iomanip.h> #include <bsl_iostream.h> #include <bsl_sstream.h> using namespace BloombergLP; using namespace bsl; // ============================================================================ // TEST PLAN // ============================================================================ // // Overview // -------- // The component under test implements a single value-semantic class, // 'bdlt::DateTz', that represents a date value with a local time offset. // // Primary Manipulators: //: o VALUE CONSTRUCTOR // // Basic Accessors: //: o 'localDate' //: o 'offset' // // This particular class provides a value constructor capable of creating an // object in any state relevant for thorough testing. The value constructor // serves as our primary manipulator and also obviates the primitive generator // function, 'gg', normally used for this purpose. // ---------------------------------------------------------------------------- // CLASS METHODS // [12] static bool isValid(const Date& localDate, int offset); // [10] static int maxSupportedBdexVersion(int versionSelector); // // CREATORS // [11] DateTz(); // [ 7] DateTz(const DateTz& original); // [ 2] DateTz(const Date& localDate, int offset); // [ 2] ~DateTz(); // // MANIPULATORS // [ 9] Date& operator=(const Date& rhs); // [11] void setDateTz(const Date& localDate, int offset); // [12] bool setDateTzIfValid(const Date& localDate, int offset); // [10] STREAM& bdexStreamIn(STREAM& stream, int version); // // ACCESSORS // [10] STREAM& bdexStreamOut(STREAM& stream, int version) const; // [13] Datetime utcStartTime() const; // [ 4] Date localDate() const; // [ 4] int offset() const; // [ 5] bsl::ostream& print(bsl::ostream& stream, int l, int spl) const; // // FREE OPERATORS // [ 6] bool operator==(const DateTz& lhs, const DateTz& rhs); // [ 6] bool operator!=(const DateTz& lhs, const DateTz& rhs); // [ 5] bsl::ostream& operator<<(bsl::ostream&, const DateTz&); // [16] void hashAppend(HASHALG&, const DateTz&); // ---------------------------------------------------------------------------- // [ 1] BREATHING TEST // [17] USAGE EXAMPLE // [ 8] Reserved for 'swap' testing. // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- typedef bdlt::DateTz Obj; typedef bslx::TestInStream In; typedef bslx::TestOutStream Out; #define VERSION_SELECTOR 20140601 //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { const int test = argc > 1 ? atoi(argv[1]) : 0; const bool verbose = argc > 2; const bool veryVerbose = argc > 3; const bool veryVeryVerbose = argc > 4; const bool veryVeryVeryVerbose = argc > 5; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: case 17: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from component header file. // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "USAGE EXAMPLE" << endl << "=============" << endl; ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Representing Dates In Different Time Zones ///- - - - - - - - - - - - - - - - - - - - - - - - - - - // Suppose that we need to compare dates in different time zones. The // 'bdlt::DateTz' type helps us to accomplish this. // // First, we default construct an object 'dateTz1', which has an offset of 0, // implying that the object represents a date in the UTC time zone. //.. bdlt::DateTz dateTz1; ASSERT(0 == dateTz1.offset()); ASSERT(dateTz1.localDate() == dateTz1.utcStartTime().date()); ASSERT(dateTz1.localDate() == bdlt::Date()); //.. // Notice the value of a default contructed 'bdlt::DateTz' object is the same // as that of a default constructed 'bdlt::Date' object. // // Then, we construct two objects 'dateTz2' and 'dateTz3' to have a local date // of 2013/12/31 in the EST time zone (UTC-5) and the pacific time zone (UTC-8) // respectively: //.. bdlt::DateTz dateTz2 (bdlt::Date(2013, 12, 31), -5 * 60); bdlt::DateTz dateTz3 (bdlt::Date(2013, 12, 31), -8 * 60); //.. // Next, we compare the local dates of the two 'DateTz' objects, and verify // that they compare equal: //.. bdlt::Date localDate(2013, 12, 31); ASSERT(localDate == dateTz2.localDate()); ASSERT(localDate == dateTz3.localDate()); //.. // Finally, we compare the starting time of the two 'DateTz' objects using the // 'utcStartTime' method: //.. ASSERT(dateTz2.utcStartTime() < dateTz3.utcStartTime()); //.. } break; case 16: { // -------------------------------------------------------------------- // TESTING: hashAppend // // Concerns: //: 1 Hope that different inputs hash differently //: 2 Verify that equal inputs hash identically //: 3 Works for const and non-const values // // Plan: //: 1 Use a table specifying a set of distinct objects, verify that //: hashes of equivalent objects match and hashes on unequal objects //: do not. // // Testing: // void hashAppend(HASHALG& hashAlg, const Calendar&); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'hashAppend'" << "\n====================\n"; typedef ::BloombergLP::bslh::Hash<> Hasher; typedef Hasher::result_type HashType; Hasher hasher; if (verbose) cout << "\nCompare hashes of pairs of values (u, v) in S X S." << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 1, 1, 2, 0 }, { L_, 1, 2, 1, 0 }, { L_, 2, 1, 1, 1439 }, { L_, 1, 1, 1, -1 }, { L_, 1, 1, 2, 1 }, { L_, 1, 2, 1, -1439 }, { L_, 2, 1, 1, 1438 }, { L_, 9998, 12, 31, 0 }, { L_, 9999, 11, 30, 0 }, { L_, 9999, 12, 30, 0 }, { L_, 9999, 12, 31, 0 }, { L_, 9998, 12, 31, 1 }, { L_, 9999, 11, 30, -1439 }, { L_, 9999, 12, 30, -1 }, { L_, 9999, 12, 31, -143 }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int U_LINE = DATA[i].d_line; const int U_YEAR = DATA[i].d_year; const int U_MONTH = DATA[i].d_month; const int U_DAY = DATA[i].d_day; const int U_OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P(U_LINE) P_(U_YEAR) P_(U_MONTH) P_(U_DAY) P(U_OFFSET); } const bdlt::Date U_DATE(U_YEAR, U_MONTH, U_DAY); const Obj U(U_DATE, U_OFFSET); for (int j = 0; j < NUM_DATA; ++j) { const int V_LINE = DATA[j].d_line; const int V_YEAR = DATA[j].d_year; const int V_MONTH = DATA[j].d_month; const int V_DAY = DATA[j].d_day; const int V_OFFSET = DATA[j].d_offset; if (veryVerbose) { T_ T_ P_(V_LINE) P_(V_YEAR); P_(V_MONTH) P_(V_DAY) P(V_OFFSET); } const bdlt::Date V_DATE(V_YEAR, V_MONTH, V_DAY); const Obj V(V_DATE, V_OFFSET); HashType hU = hasher(U); HashType hV = hasher(V); if (veryVeryVerbose) { T_ T_ T_ P_(i) P_(j) P_(hU) P(hV) } ASSERTV(U_LINE, V_LINE, (i == j) == (hU == hV)); } } } } break; case 15: { // Deprecated test case. Do not remove. } break; case 14: { // Deprecated test case. Do not remove. } break; case 13: { // -------------------------------------------------------------------- // 'utcStartTime' METHOD // // Concerns: //: 1 'utcStartTime' computes the correct UTC start time of the local //: date accordingly to its timezone. // // Plan: //: 1 Using the table-driven technique, specify a set of dates, their //: associated offset, and their starting UTC times. Verify that //: 'utcStartTime' return the expected value the following invariant //: hold: 'utcStartTime() == localDate() - offset()'. (C-1) // // Testing: // Datetime utcStartTime() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "'utcStartTime' METHOD" << endl << "=====================" << endl; struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset int d_utcYear; // expected UTC year int d_utcMonth; // expected UTC month int d_utcDay; // expected UTC day int d_utcHour; // expected UTC hour int d_utcMinute; // expected UTC minute } DATA[] = { //LINE YR MO D OFF G_Y G_M G_D G_H G_M //---- -- -- -- --- --- --- --- --- --- { L_, 1, 1, 1, 0, 1, 1, 1, 0, 0 }, { L_, 1, 1, 1, -1, 1, 1, 1, 0, 1 }, { L_, 1, 1, 2, 1, 1, 1, 1, 23, 59 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; const int UTC_YEAR = DATA[i].d_utcYear; const int UTC_MONTH = DATA[i].d_utcMonth; const int UTC_DAY = DATA[i].d_utcDay; const int UTC_HOUR = DATA[i].d_utcHour; const int UTC_MINUTE = DATA[i].d_utcMinute; if(veryVerbose) { T_ P_(LINE) P_(YEAR) P_(MONTH) P_(DAY) P_(OFFSET) P_(UTC_YEAR) P_(UTC_MONTH) P_(UTC_DAY) P_(UTC_HOUR) P(UTC_MINUTE) } const bdlt::Date TEMP_DATE(YEAR, MONTH, DAY); const Obj X(TEMP_DATE, OFFSET); const bdlt::Datetime EXP1(UTC_YEAR, UTC_MONTH, UTC_DAY, UTC_HOUR, UTC_MINUTE); bdlt::Datetime exp2(bdlt::Datetime(X.localDate())); const bdlt::Datetime& EXP2 = exp2; exp2.addMinutes(-X.offset()); if (veryVerbose) { T_ cout << "UTC START TIME: " << X.utcStartTime() << endl; } ASSERTV(LINE, EXP1 == X.utcStartTime()); ASSERTV(LINE, EXP2 == X.utcStartTime()); } } break; case 12: { // -------------------------------------------------------------------- // 'isValid' AND 'setDateTzIfValid' METHODS // // Concerns: //: 1 'isValid' correctly determines whether a date and an associated //: offset are valid attributes of a 'DateTz' object. //: //: 2 'setDateTzIfValid' sets the date and offset of a 'DateTz' //: object to the specified values only if they are valid. // // Plan: //: 1 Using the table-driven technique, specify a set of valid and //: invalid object values. For each value verify that 'isValid' //: returns the correct result and 'setDateTzIfValid' behaves //: correctly. (C-1..2) // // Testing: // static bool isValid(const Date& localDate, int offset); // bool setDateTzIfValid(const Date& localDate, int offset); // -------------------------------------------------------------------- // Set the assert handler to mute error coming from construction of an // invalid date. if (verbose) cout << endl << "'isValid' AND 'setDateTzIfValid' METHODS" << endl << "========================================" << endl; enum { MAX_TIMEZONE = 24 * 60 - 1, MTZ = MAX_TIMEZONE }; struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset int d_isValid; // is valid } DATA[] = { //LINE YEAR MO DAY OFF VALID //---- ---- -- --- --- ----- { L_, 1776, 7, 4, 0, 1 }, { L_, 1776, 7, 4, 4*60, 1 }, { L_, 1776, 7, 4, -4*60, 1 }, { L_, 1776, 7, 4, MTZ, 1 }, { L_, 1776, 7, 4, -MTZ, 1 }, { L_, 1776, 7, 4, 24*60, 0 }, { L_, 1776, 7, 4, -24*60, 0 }, { L_, 1776, 7, 4, 99*60, 0 }, { L_, 1776, 7, 4, -99*60, 0 }, { L_, 1, 1, 1, 0, 1 }, { L_, 1, 1, 1, MTZ, 1 }, { L_, 1, 1, 1, -MTZ, 1 }, { L_, 1, 1, 1, 24*60, 0 }, { L_, 1, 1, 1, -24*60, 0 }, { L_, 1, 1, 1, 99*60, 0 }, { L_, 1, 1, 1, -99*60, 0 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int di = 0; di < NUM_DATA; ++di) { const int LINE = DATA[di].d_line; const int YEAR = DATA[di].d_year; const int MONTH = DATA[di].d_month; const int DAY = DATA[di].d_day; const int OFFSET = DATA[di].d_offset; const int IS_VALID = DATA[di].d_isValid; if(veryVerbose) { T_ P_(LINE) P_(YEAR) P_(MONTH) P_(DAY) P_(OFFSET) P(IS_VALID) } const bdlt::Date SRC_DATE(YEAR, MONTH, DAY); ASSERTV(LINE, IS_VALID == bdlt::DateTz::isValid(SRC_DATE, OFFSET)); const bdlt::Date DEST_DATE(2003, 3, 18); bdlt::DateTz t(DEST_DATE, 5*60); int sts = t.setDateTzIfValid(SRC_DATE, OFFSET); ASSERTV(LINE, IS_VALID == !sts); if (IS_VALID) { ASSERTV(LINE, t.localDate().year() == YEAR); ASSERTV(LINE, t.localDate().month() == MONTH); ASSERTV(LINE, t.localDate().day() == DAY); ASSERTV(LINE, t.offset() == OFFSET); } else { // verify t was unchanged. ASSERTV(LINE, t.localDate().year() == 2003); ASSERTV(LINE, t.localDate().month() == 3); ASSERTV(LINE, t.localDate().day() == 18); ASSERTV(LINE, t.offset() == 5*60); } } } break; case 11: { // -------------------------------------------------------------------- // DEFAULT CTOR AND 'setDateTz' METHOD // // Concerns: //: 1 An object created with the default constructor has the //: contractually specified default value. //: //: 2 The 'setDateTz' method sets the date and locale offset of the //: object to the specified values. //: //: 3 QoI: Asserted precondition violations are detected when enabled. // // Plan: //: 1 Default construct an object and verify that the object has the //: expected value. (C-1) //: //: 2 Use the table-driven technique, specify a range of distinct date //: and offset values. Pass each value to the 'setDateTz' method and //: verify that the resulting object value is correct. (C-2) //: //: 3 Verify that, in appropriate build modes, defensive checks are //: triggered for invalid attribute values, but not triggered for //: adjacent valid ones (using the 'BSLS_ASSERTTEST_*' macros). //: (C-3) // // Testing: // DateTz(); // void setDateTz(const Date& localDate, int offset); // -------------------------------------------------------------------- if (verbose) cout << endl << "DEFAULT CTOR AND 'setDateTz' METHOD" << endl << "===================================" << endl; if (verbose) cout << "\nTesting default constructor." << endl; { Obj mX; const Obj& X = mX; const bdlt::Date& LOCAL_DATE = X.localDate(); ASSERT(1 == LOCAL_DATE.year()); ASSERT(1 == LOCAL_DATE.month()); ASSERT(1 == LOCAL_DATE.day()); ASSERT(0 == X.offset()); } if (verbose) cout << "\nTesting how 'setDateTz' forwards 'Date'." << endl; { // First let's make sure that the 'Date' object is passed down // correctly, let's use a 3 different offsets. static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 1600, 6, 30, 5*60 }, { L_, 9999, 12, 31, 23*60 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET) } const Obj ZZ(bdlt::Date(YEAR, MONTH, DAY), OFFSET); Obj mX; const Obj& X = mX; mX.setDateTz(bdlt::Date(YEAR, MONTH, DAY), OFFSET); if (veryVeryVerbose) { T_ T_ P_(ZZ) P(X) } ASSERTV(LINE, ZZ == X); } } if (verbose) cout << "\nTesting 'setDateTz' with different offsets." << endl; { // Now we trust that the 'Date' construction part is reliable. // Let's verify that the offset part works fine. const int DATA[] = { -1439, -1339, -60, -1, 0, 1, 60, 1339, 1439 }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int YEAR = 1; const int MONTH = 1; const int DAY = 1; const int OFFSET = DATA[i]; if (veryVerbose) { T_ P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET) } Obj mX; const Obj& X = mX; bdlt::Date TEMP_DATE(YEAR, MONTH, DAY); mX.setDateTz(TEMP_DATE, OFFSET); if (veryVeryVerbose) { T_ T_ P(X) } const bdlt::Date& LOCAL_DATE = X.localDate(); ASSERTV(i, YEAR == LOCAL_DATE.year()); ASSERTV(i, MONTH == LOCAL_DATE.month()); ASSERTV(i, DAY == LOCAL_DATE.day()); ASSERTV(i, OFFSET == X.offset()); } } // Negative Testing if (verbose) cout << "\nTesting 'setDateTz' with invalid data (negative test)." << endl; { bsls::AssertFailureHandlerGuard hG( bsls::AssertTest::failTestDriver); if (veryVerbose) cout << "\t'timeout'" << endl; { Obj mX; ASSERT_SAFE_FAIL(mX.setDateTz(bdlt::Date(), 1440)); ASSERT_SAFE_PASS(mX.setDateTz(bdlt::Date(), 1439)); ASSERT_SAFE_FAIL(mX.setDateTz(bdlt::Date(), -1440)); ASSERT_SAFE_PASS(mX.setDateTz(bdlt::Date(), -1439)); } } } break; case 10: { // -------------------------------------------------------------------- // TESTING BDEX STREAMING // Verify the BDEX streaming implementation works correctly. // Specific concerns include wire format, handling of stream states // (valid, empty, invalid, incomplete, and corrupted), and exception // neutrality. // // Concerns: //: 1 The class method 'maxSupportedBdexVersion' returns the correct //: version to be used for the specified 'versionSelector'. //: //: 2 The 'bdexStreamOut' method is callable on a reference providing //: only non-modifiable access. //: //: 3 For valid streams, externalization and unexternalization are //: inverse operations. //: //: 4 For invalid streams, externalization leaves the stream invalid //: and unexternalization does not alter the value of the object and //: leaves the stream invalid. //: //: 5 Unexternalizing of incomplete, invalid, or corrupted data results //: in a valid object of unspecified value and an invalidated stream. //: //: 6 The wire format of the object is as expected. //: //: 7 All methods are exception neutral. //: //: 8 The 'bdexStreamIn' and 'bdexStreamOut' methods return a reference //: to the provided stream in all situations. //: //: 9 The initial value of the object has no affect on //: unexternalization. // // Plan: //: 1 Test 'maxSupportedBdexVersion' explicitly. (C-1) //: //: 2 All calls to the 'bdexStreamOut' accessor will be done from a //: 'const' object or reference and all calls to the 'bdexStreamOut' //: free function (provided by 'bslx') will be supplied a 'const' //: object or reference. (C-2) //: //: 3 Perform a direct test of the 'bdexStreamOut' and 'bdexStreamIn' //: methods (the rest of the testing will use the free functions //: 'bslx::OutStreamFunctions::bdexStreamOut' and //: 'bslx::InStreamFunctions::bdexStreamIn'). //: //: 4 Define a set 'S' of test values to be used throughout the test //: case. //: //: 5 For all '(u, v)' in the cross product 'S X S', stream the value //: of 'u' into (a temporary copy of) 'v', 'T', and assert 'T == u'. //: (C-3, 9) //: //: 6 For all 'u' in 'S', create a copy of 'u' and attempt to stream //: into it from an invalid stream. Verify after each attempt that //: the object is unchanged and that the stream is invalid. (C-4) //: //: 7 Write 3 distinct objects to an output stream buffer of total //: length 'N'. For each partial stream length from 0 to 'N - 1', //: construct an input stream and attempt to read into objects //: initialized with distinct values. Verify values of objects //: that are either successfully modified or left entirely //: unmodified, and that the stream became invalid immediately after //: the first incomplete read. Finally, ensure that each object //: streamed into is in some valid state. //: //: 8 Use the underlying stream package to simulate a typical valid //: (control) stream and verify that it can be streamed in //: successfully. Then for each data field in the stream (beginning //: with the version number), provide one or more similar tests with //: that data field corrupted. After each test, verify that the //: object is in some valid state after streaming, and that the //: input stream has become invalid. (C-5) //: //: 9 Explicitly test the wire format. (C-6) //: //:10 In all cases, confirm exception neutrality using the specially //: instrumented 'bslx::TestInStream' and a pair of standard macros, //: 'BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN' and //: 'BSLX_TESTINSTREAM_EXCEPTION_TEST_END', which configure the //: 'bslx::TestInStream' object appropriately in a loop. (C-7) //: //:11 In all cases, verify the return value of the tested method. //: (C-8) // // Testing: // static int maxSupportedBdexVersion(int versionSelector); // STREAM& bdexStreamIn(STREAM& stream, int version); // STREAM& bdexStreamOut(STREAM& stream, int version) const; // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING BDEX STREAMING" << endl << "======================" << endl; // Allocator to use instead of the default allocator. bslma::TestAllocator allocator("bslx", veryVeryVeryVerbose); // Scalar object values used in various stream tests. const bdlt::Date A( 1, 1, 1); const bdlt::Date B( 1, 1, 2); const bdlt::Date C( 3, 4, 7); const bdlt::Date D(2012, 4, 7); const bdlt::Date E(2014, 6, 14); const bdlt::Date F(2014, 10, 22); const bdlt::Date G(9999, 12, 31); const Obj VA(A, 0); const Obj VB(B, 1); const Obj VC(C, -1); const Obj VD(D, 203); const Obj VE(E, -507); const Obj VF(F, 1000); const Obj VG(G, -1100); // Array object used in various stream tests. const Obj VALUES[] = { VA, VB, VC, VD, VE, VF, VG }; const int NUM_VALUES = static_cast<int>(sizeof VALUES / sizeof *VALUES); if (verbose) { cout << "\nTesting 'maxSupportedBdexVersion'." << endl; } { ASSERT(1 == Obj::maxSupportedBdexVersion(0)); ASSERT(1 == Obj::maxSupportedBdexVersion(VERSION_SELECTOR)); using bslx::VersionFunctions::maxSupportedBdexVersion; ASSERT(1 == maxSupportedBdexVersion(reinterpret_cast<Obj *>(0), 0)); ASSERT(1 == maxSupportedBdexVersion(reinterpret_cast<Obj *>(0), VERSION_SELECTOR)); } const int VERSION = Obj::maxSupportedBdexVersion(0); if (verbose) { cout << "\nDirect initial trial of 'bdexStreamOut' and (valid) " << "'bdexStreamIn' functionality." << endl; } { const Obj X(VC); Out out(VERSION_SELECTOR, &allocator); Out& rvOut = X.bdexStreamOut(out, VERSION); ASSERT(&out == &rvOut); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); In in(OD, LOD); ASSERT(in); ASSERT(!in.isEmpty()); Obj mT(VA); const Obj& T = mT; ASSERT(X != T); In& rvIn = mT.bdexStreamIn(in, VERSION); ASSERT(&in == &rvIn); ASSERT(X == T); ASSERT(in); ASSERT(in.isEmpty()); } // We will use the stream free functions provided by 'bslx', as opposed // to the class member functions, since the 'bslx' implementation gives // priority to the free function implementations; we want to test what // will be used. Furthermore, toward making this test case more // reusable in other components, from here on we generally use the // 'bdexStreamIn' and 'bdexStreamOut' free functions that are defined // in the 'bslx' package rather than call the like-named member // functions directly. if (verbose) { cout << "\nThorough test using stream free functions." << endl; } { for (int i = 0; i < NUM_VALUES; ++i) { const Obj X(VALUES[i]); Out out(VERSION_SELECTOR, &allocator); using bslx::OutStreamFunctions::bdexStreamOut; using bslx::InStreamFunctions::bdexStreamIn; Out& rvOut = bdexStreamOut(out, X, VERSION); LOOP_ASSERT(i, &out == &rvOut); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); // Verify that each new value overwrites every old value and // that the input stream is emptied, but remains valid. for (int j = 0; j < NUM_VALUES; ++j) { In in(OD, LOD); LOOP2_ASSERT(i, j, in); LOOP2_ASSERT(i, j, !in.isEmpty()); Obj mT(VALUES[j]); const Obj& T = mT; LOOP2_ASSERT(i, j, (X == T) == (i == j)); BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) { in.reset(); In& rvIn = bdexStreamIn(in, mT, VERSION); LOOP2_ASSERT(i, j, &in == &rvIn); } BSLX_TESTINSTREAM_EXCEPTION_TEST_END LOOP2_ASSERT(i, j, X == T); LOOP2_ASSERT(i, j, in); LOOP2_ASSERT(i, j, in.isEmpty()); } } } if (verbose) { cout << "\tOn empty streams and non-empty, invalid streams." << endl; } // Verify correct behavior for empty streams (valid and invalid). { Out out(VERSION_SELECTOR, &allocator); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); ASSERT(0 == LOD); for (int i = 0; i < NUM_VALUES; ++i) { In in(OD, LOD); LOOP_ASSERT(i, in); LOOP_ASSERT(i, in.isEmpty()); // Ensure that reading from an empty or invalid input stream // leaves the stream invalid and the target object unchanged. using bslx::InStreamFunctions::bdexStreamIn; const Obj X(VALUES[i]); Obj mT(X); const Obj& T = mT; LOOP_ASSERT(i, X == T); BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) { in.reset(); // Stream is valid. In& rvIn1 = bdexStreamIn(in, mT, VERSION); LOOP_ASSERT(i, &in == &rvIn1); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, X == T); // Stream is invalid. In& rvIn2 = bdexStreamIn(in, mT, VERSION); LOOP_ASSERT(i, &in == &rvIn2); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, X == T); } BSLX_TESTINSTREAM_EXCEPTION_TEST_END } } // Verify correct behavior for non-empty, invalid streams. { Out out(VERSION_SELECTOR, &allocator); using bslx::OutStreamFunctions::bdexStreamOut; Out& rvOut = bdexStreamOut(out, Obj(), VERSION); ASSERT(&out == &rvOut); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); ASSERT(0 < LOD); for (int i = 0; i < NUM_VALUES; ++i) { In in(OD, LOD); in.invalidate(); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, !in.isEmpty()); // Ensure that reading from a non-empty, invalid input stream // leaves the stream invalid and the target object unchanged. using bslx::InStreamFunctions::bdexStreamIn; const Obj X(VALUES[i]); Obj mT(X); const Obj& T = mT; LOOP_ASSERT(i, X == T); BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) { in.reset(); in.invalidate(); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, !in.isEmpty()); In& rvIn = bdexStreamIn(in, mT, VERSION); LOOP_ASSERT(i, &in == &rvIn); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, X == T); } BSLX_TESTINSTREAM_EXCEPTION_TEST_END } } if (verbose) { cout << "\tOn incomplete (but otherwise valid) data." << endl; } { const Obj W1 = VA, X1 = VB; const Obj W2 = VB, X2 = VC; const Obj W3 = VC, X3 = VD; using bslx::OutStreamFunctions::bdexStreamOut; using bslx::InStreamFunctions::bdexStreamIn; Out out(VERSION_SELECTOR, &allocator); Out& rvOut1 = bdexStreamOut(out, X1, VERSION); ASSERT(&out == &rvOut1); const int LOD1 = static_cast<int>(out.length()); Out& rvOut2 = bdexStreamOut(out, X2, VERSION); ASSERT(&out == &rvOut2); const int LOD2 = static_cast<int>(out.length()); Out& rvOut3 = bdexStreamOut(out, X3, VERSION); ASSERT(&out == &rvOut3); const int LOD3 = static_cast<int>(out.length()); const char *const OD3 = out.data(); for (int i = 0; i < LOD3; ++i) { In in(OD3, i); BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) { in.reset(); LOOP_ASSERT(i, in); LOOP_ASSERT(i, !i == in.isEmpty()); Obj mT1(W1); const Obj& T1 = mT1; Obj mT2(W2); const Obj& T2 = mT2; Obj mT3(W3); const Obj& T3 = mT3; if (i < LOD1) { In& rvIn1 = bdexStreamIn(in, mT1, VERSION); LOOP_ASSERT(i, &in == &rvIn1); LOOP_ASSERT(i, !in); if (0 == i) LOOP_ASSERT(i, W1 == T1); In& rvIn2 = bdexStreamIn(in, mT2, VERSION); LOOP_ASSERT(i, &in == &rvIn2); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, W2 == T2); In& rvIn3 = bdexStreamIn(in, mT3, VERSION); LOOP_ASSERT(i, &in == &rvIn3); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, W3 == T3); } else if (i < LOD2) { In& rvIn1 = bdexStreamIn(in, mT1, VERSION); LOOP_ASSERT(i, &in == &rvIn1); LOOP_ASSERT(i, in); LOOP_ASSERT(i, X1 == T1); In& rvIn2 = bdexStreamIn(in, mT2, VERSION); LOOP_ASSERT(i, &in == &rvIn2); LOOP_ASSERT(i, !in); if (LOD1 <= i) LOOP_ASSERT(i, W2 == T2); In& rvIn3 = bdexStreamIn(in, mT3, VERSION); LOOP_ASSERT(i, &in == &rvIn3); LOOP_ASSERT(i, !in); LOOP_ASSERT(i, W3 == T3); } else { // 'LOD2 <= i < LOD3' In& rvIn1 = bdexStreamIn(in, mT1, VERSION); LOOP_ASSERT(i, &in == &rvIn1); LOOP_ASSERT(i, in); LOOP_ASSERT(i, X1 == T1); In& rvIn2 = bdexStreamIn(in, mT2, VERSION); LOOP_ASSERT(i, &in == &rvIn2); LOOP_ASSERT(i, in); LOOP_ASSERT(i, X2 == T2); In& rvIn3 = bdexStreamIn(in, mT3, VERSION); LOOP_ASSERT(i, &in == &rvIn3); LOOP_ASSERT(i, !in); if (LOD2 <= i) LOOP_ASSERT(i, W3 == T3); } // Verify the objects are in a valid state. LOOP_ASSERT(i, -1440 < T1.offset() && 1440 > T1.offset()); LOOP_ASSERT(i, -1440 < T2.offset() && 1440 > T2.offset()); LOOP_ASSERT(i, -1440 < T3.offset() && 1440 > T3.offset()); } BSLX_TESTINSTREAM_EXCEPTION_TEST_END } } if (verbose) { cout << "\tOn corrupted data." << endl; } const Obj W; // default value const Obj X(bdlt::Date(1, 1, 1), -3); // original (control) const Obj Y(bdlt::Date(1, 1, 1), 1); // new (streamed-out) // Verify the three objects are distinct. ASSERT(W != X); ASSERT(W != Y); ASSERT(X != Y); const int SERIAL_Y = 1; // internal rep. of 'Y.offset()' if (verbose) { cout << "\t\tGood stream (for control)." << endl; } { Out out(VERSION_SELECTOR, &allocator); // Stream out "new" value. using bslx::OutStreamFunctions::bdexStreamOut; bdexStreamOut(out, bdlt::Date(1, 1, 1), VERSION); out.putInt32(SERIAL_Y); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); Obj mT(X); const Obj& T = mT; ASSERT(X == T); In in(OD, LOD); ASSERT(in); using bslx::InStreamFunctions::bdexStreamIn; In& rvIn = bdexStreamIn(in, mT, VERSION); ASSERT(&in == &rvIn); ASSERT(in); ASSERT(Y == T); } if (verbose) { cout << "\t\tBad version." << endl; } { const char version = 0; // too small ('version' must be >= 1) Out out(VERSION_SELECTOR, &allocator); // Stream out "new" value. using bslx::OutStreamFunctions::bdexStreamOut; bdexStreamOut(out, bdlt::Date(1, 1, 1), VERSION); out.putInt32(SERIAL_Y); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); Obj mT(X); const Obj& T = mT; ASSERT(X == T); In in(OD, LOD); ASSERT(in); in.setQuiet(!veryVerbose); using bslx::InStreamFunctions::bdexStreamIn; In& rvIn = bdexStreamIn(in, mT, version); ASSERT(&in == &rvIn); ASSERT(!in); ASSERT(X == T); } { const char version = 2 ; // too large (current version is 1) Out out(VERSION_SELECTOR, &allocator); // Stream out "new" value. using bslx::OutStreamFunctions::bdexStreamOut; bdexStreamOut(out, bdlt::Date(1, 1, 1), VERSION); out.putInt32(SERIAL_Y); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); Obj mT(X); const Obj& T = mT; ASSERT(X == T); In in(OD, LOD); ASSERT(in); in.setQuiet(!veryVerbose); using bslx::InStreamFunctions::bdexStreamIn; In& rvIn = bdexStreamIn(in, mT, version); ASSERT(&in == &rvIn); ASSERT(!in); ASSERT(X == T); } if (verbose) { cout << "\t\tOffset too small." << endl; } { Out out(VERSION_SELECTOR, &allocator); // Stream out "new" value. using bslx::OutStreamFunctions::bdexStreamOut; bdexStreamOut(out, bdlt::Date(1, 1, 1), VERSION); out.putInt32(-1440); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); Obj mT(X); const Obj& T = mT; ASSERT(X == T); In in(OD, LOD); ASSERT(in); in.setQuiet(!veryVerbose); using bslx::InStreamFunctions::bdexStreamIn; In& rvIn = bdexStreamIn(in, mT, VERSION); ASSERT(&in == &rvIn); ASSERT(!in); ASSERT(X == T); } if (verbose) { cout << "\t\tOffset too large." << endl; } { Out out(VERSION_SELECTOR, &allocator); // Stream out "new" value. using bslx::OutStreamFunctions::bdexStreamOut; bdexStreamOut(out, bdlt::Date(1, 1, 1), VERSION); out.putInt32(1440); const char *const OD = out.data(); const int LOD = static_cast<int>(out.length()); Obj mT(X); const Obj& T = mT; ASSERT(X == T); In in(OD, LOD); ASSERT(in); in.setQuiet(!veryVerbose); using bslx::InStreamFunctions::bdexStreamIn; In& rvIn = bdexStreamIn(in, mT, VERSION); ASSERT(&in == &rvIn); ASSERT(!in); ASSERT(X == T); } if (verbose) { cout << "\nWire format direct tests." << endl; } { static const struct { int d_lineNum; // source line number int d_offset; // specification offset int d_version; // version to stream with bsl::size_t d_length; // expect output length const char *d_fmt_p; // expected output format } DATA[] = { //LINE OFFSET VER LEN FORMAT //---- ------ --- --- ------------------------------ { L_, -1, 1, 7, "\x00\x00\x01\xff\xff\xff\xff" }, { L_, 0, 1, 7, "\x00\x00\x01\x00\x00\x00\x00" }, { L_, 1, 1, 7, "\x00\x00\x01\x00\x00\x00\x01" } }; const int NUM_DATA = static_cast<int>(sizeof DATA / sizeof *DATA); for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_lineNum; const int OFFSET = DATA[i].d_offset; const int VERSION = DATA[i].d_version; const bsl::size_t LEN = DATA[i].d_length; const char *const FMT = DATA[i].d_fmt_p; // Test using class methods. { Obj mX(bdlt::Date(1, 1, 1), OFFSET); const Obj& X = mX; bslx::ByteOutStream out(VERSION_SELECTOR, &allocator); bslx::ByteOutStream& rvOut = X.bdexStreamOut(out, VERSION); LOOP_ASSERT(LINE, &out == &rvOut); LOOP_ASSERT(LINE, LEN == out.length()); LOOP_ASSERT(LINE, 0 == memcmp(out.data(), FMT, LEN)); if (verbose && memcmp(out.data(), FMT, LEN)) { const char *hex = "0123456789abcdef"; P_(LINE); for (bsl::size_t j = 0; j < out.length(); ++j) { cout << "\\x" << hex[static_cast<unsigned char> ((*(out.data() + j) >> 4) & 0x0f)] << hex[static_cast<unsigned char> (*(out.data() + j) & 0x0f)]; } cout << endl; } Obj mY; const Obj& Y = mY; bslx::ByteInStream in(out.data(), out.length()); bslx::ByteInStream& rvIn = mY.bdexStreamIn(in, VERSION); LOOP_ASSERT(LINE, &in == &rvIn); LOOP_ASSERT(LINE, X == Y); } // Test using free functions. { Obj mX(bdlt::Date(1, 1, 1), OFFSET); const Obj& X = mX; using bslx::OutStreamFunctions::bdexStreamOut; bslx::ByteOutStream out(VERSION_SELECTOR, &allocator); bslx::ByteOutStream& rvOut = bdexStreamOut(out, X, VERSION); LOOP_ASSERT(LINE, &out == &rvOut); LOOP_ASSERT(LINE, LEN == out.length()); LOOP_ASSERT(LINE, 0 == memcmp(out.data(), FMT, LEN)); if (verbose && memcmp(out.data(), FMT, LEN)) { const char *hex = "0123456789abcdef"; P_(LINE); for (bsl::size_t j = 0; j < out.length(); ++j) { cout << "\\x" << hex[static_cast<unsigned char> ((*(out.data() + j) >> 4) & 0x0f)] << hex[static_cast<unsigned char> (*(out.data() + j) & 0x0f)]; } cout << endl; } Obj mY; const Obj& Y = mY; using bslx::InStreamFunctions::bdexStreamIn; bslx::ByteInStream in(out.data(), out.length()); bslx::ByteInStream& rvIn = bdexStreamIn(in, mY, VERSION); LOOP_ASSERT(LINE, &in == &rvIn); LOOP_ASSERT(LINE, X == Y); } } } } break; case 9: { // -------------------------------------------------------------------- // COPY-ASSIGNMENT OPERATOR // Ensure that we can assign the value of any object of the class to // any object of the class, such that the two objects subsequently // have the same value. // // Concerns: //: 1 The assignment operator can change the value of any modifiable //: target object to that of any source object. //: //: 2 The signature and return type are standard. //: //: 3 The reference returned is to the target object (i.e., '*this'). //: //: 4 The value of the source object is not modified. //: //: 5 Assigning an object to itself behaves as expected (alias-safety). // // Plan: //: 1 Use the address of 'operator=' to initialize a member-function //: pointer having the appropriate signature and return type for the //: copy-assignment operator defined in this component. (C-2) //: //: 2 Using the table-driven technique, specify a set S of (unique) //: objects with substantial and varied differences in value. //: Construct and initialize all combinations (U, V) in the cross //: product S x S, assign U from V, and verify the remaining //: concerns. (C-1, C-3..5) // // Testing: // Date& operator=(const Date& rhs); // -------------------------------------------------------------------- if (verbose) cout << endl << "COPY-ASSIGNMENT OPERATOR" << endl << "========================" << endl; if (verbose) cout << "\nAssign the address of the operator to a variable." << endl; { typedef Obj& (Obj::*operatorPtr)(const Obj&); // Verify that the signature and return type are standard. operatorPtr operatorAssignment = &Obj::operator=; (void)operatorAssignment; // quash potential compiler warning } if (verbose) cout << "\nTesting Assignment u = V." << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 10, 4, 5, 1 }, { L_, 100, 6, 7, -1439 }, { L_, 1000, 8, 9, 1439 }, { L_, 2000, 2, 29, -1 }, { L_, 2002, 7, 4, 1380 }, { L_, 2003, 8, 5, -1380 }, { L_, 2004, 9, 3, 5*60 }, { L_, 2020, 9, 9, -5*60 }, { L_, 9999, 12, 31, -5*60 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int V_LINE = DATA[i].d_line; const int V_YEAR = DATA[i].d_year; const int V_MONTH = DATA[i].d_month; const int V_DAY = DATA[i].d_day; const int V_OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(V_LINE) P_(V_YEAR) P_(V_MONTH) P_(V_DAY) P(V_OFFSET) } const Obj V(bdlt::Date(V_YEAR, V_MONTH, V_DAY), V_OFFSET); for (int j = 0; j < NUM_DATA; ++j) { const int U_LINE = DATA[j].d_line; const int U_YEAR = DATA[j].d_year; const int U_MONTH = DATA[j].d_month; const int U_DAY = DATA[j].d_day; const int U_OFFSET = DATA[j].d_offset; if (veryVerbose) { T_ T_ P_(U_LINE) P_(U_YEAR) P_(U_MONTH) P_(U_DAY); P(U_OFFSET); } Obj mU(bdlt::Date(U_YEAR, U_MONTH, U_DAY), U_OFFSET); const Obj& U = mU; const Obj ZZ(V); if (veryVeryVerbose) { T_ T_ T_ P_(V) P_(U) P(ZZ) } Obj *mR = &(mU = V); if (veryVeryVerbose) { T_ T_ T_ P_(V) P_(U) P(ZZ) } ASSERTV(V_LINE, U_LINE, mR == &U); ASSERTV(V_LINE, U_LINE, ZZ == U); ASSERTV(V_LINE, U_LINE, ZZ == V); } } if (verbose) cout << "Testing self-assignment" << endl; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET) } Obj mU(bdlt::Date(YEAR, MONTH, DAY), OFFSET); const Obj& U = mU; const Obj ZZ(U); if (veryVeryVerbose) { T_ T_ P_(U) P(ZZ) } ASSERTV(LINE, ZZ == U); Obj *mR = &(mU = U); if (veryVeryVerbose) { T_ T_ P_(U) P(ZZ) } ASSERTV(LINE, mR == &U); ASSERTV(LINE, ZZ == U); } } } break; case 8: { // -------------------------------------------------------------------- // SWAP MEMBER AND FREE FUNCTIONS // Ensure that, when member and free 'swap' are implemented, we can // exchange the values of any two objects. // // Concerns: // N/A // // Plan: // N/A // // Testing: // Reserved for 'swap' testing. // -------------------------------------------------------------------- if (verbose) cout << endl << "SWAP MEMBER AND FREE FUNCTIONS" << endl << "==============================" << endl; if (verbose) cout << "Not implemented for 'bdlt::DateTz'." << endl; } break; case 7: { // -------------------------------------------------------------------- // COPY CONSTRUCTOR // Ensure that we can create a distinct object of the class from any // other one, such that the two objects have the same value. // // Concerns: //: 1 The copy constructor creates an object having the same value as //: that of the supplied original object. //: //: 2 The original object is passed as a reference providing //: non-modifiable access to that object. //: //: 3 The value of the original object is unchanged. // // Plan: //: 1 Using the table-driven technique, specify a set of distinct //: object values (one per row) in terms of their attributes. //: Specify a set S whose elements have substantial and varied //: differences in value. For each element in S, copy construct a //: new object from S and verify the concerns. (C-1..3) // // Testing: // DateTz(const DateTz& original); // -------------------------------------------------------------------- if (verbose) cout << endl << "COPY CONSTRUCTOR" << endl << "================" << endl; if (verbose) cout << "\nTesting copy constructor." << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[]= { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 10, 4, 5, 1 }, { L_, 100, 6, 7, -1439 }, { L_, 1000, 8, 9, 1439 }, { L_, 2000, 2, 29, -1 }, { L_, 2002, 7, 4, 1380 }, { L_, 2003, 8, 5, -1380 }, { L_, 2004, 9, 3, 5*60 }, { L_, 9999, 12, 31, -5*60 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET) } const Obj X(bdlt::Date(YEAR, MONTH, DAY), OFFSET); const Obj ZZ(bdlt::Date(YEAR, MONTH, DAY), OFFSET); const Obj Y(X); if (veryVerbose) { T_ T_ P_(X) P_(ZZ) P(Y) } ASSERTV(LINE, X == Y); ASSERTV(LINE, Y == ZZ); } } } break; case 6: { // -------------------------------------------------------------------- // EQUALITY OPERATORS // Ensure that '==' and '!=' are the operational definition of value. // // Concerns: //: 1 Two objects, 'X' and 'Y', compare equal if and only if each of //: their corresponding salient attributes respectively compare //: equal. //: //: 2 'true == (X == X)' (i.e., identity) //: //: 3 'false == (X != X)' (i.e., identity) //: //: 4 'X == Y' if and only if 'Y == X' (i.e., commutativity) //: //: 5 'X != Y' if and only if 'Y != X' (i.e., commutativity) //: //: 6 'X != Y' if and only if '!(X == Y)' //: //: 7 Comparison is symmetric with respect to user-defined conversion //: (i.e., both comparison operators are free functions). //: //: 8 Non-modifiable objects can be compared (i.e., objects or //: references providing only non-modifiable access). //: //: 9 The equality operator's signature and return type are standard. //: //:10 The inequality operator's signature and return type are standard. // // Plan: //: 1 Use the respective addresses of 'operator==' and 'operator!=' to //: initialize function pointers having the appropriate signatures //: and return types for the two homogeneous, free equality- //: comparison operators defined in this component. //: (C-7..10) //: //: 2 Using the table-driven technique, specify a set S of unique //: object values having various minor or subtle differences. Verify //: the correctness of 'operator==' and 'operator!=' using all //: elements (u, v) of the cross product S X S. (C-1..6) // // Testing: // bool operator==(const DateTz& lhs, const DateTz& rhs); // bool operator!=(const DateTz& lhs, const DateTz& rhs); // -------------------------------------------------------------------- if (verbose) cout << endl << "EQUALITY OPERATORS" << endl << "==================" << endl; if (verbose) cout << "\nAssign the address of each operator to a variable." << endl; { typedef bool (*operatorPtr)(const Obj&, const Obj&); // Verify that the signatures and return types are standard. operatorPtr operatorEq = bdlt::operator==; operatorPtr operatorNe = bdlt::operator!=; (void)operatorEq; // quash potential compiler warnings (void)operatorNe; } if (verbose) cout << "\nCompare each pair of values (u, v) in S X S." << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 1, 1, 2, 0 }, { L_, 1, 2, 1, 0 }, { L_, 2, 1, 1, 1439 }, { L_, 1, 1, 1, -1 }, { L_, 1, 1, 2, 1 }, { L_, 1, 2, 1, -1439 }, { L_, 2, 1, 1, 1438 }, { L_, 9998, 12, 31, 0 }, { L_, 9999, 11, 30, 0 }, { L_, 9999, 12, 30, 0 }, { L_, 9999, 12, 31, 0 }, { L_, 9998, 12, 31, 1 }, { L_, 9999, 11, 30, -1439 }, { L_, 9999, 12, 30, -1 }, { L_, 9999, 12, 31, -143 }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int U_LINE = DATA[i].d_line; const int U_YEAR = DATA[i].d_year; const int U_MONTH = DATA[i].d_month; const int U_DAY = DATA[i].d_day; const int U_OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P(U_LINE) P_(U_YEAR) P_(U_MONTH) P_(U_DAY) P(U_OFFSET); } const bdlt::Date U_DATE(U_YEAR, U_MONTH, U_DAY); const Obj U(U_DATE, U_OFFSET); for (int j = 0; j < NUM_DATA; ++j) { const int V_LINE = DATA[j].d_line; const int V_YEAR = DATA[j].d_year; const int V_MONTH = DATA[j].d_month; const int V_DAY = DATA[j].d_day; const int V_OFFSET = DATA[j].d_offset; if (veryVerbose) { T_ T_ P_(V_LINE) P_(V_YEAR); P_(V_MONTH) P_(V_DAY) P(V_OFFSET); } const bdlt::Date V_DATE(V_YEAR, V_MONTH, V_DAY); const Obj V(V_DATE, V_OFFSET); bool isSame = i == j; if (veryVeryVerbose) { T_ T_ T_ P_(i) P_(j) P_(U) P(V) } ASSERTV(U_LINE, V_LINE, isSame == (U == V)); ASSERTV(U_LINE, V_LINE, !isSame == (U != V)); ASSERTV(U_LINE, V_LINE, isSame == (V == U)); ASSERTV(U_LINE, V_LINE, !isSame == (V != U)); } } } } break; case 5: { // -------------------------------------------------------------------- // PRINT AND OUTPUT OPERATOR // Ensure that the value of the object can be formatted appropriately // on an 'ostream' in some standard, human-readable form. // // Concerns: //: 1 The 'print' method writes the value to the specified 'ostream'. //: //: 2 The 'print' method writes the value in the intended format. //: //: 3 The output using 's << obj' is the same as 'obj.print(s, 0, -1)'. //: //: 4 The 'print' method signature and return type are standard. //: //: 5 The 'print' method returns the supplied 'ostream'. //: //: 6 The optional 'level' and 'spacesPerLevel' parameters have the //: correct default values. //: //: 7 The output 'operator<<' signature and return type are standard. //: //: 8 The output 'operator<<' returns the supplied 'ostream'. // // Plan: //: 1 Use the addresses of the 'print' member function and 'operator<<' //: free function defined in this component to initialize, //: respectively, member-function and free-function pointers having //: the appropriate signatures and return types. (C-4, 7) //: //: 2 Using the table-driven technique, define set of distinct //: formatting parameters and the corresponding expected output //: string for the 'print' method. If the value of the formatting //: parameters, 'level' or 'spacesPerLevel' is -8, then the //: parameters will be omitted in the method invocation. //: //: 1 Invoke the 'print' method passing the formatting parameters and //: a 'const' object. //: //: 2 Verify the address of what is returned is that of the supplied //: stream. (C-5) //: //: 3 Verify that the output string has the expected value. //: (C-1..2, 6) //: //: 3 Using the table-driven technique, define a set of distinct object //: values and the expected string output of 'operator<<'. //: //: 1 Invoke 'operator<<' passing a 'const' object. //: //: 2 Verify the address of what is returned is that of the supplied //: stream. (C-8) //: //: 3 Verify that the output string has the expected value. (C-3) // // Testing: // bsl::ostream& print(bsl::ostream& stream, int l, int spl) const; // bsl::ostream& operator<<(bsl::ostream&, const DateTz&); // -------------------------------------------------------------------- if (verbose) cout << endl << "PRINT AND OUTPUT OPERATOR" << endl << "=========================" << endl; if (verbose) cout << "\nAssign the addresses of 'print' and " "the output 'operator<<' to variables." << endl; { typedef ostream& (Obj::*funcPtr)(ostream&, int, int) const; typedef ostream& (*operatorPtr)(ostream&, const Obj&); // Verify that the signatures and return types are standard. funcPtr printMember = &Obj::print; operatorPtr operatorOp = bdlt::operator<<; (void)printMember; // quash potential compiler warnings (void)operatorOp; } static const struct { int d_lineNum; // source line number int d_level; // indentation level int d_spacesPerLevel; // spaces per indentation level int d_offset; // tz offset const char *d_expected_p; // expected output format } DATA[] = { //LINE LEVEL SPACES OFFSET FORMAT //---- ----- ------ ------ ------ { L_, 0, -1, 0, "01JAN0001+0000" }, { L_, 0, 0, 15, "01JAN0001+0015\n" }, { L_, 0, 2, 60, "01JAN0001+0100\n" }, { L_, -8, -8, 60, "01JAN0001+0100\n" }, { L_, 1, 1, 90, " 01JAN0001+0130\n" }, { L_, 1, 2, -20, " 01JAN0001-0020\n" }, { L_, 1, 0, -20, "01JAN0001-0020\n" }, { L_, 1, -1, -20, " 01JAN0001-0020" }, { L_, -1, 2, -330, "01JAN0001-0530\n" }, { L_, -1, 0, -330, "01JAN0001-0530\n" }, { L_, -2, 1, 311, "01JAN0001+0511\n" }, { L_, 2, 1, 1439, " 01JAN0001+2359\n" }, { L_, 1, 3, -1439, " 01JAN0001-2359\n" }, { L_, -9, -9, 0, "01JAN0001+0000" }, { L_, -9, -9, 15, "01JAN0001+0015" }, { L_, -9, -9, 60, "01JAN0001+0100" }, { L_, -9, -9, 90, "01JAN0001+0130" }, { L_, -9, -9, -20, "01JAN0001-0020" }, { L_, -9, -9, -330, "01JAN0001-0530" }, { L_, -9, -9, 311, "01JAN0001+0511" }, { L_, -9, -9, 1439, "01JAN0001+2359" }, { L_, -9, -9, -1439, "01JAN0001-2359" }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; if (verbose) cout << "\nTesting with various print specifications." << endl; { for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const int L = DATA[ti].d_level; const int SPL = DATA[ti].d_spacesPerLevel; const int OFF = DATA[ti].d_offset; const char *const EXP = DATA[ti].d_expected_p; if (veryVerbose) { T_ P_(L) P_(SPL) P_(OFF) } if (veryVeryVerbose) { T_ T_ Q(EXPECTED) cout << EXP; } bdlt::Date date; // 01JAN0001 const Obj X(date, OFF); ostringstream os; // Verify supplied stream is returned by reference. if (-9 == L && -9 == SPL) { ASSERTV(LINE, &os == &(os << X)); if (veryVeryVerbose) { T_ T_ Q(operator<<) } } else { ASSERTV(LINE, -8 == SPL || -8 != L); if (-8 != SPL) { ASSERTV(LINE, &os == &X.print(os, L, SPL)); } else if (-8 != L) { ASSERTV(LINE, &os == &X.print(os, L)); } else { ASSERTV(LINE, &os == &X.print(os)); } if (veryVeryVerbose) { T_ T_ Q(print) } } // Verify output is formatted as expected. if (veryVeryVerbose) { P(os.str()) } ASSERTV(LINE, EXP, os.str(), EXP == os.str()); } } } break; case 4: { // -------------------------------------------------------------------- // BASIC ACCESSORS // // Concerns: //: 1 Each accessor returns the value of the corresponding attribute of //: the object. //: //: 2 Each accessor method is declared 'const'. // // Plan: //: 1 Use the table-driven technique, specify a range of distinct //: object values. For each row 'R1' in the table: (C-1..2) //: //: 1 Default construct an object and set the object's value to that //: of 'R1' using the primary manipulator. //: //: 2 Invoke each basic accessor from a reference providing //: non-modifiable access to the object created in P-1.1 and verify //: that the return value is correct. (C-1..2) // // Testing: // Date localDate() const; // int offset() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "BASIC ACCESSORS" << endl << "===============" << endl; if (verbose) cout << "\n'localDate()', 'offset()'" << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, -1439 }, { L_, 10, 4, 5, 1439 }, { L_, 100, 6, 1, -5*60 }, { L_, 1000, 8, 9, -1438 }, { L_, 1100, 1, 31, 1380 }, { L_, 1200, 2, 15, -1380 }, { L_, 1300, 3, 31, -1 }, { L_, 1400, 4, 30, 5*60 }, { L_, 1600, 6, 30, 0 }, { L_, 1500, 5, 15, -1439 }, { L_, 1700, 7, 31, 1*60 }, { L_, 1900, 9, 30, 1 }, { L_, 2000, 10, 31, 0 }, { L_, 2200, 12, 31, 1438 }, { L_, 2400, 12, 1, -1*60 }, { L_, 9999, 12, 31, 1439 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(LINE) P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET); } const bdlt::Date localDate(YEAR, MONTH, DAY); const Obj X(localDate, OFFSET); if (veryVeryVerbose) { T_ P_(LINE) P(X) } ASSERTV(LINE, localDate, X.localDate(), localDate == X.localDate()); ASSERTV(LINE, OFFSET, X.offset(), OFFSET == X.offset()); } } } break; case 3: { // -------------------------------------------------------------------- // PRIMITIVE GENERATOR FUNCTIONS 'gg' and 'ggg': // // Concerns: // N/A // // Plan: // N/A // // Testing: // Reserved for testing of primitive generator functions. // -------------------------------------------------------------------- if (verbose) cout << endl << "PRIMITIVE GENERATOR FUNCTIONS 'gg' and 'ggg':" << endl << "=============================================" << endl; } break; case 2: { // -------------------------------------------------------------------- // PRIMARY MANIPULATOR - VALUE CONSTRUCTOR // // Concerns: //: 1 The constructor correctly initializes the local date and time //: zone offset to the specified values. //: //: 2 QoI: Asserted precondition violations are detected when enabled. // // Plan: //: 1 Using the table-driven technique, specify a set S of dates and //: offsets as (y, m, d, o) quadruplets having widely varying values. //: For each (y, m, d, o) in S, construct a date object X and verify //: that X has the expected value. (C-1) //: //: 2 Verify that, in appropriate build modes, defensive checks are //: triggered for invalid attribute values, but not triggered for //: adjacent valid ones (using the 'BSLS_ASSERTTEST_*' macros). //: (C-2) // // Testing: // DateTz(const Date& localDate, int offset); // ~DateTz(); // -------------------------------------------------------------------- if (verbose) cout << endl << "PRIMARY MANIPULATOR - VALUE CONSTRUCTOR" << endl << "=======================================" << endl; { static const struct { int d_line; // line number int d_year; // year of date int d_month; // month of date int d_day; // day of month of date int d_offset; // timezone offset } DATA[] = { //LINE YEAR MO DAY OFFSET //---- ---- -- --- ------ { L_, 1, 1, 1, 0 }, { L_, 10, 4, 5, 1 }, { L_, 100, 6, 7, -1439 }, { L_, 1000, 8, 9, 1439 }, { L_, 2000, 2, 29, -1 }, { L_, 2002, 7, 4, 1380 }, { L_, 2003, 8, 5, -1380 }, { L_, 2004, 9, 3, 5*60 }, { L_, 9999, 12, 31, -5*60 } }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; const int YEAR = DATA[i].d_year; const int MONTH = DATA[i].d_month; const int DAY = DATA[i].d_day; const int OFFSET = DATA[i].d_offset; if (veryVerbose) { T_ P_(LINE) P_(YEAR) P_(MONTH) P_(DAY) P(OFFSET); } const bdlt::Date localDate(YEAR, MONTH, DAY); const Obj X(localDate, OFFSET); if (veryVeryVerbose) { T_ T_ P_(X) } ASSERTV(LINE, localDate, X.localDate(), localDate == X.localDate()); ASSERTV(LINE, OFFSET, X.offset(), OFFSET == X.offset()); } } // Negative Testing { bsls::AssertFailureHandlerGuard hG( bsls::AssertTest::failTestDriver); if (veryVerbose) cout << "\t'timeout'" << endl; { ASSERT_SAFE_FAIL(Obj(bdlt::Date(), 1440)); ASSERT_SAFE_PASS(Obj(bdlt::Date(), 1439)); ASSERT_SAFE_FAIL(Obj(bdlt::Date(), -1440)); ASSERT_SAFE_PASS(Obj(bdlt::Date(), -1439)); } } } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This case exercises (but does not fully test) basic functionality. // // Concerns: //: 1 The class is sufficiently functional to enable comprehensive //: testing in subsequent test cases. // // Plan: //: 1 Execute each methods to verify functionality for simple case. // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) cout << "\nBREATHING TEST" << "\n==============" << endl; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Values for testing const int YRA = 1, MOA = 2, DAA = 3; // y, m, d for VA const int YRB = 4, MOB = 5, DAB = 6; // y, m, d for VB const int YRC = 7, MOC = 8, DAC = 9; // y, m, d for VC const bdlt::Date DA(YRA, MOA, DAA), DB(YRB, MOB, DAB), DC(YRC, MOC, DAC); const int OA = 60, OB = -300, OC = 270; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 1. Create an object x1 (init. to VA)." "\t\t{ x1:VA }" << endl; Obj mX1(DA, OA); const Obj& X1 = mX1; if (verbose) { cout << '\t'; P(X1); } if (verbose) cout << "\ta. Check initial state of x1." << endl; ASSERT(DA == X1.localDate()); ASSERT(OA == X1.offset()); if (verbose) cout << "\tb. Try equality operators: x1 <op> x1." << endl; ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 2. Create an object x2 (copy from x1)." "\t\t{ x1:VA x2:VA }" << endl; Obj mX2(X1); const Obj& X2 = mX2; if (verbose) { cout << '\t'; P(X2); } if (verbose) cout << "\ta. Check the initial state of x2." << endl; ASSERT(DA == X2.localDate()); ASSERT(OA == X2.offset()); if (verbose) cout << "\tb. Try equality operators: x2 <op> x1, x2." << endl; ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 3. Set x1 to a new value VB." "\t\t\t{ x1:VB x2:VA }" << endl; mX1.setDateTz(DB, OB); if (verbose) { cout << '\t'; P(X1); } ASSERT(DB == X1.localDate()); ASSERT(OB == X1.offset()); if (verbose) cout << "\ta. Check new state of x1." << endl; if (verbose) cout << "\tb. Try equality operators: x1 <op> x1, x2." << endl; ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 4. Create a default object x3()." "\t\t{ x1:VB x2:VA x3:U }" << endl; Obj mX3; const Obj& X3 = mX3; if (verbose) { cout << '\t'; P(X3); } if (verbose) cout << "\ta. Check initial state of x3." << endl; ASSERT(bdlt::Date() == X3.localDate()); ASSERT( 0 == X3.offset()); if (verbose) cout << "\tb. Try equality operators: x3 <op> x1, x2, x3." << endl; ASSERT(0 == (X3 == X1)); ASSERT(1 == (X3 != X1)); ASSERT(0 == (X3 == X2)); ASSERT(1 == (X3 != X2)); ASSERT(1 == (X3 == X3)); ASSERT(0 == (X3 != X3)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 5. Create an object x4 (copy from x3)." "\t\t{ x1:VA x2:VA x3:U x4:U }" << endl; Obj mX4(X3); const Obj& X4 = mX4; if (verbose) { cout << '\t'; P(X4); } if (verbose) cout << "\ta. Check initial state of x4." << endl; ASSERT(bdlt::Date() == X4.localDate()); ASSERT( 0 == X4.offset()); if (verbose) cout << "\tb. Try equality operators: x4 <op> x1, x2, x3, x4." << endl; ASSERT(0 == (X4 == X1)); ASSERT(1 == (X4 != X1)); ASSERT(0 == (X4 == X2)); ASSERT(1 == (X4 != X2)); ASSERT(1 == (X4 == X3)); ASSERT(0 == (X4 != X3)); ASSERT(1 == (X4 == X4)); ASSERT(0 == (X4 != X4)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 6. Set x3 to a new value VC." "\t\t\t{ x1:VB x2:VA x3:VC x4:U }" << endl; mX3.setDateTz(DC, OC); if (verbose) { cout << '\t'; P(X3); } if (verbose) cout << "\ta. Check new state of x3." << endl; ASSERT(DC == X3.localDate()); ASSERT(OC == X3.offset()); if (verbose) cout << "\tb. Try equality operators: x3 <op> x1, x2, x3, x4." << endl; ASSERT(0 == (X3 == X1)); ASSERT(1 == (X3 != X1)); ASSERT(0 == (X3 == X2)); ASSERT(1 == (X3 != X2)); ASSERT(1 == (X3 == X3)); ASSERT(0 == (X3 != X3)); ASSERT(0 == (X3 == X4)); ASSERT(1 == (X3 != X4)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 7. Assign x2 = x1." "\t\t\t\t{ x1:VB x2:VB x3:VC x4:U }" << endl; mX2 = X1; if (verbose) { cout << '\t'; P(X2); } if (verbose) cout << "\ta. Check new state of x2." << endl; ASSERT(DB == X2.localDate()); ASSERT(OB == X2.offset()); if (verbose) cout << "\tb. Try equality operators: x2 <op> x1, x2, x3, x4." << endl; ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(0 == (X2 == X3)); ASSERT(1 == (X2 != X3)); ASSERT(0 == (X2 == X4)); ASSERT(1 == (X2 != X4)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 8. Assign x2 = x3." "\t\t\t\t{ x1:VB x2:VC x3:VC x4:U }" << endl; mX2 = X3; if (verbose) { cout << '\t'; P(X2); } if (verbose) cout << "\ta. Check new state of x2." << endl; ASSERT(DC == X2.localDate()); ASSERT(OC == X2.offset()); if (verbose) cout << "\tb. Try equality operators: x2 <op> x1, x2, x3, x4." << endl; ASSERT(0 == (X2 == X1)); ASSERT(1 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(1 == (X2 == X3)); ASSERT(0 == (X2 != X3)); ASSERT(0 == (X2 == X4)); ASSERT(1 == (X2 != X4)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (verbose) cout << "\n 9. Assign x1 = x1 (aliasing)." "\t\t\t{ x1:VB x2:VC x3:VC x4:U }" << endl; mX1 = X1; if (verbose) { cout << '\t'; P(X1); } if (verbose) cout << "\ta. Check new state of x1." << endl; ASSERT(DB == X1.localDate()); ASSERT(OB == X1.offset()); if (verbose) cout << "\tb. Try equality operators: x1 <op> x1, x2, x3, x4." << endl; ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); ASSERT(0 == (X1 == X3)); ASSERT(1 == (X1 != X3)); ASSERT(0 == (X1 == X4)); ASSERT(1 == (X1 != X4)); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
apache-2.0
google/google-ctf
third_party/edk2/UefiCpuPkg/Library/CpuCommonFeaturesLib/ClockModulation.c
2
3813
/** @file Clock Modulation feature. Copyright (c) 2017 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "CpuCommonFeatures.h" /** Detects if Clock Modulation feature supported on current processor. @param[in] ProcessorNumber The index of the CPU executing this function. @param[in] CpuInfo A pointer to the REGISTER_CPU_FEATURE_INFORMATION structure for the CPU executing this function. @param[in] ConfigData A pointer to the configuration buffer returned by CPU_FEATURE_GET_CONFIG_DATA. NULL if CPU_FEATURE_GET_CONFIG_DATA was not provided in RegisterCpuFeature(). @retval TRUE Clock Modulation feature is supported. @retval FALSE Clock Modulation feature is not supported. @note This service could be called by BSP/APs. **/ BOOLEAN EFIAPI ClockModulationSupport ( IN UINTN ProcessorNumber, IN REGISTER_CPU_FEATURE_INFORMATION *CpuInfo, IN VOID *ConfigData OPTIONAL ) { return (CpuInfo->CpuIdVersionInfoEdx.Bits.ACPI == 1); } /** Initializes Clock Modulation feature to specific state. @param[in] ProcessorNumber The index of the CPU executing this function. @param[in] CpuInfo A pointer to the REGISTER_CPU_FEATURE_INFORMATION structure for the CPU executing this function. @param[in] ConfigData A pointer to the configuration buffer returned by CPU_FEATURE_GET_CONFIG_DATA. NULL if CPU_FEATURE_GET_CONFIG_DATA was not provided in RegisterCpuFeature(). @param[in] State If TRUE, then the Clock Modulation feature must be enabled. If FALSE, then the Clock Modulation feature must be disabled. @retval RETURN_SUCCESS Clock Modulation feature is initialized. @note This service could be called by BSP only. **/ RETURN_STATUS EFIAPI ClockModulationInitialize ( IN UINTN ProcessorNumber, IN REGISTER_CPU_FEATURE_INFORMATION *CpuInfo, IN VOID *ConfigData, OPTIONAL IN BOOLEAN State ) { CPUID_THERMAL_POWER_MANAGEMENT_EAX ThermalPowerManagementEax; AsmCpuid (CPUID_THERMAL_POWER_MANAGEMENT, &ThermalPowerManagementEax.Uint32, NULL, NULL, NULL); CPU_REGISTER_TABLE_WRITE_FIELD ( ProcessorNumber, Msr, MSR_IA32_CLOCK_MODULATION, MSR_IA32_CLOCK_MODULATION_REGISTER, Bits.OnDemandClockModulationDutyCycle, PcdGet8 (PcdCpuClockModulationDutyCycle) >> 1 ); if (ThermalPowerManagementEax.Bits.ECMD == 1) { CPU_REGISTER_TABLE_WRITE_FIELD ( ProcessorNumber, Msr, MSR_IA32_CLOCK_MODULATION, MSR_IA32_CLOCK_MODULATION_REGISTER, Bits.ExtendedOnDemandClockModulationDutyCycle, PcdGet8 (PcdCpuClockModulationDutyCycle) & BIT0 ); } CPU_REGISTER_TABLE_WRITE_FIELD ( ProcessorNumber, Msr, MSR_IA32_CLOCK_MODULATION, MSR_IA32_CLOCK_MODULATION_REGISTER, Bits.OnDemandClockModulationEnable, (State) ? 1 : 0 ); return RETURN_SUCCESS; }
apache-2.0
vonway/TeamTalk
server/src/msg_server/LoginServConn.cpp
2
4499
/* * LoginServConn.cpp * * Created on: 2013-7-8 * Author: ziteng@mogujie.com */ #include "LoginServConn.h" #include "MsgConn.h" #include "ImUser.h" #include "IM.Other.pb.h" #include "IM.Server.pb.h" #include "ImPduBase.h" #include "public_define.h" using namespace IM::BaseDefine; static ConnMap_t g_login_server_conn_map; static serv_info_t* g_login_server_list; static uint32_t g_login_server_count; static string g_msg_server_ip_addr1; static string g_msg_server_ip_addr2; static uint16_t g_msg_server_port; static uint32_t g_max_conn_cnt; void login_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { ConnMap_t::iterator it_old; CLoginServConn* pConn = NULL; uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_login_server_conn_map.begin(); it != g_login_server_conn_map.end(); ) { it_old = it; it++; pConn = (CLoginServConn*)it_old->second; pConn->OnTimer(cur_time); } // reconnect LoginServer serv_check_reconnect<CLoginServConn>(g_login_server_list, g_login_server_count); } void init_login_serv_conn(serv_info_t* server_list, uint32_t server_count, const char* msg_server_ip_addr1, const char* msg_server_ip_addr2, uint16_t msg_server_port, uint32_t max_conn_cnt) { g_login_server_list = server_list; g_login_server_count = server_count; serv_init<CLoginServConn>(g_login_server_list, g_login_server_count); g_msg_server_ip_addr1 = msg_server_ip_addr1; g_msg_server_ip_addr2 = msg_server_ip_addr2; g_msg_server_port = msg_server_port; g_max_conn_cnt = max_conn_cnt; netlib_register_timer(login_server_conn_timer_callback, NULL, 1000); } //--> return true if there is a LoginServer available in g_login_server_list bool is_login_server_available() { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { return true; } } return false; } void send_to_all_login_server(CImPdu* pPdu) { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { pConn->SendPdu(pPdu); } } } CLoginServConn::CLoginServConn() { m_bOpen = false; } CLoginServConn::~CLoginServConn() { } //--> connect to loginserver and update g_login_server_conn_map void CLoginServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t serv_idx) { log("Connecting to LoginServer %s:%d ", server_ip, server_port); m_serv_idx = serv_idx; m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_login_server_conn_map); if (m_handle != NETLIB_INVALID_HANDLE) { g_login_server_conn_map.insert(make_pair(m_handle, this)); } } void CLoginServConn::Close() { serv_reset<CLoginServConn>(g_login_server_list, g_login_server_count, m_serv_idx); if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); g_login_server_conn_map.erase(m_handle); } ReleaseRef(); } void CLoginServConn::OnConfirm() { log("connect to login server success "); m_bOpen = true; g_login_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2; uint32_t cur_conn_cnt = 0; uint32_t shop_user_cnt = 0; list<user_conn_t> user_conn_list; CImUserManager::GetInstance()->GetUserConnCnt(&user_conn_list, cur_conn_cnt); char hostname[256] = {0}; gethostname(hostname, 256); IM::Server::IMMsgServInfo msg; msg.set_ip1(g_msg_server_ip_addr1); msg.set_ip2(g_msg_server_ip_addr2); msg.set_port(g_msg_server_port); msg.set_max_conn_cnt(g_max_conn_cnt); msg.set_cur_conn_cnt(cur_conn_cnt); msg.set_host_name(hostname); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_MSG_SERV_INFO); SendPdu(&pdu); } void CLoginServConn::OnClose() { log("login server conn onclose, from handle=%d ", m_handle); Close(); } void CLoginServConn::OnTimer(uint64_t curr_tick) { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { IM::Other::IMHeartBeat msg; CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_HEARTBEAT); SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("conn to login server timeout "); Close(); } } void CLoginServConn::HandlePdu(CImPdu* pPdu) { //printf("recv pdu_type=%d ", pPdu->GetPduType()); }
apache-2.0
google-ar/WebARonARCore
third_party/WebKit/Source/core/dom/custom/V0CustomElementProcessingStack.cpp
2
3683
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Google Inc. nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/dom/custom/V0CustomElementProcessingStack.h" #include "core/dom/custom/V0CustomElementCallbackQueue.h" #include "core/dom/custom/V0CustomElementScheduler.h" namespace blink { size_t V0CustomElementProcessingStack::s_elementQueueStart = 0; // The base of the stack has a null sentinel value. size_t V0CustomElementProcessingStack::s_elementQueueEnd = kNumSentinels; V0CustomElementProcessingStack& V0CustomElementProcessingStack::instance() { DEFINE_STATIC_LOCAL(V0CustomElementProcessingStack, instance, (new V0CustomElementProcessingStack)); return instance; } // Dispatches callbacks when popping the processing stack. void V0CustomElementProcessingStack::processElementQueueAndPop() { instance().processElementQueueAndPop(s_elementQueueStart, s_elementQueueEnd); } void V0CustomElementProcessingStack::processElementQueueAndPop(size_t start, size_t end) { DCHECK(isMainThread()); V0CustomElementCallbackQueue::ElementQueueId thisQueue = currentElementQueue(); for (size_t i = start; i < end; ++i) { { // The created callback may schedule entered document // callbacks. CallbackDeliveryScope deliveryScope; m_flattenedProcessingStack[i]->processInElementQueue(thisQueue); } DCHECK_EQ(start, s_elementQueueStart); DCHECK_EQ(end, s_elementQueueEnd); } // Pop the element queue from the processing stack m_flattenedProcessingStack.resize(start); s_elementQueueEnd = start; if (s_elementQueueStart == kNumSentinels) V0CustomElementScheduler::callbackDispatcherDidFinish(); } void V0CustomElementProcessingStack::enqueue( V0CustomElementCallbackQueue* callbackQueue) { DCHECK(inCallbackDeliveryScope()); if (callbackQueue->owner() == currentElementQueue()) return; callbackQueue->setOwner(currentElementQueue()); m_flattenedProcessingStack.push_back(callbackQueue); ++s_elementQueueEnd; } DEFINE_TRACE(V0CustomElementProcessingStack) { visitor->trace(m_flattenedProcessingStack); } } // namespace blink
apache-2.0
google/swiftshader
src/Reactor/ReactorDebugInfo.cpp
3
3800
// Copyright 2020 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ReactorDebugInfo.hpp" #include "Print.hpp" #ifdef ENABLE_RR_DEBUG_INFO # include "boost/stacktrace.hpp" # include <algorithm> # include <cctype> # include <unordered_map> namespace rr { namespace { std::string to_lower(std::string str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); }); return str; } bool endswith_lower(const std::string &str, const std::string &suffix) { size_t strLen = str.size(); size_t suffixLen = suffix.size(); if(strLen < suffixLen) { return false; } return to_lower(str).substr(strLen - suffixLen) == to_lower(suffix); } } // namespace Backtrace getCallerBacktrace(size_t limit /* = 0 */) { namespace bs = boost::stacktrace; auto shouldSkipFile = [](const std::string &fileSR) { return fileSR.empty() || endswith_lower(fileSR, "ReactorDebugInfo.cpp") || endswith_lower(fileSR, "Reactor.cpp") || endswith_lower(fileSR, "Reactor.hpp") || endswith_lower(fileSR, "Traits.hpp") || endswith_lower(fileSR, "stacktrace.hpp"); }; auto offsetStackFrames = [](const bs::stacktrace &st) { // Return a stack trace with every stack frame address offset by -1. We do this so that we get // back the location of the function call, and not the location following it. We need this since // all debug info emits are the result of a function call. Note that technically we shouldn't // perform this offsetting on the top-most stack frame, but it doesn't matter as we discard it // anyway (see shouldSkipFile). std::vector<bs::frame> result; result.reserve(st.size()); for(bs::frame frame : st) { result.emplace_back(reinterpret_cast<void *>(reinterpret_cast<size_t>(frame.address()) - 1)); } return result; }; std::vector<Location> locations; // Cache to avoid expensive stacktrace lookups, especially since our use-case results in looking up the // same call stack addresses many times. static std::unordered_map<bs::frame::native_frame_ptr_t, Location> cache; for(bs::frame frame : offsetStackFrames(bs::stacktrace())) { Location location; auto iter = cache.find(frame.address()); if(iter == cache.end()) { location.function.file = frame.source_file(); location.function.name = frame.name(); location.line = frame.source_line(); cache[frame.address()] = location; } else { location = iter->second; } if(shouldSkipFile(location.function.file)) { continue; } locations.push_back(std::move(location)); if(limit > 0 && locations.size() >= limit) { break; } } std::reverse(locations.begin(), locations.end()); return locations; } void emitPrintLocation(const Backtrace &backtrace) { # ifdef ENABLE_RR_EMIT_PRINT_LOCATION static Location lastLocation; if(backtrace.size() == 0) { return; } Location currLocation = backtrace[backtrace.size() - 1]; if(currLocation != lastLocation) { rr::Print("rr> {0} [{1}:{2}]\n", currLocation.function.name.c_str(), currLocation.function.file.c_str(), currLocation.line); lastLocation = std::move(currLocation); } # endif } } // namespace rr #endif // ENABLE_RR_DEBUG_INFO
apache-2.0
jmerkow/ITK
Modules/ThirdParty/MINC/src/libminc/libsrc2/volume.c
3
50249
/** \file volume.c * \brief MINC 2.0 Volume Functions * \author Leila Baghdadi, Bert Vincent * * Functions to create, open, and close MINC volume objects. ************************************************************************/ #include <stdlib.h> #include <hdf5.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif /*HAVE_CONFIG_H*/ #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif //HAVE_SYS_TYPES_H #ifdef HAVE_UNISTD_H #include <unistd.h> #endif //HAVE_UNISTD_H #ifdef HAVE_MINC1 #include "minc.h" #endif //HAVE_MINC1 #include <limits.h> #include <float.h> #include <time.h> #include <math.h> #include "minc2.h" #include "minc2_private.h" /** * \defgroup mi2Vol MINC 2.0 Volume Functions */ /* Forward declarations */ static void miread_valid_range(mihandle_t volume, double *valid_max, double *valid_min); static int _miset_volume_class(mihandle_t volume, miclass_t volclass); static int _miget_volume_class(mihandle_t volume, miclass_t *volclass); /** * Creates a (hopefully) unique identifier to associate with a * MINC file, by concatenating various information about the * system, process, etc. * returns the length of identifier */ static int _generate_ident( char * id_str, size_t length ) { static int identx = 1; /* Static ID counter */ time_t now; struct tm tm_buf; char host_str[128]; char user_str[128]; char *temp_ptr; char time_str[26]; int result; // Linking in ws2_32 for gethostname is problematic with static libraries. #ifdef _WIN32 strcpy(host_str, "unknown"); #else if (gethostname(host_str, sizeof(host_str)) != 0) { strcpy(host_str, "unknown"); } #endif temp_ptr = getenv("LOGNAME"); if (temp_ptr != NULL) { strncpy(user_str, temp_ptr, sizeof(user_str) - 1); } else { strcpy(user_str, "nobody"); } time(&now); #ifdef _WIN32 memcpy(&tm_buf, localtime(&now), sizeof(tm_buf)); #else localtime_r(&now, &tm_buf); #endif strftime(time_str, sizeof(time_str), "%Y.%m.%d.%H.%M.%S", &tm_buf); result = snprintf(id_str, length, "%s:%s:%s:%u:%u", user_str, host_str, time_str, getpid(), identx++); return result; } /** * open HDF5 file */ static hid_t _hdf_open(const char *path, int mode) { hid_t fd; /* hid_t grp_id; hid_t dset_id; int ndims;*/ H5E_BEGIN_TRY { #if HDF5_MMAP_TEST if (mode & 0x8000) { hid_t prp_id; prp_id = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mmap(prp_id, 8192, 1); fd = H5Fopen(path, mode & 0x7FFF, prp_id); H5Pclose(prp_id); } else { fd = H5Fopen(path, mode, H5P_DEFAULT); } #else fd = H5Fopen(path, mode, H5P_DEFAULT); #endif } H5E_END_TRY; /* Open the image variables. */ //TODO: convert // H5E_BEGIN_TRY // { // dset_id = H5Dopen1(fd, "/minc-2.0/image/0/image"); // if (dset_id >= 0) { // hid_t type_id; // int is_compound = 0; // // hdf_get_diminfo(dset_id, &ndims, dims); // // #ifndef NO_EMULATE_VECTOR_DIMENSION // /* See if a vector_dimension needs to be emulated. // */ // type_id = H5Dget_type(dset_id); // if (type_id >= 0) { // if (H5Tget_class(type_id) == H5T_COMPOUND) { // /* OK, it's compound type. */ // struct m2_dim *dim = hdf_dim_add(file, MIvector_dimension, // H5Tget_nmembers(type_id)); // dim->is_fake = 1; // dims[ndims++] = H5Tget_nmembers(type_id); // is_compound = 1; // } // H5Tclose(type_id); // } // #endif /* NO_EMULATE_VECTOR_DIMENSION */ // // var = hdf_var_add(file, MIimage, "/minc-2.0/image/0/image", // ndims, dims); // var->is_cmpd = is_compound; // // H5Dclose(dset_id); // } // // dset_id = H5Dopen1(fd, "/minc-2.0/image/0/image-min"); // if (dset_id >= 0) { // hdf_get_diminfo(dset_id, &ndims, dims); // hdf_var_add(file, MIimagemin, "/minc-2.0/image/0/image-min", // ndims, dims); // H5Dclose(dset_id); // } // // dset_id = H5Dopen1(fd, "/minc-2.0/image/0/image-max"); // if (dset_id >= 0) { // hdf_get_diminfo(dset_id, &ndims, dims); // hdf_var_add(file, MIimagemax, "/minc-2.0/image/0/image-max", // ndims, dims); // H5Dclose(dset_id); // } // } H5E_END_TRY; // // /* Open all of the datasets in the "dimensions" category. // */ // grp_id = H5Gopen2(fd, "/minc-2.0/dimensions", H5P_DEFAULT); // hdf_open_dsets(file, grp_id, "/minc-2.0/dimensions/", 1); // H5Gclose(grp_id); // // /* Open all of the datasets in the "info" category. // */ // grp_id = H5Gopen2(fd, "/minc-2.0/info", H5P_DEFAULT); // hdf_open_dsets(file, grp_id, "/minc-2.0/info/", 0); // H5Gclose(grp_id); return fd; } /** * Create an HDF5 file. */ static hid_t _hdf_create(const char *path, int cmode) { hid_t grp_id; hid_t fd; hid_t tmp_id; hid_t hdf_gpid; hid_t fpid; fpid = H5Pcreate (H5P_FILE_ACCESS); /*VF use all the features of new HDF5 1.8*/ H5Pset_libver_bounds (fpid, H5F_LIBVER_18, H5F_LIBVER_18); H5E_BEGIN_TRY { fd = H5Fcreate(path, cmode, H5P_DEFAULT, fpid); } H5E_END_TRY; if (fd < 0) { /*TODO: report error properly*/ return MI_LOG_ERROR(MI2_MSG_CREATEFILE,path); } /* Create the default groups. * Should we use a non-zero value for size_hint (parameter 3)??? */ hdf_gpid = H5Pcreate (H5P_GROUP_CREATE); H5Pset_attr_phase_change (hdf_gpid, 0, 0); MI_CHECK_HDF_CALL_RET(grp_id = H5Gcreate2(fd, MI_ROOT_PATH , H5P_DEFAULT, hdf_gpid, H5P_DEFAULT),"H5Gcreate2") MI_CHECK_HDF_CALL_RET(tmp_id = H5Gcreate2(grp_id, "dimensions", H5P_DEFAULT, hdf_gpid, H5P_DEFAULT),"H5Gcreate2") H5Gclose(tmp_id); MI_CHECK_HDF_CALL_RET(tmp_id = H5Gcreate2(grp_id, "info", H5P_DEFAULT, hdf_gpid, H5P_DEFAULT),"H5Gcreate2") H5Gclose(tmp_id); MI_CHECK_HDF_CALL_RET(tmp_id = H5Gcreate2(grp_id, "image", H5P_DEFAULT, hdf_gpid, H5P_DEFAULT),"H5Gcreate2") H5Gclose(tmp_id); MI_CHECK_HDF_CALL_RET(tmp_id = H5Gcreate2(grp_id, "image/0", H5P_DEFAULT, hdf_gpid, H5P_DEFAULT),"H5Gcreate2") H5Pclose ( hdf_gpid ); H5Gclose(tmp_id); H5Gclose(grp_id); return fd; } static int _hdf_close(hid_t fd) { //TODO: make sure we save all that is needed MI_CHECK_HDF_CALL_RET(H5Fclose(fd),"H5Fclose") return MI_NOERROR; } /** Create the actual image for the volume. * Note that the image dataset muct be created in the hierarchy * before the image data can be added. * \ingroup mi2Vol */ int micreate_volume_image(mihandle_t volume) { char dimorder[MI2_CHAR_LENGTH]; int i; hid_t dataspace_id; hid_t dset_id; hsize_t hdf_size[MI2_MAX_VAR_DIMS]; /* Try creating IMAGE dataset i.e. /minc-2.0/image/0/image */ dimorder[0] = '\0'; /* Set string to empty */ for (i = 0; i < volume->number_of_dims; i++) { hdf_size[i] = volume->dim_handles[i]->length; /* Create the dimorder string, ordered comma-separated list of dimension names. */ strncat(dimorder, volume->dim_handles[i]->name, MI2_CHAR_LENGTH - 1); if (i != volume->number_of_dims - 1) { strncat(dimorder, ",", MI2_CHAR_LENGTH - 1); } } /* Create a SIMPLE dataspace */ dataspace_id = H5Screate_simple(volume->number_of_dims, hdf_size, NULL); if (dataspace_id < 0) { return MI_ERROR; } MI_CHECK_HDF_CALL_RET(dset_id = H5Dcreate1(volume->hdf_id, MI_ROOT_PATH "/image/0/image", volume->ftype_id, dataspace_id, volume->plist_id),"H5Dcreate1") volume->image_id = dset_id; add_standard_minc_attributes(volume->hdf_id,volume->image_id); /* Create the dimorder attribute, ordered comma-separated list of dimension names. */ miset_attr_at_loc(dset_id, "dimorder", MI_TYPE_STRING, strlen(dimorder), dimorder); H5Sclose(dataspace_id); if (volume->volume_class == MI_CLASS_REAL) { int ndims; hid_t dcpl_id; double dtmp; MI_CHECK_HDF_CALL_RET(dcpl_id = H5Pcreate(H5P_DATASET_CREATE),"H5Pcreate") if (volume->has_slice_scaling) { /* TODO: Find the slowest-varying spatial dimension; that forms * the basis for the image-min and image-max variables. Right * now this is an oversimplification! */ ndims = volume->number_of_dims - 2; MI_CHECK_HDF_CALL_RET(dataspace_id = H5Screate_simple(ndims, hdf_size, NULL),"H5Screate_simple") } else { ndims = 0; MI_CHECK_HDF_CALL_RET(dataspace_id = H5Screate(H5S_SCALAR),"H5Screate") } if (ndims != 0) { dimorder[0] = '\0'; /* Set string to empty */ for (i = 0; i < ndims; i++) { /* Create the dimorder string, ordered comma-separated list of dimension names. */ strncat(dimorder, volume->dim_handles[i]->name, MI2_CHAR_LENGTH - 1); if (i != volume->number_of_dims - 1) { strncat(dimorder, ",", MI2_CHAR_LENGTH - 1); } } } /* Create the image minimum dataset for FULL-RESOLUTION storage of data */ dtmp = 0.0; H5Pset_fill_value(dcpl_id, H5T_NATIVE_DOUBLE, &dtmp); MI_CHECK_HDF_CALL_RET(dset_id = H5Dcreate1(volume->hdf_id, MI_ROOT_PATH "/image/0/image-min", H5T_IEEE_F64LE, dataspace_id, dcpl_id),H5Dcreate1) if (ndims != 0) { miset_attr_at_loc(dset_id, "dimorder", MI_TYPE_STRING, strlen(dimorder), dimorder); } volume->imin_id = dset_id; add_standard_minc_attributes(volume->hdf_id,volume->imin_id); /* Create the image maximum dataset for FULL-RESOLUTION storage of data */ dtmp = 1.0; H5Pset_fill_value(dcpl_id, H5T_NATIVE_DOUBLE, &dtmp); MI_CHECK_HDF_CALL_RET(dset_id = H5Dcreate1(volume->hdf_id, MI_ROOT_PATH "/image/0/image-max", H5T_IEEE_F64LE, dataspace_id, dcpl_id),"H5Dcreate1") if (ndims != 0) { miset_attr_at_loc(dset_id, "dimorder", MI_TYPE_STRING, strlen(dimorder), dimorder); } volume->imax_id = dset_id; add_standard_minc_attributes(volume->hdf_id,volume->imax_id); H5Sclose(dataspace_id); H5Pclose(dcpl_id); } return (MI_NOERROR); } /** Set up the array of conversions from voxel to world coordinate order. */ static int miset_volume_world_indices(mihandle_t hvol) { int i; for (i = 0; i < hvol->number_of_dims; i++) { midimhandle_t hdim = hvol->dim_handles[i]; hdim->world_index = -1; if (hdim->dim_class == MI_DIMCLASS_SPATIAL) { if (!strcmp(hdim->name, MIxspace)) { hdim->world_index = MI2_X; } else if (!strcmp(hdim->name, MIyspace)) { hdim->world_index = MI2_Y; } else if (!strcmp(hdim->name, MIzspace)) { hdim->world_index = MI2_Z; } } else if (hdim->dim_class == MI_DIMCLASS_SFREQUENCY) { if (!strcmp(hdim->name, MIxfrequency)) { hdim->world_index = MI2_X; } else if (!strcmp(hdim->name, MIyfrequency)) { hdim->world_index = MI2_Y; } else if (!strcmp(hdim->name, MIzfrequency)) { hdim->world_index = MI2_Z; } } } return (MI_NOERROR); } /** Create and initialize a MINC 2.0 volume structure. */ static mihandle_t mialloc_volume_handle(void) { mihandle_t handle = (mihandle_t) malloc(sizeof(struct mivolume)); if (handle != NULL) { /* Clear the memory by default. */ memset(handle, 0, sizeof(struct mivolume)); /* Set the defaults for the data structure */ handle->scale_min = 0.0; handle->scale_max = 1.0; handle->image_id = -1; handle->imax_id = -1; handle->imin_id = -1; handle->plist_id = -1; handle->has_slice_scaling = FALSE; handle->is_dirty = FALSE; handle->dim_indices = NULL; handle->selected_resolution = 0; } return (handle); } /** Create a volume with the specified name, dimensions, type, class, volume properties and retrieve the volume handle. \ingroup mi2Vol */ int micreate_volume(const char *filename, int number_of_dimensions, midimhandle_t dimensions[], mitype_t volume_type, miclass_t volume_class, mivolumeprops_t create_props, mihandle_t *volume) { int i; int stat; hid_t file_id; hid_t hdf_type; hid_t hdf_plist; hid_t fspc_id; hsize_t dim[1]; hid_t grp_id; herr_t status; hid_t dataset_id = -1; hid_t dataset_width = -1; hid_t dataspace_id = -1; char *name; size_t size; hsize_t hdf_size[MI2_MAX_VAR_DIMS]; mihandle_t handle; mivolumeprops_t props_handle; char ident_str[128]; hid_t tmp_type; int dimension_is_vector = 0; /* Initialization. For the actual body of this function look at m2utils.c */ miinit(); /* Validate the parameters. */ if (filename == NULL) { return MI_LOG_ERROR(MI2_MSG_CREATEFILE," (NULL) "); } if (dimensions == NULL && number_of_dimensions != 0) { return MI_LOG_ERROR(MI2_MSG_GENERIC," Can't create volume with undefined dimensions"); } /* Allocate space for the volume handle */ handle = mialloc_volume_handle(); if (handle == NULL) { return MI_LOG_ERROR(MI2_MSG_OUTOFMEM,sizeof(struct mivolume)); } /* Initialize some of the variables associated with the volume handle. */ handle->mode = MI2_OPEN_RDWR; handle->number_of_dims = number_of_dimensions; /* convert minc type to hdf type */ hdf_type = mitype_to_hdftype(volume_type, FALSE); /* Setting up volume type_id */ switch (volume_class) { case MI_CLASS_REAL: case MI_CLASS_INT: handle->ftype_id = hdf_type; handle->mtype_id = H5Tget_native_type(handle->ftype_id, H5T_DIR_ASCEND); break; case MI_CLASS_LABEL: /* A volume of class LABEL must have an integer type (positive). */ switch (volume_type) { case MI_TYPE_UBYTE: case MI_TYPE_USHORT: case MI_TYPE_UINT: case MI_TYPE_BYTE: case MI_TYPE_SHORT: case MI_TYPE_INT: MI_CHECK_HDF_CALL_RET(handle->ftype_id = H5Tenum_create(hdf_type),"H5Tenum_create") tmp_type = H5Tget_native_type(hdf_type, H5T_DIR_ASCEND); H5Tclose(hdf_type); hdf_type = tmp_type; /* Create an enumerated type with the native type as it's base. */ MI_CHECK_HDF_CALL_RET(handle->mtype_id = H5Tenum_create(hdf_type),"H5Tenum_create") H5Tclose(hdf_type); miinit_enum(handle->ftype_id); miinit_enum(handle->mtype_id); break; default: free(handle); return (MI_ERROR); } break; case MI_CLASS_COMPLEX: switch (volume_type) { case MI_TYPE_SCOMPLEX: case MI_TYPE_ICOMPLEX: case MI_TYPE_FCOMPLEX: case MI_TYPE_DCOMPLEX: handle->ftype_id = hdf_type; handle->mtype_id = mitype_to_hdftype(volume_type, TRUE); break; default: free(handle); return MI_LOG_ERROR(MI2_MSG_BADTYPE,volume_type); } break; case MI_CLASS_UNIFORM_RECORD: MI_CHECK_HDF_CALL_RET(handle->ftype_id = H5Tcreate(H5T_COMPOUND, H5Tget_size(hdf_type)),"H5Tcreate") MI_CHECK_HDF_CALL_RET(handle->mtype_id = H5Tcreate(H5T_COMPOUND, H5Tget_size(hdf_type)),"H5Tcreate") H5Tclose(hdf_type); break; default: free(handle); return (MI_ERROR); } handle->volume_class = volume_class; /* Create file in HDF5 with the given filename and H5F_ACC_TRUNC: Truncate file, if it already exists, erasing all data previously stored in the file. and create ID and ID access as default. */ file_id = _hdf_create(filename, H5F_ACC_TRUNC); if (file_id < 0) { free(handle); return (MI_ERROR); } handle->hdf_id = file_id; _generate_ident(ident_str, sizeof(ident_str)); miset_attribute(handle, MI_ROOT_PATH, "ident", MI_TYPE_STRING, strlen(ident_str), ident_str); miset_attribute(handle, MI_ROOT_PATH, "minc_version", MI_TYPE_STRING, strlen(MINC_VERSION), MINC_VERSION); _miset_volume_class(handle, handle->volume_class); /* Create a new property list for the volume */ MI_CHECK_HDF_CALL_RET(hdf_plist = H5Pcreate(H5P_DATASET_CREATE),"H5Pcreate") handle->plist_id = hdf_plist; /* Set fill value to guarantee valid data on incomplete datasets. */ if (volume_class != MI_CLASS_LABEL && volume_class != MI_CLASS_UNIFORM_RECORD) { size_t siz = H5Tget_size(handle->ftype_id); char *tmp = calloc(1, siz); H5Pset_fill_value(hdf_plist, handle->ftype_id, tmp); free(tmp); } /* See if chunking and/or compression should be enabled and if yes set the type of storage used to store the raw data for a dataset. */ if (create_props != NULL && (create_props->compression_type == MI_COMPRESS_ZLIB || create_props->edge_count != 0)) { /* Set the storage to CHUNKED */ MI_CHECK_HDF_CALL_RET(stat = H5Pset_layout(hdf_plist, H5D_CHUNKED),"H5Pset_layout") /* Create an array, hdf_size, containing the size of each chunk */ for (i=0; i < number_of_dimensions; i++) { hdf_size[i] = create_props->edge_lengths[i]; /* If the size of each chunk is greater than the size of the corresponding dimension, set the chunk size to the dimension size */ if (hdf_size[i] > dimensions[i]->length) { hdf_size[i] = dimensions[i]->length; } } /* Sets the size of the chunks used to store a chunked layout dataset */ MI_CHECK_HDF_CALL_RET(stat = H5Pset_chunk(hdf_plist, number_of_dimensions, hdf_size),"H5Pset_chunk") /* Sets compression method and compression level */ MI_CHECK_HDF_CALL_RET(stat = H5Pset_deflate(hdf_plist, create_props->zlib_level),"H5Pset_deflate") } else { /* No COMPRESSION or CHUNKING is enabled */ MI_CHECK_HDF_CALL_RET(stat = H5Pset_layout(hdf_plist, H5D_CONTIGUOUS),"H5Pset_layout") /* CONTIGUOUS data */ } /* See if Multi-res is set to a level above 0 and if yes create subgroups i.e., /minc-2.0/image/1/.. /minc-2.0/image/2/.. etc */ // must add some code to make sure that the res level is possible if (create_props != NULL && create_props->depth > 0) { for (i=0; i < create_props->depth ; i++) { if (minc_create_thumbnail(handle, i+1) < 0) { free(handle); return (MI_ERROR); } } } /* Try creating DIMENSIONS GROUP i.e. /minc-2.0/dimensions */ MI_CHECK_HDF_CALL_RET(grp_id = H5Gopen1(file_id, MI_FULLDIMENSIONS_PATH),"H5Gopen1") /* Once the DIMENSIONS GROUP is opened, create each dimension. */ for (i=0; i < number_of_dimensions ; i++) { /* First create the dataspace required to create a dimension variable (dataset) */ if (dimensions[i]->attr & MI_DIMATTR_NOT_REGULARLY_SAMPLED) { dim[0] = dimensions[i]->length; MI_CHECK_HDF_CALL_RET(dataspace_id = H5Screate_simple(1, dim, NULL),"H5Screate_simple") } else { MI_CHECK_HDF_CALL_RET(dataspace_id = H5Screate(H5S_SCALAR),"H5Screate") } if (dataspace_id < 0) { free(handle); return (MI_ERROR); } dimension_is_vector= (strcmp ( dimensions[i]->name, MIvector_dimension ) == 0 ); /* Create a dataset(dimension variable name) in DIMENSIONS GROUP */ MI_CHECK_HDF_CALL_RET(dataset_id = H5Dcreate1(grp_id, dimensions[i]->name, H5T_IEEE_F64LE, dataspace_id, H5P_DEFAULT),"H5Dcreate1") /* Dimension variable for a regular dimension contains no meaningful data. Whereas, Dimension variable for an irregular dimension contains a vector with the lengths equal to the sampled points along the dimension. Also, create a variable named "<dimension>-width" and write the dimension->widths. */ if(!dimension_is_vector ) add_standard_minc_attributes(file_id,dataset_id); /*vector dimension is a record*/ /* Check for irregular dimension and make sure offset values are provided for this dimension */ if (dimensions[i]->attr & MI_DIMATTR_NOT_REGULARLY_SAMPLED) { if (dimensions[i]->offsets == NULL) { free(handle); return (MI_ERROR); } else { /* If dimension is regularly sampled */ MI_CHECK_HDF_CALL_RET(fspc_id = H5Dget_space(dataset_id),"H5Dget_space") /* Write the raw data from buffer (dimensions[i]->offsets) to the dataset. */ MI_CHECK_HDF_CALL_RET(status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, dataspace_id, fspc_id, H5P_DEFAULT, dimensions[i]->offsets),"H5Dwrite") /* Write the raw data from buffer (dimensions[i]->offsets) to the dataset. */ size = strlen(dimensions[i]->name) + 6 + 1; name = malloc(size); strcpy(name, dimensions[i]->name); strcat(name, "-width"); /* Create dataset dimension_name-width */ dataset_width = H5Dcreate1(grp_id, name, H5T_IEEE_F64LE, dataspace_id, H5P_DEFAULT); /* Return an Id for the dataspace of the dataset dataset_width */ MI_CHECK_HDF_CALL_RET(fspc_id = H5Dget_space(dataset_width),"H5Dget_space") /* Write the raw data from buffer (dimensions[i]->widths) to the dataset. */ MI_CHECK_HDF_CALL_RET(status = H5Dwrite(dataset_width, H5T_NATIVE_DOUBLE, dataspace_id, fspc_id, H5P_DEFAULT, dimensions[i]->widths),"H5Dwrite") /* Create new attribute "length", with appropriate type (to hdf5) conversion. miset_attr_at_loc(..) is implemented at m2utils.c */ miset_attr_at_loc(dataset_width, "length", MI_TYPE_INT, 1, &dimensions[i]->length); /* Close the specified datatset */ H5Dclose(dataset_width); free(name); } } if (dimensions[i]->attr & MI_DIMATTR_NOT_REGULARLY_SAMPLED) { name = "irregular"; } else { name = "regular__"; } /* Create attribute "spacing" and set its value to "regular__" or "irregular" */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "spacing", MI_TYPE_STRING, strlen(name), name); switch (dimensions[i]->dim_class) { case MI_DIMCLASS_SPATIAL: name = "spatial"; break; case MI_DIMCLASS_TIME: name = "time___"; break; case MI_DIMCLASS_SFREQUENCY: name = "sfreq__"; break; case MI_DIMCLASS_TFREQUENCY: name = "tfreq__"; break; case MI_DIMCLASS_USER: name = "user___"; break; case MI_DIMCLASS_RECORD: name = "record_"; break; case MI_DIMCLASS_ANY: default: /* These should not be seen in this context!!! */ return (MI_ERROR); } if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "class", MI_TYPE_STRING, strlen(name), name); /* Create Dimension attribute "direction_cosines" */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "direction_cosines", MI_TYPE_DOUBLE, 3, dimensions[i]->direction_cosines); /* Save dimension length */ miset_attr_at_loc(dataset_id, "length", MI_TYPE_INT, 1, &dimensions[i]->length); /* Save step value. */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "step", MI_TYPE_DOUBLE, 1, &dimensions[i]->step); /* Save start value. */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "start", MI_TYPE_DOUBLE, 1, &dimensions[i]->start); /* Save units. */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "units", MI_TYPE_STRING, strlen(dimensions[i]->units), dimensions[i]->units); /* Save sample width. */ if(!dimension_is_vector) miset_attr_at_loc(dataset_id, "width", MI_TYPE_DOUBLE, 1, &dimensions[i]->width); /* Save comments. If user has not specified any comments, do not add this attribute */ if (dimensions[i]->comments != NULL) { miset_attr_at_loc(dataset_id, "comments", MI_TYPE_STRING, strlen(dimensions[i]->comments), dimensions[i]->comments); } /* Close the dataset with the specified Id */ H5Dclose(dataset_id); } //for (i=0; i < number_of_dimensions ; i++) /* Close the group with the specified Id */ H5Gclose(grp_id); /* Allocate space for all the dimension handles Note, each volume handle is associated with an array of dimension handles in the order that they were create (i.e, file order) */ handle->dim_handles = (midimhandle_t *)malloc(number_of_dimensions * sizeof(midimhandle_t)); if (handle->dim_handles == NULL) { return MI_LOG_ERROR(MI2_MSG_OUTOFMEM,number_of_dimensions * sizeof(midimhandle_t)); } /* Once the space for all dimension handles is created fill the dimension handle array with the appropriate dimension handle. */ for (i = 0; i < number_of_dimensions; i++) { handle->dim_handles[i] = dimensions[i]; dimensions[i]->volume_handle = handle; } miset_volume_world_indices(handle); /* Verify the volume type. */ switch (volume_type) { case MI_TYPE_BYTE: case MI_TYPE_SHORT: case MI_TYPE_INT: case MI_TYPE_FLOAT: case MI_TYPE_DOUBLE: case MI_TYPE_STRING: case MI_TYPE_UBYTE: case MI_TYPE_USHORT: case MI_TYPE_UINT: case MI_TYPE_SCOMPLEX: case MI_TYPE_ICOMPLEX: case MI_TYPE_FCOMPLEX: case MI_TYPE_DCOMPLEX: case MI_TYPE_UNKNOWN: break; default: return MI_LOG_ERROR(MI2_MSG_BADTYPE,volume_type); } handle->volume_type = volume_type; /* Set the initial value of the valid-range */ miinit_default_range(handle->volume_type, &handle->valid_max, &handle->valid_min); /* Get the voxel to world transform for the volume */ miget_voxel_to_world(handle, handle->v2w_transform); /* Calculate the inverse transform */ miinvert_transform(handle->v2w_transform, handle->w2v_transform); /* Allocated space for the volume properties */ props_handle = (mivolumeprops_t)malloc(sizeof(struct mivolprops)); /* Initialize volume properties with zero */ memset(props_handle, 0, sizeof (struct mivolprops)); /* If volume properties is specified by the user set all the properties of the volume handle */ if (create_props != NULL) { /* Set the enable_flag for multi-resolution */ props_handle->enable_flag = create_props->enable_flag; /* Set the depth of multi-resolution, i.e., how many levels of resolution is specified maximum is 16. */ props_handle->depth = create_props->depth; /* Set compression type, currently two values either no compression or zlib is applicable. */ switch (create_props->compression_type) { case MI_COMPRESS_NONE: props_handle->compression_type = MI_COMPRESS_NONE; break; case MI_COMPRESS_ZLIB: props_handle->compression_type = MI_COMPRESS_ZLIB; break; default: free(props_handle); return MI_LOG_ERROR(MI2_MSG_BADTYPE,create_props->compression_type); } /* Note that setting compression on (i.e., MI_COMPRESS_ZLIB) turns chunking on by default. Need to set the number of chunks (edge_count) */ props_handle->zlib_level = create_props->zlib_level; props_handle->edge_count = create_props->edge_count; /* Allocate space for an array which holds the size of each chunk and fill the array with the appropriiate chunk sizes. */ props_handle->edge_lengths = (int *)malloc(create_props->max_lengths*sizeof(int)); for (i=0; i<create_props->max_lengths; i++) { props_handle->edge_lengths[i] = create_props->edge_lengths[i]; } props_handle->max_lengths = create_props->max_lengths; props_handle->record_length = create_props->record_length; /* Explicitly allocate storage for name */ if (create_props->record_name != NULL) { props_handle->record_name =malloc(strlen(create_props->record_name) + 1 ); strcpy(props_handle->record_name, create_props->record_name); } props_handle->template_flag = create_props->template_flag; } /* Set the handle to volume properties */ handle->create_props = props_handle; /* Return volume handle */ *volume = handle; return (MI_NOERROR); } /** Return the number of dimensions associated with this volume. * \ingroup mi2Vol */ int miget_volume_dimension_count(mihandle_t volume, midimclass_t cls, midimattr_t attr, int *number_of_dimensions) { int i, count=0; /* Validate the parameters */ if (volume == NULL || number_of_dimensions == NULL) { return MI_LOG_ERROR(MI2_MSG_GENERIC,"Trying to get dimension count with null volume or null variable"); } /* For each dimension check to make sure that dimension class and attribute match with the specified parameters and if yes increment the dimension count */ for (i=0; i< volume->number_of_dims; i++) { if ((cls == MI_DIMCLASS_ANY || volume->dim_handles[i]->dim_class == cls) && (attr == MI_DIMATTR_ALL || volume->dim_handles[i]->attr == attr)) { count++; } } *number_of_dimensions = count; return (MI_NOERROR); } /** Returns the number of voxels in the volume. * \ingroup mi2Vol */ int miget_volume_voxel_count(mihandle_t volume, misize_t *number_of_voxels) { char path[MI2_MAX_PATH]; hid_t dset_id; hid_t fspc_id; /* Validate parameters */ if (volume == NULL || number_of_voxels == NULL) { return MI_LOG_ERROR(MI2_MSG_GENERIC,"Trying to get voxel count with null volume or null variable"); } /* Quickest way to do this is with the dataspace identifier of the * volume. Use the volume's current resolution. */ sprintf(path, MI_ROOT_PATH "/image/%d/image", volume->selected_resolution); /* Open the dataset with the specified path */ MI_CHECK_HDF_CALL_RET(dset_id = H5Dopen1(volume->hdf_id, path),"H5Dopen1"); /* Get an Id to the copy of the dataspace */ MI_CHECK_HDF_CALL_RET(fspc_id = H5Dget_space(dset_id),"H5Dget_space"); /* Determines the number of elements in the dataspace and cast the result to an integer. */ *number_of_voxels = (misize_t) H5Sget_simple_extent_npoints(fspc_id); /* Close the dataspace */ H5Sclose(fspc_id); /* Close the dataset */ H5Dclose(dset_id); return (MI_NOERROR); } /* Get the number of dimensions in the file */ static int _miget_file_dimension_count(hid_t file_id) { hid_t dset_id; hid_t space_id; int result = -1; /* hdf5 macro can temporarily disable the automatic error printing */ H5E_BEGIN_TRY { dset_id = midescend_path(file_id, MI_ROOT_PATH "/image/0/image"); } H5E_END_TRY; if (dset_id >= 0) { /* Get an Id to the copy of the dataspace */ MI_CHECK_HDF_CALL(space_id = H5Dget_space(dset_id),"H5Dget_space"); if (space_id > 0) { /* Determine the dimensionality of the dataspace */ MI_CHECK_HDF_CALL(result = H5Sget_simple_extent_ndims(space_id),"H5Sget_simple_extent_ndims"); /* Close the dataspace */ H5Sclose(space_id); } /* Close the dataset */ H5Dclose(dset_id); } return (result); } /* Get dimension variable attributes for the given dimension name */ static int _miset_volume_class(mihandle_t volume, miclass_t volume_class) { const char *class_ptr; switch (volume_class) { case MI_CLASS_REAL: class_ptr = "real___"; break; case MI_CLASS_INT: class_ptr = "integer"; break; case MI_CLASS_LABEL: class_ptr = "label__"; break; case MI_CLASS_COMPLEX: class_ptr = "complex"; break; case MI_CLASS_UNIFORM_RECORD: class_ptr = "array__"; break; default: return MI_LOG_ERROR(MI2_MSG_GENERIC,"Unknown volume class"); } miset_attribute(volume, MI_ROOT_PATH, "class", MI_TYPE_STRING, strlen(class_ptr), class_ptr); return (MI_NOERROR); } static int _miget_volume_class(mihandle_t volume, miclass_t *volume_class) { char class_buf[MI2_CHAR_LENGTH]; if( miget_attribute(volume, MI_ROOT_PATH, "class", MI_TYPE_STRING, MI2_CHAR_LENGTH, class_buf) == MI_NOERROR ) { if (!strcmp(class_buf, "label__")) { *volume_class = MI_CLASS_LABEL; } else if (!strcmp(class_buf, "integer")) { *volume_class = MI_CLASS_INT; } else if (!strcmp(class_buf, "complex")) { *volume_class = MI_CLASS_COMPLEX; } else if (!strcmp(class_buf, "array__")) { *volume_class = MI_CLASS_UNIFORM_RECORD; } else { *volume_class = MI_CLASS_REAL; } } else { /*probably volume doesn't have this attribute*/ *volume_class = MI_CLASS_REAL; } return (MI_NOERROR); } /* Get dimension variable attributes for the given dimension name */ static int _miget_file_dimension(mihandle_t volume, const char *dimname, midimhandle_t *hdim_ptr) { char path[MI2_CHAR_LENGTH]; char temp[MI2_CHAR_LENGTH]; midimhandle_t hdim; unsigned int len; /* Create a path with the dimension name */ sprintf(path, MI_ROOT_PATH "/dimensions/%s", dimname); /* Allocate space for the dimension handle */ hdim = (midimhandle_t) malloc(sizeof (*hdim)); /* Initialize everything to zero */ memset(hdim, 0, sizeof (*hdim)); hdim->name = strdup(dimname); /* hdf5 macro can temporarily disable the automatic error printing */ H5E_BEGIN_TRY { int r; /* Get the attribute (spacing) from a minc file */ r = miget_attribute(volume, path, "spacing", MI_TYPE_STRING, MI2_CHAR_LENGTH, temp); if (r==MI_NOERROR && !strcmp(temp, "irregular")) { hdim->attr |= MI_DIMATTR_NOT_REGULARLY_SAMPLED; } else { hdim->attr |= MI_DIMATTR_REGULARLY_SAMPLED; } /* Get the attribute (class) from a minc file */ r = miget_attribute(volume, path, "class", MI_TYPE_STRING, MI2_CHAR_LENGTH, temp); if (r < 0) { /* Get the default class. */ if (!strcmp(dimname, MItime)) { hdim->dim_class = MI_DIMCLASS_TIME; } else if (!strcmp(dimname, MIvector_dimension)) { hdim->dim_class = MI_DIMCLASS_RECORD; hdim->step = 0.0; } else { hdim->dim_class = MI_DIMCLASS_SPATIAL; } } else { if (!strcmp(temp, "spatial")) { hdim->dim_class = MI_DIMCLASS_SPATIAL; } else if (!strcmp(temp, "time___")) { hdim->dim_class = MI_DIMCLASS_TIME; } else if (!strcmp(temp, "sfreq__")) { hdim->dim_class = MI_DIMCLASS_SFREQUENCY; } else if (!strcmp(temp, "tfreq__")) { hdim->dim_class = MI_DIMCLASS_TFREQUENCY; } else if (!strcmp(temp, "user___")) { hdim->dim_class = MI_DIMCLASS_USER; } else if (!strcmp(temp, "record_")) { hdim->dim_class = MI_DIMCLASS_RECORD; } else { MI_LOG_ERROR(MI2_MSG_GENERIC,"Unknown dimension type"); } } /* Get the attribute (length) from a minc file. We have to do this in * two steps, as MI_TYPE_UINT is not necessarily the same size as * hsize_t/misize_t, so we have to read the value into a variable of * the right type, then assign it to the structure member, to guarantee * proper promotion. */ r = miget_attribute(volume, path, "length", MI_TYPE_UINT, 1, &len); if (r < 0) { MI_LOG_ERROR(MI2_MSG_GENERIC,"Can't determine dimension length"); } hdim->length = len; /* Will promote unsigned int to misize_t. */ /* Get the attribute (start) from a minc file for NON vector_dimension only */ if (strcmp(dimname, "vector_dimension")) { r = miget_attribute(volume, path, MIstart, MI_TYPE_DOUBLE, 1, &hdim->start); if (r < 0) { hdim->start = 0.0; } /* Get the attribute (step) from a minc file */ r = miget_attribute(volume, path, MIstep, MI_TYPE_DOUBLE, 1, &hdim->step); if (r < 0) { hdim->step = 1.0; } } /* Get the attribute (direction_cosines) from a minc file */ r = miget_attribute(volume, path, MIdirection_cosines, MI_TYPE_DOUBLE, 3, hdim->direction_cosines); if (r < 0) { hdim->direction_cosines[MI2_X] = 0.0; hdim->direction_cosines[MI2_Y] = 0.0; hdim->direction_cosines[MI2_Z] = 0.0; if (!strcmp(dimname, MIxspace)) { hdim->direction_cosines[MI2_X] = 1.0; } else if (!strcmp(dimname, MIyspace)) { hdim->direction_cosines[MI2_Y] = 1.0; } else if (!strcmp(dimname, MIzspace)) { hdim->direction_cosines[MI2_Z] = 1.0; } } r = miget_attribute(volume, path, "units", MI_TYPE_STRING, MI2_CHAR_LENGTH, temp); if (r < 0) { hdim->units = strdup(""); } else { hdim->units = strdup(temp); } } H5E_END_TRY; /* Return the dimension handle */ *hdim_ptr = hdim; hdim->volume_handle = volume; return (MI_NOERROR); } /** Opens an existing MINC volume for read-only access if mode argument is * MI2_OPEN_READ, or read-write access if mode argument is MI2_OPEN_RDWR. * \ingroup mi2Vol */ int miopen_volume(const char *filename, int mode, mihandle_t *volume) { hid_t file_id; hid_t dset_id; hid_t space_id; mihandle_t handle; int hdf_mode; char dimorder[MI2_CHAR_LENGTH]; int i,r; char *p1, *p2; H5T_class_t hdf_class; size_t nbytes; int is_signed; int n_dimensions; /* Initialization. For the actual body of this function look at m2utils.c */ miinit(); /* Convert the specified mode to hdf mode */ if (mode == MI2_OPEN_READ) { hdf_mode = H5F_ACC_RDONLY; } else if (mode == MI2_OPEN_RDWR) { hdf_mode = H5F_ACC_RDWR; } else { return (MI_ERROR); } /* Allocate space for the volume handle */ handle = mialloc_volume_handle(); if (handle == NULL) { return MI_LOG_ERROR(MI2_MSG_OUTOFMEM,sizeof(struct mivolume)); } /* Open the hdf file using the given filename and mode */ file_id = _hdf_open(filename, hdf_mode); if (file_id < 0) { /*try to convert MINC1 file*/ #ifdef HAVE_MINC1 char * temp_file=NULL; if ( mode == MI2_OPEN_READ ) { if( (temp_file=micreate_tempfile())) { if( minc_format_convert(filename,temp_file) == MI_NOERROR ) { if( (file_id = _hdf_open(temp_file, hdf_mode) ) >0) { unlink( temp_file ); /*file will be deleted immedeately after closing...*/ free( temp_file ); } else { unlink( temp_file ); free( temp_file ); free( handle ); return MI_LOG_ERROR(MI2_MSG_OPENFILE,filename); } } else { free( temp_file ); free( handle ); return MI_LOG_ERROR(MI2_MSG_OPENFILE,filename); } } else { free( temp_file ); free( handle ); return MI_LOG_ERROR(MI2_MSG_OPENFILE,filename); } } else { free( handle ); return MI_LOG_ERROR(MI2_MSG_OPENFILE,filename); } #else free( handle ); return MI_LOG_ERROR(MI2_MSG_OPENFILE,filename); #endif } /* Set some varibales associated with the volume handle */ handle->hdf_id = file_id; handle->mode = mode; /* Get the volume class. */ _miget_volume_class(handle, &handle->volume_class); /* GET THE DIMENSION COUNT */ n_dimensions = handle->number_of_dims = _miget_file_dimension_count(file_id); if( n_dimensions <= 0 ) { free(handle); return MI_LOG_ERROR(MI2_MSG_GENERIC,"Trying to open minc file without image variable"); } /* READ EACH OF THE DIMENSIONS */ handle->dim_handles = (midimhandle_t *)malloc(n_dimensions * sizeof(midimhandle_t)); if(handle->dim_handles == NULL) { free(handle); return MI_LOG_ERROR(MI2_MSG_OUTOFMEM, n_dimensions * sizeof(midimhandle_t)); } /* Get the attribute (dimorder) from the image dataset */ r = miget_attribute(handle, MI_ROOT_PATH "/image/0/image", "dimorder", MI_TYPE_STRING, sizeof(dimorder), dimorder); if ( r < 0) { return MI_LOG_ERROR(MI2_MSG_GENERIC,"Can't determine dimension order"); } p1 = dimorder; /* Break the ordered, comma-separated list of dimension names to get each individual dimension name */ for (i = 0; i < handle->number_of_dims; i++) { p2 = strchr(p1, ','); if (p2 != NULL) { *p2 = '\0'; } /* Get dimension variable attributes for each dimension */ _miget_file_dimension(handle, p1, &handle->dim_handles[i]); p1 = p2 + 1; } if( miset_volume_world_indices(handle) < 0 ) { return MI_LOG_ERROR(MI2_MSG_GENERIC,"Can't determine world indices"); } /* SEE IF SLICE SCALING IS ENABLED */ handle->has_slice_scaling = FALSE; /* hdf5 macro can temporarily disable the automatic error printing */ H5E_BEGIN_TRY { /* Open the dataset image-max at the specified path*/ dset_id = H5Dopen1(file_id, MI_ROOT_PATH "/image/0/image-max"); } H5E_END_TRY; if (dset_id >= 0) { /* Get the Id of the copy of the dataspace of the dataset */ space_id = H5Dget_space(dset_id); if (space_id >= 0) { /* If the dimensionality of the image-max variable is one or * greater, we consider this volume to have slice-scaling enabled. */ if (H5Sget_simple_extent_ndims(space_id) >= 1) { handle->has_slice_scaling = TRUE; } H5Sclose(space_id); /* Close the dataspace handle */ } H5Dclose(dset_id); /* Close the dataset handle */ } if (!handle->has_slice_scaling) { /* Read the minimum scalar of the given type at the specified path */ miget_scalar(handle->hdf_id, H5T_NATIVE_DOUBLE, MI_ROOT_PATH "/image/0/image-min", &handle->scale_min); /* Read the maximum scalar of the given type at the specified path */ miget_scalar(handle->hdf_id, H5T_NATIVE_DOUBLE, MI_ROOT_PATH "/image/0/image-max", &handle->scale_max); } /* Read the current voxel-to-world transform */ miget_voxel_to_world(handle, handle->v2w_transform); /* Calculate the inverse transform */ miinvert_transform(handle->v2w_transform, handle->w2v_transform); /* Open the image dataset */ MI_CHECK_HDF_CALL_RET(handle->image_id = H5Dopen1(file_id, MI_ROOT_PATH "/image/0/image"),"H5Dopen1"); /* Get the Id for the copy of the datatype for the dataset */ MI_CHECK_HDF_CALL_RET(handle->ftype_id = H5Dget_type(handle->image_id),"H5Dget_type"); switch (H5Tget_class(handle->ftype_id)) { case H5T_INTEGER: case H5T_FLOAT: handle->mtype_id = H5Tget_native_type(handle->ftype_id, H5T_DIR_ASCEND); break; case H5T_COMPOUND: handle->mtype_id = H5Tcreate(H5T_COMPOUND, H5Tget_size(handle->ftype_id)); for (i = 0; i < H5Tget_nmembers(handle->ftype_id); i++) { hid_t tmp_id = H5Tget_member_type(handle->ftype_id, i); size_t tmp_off = H5Tget_member_offset(handle->ftype_id, i); char *tmp_nm = H5Tget_member_name(handle->ftype_id, i); hid_t tmp2_id = H5Tget_native_type(tmp_id, H5T_DIR_ASCEND); H5Tinsert(handle->mtype_id, tmp_nm, tmp_off, tmp2_id); free(tmp_nm); H5Tclose(tmp_id); H5Tclose(tmp2_id); } break; case H5T_ENUM: handle->mtype_id = H5Tcopy(handle->ftype_id); miinit_enum(handle->ftype_id); miinit_enum(handle->mtype_id); /* Set native order ---> is not allowed after order is set */ //H5Tset_order(handle->mtype_id, H5Tget_order(H5T_NATIVE_INT)); break; default: return (MI_ERROR); } /* hdf5 macro can temporarily disable the automatic error printing */ H5E_BEGIN_TRY { /* Open both image-min and image-max datasets */ handle->imax_id = H5Dopen1(file_id, MI_ROOT_PATH "/image/0/image-max"); handle->imin_id = H5Dopen1(file_id, MI_ROOT_PATH "/image/0/image-min"); } H5E_END_TRY; /* Convert the type to a MINC type. */ /* Get the class Id for the datatype */ hdf_class = H5Tget_class(handle->ftype_id); /* Get the size of the datatype */ nbytes = H5Tget_size(handle->ftype_id); switch (hdf_class) { case H5T_INTEGER: case H5T_ENUM: /* label images */ is_signed = (H5Tget_sign(handle->ftype_id) == H5T_SGN_2); switch (nbytes) { case 1: handle->volume_type = (is_signed ? MI_TYPE_BYTE : MI_TYPE_UBYTE); break; case 2: handle->volume_type = (is_signed ? MI_TYPE_SHORT : MI_TYPE_USHORT); break; case 4: handle->volume_type = (is_signed ? MI_TYPE_INT : MI_TYPE_UINT); break; default: return MI_LOG_ERROR(MI2_MSG_BADTYPE,hdf_class); } break; case H5T_FLOAT: handle->volume_type = (nbytes == 4) ? MI_TYPE_FLOAT : MI_TYPE_DOUBLE; break; case H5T_STRING: handle->volume_type = MI_TYPE_STRING; break; case H5T_ARRAY: /* TODO: handle this case for uniform records (arrays)? */ break; case H5T_COMPOUND: /* TODO: handle this case for non-uniform records? */ break; default: return MI_LOG_ERROR(MI2_MSG_BADTYPE,hdf_class); } /* Read the current settings for valid-range */ miread_valid_range(handle, &handle->valid_max, &handle->valid_min); *volume = handle; return (MI_NOERROR); } /** Writes any changes associated with the volume to disk. \ingroup mi2Vol */ static int miflush_volume(mihandle_t volume) { if ((volume->mode & MI2_OPEN_RDWR) != 0) { H5Fflush(volume->hdf_id, H5F_SCOPE_GLOBAL); misave_valid_range(volume); } return (MI_NOERROR); } /** Close an existing MINC volume. If the volume was newly created, * all changes will be written to disk. In all cases this function closes * the open volume and frees memory associated with the volume handle. * \ingroup mi2Vol */ int miclose_volume(mihandle_t volume) { int i; if (volume == NULL) { return MI_LOG_ERROR(MI2_MSG_GENERIC,"Trying to close null volume"); } if (volume->is_dirty) { minc_update_thumbnails(volume); volume->is_dirty = FALSE; } miflush_volume(volume); if (volume->image_id > 0) { H5Dclose(volume->image_id); } if (volume->imax_id > 0) { H5Dclose(volume->imax_id); } if (volume->imin_id > 0) { H5Dclose(volume->imin_id); } if (volume->ftype_id > 0) { H5Tclose(volume->ftype_id); } if (volume->mtype_id > 0) { H5Tclose(volume->mtype_id); } if (volume->plist_id > 0) { H5Pclose(volume->plist_id); } if (_hdf_close(volume->hdf_id) < 0) { return (MI_ERROR); } if (volume->dim_handles != NULL) { for(i=0;i<volume->number_of_dims;i++) { mifree_dimension_handle(volume->dim_handles[i]); } free(volume->dim_handles); } if (volume->dim_indices != NULL) { free(volume->dim_indices); } if (volume->create_props != NULL) { mifree_volume_props(volume->create_props); } free(volume); return (MI_NOERROR); } /** \internal */ void miinit_default_range(mitype_t mitype, double *valid_max, double *valid_min) { switch (mitype) { case MI_TYPE_BYTE: *valid_min = CHAR_MIN; *valid_max = CHAR_MAX; break; case MI_TYPE_SHORT: *valid_min = SHRT_MIN; *valid_max = SHRT_MAX; break; case MI_TYPE_INT: *valid_min = INT_MIN; *valid_max = INT_MAX; break; case MI_TYPE_UBYTE: *valid_min = 0; *valid_max = UCHAR_MAX; break; case MI_TYPE_USHORT: *valid_min = 0; *valid_max = USHRT_MAX; break; case MI_TYPE_UINT: *valid_min = 0; *valid_max = UINT_MAX; break; case MI_TYPE_FLOAT: *valid_min = -FLT_MAX; *valid_max = FLT_MAX; break; case MI_TYPE_DOUBLE: *valid_min = -DBL_MAX; *valid_max = DBL_MAX; break; case MI_TYPE_DCOMPLEX: *valid_min = -DBL_MAX; *valid_max = DBL_MAX; break; case MI_TYPE_FCOMPLEX: *valid_min = -FLT_MAX; *valid_max = FLT_MAX; break; default: *valid_min = 0; *valid_max = 1; MI_LOG_ERROR(MI2_MSG_BADTYPE,mitype); break; } } /** \internal */ static void miread_valid_range(mihandle_t volume, double *valid_max, double *valid_min) { int r; double range[2]; H5E_BEGIN_TRY { r = miget_attribute(volume, MI_ROOT_PATH "/image/0/image", "valid_range", MI_TYPE_DOUBLE, 2, range); } H5E_END_TRY; if (r == MI_NOERROR) { if (range[0] < range[1]) { *valid_min = range[0]; *valid_max = range[1]; } else { *valid_min = range[1]; *valid_max = range[0]; } } else { /* Didn't find the attribute, so assign default values. */ miinit_default_range(volume->volume_type, valid_max, valid_min); } } /** \internal * This function saves the current valid range set for a MINC file. */ void misave_valid_range(mihandle_t volume) { double range[2]; range[0] = volume->valid_min; range[1] = volume->valid_max; miset_attribute(volume, MI_ROOT_PATH "/image/0/image", "valid_range", MI_TYPE_DOUBLE, 2, range); } int miget_slice_dimension_count(mihandle_t volume, midimclass_t dimclass, midimattr_t attr, int *number_of_dimensions) { int number_of_volume_dimensions=-1; hid_t image_max_fspc_id; int slice_ndims; int result=-1; if( miget_volume_dimension_count(volume,dimclass,attr, &number_of_volume_dimensions) <0 ) { return -1; } if(!volume->has_slice_scaling) { *number_of_dimensions=number_of_volume_dimensions; return MI_NOERROR; } image_max_fspc_id=H5Dget_space(volume->imax_id); slice_ndims = H5Sget_simple_extent_ndims ( image_max_fspc_id ); if(slice_ndims>=0) { result=MI_NOERROR; *number_of_dimensions=number_of_volume_dimensions-slice_ndims; } H5Sclose(image_max_fspc_id); return result; } // kate: indent-mode cstyle; indent-width 2; replace-tabs on;
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-securityhub/source/model/AwsEcsServiceDeploymentConfigurationDetails.cpp
3
2244
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/AwsEcsServiceDeploymentConfigurationDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { AwsEcsServiceDeploymentConfigurationDetails::AwsEcsServiceDeploymentConfigurationDetails() : m_deploymentCircuitBreakerHasBeenSet(false), m_maximumPercent(0), m_maximumPercentHasBeenSet(false), m_minimumHealthyPercent(0), m_minimumHealthyPercentHasBeenSet(false) { } AwsEcsServiceDeploymentConfigurationDetails::AwsEcsServiceDeploymentConfigurationDetails(JsonView jsonValue) : m_deploymentCircuitBreakerHasBeenSet(false), m_maximumPercent(0), m_maximumPercentHasBeenSet(false), m_minimumHealthyPercent(0), m_minimumHealthyPercentHasBeenSet(false) { *this = jsonValue; } AwsEcsServiceDeploymentConfigurationDetails& AwsEcsServiceDeploymentConfigurationDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("DeploymentCircuitBreaker")) { m_deploymentCircuitBreaker = jsonValue.GetObject("DeploymentCircuitBreaker"); m_deploymentCircuitBreakerHasBeenSet = true; } if(jsonValue.ValueExists("MaximumPercent")) { m_maximumPercent = jsonValue.GetInteger("MaximumPercent"); m_maximumPercentHasBeenSet = true; } if(jsonValue.ValueExists("MinimumHealthyPercent")) { m_minimumHealthyPercent = jsonValue.GetInteger("MinimumHealthyPercent"); m_minimumHealthyPercentHasBeenSet = true; } return *this; } JsonValue AwsEcsServiceDeploymentConfigurationDetails::Jsonize() const { JsonValue payload; if(m_deploymentCircuitBreakerHasBeenSet) { payload.WithObject("DeploymentCircuitBreaker", m_deploymentCircuitBreaker.Jsonize()); } if(m_maximumPercentHasBeenSet) { payload.WithInteger("MaximumPercent", m_maximumPercent); } if(m_minimumHealthyPercentHasBeenSet) { payload.WithInteger("MinimumHealthyPercent", m_minimumHealthyPercent); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
apache-2.0
awslabs/aws-sdk-cpp
aws-cpp-sdk-wafv2/source/model/RateBasedStatementManagedKeysIPSet.cpp
3
2189
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/wafv2/model/RateBasedStatementManagedKeysIPSet.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WAFV2 { namespace Model { RateBasedStatementManagedKeysIPSet::RateBasedStatementManagedKeysIPSet() : m_iPAddressVersion(IPAddressVersion::NOT_SET), m_iPAddressVersionHasBeenSet(false), m_addressesHasBeenSet(false) { } RateBasedStatementManagedKeysIPSet::RateBasedStatementManagedKeysIPSet(JsonView jsonValue) : m_iPAddressVersion(IPAddressVersion::NOT_SET), m_iPAddressVersionHasBeenSet(false), m_addressesHasBeenSet(false) { *this = jsonValue; } RateBasedStatementManagedKeysIPSet& RateBasedStatementManagedKeysIPSet::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("IPAddressVersion")) { m_iPAddressVersion = IPAddressVersionMapper::GetIPAddressVersionForName(jsonValue.GetString("IPAddressVersion")); m_iPAddressVersionHasBeenSet = true; } if(jsonValue.ValueExists("Addresses")) { Array<JsonView> addressesJsonList = jsonValue.GetArray("Addresses"); for(unsigned addressesIndex = 0; addressesIndex < addressesJsonList.GetLength(); ++addressesIndex) { m_addresses.push_back(addressesJsonList[addressesIndex].AsString()); } m_addressesHasBeenSet = true; } return *this; } JsonValue RateBasedStatementManagedKeysIPSet::Jsonize() const { JsonValue payload; if(m_iPAddressVersionHasBeenSet) { payload.WithString("IPAddressVersion", IPAddressVersionMapper::GetNameForIPAddressVersion(m_iPAddressVersion)); } if(m_addressesHasBeenSet) { Array<JsonValue> addressesJsonList(m_addresses.size()); for(unsigned addressesIndex = 0; addressesIndex < addressesJsonList.GetLength(); ++addressesIndex) { addressesJsonList[addressesIndex].AsString(m_addresses[addressesIndex]); } payload.WithArray("Addresses", std::move(addressesJsonList)); } return payload; } } // namespace Model } // namespace WAFV2 } // namespace Aws
apache-2.0
pyca/pynacl
docs/vectors/c-source/sealbox_test_vectors.c
4
5841
/* * Copyright 2017 Donald Stufft and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Test vector generator/checker for libsodium's box_seal APIs * to build in a unix-like environment, use a command line like * $ cc sealbox_test_vectors.c -I${IPATH} -L${LPATH} -lsodium -o sealbox_test_vectors * with IPATH and LPATH defined to respectively point to libsodium's include path * and to the directory containing the link library libsodium.a or libsodium.o * */ #include <stdio.h> #include <string.h> #include <sodium.h> int checkone (char *hxsecret, char *hxpub, size_t ptlen, char *hxplaintext, size_t crlen, char *hxencrypted) { int pklen = crypto_box_PUBLICKEYBYTES; int sklen = crypto_box_SECRETKEYBYTES; char *skr = sodium_malloc (sklen); char *pub = sodium_malloc (pklen); char *txt = sodium_malloc (ptlen); char *crpt = sodium_malloc (crlen); char *outp = sodium_malloc (ptlen); int rs = sodium_hex2bin (skr, sklen, hxsecret, 2 * sklen, NULL, NULL, NULL); rs |= sodium_hex2bin (pub, pklen, hxpub, 2 * pklen, NULL, NULL, NULL); rs |= sodium_hex2bin (txt, ptlen, hxplaintext, strlen (hxplaintext), NULL, NULL, NULL); rs |= sodium_hex2bin (crpt, crlen, hxencrypted, strlen (hxencrypted), NULL, NULL, NULL); if (rs == 0) rs = crypto_box_seal_open (outp, crpt, crlen, pub, skr); if (rs == 0) rs = sodium_memcmp (outp, txt, ptlen); sodium_free (crpt); sodium_free (txt); sodium_free (skr); sodium_free (pub); return rs; } void gentestline (int minmsglen, int maxmsglen) { int pklen = crypto_box_PUBLICKEYBYTES; int sklen = crypto_box_SECRETKEYBYTES; size_t txtlen = minmsglen + randombytes_uniform (maxmsglen - minmsglen + 1); size_t encrlen = txtlen + crypto_box_SEALBYTES; char *skr = sodium_malloc (sklen); char *pub = sodium_malloc (pklen); char *txt = sodium_malloc (txtlen); char *crpt = sodium_malloc (encrlen); crypto_box_keypair (pub, skr); randombytes_buf (txt, txtlen); crypto_box_seal (crpt, txt, txtlen, pub); char *hskr = sodium_malloc (sklen * 2 + 1); char *hpub = sodium_malloc (pklen * 2 + 1); char *htxt = sodium_malloc (txtlen * 2 + 1); char *hkrp = sodium_malloc (encrlen * 2 + 1); sodium_bin2hex (hskr, sklen * 2 + 1, skr, sklen); sodium_bin2hex (hpub, pklen * 2 + 1, pub, pklen); sodium_bin2hex (htxt, txtlen * 2 + 1, txt, txtlen); sodium_bin2hex (hkrp, encrlen * 2 + 1, crpt, encrlen); printf ("%s\t%s\t%zu:%s\t%zu:%s\n", hskr, hpub, txtlen, htxt, encrlen, hkrp); } int main (int argc, char **argv) { /* * If called without any argument, the resulting executable will * read and hex decode the secret and public part of the receiver key, * the original plaintext and the ciphertext, and then * check if the message resulting from decrypting ciphertext with * the secret key is equal to the given plaintext * * If called with a sequence of integer arguments, sealbox_test_vectors * will generate the requested number of reference lines, encrypting * random messages. * */ if (sodium_init () == -1) { exit (1); } if (argc == 1) { size_t lsz = 0; char *line = NULL; ssize_t lln = 0; int res; char hxsecret[2 * crypto_box_SECRETKEYBYTES + 1]; char hxpub[2 * crypto_box_PUBLICKEYBYTES + 1]; char hxplaintext[2048 + 1]; char hxencrypted[2048 + 2 * crypto_box_SEALBYTES + 1]; char cmpplaintext[5 + 2048 + 1]; char cmpencrypted[5 + 2048 + 2 * crypto_box_SEALBYTES + 1]; size_t ptlen = 0; size_t crlen = 0; while (lln = getline (&line, &lsz, stdin) > 0) { if (lln > 0) { if (strncmp (line, "#", 1) == 0 || strncmp (line, "\n", 1) == 0 || strncmp (line, "\r", 1) == 0) continue; sscanf (line, "%s%s%s%s", hxsecret, hxpub, cmpplaintext, cmpencrypted); sscanf (cmpplaintext, "%zu:%s", &ptlen, hxplaintext); sscanf (cmpencrypted, "%zu:%s", &crlen, hxencrypted); if (ptlen == 0) memset(hxplaintext, 0, sizeof(hxplaintext)); if (crlen == 0) memset(hxencrypted, 0, sizeof(hxencrypted)); res = checkone (hxsecret, hxpub, ptlen, hxplaintext, crlen, hxencrypted); char *rsstr = (res == 0) ? "OK" : "FAIL"; printf ("%s\t%s\t%zu:%s\t%zu:%s\t%s\n", hxsecret, hxpub, ptlen, hxplaintext, crlen, hxencrypted, rsstr); } free (line); line = NULL; } } else { int nlines = atoi (argv[1]); int minmsgl = 128; int maxmsgl = 128; if (argc == 3) { minmsgl = atoi (argv[2]); maxmsgl = atoi (argv[2]) * 2; } else if (argc == 4) { minmsgl = atoi (argv[2]); maxmsgl = atoi (argv[3]); } for (int i = 0; i < nlines; i++) { gentestline (minmsgl, maxmsgl); } } }
apache-2.0
cedral/aws-sdk-cpp
aws-cpp-sdk-cloudformation/source/model/StackSetOperationResultSummary.cpp
4
5428
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cloudformation/model/StackSetOperationResultSummary.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace CloudFormation { namespace Model { StackSetOperationResultSummary::StackSetOperationResultSummary() : m_accountHasBeenSet(false), m_regionHasBeenSet(false), m_status(StackSetOperationResultStatus::NOT_SET), m_statusHasBeenSet(false), m_statusReasonHasBeenSet(false), m_accountGateResultHasBeenSet(false), m_organizationalUnitIdHasBeenSet(false) { } StackSetOperationResultSummary::StackSetOperationResultSummary(const XmlNode& xmlNode) : m_accountHasBeenSet(false), m_regionHasBeenSet(false), m_status(StackSetOperationResultStatus::NOT_SET), m_statusHasBeenSet(false), m_statusReasonHasBeenSet(false), m_accountGateResultHasBeenSet(false), m_organizationalUnitIdHasBeenSet(false) { *this = xmlNode; } StackSetOperationResultSummary& StackSetOperationResultSummary::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode accountNode = resultNode.FirstChild("Account"); if(!accountNode.IsNull()) { m_account = Aws::Utils::Xml::DecodeEscapedXmlText(accountNode.GetText()); m_accountHasBeenSet = true; } XmlNode regionNode = resultNode.FirstChild("Region"); if(!regionNode.IsNull()) { m_region = Aws::Utils::Xml::DecodeEscapedXmlText(regionNode.GetText()); m_regionHasBeenSet = true; } XmlNode statusNode = resultNode.FirstChild("Status"); if(!statusNode.IsNull()) { m_status = StackSetOperationResultStatusMapper::GetStackSetOperationResultStatusForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(statusNode.GetText()).c_str()).c_str()); m_statusHasBeenSet = true; } XmlNode statusReasonNode = resultNode.FirstChild("StatusReason"); if(!statusReasonNode.IsNull()) { m_statusReason = Aws::Utils::Xml::DecodeEscapedXmlText(statusReasonNode.GetText()); m_statusReasonHasBeenSet = true; } XmlNode accountGateResultNode = resultNode.FirstChild("AccountGateResult"); if(!accountGateResultNode.IsNull()) { m_accountGateResult = accountGateResultNode; m_accountGateResultHasBeenSet = true; } XmlNode organizationalUnitIdNode = resultNode.FirstChild("OrganizationalUnitId"); if(!organizationalUnitIdNode.IsNull()) { m_organizationalUnitId = Aws::Utils::Xml::DecodeEscapedXmlText(organizationalUnitIdNode.GetText()); m_organizationalUnitIdHasBeenSet = true; } } return *this; } void StackSetOperationResultSummary::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_accountHasBeenSet) { oStream << location << index << locationValue << ".Account=" << StringUtils::URLEncode(m_account.c_str()) << "&"; } if(m_regionHasBeenSet) { oStream << location << index << locationValue << ".Region=" << StringUtils::URLEncode(m_region.c_str()) << "&"; } if(m_statusHasBeenSet) { oStream << location << index << locationValue << ".Status=" << StackSetOperationResultStatusMapper::GetNameForStackSetOperationResultStatus(m_status) << "&"; } if(m_statusReasonHasBeenSet) { oStream << location << index << locationValue << ".StatusReason=" << StringUtils::URLEncode(m_statusReason.c_str()) << "&"; } if(m_accountGateResultHasBeenSet) { Aws::StringStream accountGateResultLocationAndMemberSs; accountGateResultLocationAndMemberSs << location << index << locationValue << ".AccountGateResult"; m_accountGateResult.OutputToStream(oStream, accountGateResultLocationAndMemberSs.str().c_str()); } if(m_organizationalUnitIdHasBeenSet) { oStream << location << index << locationValue << ".OrganizationalUnitId=" << StringUtils::URLEncode(m_organizationalUnitId.c_str()) << "&"; } } void StackSetOperationResultSummary::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_accountHasBeenSet) { oStream << location << ".Account=" << StringUtils::URLEncode(m_account.c_str()) << "&"; } if(m_regionHasBeenSet) { oStream << location << ".Region=" << StringUtils::URLEncode(m_region.c_str()) << "&"; } if(m_statusHasBeenSet) { oStream << location << ".Status=" << StackSetOperationResultStatusMapper::GetNameForStackSetOperationResultStatus(m_status) << "&"; } if(m_statusReasonHasBeenSet) { oStream << location << ".StatusReason=" << StringUtils::URLEncode(m_statusReason.c_str()) << "&"; } if(m_accountGateResultHasBeenSet) { Aws::String accountGateResultLocationAndMember(location); accountGateResultLocationAndMember += ".AccountGateResult"; m_accountGateResult.OutputToStream(oStream, accountGateResultLocationAndMember.c_str()); } if(m_organizationalUnitIdHasBeenSet) { oStream << location << ".OrganizationalUnitId=" << StringUtils::URLEncode(m_organizationalUnitId.c_str()) << "&"; } } } // namespace Model } // namespace CloudFormation } // namespace Aws
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-elasticmapreduce/source/model/DeleteStudioSessionMappingRequest.cpp
4
1455
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/elasticmapreduce/model/DeleteStudioSessionMappingRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::EMR::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeleteStudioSessionMappingRequest::DeleteStudioSessionMappingRequest() : m_studioIdHasBeenSet(false), m_identityIdHasBeenSet(false), m_identityNameHasBeenSet(false), m_identityType(IdentityType::NOT_SET), m_identityTypeHasBeenSet(false) { } Aws::String DeleteStudioSessionMappingRequest::SerializePayload() const { JsonValue payload; if(m_studioIdHasBeenSet) { payload.WithString("StudioId", m_studioId); } if(m_identityIdHasBeenSet) { payload.WithString("IdentityId", m_identityId); } if(m_identityNameHasBeenSet) { payload.WithString("IdentityName", m_identityName); } if(m_identityTypeHasBeenSet) { payload.WithString("IdentityType", IdentityTypeMapper::GetNameForIdentityType(m_identityType)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection DeleteStudioSessionMappingRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ElasticMapReduce.DeleteStudioSessionMapping")); return headers; }
apache-2.0
llvm-mirror/lldb
source/API/SBAddress.cpp
4
10874
//===-- SBAddress.cpp -------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/API/SBAddress.h" #include "SBReproducerPrivate.h" #include "Utils.h" #include "lldb/API/SBProcess.h" #include "lldb/API/SBSection.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Address.h" #include "lldb/Core/Module.h" #include "lldb/Symbol/LineEntry.h" #include "lldb/Target/Target.h" #include "lldb/Utility/StreamString.h" using namespace lldb; using namespace lldb_private; SBAddress::SBAddress() : m_opaque_up(new Address()) { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBAddress); } SBAddress::SBAddress(const Address *lldb_object_ptr) : m_opaque_up(new Address()) { if (lldb_object_ptr) m_opaque_up = std::make_unique<Address>(*lldb_object_ptr); } SBAddress::SBAddress(const SBAddress &rhs) : m_opaque_up(new Address()) { LLDB_RECORD_CONSTRUCTOR(SBAddress, (const lldb::SBAddress &), rhs); m_opaque_up = clone(rhs.m_opaque_up); } SBAddress::SBAddress(lldb::SBSection section, lldb::addr_t offset) : m_opaque_up(new Address(section.GetSP(), offset)) { LLDB_RECORD_CONSTRUCTOR(SBAddress, (lldb::SBSection, lldb::addr_t), section, offset); } // Create an address by resolving a load address using the supplied target SBAddress::SBAddress(lldb::addr_t load_addr, lldb::SBTarget &target) : m_opaque_up(new Address()) { LLDB_RECORD_CONSTRUCTOR(SBAddress, (lldb::addr_t, lldb::SBTarget &), load_addr, target); SetLoadAddress(load_addr, target); } SBAddress::~SBAddress() {} const SBAddress &SBAddress::operator=(const SBAddress &rhs) { LLDB_RECORD_METHOD(const lldb::SBAddress &, SBAddress, operator=,(const lldb::SBAddress &), rhs); if (this != &rhs) m_opaque_up = clone(rhs.m_opaque_up); return LLDB_RECORD_RESULT(*this); } bool lldb::operator==(const SBAddress &lhs, const SBAddress &rhs) { if (lhs.IsValid() && rhs.IsValid()) return lhs.ref() == rhs.ref(); return false; } bool SBAddress::operator!=(const SBAddress &rhs) const { LLDB_RECORD_METHOD_CONST(bool, SBAddress, operator!=,(const SBAddress &), &rhs); return !(*this == rhs); } bool SBAddress::IsValid() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBAddress, IsValid); return this->operator bool(); } SBAddress::operator bool() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBAddress, operator bool); return m_opaque_up != nullptr && m_opaque_up->IsValid(); } void SBAddress::Clear() { LLDB_RECORD_METHOD_NO_ARGS(void, SBAddress, Clear); m_opaque_up.reset(new Address()); } void SBAddress::SetAddress(lldb::SBSection section, lldb::addr_t offset) { LLDB_RECORD_METHOD(void, SBAddress, SetAddress, (lldb::SBSection, lldb::addr_t), section, offset); Address &addr = ref(); addr.SetSection(section.GetSP()); addr.SetOffset(offset); } void SBAddress::SetAddress(const Address *lldb_object_ptr) { if (lldb_object_ptr) ref() = *lldb_object_ptr; else m_opaque_up.reset(new Address()); } lldb::addr_t SBAddress::GetFileAddress() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBAddress, GetFileAddress); if (m_opaque_up->IsValid()) return m_opaque_up->GetFileAddress(); else return LLDB_INVALID_ADDRESS; } lldb::addr_t SBAddress::GetLoadAddress(const SBTarget &target) const { LLDB_RECORD_METHOD_CONST(lldb::addr_t, SBAddress, GetLoadAddress, (const lldb::SBTarget &), target); lldb::addr_t addr = LLDB_INVALID_ADDRESS; TargetSP target_sp(target.GetSP()); if (target_sp) { if (m_opaque_up->IsValid()) { std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); addr = m_opaque_up->GetLoadAddress(target_sp.get()); } } return addr; } void SBAddress::SetLoadAddress(lldb::addr_t load_addr, lldb::SBTarget &target) { LLDB_RECORD_METHOD(void, SBAddress, SetLoadAddress, (lldb::addr_t, lldb::SBTarget &), load_addr, target); // Create the address object if we don't already have one ref(); if (target.IsValid()) *this = target.ResolveLoadAddress(load_addr); else m_opaque_up->Clear(); // Check if we weren't were able to resolve a section offset address. If we // weren't it is ok, the load address might be a location on the stack or // heap, so we should just have an address with no section and a valid offset if (!m_opaque_up->IsValid()) m_opaque_up->SetOffset(load_addr); } bool SBAddress::OffsetAddress(addr_t offset) { LLDB_RECORD_METHOD(bool, SBAddress, OffsetAddress, (lldb::addr_t), offset); if (m_opaque_up->IsValid()) { addr_t addr_offset = m_opaque_up->GetOffset(); if (addr_offset != LLDB_INVALID_ADDRESS) { m_opaque_up->SetOffset(addr_offset + offset); return true; } } return false; } lldb::SBSection SBAddress::GetSection() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSection, SBAddress, GetSection); lldb::SBSection sb_section; if (m_opaque_up->IsValid()) sb_section.SetSP(m_opaque_up->GetSection()); return LLDB_RECORD_RESULT(sb_section); } lldb::addr_t SBAddress::GetOffset() { LLDB_RECORD_METHOD_NO_ARGS(lldb::addr_t, SBAddress, GetOffset); if (m_opaque_up->IsValid()) return m_opaque_up->GetOffset(); return 0; } Address *SBAddress::operator->() { return m_opaque_up.get(); } const Address *SBAddress::operator->() const { return m_opaque_up.get(); } Address &SBAddress::ref() { if (m_opaque_up == nullptr) m_opaque_up.reset(new Address()); return *m_opaque_up; } const Address &SBAddress::ref() const { // This object should already have checked with "IsValid()" prior to calling // this function. In case you didn't we will assert and die to let you know. assert(m_opaque_up.get()); return *m_opaque_up; } Address *SBAddress::get() { return m_opaque_up.get(); } bool SBAddress::GetDescription(SBStream &description) { LLDB_RECORD_METHOD(bool, SBAddress, GetDescription, (lldb::SBStream &), description); // Call "ref()" on the stream to make sure it creates a backing stream in // case there isn't one already... Stream &strm = description.ref(); if (m_opaque_up->IsValid()) { m_opaque_up->Dump(&strm, nullptr, Address::DumpStyleResolvedDescription, Address::DumpStyleModuleWithFileAddress, 4); } else strm.PutCString("No value"); return true; } SBModule SBAddress::GetModule() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBModule, SBAddress, GetModule); SBModule sb_module; if (m_opaque_up->IsValid()) sb_module.SetSP(m_opaque_up->GetModule()); return LLDB_RECORD_RESULT(sb_module); } SBSymbolContext SBAddress::GetSymbolContext(uint32_t resolve_scope) { LLDB_RECORD_METHOD(lldb::SBSymbolContext, SBAddress, GetSymbolContext, (uint32_t), resolve_scope); SBSymbolContext sb_sc; SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); if (m_opaque_up->IsValid()) m_opaque_up->CalculateSymbolContext(&sb_sc.ref(), scope); return LLDB_RECORD_RESULT(sb_sc); } SBCompileUnit SBAddress::GetCompileUnit() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBCompileUnit, SBAddress, GetCompileUnit); SBCompileUnit sb_comp_unit; if (m_opaque_up->IsValid()) sb_comp_unit.reset(m_opaque_up->CalculateSymbolContextCompileUnit()); return LLDB_RECORD_RESULT(sb_comp_unit); } SBFunction SBAddress::GetFunction() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBFunction, SBAddress, GetFunction); SBFunction sb_function; if (m_opaque_up->IsValid()) sb_function.reset(m_opaque_up->CalculateSymbolContextFunction()); return LLDB_RECORD_RESULT(sb_function); } SBBlock SBAddress::GetBlock() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBBlock, SBAddress, GetBlock); SBBlock sb_block; if (m_opaque_up->IsValid()) sb_block.SetPtr(m_opaque_up->CalculateSymbolContextBlock()); return LLDB_RECORD_RESULT(sb_block); } SBSymbol SBAddress::GetSymbol() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSymbol, SBAddress, GetSymbol); SBSymbol sb_symbol; if (m_opaque_up->IsValid()) sb_symbol.reset(m_opaque_up->CalculateSymbolContextSymbol()); return LLDB_RECORD_RESULT(sb_symbol); } SBLineEntry SBAddress::GetLineEntry() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBLineEntry, SBAddress, GetLineEntry); SBLineEntry sb_line_entry; if (m_opaque_up->IsValid()) { LineEntry line_entry; if (m_opaque_up->CalculateSymbolContextLineEntry(line_entry)) sb_line_entry.SetLineEntry(line_entry); } return LLDB_RECORD_RESULT(sb_line_entry); } namespace lldb_private { namespace repro { template <> void RegisterMethods<SBAddress>(Registry &R) { LLDB_REGISTER_CONSTRUCTOR(SBAddress, ()); LLDB_REGISTER_CONSTRUCTOR(SBAddress, (const lldb::SBAddress &)); LLDB_REGISTER_CONSTRUCTOR(SBAddress, (lldb::SBSection, lldb::addr_t)); LLDB_REGISTER_CONSTRUCTOR(SBAddress, (lldb::addr_t, lldb::SBTarget &)); LLDB_REGISTER_METHOD(const lldb::SBAddress &, SBAddress, operator=,(const lldb::SBAddress &)); LLDB_REGISTER_METHOD_CONST(bool, SBAddress, operator!=,(const lldb::SBAddress &)); LLDB_REGISTER_METHOD_CONST(bool, SBAddress, IsValid, ()); LLDB_REGISTER_METHOD_CONST(bool, SBAddress, operator bool, ()); LLDB_REGISTER_METHOD(void, SBAddress, Clear, ()); LLDB_REGISTER_METHOD(void, SBAddress, SetAddress, (lldb::SBSection, lldb::addr_t)); LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBAddress, GetFileAddress, ()); LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBAddress, GetLoadAddress, (const lldb::SBTarget &)); LLDB_REGISTER_METHOD(void, SBAddress, SetLoadAddress, (lldb::addr_t, lldb::SBTarget &)); LLDB_REGISTER_METHOD(bool, SBAddress, OffsetAddress, (lldb::addr_t)); LLDB_REGISTER_METHOD(lldb::SBSection, SBAddress, GetSection, ()); LLDB_REGISTER_METHOD(lldb::addr_t, SBAddress, GetOffset, ()); LLDB_REGISTER_METHOD(bool, SBAddress, GetDescription, (lldb::SBStream &)); LLDB_REGISTER_METHOD(lldb::SBModule, SBAddress, GetModule, ()); LLDB_REGISTER_METHOD(lldb::SBSymbolContext, SBAddress, GetSymbolContext, (uint32_t)); LLDB_REGISTER_METHOD(lldb::SBCompileUnit, SBAddress, GetCompileUnit, ()); LLDB_REGISTER_METHOD(lldb::SBFunction, SBAddress, GetFunction, ()); LLDB_REGISTER_METHOD(lldb::SBBlock, SBAddress, GetBlock, ()); LLDB_REGISTER_METHOD(lldb::SBSymbol, SBAddress, GetSymbol, ()); LLDB_REGISTER_METHOD(lldb::SBLineEntry, SBAddress, GetLineEntry, ()); } } }
apache-2.0
wmydz1/tape
c-tape/queuefile.c
5
25144
/* * Copyright (C) 2012 Square, 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. */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fileio.h" #include "logutil.h" #include "queuefile.h" /* * Port of Tape project from Java. https://github.com/square/tape * * Integers are forced to be 32-bit, maximum file size supported is 2^32 (4GB). * * See description in queuefile.h. */ /** frees if oldPointer is not NULL, assigns newPointer. */ #define freeAndAssign(OLD, NEW) _freeAndAssign((void**)(OLD), (void*)(NEW)) static bool _freeAndAssign(void** oldPointer, void* newPointer); /** frees and assigns oldPointer IFF newPointer is not NULL. */ #define freeAndAssignNonNull(OLD, NEW) _freeAndAssignNonNull((void**)(OLD), (void*)(NEW)) static bool _freeAndAssignNonNull(void** oldPointer, void* newPointer); // Use macro to maintain line number #define NULLARG(P) ((P) == NULL ? LOG(LWARN, "Null argument passed") || 1 : 0) #define CHECKOOM(P) ((P) == NULL ? LOG(LWARN, "Out of memory") || 1 : 0) // For sanity tests #define MAX_FILENAME_LEN 4096 // ------------------------------ Element ----------------------------------- #define Element_HEADER_LENGTH 4 /** A pointer to an element. */ typedef struct { /** Position in file. */ uint32_t position; /** The length of the data. */ uint32_t length; } Element; /** * Constructs a new element. * * @param position within file * @param length of data */ static Element* Element_new(uint32_t position, uint32_t length) { Element* e = malloc(sizeof(Element)); if (CHECKOOM(e)) return NULL; e->position = position; e->length = length; return e; } static void Element_fprintf(Element* e, FILE* fout) { fprintf(fout, "Element:[position = %d, length = %d]", e->position, e->length); } // ------------------------------ QueueFile ----------------------------------- /** Initial file size in bytes. */ #define QueueFile_INITIAL_LENGTH 4096 // one file system block /** Length of header in bytes. */ #define QueueFile_HEADER_LENGTH 16 // May not be shorter than 16 bytes. struct _QueueFile { /** * The underlying file. Uses a ring buffer to store entries. Designed so that * a modification isn't committed or visible until we write the header. The * header is much smaller than a segment. So long as the underlying file * system supports atomic segment writes, changes to the queue are atomic. * Storing the file length ensures we can recover from a failed expansion * (i.e. if setting the file length succeeds but the process dies before the * data can be copied). * * Format: * Header (16 bytes) * Element Ring Buffer (File Length - 16 bytes) * * Header: * File Length (4 bytes) * Element Count (4 bytes) * First Element Position (4 bytes, =0 if null) * Last Element Position (4 bytes, =0 if null) * * Element: * Length (4 bytes) * Data (Length bytes) */ FILE* file; /** Cached file length. Always a power of 2. */ uint32_t fileLength; /** Number of elements. */ uint32_t elementCount; /** Pointer to first (or eldest) element. */ Element* first; /** Pointer to last (or newest) element. */ Element* last; /** In-memory buffer. Big enough to hold the header. */ byte buffer[QueueFile_HEADER_LENGTH]; /** mutex to synchronize method access */ pthread_mutex_t mutex; }; static bool initialize(char* filename); static bool QueueFile_readHeader(QueueFile* qf); // see description in queuefile.h. QueueFile* QueueFile_new(char* filename) { if (NULLARG(filename)) return NULL; QueueFile* qf = malloc(sizeof(QueueFile)); if (CHECKOOM(qf)) return NULL; memset(qf, 0, sizeof(QueueFile)); // making sure pointers & counters are null! qf->file = fopen(filename, "r+"); if (qf->file == NULL) { if (initialize(filename)) { qf->file = fopen(filename, "r+"); } if (qf->file == NULL) { free(qf); return NULL; } } if (!QueueFile_readHeader(qf)) { fclose(qf->file); free(qf); return NULL; } // TODO(jochen): consider NP mutex options, audit code for re-entrancy and // eliminate recursive option if needed. // NOTE: there was a problem with static initializers on OSX // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51906 pthread_mutexattr_t mta; pthread_mutexattr_init(&mta); pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qf->mutex, &mta); return qf; } // see description in queuefile.h. bool QueueFile_closeAndFree(QueueFile* qf) { pthread_mutex_lock(&qf->mutex); bool success = !fclose(qf->file); if (success) { if (qf != NULL) { if (qf->first != NULL) { free(qf->first); } if (qf->last != NULL && qf->last != qf->first) free(qf->last); qf->first = qf->last = NULL; } } pthread_mutex_unlock(&qf->mutex); if (success) free(qf); return success; } /** * Stores unsigned int in buffer (big endian). */ static void writeInt(byte* buffer, uint32_t offset, uint32_t value) { buffer[offset] = (byte) (value >> 24); buffer[offset + 1] = (byte) (value >> 16); buffer[offset + 2] = (byte) (value >> 8); buffer[offset + 3] = (byte) value; } /** * Stores unsigned ints into a buffer, in the order of parameters passed. */ static void writeInts(byte* buffer, uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4) { writeInt(buffer, 0, v1); writeInt(buffer, 4, v2); writeInt(buffer, 8, v3); writeInt(buffer, 12, v4); } /** Reads an unsigned int from a buffer (assumes big endian). */ static uint32_t readInt(byte* buffer, uint32_t offset) { return ((buffer[offset] & 0xff) << 24) + ((buffer[offset + 1] & 0xff) << 16) + ((buffer[offset + 2] & 0xff) << 8) + (buffer[offset + 3] & 0xff); } static Element* QueueFile_readElement(QueueFile* qf, uint32_t position); /** Reads the header. */ static bool QueueFile_readHeader(QueueFile* qf) { if (!FileIo_seek(qf->file, 0) || !FileIo_read(qf->file, qf->buffer, 0, (uint32_t) sizeof(qf->buffer))) { return false; } qf->fileLength = readInt(qf->buffer, 0); uint32_t actualLength = (uint32_t) FileIo_getLength(qf->file); if (qf->fileLength > actualLength) { LOG(LWARN, "File is truncated. Expected length: %d, Actual length: %d", qf->fileLength, actualLength); return false; } qf->elementCount = readInt(qf->buffer, 4); uint32_t firstOffset = readInt(qf->buffer, 8); uint32_t lastOffset = readInt(qf->buffer, 12); return freeAndAssign(&qf->first, QueueFile_readElement(qf, firstOffset)) && freeAndAssign(&qf->last, QueueFile_readElement(qf, lastOffset)); } /** * Writes header atomically. The arguments contain the updated values. The * class member fields should not have changed yet. This only updates the * state in the file. It's up to the caller to update the class member * variables *after* this call succeeds. Assumes segment writes are atomic in * the underlying file system. */ static bool QueueFile_writeHeader(QueueFile* qf, uint32_t fileLength, uint32_t elementCount, uint32_t firstPosition, uint32_t lastPosition) { writeInts(qf->buffer, fileLength, elementCount, firstPosition, lastPosition); return FileIo_seek(qf->file, 0) && FileIo_write(qf->file, qf->buffer, 0, QueueFile_HEADER_LENGTH); } /** * Returns the Element for the given offset. CALLER MUST FREE MEMORY. */ static Element* QueueFile_readElement(QueueFile* qf, uint32_t position) { if (position == 0 || !FileIo_seek(qf->file, position) || !FileIo_read(qf->file, qf->buffer, 0, (uint32_t) sizeof(uint32_t))) { return NULL; } uint32_t length = readInt(qf->buffer, 0); return Element_new(position, length); } char* makeTempFilename(const char* name, int maxLen); /** Atomically initializes a new file. */ static bool initialize(char* filename) { if (QueueFile_HEADER_LENGTH < 16) { LOG(LFATAL, "Configuration error, header length must be >= 16 bytes"); return false; } char* tempname = makeTempFilename(filename, MAX_FILENAME_LEN); if (tempname == NULL) { LOG(LWARN, "Filename too long or out of memory: %s", filename); return false; } FILE* tempfile = fopen(tempname, "w+"); if (tempfile == NULL) { free(tempname); return false; } bool success = false; // TODO(jochen): if truncate in setLength does not work for target platform, consider // appending 0s using FileIo_writeZeros. if (FileIo_setLength(tempfile, QueueFile_INITIAL_LENGTH)) { byte headerBuffer[QueueFile_HEADER_LENGTH]; writeInts(headerBuffer, QueueFile_INITIAL_LENGTH, 0, 0, 0); success = FileIo_write(tempfile, headerBuffer, 0, QueueFile_HEADER_LENGTH); } fclose(tempfile); success = success && rename(tempname, filename) == 0; if (!success) { LOG(LFATAL, "Error initializing temporary file %s", tempname); remove(tempname); } free(tempname); return success; } /** Wraps the position if it exceeds the end of the file. */ static uint32_t QueueFile_wrapPosition(const QueueFile* qf, uint32_t position) { return position < qf->fileLength ? position : QueueFile_HEADER_LENGTH + position - qf->fileLength; } /** * Writes count bytes from buffer to position in file. Automatically wraps * write if position is past the end of the file or if buffer overlaps it. * * @param position in file to write to * @param buffer to write from * @param count # of bytes to write */ static bool QueueFile_ringWrite(QueueFile* qf, uint32_t position, const byte* buffer, uint32_t offset, uint32_t count) { bool success = false; position = QueueFile_wrapPosition(qf, position); if (position + count <= qf->fileLength) { success = FileIo_seek(qf->file, position) && FileIo_write(qf->file, buffer, offset, count); } else { // The write overlaps the EOF. // # of bytes to write before the EOF. uint32_t beforeEof = qf->fileLength - position; success = FileIo_seek(qf->file, position) && FileIo_write(qf->file, buffer, offset, beforeEof) && FileIo_seek(qf->file, QueueFile_HEADER_LENGTH) && FileIo_write(qf->file, buffer, offset + beforeEof, count - beforeEof); } return success; } /** * Reads count bytes into buffer from file. Wraps if necessary. * * @param position in file to read from * @param buffer to read into * @param count # of bytes to read */ static bool QueueFile_ringRead(QueueFile* qf, uint32_t position, byte* buffer, uint32_t offset, uint32_t count) { bool success = false; position = QueueFile_wrapPosition(qf, position); if (position + count <= qf->fileLength) { success = FileIo_seek(qf->file, position) && FileIo_read(qf->file, buffer, 0, count); } else { // The read overlaps the EOF. // # of bytes to read before the EOF. uint32_t beforeEof = qf->fileLength - position; success = FileIo_seek(qf->file, position) && FileIo_read(qf->file, buffer, offset, beforeEof) && FileIo_seek(qf->file, QueueFile_HEADER_LENGTH) && FileIo_read(qf->file, buffer, offset + beforeEof, count - beforeEof); } return success; } // see description in queuefile.h. bool QueueFile_isEmpty(QueueFile* qf) { if (NULLARG(qf)) return true; pthread_mutex_lock(&qf->mutex); uint32_t elementCount = qf->elementCount == 0; pthread_mutex_unlock(&qf->mutex); return elementCount; } static bool QueueFile_expandIfNecessary(QueueFile* qf, uint32_t dataLength); // see description in queuefile.h. bool QueueFile_add(QueueFile* qf, const byte* data, uint32_t offset, uint32_t count) { if (NULLARG(qf) || NULLARG(data)) return false; bool success = false; pthread_mutex_lock(&qf->mutex); if (QueueFile_expandIfNecessary(qf, count)) { // Insert a new element after the current last element. bool wasEmpty = QueueFile_isEmpty(qf); uint32_t position = wasEmpty ? QueueFile_HEADER_LENGTH : QueueFile_wrapPosition(qf, qf->last->position + Element_HEADER_LENGTH + qf->last->length); Element* newLast = Element_new(position, count); // Write length & data. writeInt(qf->buffer, 0, count); if (newLast != NULL) { if (QueueFile_ringWrite(qf, newLast->position, qf->buffer, 0, Element_HEADER_LENGTH) && QueueFile_ringWrite(qf, newLast->position + Element_HEADER_LENGTH, data, offset, count)) { // Commit the addition. If wasEmpty, first == last. uint32_t firstPosition = wasEmpty ? newLast->position : qf->first->position; success = QueueFile_writeHeader(qf, qf->fileLength, qf->elementCount + 1, firstPosition, newLast->position); } if (success) { if (freeAndAssignNonNull(&qf->last, newLast)) { if (wasEmpty) freeAndAssignNonNull(&qf->first, Element_new(qf->last->position, qf->last->length)); success = true; qf->elementCount++; } } else { free(newLast); } } } pthread_mutex_unlock(&qf->mutex); return success; } /** Returns the number of used bytes. */ static uint32_t QueueFile_usedBytes(QueueFile* qf) { if (qf->elementCount == 0) return QueueFile_HEADER_LENGTH; if (qf->last->position >= qf->first->position) { // Contiguous queue. return (qf->last->position - qf->first->position) // all but last entry + Element_HEADER_LENGTH + qf->last->length // last entry + QueueFile_HEADER_LENGTH; } else { // tail < head. The queue wraps. return qf->last->position // buffer front + header + Element_HEADER_LENGTH + qf->last->length // last entry + qf->fileLength - qf->first->position; // buffer end } } /** Returns number of unused bytes. */ static uint32_t QueueFile_remainingBytes(QueueFile* qf) { return qf->fileLength - QueueFile_usedBytes(qf); } /** * If necessary, expands the file to accommodate an additional element of the * given length. * * @param dataLength length of data being added * @returns false only if an error was encountered. */ static bool QueueFile_expandIfNecessary(QueueFile* qf, uint32_t dataLength) { uint32_t elementLength = Element_HEADER_LENGTH + dataLength; uint32_t remainingBytes = QueueFile_remainingBytes(qf); if (remainingBytes >= elementLength) { return true; } // Expand. uint32_t previousLength = qf->fileLength; uint32_t newLength; // Double the length until we can fit the new data. do { remainingBytes += previousLength; newLength = previousLength << 1; previousLength = newLength; } while (remainingBytes < elementLength); // TODO(jochen): if truncate in setLength does not work for target platform, // consider appending 0s using FileIo_writeZeros. if (!FileIo_setLength(qf->file, newLength)) { return false; } // Calculate the position of the tail end of the data in the ring buffer uint32_t endOfLastElement = QueueFile_wrapPosition(qf, qf->last->position + Element_HEADER_LENGTH + qf->last->length); // If the buffer is split, we need to make it contiguous, so append the // tail of the queue to after the end of the old file. if (endOfLastElement < qf->first->position) { uint32_t count = endOfLastElement - Element_HEADER_LENGTH; if (!FileIo_transferTo(qf->file, QueueFile_HEADER_LENGTH, qf->fileLength, count)) { return false; } } // Commit the expansion. if (qf->last->position < qf->first->position) { uint32_t newLastPosition = qf->fileLength + qf->last->position - QueueFile_HEADER_LENGTH; if (!QueueFile_writeHeader(qf, newLength, qf->elementCount, qf->first->position, newLastPosition)) { return false; } if (!freeAndAssignNonNull(&qf->last, Element_new(newLastPosition, qf->last->length))) { return false; } } else { if (!QueueFile_writeHeader(qf, newLength, qf->elementCount, qf->first->position, qf->last->position)) { return false; } } qf->fileLength = newLength; return true; } // see description in queuefile.h. byte* QueueFile_peek(QueueFile* qf, uint32_t* returnedLength) { if (NULLARG(qf) || NULLARG(returnedLength) || QueueFile_isEmpty(qf)) return NULL; pthread_mutex_lock(&qf->mutex); *returnedLength = 0; uint32_t length = qf->first->length; byte* data = malloc((size_t) length); if (CHECKOOM(data)) return NULL; if (!QueueFile_ringRead(qf, qf->first->position + Element_HEADER_LENGTH, data, 0, length)) { free(data); data = NULL; } *returnedLength = length; pthread_mutex_unlock(&qf->mutex); return data; } struct _QueueFile_ElementStream { QueueFile* qf; uint32_t position; uint32_t remaining; }; // see description in queuefile.h. bool QueueFile_readElementStream(QueueFile_ElementStream* stream, byte* buffer, uint32_t length, uint32_t* lengthRemaining) { if (NULLARG(stream) || NULLARG(buffer) || NULLARG(lengthRemaining) || NULLARG(stream->qf)) return false; *lengthRemaining = 0; if (stream->remaining == 0) { return true; } if (length > stream->remaining) length = stream->remaining; if (QueueFile_ringRead(stream->qf, stream->position, buffer, 0, length)) { stream->position = QueueFile_wrapPosition(stream->qf, stream->position + length); stream->remaining -= length; *lengthRemaining = stream->remaining; } else { return false; } return true; } // see description in queuefile.h. int QueueFile_readElementStreamNextByte(QueueFile_ElementStream* stream) { byte buffer; uint32_t remaining; if (stream->remaining == 0) { return -1; } if (!QueueFile_readElementStream(stream, &buffer, (uint32_t) sizeof(byte), &remaining)) { return -1; } return (int)buffer; } // see description in queuefile.h. bool QueueFile_peekWithElementReader(QueueFile* qf, QueueFile_ElementReaderFunc reader) { if (NULLARG(reader) || NULLARG(qf)) return false; pthread_mutex_lock(&qf->mutex); bool success = false; if (qf->elementCount == 0) { success = true; } else { if (qf->first == NULL) { LOG(LFATAL, "Internal error: queue should have a first element."); } else { Element* current = QueueFile_readElement(qf, qf->first->position); if (current != NULL) { QueueFile_ElementStream stream; stream.qf = qf; stream.position = QueueFile_wrapPosition(qf, current->position + Element_HEADER_LENGTH); stream.remaining = current->length; free(current); (*reader)(&stream, stream.remaining); success = true; } } } pthread_mutex_unlock(&qf->mutex); return success; } // see description in queuefile.h. bool QueueFile_forEach(QueueFile* qf, QueueFile_ElementReaderFunc reader) { if (NULLARG(reader) || NULLARG(qf)) return false; pthread_mutex_lock(&qf->mutex); bool success = false; if (qf->elementCount == 0) { success = true; } else { if (qf->first == NULL) { LOG(LFATAL, "Internal error: queue should have a first element."); } else { uint32_t nextReadPosition = qf->first->position; uint32_t i; bool stopRequested = false; success = true; for (i = 0; i < qf->elementCount && !stopRequested && success; i++) { Element* current = QueueFile_readElement(qf, nextReadPosition); if (current != NULL) { QueueFile_ElementStream stream; stream.qf = qf; stream.position = QueueFile_wrapPosition(qf, current->position + Element_HEADER_LENGTH); stream.remaining = current->length; stopRequested = !(*reader)(&stream, stream.remaining); nextReadPosition = QueueFile_wrapPosition(qf, current->position + Element_HEADER_LENGTH + current->length); free(current); } else { success = false; } } } } pthread_mutex_unlock(&qf->mutex); return success; } // see description in queuefile.h. uint32_t QueueFile_size(QueueFile* qf) { if (NULLARG(qf)) return 0; pthread_mutex_lock(&qf->mutex); uint32_t elementCount = qf->elementCount; pthread_mutex_unlock(&qf->mutex); return elementCount; } // see description in queuefile.h. bool QueueFile_remove(QueueFile* qf) { if (NULLARG(qf)) return false; pthread_mutex_lock(&qf->mutex); bool success = false; if (!QueueFile_isEmpty(qf)) { if (qf->elementCount == 1) { success = QueueFile_clear(qf); } else { // assert elementCount > 1 uint32_t newFirstPosition = QueueFile_wrapPosition(qf, qf->first->position + Element_HEADER_LENGTH + qf->first->length); if (QueueFile_ringRead(qf, newFirstPosition, qf->buffer, 0, Element_HEADER_LENGTH)) { int length = readInt(qf->buffer, 0); if (QueueFile_writeHeader(qf, qf->fileLength, qf->elementCount - 1, newFirstPosition, qf->last->position)) { if (freeAndAssignNonNull(&qf->first, Element_new(newFirstPosition, (uint32_t) length))) { --qf->elementCount; success = true; } } } } } pthread_mutex_unlock(&qf->mutex); return success; } // see description in queuefile.h. bool QueueFile_clear(QueueFile* qf) { if (NULLARG(qf)) return false; bool success = false; pthread_mutex_lock(&qf->mutex); if (QueueFile_writeHeader(qf, QueueFile_INITIAL_LENGTH, 0, 0, 0)) { qf->elementCount = 0; if (qf->first != NULL) { free(qf->first); } qf->first = NULL; if (qf->last != NULL) { free(qf->last); } qf->last = NULL; if (qf->fileLength > QueueFile_INITIAL_LENGTH) { if (FileIo_setLength(qf->file, QueueFile_INITIAL_LENGTH)) { qf->fileLength = QueueFile_INITIAL_LENGTH; success = true; } } else { success = true; } } pthread_mutex_unlock(&qf->mutex); return success; } // TODO(jochen): bool QueueFile_fprintf(QueueFile *qf); FILE* _for_testing_QueueFile_getFhandle(QueueFile *qf) { return qf->file; } // ---------------------------- Utility Functions ------------------------------ /** * Make a temporary filename (appends ".tmp") at most maxLen chars long. * Caller must free result. */ char* makeTempFilename(const char* filename, int maxLen) { // Use a temp file so we don't leave a partially-initialized file. if (filename == NULL || maxLen < 4) { return NULL; } size_t len = strnlen(filename, (size_t) maxLen - 5) + 5; char* tempname = malloc(len); if (CHECKOOM(tempname)) { return NULL; } strncpy(tempname, filename, len); tempname[len-1] = '\0'; // make sure it's terminated if filename was too long. strcat(tempname, ".tmp"); return tempname; } static bool _freeAndAssignNonNull(void** oldPointer, void* newPointer) { if (newPointer != NULL) { if (*oldPointer != NULL) { free(*oldPointer); } *oldPointer = newPointer; return true; } return false; } static bool _freeAndAssign(void** oldPointer, void* newPointer) { if (*oldPointer != NULL) { free(*oldPointer); } *oldPointer = newPointer; return true; }
apache-2.0
WhiteBearSolutions/WBSAirback
packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/arch/arm/mach-omap2/powerdomain.c
261
28329
/* * OMAP powerdomain control * * Copyright (C) 2007-2008, 2011 Texas Instruments, Inc. * Copyright (C) 2007-2011 Nokia Corporation * * Written by Paul Walmsley * Added OMAP4 specific support by Abhijit Pagare <abhijitpagare@ti.com> * State counting code by Tero Kristo <tero.kristo@nokia.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #undef DEBUG #include <linux/kernel.h> #include <linux/types.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/string.h> #include <trace/events/power.h> #include "cm2xxx_3xxx.h" #include "prcm44xx.h" #include "cm44xx.h" #include "prm2xxx_3xxx.h" #include "prm44xx.h" #include <asm/cpu.h> #include <plat/cpu.h> #include "powerdomain.h" #include "clockdomain.h" #include <plat/prcm.h> #include "pm.h" #define PWRDM_TRACE_STATES_FLAG (1<<31) enum { PWRDM_STATE_NOW = 0, PWRDM_STATE_PREV, }; /* pwrdm_list contains all registered struct powerdomains */ static LIST_HEAD(pwrdm_list); static struct pwrdm_ops *arch_pwrdm; /* Private functions */ static struct powerdomain *_pwrdm_lookup(const char *name) { struct powerdomain *pwrdm, *temp_pwrdm; pwrdm = NULL; list_for_each_entry(temp_pwrdm, &pwrdm_list, node) { if (!strcmp(name, temp_pwrdm->name)) { pwrdm = temp_pwrdm; break; } } return pwrdm; } /** * _pwrdm_register - register a powerdomain * @pwrdm: struct powerdomain * to register * * Adds a powerdomain to the internal powerdomain list. Returns * -EINVAL if given a null pointer, -EEXIST if a powerdomain is * already registered by the provided name, or 0 upon success. */ static int _pwrdm_register(struct powerdomain *pwrdm) { int i; struct voltagedomain *voltdm; if (!pwrdm || !pwrdm->name) return -EINVAL; if (cpu_is_omap44xx() && pwrdm->prcm_partition == OMAP4430_INVALID_PRCM_PARTITION) { pr_err("powerdomain: %s: missing OMAP4 PRCM partition ID\n", pwrdm->name); return -EINVAL; } if (_pwrdm_lookup(pwrdm->name)) return -EEXIST; voltdm = voltdm_lookup(pwrdm->voltdm.name); if (!voltdm) { pr_err("powerdomain: %s: voltagedomain %s does not exist\n", pwrdm->name, pwrdm->voltdm.name); return -EINVAL; } pwrdm->voltdm.ptr = voltdm; INIT_LIST_HEAD(&pwrdm->voltdm_node); voltdm_add_pwrdm(voltdm, pwrdm); list_add(&pwrdm->node, &pwrdm_list); /* Initialize the powerdomain's state counter */ for (i = 0; i < PWRDM_MAX_PWRSTS; i++) pwrdm->state_counter[i] = 0; pwrdm->ret_logic_off_counter = 0; for (i = 0; i < pwrdm->banks; i++) pwrdm->ret_mem_off_counter[i] = 0; pwrdm_wait_transition(pwrdm); pwrdm->state = pwrdm_read_pwrst(pwrdm); pwrdm->state_counter[pwrdm->state] = 1; pr_debug("powerdomain: registered %s\n", pwrdm->name); return 0; } static void _update_logic_membank_counters(struct powerdomain *pwrdm) { int i; u8 prev_logic_pwrst, prev_mem_pwrst; prev_logic_pwrst = pwrdm_read_prev_logic_pwrst(pwrdm); if ((pwrdm->pwrsts_logic_ret == PWRSTS_OFF_RET) && (prev_logic_pwrst == PWRDM_POWER_OFF)) pwrdm->ret_logic_off_counter++; for (i = 0; i < pwrdm->banks; i++) { prev_mem_pwrst = pwrdm_read_prev_mem_pwrst(pwrdm, i); if ((pwrdm->pwrsts_mem_ret[i] == PWRSTS_OFF_RET) && (prev_mem_pwrst == PWRDM_POWER_OFF)) pwrdm->ret_mem_off_counter[i]++; } } static int _pwrdm_state_switch(struct powerdomain *pwrdm, int flag) { int prev, state, trace_state = 0; if (pwrdm == NULL) return -EINVAL; state = pwrdm_read_pwrst(pwrdm); switch (flag) { case PWRDM_STATE_NOW: prev = pwrdm->state; break; case PWRDM_STATE_PREV: prev = pwrdm_read_prev_pwrst(pwrdm); if (pwrdm->state != prev) pwrdm->state_counter[prev]++; if (prev == PWRDM_POWER_RET) _update_logic_membank_counters(pwrdm); /* * If the power domain did not hit the desired state, * generate a trace event with both the desired and hit states */ if (state != prev) { trace_state = (PWRDM_TRACE_STATES_FLAG | ((state & OMAP_POWERSTATE_MASK) << 8) | ((prev & OMAP_POWERSTATE_MASK) << 0)); trace_power_domain_target(pwrdm->name, trace_state, smp_processor_id()); } break; default: return -EINVAL; } if (state != prev) pwrdm->state_counter[state]++; pm_dbg_update_time(pwrdm, prev); pwrdm->state = state; return 0; } static int _pwrdm_pre_transition_cb(struct powerdomain *pwrdm, void *unused) { pwrdm_clear_all_prev_pwrst(pwrdm); _pwrdm_state_switch(pwrdm, PWRDM_STATE_NOW); return 0; } static int _pwrdm_post_transition_cb(struct powerdomain *pwrdm, void *unused) { _pwrdm_state_switch(pwrdm, PWRDM_STATE_PREV); return 0; } /* Public functions */ /** * pwrdm_register_platform_funcs - register powerdomain implementation fns * @po: func pointers for arch specific implementations * * Register the list of function pointers used to implement the * powerdomain functions on different OMAP SoCs. Should be called * before any other pwrdm_register*() function. Returns -EINVAL if * @po is null, -EEXIST if platform functions have already been * registered, or 0 upon success. */ int pwrdm_register_platform_funcs(struct pwrdm_ops *po) { if (!po) return -EINVAL; if (arch_pwrdm) return -EEXIST; arch_pwrdm = po; return 0; } /** * pwrdm_register_pwrdms - register SoC powerdomains * @ps: pointer to an array of struct powerdomain to register * * Register the powerdomains available on a particular OMAP SoC. Must * be called after pwrdm_register_platform_funcs(). May be called * multiple times. Returns -EACCES if called before * pwrdm_register_platform_funcs(); -EINVAL if the argument @ps is * null; or 0 upon success. */ int pwrdm_register_pwrdms(struct powerdomain **ps) { struct powerdomain **p = NULL; if (!arch_pwrdm) return -EEXIST; if (!ps) return -EINVAL; for (p = ps; *p; p++) _pwrdm_register(*p); return 0; } /** * pwrdm_complete_init - set up the powerdomain layer * * Do whatever is necessary to initialize registered powerdomains and * powerdomain code. Currently, this programs the next power state * for each powerdomain to ON. This prevents powerdomains from * unexpectedly losing context or entering high wakeup latency modes * with non-power-management-enabled kernels. Must be called after * pwrdm_register_pwrdms(). Returns -EACCES if called before * pwrdm_register_pwrdms(), or 0 upon success. */ int pwrdm_complete_init(void) { struct powerdomain *temp_p; if (list_empty(&pwrdm_list)) return -EACCES; list_for_each_entry(temp_p, &pwrdm_list, node) pwrdm_set_next_pwrst(temp_p, PWRDM_POWER_ON); return 0; } /** * pwrdm_lookup - look up a powerdomain by name, return a pointer * @name: name of powerdomain * * Find a registered powerdomain by its name @name. Returns a pointer * to the struct powerdomain if found, or NULL otherwise. */ struct powerdomain *pwrdm_lookup(const char *name) { struct powerdomain *pwrdm; if (!name) return NULL; pwrdm = _pwrdm_lookup(name); return pwrdm; } /** * pwrdm_for_each - call function on each registered clockdomain * @fn: callback function * * * Call the supplied function @fn for each registered powerdomain. * The callback function @fn can return anything but 0 to bail out * early from the iterator. Returns the last return value of the * callback function, which should be 0 for success or anything else * to indicate failure; or -EINVAL if the function pointer is null. */ int pwrdm_for_each(int (*fn)(struct powerdomain *pwrdm, void *user), void *user) { struct powerdomain *temp_pwrdm; int ret = 0; if (!fn) return -EINVAL; list_for_each_entry(temp_pwrdm, &pwrdm_list, node) { ret = (*fn)(temp_pwrdm, user); if (ret) break; } return ret; } /** * pwrdm_add_clkdm - add a clockdomain to a powerdomain * @pwrdm: struct powerdomain * to add the clockdomain to * @clkdm: struct clockdomain * to associate with a powerdomain * * Associate the clockdomain @clkdm with a powerdomain @pwrdm. This * enables the use of pwrdm_for_each_clkdm(). Returns -EINVAL if * presented with invalid pointers; -ENOMEM if memory could not be allocated; * or 0 upon success. */ int pwrdm_add_clkdm(struct powerdomain *pwrdm, struct clockdomain *clkdm) { int i; int ret = -EINVAL; if (!pwrdm || !clkdm) return -EINVAL; pr_debug("powerdomain: associating clockdomain %s with powerdomain " "%s\n", clkdm->name, pwrdm->name); for (i = 0; i < PWRDM_MAX_CLKDMS; i++) { if (!pwrdm->pwrdm_clkdms[i]) break; #ifdef DEBUG if (pwrdm->pwrdm_clkdms[i] == clkdm) { ret = -EINVAL; goto pac_exit; } #endif } if (i == PWRDM_MAX_CLKDMS) { pr_debug("powerdomain: increase PWRDM_MAX_CLKDMS for " "pwrdm %s clkdm %s\n", pwrdm->name, clkdm->name); WARN_ON(1); ret = -ENOMEM; goto pac_exit; } pwrdm->pwrdm_clkdms[i] = clkdm; ret = 0; pac_exit: return ret; } /** * pwrdm_del_clkdm - remove a clockdomain from a powerdomain * @pwrdm: struct powerdomain * to add the clockdomain to * @clkdm: struct clockdomain * to associate with a powerdomain * * Dissociate the clockdomain @clkdm from the powerdomain * @pwrdm. Returns -EINVAL if presented with invalid pointers; -ENOENT * if @clkdm was not associated with the powerdomain, or 0 upon * success. */ int pwrdm_del_clkdm(struct powerdomain *pwrdm, struct clockdomain *clkdm) { int ret = -EINVAL; int i; if (!pwrdm || !clkdm) return -EINVAL; pr_debug("powerdomain: dissociating clockdomain %s from powerdomain " "%s\n", clkdm->name, pwrdm->name); for (i = 0; i < PWRDM_MAX_CLKDMS; i++) if (pwrdm->pwrdm_clkdms[i] == clkdm) break; if (i == PWRDM_MAX_CLKDMS) { pr_debug("powerdomain: clkdm %s not associated with pwrdm " "%s ?!\n", clkdm->name, pwrdm->name); ret = -ENOENT; goto pdc_exit; } pwrdm->pwrdm_clkdms[i] = NULL; ret = 0; pdc_exit: return ret; } /** * pwrdm_for_each_clkdm - call function on each clkdm in a pwrdm * @pwrdm: struct powerdomain * to iterate over * @fn: callback function * * * Call the supplied function @fn for each clockdomain in the powerdomain * @pwrdm. The callback function can return anything but 0 to bail * out early from the iterator. Returns -EINVAL if presented with * invalid pointers; or passes along the last return value of the * callback function, which should be 0 for success or anything else * to indicate failure. */ int pwrdm_for_each_clkdm(struct powerdomain *pwrdm, int (*fn)(struct powerdomain *pwrdm, struct clockdomain *clkdm)) { int ret = 0; int i; if (!fn) return -EINVAL; for (i = 0; i < PWRDM_MAX_CLKDMS && !ret; i++) ret = (*fn)(pwrdm, pwrdm->pwrdm_clkdms[i]); return ret; } /** * pwrdm_get_voltdm - return a ptr to the voltdm that this pwrdm resides in * @pwrdm: struct powerdomain * * * Return a pointer to the struct voltageomain that the specified powerdomain * @pwrdm exists in. */ struct voltagedomain *pwrdm_get_voltdm(struct powerdomain *pwrdm) { return pwrdm->voltdm.ptr; } /** * pwrdm_get_mem_bank_count - get number of memory banks in this powerdomain * @pwrdm: struct powerdomain * * * Return the number of controllable memory banks in powerdomain @pwrdm, * starting with 1. Returns -EINVAL if the powerdomain pointer is null. */ int pwrdm_get_mem_bank_count(struct powerdomain *pwrdm) { if (!pwrdm) return -EINVAL; return pwrdm->banks; } /** * pwrdm_set_next_pwrst - set next powerdomain power state * @pwrdm: struct powerdomain * to set * @pwrst: one of the PWRDM_POWER_* macros * * Set the powerdomain @pwrdm's next power state to @pwrst. The powerdomain * may not enter this state immediately if the preconditions for this state * have not been satisfied. Returns -EINVAL if the powerdomain pointer is * null or if the power state is invalid for the powerdomin, or returns 0 * upon success. */ int pwrdm_set_next_pwrst(struct powerdomain *pwrdm, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (!(pwrdm->pwrsts & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: setting next powerstate for %s to %0x\n", pwrdm->name, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_next_pwrst) { /* Trace the pwrdm desired target state */ trace_power_domain_target(pwrdm->name, pwrst, smp_processor_id()); /* Program the pwrdm desired target state */ ret = arch_pwrdm->pwrdm_set_next_pwrst(pwrdm, pwrst); } return ret; } /** * pwrdm_read_next_pwrst - get next powerdomain power state * @pwrdm: struct powerdomain * to get power state * * Return the powerdomain @pwrdm's next power state. Returns -EINVAL * if the powerdomain pointer is null or returns the next power state * upon success. */ int pwrdm_read_next_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_next_pwrst) ret = arch_pwrdm->pwrdm_read_next_pwrst(pwrdm); return ret; } /** * pwrdm_read_pwrst - get current powerdomain power state * @pwrdm: struct powerdomain * to get power state * * Return the powerdomain @pwrdm's current power state. Returns -EINVAL * if the powerdomain pointer is null or returns the current power state * upon success. */ int pwrdm_read_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_pwrst) ret = arch_pwrdm->pwrdm_read_pwrst(pwrdm); return ret; } /** * pwrdm_read_prev_pwrst - get previous powerdomain power state * @pwrdm: struct powerdomain * to get previous power state * * Return the powerdomain @pwrdm's previous power state. Returns -EINVAL * if the powerdomain pointer is null or returns the previous power state * upon success. */ int pwrdm_read_prev_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_pwrst) ret = arch_pwrdm->pwrdm_read_prev_pwrst(pwrdm); return ret; } /** * pwrdm_set_logic_retst - set powerdomain logic power state upon retention * @pwrdm: struct powerdomain * to set * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that the logic portion of the * powerdomain @pwrdm will enter when the powerdomain enters retention. * This will be either RETENTION or OFF, if supported. Returns * -EINVAL if the powerdomain pointer is null or the target power * state is not not supported, or returns 0 upon success. */ int pwrdm_set_logic_retst(struct powerdomain *pwrdm, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (!(pwrdm->pwrsts_logic_ret & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: setting next logic powerstate for %s to %0x\n", pwrdm->name, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_logic_retst) ret = arch_pwrdm->pwrdm_set_logic_retst(pwrdm, pwrst); return ret; } /** * pwrdm_set_mem_onst - set memory power state while powerdomain ON * @pwrdm: struct powerdomain * to set * @bank: memory bank number to set (0-3) * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that memory bank @bank of the * powerdomain @pwrdm will enter when the powerdomain enters the ON * state. @bank will be a number from 0 to 3, and represents different * types of memory, depending on the powerdomain. Returns -EINVAL if * the powerdomain pointer is null or the target power state is not * not supported for this memory bank, -EEXIST if the target memory * bank does not exist or is not controllable, or returns 0 upon * success. */ int pwrdm_set_mem_onst(struct powerdomain *pwrdm, u8 bank, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (pwrdm->banks < (bank + 1)) return -EEXIST; if (!(pwrdm->pwrsts_mem_on[bank] & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: setting next memory powerstate for domain %s " "bank %0x while pwrdm-ON to %0x\n", pwrdm->name, bank, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_mem_onst) ret = arch_pwrdm->pwrdm_set_mem_onst(pwrdm, bank, pwrst); return ret; } /** * pwrdm_set_mem_retst - set memory power state while powerdomain in RET * @pwrdm: struct powerdomain * to set * @bank: memory bank number to set (0-3) * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that memory bank @bank of the * powerdomain @pwrdm will enter when the powerdomain enters the * RETENTION state. Bank will be a number from 0 to 3, and represents * different types of memory, depending on the powerdomain. @pwrst * will be either RETENTION or OFF, if supported. Returns -EINVAL if * the powerdomain pointer is null or the target power state is not * not supported for this memory bank, -EEXIST if the target memory * bank does not exist or is not controllable, or returns 0 upon * success. */ int pwrdm_set_mem_retst(struct powerdomain *pwrdm, u8 bank, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (pwrdm->banks < (bank + 1)) return -EEXIST; if (!(pwrdm->pwrsts_mem_ret[bank] & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: setting next memory powerstate for domain %s " "bank %0x while pwrdm-RET to %0x\n", pwrdm->name, bank, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_mem_retst) ret = arch_pwrdm->pwrdm_set_mem_retst(pwrdm, bank, pwrst); return ret; } /** * pwrdm_read_logic_pwrst - get current powerdomain logic retention power state * @pwrdm: struct powerdomain * to get current logic retention power state * * Return the power state that the logic portion of powerdomain @pwrdm * will enter when the powerdomain enters retention. Returns -EINVAL * if the powerdomain pointer is null or returns the logic retention * power state upon success. */ int pwrdm_read_logic_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_logic_pwrst) ret = arch_pwrdm->pwrdm_read_logic_pwrst(pwrdm); return ret; } /** * pwrdm_read_prev_logic_pwrst - get previous powerdomain logic power state * @pwrdm: struct powerdomain * to get previous logic power state * * Return the powerdomain @pwrdm's previous logic power state. Returns * -EINVAL if the powerdomain pointer is null or returns the previous * logic power state upon success. */ int pwrdm_read_prev_logic_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_logic_pwrst) ret = arch_pwrdm->pwrdm_read_prev_logic_pwrst(pwrdm); return ret; } /** * pwrdm_read_logic_retst - get next powerdomain logic power state * @pwrdm: struct powerdomain * to get next logic power state * * Return the powerdomain pwrdm's logic power state. Returns -EINVAL * if the powerdomain pointer is null or returns the next logic * power state upon success. */ int pwrdm_read_logic_retst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_logic_retst) ret = arch_pwrdm->pwrdm_read_logic_retst(pwrdm); return ret; } /** * pwrdm_read_mem_pwrst - get current memory bank power state * @pwrdm: struct powerdomain * to get current memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain @pwrdm's current memory power state for bank * @bank. Returns -EINVAL if the powerdomain pointer is null, -EEXIST if * the target memory bank does not exist or is not controllable, or * returns the current memory power state upon success. */ int pwrdm_read_mem_pwrst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (pwrdm->flags & PWRDM_HAS_MPU_QUIRK) bank = 1; if (arch_pwrdm && arch_pwrdm->pwrdm_read_mem_pwrst) ret = arch_pwrdm->pwrdm_read_mem_pwrst(pwrdm, bank); return ret; } /** * pwrdm_read_prev_mem_pwrst - get previous memory bank power state * @pwrdm: struct powerdomain * to get previous memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain @pwrdm's previous memory power state for * bank @bank. Returns -EINVAL if the powerdomain pointer is null, * -EEXIST if the target memory bank does not exist or is not * controllable, or returns the previous memory power state upon * success. */ int pwrdm_read_prev_mem_pwrst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (pwrdm->flags & PWRDM_HAS_MPU_QUIRK) bank = 1; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_mem_pwrst) ret = arch_pwrdm->pwrdm_read_prev_mem_pwrst(pwrdm, bank); return ret; } /** * pwrdm_read_mem_retst - get next memory bank power state * @pwrdm: struct powerdomain * to get mext memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain pwrdm's next memory power state for bank * x. Returns -EINVAL if the powerdomain pointer is null, -EEXIST if * the target memory bank does not exist or is not controllable, or * returns the next memory power state upon success. */ int pwrdm_read_mem_retst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (arch_pwrdm && arch_pwrdm->pwrdm_read_mem_retst) ret = arch_pwrdm->pwrdm_read_mem_retst(pwrdm, bank); return ret; } /** * pwrdm_clear_all_prev_pwrst - clear previous powerstate register for a pwrdm * @pwrdm: struct powerdomain * to clear * * Clear the powerdomain's previous power state register @pwrdm. * Clears the entire register, including logic and memory bank * previous power states. Returns -EINVAL if the powerdomain pointer * is null, or returns 0 upon success. */ int pwrdm_clear_all_prev_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; /* * XXX should get the powerdomain's current state here; * warn & fail if it is not ON. */ pr_debug("powerdomain: clearing previous power state reg for %s\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_clear_all_prev_pwrst) ret = arch_pwrdm->pwrdm_clear_all_prev_pwrst(pwrdm); return ret; } /** * pwrdm_enable_hdwr_sar - enable automatic hardware SAR for a pwrdm * @pwrdm: struct powerdomain * * * Enable automatic context save-and-restore upon power state change * for some devices in the powerdomain @pwrdm. Warning: this only * affects a subset of devices in a powerdomain; check the TRM * closely. Returns -EINVAL if the powerdomain pointer is null or if * the powerdomain does not support automatic save-and-restore, or * returns 0 upon success. */ int pwrdm_enable_hdwr_sar(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; if (!(pwrdm->flags & PWRDM_HAS_HDWR_SAR)) return ret; pr_debug("powerdomain: %s: setting SAVEANDRESTORE bit\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_enable_hdwr_sar) ret = arch_pwrdm->pwrdm_enable_hdwr_sar(pwrdm); return ret; } /** * pwrdm_disable_hdwr_sar - disable automatic hardware SAR for a pwrdm * @pwrdm: struct powerdomain * * * Disable automatic context save-and-restore upon power state change * for some devices in the powerdomain @pwrdm. Warning: this only * affects a subset of devices in a powerdomain; check the TRM * closely. Returns -EINVAL if the powerdomain pointer is null or if * the powerdomain does not support automatic save-and-restore, or * returns 0 upon success. */ int pwrdm_disable_hdwr_sar(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; if (!(pwrdm->flags & PWRDM_HAS_HDWR_SAR)) return ret; pr_debug("powerdomain: %s: clearing SAVEANDRESTORE bit\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_disable_hdwr_sar) ret = arch_pwrdm->pwrdm_disable_hdwr_sar(pwrdm); return ret; } /** * pwrdm_has_hdwr_sar - test whether powerdomain supports hardware SAR * @pwrdm: struct powerdomain * * * Returns 1 if powerdomain @pwrdm supports hardware save-and-restore * for some devices, or 0 if it does not. */ bool pwrdm_has_hdwr_sar(struct powerdomain *pwrdm) { return (pwrdm && pwrdm->flags & PWRDM_HAS_HDWR_SAR) ? 1 : 0; } /** * pwrdm_set_lowpwrstchange - Request a low power state change * @pwrdm: struct powerdomain * * * Allows a powerdomain to transtion to a lower power sleep state * from an existing sleep state without waking up the powerdomain. * Returns -EINVAL if the powerdomain pointer is null or if the * powerdomain does not support LOWPOWERSTATECHANGE, or returns 0 * upon success. */ int pwrdm_set_lowpwrstchange(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (!(pwrdm->flags & PWRDM_HAS_LOWPOWERSTATECHANGE)) return -EINVAL; pr_debug("powerdomain: %s: setting LOWPOWERSTATECHANGE bit\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_set_lowpwrstchange) ret = arch_pwrdm->pwrdm_set_lowpwrstchange(pwrdm); return ret; } /** * pwrdm_wait_transition - wait for powerdomain power transition to finish * @pwrdm: struct powerdomain * to wait for * * If the powerdomain @pwrdm is in the process of a state transition, * spin until it completes the power transition, or until an iteration * bailout value is reached. Returns -EINVAL if the powerdomain * pointer is null, -EAGAIN if the bailout value was reached, or * returns 0 upon success. */ int pwrdm_wait_transition(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_wait_transition) ret = arch_pwrdm->pwrdm_wait_transition(pwrdm); return ret; } int pwrdm_state_switch(struct powerdomain *pwrdm) { return _pwrdm_state_switch(pwrdm, PWRDM_STATE_NOW); } int pwrdm_clkdm_state_switch(struct clockdomain *clkdm) { if (clkdm != NULL && clkdm->pwrdm.ptr != NULL) { pwrdm_wait_transition(clkdm->pwrdm.ptr); return pwrdm_state_switch(clkdm->pwrdm.ptr); } return -EINVAL; } int pwrdm_pre_transition(void) { pwrdm_for_each(_pwrdm_pre_transition_cb, NULL); return 0; } int pwrdm_post_transition(void) { pwrdm_for_each(_pwrdm_post_transition_cb, NULL); return 0; } /** * pwrdm_get_context_loss_count - get powerdomain's context loss count * @pwrdm: struct powerdomain * to wait for * * Context loss count is the sum of powerdomain off-mode counter, the * logic off counter and the per-bank memory off counter. Returns negative * (and WARNs) upon error, otherwise, returns the context loss count. */ int pwrdm_get_context_loss_count(struct powerdomain *pwrdm) { int i, count; if (!pwrdm) { WARN(1, "powerdomain: %s: pwrdm is null\n", __func__); return -ENODEV; } count = pwrdm->state_counter[PWRDM_POWER_OFF]; count += pwrdm->ret_logic_off_counter; for (i = 0; i < pwrdm->banks; i++) count += pwrdm->ret_mem_off_counter[i]; /* * Context loss count has to be a non-negative value. Clear the sign * bit to get a value range from 0 to INT_MAX. */ count &= INT_MAX; pr_debug("powerdomain: %s: context loss count = %d\n", pwrdm->name, count); return count; } /** * pwrdm_can_ever_lose_context - can this powerdomain ever lose context? * @pwrdm: struct powerdomain * * * Given a struct powerdomain * @pwrdm, returns 1 if the powerdomain * can lose either memory or logic context or if @pwrdm is invalid, or * returns 0 otherwise. This function is not concerned with how the * powerdomain registers are programmed (i.e., to go off or not); it's * concerned with whether it's ever possible for this powerdomain to * go off while some other part of the chip is active. This function * assumes that every powerdomain can go to either ON or INACTIVE. */ bool pwrdm_can_ever_lose_context(struct powerdomain *pwrdm) { int i; if (IS_ERR_OR_NULL(pwrdm)) { pr_debug("powerdomain: %s: invalid powerdomain pointer\n", __func__); return 1; } if (pwrdm->pwrsts & PWRSTS_OFF) return 1; if (pwrdm->pwrsts & PWRSTS_RET) { if (pwrdm->pwrsts_logic_ret & PWRSTS_OFF) return 1; for (i = 0; i < pwrdm->banks; i++) if (pwrdm->pwrsts_mem_ret[i] & PWRSTS_OFF) return 1; } for (i = 0; i < pwrdm->banks; i++) if (pwrdm->pwrsts_mem_on[i] & PWRSTS_OFF) return 1; return 0; }
apache-2.0
kerlw/stunserver
testcode/testdatastream.cpp
7
1572
/* Copyright 2011 John Selbie 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 "commonincludes.hpp" #include "stuncore.h" #include "testdatastream.h" // This test validates the code in stuncore\datastream.cpp HRESULT CTestDataStream::Run() { CDataStream stream; HRESULT hr; const char* str1 = "ABCDEFGHIJ"; const char* str2 = "KLMNOPQRSTUVW"; const char* str3 = "mnop"; const char* str4 = "XYZ"; char ch1= ' ', ch2=' ', ch3= ' '; Chk(stream.Write(str1, strlen(str1))); Chk(stream.Write(str2, strlen(str2))); Chk(stream.SeekDirect(12)); // seek to "M" Chk(stream.Write(str3, strlen(str3))); Chk(stream.SeekDirect(stream.GetSize())); Chk(stream.Write(str4, strlen(str4))); Chk(stream.WriteUint8(0)); stream.SeekDirect(9); stream.ReadInt8((int8_t*)&ch1); ChkIf(ch1 != 'J', E_FAIL); Chk(stream.ReadInt8((int8_t*)&ch2)); ChkIf(ch2 != 'K', E_FAIL); stream.SeekRelative(1); stream.ReadInt8((int8_t*)&ch3); ChkIf(ch3 != 'm', E_FAIL); Cleanup: return hr; }
apache-2.0
ppittle/AlienSwarmDirectorMod
trunk/src/game/client/swarm/vgui/objectiveicons.cpp
7
3955
#include "cbase.h" #include "c_asw_game_resource.h" #include "ObjectiveIcons.h" #include "c_asw_player.h" #include "c_asw_objective.h" #include "vgui_controls/AnimationController.h" #include "ObjectiveTitlePanel.h" #include "ObjectiveDetailsPanel.h" #include <vgui/ISurface.h> #include <vgui_controls/ImagePanel.h> // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> ObjectiveIcons::ObjectiveIcons(Panel *parent, const char *name) : Panel(parent, name) { for (int i=0;i<5;i++) { m_pIcon[i] = new vgui::ImagePanel(this, "ObjectiveIconImage"); if (m_pIcon[i]) { m_pIcon[i]->SetShouldScaleImage(true); m_pIcon[i]->SetMouseInputEnabled(false); } } m_iNumFading = 1; m_pObjective = NULL; m_pQueuedObjective = NULL; m_bHaveQueued = false; } ObjectiveIcons::~ObjectiveIcons() { } void ObjectiveIcons::PerformLayout() { int width = ScreenWidth(); int height = ScreenHeight(); int map_edge = (width * 0.3f) + (height * 0.66666f); float fIconSize = height * 0.1f; int padding = (width/1024.0f) * 28.0f; SetSize(fIconSize * 1.01 + padding, fIconSize * 1.1f * m_iNumFading + padding * 0.5f); SetPos(map_edge + padding, height * 0.03f); for (int i=0;i<5;i++) { m_pIcon[i]->SetPos(padding * 0.5f, fIconSize * 1.1f * i + padding * 0.5f); m_pIcon[i]->SetSize(fIconSize, fIconSize); } } void ObjectiveIcons::OnThink() { BaseClass::OnThink(); // this is no longer being used /* if (m_bHaveQueued) { if (m_pIcon[0] && m_pIcon[0]->GetAlpha() <= 0) { m_bHaveQueued = false; m_pObjective = m_pQueuedObjective; m_pQueuedObjective = NULL; if (m_pObjective) { char buffer[255]; m_iNumFading = 0; for (int i=0;i<5;i++) { if (m_pObjective->GetInfoIcon(i) && m_pObjective->GetInfoIcon(i)[0] != 0) { Q_snprintf(buffer, sizeof(buffer), "swarm/ObjectiveIcons/%s", m_pObjective->GetInfoIcon(i)); m_pIcon[i]->SetImage(buffer); // fade it in, in sequence int xpos, ypos; m_pIcon[i]->GetPos(xpos, ypos); //Msg("fading in %d which has ypos %d\n", i, ypos); vgui::GetAnimationController()->RunAnimationCommand(m_pIcon[i], "alpha", 255, 0.2f * i, 0.3f, vgui::AnimationController::INTERPOLATOR_LINEAR); m_pIcon[i]->SetDrawColor(Color(66,142,192,255)); m_iNumFading++; } } if (m_iNumFading > 0) { int icon_size = ScreenHeight() * 0.1f; int padding = ScreenHeight() * 0.0125f; SetTall(icon_size * 1.1f * m_iNumFading + padding * 0.5f); vgui::GetAnimationController()->RunAnimationCommand(this, "alpha", 255, 0, 0.3f, vgui::AnimationController::INTERPOLATOR_LINEAR); CLocalPlayerFilter filter; C_BaseEntity::EmitSound( filter, -1, "ASWInterface.MissionBoxes" ); } } } } */ } void ObjectiveIcons::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); SetBgColor(Color(30,66,89,164)); //SetBorder(pScheme->GetBorder("ASWBriefingButtonBorder")); //SetPaintBorderEnabled(true); //SetPaintBackgroundEnabled(false); for (int i=0;i<5;i++) { m_pIcon[i]->SetAlpha(0); m_pIcon[i]->SetPaintBackgroundEnabled(true); //m_pIcon[i]->SetFillColor(Color(30,66,89,164)); //m_pIcon[i]->SetFillColor(Color(0,0,0,64)); m_pIcon[i]->SetDrawColor(pScheme->GetColor("LightBlue", Color(255,255,255,255))); } SetAlpha(0); } void ObjectiveIcons::FadeOut() { for (int i=0;i<5;i++) { if (m_pIcon[i]->GetAlpha() > 0) vgui::GetAnimationController()->RunAnimationCommand(m_pIcon[i], "alpha", 0, 0, 0.3f, vgui::AnimationController::INTERPOLATOR_LINEAR); } vgui::GetAnimationController()->RunAnimationCommand(this, "alpha", 0, 0, 0.3f, vgui::AnimationController::INTERPOLATOR_LINEAR); } void ObjectiveIcons::SetObjective(C_ASW_Objective* pObjective) { if (pObjective != m_pObjective && pObjective != m_pQueuedObjective) { m_pQueuedObjective = pObjective; m_bHaveQueued = true; FadeOut(); } }
apache-2.0
Osirium/xrdp
sesman/libscp/libscp_tcp.c
8
2798
/** * xrdp: A Remote Desktop Protocol server. * * Copyright (C) Jay Sorg 2004-2012 * * 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. */ /** * * @file tcp.c * @brief Tcp stream funcions * @author Jay Sorg, Simone Fedele * */ #include "libscp_tcp.h" extern struct log_config *s_log; /*****************************************************************************/ int DEFAULT_CC scp_tcp_force_recv(int sck, char *data, int len) { int rcvd; int block; LOG_DBG("scp_tcp_force_recv()"); block = scp_lock_fork_critical_section_start(); while (len > 0) { rcvd = g_tcp_recv(sck, data, len, 0); if (rcvd == -1) { if (g_tcp_last_error_would_block(sck)) { g_sleep(1); } else { scp_lock_fork_critical_section_end(block); return 1; } } else if (rcvd == 0) { scp_lock_fork_critical_section_end(block); return 1; } else { data += rcvd; len -= rcvd; } } scp_lock_fork_critical_section_end(block); return 0; } /*****************************************************************************/ int DEFAULT_CC scp_tcp_force_send(int sck, char *data, int len) { int sent; int block; LOG_DBG("scp_tcp_force_send()"); block = scp_lock_fork_critical_section_start(); while (len > 0) { sent = g_tcp_send(sck, data, len, 0); if (sent == -1) { if (g_tcp_last_error_would_block(sck)) { g_sleep(1); } else { scp_lock_fork_critical_section_end(block); return 1; } } else if (sent == 0) { scp_lock_fork_critical_section_end(block); return 1; } else { data += sent; len -= sent; } } scp_lock_fork_critical_section_end(block); return 0; } /*****************************************************************************/ int DEFAULT_CC scp_tcp_bind(int sck, char *addr, char *port) { return g_tcp_bind_address(sck, port, addr); }
apache-2.0
Gilbert88/mesos
src/slave/containerizer/mesos/isolators/volume/utils.cpp
9
1793
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stout/path.hpp> #include <stout/stringify.hpp> #include <stout/strings.hpp> #include "slave/containerizer/mesos/isolators/volume/utils.hpp" using std::string; using std::vector; namespace mesos { namespace internal { namespace slave { namespace volume { PathValidator::PathValidator(const vector<string>& _whitelist) : whitelist(_whitelist) {} PathValidator PathValidator::parse(const string& whitelist) { return PathValidator(strings::split(whitelist, HOST_PATH_WHITELIST_DELIM)); } Try<Nothing> PathValidator::validate(const string& path) const { foreach (const string& allowedPath, whitelist) { const string allowedDirectory = path::join( allowedPath, stringify(os::PATH_SEPARATOR)); if (path == allowedPath || strings::startsWith(path, allowedDirectory)) { return Nothing(); } } return Error("Path '" + path + "' is not whitelisted"); } } // namespace volume { } // namespace slave { } // namespace internal { } // namespace mesos {
apache-2.0
pillip8282/TizenRT
external/libsodium/port/crypto_hash_mbedtls/crypto_hash_sha512_mbedtls.c
10
4612
/**************************************************************************** * * Copyright 2019 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ // Copyright 2017 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "crypto_hash_sha512.h" #include <mbedtls/sha512.h> #include <string.h> #ifdef MBEDTLS_SHA512_ALT /* Wrapper only works if the libsodium context structure can be mapped directly to the mbedTLS context structure. For ESP8266 hardware SHA, the problems are fitting all the data in the libsodium state structure, and also that libsodium doesn't have mbedtls_sha512_free() or mbedtls_sha512_clone() so we can't manage the hardware state in a clean way. */ #error "This wrapper only support standard software mbedTLS SHA" #endif /* Sanity check that all the context fields have identical sizes (this should be more or less given from the SHA512 algorithm) Note that the meaning of the fields is *not* all the same. In libsodium, SHA512 'count' is a 2xuin64_t *bit* count where count[0] == MSB. In mbedTLS, SHA512 'total' is a 2xuint64_t *byte* count where count[0] == LSB. For this implementation, we don't convert so the libsodium state structure actually holds a binary copy of the mbedTLS totals. This doesn't matter inside libsodium's documented API, but would matter if any callers try to use the state's bit count. */ _Static_assert(sizeof(((crypto_hash_sha512_state *)0)->state) == sizeof(((mbedtls_sha512_context *)0)->state), "state mismatch"); _Static_assert(sizeof(((crypto_hash_sha512_state *)0)->count) == sizeof(((mbedtls_sha512_context *)0)->total), "count mismatch"); _Static_assert(sizeof(((crypto_hash_sha512_state *)0)->buf) == sizeof(((mbedtls_sha512_context *)0)->buffer), "buf mismatch"); /* Inline functions to convert between mbedTLS & libsodium context structures */ static void sha512_mbedtls_to_libsodium(crypto_hash_sha512_state *ls_state, const mbedtls_sha512_context *mb_ctx) { memcpy(ls_state->count, mb_ctx->total, sizeof(ls_state->count)); memcpy(ls_state->state, mb_ctx->state, sizeof(ls_state->state)); memcpy(ls_state->buf, mb_ctx->buffer, sizeof(ls_state->buf)); } static void sha512_libsodium_to_mbedtls(mbedtls_sha512_context *mb_ctx, crypto_hash_sha512_state *ls_state) { memcpy(mb_ctx->total, ls_state->count, sizeof(mb_ctx->total)); memcpy(mb_ctx->state, ls_state->state, sizeof(mb_ctx->state)); memcpy(mb_ctx->buffer, ls_state->buf, sizeof(mb_ctx->buffer)); mb_ctx->is384 = 0; } int crypto_hash_sha512_init(crypto_hash_sha512_state *state) { mbedtls_sha512_context ctx; mbedtls_sha512_init(&ctx); int ret = mbedtls_sha512_starts_ret(&ctx, 0); if (ret != 0) { return ret; } sha512_mbedtls_to_libsodium(state, &ctx); return 0; } int crypto_hash_sha512_update(crypto_hash_sha512_state *state, const unsigned char *in, unsigned long long inlen) { mbedtls_sha512_context ctx; sha512_libsodium_to_mbedtls(&ctx, state); int ret = mbedtls_sha512_update_ret(&ctx, in, inlen); if (ret != 0) { return ret; } sha512_mbedtls_to_libsodium(state, &ctx); return 0; } int crypto_hash_sha512_final(crypto_hash_sha512_state *state, unsigned char *out) { mbedtls_sha512_context ctx; sha512_libsodium_to_mbedtls(&ctx, state); return mbedtls_sha512_finish_ret(&ctx, out); } int crypto_hash_sha512(unsigned char *out, const unsigned char *in, unsigned long long inlen) { return mbedtls_sha512_ret(in, inlen, out, 0); }
apache-2.0
mbedmicro/mbed
storage/filesystem/littlefsv2/tests/TESTS/filesystem/interspersed/main.cpp
10
11634
/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * 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 "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include <stdlib.h> #include <errno.h> using namespace utest::v1; // test configuration #ifndef MBED_TEST_FILESYSTEM #define MBED_TEST_FILESYSTEM LittleFileSystem2 #endif #ifndef MBED_TEST_FILESYSTEM_DECL #define MBED_TEST_FILESYSTEM_DECL MBED_TEST_FILESYSTEM fs("fs") #endif #ifndef MBED_TEST_BLOCKDEVICE #error [NOT_SUPPORTED] Non-volatile block device required #endif #ifndef MBED_TEST_BLOCKDEVICE_DECL #define MBED_TEST_BLOCKDEVICE_DECL MBED_TEST_BLOCKDEVICE bd #endif #ifndef MBED_TEST_FILES #define MBED_TEST_FILES 4 #endif #ifndef MBED_TEST_DIRS #define MBED_TEST_DIRS 4 #endif #ifndef MBED_TEST_BUFFER #define MBED_TEST_BUFFER 8192 #endif #ifndef MBED_TEST_TIMEOUT #define MBED_TEST_TIMEOUT 480 #endif // declarations #define STRINGIZE(x) STRINGIZE2(x) #define STRINGIZE2(x) #x #define INCLUDE(x) STRINGIZE(x.h) #include INCLUDE(MBED_TEST_FILESYSTEM) #include INCLUDE(MBED_TEST_BLOCKDEVICE) MBED_TEST_FILESYSTEM_DECL; MBED_TEST_BLOCKDEVICE_DECL; Dir dir[MBED_TEST_DIRS]; File file[MBED_TEST_FILES]; DIR *dd[MBED_TEST_DIRS]; FILE *fd[MBED_TEST_FILES]; struct dirent ent; struct dirent *ed; size_t size; uint8_t buffer[MBED_TEST_BUFFER]; uint8_t rbuffer[MBED_TEST_BUFFER]; uint8_t wbuffer[MBED_TEST_BUFFER]; // tests void test_parallel_tests() { int res = bd.init(); TEST_ASSERT_EQUAL(0, res); { res = MBED_TEST_FILESYSTEM::format(&bd); TEST_ASSERT_EQUAL(0, res); } res = bd.deinit(); TEST_ASSERT_EQUAL(0, res); } void test_parallel_file_test() { int res = bd.init(); TEST_ASSERT_EQUAL(0, res); { res = fs.mount(&bd); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "a", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); res = file[1].open(&fs, "b", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); res = file[2].open(&fs, "c", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); res = file[3].open(&fs, "d", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 10; i++) { res = file[0].write((const void *)"a", 1); TEST_ASSERT_EQUAL(1, res); res = file[1].write((const void *)"b", 1); TEST_ASSERT_EQUAL(1, res); res = file[2].write((const void *)"c", 1); TEST_ASSERT_EQUAL(1, res); res = file[3].write((const void *)"d", 1); TEST_ASSERT_EQUAL(1, res); } file[0].close(); file[1].close(); file[2].close(); file[3].close(); res = dir[0].open(&fs, "/"); TEST_ASSERT_EQUAL(0, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, ".."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "a"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "b"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "c"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "d"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "a", O_RDONLY); TEST_ASSERT_EQUAL(0, res); res = file[1].open(&fs, "b", O_RDONLY); TEST_ASSERT_EQUAL(0, res); res = file[2].open(&fs, "c", O_RDONLY); TEST_ASSERT_EQUAL(0, res); res = file[3].open(&fs, "d", O_RDONLY); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('a', res); res = file[1].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('b', res); res = file[2].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('c', res); res = file[3].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('d', res); } file[0].close(); file[1].close(); file[2].close(); file[3].close(); res = fs.unmount(); TEST_ASSERT_EQUAL(0, res); } res = bd.deinit(); TEST_ASSERT_EQUAL(0, res); } void test_parallel_remove_file_test() { int res = bd.init(); TEST_ASSERT_EQUAL(0, res); { res = fs.mount(&bd); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 5; i++) { res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); } res = fs.remove("a"); TEST_ASSERT_EQUAL(0, res); res = fs.remove("b"); TEST_ASSERT_EQUAL(0, res); res = fs.remove("c"); TEST_ASSERT_EQUAL(0, res); res = fs.remove("d"); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 5; i++) { res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); } file[0].close(); res = dir[0].open(&fs, "/"); TEST_ASSERT_EQUAL(0, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, ".."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "e"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_RDONLY); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('e', res); } file[0].close(); res = fs.unmount(); TEST_ASSERT_EQUAL(0, res); } res = bd.deinit(); TEST_ASSERT_EQUAL(0, res); } void test_remove_inconveniently_test() { int res = bd.init(); TEST_ASSERT_EQUAL(0, res); { res = fs.mount(&bd); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_WRONLY | O_TRUNC); TEST_ASSERT_EQUAL(0, res); res = file[1].open(&fs, "f", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); res = file[2].open(&fs, "g", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 5; i++) { res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); res = file[1].write((const void *)"f", 1); TEST_ASSERT_EQUAL(1, res); res = file[2].write((const void *)"g", 1); TEST_ASSERT_EQUAL(1, res); } res = fs.remove("f"); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 5; i++) { res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); res = file[1].write((const void *)"f", 1); TEST_ASSERT_EQUAL(1, res); res = file[2].write((const void *)"g", 1); TEST_ASSERT_EQUAL(1, res); } file[0].close(); file[1].close(); file[2].close(); res = dir[0].open(&fs, "/"); TEST_ASSERT_EQUAL(0, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, ".."); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "e"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "g"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_RDONLY); TEST_ASSERT_EQUAL(0, res); res = file[1].open(&fs, "g", O_RDONLY); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('e', res); res = file[1].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('g', res); } file[0].close(); file[1].close(); res = fs.unmount(); TEST_ASSERT_EQUAL(0, res); } res = bd.deinit(); TEST_ASSERT_EQUAL(0, res); } // test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(MBED_TEST_TIMEOUT, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Parallel tests", test_parallel_tests), Case("Parallel file test", test_parallel_file_test), Case("Parallel remove file test", test_parallel_remove_file_test), Case("Remove inconveniently test", test_remove_inconveniently_test), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); }
apache-2.0
gaoxiaojun/miniCTK
Plugins/org.blueberry.core.commands/src/common/berryCommandExceptions.cpp
10
1304
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCommandExceptions.h" namespace berry { CTK_IMPLEMENT_EXCEPTION(CommandException, ctkRuntimeException, "Command exception") CTK_IMPLEMENT_EXCEPTION(ExecutionException, CommandException, "Command execution exception") CTK_IMPLEMENT_EXCEPTION(NotHandledException, CommandException, "Command not handled exception") CTK_IMPLEMENT_EXCEPTION(NotDefinedException, CommandException, "Command not defined exception") CTK_IMPLEMENT_EXCEPTION(NotEnabledException, CommandException, "Command not enabled exception") CTK_IMPLEMENT_EXCEPTION(ParameterValueConversionException, CommandException, "Parameter value conversion exception") CTK_IMPLEMENT_EXCEPTION(ParameterValuesException, CommandException, "Parameter values exception") CTK_IMPLEMENT_EXCEPTION(SerializationException, CommandException, "Serialization exception") }
apache-2.0
graetzer/arangodb
3rdParty/boost/1.71.0/libs/compute/test/test_lambda.cpp
10
20131
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestLambda #include <boost/test/unit_test.hpp> #include <boost/tuple/tuple_io.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/compute/function.hpp> #include <boost/compute/lambda.hpp> #include <boost/compute/algorithm/copy_n.hpp> #include <boost/compute/algorithm/for_each.hpp> #include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/functional/bind.hpp> #include <boost/compute/iterator/zip_iterator.hpp> #include <boost/compute/types/pair.hpp> #include <boost/compute/types/tuple.hpp> #include "check_macros.hpp" #include "quirks.hpp" #include "context_setup.hpp" namespace bc = boost::compute; namespace compute = boost::compute; BOOST_AUTO_TEST_CASE(squared_plus_one) { bc::vector<int> vector(context); vector.push_back(1, queue); vector.push_back(2, queue); vector.push_back(3, queue); vector.push_back(4, queue); vector.push_back(5, queue); // multiply each value by itself and add one bc::transform(vector.begin(), vector.end(), vector.begin(), (bc::_1 * bc::_1) + 1, queue); CHECK_RANGE_EQUAL(int, 5, vector, (2, 5, 10, 17, 26)); } BOOST_AUTO_TEST_CASE(abs_int) { bc::vector<int> vector(context); vector.push_back(-1, queue); vector.push_back(-2, queue); vector.push_back(3, queue); vector.push_back(-4, queue); vector.push_back(5, queue); bc::transform(vector.begin(), vector.end(), vector.begin(), abs(bc::_1), queue); CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 3, 4, 5)); } template<class Result, class Expr> void check_lambda_result(const Expr &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of<Expr>::type, Result >::value )); } template<class Result, class Expr, class Arg1> void check_lambda_result(const Expr &, const Arg1 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1> >::type, Result >::value )); } template<class Result, class Expr, class Arg1, class Arg2> void check_lambda_result(const Expr &, const Arg1 &, const Arg2 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1, Arg2> >::type, Result >::value )); } template<class Result, class Expr, class Arg1, class Arg2, class Arg3> void check_lambda_result(const Expr &, const Arg1 &, const Arg2 &, const Arg3 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1, Arg2, Arg3> >::type, Result >::value )); } BOOST_AUTO_TEST_CASE(result_of) { using ::boost::compute::lambda::_1; using ::boost::compute::lambda::_2; using ::boost::compute::lambda::_3; namespace proto = ::boost::proto; using boost::compute::int_; check_lambda_result<int_>(proto::lit(1)); check_lambda_result<int_>(proto::lit(1) + 2); check_lambda_result<float>(proto::lit(1.2f)); check_lambda_result<float>(proto::lit(1) + 1.2f); check_lambda_result<float>(proto::lit(1) / 2 + 1.2f); using boost::compute::float4_; using boost::compute::int4_; check_lambda_result<int_>(_1, int_(1)); check_lambda_result<float>(_1, float(1.2f)); check_lambda_result<float4_>(_1, float4_(1, 2, 3, 4)); check_lambda_result<float4_>(2.0f * _1, float4_(1, 2, 3, 4)); check_lambda_result<float4_>(_1 * 2.0f, float4_(1, 2, 3, 4)); check_lambda_result<float>(dot(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float>(dot(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float>(distance(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float>(distance(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float>(length(_1), float4_(3, 2, 1, 0)); check_lambda_result<float4_>(cross(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float4_>(cross(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(max(_1, _2), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(max(_1, float(1.0f)), float4_(0, 1, 2, 3)); check_lambda_result<int4_>(max(_1, int4_(3, 2, 1, 0)), int4_(0, 1, 2, 3)); check_lambda_result<int4_>(max(_1, int_(1)), int4_(0, 1, 2, 3)); check_lambda_result<float4_>(min(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(step(_1, _2), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3)); check_lambda_result<int4_>(step(_1, _2), float(3.0f), int4_(0, 1, 2, 3)); check_lambda_result<float4_>( smoothstep(_1, _2, _3), float4_(3, 2, 1, 0), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3) ); check_lambda_result<int4_>( smoothstep(_1, _2, _3), float(2.0f), float(3.0f), int4_(0, 1, 2, 3) ); check_lambda_result<int4_>(bc::lambda::isinf(_1), float4_(0, 1, 2, 3)); check_lambda_result<int>(_1 + 2, int(2)); check_lambda_result<float>(_1 + 2, float(2.2f)); check_lambda_result<int>(_1 + _2, int(1), int(2)); check_lambda_result<float>(_1 + _2, int(1), float(2.2f)); check_lambda_result<int>(_1 + _1, int(1)); check_lambda_result<float>(_1 * _1, float(1)); using boost::compute::lambda::get; check_lambda_result<float>(get<0>(_1), float4_(1, 2, 3, 4)); check_lambda_result<bool>(get<0>(_1) < 1.f, float4_(1, 2, 3, 4)); check_lambda_result<bool>(_1 < 1.f, float(2)); using boost::compute::lambda::make_pair; check_lambda_result<int>(get<0>(make_pair(_1, _2)), int(1), float(1.2f)); check_lambda_result<float>(get<1>(make_pair(_1, _2)), int(1), float(1.2f)); check_lambda_result<std::pair<int, float> >(make_pair(_1, _2), int(1), float(1.2f)); using boost::compute::lambda::make_tuple; check_lambda_result<boost::tuple<int> >(make_tuple(_1), int(1)); check_lambda_result<boost::tuple<int, float> >(make_tuple(_1, _2), int(1), float(1.2f)); check_lambda_result<boost::tuple<int, int> >(make_tuple(_1, _1), int(1)); check_lambda_result<boost::tuple<int, float> >(make_tuple(_1, _2), int(1), float(1.4f)); check_lambda_result<boost::tuple<char, int, float> >( make_tuple(_1, _2, _3), char('a'), int(2), float(3.4f) ); check_lambda_result<boost::tuple<int, int, int> >( make_tuple(_1, _1, _1), int(1), float(1.4f) ); check_lambda_result<boost::tuple<int, float, int, float, int> >( make_tuple(_1, _2, _1, _2, _1), int(1), float(1.4f) ); } BOOST_AUTO_TEST_CASE(make_function_from_lamdba) { using boost::compute::lambda::_1; int data[] = { 2, 4, 6, 8, 10 }; compute::vector<int> vector(data, data + 5, queue); compute::function<int(int)> f = _1 * 2 + 3; compute::transform( vector.begin(), vector.end(), vector.begin(), f, queue ); CHECK_RANGE_EQUAL(int, 5, vector, (7, 11, 15, 19, 23)); } BOOST_AUTO_TEST_CASE(make_function_from_binary_lamdba) { using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::abs; int data1[] = { 2, 4, 6, 8, 10 }; int data2[] = { 10, 8, 6, 4, 2 }; compute::vector<int> vec1(data1, data1 + 5, queue); compute::vector<int> vec2(data2, data2 + 5, queue); compute::vector<int> result(5, context); compute::function<int(int, int)> f = abs(_1 - _2); compute::transform( vec1.begin(), vec1.end(), vec2.begin(), result.begin(), f, queue ); CHECK_RANGE_EQUAL(int, 5, result, (8, 4, 0, 4, 8)); } BOOST_AUTO_TEST_CASE(lambda_binary_function_with_pointer_modf) { using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::abs; bc::float_ data1[] = { 2.2f, 4.2f, 6.3f, 8.3f, 10.2f }; compute::vector<bc::float_> vec1(data1, data1 + 5, queue); compute::vector<bc::float_> vec2(size_t(5), context); compute::vector<bc::float_> result(5, context); compute::transform( bc::make_transform_iterator(vec1.begin(), _1 + 0.01f), bc::make_transform_iterator(vec1.end(), _1 + 0.01f), vec2.begin(), result.begin(), bc::lambda::modf(_1, _2), queue ); CHECK_RANGE_CLOSE(bc::float_, 5, result, (0.21f, 0.21f, 0.31f, 0.31f, 0.21f), 0.01f); CHECK_RANGE_CLOSE(bc::float_, 5, vec2, (2, 4, 6, 8, 10), 0.01f); } BOOST_AUTO_TEST_CASE(lambda_tenary_function_with_pointer_remquo) { if(!has_remquo_func(device)) { return; } using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::get; bc::float_ data1[] = { 2.2f, 4.2f, 6.3f, 8.3f, 10.2f }; bc::float_ data2[] = { 4.4f, 4.2f, 6.3f, 16.6f, 10.2f }; compute::vector<bc::float_> vec1(data1, data1 + 5, queue); compute::vector<bc::float_> vec2(data2, data2 + 5, queue); compute::vector<bc::int_> vec3(size_t(5), context); compute::vector<bc::float_> result(5, context); compute::transform( compute::make_zip_iterator( boost::make_tuple(vec1.begin(), vec2.begin(), vec3.begin()) ), compute::make_zip_iterator( boost::make_tuple(vec1.end(), vec2.end(), vec3.end()) ), result.begin(), bc::lambda::remquo(get<0>(_1), get<1>(_1), get<2>(_1)), queue ); CHECK_RANGE_CLOSE(bc::float_, 5, result, (2.2f, 0.0f, 0.0f, 8.3f, 0.0f), 0.01f); CHECK_RANGE_EQUAL(bc::int_, 5, vec3, (0, 1, 1, 0, 1)); } BOOST_AUTO_TEST_CASE(lambda_get_vector) { using boost::compute::_1; using boost::compute::int2_; using boost::compute::lambda::get; int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; compute::vector<int2_> vector(4, context); compute::copy( reinterpret_cast<int2_ *>(data), reinterpret_cast<int2_ *>(data) + 4, vector.begin(), queue ); // extract first component of each vector compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second component of each vector compute::vector<int> second_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (2, 4, 6, 8)); } BOOST_AUTO_TEST_CASE(lambda_get_pair) { using boost::compute::_1; using boost::compute::lambda::get; compute::vector<std::pair<int, float> > vector(context); vector.push_back(std::make_pair(1, 1.2f), queue); vector.push_back(std::make_pair(3, 3.4f), queue); vector.push_back(std::make_pair(5, 5.6f), queue); vector.push_back(std::make_pair(7, 7.8f), queue); // extract first compoenent of each pair compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second compoenent of each pair compute::vector<float> second_component(4, context); compute::transform( vector.begin(), vector.end(), second_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(float, 4, second_component, (1.2f, 3.4f, 5.6f, 7.8f)); } BOOST_AUTO_TEST_CASE(lambda_get_tuple) { using boost::compute::_1; using boost::compute::lambda::get; compute::vector<boost::tuple<int, char, float> > vector(context); vector.push_back(boost::make_tuple(1, 'a', 1.2f), queue); vector.push_back(boost::make_tuple(3, 'b', 3.4f), queue); vector.push_back(boost::make_tuple(5, 'c', 5.6f), queue); vector.push_back(boost::make_tuple(7, 'd', 7.8f), queue); // extract first component of each tuple compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second component of each tuple compute::vector<char> second_component(4, context); compute::transform( vector.begin(), vector.end(), second_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(char, 4, second_component, ('a', 'b', 'c', 'd')); // extract third component of each tuple compute::vector<float> third_component(4, context); compute::transform( vector.begin(), vector.end(), third_component.begin(), get<2>(_1), queue ); CHECK_RANGE_EQUAL(float, 4, third_component, (1.2f, 3.4f, 5.6f, 7.8f)); } BOOST_AUTO_TEST_CASE(lambda_get_zip_iterator) { using boost::compute::_1; using boost::compute::lambda::get; float data[] = { 1.2f, 2.3f, 3.4f, 4.5f, 5.6f, 6.7f, 7.8f, 9.0f }; compute::vector<float> input(8, context); compute::copy(data, data + 8, input.begin(), queue); compute::vector<float> output(8, context); compute::for_each( compute::make_zip_iterator( boost::make_tuple(input.begin(), output.begin()) ), compute::make_zip_iterator( boost::make_tuple(input.end(), output.end()) ), get<1>(_1) = get<0>(_1), queue ); CHECK_RANGE_EQUAL(float, 8, output, (1.2f, 2.3f, 3.4f, 4.5f, 5.6f, 6.7f, 7.8f, 9.0f) ); } BOOST_AUTO_TEST_CASE(lambda_make_pair) { using boost::compute::_1; using boost::compute::_2; using boost::compute::lambda::make_pair; int int_data[] = { 1, 3, 5, 7 }; float float_data[] = { 1.2f, 2.3f, 3.4f, 4.5f }; compute::vector<int> int_vector(int_data, int_data + 4, queue); compute::vector<float> float_vector(float_data, float_data + 4, queue); compute::vector<std::pair<int, float> > output_vector(4, context); compute::transform( int_vector.begin(), int_vector.end(), float_vector.begin(), output_vector.begin(), make_pair(_1 - 1, 0 - _2), queue ); std::vector<std::pair<int, float> > host_vector(4); compute::copy_n(output_vector.begin(), 4, host_vector.begin(), queue); BOOST_CHECK(host_vector[0] == std::make_pair(0, -1.2f)); BOOST_CHECK(host_vector[1] == std::make_pair(2, -2.3f)); BOOST_CHECK(host_vector[2] == std::make_pair(4, -3.4f)); BOOST_CHECK(host_vector[3] == std::make_pair(6, -4.5f)); } BOOST_AUTO_TEST_CASE(lambda_make_tuple) { using boost::compute::_1; using boost::compute::lambda::get; using boost::compute::lambda::make_tuple; std::vector<boost::tuple<int, float> > data; data.push_back(boost::make_tuple(2, 1.2f)); data.push_back(boost::make_tuple(4, 2.4f)); data.push_back(boost::make_tuple(6, 4.6f)); data.push_back(boost::make_tuple(8, 6.8f)); compute::vector<boost::tuple<int, float> > input_vector(4, context); compute::copy(data.begin(), data.end(), input_vector.begin(), queue); // reverse the elements in the tuple compute::vector<boost::tuple<float, int> > output_vector(4, context); compute::transform( input_vector.begin(), input_vector.end(), output_vector.begin(), make_tuple(get<1>(_1), get<0>(_1)), queue ); std::vector<boost::tuple<float, int> > host_vector(4); compute::copy_n(output_vector.begin(), 4, host_vector.begin(), queue); BOOST_CHECK_EQUAL(host_vector[0], boost::make_tuple(1.2f, 2)); BOOST_CHECK_EQUAL(host_vector[1], boost::make_tuple(2.4f, 4)); BOOST_CHECK_EQUAL(host_vector[2], boost::make_tuple(4.6f, 6)); BOOST_CHECK_EQUAL(host_vector[3], boost::make_tuple(6.8f, 8)); // duplicate each element in the tuple compute::vector<boost::tuple<int, int, float, float> > doubled_vector(4, context); compute::transform( input_vector.begin(), input_vector.end(), doubled_vector.begin(), make_tuple(get<0>(_1), get<0>(_1), get<1>(_1), get<1>(_1)), queue ); std::vector<boost::tuple<int, int, float, float> > doubled_host_vector(4); compute::copy_n(doubled_vector.begin(), 4, doubled_host_vector.begin(), queue); BOOST_CHECK_EQUAL(doubled_host_vector[0], boost::make_tuple(2, 2, 1.2f, 1.2f)); BOOST_CHECK_EQUAL(doubled_host_vector[1], boost::make_tuple(4, 4, 2.4f, 2.4f)); BOOST_CHECK_EQUAL(doubled_host_vector[2], boost::make_tuple(6, 6, 4.6f, 4.6f)); BOOST_CHECK_EQUAL(doubled_host_vector[3], boost::make_tuple(8, 8, 6.8f, 6.8f)); } BOOST_AUTO_TEST_CASE(bind_lambda_function) { using compute::placeholders::_1; namespace lambda = compute::lambda; int data[] = { 1, 2, 3, 4 }; compute::vector<int> vector(data, data + 4, queue); compute::transform( vector.begin(), vector.end(), vector.begin(), compute::bind(lambda::_1 * lambda::_2, _1, 2), queue ); CHECK_RANGE_EQUAL(int, 4, vector, (2, 4, 6, 8)); } BOOST_AUTO_TEST_CASE(lambda_function_with_uint_args) { compute::uint_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::uint_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::uint_(4), compute::uint_(6)), queue ); CHECK_RANGE_EQUAL(compute::uint_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_short_args) { compute::short_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::short_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::short_(4), compute::short_(6)), queue ); CHECK_RANGE_EQUAL(compute::short_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_uchar_args) { compute::uchar_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::uchar_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::uchar_(4), compute::uchar_(6)), queue ); CHECK_RANGE_EQUAL(compute::uchar_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_char_args) { compute::char_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::char_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::char_(4), compute::char_(6)), queue ); CHECK_RANGE_EQUAL(compute::char_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_SUITE_END()
apache-2.0
andcor02/mbed-os
features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NORDIC_SOFTDEVICE/TARGET_NRF51/source/btle/btle.cpp
13
9116
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/common.h" #include "nordic_common.h" #include "btle.h" #include "btle_clock.h" #include "ble_flash.h" #include "ble_conn_params.h" #include "btle_gap.h" #include "custom/custom_helper.h" #include "ble/GapEvents.h" #include "nRF5xn.h" #ifdef S110 #define IS_LEGACY_DEVICE_MANAGER_ENABLED 1 #elif defined(S130) || defined(S132) #define IS_LEGACY_DEVICE_MANAGER_ENABLED 0 #endif extern "C" { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #include "pstorage.h" #else #include "fstorage.h" #include "fds.h" #include "ble_conn_state.h" #endif #include "softdevice_handler.h" #include "ble_stack_handler_types.h" } #include "nrf_ble_hci.h" #include "nRF5xPalGattClient.h" #include "nRF5xPalSecurityManager.h" bool isEventsSignaled = false; extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name); void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name); extern "C" void SD_EVT_IRQHandler(void); // export the softdevice event handler for registration by nvic-set-vector. void btle_handler(ble_evt_t *p_ble_evt); static void sys_evt_dispatch(uint32_t sys_evt) { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) pstorage_sys_event_handler(sys_evt); #else // Forward Softdevice events to the fstorage module fs_sys_event_handler(sys_evt); #endif } /** * This function is called in interrupt context to handle BLE events; i.e. pull * system and user events out of the pending events-queue of the BLE stack. The * BLE stack signals the availability of events by the triggering the SWI2 * interrupt, which forwards the handling to this function. * * The event processing loop is implemented in intern_softdevice_events_execute(). * * This function will signal to the user code by calling signalEventsToProcess * that their is events to process and BLE::processEvents should be called. */ static uint32_t signalEvent() { if(isEventsSignaled == false) { isEventsSignaled = true; nRF5xn::Instance(BLE::DEFAULT_INSTANCE).signalEventsToProcess(BLE::DEFAULT_INSTANCE); } return NRF_SUCCESS; } error_t btle_init(void) { nrf_clock_lf_cfg_t clockConfiguration; // register softdevice handler vector NVIC_SetVector(SD_EVT_IRQn, (uint32_t) SD_EVT_IRQHandler); // Configure the LF clock according to values provided by btle_clock.h. // It is input from the chain of the yotta configuration system. clockConfiguration.source = LFCLK_CONF_SOURCE; clockConfiguration.xtal_accuracy = LFCLK_CONF_ACCURACY; clockConfiguration.rc_ctiv = LFCLK_CONF_RC_CTIV; clockConfiguration.rc_temp_ctiv = LFCLK_CONF_RC_TEMP_CTIV; SOFTDEVICE_HANDLER_INIT(&clockConfiguration, signalEvent); // Enable BLE stack ble_enable_params_t ble_enable_params; uint32_t err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT, PERIPHERAL_LINK_COUNT, &ble_enable_params); ble_enable_params.gatts_enable_params.attr_tab_size = GATTS_ATTR_TAB_SIZE; ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT; ble_enable_params.common_enable_params.vs_uuid_count = UUID_TABLE_MAX_ENTRIES; if(err_code != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (softdevice_enable(&ble_enable_params) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #if (NRF_SD_BLE_API_VERSION <= 2) ble_gap_addr_t addr; if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #else #endif ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler)); ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch)); return btle_gap_init(); } void btle_handler(ble_evt_t *p_ble_evt) { using ble::pal::vendor::nordic::nRF5xGattClient; using ble::pal::vendor::nordic::nRF5xSecurityManager; /* Library service handlers */ #if SDK_CONN_PARAMS_MODULE_ENABLE ble_conn_params_on_ble_evt(p_ble_evt); #endif #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #else // Forward BLE events to the Connection State module. // This must be called before any event handler that uses this module. ble_conn_state_on_ble_evt(p_ble_evt); #endif #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) ble::impl::PalGattClient::handle_events(p_ble_evt); #endif nRF5xn &ble = nRF5xn::Instance(BLE::DEFAULT_INSTANCE); nRF5xGap &gap = (nRF5xGap &) ble.getGap(); nRF5xGattServer &gattServer = (nRF5xGattServer &) ble.getGattServer(); ble::impl::PalSecurityManagerImpl &securityManager = ble::impl::PalSecurityManagerImpl::get_security_manager(); /* Custom event handler */ switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: gap.on_connection( p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->evt.gap_evt.params.connected ); break; case BLE_GAP_EVT_DISCONNECTED: { Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle; // Since we are not in a connection and have not started advertising, // store bonds gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID); Gap::DisconnectionReason_t reason; switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) { case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION: reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION; break; case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION: reason = Gap::REMOTE_USER_TERMINATED_CONNECTION; break; case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE: reason = Gap::CONN_INTERVAL_UNACCEPTABLE; break; default: /* Please refer to the underlying transport library for an * interpretion of this reason's value. */ reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason); break; } #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) // Close all pending discoveries for this connection ble::impl::PalGattClient::handle_connection_termination(handle); #endif gap.processDisconnectionEvent(handle, reason); break; } case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST: { Gap::Handle_t connection = p_ble_evt->evt.gap_evt.conn_handle; const ble_gap_evt_conn_param_update_request_t *update_request = &p_ble_evt->evt.gap_evt.params.conn_param_update_request; sd_ble_gap_conn_param_update(connection, &update_request->conn_params); break; } case BLE_GAP_EVT_TIMEOUT: gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src)); break; case BLE_GATTC_EVT_TIMEOUT: case BLE_GATTS_EVT_TIMEOUT: // Disconnect on GATT Server and Client timeout events. // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle, // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION)); break; case BLE_GAP_EVT_ADV_REPORT: gap.on_advertising_packet(p_ble_evt->evt.gap_evt.params.adv_report); break; default: break; } // Process security manager events securityManager.sm_handler(p_ble_evt); gattServer.hwCallback(p_ble_evt); } /*! @brief Callback when an error occurs inside the SoftDevice or ASSERT in debug*/ void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name) { error("nrf failure at %s:%d", p_file_name, line_num); } /*! @brief Handler for general errors above the SoftDevice layer. Typically we can' recover from this so we do a reset. */ void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name) { ASSERT_STATUS_RET_VOID( error_code ); NVIC_SystemReset(); }
apache-2.0
50wu/gpdb
gpcontrib/zstd/zstd_compression.c
14
4405
/*--------------------------------------------------------------------- * * zstd_compression.c * * IDENTIFICATION * src/backend/catalog/zstd_compression.c * *--------------------------------------------------------------------- */ #include "postgres.h" #include "access/genam.h" #include "catalog/pg_compression.h" #include "fmgr.h" #include "storage/gp_compress.h" #include "utils/builtins.h" #include <zstd.h> #include <zstd_errors.h> Datum zstd_constructor(PG_FUNCTION_ARGS); Datum zstd_destructor(PG_FUNCTION_ARGS); Datum zstd_compress(PG_FUNCTION_ARGS); Datum zstd_decompress(PG_FUNCTION_ARGS); Datum zstd_validator(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(zstd_constructor); PG_FUNCTION_INFO_V1(zstd_destructor); PG_FUNCTION_INFO_V1(zstd_compress); PG_FUNCTION_INFO_V1(zstd_decompress); PG_FUNCTION_INFO_V1(zstd_validator); #ifndef UNIT_TESTING PG_MODULE_MAGIC; #endif /* Internal state for zstd */ typedef struct zstd_state { int level; /* Compression level */ bool compress; /* Compress if true, decompress otherwise */ zstd_context *ctx; /* ZSTD compression/decompresion contexts */ } zstd_state; Datum zstd_constructor(PG_FUNCTION_ARGS) { /* PG_GETARG_POINTER(0) is TupleDesc that is currently unused. */ StorageAttributes *sa = (StorageAttributes *) PG_GETARG_POINTER(1); CompressionState *cs = palloc0(sizeof(CompressionState)); zstd_state *state = palloc0(sizeof(zstd_state)); bool compress = PG_GETARG_BOOL(2); if (!PointerIsValid(sa->comptype)) elog(ERROR, "zstd_constructor called with no compression type"); cs->opaque = (void *) state; cs->desired_sz = NULL; if (sa->complevel == 0) sa->complevel = 1; state->level = sa->complevel; state->compress = compress; state->ctx = zstd_alloc_context(); state->ctx->cctx = ZSTD_createCCtx(); state->ctx->dctx = ZSTD_createDCtx(); if (!state->ctx->cctx) elog(ERROR, "out of memory"); if (!state->ctx->dctx) elog(ERROR, "out of memory"); PG_RETURN_POINTER(cs); } Datum zstd_destructor(PG_FUNCTION_ARGS) { CompressionState *cs = (CompressionState *) PG_GETARG_POINTER(0); if (cs != NULL && cs->opaque != NULL) { zstd_state *state = (zstd_state *) cs->opaque; zstd_free_context(state->ctx); pfree(state); } PG_RETURN_VOID(); } /* * zstd compression implementation * * Note that when compression fails due to algorithm inefficiency, * dst_used is set so src_sz, but the output buffer contents are left unchanged */ Datum zstd_compress(PG_FUNCTION_ARGS) { /* FIXME: Change types to ZSTD::size_t */ const void *src = PG_GETARG_POINTER(0); int32 src_sz = PG_GETARG_INT32(1); void *dst = PG_GETARG_POINTER(2); int32 dst_sz = PG_GETARG_INT32(3); int32 *dst_used = (int32 *) PG_GETARG_POINTER(4); CompressionState *cs = (CompressionState *) PG_GETARG_POINTER(5); zstd_state *state = (zstd_state *) cs->opaque; unsigned long dst_length_used; dst_length_used = ZSTD_compressCCtx(state->ctx->cctx, dst, dst_sz, src, src_sz, state->level); if (ZSTD_isError(dst_length_used)) { if (ZSTD_getErrorCode(dst_length_used) == ZSTD_error_dstSize_tooSmall) { /* * This error is returned when "compressed" output is bigger than * uncompressed input. The caller can detect this by checking * dst_used >= src_size */ dst_length_used = src_sz; } else elog(ERROR, "%s", ZSTD_getErrorName(dst_length_used)); } *dst_used = (int32) dst_length_used; PG_RETURN_VOID(); } Datum zstd_decompress(PG_FUNCTION_ARGS) { /* FIXME: Change types to ZSTD::size_t */ const void *src = PG_GETARG_POINTER(0); int32 src_sz = PG_GETARG_INT32(1); void *dst = PG_GETARG_POINTER(2); int32 dst_sz = PG_GETARG_INT32(3); int32 *dst_used = (int32 *) PG_GETARG_POINTER(4); CompressionState *cs = (CompressionState *) PG_GETARG_POINTER(5); zstd_state *state = (zstd_state *) cs->opaque; unsigned long dst_length_used; if (src_sz <= 0) elog(ERROR, "invalid source buffer size %d", src_sz); if (dst_sz <= 0) elog(ERROR, "invalid destination buffer size %d", dst_sz); dst_length_used = ZSTD_decompressDCtx(state->ctx->dctx, dst, dst_sz, src, src_sz); if (ZSTD_isError(dst_length_used)) { elog(ERROR, "%s", ZSTD_getErrorName(dst_length_used)); } *dst_used = (int32) dst_length_used; PG_RETURN_VOID(); } Datum zstd_validator(PG_FUNCTION_ARGS) { PG_RETURN_VOID(); }
apache-2.0
olegartys/TizenRT
apps/examples/testcase/le_tc/kernel/tc_tash_stackmonitor.c
15
2333
/**************************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /// @file tc_tash_stackmonitor.c /// @brief Test Case Example for stkmon tash cmd /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <stdio.h> #include <stdlib.h> #include <sched.h> #include <apps/shell/tash.h> #include "tc_internal.h" #define DEFAULT_STKSIZE 1024 #define TC_STACKMONITOR_TASKNAME "tc_stackmonitor" #define TC_STACKMONITOR_PRIO 100 static void *stkmon_thread(void *arg) { /* waiting 10s for testing */ sleep(10); return NULL; } static int tc_tash_stackmonitor(int argc, char *args[]) { int ret = ERROR; pthread_t tc_thread; pthread_attr_t tc_thread_attr; pthread_attr_init(&tc_thread_attr); if (argc < 2) { printf("No param - Test with default value(stacksize:1024)\n"); tc_thread_attr.stacksize = DEFAULT_STKSIZE; } else { tc_thread_attr.stacksize = atoi(args[1]); printf("Test with stacksize: %d\n", tc_thread_attr.stacksize); } printf("Expected Stack Size for tc_stackmonitor thread : %d\n", tc_thread_attr.stacksize - 4); tc_thread_attr.priority = TC_STACKMONITOR_PRIO; ret = pthread_create(&tc_thread, &tc_thread_attr, stkmon_thread, NULL); TC_ASSERT_EQ_RETURN("pthread_create", ret, OK, ERROR); pthread_setname_np(tc_thread, TC_STACKMONITOR_TASKNAME); pthread_detach(tc_thread); TC_SUCCESS_RESULT(); return OK; } int tash_stackmonitor_main(void) { tash_cmd_install("tc-stkmon", tc_tash_stackmonitor, TASH_EXECMD_SYNC); return 0; }
apache-2.0
GDXN/CoActionOS-Public
CoActionOS-Applib/src/lib/dsp/MatrixFunctions/arm_mat_trans_q15.c
17
8433
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2013 ARM Limited. All rights reserved. * * $Date: 17. January 2013 * $Revision: V1.4.1 * * Project: CMSIS DSP Library * Title: arm_mat_trans_q15.c * * Description: Q15 matrix transpose. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupMatrix */ /** * @addtogroup MatrixTrans * @{ */ /* * @brief Q15 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either <code>ARM_MATH_SIZE_MISMATCH</code> * or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking. */ arm_status arm_mat_trans_q15( const arm_matrix_instance_q15 * pSrc, arm_matrix_instance_q15 * pDst) { q15_t *pSrcA = pSrc->pData; /* input data matrix pointer */ q15_t *pOut = pDst->pData; /* output data matrix pointer */ uint16_t nRows = pSrc->numRows; /* number of nRows */ uint16_t nColumns = pSrc->numCols; /* number of nColumns */ uint16_t col, row = nRows, i = 0u; /* row and column loop counters */ arm_status status; /* status of matrix transpose */ #ifndef ARM_MATH_CM0_FAMILY /* Run the below code for Cortex-M4 and Cortex-M3 */ #ifndef UNALIGNED_SUPPORT_DISABLE q31_t in; /* variable to hold temporary output */ #else q15_t in; #endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */ #ifdef ARM_MATH_MATRIX_CHECK /* Check for matrix mismatch condition */ if((pSrc->numRows != pDst->numCols) || (pSrc->numCols != pDst->numRows)) { /* Set status as ARM_MATH_SIZE_MISMATCH */ status = ARM_MATH_SIZE_MISMATCH; } else #endif /* #ifdef ARM_MATH_MATRIX_CHECK */ { /* Matrix transpose by exchanging the rows with columns */ /* row loop */ do { /* Apply loop unrolling and exchange the columns with row elements */ col = nColumns >> 2u; /* The pointer pOut is set to starting address of the column being processed */ pOut = pDst->pData + i; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while(col > 0u) { #ifndef UNALIGNED_SUPPORT_DISABLE /* Read two elements from the row */ in = *__SIMD32(pSrcA)++; /* Unpack and store one element in the destination */ #ifndef ARM_MATH_BIG_ENDIAN *pOut = (q15_t) in; #else *pOut = (q15_t) ((in & (q31_t) 0xffff0000) >> 16); #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Update the pointer pOut to point to the next row of the transposed matrix */ pOut += nRows; /* Unpack and store the second element in the destination */ #ifndef ARM_MATH_BIG_ENDIAN *pOut = (q15_t) ((in & (q31_t) 0xffff0000) >> 16); #else *pOut = (q15_t) in; #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Update the pointer pOut to point to the next row of the transposed matrix */ pOut += nRows; /* Read two elements from the row */ #ifndef ARM_MATH_BIG_ENDIAN in = *__SIMD32(pSrcA)++; #else in = *__SIMD32(pSrcA)++; #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Unpack and store one element in the destination */ #ifndef ARM_MATH_BIG_ENDIAN *pOut = (q15_t) in; #else *pOut = (q15_t) ((in & (q31_t) 0xffff0000) >> 16); #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Update the pointer pOut to point to the next row of the transposed matrix */ pOut += nRows; /* Unpack and store the second element in the destination */ #ifndef ARM_MATH_BIG_ENDIAN *pOut = (q15_t) ((in & (q31_t) 0xffff0000) >> 16); #else *pOut = (q15_t) in; #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ #else /* Read one element from the row */ in = *pSrcA++; /* Store one element in the destination */ *pOut = in; /* Update the pointer px to point to the next row of the transposed matrix */ pOut += nRows; /* Read one element from the row */ in = *pSrcA++; /* Store one element in the destination */ *pOut = in; /* Update the pointer px to point to the next row of the transposed matrix */ pOut += nRows; /* Read one element from the row */ in = *pSrcA++; /* Store one element in the destination */ *pOut = in; /* Update the pointer px to point to the next row of the transposed matrix */ pOut += nRows; /* Read one element from the row */ in = *pSrcA++; /* Store one element in the destination */ *pOut = in; #endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */ /* Update the pointer pOut to point to the next row of the transposed matrix */ pOut += nRows; /* Decrement the column loop counter */ col--; } /* Perform matrix transpose for last 3 samples here. */ col = nColumns % 0x4u; #else /* Run the below code for Cortex-M0 */ #ifdef ARM_MATH_MATRIX_CHECK /* Check for matrix mismatch condition */ if((pSrc->numRows != pDst->numCols) || (pSrc->numCols != pDst->numRows)) { /* Set status as ARM_MATH_SIZE_MISMATCH */ status = ARM_MATH_SIZE_MISMATCH; } else #endif /* #ifdef ARM_MATH_MATRIX_CHECK */ { /* Matrix transpose by exchanging the rows with columns */ /* row loop */ do { /* The pointer pOut is set to starting address of the column being processed */ pOut = pDst->pData + i; /* Initialize column loop counter */ col = nColumns; #endif /* #ifndef ARM_MATH_CM0_FAMILY */ while(col > 0u) { /* Read and store the input element in the destination */ *pOut = *pSrcA++; /* Update the pointer pOut to point to the next row of the transposed matrix */ pOut += nRows; /* Decrement the column loop counter */ col--; } i++; /* Decrement the row loop counter */ row--; } while(row > 0u); /* set status as ARM_MATH_SUCCESS */ status = ARM_MATH_SUCCESS; } /* Return to application */ return (status); } /** * @} end of MatrixTrans group */
apache-2.0
indashnet/InDashNet.Open.UN2000
android/external/skia/tools/skpdiff/SkDifferentPixelsMetric_cpu.cpp
18
2757
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <cstring> #include "SkBitmap.h" #include "SkDifferentPixelsMetric.h" #include "skpdiff_util.h" struct SkDifferentPixelsMetric::QueuedDiff { bool finished; double result; SkTDArray<SkIPoint>* poi; }; const char* SkDifferentPixelsMetric::getName() { return "different_pixels"; } int SkDifferentPixelsMetric::queueDiff(SkBitmap* baseline, SkBitmap* test) { double startTime = get_seconds(); int diffID = fQueuedDiffs.count(); QueuedDiff* diff = fQueuedDiffs.push(); SkTDArray<SkIPoint>* poi = diff->poi = new SkTDArray<SkIPoint>(); // If we never end up running the kernel, include some safe defaults in the result. diff->finished = false; diff->result = -1; // Ensure the images are comparable if (baseline->width() != test->width() || baseline->height() != test->height() || baseline->width() <= 0 || baseline->height() <= 0 || baseline->config() != test->config()) { diff->finished = true; return diffID; } int width = baseline->width(); int height = baseline->height(); int differentPixelsCount = 0; // Prepare the pixels for comparison baseline->lockPixels(); test->lockPixels(); for (int y = 0; y < height; y++) { // Grab a row from each image for easy comparison unsigned char* baselineRow = (unsigned char*)baseline->getAddr(0, y); unsigned char* testRow = (unsigned char*)test->getAddr(0, y); for (int x = 0; x < width; x++) { // Compare one pixel at a time so each differing pixel can be noted if (std::memcmp(&baselineRow[x * 4], &testRow[x * 4], 4) != 0) { poi->push()->set(x, y); differentPixelsCount++; } } } test->unlockPixels(); baseline->unlockPixels(); // Calculates the percentage of identical pixels diff->result = 1.0 - ((double)differentPixelsCount / (width * height)); SkDebugf("Time: %f\n", (get_seconds() - startTime)); return diffID; } void SkDifferentPixelsMetric::deleteDiff(int id) { if (NULL != fQueuedDiffs[id].poi) { delete fQueuedDiffs[id].poi; fQueuedDiffs[id].poi = NULL; } } bool SkDifferentPixelsMetric::isFinished(int id) { return fQueuedDiffs[id].finished; } double SkDifferentPixelsMetric::getResult(int id) { return fQueuedDiffs[id].result; } int SkDifferentPixelsMetric::getPointsOfInterestCount(int id) { return fQueuedDiffs[id].poi->count(); } SkIPoint* SkDifferentPixelsMetric::getPointsOfInterest(int id) { return fQueuedDiffs[id].poi->begin(); }
apache-2.0
davidfather/TizenRT
external/libopus/src/opus_demo.c
20
35114
/* Copyright (c) 2007-2008 CSIRO Copyright (c) 2007-2009 Xiph.Org Foundation Written by Jean-Marc Valin */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "opus.h" #include "debug.h" #include "opus_types.h" #include "opus_private.h" #include "opus_multistream.h" #define MAX_PACKET 1500 void print_usage( char* argv[] ) { fprintf(stderr, "Usage: %s [-e] <application> <sampling rate (Hz)> <channels (1/2)> " "<bits per second> [options] <input> <output>\n", argv[0]); fprintf(stderr, " %s -d <sampling rate (Hz)> <channels (1/2)> " "[options] <input> <output>\n\n", argv[0]); fprintf(stderr, "application: voip | audio | restricted-lowdelay\n" ); fprintf(stderr, "options:\n" ); fprintf(stderr, "-e : only runs the encoder (output the bit-stream)\n" ); fprintf(stderr, "-d : only runs the decoder (reads the bit-stream as input)\n" ); fprintf(stderr, "-cbr : enable constant bitrate; default: variable bitrate\n" ); fprintf(stderr, "-cvbr : enable constrained variable bitrate; default: unconstrained\n" ); fprintf(stderr, "-delayed-decision : use look-ahead for speech/music detection (experts only); default: disabled\n" ); fprintf(stderr, "-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate\n" ); fprintf(stderr, "-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20 \n" ); fprintf(stderr, "-max_payload <bytes> : maximum payload size in bytes, default: 1024\n" ); fprintf(stderr, "-complexity <comp> : complexity, 0 (lowest) ... 10 (highest); default: 10\n" ); fprintf(stderr, "-inbandfec : enable SILK inband FEC\n" ); fprintf(stderr, "-forcemono : force mono encoding, even for stereo input\n" ); fprintf(stderr, "-dtx : enable SILK DTX\n" ); fprintf(stderr, "-loss <perc> : simulate packet loss, in percent (0-100); default: 0\n" ); } static void int_to_char(opus_uint32 i, unsigned char ch[4]) { ch[0] = i>>24; ch[1] = (i>>16)&0xFF; ch[2] = (i>>8)&0xFF; ch[3] = i&0xFF; } static opus_uint32 char_to_int(unsigned char ch[4]) { return ((opus_uint32)ch[0]<<24) | ((opus_uint32)ch[1]<<16) | ((opus_uint32)ch[2]<< 8) | (opus_uint32)ch[3]; } static void check_encoder_option(int decode_only, const char *opt) { if (decode_only) { fprintf(stderr, "option %s is only for encoding\n", opt); exit(EXIT_FAILURE); } } static const int silk8_test[][4] = { {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480, 2} }; static const int silk12_test[][4] = { {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480, 2} }; static const int silk16_test[][4] = { {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480, 2} }; static const int hybrid24_test[][4] = { {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2} }; static const int hybrid48_test[][4] = { {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 1}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2}, {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2} }; static const int celt_test[][4] = { {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 240, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 240, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 240, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 120, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 120, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 120, 1}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 240, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 240, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 240, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 120, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND, 120, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND, 120, 2}, }; static const int celt_hq_test[][4] = { {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 240, 2}, {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND, 120, 2}, }; #if 0 /* This is a hack that replaces the normal encoder/decoder with the multistream version */ #define OpusEncoder OpusMSEncoder #define OpusDecoder OpusMSDecoder #define opus_encode opus_multistream_encode #define opus_decode opus_multistream_decode #define opus_encoder_ctl opus_multistream_encoder_ctl #define opus_decoder_ctl opus_multistream_decoder_ctl #define opus_encoder_create ms_opus_encoder_create #define opus_decoder_create ms_opus_decoder_create #define opus_encoder_destroy opus_multistream_encoder_destroy #define opus_decoder_destroy opus_multistream_decoder_destroy static OpusEncoder *ms_opus_encoder_create(opus_int32 Fs, int channels, int application, int *error) { int streams, coupled_streams; unsigned char mapping[256]; return (OpusEncoder *)opus_multistream_surround_encoder_create(Fs, channels, 1, &streams, &coupled_streams, mapping, application, error); } static OpusDecoder *ms_opus_decoder_create(opus_int32 Fs, int channels, int *error) { int streams; int coupled_streams; unsigned char mapping[256]={0,1}; streams = 1; coupled_streams = channels==2; return (OpusDecoder *)opus_multistream_decoder_create(Fs, channels, streams, coupled_streams, mapping, error); } #endif int main(int argc, char *argv[]) { int err; char *inFile, *outFile; FILE *fin, *fout; OpusEncoder *enc=NULL; OpusDecoder *dec=NULL; int args; int len[2]; int frame_size, channels; opus_int32 bitrate_bps=0; unsigned char *data[2]; unsigned char *fbytes; opus_int32 sampling_rate; int use_vbr; int max_payload_bytes; int complexity; int use_inbandfec; int use_dtx; int forcechannels; int cvbr = 0; int packet_loss_perc; opus_int32 count=0, count_act=0; int k; opus_int32 skip=0; int stop=0; short *in, *out; int application=OPUS_APPLICATION_AUDIO; double bits=0.0, bits_max=0.0, bits_act=0.0, bits2=0.0, nrg; double tot_samples=0; opus_uint64 tot_in, tot_out; int bandwidth=OPUS_AUTO; const char *bandwidth_string; int lost = 0, lost_prev = 1; int toggle = 0; opus_uint32 enc_final_range[2]; opus_uint32 dec_final_range; int encode_only=0, decode_only=0; int max_frame_size = 48000*2; size_t num_read; int curr_read=0; int sweep_bps = 0; int random_framesize=0, newsize=0, delayed_celt=0; int sweep_max=0, sweep_min=0; int random_fec=0; const int (*mode_list)[4]=NULL; int nb_modes_in_list=0; int curr_mode=0; int curr_mode_count=0; int mode_switch_time = 48000; int nb_encoded=0; int remaining=0; int variable_duration=OPUS_FRAMESIZE_ARG; int delayed_decision=0; if (argc < 5 ) { print_usage( argv ); return EXIT_FAILURE; } tot_in=tot_out=0; fprintf(stderr, "%s\n", opus_get_version_string()); args = 1; if (strcmp(argv[args], "-e")==0) { encode_only = 1; args++; } else if (strcmp(argv[args], "-d")==0) { decode_only = 1; args++; } if (!decode_only && argc < 7 ) { print_usage( argv ); return EXIT_FAILURE; } if (!decode_only) { if (strcmp(argv[args], "voip")==0) application = OPUS_APPLICATION_VOIP; else if (strcmp(argv[args], "restricted-lowdelay")==0) application = OPUS_APPLICATION_RESTRICTED_LOWDELAY; else if (strcmp(argv[args], "audio")!=0) { fprintf(stderr, "unknown application: %s\n", argv[args]); print_usage(argv); return EXIT_FAILURE; } args++; } sampling_rate = (opus_int32)atol(argv[args]); args++; if (sampling_rate != 8000 && sampling_rate != 12000 && sampling_rate != 16000 && sampling_rate != 24000 && sampling_rate != 48000) { fprintf(stderr, "Supported sampling rates are 8000, 12000, " "16000, 24000 and 48000.\n"); return EXIT_FAILURE; } frame_size = sampling_rate/50; channels = atoi(argv[args]); args++; if (channels < 1 || channels > 2) { fprintf(stderr, "Opus_demo supports only 1 or 2 channels.\n"); return EXIT_FAILURE; } if (!decode_only) { bitrate_bps = (opus_int32)atol(argv[args]); args++; } /* defaults: */ use_vbr = 1; max_payload_bytes = MAX_PACKET; complexity = 10; use_inbandfec = 0; forcechannels = OPUS_AUTO; use_dtx = 0; packet_loss_perc = 0; while( args < argc - 2 ) { /* process command line options */ if( strcmp( argv[ args ], "-cbr" ) == 0 ) { check_encoder_option(decode_only, "-cbr"); use_vbr = 0; args++; } else if( strcmp( argv[ args ], "-bandwidth" ) == 0 ) { check_encoder_option(decode_only, "-bandwidth"); if (strcmp(argv[ args + 1 ], "NB")==0) bandwidth = OPUS_BANDWIDTH_NARROWBAND; else if (strcmp(argv[ args + 1 ], "MB")==0) bandwidth = OPUS_BANDWIDTH_MEDIUMBAND; else if (strcmp(argv[ args + 1 ], "WB")==0) bandwidth = OPUS_BANDWIDTH_WIDEBAND; else if (strcmp(argv[ args + 1 ], "SWB")==0) bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND; else if (strcmp(argv[ args + 1 ], "FB")==0) bandwidth = OPUS_BANDWIDTH_FULLBAND; else { fprintf(stderr, "Unknown bandwidth %s. " "Supported are NB, MB, WB, SWB, FB.\n", argv[ args + 1 ]); return EXIT_FAILURE; } args += 2; } else if( strcmp( argv[ args ], "-framesize" ) == 0 ) { check_encoder_option(decode_only, "-framesize"); if (strcmp(argv[ args + 1 ], "2.5")==0) frame_size = sampling_rate/400; else if (strcmp(argv[ args + 1 ], "5")==0) frame_size = sampling_rate/200; else if (strcmp(argv[ args + 1 ], "10")==0) frame_size = sampling_rate/100; else if (strcmp(argv[ args + 1 ], "20")==0) frame_size = sampling_rate/50; else if (strcmp(argv[ args + 1 ], "40")==0) frame_size = sampling_rate/25; else if (strcmp(argv[ args + 1 ], "60")==0) frame_size = 3*sampling_rate/50; else if (strcmp(argv[ args + 1 ], "80")==0) frame_size = 4*sampling_rate/50; else if (strcmp(argv[ args + 1 ], "100")==0) frame_size = 5*sampling_rate/50; else if (strcmp(argv[ args + 1 ], "120")==0) frame_size = 6*sampling_rate/50; else { fprintf(stderr, "Unsupported frame size: %s ms. " "Supported are 2.5, 5, 10, 20, 40, 60, 80, 100, 120.\n", argv[ args + 1 ]); return EXIT_FAILURE; } args += 2; } else if( strcmp( argv[ args ], "-max_payload" ) == 0 ) { check_encoder_option(decode_only, "-max_payload"); max_payload_bytes = atoi( argv[ args + 1 ] ); args += 2; } else if( strcmp( argv[ args ], "-complexity" ) == 0 ) { check_encoder_option(decode_only, "-complexity"); complexity = atoi( argv[ args + 1 ] ); args += 2; } else if( strcmp( argv[ args ], "-inbandfec" ) == 0 ) { use_inbandfec = 1; args++; } else if( strcmp( argv[ args ], "-forcemono" ) == 0 ) { check_encoder_option(decode_only, "-forcemono"); forcechannels = 1; args++; } else if( strcmp( argv[ args ], "-cvbr" ) == 0 ) { check_encoder_option(decode_only, "-cvbr"); cvbr = 1; args++; } else if( strcmp( argv[ args ], "-delayed-decision" ) == 0 ) { check_encoder_option(decode_only, "-delayed-decision"); delayed_decision = 1; args++; } else if( strcmp( argv[ args ], "-dtx") == 0 ) { check_encoder_option(decode_only, "-dtx"); use_dtx = 1; args++; } else if( strcmp( argv[ args ], "-loss" ) == 0 ) { packet_loss_perc = atoi( argv[ args + 1 ] ); args += 2; } else if( strcmp( argv[ args ], "-sweep" ) == 0 ) { check_encoder_option(decode_only, "-sweep"); sweep_bps = atoi( argv[ args + 1 ] ); args += 2; } else if( strcmp( argv[ args ], "-random_framesize" ) == 0 ) { check_encoder_option(decode_only, "-random_framesize"); random_framesize = 1; args++; } else if( strcmp( argv[ args ], "-sweep_max" ) == 0 ) { check_encoder_option(decode_only, "-sweep_max"); sweep_max = atoi( argv[ args + 1 ] ); args += 2; } else if( strcmp( argv[ args ], "-random_fec" ) == 0 ) { check_encoder_option(decode_only, "-random_fec"); random_fec = 1; args++; } else if( strcmp( argv[ args ], "-silk8k_test" ) == 0 ) { check_encoder_option(decode_only, "-silk8k_test"); mode_list = silk8_test; nb_modes_in_list = 8; args++; } else if( strcmp( argv[ args ], "-silk12k_test" ) == 0 ) { check_encoder_option(decode_only, "-silk12k_test"); mode_list = silk12_test; nb_modes_in_list = 8; args++; } else if( strcmp( argv[ args ], "-silk16k_test" ) == 0 ) { check_encoder_option(decode_only, "-silk16k_test"); mode_list = silk16_test; nb_modes_in_list = 8; args++; } else if( strcmp( argv[ args ], "-hybrid24k_test" ) == 0 ) { check_encoder_option(decode_only, "-hybrid24k_test"); mode_list = hybrid24_test; nb_modes_in_list = 4; args++; } else if( strcmp( argv[ args ], "-hybrid48k_test" ) == 0 ) { check_encoder_option(decode_only, "-hybrid48k_test"); mode_list = hybrid48_test; nb_modes_in_list = 4; args++; } else if( strcmp( argv[ args ], "-celt_test" ) == 0 ) { check_encoder_option(decode_only, "-celt_test"); mode_list = celt_test; nb_modes_in_list = 32; args++; } else if( strcmp( argv[ args ], "-celt_hq_test" ) == 0 ) { check_encoder_option(decode_only, "-celt_hq_test"); mode_list = celt_hq_test; nb_modes_in_list = 4; args++; } else { printf( "Error: unrecognized setting: %s\n\n", argv[ args ] ); print_usage( argv ); return EXIT_FAILURE; } } if (sweep_max) sweep_min = bitrate_bps; if (max_payload_bytes < 0 || max_payload_bytes > MAX_PACKET) { fprintf (stderr, "max_payload_bytes must be between 0 and %d\n", MAX_PACKET); return EXIT_FAILURE; } inFile = argv[argc-2]; fin = fopen(inFile, "rb"); if (!fin) { fprintf (stderr, "Could not open input file %s\n", argv[argc-2]); return EXIT_FAILURE; } if (mode_list) { int size; fseek(fin, 0, SEEK_END); size = ftell(fin); fprintf(stderr, "File size is %d bytes\n", size); fseek(fin, 0, SEEK_SET); mode_switch_time = size/sizeof(short)/channels/nb_modes_in_list; fprintf(stderr, "Switching mode every %d samples\n", mode_switch_time); } outFile = argv[argc-1]; fout = fopen(outFile, "wb+"); if (!fout) { fprintf (stderr, "Could not open output file %s\n", argv[argc-1]); fclose(fin); return EXIT_FAILURE; } if (!decode_only) { enc = opus_encoder_create(sampling_rate, channels, application, &err); if (err != OPUS_OK) { fprintf(stderr, "Cannot create encoder: %s\n", opus_strerror(err)); fclose(fin); fclose(fout); return EXIT_FAILURE; } opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps)); opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(bandwidth)); opus_encoder_ctl(enc, OPUS_SET_VBR(use_vbr)); opus_encoder_ctl(enc, OPUS_SET_VBR_CONSTRAINT(cvbr)); opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity)); opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(use_inbandfec)); opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(forcechannels)); opus_encoder_ctl(enc, OPUS_SET_DTX(use_dtx)); opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(packet_loss_perc)); opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip)); opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16)); opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration)); } if (!encode_only) { dec = opus_decoder_create(sampling_rate, channels, &err); if (err != OPUS_OK) { fprintf(stderr, "Cannot create decoder: %s\n", opus_strerror(err)); fclose(fin); fclose(fout); return EXIT_FAILURE; } } switch(bandwidth) { case OPUS_BANDWIDTH_NARROWBAND: bandwidth_string = "narrowband"; break; case OPUS_BANDWIDTH_MEDIUMBAND: bandwidth_string = "mediumband"; break; case OPUS_BANDWIDTH_WIDEBAND: bandwidth_string = "wideband"; break; case OPUS_BANDWIDTH_SUPERWIDEBAND: bandwidth_string = "superwideband"; break; case OPUS_BANDWIDTH_FULLBAND: bandwidth_string = "fullband"; break; case OPUS_AUTO: bandwidth_string = "auto bandwidth"; break; default: bandwidth_string = "unknown"; break; } if (decode_only) fprintf(stderr, "Decoding with %ld Hz output (%d channels)\n", (long)sampling_rate, channels); else fprintf(stderr, "Encoding %ld Hz input at %.3f kb/s " "in %s with %d-sample frames.\n", (long)sampling_rate, bitrate_bps*0.001, bandwidth_string, frame_size); in = (short*)malloc(max_frame_size*channels*sizeof(short)); out = (short*)malloc(max_frame_size*channels*sizeof(short)); /* We need to allocate for 16-bit PCM data, but we store it as unsigned char. */ fbytes = (unsigned char*)malloc(max_frame_size*channels*sizeof(short)); data[0] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char)); if ( use_inbandfec ) { data[1] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char)); } if(delayed_decision) { if (frame_size==sampling_rate/400) variable_duration = OPUS_FRAMESIZE_2_5_MS; else if (frame_size==sampling_rate/200) variable_duration = OPUS_FRAMESIZE_5_MS; else if (frame_size==sampling_rate/100) variable_duration = OPUS_FRAMESIZE_10_MS; else if (frame_size==sampling_rate/50) variable_duration = OPUS_FRAMESIZE_20_MS; else if (frame_size==sampling_rate/25) variable_duration = OPUS_FRAMESIZE_40_MS; else if (frame_size==3*sampling_rate/50) variable_duration = OPUS_FRAMESIZE_60_MS; else if (frame_size==4*sampling_rate/50) variable_duration = OPUS_FRAMESIZE_80_MS; else if (frame_size==5*sampling_rate/50) variable_duration = OPUS_FRAMESIZE_100_MS; else variable_duration = OPUS_FRAMESIZE_120_MS; opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration)); frame_size = 2*48000; } while (!stop) { if (delayed_celt) { frame_size = newsize; delayed_celt = 0; } else if (random_framesize && rand()%20==0) { newsize = rand()%6; switch(newsize) { case 0: newsize=sampling_rate/400; break; case 1: newsize=sampling_rate/200; break; case 2: newsize=sampling_rate/100; break; case 3: newsize=sampling_rate/50; break; case 4: newsize=sampling_rate/25; break; case 5: newsize=3*sampling_rate/50; break; } while (newsize < sampling_rate/25 && bitrate_bps-abs(sweep_bps) <= 3*12*sampling_rate/newsize) newsize*=2; if (newsize < sampling_rate/100 && frame_size >= sampling_rate/100) { opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY)); delayed_celt=1; } else { frame_size = newsize; } } if (random_fec && rand()%30==0) { opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(rand()%4==0)); } if (decode_only) { unsigned char ch[4]; num_read = fread(ch, 1, 4, fin); if (num_read!=4) break; len[toggle] = char_to_int(ch); if (len[toggle]>max_payload_bytes || len[toggle]<0) { fprintf(stderr, "Invalid payload length: %d\n",len[toggle]); break; } num_read = fread(ch, 1, 4, fin); if (num_read!=4) break; enc_final_range[toggle] = char_to_int(ch); num_read = fread(data[toggle], 1, len[toggle], fin); if (num_read!=(size_t)len[toggle]) { fprintf(stderr, "Ran out of input, " "expecting %d bytes got %d\n", len[toggle],(int)num_read); break; } } else { int i; if (mode_list!=NULL) { opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(mode_list[curr_mode][1])); opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(mode_list[curr_mode][0])); opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(mode_list[curr_mode][3])); frame_size = mode_list[curr_mode][2]; } num_read = fread(fbytes, sizeof(short)*channels, frame_size-remaining, fin); curr_read = (int)num_read; tot_in += curr_read; for(i=0;i<curr_read*channels;i++) { opus_int32 s; s=fbytes[2*i+1]<<8|fbytes[2*i]; s=((s&0xFFFF)^0x8000)-0x8000; in[i+remaining*channels]=s; } if (curr_read+remaining < frame_size) { for (i=(curr_read+remaining)*channels;i<frame_size*channels;i++) in[i] = 0; if (encode_only || decode_only) stop = 1; } len[toggle] = opus_encode(enc, in, frame_size, data[toggle], max_payload_bytes); nb_encoded = opus_packet_get_samples_per_frame(data[toggle], sampling_rate)*opus_packet_get_nb_frames(data[toggle], len[toggle]); remaining = frame_size-nb_encoded; for(i=0;i<remaining*channels;i++) in[i] = in[nb_encoded*channels+i]; if (sweep_bps!=0) { bitrate_bps += sweep_bps; if (sweep_max) { if (bitrate_bps > sweep_max) sweep_bps = -sweep_bps; else if (bitrate_bps < sweep_min) sweep_bps = -sweep_bps; } /* safety */ if (bitrate_bps<1000) bitrate_bps = 1000; opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps)); } opus_encoder_ctl(enc, OPUS_GET_FINAL_RANGE(&enc_final_range[toggle])); if (len[toggle] < 0) { fprintf (stderr, "opus_encode() returned %d\n", len[toggle]); fclose(fin); fclose(fout); return EXIT_FAILURE; } curr_mode_count += frame_size; if (curr_mode_count > mode_switch_time && curr_mode < nb_modes_in_list-1) { curr_mode++; curr_mode_count = 0; } } #if 0 /* This is for testing the padding code, do not enable by default */ if (len[toggle]<1275) { int new_len = len[toggle]+rand()%(max_payload_bytes-len[toggle]); if ((err = opus_packet_pad(data[toggle], len[toggle], new_len)) != OPUS_OK) { fprintf(stderr, "padding failed: %s\n", opus_strerror(err)); return EXIT_FAILURE; } len[toggle] = new_len; } #endif if (encode_only) { unsigned char int_field[4]; int_to_char(len[toggle], int_field); if (fwrite(int_field, 1, 4, fout) != 4) { fprintf(stderr, "Error writing.\n"); return EXIT_FAILURE; } int_to_char(enc_final_range[toggle], int_field); if (fwrite(int_field, 1, 4, fout) != 4) { fprintf(stderr, "Error writing.\n"); return EXIT_FAILURE; } if (fwrite(data[toggle], 1, len[toggle], fout) != (unsigned)len[toggle]) { fprintf(stderr, "Error writing.\n"); return EXIT_FAILURE; } tot_samples += nb_encoded; } else { opus_int32 output_samples; lost = len[toggle]==0 || (packet_loss_perc>0 && rand()%100 < packet_loss_perc); if (lost) opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples)); else output_samples = max_frame_size; if( count >= use_inbandfec ) { /* delay by one packet when using in-band FEC */ if( use_inbandfec ) { if( lost_prev ) { /* attempt to decode with in-band FEC from next packet */ opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples)); output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 1); } else { /* regular decode */ output_samples = max_frame_size; output_samples = opus_decode(dec, data[1-toggle], len[1-toggle], out, output_samples, 0); } } else { output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 0); } if (output_samples>0) { if (!decode_only && tot_out + output_samples > tot_in) { stop=1; output_samples = (opus_int32)(tot_in - tot_out); } if (output_samples>skip) { int i; for(i=0;i<(output_samples-skip)*channels;i++) { short s; s=out[i+(skip*channels)]; fbytes[2*i]=s&0xFF; fbytes[2*i+1]=(s>>8)&0xFF; } if (fwrite(fbytes, sizeof(short)*channels, output_samples-skip, fout) != (unsigned)(output_samples-skip)){ fprintf(stderr, "Error writing.\n"); return EXIT_FAILURE; } tot_out += output_samples-skip; } if (output_samples<skip) skip -= output_samples; else skip = 0; } else { fprintf(stderr, "error decoding frame: %s\n", opus_strerror(output_samples)); } tot_samples += output_samples; } } if (!encode_only) opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE(&dec_final_range)); /* compare final range encoder rng values of encoder and decoder */ if( enc_final_range[toggle^use_inbandfec]!=0 && !encode_only && !lost && !lost_prev && dec_final_range != enc_final_range[toggle^use_inbandfec] ) { fprintf (stderr, "Error: Range coder state mismatch " "between encoder and decoder " "in frame %ld: 0x%8lx vs 0x%8lx\n", (long)count, (unsigned long)enc_final_range[toggle^use_inbandfec], (unsigned long)dec_final_range); fclose(fin); fclose(fout); return EXIT_FAILURE; } lost_prev = lost; if( count >= use_inbandfec ) { /* count bits */ bits += len[toggle]*8; bits_max = ( len[toggle]*8 > bits_max ) ? len[toggle]*8 : bits_max; bits2 += len[toggle]*len[toggle]*64; if (!decode_only) { nrg = 0.0; for ( k = 0; k < frame_size * channels; k++ ) { nrg += in[ k ] * (double)in[ k ]; } nrg /= frame_size * channels; if( nrg > 1e5 ) { bits_act += len[toggle]*8; count_act++; } } } count++; toggle = (toggle + use_inbandfec) & 1; } /* Print out bitrate statistics */ if(decode_only) frame_size = (int)(tot_samples / count); count -= use_inbandfec; fprintf (stderr, "average bitrate: %7.3f kb/s\n", 1e-3*bits*sampling_rate/tot_samples); fprintf (stderr, "maximum bitrate: %7.3f kb/s\n", 1e-3*bits_max*sampling_rate/frame_size); if (!decode_only) fprintf (stderr, "active bitrate: %7.3f kb/s\n", 1e-3*bits_act*sampling_rate/(1e-15+frame_size*(double)count_act)); fprintf (stderr, "bitrate standard deviation: %7.3f kb/s\n", 1e-3*sqrt(bits2/count - bits*bits/(count*(double)count))*sampling_rate/frame_size); silk_TimerSave("opus_timing.txt"); opus_encoder_destroy(enc); opus_decoder_destroy(dec); free(data[0]); if (use_inbandfec) free(data[1]); fclose(fin); fclose(fout); free(in); free(out); free(fbytes); return EXIT_SUCCESS; }
apache-2.0
AubrCool/rt-thread
bsp/gkipc/libraries/drv/710XS/gh/src/gh_vo_mixer1.c
22
61190
/****************************************************************************** ** ** \file gh_vo_mixer1.c ** ** \brief VO Mixer B access function. ** ** Copyright: 2012 - 2013 (C) GoKe Microelectronics ShangHai Branch ** ** \attention THIS SAMPLE CODE IS PROVIDED AS IS. GOKE MICROELECTRONICS ** ACCEPTS NO RESPONSIBILITY OR LIABILITY FOR ANY ERRORS OR ** OMMISSIONS. ** ** \note Do not modify this file as it is generated automatically. ** ******************************************************************************/ #include "gh_vo_mixer1.h" /*----------------------------------------------------------------------------*/ /* mirror variables */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_CONTROL (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_CONTROL(U32 data) { *(volatile U32 *)REG_VO_MIXER1_CONTROL = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_CONTROL] <-- 0x%08x\n", REG_VO_MIXER1_CONTROL,data,data); #endif } U32 GH_VO_MIXER1_get_CONTROL(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_CONTROL); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_CONTROL] --> 0x%08x\n", REG_VO_MIXER1_CONTROL,value); #endif return value; } void GH_VO_MIXER1_set_CONTROL_Reset(U8 data) { GH_VO_MIXER1_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_CONTROL; d.bitc.reset = data; *(volatile U32 *)REG_VO_MIXER1_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_CONTROL_Reset] <-- 0x%08x\n", REG_VO_MIXER1_CONTROL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_CONTROL_Reset(void) { GH_VO_MIXER1_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_CONTROL_Reset] --> 0x%08x\n", REG_VO_MIXER1_CONTROL,value); #endif return tmp_value.bitc.reset; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_STATUS (read) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 U32 GH_VO_MIXER1_get_STATUS(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_STATUS); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_STATUS] --> 0x%08x\n", REG_VO_MIXER1_STATUS,value); #endif return value; } U8 GH_VO_MIXER1_get_STATUS_Reset(void) { GH_VO_MIXER1_STATUS_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_STATUS); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_STATUS_Reset] --> 0x%08x\n", REG_VO_MIXER1_STATUS,value); #endif return tmp_value.bitc.reset; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_ACTIVE_SIZE (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_ACTIVE_SIZE(U32 data) { *(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ACTIVE_SIZE] <-- 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,data,data); #endif } U32 GH_VO_MIXER1_get_ACTIVE_SIZE(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ACTIVE_SIZE] --> 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,value); #endif return value; } void GH_VO_MIXER1_set_ACTIVE_SIZE_Vertical(U16 data) { GH_VO_MIXER1_ACTIVE_SIZE_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE; d.bitc.vertical = data; *(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ACTIVE_SIZE_Vertical] <-- 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_ACTIVE_SIZE_Vertical(void) { GH_VO_MIXER1_ACTIVE_SIZE_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ACTIVE_SIZE_Vertical] --> 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,value); #endif return tmp_value.bitc.vertical; } void GH_VO_MIXER1_set_ACTIVE_SIZE_Horizontal(U16 data) { GH_VO_MIXER1_ACTIVE_SIZE_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE; d.bitc.horizontal = data; *(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ACTIVE_SIZE_Horizontal] <-- 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_ACTIVE_SIZE_Horizontal(void) { GH_VO_MIXER1_ACTIVE_SIZE_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ACTIVE_SIZE); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ACTIVE_SIZE_Horizontal] --> 0x%08x\n", REG_VO_MIXER1_ACTIVE_SIZE,value); #endif return tmp_value.bitc.horizontal; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_VIDEO_START (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_VIDEO_START(U32 data) { *(volatile U32 *)REG_VO_MIXER1_VIDEO_START = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_START] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_START,data,data); #endif } U32 GH_VO_MIXER1_get_VIDEO_START(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_START); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_START] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_START,value); #endif return value; } void GH_VO_MIXER1_set_VIDEO_START_Vertical(U16 data) { GH_VO_MIXER1_VIDEO_START_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_VIDEO_START; d.bitc.vertical = data; *(volatile U32 *)REG_VO_MIXER1_VIDEO_START = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_START_Vertical] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_START,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_VIDEO_START_Vertical(void) { GH_VO_MIXER1_VIDEO_START_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_START); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_START_Vertical] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_START,value); #endif return tmp_value.bitc.vertical; } void GH_VO_MIXER1_set_VIDEO_START_Horizontal(U16 data) { GH_VO_MIXER1_VIDEO_START_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_VIDEO_START; d.bitc.horizontal = data; *(volatile U32 *)REG_VO_MIXER1_VIDEO_START = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_START_Horizontal] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_START,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_VIDEO_START_Horizontal(void) { GH_VO_MIXER1_VIDEO_START_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_START); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_START_Horizontal] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_START,value); #endif return tmp_value.bitc.horizontal; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_VIDEO_END (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_VIDEO_END(U32 data) { *(volatile U32 *)REG_VO_MIXER1_VIDEO_END = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_END] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_END,data,data); #endif } U32 GH_VO_MIXER1_get_VIDEO_END(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_END); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_END] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_END,value); #endif return value; } void GH_VO_MIXER1_set_VIDEO_END_Vertical(U16 data) { GH_VO_MIXER1_VIDEO_END_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_VIDEO_END; d.bitc.vertical = data; *(volatile U32 *)REG_VO_MIXER1_VIDEO_END = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_END_Vertical] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_END,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_VIDEO_END_Vertical(void) { GH_VO_MIXER1_VIDEO_END_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_END); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_END_Vertical] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_END,value); #endif return tmp_value.bitc.vertical; } void GH_VO_MIXER1_set_VIDEO_END_Horizontal(U16 data) { GH_VO_MIXER1_VIDEO_END_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_VIDEO_END; d.bitc.horizontal = data; *(volatile U32 *)REG_VO_MIXER1_VIDEO_END = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_VIDEO_END_Horizontal] <-- 0x%08x\n", REG_VO_MIXER1_VIDEO_END,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_VIDEO_END_Horizontal(void) { GH_VO_MIXER1_VIDEO_END_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_VIDEO_END); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_VIDEO_END_Horizontal] --> 0x%08x\n", REG_VO_MIXER1_VIDEO_END,value); #endif return tmp_value.bitc.horizontal; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_OSD_START (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_OSD_START(U32 data) { *(volatile U32 *)REG_VO_MIXER1_OSD_START = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_START] <-- 0x%08x\n", REG_VO_MIXER1_OSD_START,data,data); #endif } U32 GH_VO_MIXER1_get_OSD_START(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_START); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_START] --> 0x%08x\n", REG_VO_MIXER1_OSD_START,value); #endif return value; } void GH_VO_MIXER1_set_OSD_START_Vertical(U16 data) { GH_VO_MIXER1_OSD_START_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_START; d.bitc.vertical = data; *(volatile U32 *)REG_VO_MIXER1_OSD_START = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_START_Vertical] <-- 0x%08x\n", REG_VO_MIXER1_OSD_START,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_OSD_START_Vertical(void) { GH_VO_MIXER1_OSD_START_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_START); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_START_Vertical] --> 0x%08x\n", REG_VO_MIXER1_OSD_START,value); #endif return tmp_value.bitc.vertical; } void GH_VO_MIXER1_set_OSD_START_Horizontal(U16 data) { GH_VO_MIXER1_OSD_START_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_START; d.bitc.horizontal = data; *(volatile U32 *)REG_VO_MIXER1_OSD_START = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_START_Horizontal] <-- 0x%08x\n", REG_VO_MIXER1_OSD_START,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_OSD_START_Horizontal(void) { GH_VO_MIXER1_OSD_START_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_START); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_START_Horizontal] --> 0x%08x\n", REG_VO_MIXER1_OSD_START,value); #endif return tmp_value.bitc.horizontal; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_OSD_END (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_OSD_END(U32 data) { *(volatile U32 *)REG_VO_MIXER1_OSD_END = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_END] <-- 0x%08x\n", REG_VO_MIXER1_OSD_END,data,data); #endif } U32 GH_VO_MIXER1_get_OSD_END(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_END); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_END] --> 0x%08x\n", REG_VO_MIXER1_OSD_END,value); #endif return value; } void GH_VO_MIXER1_set_OSD_END_Vertical(U16 data) { GH_VO_MIXER1_OSD_END_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_END; d.bitc.vertical = data; *(volatile U32 *)REG_VO_MIXER1_OSD_END = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_END_Vertical] <-- 0x%08x\n", REG_VO_MIXER1_OSD_END,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_OSD_END_Vertical(void) { GH_VO_MIXER1_OSD_END_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_END); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_END_Vertical] --> 0x%08x\n", REG_VO_MIXER1_OSD_END,value); #endif return tmp_value.bitc.vertical; } void GH_VO_MIXER1_set_OSD_END_Horizontal(U16 data) { GH_VO_MIXER1_OSD_END_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_END; d.bitc.horizontal = data; *(volatile U32 *)REG_VO_MIXER1_OSD_END = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_END_Horizontal] <-- 0x%08x\n", REG_VO_MIXER1_OSD_END,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_OSD_END_Horizontal(void) { GH_VO_MIXER1_OSD_END_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_END); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_END_Horizontal] --> 0x%08x\n", REG_VO_MIXER1_OSD_END,value); #endif return tmp_value.bitc.horizontal; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_BACKGROUND (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_BACKGROUND(U32 data) { *(volatile U32 *)REG_VO_MIXER1_BACKGROUND = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_BACKGROUND] <-- 0x%08x\n", REG_VO_MIXER1_BACKGROUND,data,data); #endif } U32 GH_VO_MIXER1_get_BACKGROUND(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_BACKGROUND); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_BACKGROUND] --> 0x%08x\n", REG_VO_MIXER1_BACKGROUND,value); #endif return value; } void GH_VO_MIXER1_set_BACKGROUND_V(U8 data) { GH_VO_MIXER1_BACKGROUND_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_BACKGROUND; d.bitc.v = data; *(volatile U32 *)REG_VO_MIXER1_BACKGROUND = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_BACKGROUND_V] <-- 0x%08x\n", REG_VO_MIXER1_BACKGROUND,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_BACKGROUND_V(void) { GH_VO_MIXER1_BACKGROUND_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_BACKGROUND); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_BACKGROUND_V] --> 0x%08x\n", REG_VO_MIXER1_BACKGROUND,value); #endif return tmp_value.bitc.v; } void GH_VO_MIXER1_set_BACKGROUND_U(U8 data) { GH_VO_MIXER1_BACKGROUND_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_BACKGROUND; d.bitc.u = data; *(volatile U32 *)REG_VO_MIXER1_BACKGROUND = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_BACKGROUND_U] <-- 0x%08x\n", REG_VO_MIXER1_BACKGROUND,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_BACKGROUND_U(void) { GH_VO_MIXER1_BACKGROUND_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_BACKGROUND); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_BACKGROUND_U] --> 0x%08x\n", REG_VO_MIXER1_BACKGROUND,value); #endif return tmp_value.bitc.u; } void GH_VO_MIXER1_set_BACKGROUND_Y(U8 data) { GH_VO_MIXER1_BACKGROUND_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_BACKGROUND; d.bitc.y = data; *(volatile U32 *)REG_VO_MIXER1_BACKGROUND = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_BACKGROUND_Y] <-- 0x%08x\n", REG_VO_MIXER1_BACKGROUND,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_BACKGROUND_Y(void) { GH_VO_MIXER1_BACKGROUND_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_BACKGROUND); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_BACKGROUND_Y] --> 0x%08x\n", REG_VO_MIXER1_BACKGROUND,value); #endif return tmp_value.bitc.y; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_HIGHLIGHT (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_HIGHLIGHT(U32 data) { *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_HIGHLIGHT] <-- 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,data,data); #endif } U32 GH_VO_MIXER1_get_HIGHLIGHT(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_HIGHLIGHT] --> 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,value); #endif return value; } void GH_VO_MIXER1_set_HIGHLIGHT_V(U8 data) { GH_VO_MIXER1_HIGHLIGHT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT; d.bitc.v = data; *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_HIGHLIGHT_V] <-- 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_HIGHLIGHT_V(void) { GH_VO_MIXER1_HIGHLIGHT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_HIGHLIGHT_V] --> 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,value); #endif return tmp_value.bitc.v; } void GH_VO_MIXER1_set_HIGHLIGHT_U(U8 data) { GH_VO_MIXER1_HIGHLIGHT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT; d.bitc.u = data; *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_HIGHLIGHT_U] <-- 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_HIGHLIGHT_U(void) { GH_VO_MIXER1_HIGHLIGHT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_HIGHLIGHT_U] --> 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,value); #endif return tmp_value.bitc.u; } void GH_VO_MIXER1_set_HIGHLIGHT_Y(U8 data) { GH_VO_MIXER1_HIGHLIGHT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT; d.bitc.y = data; *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_HIGHLIGHT_Y] <-- 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_HIGHLIGHT_Y(void) { GH_VO_MIXER1_HIGHLIGHT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_HIGHLIGHT_Y] --> 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,value); #endif return tmp_value.bitc.y; } void GH_VO_MIXER1_set_HIGHLIGHT_threshold(U8 data) { GH_VO_MIXER1_HIGHLIGHT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT; d.bitc.threshold = data; *(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_HIGHLIGHT_threshold] <-- 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_HIGHLIGHT_threshold(void) { GH_VO_MIXER1_HIGHLIGHT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_HIGHLIGHT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_HIGHLIGHT_threshold] --> 0x%08x\n", REG_VO_MIXER1_HIGHLIGHT,value); #endif return tmp_value.bitc.threshold; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_OSD_CONTROL (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_OSD_CONTROL(U32 data) { *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,data,data); #endif } U32 GH_VO_MIXER1_get_OSD_CONTROL(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return value; } void GH_VO_MIXER1_set_OSD_CONTROL_Global_Blend(U8 data) { GH_VO_MIXER1_OSD_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL; d.bitc.global_blend = data; *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL_Global_Blend] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OSD_CONTROL_Global_Blend(void) { GH_VO_MIXER1_OSD_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL_Global_Blend] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return tmp_value.bitc.global_blend; } void GH_VO_MIXER1_set_OSD_CONTROL_Premultiplied(U8 data) { GH_VO_MIXER1_OSD_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL; d.bitc.premultiplied = data; *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL_Premultiplied] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OSD_CONTROL_Premultiplied(void) { GH_VO_MIXER1_OSD_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL_Premultiplied] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return tmp_value.bitc.premultiplied; } void GH_VO_MIXER1_set_OSD_CONTROL_Mode(U8 data) { GH_VO_MIXER1_OSD_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL; d.bitc.mode = data; *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL_Mode] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OSD_CONTROL_Mode(void) { GH_VO_MIXER1_OSD_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL_Mode] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return tmp_value.bitc.mode; } void GH_VO_MIXER1_set_OSD_CONTROL_Enable_Transparent_Color(U8 data) { GH_VO_MIXER1_OSD_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL; d.bitc.enable_transparent_color = data; *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL_Enable_Transparent_Color] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OSD_CONTROL_Enable_Transparent_Color(void) { GH_VO_MIXER1_OSD_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL_Enable_Transparent_Color] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return tmp_value.bitc.enable_transparent_color; } void GH_VO_MIXER1_set_OSD_CONTROL_Transparent_Color(U16 data) { GH_VO_MIXER1_OSD_CONTROL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL; d.bitc.transparent_color = data; *(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OSD_CONTROL_Transparent_Color] <-- 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,d.all,d.all); #endif } U16 GH_VO_MIXER1_get_OSD_CONTROL_Transparent_Color(void) { GH_VO_MIXER1_OSD_CONTROL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OSD_CONTROL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OSD_CONTROL_Transparent_Color] --> 0x%08x\n", REG_VO_MIXER1_OSD_CONTROL,value); #endif return tmp_value.bitc.transparent_color; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_ENABLE_CTRL (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_ENABLE_CTRL(U32 data) { *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ENABLE_CTRL] <-- 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,data,data); #endif } U32 GH_VO_MIXER1_get_ENABLE_CTRL(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ENABLE_CTRL] --> 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,value); #endif return value; } void GH_VO_MIXER1_set_ENABLE_CTRL_enable(U8 data) { GH_VO_MIXER1_ENABLE_CTRL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL; d.bitc.enable = data; *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ENABLE_CTRL_enable] <-- 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_ENABLE_CTRL_enable(void) { GH_VO_MIXER1_ENABLE_CTRL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ENABLE_CTRL_enable] --> 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,value); #endif return tmp_value.bitc.enable; } void GH_VO_MIXER1_set_ENABLE_CTRL_mapped_direct(U8 data) { GH_VO_MIXER1_ENABLE_CTRL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL; d.bitc.mapped_direct = data; *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ENABLE_CTRL_mapped_direct] <-- 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_ENABLE_CTRL_mapped_direct(void) { GH_VO_MIXER1_ENABLE_CTRL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ENABLE_CTRL_mapped_direct] --> 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,value); #endif return tmp_value.bitc.mapped_direct; } void GH_VO_MIXER1_set_ENABLE_CTRL_smem(U8 data) { GH_VO_MIXER1_ENABLE_CTRL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL; d.bitc.smem = data; *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ENABLE_CTRL_smem] <-- 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_ENABLE_CTRL_smem(void) { GH_VO_MIXER1_ENABLE_CTRL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ENABLE_CTRL_smem] --> 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,value); #endif return tmp_value.bitc.smem; } void GH_VO_MIXER1_set_ENABLE_CTRL_display(U8 data) { GH_VO_MIXER1_ENABLE_CTRL_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL; d.bitc.display = data; *(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_ENABLE_CTRL_display] <-- 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_ENABLE_CTRL_display(void) { GH_VO_MIXER1_ENABLE_CTRL_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_ENABLE_CTRL); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_ENABLE_CTRL_display] --> 0x%08x\n", REG_VO_MIXER1_ENABLE_CTRL,value); #endif return tmp_value.bitc.display; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_INPUT_VIDEO_SYNC (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_INPUT_VIDEO_SYNC(U32 data) { *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_INPUT_VIDEO_SYNC] <-- 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,data,data); #endif } U32 GH_VO_MIXER1_get_INPUT_VIDEO_SYNC(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_INPUT_VIDEO_SYNC] --> 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,value); #endif return value; } void GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_sync_mode(U8 data) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC; d.bitc.sync_mode = data; *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_sync_mode] <-- 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_sync_mode(void) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_sync_mode] --> 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,value); #endif return tmp_value.bitc.sync_mode; } void GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_line(U8 data) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC; d.bitc.line = data; *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_line] <-- 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_line(void) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_line] --> 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,value); #endif return tmp_value.bitc.line; } void GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_video(U8 data) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC; d.bitc.video = data; *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_video] <-- 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_video(void) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_video] --> 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,value); #endif return tmp_value.bitc.video; } void GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_decrement(U8 data) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC; d.bitc.decrement = data; *(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_INPUT_VIDEO_SYNC_decrement] <-- 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_decrement(void) { GH_VO_MIXER1_INPUT_VIDEO_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_INPUT_VIDEO_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_INPUT_VIDEO_SYNC_decrement] --> 0x%08x\n", REG_VO_MIXER1_INPUT_VIDEO_SYNC,value); #endif return tmp_value.bitc.decrement; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_OUTPUT_SYNC (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_OUTPUT_SYNC(U32 data) { *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,data,data); #endif } U32 GH_VO_MIXER1_get_OUTPUT_SYNC(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return value; } void GH_VO_MIXER1_set_OUTPUT_SYNC_sync_mode(U8 data) { GH_VO_MIXER1_OUTPUT_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC; d.bitc.sync_mode = data; *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC_sync_mode] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OUTPUT_SYNC_sync_mode(void) { GH_VO_MIXER1_OUTPUT_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC_sync_mode] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return tmp_value.bitc.sync_mode; } void GH_VO_MIXER1_set_OUTPUT_SYNC_number(U8 data) { GH_VO_MIXER1_OUTPUT_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC; d.bitc.number = data; *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC_number] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OUTPUT_SYNC_number(void) { GH_VO_MIXER1_OUTPUT_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC_number] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return tmp_value.bitc.number; } void GH_VO_MIXER1_set_OUTPUT_SYNC_counter(U8 data) { GH_VO_MIXER1_OUTPUT_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC; d.bitc.counter = data; *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC_counter] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OUTPUT_SYNC_counter(void) { GH_VO_MIXER1_OUTPUT_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC_counter] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return tmp_value.bitc.counter; } void GH_VO_MIXER1_set_OUTPUT_SYNC_sync(U8 data) { GH_VO_MIXER1_OUTPUT_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC; d.bitc.sync = data; *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC_sync] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OUTPUT_SYNC_sync(void) { GH_VO_MIXER1_OUTPUT_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC_sync] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return tmp_value.bitc.sync; } void GH_VO_MIXER1_set_OUTPUT_SYNC_frame(U8 data) { GH_VO_MIXER1_OUTPUT_SYNC_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC; d.bitc.frame = data; *(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_OUTPUT_SYNC_frame] <-- 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_OUTPUT_SYNC_frame(void) { GH_VO_MIXER1_OUTPUT_SYNC_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_OUTPUT_SYNC); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_OUTPUT_SYNC_frame] --> 0x%08x\n", REG_VO_MIXER1_OUTPUT_SYNC,value); #endif return tmp_value.bitc.frame; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_SMEM_INPUT (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_SMEM_INPUT(U32 data) { *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,data,data); #endif } U32 GH_VO_MIXER1_get_SMEM_INPUT(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return value; } void GH_VO_MIXER1_set_SMEM_INPUT_luma_number(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.luma_number = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_luma_number] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_luma_number(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_luma_number] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.luma_number; } void GH_VO_MIXER1_set_SMEM_INPUT_chroma_number(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.chroma_number = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_chroma_number] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_chroma_number(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_chroma_number] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.chroma_number; } void GH_VO_MIXER1_set_SMEM_INPUT_osd_number(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.osd_number = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_osd_number] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_osd_number(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_osd_number] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.osd_number; } void GH_VO_MIXER1_set_SMEM_INPUT_priority(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.priority = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_priority] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_priority(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_priority] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.priority; } void GH_VO_MIXER1_set_SMEM_INPUT_video_length(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.video_length = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_video_length] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_video_length(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_video_length] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.video_length; } void GH_VO_MIXER1_set_SMEM_INPUT_osd_length(U8 data) { GH_VO_MIXER1_SMEM_INPUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT; d.bitc.osd_length = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_INPUT_osd_length] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_INPUT_osd_length(void) { GH_VO_MIXER1_SMEM_INPUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_INPUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_INPUT_osd_length] --> 0x%08x\n", REG_VO_MIXER1_SMEM_INPUT,value); #endif return tmp_value.bitc.osd_length; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_SMEM_OUT (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_SMEM_OUT(U32 data) { *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_OUT] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,data,data); #endif } U32 GH_VO_MIXER1_get_SMEM_OUT(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_OUT); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_OUT] --> 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,value); #endif return value; } void GH_VO_MIXER1_set_SMEM_OUT_luma_number(U8 data) { GH_VO_MIXER1_SMEM_OUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT; d.bitc.luma_number = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_OUT_luma_number] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_OUT_luma_number(void) { GH_VO_MIXER1_SMEM_OUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_OUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_OUT_luma_number] --> 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,value); #endif return tmp_value.bitc.luma_number; } void GH_VO_MIXER1_set_SMEM_OUT_chroma_number(U8 data) { GH_VO_MIXER1_SMEM_OUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT; d.bitc.chroma_number = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_OUT_chroma_number] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_OUT_chroma_number(void) { GH_VO_MIXER1_SMEM_OUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_OUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_OUT_chroma_number] --> 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,value); #endif return tmp_value.bitc.chroma_number; } void GH_VO_MIXER1_set_SMEM_OUT_priority(U8 data) { GH_VO_MIXER1_SMEM_OUT_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT; d.bitc.priority = data; *(volatile U32 *)REG_VO_MIXER1_SMEM_OUT = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_SMEM_OUT_priority] <-- 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_SMEM_OUT_priority(void) { GH_VO_MIXER1_SMEM_OUT_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_SMEM_OUT); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_SMEM_OUT_priority] --> 0x%08x\n", REG_VO_MIXER1_SMEM_OUT,value); #endif return tmp_value.bitc.priority; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_FRAME_ENABLE (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_FRAME_ENABLE(U32 data) { *(volatile U32 *)REG_VO_MIXER1_FRAME_ENABLE = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_FRAME_ENABLE] <-- 0x%08x\n", REG_VO_MIXER1_FRAME_ENABLE,data,data); #endif } U32 GH_VO_MIXER1_get_FRAME_ENABLE(void) { U32 value = (*(volatile U32 *)REG_VO_MIXER1_FRAME_ENABLE); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_FRAME_ENABLE] --> 0x%08x\n", REG_VO_MIXER1_FRAME_ENABLE,value); #endif return value; } void GH_VO_MIXER1_set_FRAME_ENABLE_enable(U8 data) { GH_VO_MIXER1_FRAME_ENABLE_S d; d.all = *(volatile U32 *)REG_VO_MIXER1_FRAME_ENABLE; d.bitc.enable = data; *(volatile U32 *)REG_VO_MIXER1_FRAME_ENABLE = d.all; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_FRAME_ENABLE_enable] <-- 0x%08x\n", REG_VO_MIXER1_FRAME_ENABLE,d.all,d.all); #endif } U8 GH_VO_MIXER1_get_FRAME_ENABLE_enable(void) { GH_VO_MIXER1_FRAME_ENABLE_S tmp_value; U32 value = (*(volatile U32 *)REG_VO_MIXER1_FRAME_ENABLE); tmp_value.all = value; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_FRAME_ENABLE_enable] --> 0x%08x\n", REG_VO_MIXER1_FRAME_ENABLE,value); #endif return tmp_value.bitc.enable; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* register VO_MIXER1_CLUT_B (read/write) */ /*----------------------------------------------------------------------------*/ #if GH_INLINE_LEVEL == 0 void GH_VO_MIXER1_set_CLUT_B(U16 index, U32 data) { *(volatile U32 *)(REG_VO_MIXER1_CLUT_B + index * FIO_MOFFSET(VO_MIXER1,0x00000004)) = data; #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "WRREG(0x%08x,0x%08x); \\\\ [GH_VO_MIXER1_set_CLUT_B] <-- 0x%08x\n", (REG_VO_MIXER1_CLUT_B + index * FIO_MOFFSET(VO_MIXER1,0x00000004)),data,data); #endif } U32 GH_VO_MIXER1_get_CLUT_B(U16 index) { U32 value = (*(volatile U32 *)(REG_VO_MIXER1_CLUT_B + index * FIO_MOFFSET(VO_MIXER1,0x00000004))); #if GH_VO_MIXER1_ENABLE_DEBUG_PRINT GH_VO_MIXER1_DEBUG_PRINT_FUNCTION( "value = RDREG(0x%08x); \\\\ [GH_VO_MIXER1_get_CLUT_B] --> 0x%08x\n", (REG_VO_MIXER1_CLUT_B + index * FIO_MOFFSET(VO_MIXER1,0x00000004)),value); #endif return value; } #endif /* GH_INLINE_LEVEL == 0 */ /*----------------------------------------------------------------------------*/ /* init function */ /*----------------------------------------------------------------------------*/ void GH_VO_MIXER1_init(void) { int i; GH_VO_MIXER1_set_CONTROL((U32)0x00000000); GH_VO_MIXER1_set_ACTIVE_SIZE((U32)0x00000000); GH_VO_MIXER1_set_VIDEO_START((U32)0x00000000); GH_VO_MIXER1_set_VIDEO_END((U32)0x00000000); GH_VO_MIXER1_set_OSD_START((U32)0x00000000); GH_VO_MIXER1_set_OSD_END((U32)0x00000000); GH_VO_MIXER1_set_BACKGROUND((U32)0x00000000); GH_VO_MIXER1_set_HIGHLIGHT((U32)0xff000000); GH_VO_MIXER1_set_OSD_CONTROL((U32)0x000000ff); GH_VO_MIXER1_set_ENABLE_CTRL((U32)0x00000000); GH_VO_MIXER1_set_INPUT_VIDEO_SYNC((U32)0x00000000); GH_VO_MIXER1_set_OUTPUT_SYNC((U32)0x00000000); GH_VO_MIXER1_set_SMEM_INPUT((U32)0x00000000); GH_VO_MIXER1_set_SMEM_OUT((U32)0x00000000); GH_VO_MIXER1_set_FRAME_ENABLE((U32)0x00000000); GH_VO_MIXER1_set_CLUT_B(0, (U32)0x00000000); for (i=1; i<256; i++) { GH_VO_MIXER1_set_CLUT_B(i, (U32)0x00000000); } /* read read-clear registers in order to set mirror variables */ } /*----------------------------------------------------------------------------*/ /* end of file */ /*----------------------------------------------------------------------------*/
apache-2.0
msmolens/CTK
Plugins/org.commontk.eventadmin/dispatch/ctkEAThreadFactoryUser.cpp
25
1813
/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "ctkEAThreadFactoryUser_p.h" #include <QRunnable> ctkEAThreadFactoryUser::DefaultThread::DefaultThread(ctkEARunnable* command) : command(command) { } void ctkEAThreadFactoryUser::DefaultThread::run() { const bool autoDelete = command->autoDelete(); command->run(); if (autoDelete && !--command->ref) delete command; } ctkEAInterruptibleThread* ctkEAThreadFactoryUser::DefaultThreadFactory::newThread(ctkEARunnable* command) { return new DefaultThread(command); } ctkEAThreadFactoryUser::ctkEAThreadFactoryUser() : mutex(QMutex::Recursive), threadFactory(new DefaultThreadFactory()) { } ctkEAThreadFactoryUser::~ctkEAThreadFactoryUser() { delete threadFactory; } ctkEAThreadFactory* ctkEAThreadFactoryUser::setThreadFactory(ctkEAThreadFactory* factory) { QMutexLocker lock(&mutex); ctkEAThreadFactory* old = threadFactory; threadFactory = factory; return old; } ctkEAThreadFactory* ctkEAThreadFactoryUser::getThreadFactory() { return threadFactory; }
apache-2.0
pillip8282/TizenRT
os/kernel/environ/env_getenv.c
27
4790
/**************************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /**************************************************************************** * env_getenv.c * * Copyright (C) 2007, 2008, 2013 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #ifndef CONFIG_DISABLE_ENVIRON #include <sched.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "sched/sched.h" #include "environ/environ.h" /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: getenv * * Description: * The getenv() function searches the environment list for a string that * matches the string pointed to by name. * * Parameters: * name - The name of the variable to find. * * Return Value: * The value of the valiable (read-only) or NULL on failure * * Assumptions: * Not called from an interrupt handler * ****************************************************************************/ FAR char *getenv(const char *name) { FAR struct tcb_s *rtcb; FAR struct task_group_s *group; FAR char *pvar; FAR char *pvalue = NULL; int ret = OK; /* Verify that a string was passed */ if (!name) { ret = EINVAL; goto errout; } /* Get a reference to the thread-private environ in the TCB. */ sched_lock(); rtcb = this_task(); group = rtcb->group; /* Check if the variable exists */ if (!group || (pvar = env_findvar(group, name)) == NULL) { ret = ENOENT; goto errout_with_lock; } /* It does! Get the value sub-string from the name=value string */ pvalue = strchr(pvar, '='); if (!pvalue) { /* The name=value string has no '=' This is a bug! */ ret = EINVAL; goto errout_with_lock; } /* Adjust the pointer so that it points to the value right after the '=' */ pvalue++; sched_unlock(); return pvalue; errout_with_lock: sched_unlock(); errout: set_errno(ret); return NULL; } #endif /* CONFIG_DISABLE_ENVIRON */
apache-2.0
307509256/v2v
ffmpeg-jni/jni/include2/libavfilter/deshake_opencl.c
27
9538
/* * Copyright (C) 2013 Wei Gao <weigao@multicorewareinc.com> * Copyright (C) 2013 Lenny Wang * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * transform input video */ #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "deshake_opencl.h" #include "libavutil/opencl_internal.h" #define PLANE_NUM 3 #define ROUND_TO_16(a) (((((a) - 1)/16)+1)*16) int ff_opencl_transform(AVFilterContext *ctx, int width, int height, int cw, int ch, const float *matrix_y, const float *matrix_uv, enum InterpolateMethod interpolate, enum FillMethod fill, AVFrame *in, AVFrame *out) { int ret = 0; cl_int status; DeshakeContext *deshake = ctx->priv; float4 packed_matrix_lu = {matrix_y[0], matrix_y[1], matrix_y[2], matrix_y[5]}; float4 packed_matrix_ch = {matrix_uv[0], matrix_uv[1], matrix_uv[2], matrix_uv[5]}; size_t global_worksize_lu[2] = {(size_t)ROUND_TO_16(width), (size_t)ROUND_TO_16(height)}; size_t global_worksize_ch[2] = {(size_t)ROUND_TO_16(cw), (size_t)(2*ROUND_TO_16(ch))}; size_t local_worksize[2] = {16, 16}; FFOpenclParam param_lu = {0}; FFOpenclParam param_ch = {0}; param_lu.ctx = param_ch.ctx = ctx; param_lu.kernel = deshake->opencl_ctx.kernel_luma; param_ch.kernel = deshake->opencl_ctx.kernel_chroma; if ((unsigned int)interpolate > INTERPOLATE_BIQUADRATIC) { av_log(ctx, AV_LOG_ERROR, "Selected interpolate method is invalid\n"); return AVERROR(EINVAL); } ret = avpriv_opencl_set_parameter(&param_lu, FF_OPENCL_PARAM_INFO(deshake->opencl_ctx.cl_inbuf), FF_OPENCL_PARAM_INFO(deshake->opencl_ctx.cl_outbuf), FF_OPENCL_PARAM_INFO(packed_matrix_lu), FF_OPENCL_PARAM_INFO(interpolate), FF_OPENCL_PARAM_INFO(fill), FF_OPENCL_PARAM_INFO(in->linesize[0]), FF_OPENCL_PARAM_INFO(out->linesize[0]), FF_OPENCL_PARAM_INFO(height), FF_OPENCL_PARAM_INFO(width), NULL); if (ret < 0) return ret; ret = avpriv_opencl_set_parameter(&param_ch, FF_OPENCL_PARAM_INFO(deshake->opencl_ctx.cl_inbuf), FF_OPENCL_PARAM_INFO(deshake->opencl_ctx.cl_outbuf), FF_OPENCL_PARAM_INFO(packed_matrix_ch), FF_OPENCL_PARAM_INFO(interpolate), FF_OPENCL_PARAM_INFO(fill), FF_OPENCL_PARAM_INFO(in->linesize[0]), FF_OPENCL_PARAM_INFO(out->linesize[0]), FF_OPENCL_PARAM_INFO(in->linesize[1]), FF_OPENCL_PARAM_INFO(out->linesize[1]), FF_OPENCL_PARAM_INFO(height), FF_OPENCL_PARAM_INFO(width), FF_OPENCL_PARAM_INFO(ch), FF_OPENCL_PARAM_INFO(cw), NULL); if (ret < 0) return ret; status = clEnqueueNDRangeKernel(deshake->opencl_ctx.command_queue, deshake->opencl_ctx.kernel_luma, 2, NULL, global_worksize_lu, local_worksize, 0, NULL, NULL); status |= clEnqueueNDRangeKernel(deshake->opencl_ctx.command_queue, deshake->opencl_ctx.kernel_chroma, 2, NULL, global_worksize_ch, local_worksize, 0, NULL, NULL); if (status != CL_SUCCESS) { av_log(ctx, AV_LOG_ERROR, "OpenCL run kernel error occurred: %s\n", av_opencl_errstr(status)); return AVERROR_EXTERNAL; } ret = av_opencl_buffer_read_image(out->data, deshake->opencl_ctx.out_plane_size, deshake->opencl_ctx.plane_num, deshake->opencl_ctx.cl_outbuf, deshake->opencl_ctx.cl_outbuf_size); if (ret < 0) return ret; return ret; } int ff_opencl_deshake_init(AVFilterContext *ctx) { int ret = 0; DeshakeContext *deshake = ctx->priv; ret = av_opencl_init(NULL); if (ret < 0) return ret; deshake->opencl_ctx.plane_num = PLANE_NUM; deshake->opencl_ctx.command_queue = av_opencl_get_command_queue(); if (!deshake->opencl_ctx.command_queue) { av_log(ctx, AV_LOG_ERROR, "Unable to get OpenCL command queue in filter 'deshake'\n"); return AVERROR(EINVAL); } deshake->opencl_ctx.program = av_opencl_compile("avfilter_transform", NULL); if (!deshake->opencl_ctx.program) { av_log(ctx, AV_LOG_ERROR, "OpenCL failed to compile program 'avfilter_transform'\n"); return AVERROR(EINVAL); } if (!deshake->opencl_ctx.kernel_luma) { deshake->opencl_ctx.kernel_luma = clCreateKernel(deshake->opencl_ctx.program, "avfilter_transform_luma", &ret); if (ret != CL_SUCCESS) { av_log(ctx, AV_LOG_ERROR, "OpenCL failed to create kernel 'avfilter_transform_luma'\n"); return AVERROR(EINVAL); } } if (!deshake->opencl_ctx.kernel_chroma) { deshake->opencl_ctx.kernel_chroma = clCreateKernel(deshake->opencl_ctx.program, "avfilter_transform_chroma", &ret); if (ret != CL_SUCCESS) { av_log(ctx, AV_LOG_ERROR, "OpenCL failed to create kernel 'avfilter_transform_chroma'\n"); return AVERROR(EINVAL); } } return ret; } void ff_opencl_deshake_uninit(AVFilterContext *ctx) { DeshakeContext *deshake = ctx->priv; av_opencl_buffer_release(&deshake->opencl_ctx.cl_inbuf); av_opencl_buffer_release(&deshake->opencl_ctx.cl_outbuf); clReleaseKernel(deshake->opencl_ctx.kernel_luma); clReleaseKernel(deshake->opencl_ctx.kernel_chroma); clReleaseProgram(deshake->opencl_ctx.program); deshake->opencl_ctx.command_queue = NULL; av_opencl_uninit(); } int ff_opencl_deshake_process_inout_buf(AVFilterContext *ctx, AVFrame *in, AVFrame *out) { int ret = 0; AVFilterLink *link = ctx->inputs[0]; DeshakeContext *deshake = ctx->priv; const int hshift = av_pix_fmt_desc_get(link->format)->log2_chroma_h; int chroma_height = AV_CEIL_RSHIFT(link->h, hshift); if ((!deshake->opencl_ctx.cl_inbuf) || (!deshake->opencl_ctx.cl_outbuf)) { deshake->opencl_ctx.in_plane_size[0] = (in->linesize[0] * in->height); deshake->opencl_ctx.in_plane_size[1] = (in->linesize[1] * chroma_height); deshake->opencl_ctx.in_plane_size[2] = (in->linesize[2] * chroma_height); deshake->opencl_ctx.out_plane_size[0] = (out->linesize[0] * out->height); deshake->opencl_ctx.out_plane_size[1] = (out->linesize[1] * chroma_height); deshake->opencl_ctx.out_plane_size[2] = (out->linesize[2] * chroma_height); deshake->opencl_ctx.cl_inbuf_size = deshake->opencl_ctx.in_plane_size[0] + deshake->opencl_ctx.in_plane_size[1] + deshake->opencl_ctx.in_plane_size[2]; deshake->opencl_ctx.cl_outbuf_size = deshake->opencl_ctx.out_plane_size[0] + deshake->opencl_ctx.out_plane_size[1] + deshake->opencl_ctx.out_plane_size[2]; if (!deshake->opencl_ctx.cl_inbuf) { ret = av_opencl_buffer_create(&deshake->opencl_ctx.cl_inbuf, deshake->opencl_ctx.cl_inbuf_size, CL_MEM_READ_ONLY, NULL); if (ret < 0) return ret; } if (!deshake->opencl_ctx.cl_outbuf) { ret = av_opencl_buffer_create(&deshake->opencl_ctx.cl_outbuf, deshake->opencl_ctx.cl_outbuf_size, CL_MEM_READ_WRITE, NULL); if (ret < 0) return ret; } } ret = av_opencl_buffer_write_image(deshake->opencl_ctx.cl_inbuf, deshake->opencl_ctx.cl_inbuf_size, 0, in->data,deshake->opencl_ctx.in_plane_size, deshake->opencl_ctx.plane_num); if(ret < 0) return ret; return ret; }
apache-2.0
brightchen/Impala
thirdparty/openldap-2.4.25/servers/slapd/abandon.c
28
4067
/* abandon.c - decode and handle an ldap abandon operation */ /* $OpenLDAP: pkg/ldap/servers/slapd/abandon.c,v 1.52.2.9 2011/01/04 23:50:15 kurt Exp $ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 1998-2011 The OpenLDAP Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ /* Portions Copyright (c) 1995 Regents of the University of Michigan. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that this notice is preserved and that due credit is given * to the University of Michigan at Ann Arbor. The name of the University * may not be used to endorse or promote products derived from this * software without specific prior written permission. This software * is provided ``as is'' without express or implied warranty. */ #include "portable.h" #include <stdio.h> #include <ac/socket.h> #include "slap.h" int do_abandon( Operation *op, SlapReply *rs ) { ber_int_t id; Operation *o; const char *msg; Debug( LDAP_DEBUG_TRACE, "%s do_abandon\n", op->o_log_prefix, 0, 0 ); /* * Parse the abandon request. It looks like this: * * AbandonRequest := MessageID */ if ( ber_scanf( op->o_ber, "i", &id ) == LBER_ERROR ) { Debug( LDAP_DEBUG_ANY, "%s do_abandon: ber_scanf failed\n", op->o_log_prefix, 0, 0 ); send_ldap_discon( op, rs, LDAP_PROTOCOL_ERROR, "decoding error" ); return SLAPD_DISCONNECT; } Statslog( LDAP_DEBUG_STATS, "%s ABANDON msg=%ld\n", op->o_log_prefix, (long) id, 0, 0, 0 ); if( get_ctrls( op, rs, 0 ) != LDAP_SUCCESS ) { Debug( LDAP_DEBUG_ANY, "%s do_abandon: get_ctrls failed\n", op->o_log_prefix, 0, 0 ); return rs->sr_err; } Debug( LDAP_DEBUG_ARGS, "%s do_abandon: id=%ld\n", op->o_log_prefix, (long) id, 0 ); if( id <= 0 ) { Debug( LDAP_DEBUG_ANY, "%s do_abandon: bad msgid %ld\n", op->o_log_prefix, (long) id, 0 ); return LDAP_SUCCESS; } ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex ); /* Find the operation being abandoned. */ LDAP_STAILQ_FOREACH( o, &op->o_conn->c_ops, o_next ) { if ( o->o_msgid == id ) { break; } } if ( o == NULL ) { msg = "not found"; /* The operation is not active. Just discard it if found. */ LDAP_STAILQ_FOREACH( o, &op->o_conn->c_pending_ops, o_next ) { if ( o->o_msgid == id ) { msg = "discarded"; /* FIXME: This traverses c_pending_ops yet again. */ LDAP_STAILQ_REMOVE( &op->o_conn->c_pending_ops, o, Operation, o_next ); LDAP_STAILQ_NEXT(o, o_next) = NULL; op->o_conn->c_n_ops_pending--; slap_op_free( o, NULL ); break; } } } else if ( o->o_tag == LDAP_REQ_BIND || o->o_tag == LDAP_REQ_UNBIND || o->o_tag == LDAP_REQ_ABANDON ) { msg = "cannot be abandoned"; #if 0 /* Would break o_abandon used as "suppress response" flag, ITS#6138 */ } else if ( o->o_abandon ) { msg = "already being abandoned"; #endif } else { msg = "found"; /* Set the o_abandon flag in the to-be-abandoned operation. * The backend can periodically check this flag and abort the * operation at a convenient time. However it should "send" * the response anyway, with result code SLAPD_ABANDON. * The functions in result.c will intercept the message. */ o->o_abandon = 1; op->orn_msgid = id; op->o_bd = frontendDB; rs->sr_err = frontendDB->be_abandon( op, rs ); } ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex ); Debug( LDAP_DEBUG_TRACE, "%s do_abandon: op=%ld %s\n", op->o_log_prefix, (long) id, msg ); return rs->sr_err; } int fe_op_abandon( Operation *op, SlapReply *rs ) { LDAP_STAILQ_FOREACH( op->o_bd, &backendDB, be_next ) { if ( op->o_bd->be_abandon ) { (void)op->o_bd->be_abandon( op, rs ); } } return LDAP_SUCCESS; }
apache-2.0
BartokW/sagetv
third_party/mplayer/libavformat/flvdec.c
31
17274
/* * FLV demuxer * Copyright (c) 2003 The FFmpeg Project. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * * This demuxer will generate a 1 byte extradata for VP6F content. * It is composed of: * - upper 4bits: difference between encoded width and visible width * - lower 4bits: difference between encoded height and visible height */ #include "avformat.h" #include "flv.h" static int flv_probe(AVProbeData *p) { const uint8_t *d; if (p->buf_size < 6) return 0; d = p->buf; if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0) { return AVPROBE_SCORE_MAX; } return 0; } static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) { AVCodecContext *acodec = astream->codec; switch(flv_codecid) { //no distinction between S16 and S8 PCM codec flags case FLV_CODECID_PCM_BE: acodec->codec_id = acodec->bits_per_sample == 8 ? CODEC_ID_PCM_S8 : CODEC_ID_PCM_S16BE; break; case FLV_CODECID_PCM_LE: acodec->codec_id = acodec->bits_per_sample == 8 ? CODEC_ID_PCM_S8 : CODEC_ID_PCM_S16LE; break; case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break; case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = 1 ; break; case FLV_CODECID_NELLYMOSER_8HZ_MONO: acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate case FLV_CODECID_NELLYMOSER: default: av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET); acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET; } } static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) { AVCodecContext *vcodec = vstream->codec; switch(flv_codecid) { case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break; case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break; case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ; if(vcodec->extradata_size != 1) { vcodec->extradata_size = 1; vcodec->extradata = av_malloc(1); } vcodec->extradata[0] = get_byte(&s->pb); return 1; // 1 byte body size adjustment for flv_read_packet() default: av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid); vcodec->codec_tag = flv_codecid; } return 0; } static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) { int length = get_be16(ioc); if(length >= buffsize) { url_fskip(ioc, length); return -1; } get_buffer(ioc, buffer, length); buffer[length] = '\0'; return length; } static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, unsigned int max_pos, int depth) { AVCodecContext *acodec, *vcodec; ByteIOContext *ioc; AMFDataType amf_type; char str_val[256]; double num_val; num_val = 0; ioc = &s->pb; amf_type = get_byte(ioc); switch(amf_type) { case AMF_DATA_TYPE_NUMBER: num_val = av_int2dbl(get_be64(ioc)); break; case AMF_DATA_TYPE_BOOL: num_val = get_byte(ioc); break; case AMF_DATA_TYPE_STRING: if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0) return -1; break; case AMF_DATA_TYPE_OBJECT: { unsigned int keylen; while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) { url_fskip(ioc, keylen); //skip key string if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0) return -1; //if we couldn't skip, bomb out. } if(get_byte(ioc) != AMF_END_OF_OBJECT) return -1; } break; case AMF_DATA_TYPE_NULL: case AMF_DATA_TYPE_UNDEFINED: case AMF_DATA_TYPE_UNSUPPORTED: break; //these take up no additional space case AMF_DATA_TYPE_MIXEDARRAY: url_fskip(ioc, 4); //skip 32-bit max array index while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) { //this is the only case in which we would want a nested parse to not skip over the object if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0) return -1; } if(get_byte(ioc) != AMF_END_OF_OBJECT) return -1; break; case AMF_DATA_TYPE_ARRAY: { unsigned int arraylen, i; arraylen = get_be32(ioc); for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) { if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0) return -1; //if we couldn't skip, bomb out. } } break; case AMF_DATA_TYPE_DATE: url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16) break; default: //unsupported type, we couldn't skip return -1; } if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL acodec = astream ? astream->codec : NULL; vcodec = vstream ? vstream->codec : NULL; if(amf_type == AMF_DATA_TYPE_BOOL) { if(!strcmp(key, "stereo") && acodec) acodec->channels = num_val > 0 ? 2 : 1; } else if(amf_type == AMF_DATA_TYPE_NUMBER) { if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE; // else if(!strcmp(key, "width") && vcodec && num_val > 0) vcodec->width = num_val; // else if(!strcmp(key, "height") && vcodec && num_val > 0) vcodec->height = num_val; else if(!strcmp(key, "audiocodecid") && acodec) flv_set_audio_codec(s, astream, (int)num_val << FLV_AUDIO_CODECID_OFFSET); else if(!strcmp(key, "videocodecid") && vcodec) flv_set_video_codec(s, vstream, (int)num_val); else if(!strcmp(key, "audiosamplesize") && acodec && num_val >= 0) { acodec->bits_per_sample = num_val; //we may have to rewrite a previously read codecid because FLV only marks PCM endianness. if(num_val == 8 && (acodec->codec_id == CODEC_ID_PCM_S16BE || acodec->codec_id == CODEC_ID_PCM_S16LE)) acodec->codec_id = CODEC_ID_PCM_S8; } else if(!strcmp(key, "audiosamplerate") && acodec && num_val >= 0) { //some tools, like FLVTool2, write consistently approximate metadata sample rates switch((int)num_val) { case 44000: acodec->sample_rate = 44100 ; break; case 22000: acodec->sample_rate = 22050 ; break; case 11000: acodec->sample_rate = 11025 ; break; case 5000 : acodec->sample_rate = 5512 ; break; default : acodec->sample_rate = num_val; } } } } return 0; } static int flv_read_metabody(AVFormatContext *s, unsigned int next_pos) { AMFDataType type; AVStream *stream, *astream, *vstream; ByteIOContext *ioc; int i, keylen; char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want. astream = NULL; vstream = NULL; keylen = 0; ioc = &s->pb; //first object needs to be "onMetaData" string type = get_byte(ioc); if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData")) return -1; //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called. for(i = 0; i < s->nb_streams; i++) { stream = s->streams[i]; if (stream->codec->codec_type == CODEC_TYPE_AUDIO) astream = stream; else if(stream->codec->codec_type == CODEC_TYPE_VIDEO) vstream = stream; } //parse the second object (we want a mixed array) if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0) return -1; return 0; } static int flv_read_header(AVFormatContext *s, AVFormatParameters *ap) { int offset, flags; AVStream *st; url_fskip(&s->pb, 4); flags = get_byte(&s->pb); /* old flvtool cleared this field */ /* FIXME: better fix needed */ if (!flags) { flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO; av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n"); } if(flags & FLV_HEADER_FLAG_HASVIDEO){ st = av_new_stream(s, 0); if (!st) return AVERROR_NOMEM; st->codec->codec_type = CODEC_TYPE_VIDEO; av_set_pts_info(st, 24, 1, 1000); /* 24 bit pts in ms */ } if(flags & FLV_HEADER_FLAG_HASAUDIO){ st = av_new_stream(s, 1); if (!st) return AVERROR_NOMEM; st->codec->codec_type = CODEC_TYPE_AUDIO; av_set_pts_info(st, 24, 1, 1000); /* 24 bit pts in ms */ } offset = get_be32(&s->pb); url_fseek(&s->pb, offset, SEEK_SET); s->start_time = 0; return 0; } static int64_t flv_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit) { int64_t pos, pts; int type, size, flags; int extraBytes[6]; int pad; int i,j; #ifdef DEBUG_SEEK printf("FLV Seek stream_index=%d pos=0x%llx\n", stream_index, *pos_arg); #endif pos = *pos_arg; // Skip 4 bytes for the previous tag size or searching from a size one byte further will read back the same location url_fseek(&s->pb, pos + 4, SEEK_SET); for(;;) { // We may not be at a valid point in the stream if (url_feof(&s->pb)) return AV_NOPTS_VALUE; pos = url_ftell(&s->pb); if (pos >= pos_limit) return AV_NOPTS_VALUE; // To see if we're at a valid point we check to see if the type byte is valid // and if the padding is all zero. //prevTagSize = get_be32(&s->pb); type = get_byte(&s->pb); if (type != 8 && type != 9 && type != 18) { continue; } #ifdef DEBUG_SEEK printf("FLV Seek found potential type code=%d pos=0x%llx\n", type, pos); #endif for (i = 0; i < 6; i++) extraBytes[i] = get_byte(&s->pb); pad = 0; for (j = 0; j < 4 && !pad; j++) { pad = get_byte(&s->pb); if (pad != 0) { // Now we see if there were any valid type markers in the data we've read. If so // then we'll need to seek back to check that one out further. for (i = 0; i < 6; i++) { if (extraBytes[i] == 8 || extraBytes[i] == 9 || extraBytes[i] == 18) { #ifdef DEBUG_SEEK printf("FLV Seek found potential type ...skipping back code=%d pos=0x%llx\n", extraBytes[i], pos + 1 + i); #endif url_fseek(&s->pb, pos + 1 + i, SEEK_SET); break; } } if (i == 6 && (pad == 8 || pad == 9 || pad == 18)) { #ifdef DEBUG_SEEK printf("FLV Seek found potential type ...skipping back-2 code=%d pos=0x%llx\n", pad, pos + 7 + j); #endif url_fseek(&s->pb, pos + 7 + j, SEEK_SET); } } } if (pad) // bad packet continue; size = (extraBytes[0] << 16) + (extraBytes[1] << 8) + extraBytes[2]; pts = (extraBytes[3] << 16) + (extraBytes[4] << 8) + extraBytes[5]; #ifdef DEBUG_SEEK printf("FLV Seek found stream tag type code=%d size=%d pts=%d\n", type, size, pts); #endif // Check to see if the stream type matches if ((type == 8 && s->streams[stream_index]->id == 1) || (type == 9 && s->streams[stream_index]->id == 0)) { #ifdef DEBUG_SEEK printf("FLV Seek found matching stream index!\n"); #endif flags = get_byte(&s->pb); // Make sure it's a key frame! if (type == 8 || ((flags >> 4)==1)) { #ifdef DEBUG_SEEK printf("FLV Seek found keyframe!\n"); #endif // Found it! break; } url_fskip(&s->pb, size + 3); continue; } url_fskip(&s->pb, size + 4); } *pos_arg = pos - 4; // go back the previousTagSize data return pts; } static int flv_read_packet(AVFormatContext *s, AVPacket *pkt) { int ret, i, type, size, pts, flags, is_audio, next, pos; AVStream *st = NULL; for(;;){ pos = url_ftell(&s->pb); url_fskip(&s->pb, 4); /* size of previous packet */ type = get_byte(&s->pb); size = get_be24(&s->pb); pts = get_be24(&s->pb); // av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, pts:%d\n", type, size, pts); if (url_feof(&s->pb)) return AVERROR_IO; url_fskip(&s->pb, 4); /* reserved */ flags = 0; if(size == 0) continue; next= size + url_ftell(&s->pb); if (type == FLV_TAG_TYPE_AUDIO) { is_audio=1; flags = get_byte(&s->pb); } else if (type == FLV_TAG_TYPE_VIDEO) { is_audio=0; flags = get_byte(&s->pb); } else { if (type == FLV_TAG_TYPE_META && size > 13+1+4) flv_read_metabody(s, next); else /* skip packet */ av_log(s, AV_LOG_ERROR, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags); url_fseek(&s->pb, next, SEEK_SET); continue; } /* now find stream */ for(i=0;i<s->nb_streams;i++) { st = s->streams[i]; if (st->id == is_audio) break; } if(i == s->nb_streams){ av_log(NULL, AV_LOG_ERROR, "invalid stream\n"); url_fseek(&s->pb, next, SEEK_SET); continue; } // av_log(NULL, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard); if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio)) ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio)) || st->discard >= AVDISCARD_ALL ){ url_fseek(&s->pb, next, SEEK_SET); continue; } if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) av_add_index_entry(st, pos, pts, size, 0, AVINDEX_KEYFRAME); break; } // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps // NOTE: Narflex - do not read in the duration here because it requires seeking to the end of // the stream which may not work right for active files (and we can't detect that at this point since // it's not set yet). Besides, this duration isn't needed since it's also discovered when reading packets if(0 && !url_is_streamed(&s->pb)){ int size; const int pos= url_ftell(&s->pb); const int fsize= url_fsize(&s->pb); url_fseek(&s->pb, fsize-4, SEEK_SET); size= get_be32(&s->pb); url_fseek(&s->pb, fsize-3-size, SEEK_SET); if(size == get_be24(&s->pb) + 11){ s->duration= get_be24(&s->pb) * (int64_t)AV_TIME_BASE / 1000; } url_fseek(&s->pb, pos, SEEK_SET); } if(is_audio){ if(!st->codec->sample_rate || !st->codec->bits_per_sample || (!st->codec->codec_id && !st->codec->codec_tag)) { st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1; if((flags & FLV_AUDIO_CODECID_MASK) == FLV_CODECID_NELLYMOSER_8HZ_MONO) st->codec->sample_rate= 8000; else st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3); st->codec->bits_per_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8; flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK); } }else{ size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK); } ret= av_get_packet(&s->pb, pkt, size - 1); if (ret <= 0) { return AVERROR_IO; } /* note: we need to modify the packet size here to handle the last packet */ pkt->size = ret; pkt->pts = pts; pkt->stream_index = st->index; if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)) pkt->flags |= PKT_FLAG_KEY; return ret; } static int flv_read_close(AVFormatContext *s) { return 0; } AVInputFormat flv_demuxer = { "flv", "flv format", 0, flv_probe, flv_read_header, flv_read_packet, flv_read_close, NULL, flv_read_timestamp, .extensions = "flv", .value = CODEC_ID_FLV1, };
apache-2.0
jrmull/sagetv
third_party/mplayer/osdep/getch2-win.c
31
4802
/* windows TermIO for MPlayer (C) 2003 Sascha Sommer */ // See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp // for additional virtual keycodes #include "config.h" #include <stdio.h> #include <windows.h> #include "keycodes.h" #include "input/input.h" // HACK, stdin is used as something else below #undef stdin int mp_input_win32_slave_cmd_func(int fd,char* dest,int size){ DWORD retval, dw1, dw2; int i; HANDLE stdin = GetStdHandle(STD_INPUT_HANDLE); if(!PeekNamedPipe(stdin, dest, size, &retval, &dw1, &dw2) || !retval){ return MP_INPUT_NOTHING; } // Find the first \n and stop there so we don't miss any commands for (i = 0; i < retval; i++) { if (dest[i] == '\n') { retval = i + 1; break; } } if(retval>size)retval=size; ReadFile(stdin, dest, retval, &retval, NULL); // MPlayer likes \n terminated lines instead of \r\n terminated if (dest[retval - 2] == '\r') { dest[retval - 2] = '\n'; retval--; } dest[retval] = '\0'; if(retval)return retval; return MP_INPUT_NOTHING; } int screen_width=80; int screen_height=24; char * erase_to_end_of_line = NULL; void get_screen_size(){ } static HANDLE stdin; static int getch2_status=0; int getch2(int time){ INPUT_RECORD eventbuffer[128]; DWORD retval; int i=0; if(!getch2_status)return -1; /*check if there are input events*/ WaitForSingleObject(stdin, time); if(!GetNumberOfConsoleInputEvents(stdin,&retval)) { printf("getch2: can't get number of input events: %i\n",GetLastError()); return -1; } if(retval<=0)return -1; /*read all events*/ if(!ReadConsoleInput(stdin,eventbuffer,128,&retval)) { printf("getch: can't read input events\n"); return -1; } /*filter out keyevents*/ for (i = 0; i < retval; i++) { switch(eventbuffer[i].EventType) { case KEY_EVENT: /*only a pressed key is interresting for us*/ if(eventbuffer[i].Event.KeyEvent.bKeyDown == TRUE) { /*check for special keys*/ switch(eventbuffer[i].Event.KeyEvent.wVirtualKeyCode) { case VK_HOME: return KEY_HOME; case VK_END: return KEY_END; case VK_DELETE: return KEY_DEL; case VK_INSERT: return KEY_INS; case VK_BACK: return KEY_BS; case VK_PRIOR: return KEY_PGUP; case VK_NEXT: return KEY_PGDWN; case VK_RETURN: return KEY_ENTER; case VK_ESCAPE: return KEY_ESC; case VK_LEFT: return KEY_LEFT; case VK_UP: return KEY_UP; case VK_RIGHT: return KEY_RIGHT; case VK_DOWN: return KEY_DOWN; case VK_SHIFT: continue; } /*check for function keys*/ if(0x87 >= eventbuffer[i].Event.KeyEvent.wVirtualKeyCode && eventbuffer[i].Event.KeyEvent.wVirtualKeyCode >= 0x70) return (KEY_F + 1 + eventbuffer[i].Event.KeyEvent.wVirtualKeyCode - 0x70); /*only characters should be remaining*/ //printf("getch2: YOU PRESSED \"%c\" \n",eventbuffer[i].Event.KeyEvent.uChar.AsciiChar); return eventbuffer[i].Event.KeyEvent.uChar.AsciiChar; } break; case MOUSE_EVENT: case WINDOW_BUFFER_SIZE_EVENT: case FOCUS_EVENT: case MENU_EVENT: default: //printf("getch2: unsupported event type"); break; } } return -1; } void getch2_enable(){ DWORD retval; stdin = GetStdHandle(STD_INPUT_HANDLE); if(!GetNumberOfConsoleInputEvents(stdin,&retval)) { printf("getch2: %i can't get number of input events [disabling console input]\n",GetLastError()); getch2_status = 0; } else getch2_status=1; } void getch2_disable(){ if(!getch2_status) return; // already disabled / never enabled getch2_status=0; } #ifdef USE_ICONV static const struct { unsigned cp; char* alias; } cp_alias[] = { { 20127, "ASCII" }, { 20866, "KOI8-R" }, { 21866, "KOI8-RU" }, { 28591, "ISO-8859-1" }, { 28592, "ISO-8859-2" }, { 28593, "ISO-8859-3" }, { 28594, "ISO-8859-4" }, { 28595, "ISO-8859-5" }, { 28596, "ISO-8859-6" }, { 28597, "ISO-8859-7" }, { 28598, "ISO-8859-8" }, { 28599, "ISO-8859-9" }, { 28605, "ISO-8859-15" }, { 65001, "UTF-8" }, { 0, NULL } }; char* get_term_charset(void) { static char codepage[10]; unsigned i, cpno = GetConsoleOutputCP(); if (!cpno) cpno = GetACP(); if (!cpno) return NULL; for (i = 0; cp_alias[i].cp; i++) if (cpno == cp_alias[i].cp) return cp_alias[i].alias; snprintf(codepage, sizeof(codepage), "CP%u", cpno); return codepage; } #endif
apache-2.0
xiechengen/GearVRf
GVRf/Framework/jni/objects/components/orthogonal_camera_jni.cpp
31
6995
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************** * JNI ***************************************************************************/ #include "orthogonal_camera.h" #include "util/gvr_jni.h" namespace gvr { extern "C" { JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeOrthogonalCamera_ctor(JNIEnv * env, jobject obj); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getLeftClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setLeftClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat left); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getRightClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setRightClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat right); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getBottomClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setBottomClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat bottom); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getTopClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setTopClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat top); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getNearClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setNearClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat near); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getFarClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera); JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setFarClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat far); } ; JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeOrthogonalCamera_ctor(JNIEnv * env, jobject obj) { return reinterpret_cast<jlong>(new OrthogonalCamera()); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getLeftClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->left_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setLeftClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat left) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_near_clipping_distance(left); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getRightClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->right_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setRightClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat right) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_right_clipping_distance(right); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getBottomClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->bottom_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setBottomClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat bottom) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_bottom_clipping_distance(bottom); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getTopClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->top_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setTopClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat top) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_top_clipping_distance(top); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getNearClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->near_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setNearClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat near) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_near_clipping_distance(near); } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeOrthogonalCamera_getFarClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); return orthogonal_camera->far_clipping_distance(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeOrthogonalCamera_setFarClippingDistance( JNIEnv * env, jobject obj, jlong jorthogonal_camera, jfloat far) { OrthogonalCamera* orthogonal_camera = reinterpret_cast<OrthogonalCamera*>(jorthogonal_camera); orthogonal_camera->set_far_clipping_distance(far); } }
apache-2.0
efortuna/AndroidSDKClone
ndk_experimental/sources/cxx-stl/llvm-libc++/libcxx/test/localization/locale.categories/category.numeric/locale.nm.put/facet.num.put.members/put_unsigned_long.pass.cpp
34
12457
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // class num_put<charT, OutputIterator> // iter_type put(iter_type s, ios_base& iob, char_type fill, unsigned long v) const; #include <locale> #include <ios> #include <cassert> #include <streambuf> #include "test_iterators.h" typedef std::num_put<char, output_iterator<char*> > F; class my_facet : public F { public: explicit my_facet(std::size_t refs = 0) : F(refs) {} }; class my_numpunct : public std::numpunct<char> { public: my_numpunct() : std::numpunct<char>() {} protected: virtual char_type do_thousands_sep() const {return '_';} virtual std::string do_grouping() const {return std::string("\1\2\3");} }; int main() { const my_facet f(1); { std::ios ios(0); unsigned long v = 0; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0"); } { std::ios ios(0); unsigned long v = 1; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "1"); } { std::ios ios(0); unsigned long v = -1; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == (sizeof(unsigned long) == 4 ? "4294967295" : "18446744073709551615")); } { std::ios ios(0); unsigned long v = -1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == (sizeof(unsigned long) == 4 ? "4294966296" : "18446744073709550616")); } { std::ios ios(0); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "1000"); } { std::ios ios(0); showpos(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "1000"); } { std::ios ios(0); oct(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "1750"); } { std::ios ios(0); oct(ios); showbase(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "01750"); } { std::ios ios(0); hex(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "3e8"); } { std::ios ios(0); hex(ios); showbase(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0x3e8"); } { std::ios ios(0); hex(ios); showbase(ios); uppercase(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0X3E8"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); hex(ios); showbase(ios); uppercase(ios); unsigned long v = 1000; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0X3E_8"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); hex(ios); showbase(ios); unsigned long v = 2147483647; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0x7f_fff_ff_f"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); oct(ios); unsigned long v = 0123467; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "123_46_7"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); oct(ios); showbase(ios); unsigned long v = 0123467; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0_123_46_7"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); oct(ios); showbase(ios); right(ios); ios.width(15); unsigned long v = 0123467; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "*****0_123_46_7"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); oct(ios); showbase(ios); left(ios); ios.width(15); unsigned long v = 0123467; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0_123_46_7*****"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); oct(ios); showbase(ios); internal(ios); ios.width(15); unsigned long v = 0123467; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "*****0_123_46_7"); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); hex(ios); showbase(ios); right(ios); ios.width(15); unsigned long v = 2147483647; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "**0x7f_fff_ff_f"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); hex(ios); showbase(ios); left(ios); ios.width(15); unsigned long v = 2147483647; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0x7f_fff_ff_f**"); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); hex(ios); showbase(ios); internal(ios); ios.width(15); unsigned long v = 2147483647; char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "0x**7f_fff_ff_f"); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); showpos(ios); unsigned long v = 1000; right(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "****1_00_0"); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); showpos(ios); unsigned long v = 1000; left(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "1_00_0****"); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); showpos(ios); unsigned long v = 1000; internal(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == "****1_00_0"); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); unsigned long v = -1000; right(ios); showpos(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == (sizeof(unsigned long) == 4 ? "4_294_966_29_6" : "18_446_744_073_709_550_61_6")); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); unsigned long v = -1000; left(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == (sizeof(unsigned long) == 4 ? "4_294_966_29_6" : "18_446_744_073_709_550_61_6")); assert(ios.width() == 0); } { std::ios ios(0); ios.imbue(std::locale(std::locale::classic(), new my_numpunct)); unsigned long v = -1000; internal(ios); ios.width(10); char str[50]; std::ios_base::iostate err = ios.goodbit; output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v); std::string ex(str, iter.base()); assert(ex == (sizeof(unsigned long) == 4 ? "4_294_966_29_6" : "18_446_744_073_709_550_61_6")); assert(ios.width() == 0); } }
apache-2.0
mosaic-cloud/mosaic-distribution-dependencies
dependencies/mozilla-js/1.8.5/js/src/ctypes/libffi/testsuite/libffi.call/cls_multi_uchar.c
805
2279
/* Area: ffi_call, closure_call Purpose: Check passing of multiple unsigned char values. Limitations: none. PR: PR13221. Originator: <andreast@gcc.gnu.org> 20031129 */ /* { dg-do run } */ #include "ffitest.h" unsigned char test_func_fn(unsigned char a1, unsigned char a2, unsigned char a3, unsigned char a4) { unsigned char result; result = a1 + a2 + a3 + a4; printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result); return result; } static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, void *data __UNUSED__) { unsigned char a1, a2, a3, a4; a1 = *(unsigned char *)avals[0]; a2 = *(unsigned char *)avals[1]; a3 = *(unsigned char *)avals[2]; a4 = *(unsigned char *)avals[3]; *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4); } typedef unsigned char (*test_type)(unsigned char, unsigned char, unsigned char, unsigned char); void test_func(ffi_cif *cif __UNUSED__, void *rval __UNUSED__, void **avals, void *data __UNUSED__) { printf("%d %d %d %d\n", *(unsigned char *)avals[0], *(unsigned char *)avals[1], *(unsigned char *)avals[2], *(unsigned char *)avals[3]); } int main (void) { ffi_cif cif; void *code; ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); void * args_dbl[5]; ffi_type * cl_arg_types[5]; ffi_arg res_call; unsigned char a, b, c, d, res_closure; a = 1; b = 2; c = 127; d = 125; args_dbl[0] = &a; args_dbl[1] = &b; args_dbl[2] = &c; args_dbl[3] = &d; args_dbl[4] = NULL; cl_arg_types[0] = &ffi_type_uchar; cl_arg_types[1] = &ffi_type_uchar; cl_arg_types[2] = &ffi_type_uchar; cl_arg_types[3] = &ffi_type_uchar; cl_arg_types[4] = NULL; /* Initialize the cif */ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &ffi_type_uchar, cl_arg_types) == FFI_OK); ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); /* { dg-output "1 2 127 125: 255" } */ printf("res: %d\n", (unsigned char)res_call); /* { dg-output "\nres: 255" } */ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); res_closure = (*((test_type)code))(1, 2, 127, 125); /* { dg-output "\n1 2 127 125: 255" } */ printf("res: %d\n", res_closure); /* { dg-output "\nres: 255" } */ exit(0); }
apache-2.0
svogl/mbed-os
TESTS/mbed_drivers/echo/main.cpp
40
2125
/* * Copyright (c) 2013-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string.h> #include "mbed.h" #include "greentea-client/test_env.h" #include "unity/unity.h" #include "utest/utest.h" using namespace utest::v1; // Echo server (echo payload to host) template<int N> void test_case_echo_server_x() { char _key[10] = {}; char _value[128] = {}; const int echo_count = N; // Handshake with host greentea_send_kv("echo_count", echo_count); greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); TEST_ASSERT_EQUAL_INT(echo_count, atoi(_value)); for (int i=0; i < echo_count; ++i) { greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); greentea_send_kv(_key, _value); } } utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } Case cases[] = { Case("Echo server: x16", test_case_echo_server_x<16>, greentea_failure_handler), Case("Echo server: x32", test_case_echo_server_x<32>, greentea_failure_handler), Case("Echo server: x64", test_case_echo_server_x<64>, greentea_failure_handler), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(180, "echo"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); }
apache-2.0
tejas1996/mathrunner
tess-two/jni/com_googlecode_tesseract_android/src/cube/bmp_8.cpp
43
28231
/********************************************************************** * File: bmp_8.cpp * Description: Implementation of an 8-bit Bitmap class * Author: Ahmad Abdulkader * Created: 2007 * * (C) Copyright 2008, 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. * **********************************************************************/ #include <stdlib.h> #include <math.h> #include <cstring> #include <algorithm> #include "bmp_8.h" #include "con_comp.h" #include "platform.h" #ifdef USE_STD_NAMESPACE using std::min; using std::max; #endif namespace tesseract { const int Bmp8::kDeslantAngleCount = (1 + static_cast<int>(0.5f + (kMaxDeslantAngle - kMinDeslantAngle) / kDeslantAngleDelta)); float *Bmp8::tan_table_ = NULL; Bmp8::Bmp8(unsigned short wid, unsigned short hgt) : wid_(wid) , hgt_(hgt) { line_buff_ = CreateBmpBuffer(); } Bmp8::~Bmp8() { FreeBmpBuffer(line_buff_); } // free buffer void Bmp8::FreeBmpBuffer(unsigned char **buff) { if (buff != NULL) { if (buff[0] != NULL) { delete []buff[0]; } delete []buff; } } void Bmp8::FreeBmpBuffer(unsigned int **buff) { if (buff != NULL) { if (buff[0] != NULL) { delete []buff[0]; } delete []buff; } } // init bmp buffers unsigned char **Bmp8::CreateBmpBuffer(unsigned char init_val) { unsigned char **buff; // Check valid sizes if (!hgt_ || !wid_) return NULL; // compute stride (align on 4 byte boundries) stride_ = ((wid_ % 4) == 0) ? wid_ : (4 * (1 + (wid_ / 4))); buff = (unsigned char **) new unsigned char *[hgt_ * sizeof(*buff)]; if (!buff) { delete []buff; return NULL; } // alloc and init memory for buffer and line buffer buff[0] = (unsigned char *) new unsigned char[stride_ * hgt_ * sizeof(*buff[0])]; if (!buff[0]) { return NULL; } memset(buff[0], init_val, stride_ * hgt_ * sizeof(*buff[0])); for (int y = 1; y < hgt_; y++) { buff[y] = buff[y -1] + stride_; } return buff; } // init bmp buffers unsigned int ** Bmp8::CreateBmpBuffer(int wid, int hgt, unsigned char init_val) { unsigned int **buff; // compute stride (align on 4 byte boundries) buff = (unsigned int **) new unsigned int *[hgt * sizeof(*buff)]; if (!buff) { delete []buff; return NULL; } // alloc and init memory for buffer and line buffer buff[0] = (unsigned int *) new unsigned int[wid * hgt * sizeof(*buff[0])]; if (!buff[0]) { return NULL; } memset(buff[0], init_val, wid * hgt * sizeof(*buff[0])); for (int y = 1; y < hgt; y++) { buff[y] = buff[y -1] + wid; } return buff; } // clears the contents of the bmp bool Bmp8::Clear() { if (line_buff_ == NULL) { return false; } memset(line_buff_[0], 0xff, stride_ * hgt_ * sizeof(*line_buff_[0])); return true; } bool Bmp8::LoadFromCharDumpFile(CachedFile *fp) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // read and check 32 bit marker if (fp->Read(&val32, sizeof(val32)) != sizeof(val32)) { return false; } if (val32 != kMagicNumber) { return false; } // read wid and hgt if (fp->Read(&wid, sizeof(wid)) != sizeof(wid)) { return false; } if (fp->Read(&hgt, sizeof(hgt)) != sizeof(hgt)) { return false; } // read buf size if (fp->Read(&buf_size, sizeof(buf_size)) != sizeof(buf_size)) { return false; } // validate buf size: for now, only 3 channel (RBG) is supported pix_cnt = wid * hgt; if (buf_size != (3 * pix_cnt)) { return false; } // alloc memory & read the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } if (fp->Read(buff, buf_size) != buf_size) { delete []buff; return false; } // create internal buffers wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { delete []buff; return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (buff[pix] != buff[pix + 1] || buff[pix] != buff[pix + 2]) { delete []buff; return false; } line_buff_[y][x] = buff[pix]; } } // delete temp buffer delete[]buff; return true; } Bmp8 * Bmp8::FromCharDumpFile(CachedFile *fp) { // create a Bmp8 object Bmp8 *bmp_obj = new Bmp8(0, 0); if (bmp_obj == NULL) { return NULL; } if (bmp_obj->LoadFromCharDumpFile(fp) == false) { delete bmp_obj; return NULL; } return bmp_obj; } bool Bmp8::LoadFromCharDumpFile(FILE *fp) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // read and check 32 bit marker if (fread(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } if (val32 != kMagicNumber) { return false; } // read wid and hgt if (fread(&wid, 1, sizeof(wid), fp) != sizeof(wid)) { return false; } if (fread(&hgt, 1, sizeof(hgt), fp) != sizeof(hgt)) { return false; } // read buf size if (fread(&buf_size, 1, sizeof(buf_size), fp) != sizeof(buf_size)) { return false; } // validate buf size: for now, only 3 channel (RBG) is supported pix_cnt = wid * hgt; if (buf_size != (3 * pix_cnt)) { return false; } // alloc memory & read the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } if (fread(buff, 1, buf_size, fp) != buf_size) { delete []buff; return false; } // create internal buffers wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { delete []buff; return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (buff[pix] != buff[pix + 1] || buff[pix] != buff[pix + 2]) { delete []buff; return false; } line_buff_[y][x] = buff[pix]; } } // delete temp buffer delete[]buff; return true; } Bmp8 * Bmp8::FromCharDumpFile(FILE *fp) { // create a Bmp8 object Bmp8 *bmp_obj = new Bmp8(0, 0); if (bmp_obj == NULL) { return NULL; } if (bmp_obj->LoadFromCharDumpFile(fp) == false) { delete bmp_obj; return NULL; } return bmp_obj; } bool Bmp8::IsBlankColumn(int x) const { for (int y = 0; y < hgt_; y++) { if (line_buff_[y][x] != 0xff) { return false; } } return true; } bool Bmp8::IsBlankRow(int y) const { for (int x = 0; x < wid_; x++) { if (line_buff_[y][x] != 0xff) { return false; } } return true; } // crop the bitmap returning new dimensions void Bmp8::Crop(int *xst, int *yst, int *wid, int *hgt) { (*xst) = 0; (*yst) = 0; int xend = wid_ - 1; int yend = hgt_ - 1; while ((*xst) < (wid_ - 1) && (*xst) <= xend) { // column is not empty if (!IsBlankColumn((*xst))) { break; } (*xst)++; } while (xend > 0 && xend >= (*xst)) { // column is not empty if (!IsBlankColumn(xend)) { break; } xend--; } while ((*yst) < (hgt_ - 1) && (*yst) <= yend) { // column is not empty if (!IsBlankRow((*yst))) { break; } (*yst)++; } while (yend > 0 && yend >= (*yst)) { // column is not empty if (!IsBlankRow(yend)) { break; } yend--; } (*wid) = xend - (*xst) + 1; (*hgt) = yend - (*yst) + 1; } // generates a scaled bitmap with dimensions the new bmp will have the // same aspect ratio and will be centered in the box bool Bmp8::ScaleFrom(Bmp8 *bmp, bool isotropic) { int x_num; int x_denom; int y_num; int y_denom; int xoff; int yoff; int xsrc; int ysrc; int xdest; int ydest; int xst_src = 0; int yst_src = 0; int xend_src = bmp->wid_ - 1; int yend_src = bmp->hgt_ - 1; int wid_src; int hgt_src; // src dimensions wid_src = xend_src - xst_src + 1, hgt_src = yend_src - yst_src + 1; // scale to maintain aspect ratio if required if (isotropic) { if ((wid_ * hgt_src) > (hgt_ * wid_src)) { x_num = y_num = hgt_; x_denom = y_denom = hgt_src; } else { x_num = y_num = wid_; x_denom = y_denom = wid_src; } } else { x_num = wid_; y_num = hgt_; x_denom = wid_src; y_denom = hgt_src; } // compute offsets needed to center new bmp xoff = (wid_ - ((x_num * wid_src) / x_denom)) / 2; yoff = (hgt_ - ((y_num * hgt_src) / y_denom)) / 2; // scale up if (y_num > y_denom) { for (ydest = yoff; ydest < (hgt_ - yoff); ydest++) { // compute un-scaled y ysrc = static_cast<int>(0.5 + (1.0 * (ydest - yoff) * y_denom / y_num)); if (ysrc < 0 || ysrc >= hgt_src) { continue; } for (xdest = xoff; xdest < (wid_ - xoff); xdest++) { // compute un-scaled y xsrc = static_cast<int>(0.5 + (1.0 * (xdest - xoff) * x_denom / x_num)); if (xsrc < 0 || xsrc >= wid_src) { continue; } line_buff_[ydest][xdest] = bmp->line_buff_[ysrc + yst_src][xsrc + xst_src]; } } } else { // or scale down // scaling down is a bit tricky: we'll accumulate pixels // and then compute the means unsigned int **dest_line_buff = CreateBmpBuffer(wid_, hgt_, 0), **dest_pix_cnt = CreateBmpBuffer(wid_, hgt_, 0); for (ysrc = 0; ysrc < hgt_src; ysrc++) { // compute scaled y ydest = yoff + static_cast<int>(0.5 + (1.0 * ysrc * y_num / y_denom)); if (ydest < 0 || ydest >= hgt_) { continue; } for (xsrc = 0; xsrc < wid_src; xsrc++) { // compute scaled y xdest = xoff + static_cast<int>(0.5 + (1.0 * xsrc * x_num / x_denom)); if (xdest < 0 || xdest >= wid_) { continue; } dest_line_buff[ydest][xdest] += bmp->line_buff_[ysrc + yst_src][xsrc + xst_src]; dest_pix_cnt[ydest][xdest]++; } } for (ydest = 0; ydest < hgt_; ydest++) { for (xdest = 0; xdest < wid_; xdest++) { if (dest_pix_cnt[ydest][xdest] > 0) { unsigned int pixval = dest_line_buff[ydest][xdest] / dest_pix_cnt[ydest][xdest]; line_buff_[ydest][xdest] = (unsigned char) min((unsigned int)255, pixval); } } } // we no longer need these temp buffers FreeBmpBuffer(dest_line_buff); FreeBmpBuffer(dest_pix_cnt); } return true; } bool Bmp8::LoadFromRawData(unsigned char *data) { unsigned char *pline_data = data; // copy the data for (int y = 0; y < hgt_; y++, pline_data += wid_) { memcpy(line_buff_[y], pline_data, wid_ * sizeof(*pline_data)); } return true; } bool Bmp8::SaveBmp2CharDumpFile(FILE *fp) const { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // write and check 32 bit marker val32 = kMagicNumber; if (fwrite(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } // write wid and hgt wid = wid_; if (fwrite(&wid, 1, sizeof(wid), fp) != sizeof(wid)) { return false; } hgt = hgt_; if (fwrite(&hgt, 1, sizeof(hgt), fp) != sizeof(hgt)) { return false; } // write buf size pix_cnt = wid * hgt; buf_size = 3 * pix_cnt; if (fwrite(&buf_size, 1, sizeof(buf_size), fp) != sizeof(buf_size)) { return false; } // alloc memory & write the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { buff[pix] = buff[pix + 1] = buff[pix + 2] = line_buff_[y][x]; } } if (fwrite(buff, 1, buf_size, fp) != buf_size) { delete []buff; return false; } // delete temp buffer delete[]buff; return true; } // copy part of the specified bitmap to the top of the bitmap // does any necessary clipping void Bmp8::Copy(int x_st, int y_st, int wid, int hgt, Bmp8 *bmp_dest) const { int x_end = min(x_st + wid, static_cast<int>(wid_)), y_end = min(y_st + hgt, static_cast<int>(hgt_)); for (int y = y_st; y < y_end; y++) { for (int x = x_st; x < x_end; x++) { bmp_dest->line_buff_[y - y_st][x - x_st] = line_buff_[y][x]; } } } bool Bmp8::IsIdentical(Bmp8 *pBmp) const { if (wid_ != pBmp->wid_ || hgt_ != pBmp->hgt_) { return false; } for (int y = 0; y < hgt_; y++) { if (memcmp(line_buff_[y], pBmp->line_buff_[y], wid_) != 0) { return false; } } return true; } // Detect connected components in the bitmap ConComp ** Bmp8::FindConComps(int *concomp_cnt, int min_size) const { (*concomp_cnt) = 0; unsigned int **out_bmp_array = CreateBmpBuffer(wid_, hgt_, 0); if (out_bmp_array == NULL) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not allocate " "bitmap array\n"); return NULL; } // listed of connected components ConComp **concomp_array = NULL; int x; int y; int x_nbr; int y_nbr; int concomp_id; int alloc_concomp_cnt = 0; // neighbors to check const int nbr_cnt = 4; // relative coordinates of nbrs int x_del[nbr_cnt] = {-1, 0, 1, -1}, y_del[nbr_cnt] = {-1, -1, -1, 0}; for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // is this a foreground pix if (line_buff_[y][x] != 0xff) { int master_concomp_id = 0; ConComp *master_concomp = NULL; // checkout the nbrs for (int nbr = 0; nbr < nbr_cnt; nbr++) { x_nbr = x + x_del[nbr]; y_nbr = y + y_del[nbr]; if (x_nbr < 0 || y_nbr < 0 || x_nbr >= wid_ || y_nbr >= hgt_) { continue; } // is this nbr a foreground pix if (line_buff_[y_nbr][x_nbr] != 0xff) { // get its concomp ID concomp_id = out_bmp_array[y_nbr][x_nbr]; // this should not happen if (concomp_id < 1 || concomp_id > alloc_concomp_cnt) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): illegal " "connected component id: %d\n", concomp_id); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // if we has previously found a component then merge the two // and delete the latest one if (master_concomp != NULL && concomp_id != master_concomp_id) { // relabel all the pts ConCompPt *pt_ptr = concomp_array[concomp_id - 1]->Head(); while (pt_ptr != NULL) { out_bmp_array[pt_ptr->y()][pt_ptr->x()] = master_concomp_id; pt_ptr = pt_ptr->Next(); } // merge the two concomp if (!master_concomp->Merge(concomp_array[concomp_id - 1])) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "merge connected component: %d\n", concomp_id); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // delete the merged concomp delete concomp_array[concomp_id - 1]; concomp_array[concomp_id - 1] = NULL; } else { // this is the first concomp we encounter master_concomp_id = concomp_id; master_concomp = concomp_array[master_concomp_id - 1]; out_bmp_array[y][x] = master_concomp_id; if (!master_concomp->Add(x, y)) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "add connected component (%d,%d)\n", x, y); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } } } // foreground nbr } // nbrs // if there was no foreground pix, then create a new concomp if (master_concomp == NULL) { master_concomp = new ConComp(); if (master_concomp == NULL || master_concomp->Add(x, y) == false) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "allocate or add a connected component\n"); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // extend the list of concomps if needed if ((alloc_concomp_cnt % kConCompAllocChunk) == 0) { ConComp **temp_con_comp = new ConComp *[alloc_concomp_cnt + kConCompAllocChunk]; if (temp_con_comp == NULL) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "extend array of connected components\n"); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } if (alloc_concomp_cnt > 0) { memcpy(temp_con_comp, concomp_array, alloc_concomp_cnt * sizeof(*concomp_array)); delete []concomp_array; } concomp_array = temp_con_comp; } concomp_array[alloc_concomp_cnt++] = master_concomp; out_bmp_array[y][x] = alloc_concomp_cnt; } } // foreground pix } // x } // y // free the concomp bmp FreeBmpBuffer(out_bmp_array); if (alloc_concomp_cnt > 0 && concomp_array != NULL) { // scan the array of connected components and color // the o/p buffer with the corresponding concomps (*concomp_cnt) = 0; ConComp *concomp = NULL; for (int concomp_idx = 0; concomp_idx < alloc_concomp_cnt; concomp_idx++) { concomp = concomp_array[concomp_idx]; // found a concomp if (concomp != NULL) { // add the connected component if big enough if (concomp->PtCnt() > min_size) { concomp->SetLeftMost(true); concomp->SetRightMost(true); concomp->SetID((*concomp_cnt)); concomp_array[(*concomp_cnt)++] = concomp; } else { delete concomp; } } } } return concomp_array; } // precompute the tan table to speedup deslanting bool Bmp8::ComputeTanTable() { int ang_idx; float ang_val; // alloc memory for tan table delete []tan_table_; tan_table_ = new float[kDeslantAngleCount]; if (tan_table_ == NULL) { return false; } for (ang_idx = 0, ang_val = kMinDeslantAngle; ang_idx < kDeslantAngleCount; ang_idx++) { tan_table_[ang_idx] = tan(ang_val * M_PI / 180.0f); ang_val += kDeslantAngleDelta; } return true; } // generates a deslanted bitmap from the passed bitmap. bool Bmp8::Deslant() { int x; int y; int des_x; int des_y; int ang_idx; int best_ang; int min_des_x; int max_des_x; int des_wid; // only do deslanting if bitmap is wide enough // otherwise it slant estimate might not be reliable if (wid_ < (hgt_ * 2)) { return true; } // compute tan table if needed if (tan_table_ == NULL && !ComputeTanTable()) { return false; } // compute min and max values for x after deslant min_des_x = static_cast<int>(0.5f + (hgt_ - 1) * tan_table_[0]); max_des_x = (wid_ - 1) + static_cast<int>(0.5f + (hgt_ - 1) * tan_table_[kDeslantAngleCount - 1]); des_wid = max_des_x - min_des_x + 1; // alloc memory for histograms int **angle_hist = new int*[kDeslantAngleCount]; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { angle_hist[ang_idx] = new int[des_wid]; if (angle_hist[ang_idx] == NULL) { delete[] angle_hist; return false; } memset(angle_hist[ang_idx], 0, des_wid * sizeof(*angle_hist[ang_idx])); } // compute histograms for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { des_y = hgt_ - y - 1; // stamp all histograms for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { des_x = x + static_cast<int>(0.5f + (des_y * tan_table_[ang_idx])); if (des_x >= min_des_x && des_x <= max_des_x) { angle_hist[ang_idx][des_x - min_des_x]++; } } } } } // find the histogram with the lowest entropy float entropy; double best_entropy = 0.0f; double norm_val; best_ang = -1; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { entropy = 0.0f; for (x = min_des_x; x <= max_des_x; x++) { if (angle_hist[ang_idx][x - min_des_x] > 0) { norm_val = (1.0f * angle_hist[ang_idx][x - min_des_x] / hgt_); entropy += (-1.0f * norm_val * log(norm_val)); } } if (best_ang == -1 || entropy < best_entropy) { best_ang = ang_idx; best_entropy = entropy; } // free the histogram delete[] angle_hist[ang_idx]; } delete[] angle_hist; // deslant if (best_ang != -1) { unsigned char **dest_lines; int old_wid = wid_; // create a new buffer wid_ = des_wid; dest_lines = CreateBmpBuffer(); if (dest_lines == NULL) { return false; } for (y = 0; y < hgt_; y++) { for (x = 0; x < old_wid; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { des_y = hgt_ - y - 1; // compute new pos des_x = x + static_cast<int>(0.5f + (des_y * tan_table_[best_ang])); dest_lines[y][des_x - min_des_x] = 0; } } } // free old buffer FreeBmpBuffer(line_buff_); line_buff_ = dest_lines; } return true; } // Load dimensions & contents of bitmap from raw data bool Bmp8::LoadFromCharDumpFile(unsigned char **raw_data_ptr) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; unsigned char *raw_data = (*raw_data_ptr); int buf_size; int pix; unsigned int val32; // read and check 32 bit marker memcpy(&val32, raw_data, sizeof(val32)); raw_data += sizeof(val32); if (val32 != kMagicNumber) { return false; } // read wid and hgt memcpy(&wid, raw_data, sizeof(wid)); raw_data += sizeof(wid); memcpy(&hgt, raw_data, sizeof(hgt)); raw_data += sizeof(hgt); // read buf size memcpy(&buf_size, raw_data, sizeof(buf_size)); raw_data += sizeof(buf_size); // validate buf size: for now, only 3 channel (RBG) is supported if (buf_size != (3 * wid * hgt)) { return false; } wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (raw_data[pix] != raw_data[pix + 1] || raw_data[pix] != raw_data[pix + 2]) { return false; } line_buff_[y][x] = raw_data[pix]; } } (*raw_data_ptr) = raw_data + buf_size; return true; } float Bmp8::ForegroundRatio() const { int fore_cnt = 0; if (wid_ == 0 || hgt_ == 0) { return 1.0; } for (int y = 0; y < hgt_; y++) { for (int x = 0; x < wid_; x++) { fore_cnt += (line_buff_[y][x] == 0xff ? 0 : 1); } } return (1.0 * (fore_cnt / hgt_) / wid_); } // generates a deslanted bitmap from the passed bitmap bool Bmp8::HorizontalDeslant(double *deslant_angle) { int x; int y; int des_y; int ang_idx; int best_ang; int min_des_y; int max_des_y; int des_hgt; // compute tan table if necess. if (tan_table_ == NULL && !ComputeTanTable()) { return false; } // compute min and max values for x after deslant min_des_y = min(0, static_cast<int>((wid_ - 1) * tan_table_[0])); max_des_y = (hgt_ - 1) + max(0, static_cast<int>((wid_ - 1) * tan_table_[kDeslantAngleCount - 1])); des_hgt = max_des_y - min_des_y + 1; // alloc memory for histograms int **angle_hist = new int*[kDeslantAngleCount]; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { angle_hist[ang_idx] = new int[des_hgt]; if (angle_hist[ang_idx] == NULL) { delete[] angle_hist; return false; } memset(angle_hist[ang_idx], 0, des_hgt * sizeof(*angle_hist[ang_idx])); } // compute histograms for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { // stamp all histograms for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { des_y = y - static_cast<int>(x * tan_table_[ang_idx]); if (des_y >= min_des_y && des_y <= max_des_y) { angle_hist[ang_idx][des_y - min_des_y]++; } } } } } // find the histogram with the lowest entropy float entropy; float best_entropy = 0.0f; float norm_val; best_ang = -1; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { entropy = 0.0f; for (y = min_des_y; y <= max_des_y; y++) { if (angle_hist[ang_idx][y - min_des_y] > 0) { norm_val = (1.0f * angle_hist[ang_idx][y - min_des_y] / wid_); entropy += (-1.0f * norm_val * log(norm_val)); } } if (best_ang == -1 || entropy < best_entropy) { best_ang = ang_idx; best_entropy = entropy; } // free the histogram delete[] angle_hist[ang_idx]; } delete[] angle_hist; (*deslant_angle) = 0.0; // deslant if (best_ang != -1) { unsigned char **dest_lines; int old_hgt = hgt_; // create a new buffer min_des_y = min(0, static_cast<int>((wid_ - 1) * -tan_table_[best_ang])); max_des_y = (hgt_ - 1) + max(0, static_cast<int>((wid_ - 1) * -tan_table_[best_ang])); hgt_ = max_des_y - min_des_y + 1; dest_lines = CreateBmpBuffer(); if (dest_lines == NULL) { return false; } for (y = 0; y < old_hgt; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { // compute new pos des_y = y - static_cast<int>((x * tan_table_[best_ang])); dest_lines[des_y - min_des_y][x] = 0; } } } // free old buffer FreeBmpBuffer(line_buff_); line_buff_ = dest_lines; (*deslant_angle) = kMinDeslantAngle + (best_ang * kDeslantAngleDelta); } return true; } float Bmp8::MeanHorizontalHistogramEntropy() const { float entropy = 0.0f; // compute histograms for (int y = 0; y < hgt_; y++) { int pix_cnt = 0; for (int x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { pix_cnt++; } } if (pix_cnt > 0) { float norm_val = (1.0f * pix_cnt / wid_); entropy += (-1.0f * norm_val * log(norm_val)); } } return entropy / hgt_; } int *Bmp8::HorizontalHistogram() const { int *hist = new int[hgt_]; if (hist == NULL) { return NULL; } // compute histograms for (int y = 0; y < hgt_; y++) { hist[y] = 0; for (int x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { hist[y]++; } } } return hist; } } // namespace tesseract
apache-2.0
hak/android-ndk
gles3jni/app/src/main/jni/RendererES3.cpp
46
5247
/* * Copyright 2013 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. */ #include "gles3jni.h" #include <EGL/egl.h> #define STR(s) #s #define STRV(s) STR(s) #define POS_ATTRIB 0 #define COLOR_ATTRIB 1 #define SCALEROT_ATTRIB 2 #define OFFSET_ATTRIB 3 static const char VERTEX_SHADER[] = "#version 300 es\n" "layout(location = " STRV(POS_ATTRIB) ") in vec2 pos;\n" "layout(location=" STRV(COLOR_ATTRIB) ") in vec4 color;\n" "layout(location=" STRV(SCALEROT_ATTRIB) ") in vec4 scaleRot;\n" "layout(location=" STRV(OFFSET_ATTRIB) ") in vec2 offset;\n" "out vec4 vColor;\n" "void main() {\n" " mat2 sr = mat2(scaleRot.xy, scaleRot.zw);\n" " gl_Position = vec4(sr*pos + offset, 0.0, 1.0);\n" " vColor = color;\n" "}\n"; static const char FRAGMENT_SHADER[] = "#version 300 es\n" "precision mediump float;\n" "in vec4 vColor;\n" "out vec4 outColor;\n" "void main() {\n" " outColor = vColor;\n" "}\n"; class RendererES3: public Renderer { public: RendererES3(); virtual ~RendererES3(); bool init(); private: enum {VB_INSTANCE, VB_SCALEROT, VB_OFFSET, VB_COUNT}; virtual float* mapOffsetBuf(); virtual void unmapOffsetBuf(); virtual float* mapTransformBuf(); virtual void unmapTransformBuf(); virtual void draw(unsigned int numInstances); const EGLContext mEglContext; GLuint mProgram; GLuint mVB[VB_COUNT]; GLuint mVBState; }; Renderer* createES3Renderer() { RendererES3* renderer = new RendererES3; if (!renderer->init()) { delete renderer; return NULL; } return renderer; } RendererES3::RendererES3() : mEglContext(eglGetCurrentContext()), mProgram(0), mVBState(0) { for (int i = 0; i < VB_COUNT; i++) mVB[i] = 0; } bool RendererES3::init() { mProgram = createProgram(VERTEX_SHADER, FRAGMENT_SHADER); if (!mProgram) return false; glGenBuffers(VB_COUNT, mVB); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_INSTANCE]); glBufferData(GL_ARRAY_BUFFER, sizeof(QUAD), &QUAD[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_SCALEROT]); glBufferData(GL_ARRAY_BUFFER, MAX_INSTANCES * 4*sizeof(float), NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_OFFSET]); glBufferData(GL_ARRAY_BUFFER, MAX_INSTANCES * 2*sizeof(float), NULL, GL_STATIC_DRAW); glGenVertexArrays(1, &mVBState); glBindVertexArray(mVBState); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_INSTANCE]); glVertexAttribPointer(POS_ATTRIB, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, pos)); glVertexAttribPointer(COLOR_ATTRIB, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, rgba)); glEnableVertexAttribArray(POS_ATTRIB); glEnableVertexAttribArray(COLOR_ATTRIB); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_SCALEROT]); glVertexAttribPointer(SCALEROT_ATTRIB, 4, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0); glEnableVertexAttribArray(SCALEROT_ATTRIB); glVertexAttribDivisor(SCALEROT_ATTRIB, 1); glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_OFFSET]); glVertexAttribPointer(OFFSET_ATTRIB, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0); glEnableVertexAttribArray(OFFSET_ATTRIB); glVertexAttribDivisor(OFFSET_ATTRIB, 1); ALOGV("Using OpenGL ES 3.0 renderer"); return true; } RendererES3::~RendererES3() { /* The destructor may be called after the context has already been * destroyed, in which case our objects have already been destroyed. * * If the context exists, it must be current. This only happens when we're * cleaning up after a failed init(). */ if (eglGetCurrentContext() != mEglContext) return; glDeleteVertexArrays(1, &mVBState); glDeleteBuffers(VB_COUNT, mVB); glDeleteProgram(mProgram); } float* RendererES3::mapOffsetBuf() { glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_OFFSET]); return (float*)glMapBufferRange(GL_ARRAY_BUFFER, 0, MAX_INSTANCES * 2*sizeof(float), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); } void RendererES3::unmapOffsetBuf() { glUnmapBuffer(GL_ARRAY_BUFFER); } float* RendererES3::mapTransformBuf() { glBindBuffer(GL_ARRAY_BUFFER, mVB[VB_SCALEROT]); return (float*)glMapBufferRange(GL_ARRAY_BUFFER, 0, MAX_INSTANCES * 4*sizeof(float), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); } void RendererES3::unmapTransformBuf() { glUnmapBuffer(GL_ARRAY_BUFFER); } void RendererES3::draw(unsigned int numInstances) { glUseProgram(mProgram); glBindVertexArray(mVBState); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstances); }
apache-2.0
mbedmicro/mbed
connectivity/lwipstack/lwip/src/apps/snmp/lwip_snmpv3.c
47
3899
/** * @file * Additional SNMPv3 functionality RFC3414 and RFC3826. */ /* * Copyright (c) 2016 Elias Oenal. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * Author: Elias Oenal <lwip@eliasoenal.com> */ #include "snmpv3_priv.h" #include "lwip/apps/snmpv3.h" #include "lwip/sys.h" #include <string.h> #if LWIP_SNMP && LWIP_SNMP_V3 #ifdef LWIP_SNMPV3_INCLUDE_ENGINE #include LWIP_SNMPV3_INCLUDE_ENGINE #endif #define SNMP_MAX_TIME_BOOT 2147483647UL /** Call this if engine has been changed. Has to reset boots, see below */ void snmpv3_engine_id_changed(void) { snmpv3_set_engine_boots(0); } /** According to RFC3414 2.2.2. * * The number of times that the SNMP engine has * (re-)initialized itself since snmpEngineID * was last configured. */ s32_t snmpv3_get_engine_boots_internal(void) { if (snmpv3_get_engine_boots() == 0 || snmpv3_get_engine_boots() < SNMP_MAX_TIME_BOOT) { return snmpv3_get_engine_boots(); } snmpv3_set_engine_boots(SNMP_MAX_TIME_BOOT); return snmpv3_get_engine_boots(); } /** RFC3414 2.2.2. * * Once the timer reaches 2147483647 it gets reset to zero and the * engine boot ups get incremented. */ s32_t snmpv3_get_engine_time_internal(void) { if (snmpv3_get_engine_time() >= SNMP_MAX_TIME_BOOT) { snmpv3_reset_engine_time(); if (snmpv3_get_engine_boots() < SNMP_MAX_TIME_BOOT - 1) { snmpv3_set_engine_boots(snmpv3_get_engine_boots() + 1); } else { snmpv3_set_engine_boots(SNMP_MAX_TIME_BOOT); } } return snmpv3_get_engine_time(); } #if LWIP_SNMP_V3_CRYPTO /* This function ignores the byte order suggestion in RFC3414 * since it simply doesn't influence the effectiveness of an IV. * * Implementing RFC3826 priv param algorithm if LWIP_RAND is available. * * @todo: This is a potential thread safety issue. */ err_t snmpv3_build_priv_param(u8_t *priv_param) { #ifdef LWIP_RAND /* Based on RFC3826 */ static u8_t init; static u32_t priv1, priv2; /* Lazy initialisation */ if (init == 0) { init = 1; priv1 = LWIP_RAND(); priv2 = LWIP_RAND(); } SMEMCPY(&priv_param[0], &priv1, sizeof(priv1)); SMEMCPY(&priv_param[4], &priv2, sizeof(priv2)); /* Emulate 64bit increment */ priv1++; if (!priv1) { /* Overflow */ priv2++; } #else /* Based on RFC3414 */ static u32_t ctr; u32_t boots = snmpv3_get_engine_boots_internal(); SMEMCPY(&priv_param[0], &boots, 4); SMEMCPY(&priv_param[4], &ctr, 4); ctr++; #endif return ERR_OK; } #endif /* LWIP_SNMP_V3_CRYPTO */ #endif
apache-2.0
kartben/iotivity
extlibs/tinydtls/ecc/test_helper.c
48
2790
/* * Copyright (c) 2009 Chris K Cockrum <ckc@cockrum.net> * * Copyright (c) 2013 Jens Trillmann <jtrillma@tzi.de> * Copyright (c) 2013 Marc Müller-Weinhardt <muewei@tzi.de> * Copyright (c) 2013 Lars Schmertmann <lars@tzi.de> * Copyright (c) 2013 Hauke Mehrtens <hauke@hauke-m.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * This implementation is based in part on the paper Implementation of an * Elliptic Curve Cryptosystem on an 8-bit Microcontroller [0] by * Chris K Cockrum <ckc@cockrum.net>. * * [0]: http://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf * * This is a efficient ECC implementation on the secp256r1 curve for 32 Bit CPU * architectures. It provides basic operations on the secp256r1 curve and support * for ECDH and ECDSA. */ #include "test_helper.h" #include "ecc.h" #include <string.h> #include <stdio.h> #include <stdlib.h> void ecc_printNumber(const uint32_t *x, int numberLength){ //here the values are turned to MSB! int n; for(n = numberLength - 1; n >= 0; n--){ printf("%08x", x[n]); } printf("\n"); } void ecc_setRandom(uint32_t *secret){ int i; for (i = 0; i < arrayLength; ++i) { secret[i] = rand(); } } const uint32_t ecc_prime_m[8] = {0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xffffffff}; /* This is added after an static byte addition if the answer has a carry in MSB*/ const uint32_t ecc_prime_r[8] = {0x00000001, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe, 0x00000000}; #ifdef CONTIKI void test_assert(const char *file, int lineno) { printf("Assertion failed: file %s, line %d.\n", file, lineno); /* * loop for a while; * call _reset_vector__(); */ } #endif
apache-2.0
sitexa/otp
lib/erl_interface/src/decode/decode_pid.c
49
1240
/* * %CopyrightBegin% * * Copyright Ericsson AB 1998-2013. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #include <string.h> #include "eidef.h" #include "eiext.h" #include "putget.h" int ei_decode_pid(const char *buf, int *index, erlang_pid *p) { const char *s = buf + *index; const char *s0 = s; if (get8(s) != ERL_PID_EXT) return -1; if (p) { if (get_atom(&s, p->node, NULL) < 0) return -1; p->num = get32be(s) & 0x7fff; /* 15 bits */ p->serial = get32be(s) & 0x1fff; /* 13 bits */ p->creation = get8(s) & 0x03; /* 2 bits */ } else { if (get_atom(&s, NULL, NULL) < 0) return -1; s+= 9; } *index += s-s0; return 0; }
apache-2.0
yawnosnorous/python-for-android
python3-alpha/ncurses-5.9/form/fld_max.c
51
3702
/**************************************************************************** * Copyright (c) 1998-2004,2010 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1995,1997 * ****************************************************************************/ #include "form.priv.h" MODULE_ID("$Id: fld_max.c,v 1.10 2010/01/23 21:14:36 tom Exp $") /*--------------------------------------------------------------------------- | Facility : libnform | Function : int set_max_field(FIELD *field, int maxgrow) | | Description : Set the maximum growth for a dynamic field. If maxgrow=0 | the field may grow to any possible size. | | Return Values : E_OK - success | E_BAD_ARGUMENT - invalid argument +--------------------------------------------------------------------------*/ NCURSES_EXPORT(int) set_max_field(FIELD *field, int maxgrow) { T((T_CALLED("set_max_field(%p,%d)"), (void *)field, maxgrow)); if (!field || (maxgrow < 0)) RETURN(E_BAD_ARGUMENT); else { bool single_line_field = Single_Line_Field(field); if (maxgrow > 0) { if ((single_line_field && (maxgrow < field->dcols)) || (!single_line_field && (maxgrow < field->drows))) RETURN(E_BAD_ARGUMENT); } field->maxgrow = maxgrow; field->status &= ~_MAY_GROW; if (!(field->opts & O_STATIC)) { if ((maxgrow == 0) || (single_line_field && (field->dcols < maxgrow)) || (!single_line_field && (field->drows < maxgrow))) field->status |= _MAY_GROW; } } RETURN(E_OK); } /* fld_max.c ends here */
apache-2.0
Yeolar/coral-folly
folly/experimental/io/test/FsUtilTest.cpp
53
2567
/* * Copyright 2015 Facebook, 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. */ #include <folly/experimental/io/FsUtil.h> #include <glog/logging.h> #include <gtest/gtest.h> using namespace folly; using namespace folly::fs; namespace { // We cannot use EXPECT_EQ(a, b) due to a bug in gtest 1.6.0: gtest wants // to print path as a container even though it has operator<< defined, // and as path is a container of path, this leads to infinite // recursion. void expectPathEq(const path& a, const path& b) { EXPECT_TRUE(a == b) << "expected path=" << a << "\nactual path=" << b; } } // namespace TEST(Simple, Path) { path root("/"); path abs1("/hello/world"); path rel1("meow"); EXPECT_TRUE(starts_with(abs1, root)); EXPECT_FALSE(starts_with(rel1, root)); expectPathEq(path("hello/world"), remove_prefix(abs1, root)); EXPECT_THROW({remove_prefix(rel1, root);}, filesystem_error); path abs2("/hello"); path abs3("/hello/"); path abs4("/hello/world"); path abs5("/hello/world/"); path abs6("/hello/wo"); EXPECT_TRUE(starts_with(abs1, abs2)); EXPECT_TRUE(starts_with(abs1, abs3)); EXPECT_TRUE(starts_with(abs1, abs4)); EXPECT_FALSE(starts_with(abs1, abs5)); EXPECT_FALSE(starts_with(abs1, abs6)); expectPathEq(path("world"), remove_prefix(abs1, abs2)); expectPathEq(path("world"), remove_prefix(abs1, abs3)); expectPathEq(path(), remove_prefix(abs1, abs4)); EXPECT_THROW({remove_prefix(abs1, abs5);}, filesystem_error); EXPECT_THROW({remove_prefix(abs1, abs6);}, filesystem_error); } TEST(Simple, CanonicalizeParent) { path a("/usr/bin/tail"); path b("/usr/lib/../bin/tail"); path c("/usr/bin/DOES_NOT_EXIST_ASDF"); path d("/usr/lib/../bin/DOES_NOT_EXIST_ASDF"); expectPathEq(a, canonical(a)); expectPathEq(a, canonical_parent(b)); expectPathEq(a, canonical(b)); expectPathEq(a, canonical_parent(b)); EXPECT_THROW({canonical(c);}, filesystem_error); EXPECT_THROW({canonical(d);}, filesystem_error); expectPathEq(c, canonical_parent(c)); expectPathEq(c, canonical_parent(d)); }
apache-2.0
loversInJapan/folly
folly/test/SpookyHashV1Test.cpp
54
17654
/* * Copyright 2015 Facebook, 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. */ // SpookyHash: a 128-bit noncryptographic hash function // By Bob Jenkins, public domain #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif #include <folly/SpookyHashV1.h> #include <folly/Benchmark.h> #include <cinttypes> #include <cstdio> #include <cstddef> #include <cstring> #include <cstdlib> #include <ctime> #include <gtest/gtest.h> using namespace ::folly::hash; static bool failed = false; static uint64_t GetTickCount() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; // milliseconds } class Random { public: inline uint64_t Value() { uint64_t e = m_a - Rot64(m_b, 23); m_a = m_b ^ Rot64(m_c, 16); m_b = m_c + Rot64(m_d, 11); m_c = m_d + e; m_d = e + m_a; return m_d; } inline void Init( uint64_t seed) { m_a = 0xdeadbeef; m_b = m_c = m_d = seed; for (int i=0; i<20; ++i) (void)Value(); } private: static inline uint64_t Rot64(uint64_t x, int k) { return (x << k) | (x >> (64-(k))); } uint64_t m_a; uint64_t m_b; uint64_t m_c; uint64_t m_d; }; // fastest conceivable hash function (for comparison) static void Add(const void *data, size_t length, uint64_t *hash1, uint64_t *hash2) { uint64_t *p64 = (uint64_t *)data; uint64_t *end = p64 + length/8; uint64_t hash = *hash1 + *hash2; while (p64 < end) { hash += *p64; ++p64; } *hash1 = hash; *hash2 = hash; } #define BUFSIZE (512) void TestResults() { printf("\ntesting results ...\n"); static const uint32_t expected[BUFSIZE] = { 0xa24295ec, 0xfe3a05ce, 0x257fd8ef, 0x3acd5217, 0xfdccf85c, 0xc7b5f143, 0x3b0c3ff0, 0x5220f13c, 0xa6426724, 0x4d5426b4, 0x43e76b26, 0x051bc437, 0xd8f28a02, 0x23ccc30e, 0x811d1a2d, 0x039128d4, 0x9cd96a73, 0x216e6a8d, 0x97293fe8, 0xe4fc6d09, 0x1ad34423, 0x9722d7e4, 0x5a6fdeca, 0x3c94a7e1, 0x81a9a876, 0xae3f7c0e, 0x624b50ee, 0x875e5771, 0x0095ab74, 0x1a7333fb, 0x056a4221, 0xa38351fa, 0x73f575f1, 0x8fded05b, 0x9097138f, 0xbd74620c, 0x62d3f5f2, 0x07b78bd0, 0xbafdd81e, 0x0638f2ff, 0x1f6e3aeb, 0xa7786473, 0x71700e1d, 0x6b4625ab, 0xf02867e1, 0xb2b2408f, 0x9ce21ce5, 0xa62baaaf, 0x26720461, 0x434813ee, 0x33bc0f14, 0xaaab098a, 0x750af488, 0xc31bf476, 0x9cecbf26, 0x94793cf3, 0xe1a27584, 0xe80c4880, 0x1299f748, 0x25e55ed2, 0x405e3feb, 0x109e2412, 0x3e55f94f, 0x59575864, 0x365c869d, 0xc9852e6a, 0x12c30c62, 0x47f5b286, 0xb47e488d, 0xa6667571, 0x78220d67, 0xa49e30b9, 0x2005ef88, 0xf6d3816d, 0x6926834b, 0xe6116805, 0x694777aa, 0x464af25b, 0x0e0e2d27, 0x0ea92eae, 0x602c2ca9, 0x1d1d79c5, 0x6364f280, 0x939ee1a4, 0x3b851bd8, 0x5bb6f19f, 0x80b9ed54, 0x3496a9f1, 0xdf815033, 0x91612339, 0x14c516d6, 0xa3f0a804, 0x5e78e975, 0xf408bcd9, 0x63d525ed, 0xa1e459c3, 0xfde303af, 0x049fc17f, 0xe7ed4489, 0xfaeefdb6, 0x2b1b2fa8, 0xc67579a6, 0x5505882e, 0xe3e1c7cb, 0xed53bf30, 0x9e628351, 0x8fa12113, 0x7500c30f, 0xde1bee00, 0xf1fefe06, 0xdc759c00, 0x4c75e5ab, 0xf889b069, 0x695bf8ae, 0x47d6600f, 0xd2a84f87, 0xa0ca82a9, 0x8d2b750c, 0xe03d8cd7, 0x581fea33, 0x969b0460, 0x36c7b7de, 0x74b3fd20, 0x2bb8bde6, 0x13b20dec, 0xa2dcee89, 0xca36229d, 0x06fdb74e, 0x6d9a982d, 0x02503496, 0xbdb4e0d9, 0xbd1f94cf, 0x6d26f82d, 0xcf5e41cd, 0x88b67b65, 0x3e1b3ee4, 0xb20e5e53, 0x1d9be438, 0xcef9c692, 0x299bd1b2, 0xb1279627, 0x210b5f3d, 0x5569bd88, 0x9652ed43, 0x7e8e0f8c, 0xdfa01085, 0xcd6d6343, 0xb8739826, 0xa52ce9a0, 0xd33ef231, 0x1b4d92c2, 0xabfa116d, 0xcdf47800, 0x3a4eefdc, 0xd01f3bcf, 0x30a32f46, 0xfb54d851, 0x06a98f67, 0xbdcd0a71, 0x21a00949, 0xfe7049c9, 0x67ef46d2, 0xa1fabcbc, 0xa4c72db4, 0x4a8a910d, 0x85a890ad, 0xc37e9454, 0xfc3d034a, 0x6f46cc52, 0x742be7a8, 0xe94ecbc5, 0x5f993659, 0x98270309, 0x8d1adae9, 0xea6e035e, 0x293d5fae, 0x669955b3, 0x5afe23b5, 0x4c74efbf, 0x98106505, 0xfbe09627, 0x3c00e8df, 0x5b03975d, 0x78edc83c, 0x117c49c6, 0x66cdfc73, 0xfa55c94f, 0x5bf285fe, 0x2db49b7d, 0xfbfeb8f0, 0xb7631bab, 0x837849f3, 0xf77f3ae5, 0x6e5db9bc, 0xfdd76f15, 0x545abf92, 0x8b538102, 0xdd5c9b65, 0xa5adfd55, 0xecbd7bc5, 0x9f99ebdd, 0x67500dcb, 0xf5246d1f, 0x2b0c061c, 0x927a3747, 0xc77ba267, 0x6da9f855, 0x6240d41a, 0xe9d1701d, 0xc69f0c55, 0x2c2c37cf, 0x12d82191, 0x47be40d3, 0x165b35cd, 0xb7db42e1, 0x358786e4, 0x84b8fc4e, 0x92f57c28, 0xf9c8bbd7, 0xab95a33d, 0x11009238, 0xe9770420, 0xd6967e2a, 0x97c1589f, 0x2ee7e7d3, 0x32cc86da, 0xe47767d1, 0x73e9b61e, 0xd35bac45, 0x835a62bb, 0x5d9217b0, 0x43f3f0ed, 0x8a97911e, 0x4ec7eb55, 0x4b5a988c, 0xb9056683, 0x45456f97, 0x1669fe44, 0xafb861b8, 0x8e83a19c, 0x0bab08d6, 0xe6a145a9, 0xc31e5fc2, 0x27621f4c, 0x795692fa, 0xb5e33ab9, 0x1bc786b6, 0x45d1c106, 0x986531c9, 0x40c9a0ec, 0xff0fdf84, 0xa7359a42, 0xfd1c2091, 0xf73463d4, 0x51b0d635, 0x1d602fb4, 0xc56b69b7, 0x6909d3f7, 0xa04d68f4, 0x8d1001a7, 0x8ecace50, 0x21ec4765, 0x3530f6b0, 0x645f3644, 0x9963ef1e, 0x2b3c70d5, 0xa20c823b, 0x8d26dcae, 0x05214e0c, 0x1993896d, 0x62085a35, 0x7b620b67, 0x1dd85da2, 0x09ce9b1d, 0xd7873326, 0x063ff730, 0xf4ff3c14, 0x09a49d69, 0x532062ba, 0x03ba7729, 0xbd9a86cc, 0xe26d02a7, 0x7ccbe5d3, 0x4f662214, 0x8b999a66, 0x3d0b92b4, 0x70b210f0, 0xf5b8f16f, 0x32146d34, 0x430b92bf, 0x8ab6204c, 0x35e6e1ff, 0xc2f6c2fa, 0xa2df8a1a, 0x887413ec, 0x7cb7a69f, 0x7ac6dbe6, 0x9102d1cb, 0x8892a590, 0xc804fe3a, 0xdfc4920a, 0xfc829840, 0x8910d2eb, 0x38a210fd, 0x9d840cc9, 0x7b9c827f, 0x3444ca0c, 0x071735ab, 0x5e9088e4, 0xc995d60e, 0xbe0bb942, 0x17b089ae, 0x050e1054, 0xcf4324f7, 0x1e3e64dd, 0x436414bb, 0xc48fc2e3, 0x6b6b83d4, 0x9f6558ac, 0x781b22c5, 0x7147cfe2, 0x3c221b4d, 0xa5602765, 0x8f01a4f0, 0x2a9f14ae, 0x12158cb8, 0x28177c50, 0x1091a165, 0x39e4e4be, 0x3e451b7a, 0xd965419c, 0x52053005, 0x0798aa53, 0xe6773e13, 0x1207f671, 0xd2ef998b, 0xab88a38f, 0xc77a8482, 0xa88fb031, 0x5199e0cd, 0x01b30536, 0x46eeb0ef, 0x814259ff, 0x9789a8cf, 0x376ec5ac, 0x7087034a, 0x948b6bdd, 0x4281e628, 0x2c848370, 0xd76ce66a, 0xe9b6959e, 0x24321a8e, 0xdeddd622, 0xb890f960, 0xea26c00a, 0x55e7d8b2, 0xeab67f09, 0x9227fb08, 0xeebbed06, 0xcac1b0d1, 0xb6412083, 0x05d2b0e7, 0x9037624a, 0xc9702198, 0x2c8d1a86, 0x3e7d416e, 0xc3f1a39f, 0xf04bdce4, 0xc88cdb61, 0xbdc89587, 0x4d29b63b, 0x6f24c267, 0x4b529c87, 0x573f5a53, 0xdb3316e9, 0x288eb53b, 0xd2c074bd, 0xef44a99a, 0x2b404d2d, 0xf6706464, 0xfe824f4c, 0xc3debaf8, 0x12f44f98, 0x03135e76, 0xb4888e7f, 0xb6b2325d, 0x3a138259, 0x513c83ec, 0x2386d214, 0x94555500, 0xfbd1522d, 0xda2af018, 0x15b054c0, 0x5ad654e6, 0xb6ed00aa, 0xa2f2180e, 0x5f662825, 0xecd11366, 0x1de5e99d, 0x07afd2ad, 0xcf457b04, 0xe631e10b, 0x83ae8a21, 0x709f0d59, 0x3e278bf9, 0x246816db, 0x9f5e8fd3, 0xc5b5b5a2, 0xd54a9d5c, 0x4b6f2856, 0x2eb5a666, 0xfc68bdd4, 0x1ed1a7f8, 0x98a34b75, 0xc895ada9, 0x2907cc69, 0x87b0b455, 0xddaf96d9, 0xe7da15a6, 0x9298c82a, 0x72bd5cab, 0x2e2a6ad4, 0x7f4b6bb8, 0x525225fe, 0x985abe90, 0xac1fd6e1, 0xb8340f23, 0x92985159, 0x7d29501d, 0xe75dc744, 0x687501b4, 0x92077dc3, 0x58281a67, 0xe7e8e9be, 0xd0e64fd1, 0xb2eb0a30, 0x0e1feccd, 0xc0dc4a9e, 0x5c4aeace, 0x2ca5b93c, 0xee0ec34f, 0xad78467b, 0x0830e76e, 0x0df63f8b, 0x2c2dfd95, 0x9b41ed31, 0x9ff4cddc, 0x1590c412, 0x2366fc82, 0x7a83294f, 0x9336c4de, 0x2343823c, 0x5b681096, 0xf320e4c2, 0xc22b70e2, 0xb5fbfb2a, 0x3ebc2fed, 0x11af07bd, 0x429a08c5, 0x42bee387, 0x58629e33, 0xfb63b486, 0x52135fbe, 0xf1380e60, 0x6355de87, 0x2f0bb19a, 0x167f63ac, 0x507224cf, 0xf7c99d00, 0x71646f50, 0x74feb1ca, 0x5f9abfdd, 0x278f7d68, 0x70120cd7, 0x4281b0f2, 0xdc8ebe5c, 0x36c32163, 0x2da1e884, 0x61877598, 0xbef04402, 0x304db695, 0xfa8e9add, 0x503bac31, 0x0fe04722, 0xf0d59f47, 0xcdc5c595, 0x918c39dd, 0x0cad8d05, 0x6b3ed1eb, 0x4d43e089, 0x7ab051f8, 0xdeec371f, 0x0f4816ae, 0xf8a1a240, 0xd15317f6, 0xb8efbf0b, 0xcdd05df8, 0x4fd5633e, 0x7cf19668, 0x25d8f422, 0x72d156f2, 0x2a778502, 0xda7aefb9, 0x4f4f66e8, 0x19db6bff, 0x74e468da, 0xa754f358, 0x7339ec50, 0x139006f6, 0xefbd0b91, 0x217e9a73, 0x939bd79c }; uint8_t buf[BUFSIZE]; uint32_t saw[BUFSIZE]; for (int i=0; i<BUFSIZE; ++i) { buf[i] = i+128; saw[i] = SpookyHashV1::Hash32(buf, i, 0); if (saw[i] != expected[i]) { printf("%d: saw 0x%.8x, expected 0x%.8x\n", i, saw[i], expected[i]); failed = true; } } } #undef BUFSIZE #define NUMBUF (1<<10) #define BUFSIZE (1<<20) void DoTimingBig(int seed) { printf("\ntesting time to hash 2^^30 bytes ...\n"); char *buf[NUMBUF]; for (int i=0; i<NUMBUF; ++i) { buf[i] = (char *)malloc(BUFSIZE); memset(buf[i], (char)seed, BUFSIZE); } uint64_t a = GetTickCount(); uint64_t hash1 = seed; uint64_t hash2 = seed; for (uint64_t i=0; i<NUMBUF; ++i) { SpookyHashV1::Hash128(buf[i], BUFSIZE, &hash1, &hash2); } uint64_t z = GetTickCount(); printf("SpookyHashV1::Hash128, uncached: time is " "%4" PRIu64 " milliseconds\n", z-a); a = GetTickCount(); for (uint64_t i=0; i<NUMBUF; ++i) { Add(buf[i], BUFSIZE, &hash1, &hash2); } z = GetTickCount(); printf("Addition , uncached: time is " "%4" PRIu64 " milliseconds\n", z-a); a = GetTickCount(); for (uint64_t i=0; i<NUMBUF*BUFSIZE/1024; ++i) { SpookyHashV1::Hash128(buf[0], 1024, &hash1, &hash2); } z = GetTickCount(); printf("SpookyHashV1::Hash128, cached: time is " "%4" PRIu64 " milliseconds\n", z-a); a = GetTickCount(); for (uint64_t i=0; i<NUMBUF*BUFSIZE/1024; ++i) { Add(buf[0], 1024, &hash1, &hash2); } z = GetTickCount(); printf("Addition , cached: time is " "%4" PRIu64 " milliseconds\n", z-a); for (int i=0; i<NUMBUF; ++i) { free(buf[i]); buf[i] = 0; } } #undef NUMBUF #undef BUFSIZE #define BUFSIZE (1<<14) #define NUMITER 10000000 void DoTimingSmall(int seed) { printf("\ntesting timing of hashing up to %d cached aligned bytes %d " "times ...\n", BUFSIZE, NUMITER); uint64_t buf[BUFSIZE/8]; for (int i=0; i<BUFSIZE/8; ++i) { buf[i] = i+seed; } for (int i=1; i <= BUFSIZE; i <<= 1) { uint64_t a = GetTickCount(); uint64_t hash1 = seed; uint64_t hash2 = seed+i; for (int j=0; j<NUMITER; ++j) { SpookyHashV1::Hash128((char *)buf, i, &hash1, &hash2); } uint64_t z = GetTickCount(); printf("%d bytes: hash is %.16" PRIx64 " %.16" PRIx64 ", " "time is %" PRIu64 "\n", i, hash1, hash2, z-a); } } #undef BUFSIZE #define BUFSIZE 1024 void TestAlignment() { printf("\ntesting alignment ...\n"); char buf[BUFSIZE]; uint64_t hash[8]; for (int i=0; i<BUFSIZE-16; ++i) { for (int j=0; j<8; ++j) { buf[j] = (char)i+j; for (int k=1; k<=i; ++k) { buf[j+k] = k; } buf[j+i+1] = (char)i+j; hash[j] = SpookyHashV1::Hash64((const void *)(buf+j+1), i, 0); } for (int j=1; j<8; ++j) { if (hash[0] != hash[j]) { printf("alignment problems: %d %d\n", i, j); failed = true; } } } } #undef BUFSIZE // test that all deltas of one or two input bits affect all output bits #define BUFSIZE 256 #define TRIES 50 #define MEASURES 6 void TestDeltas(int seed) { printf("\nall 1 or 2 bit input deltas get %d tries to flip every output " "bit ...\n", TRIES); Random random; random.Init((uint64_t)seed); // for messages 0..BUFSIZE-1 bytes for (int h=0; h<BUFSIZE; ++h) { int maxk = 0; // first bit to set for (int i=0; i<h*8; ++i) { // second bit to set, or don't have a second bit for (int j=0; j<=i; ++j) { uint64_t measure[MEASURES][2]; uint64_t counter[MEASURES][2]; for (int l=0; l<2; ++l) { for (int m=0; m<MEASURES; ++m) { counter[m][l] = 0; } } // try to hit every output bit TRIES times int k; for (k=0; k<TRIES; ++k) { uint8_t buf1[BUFSIZE]; uint8_t buf2[BUFSIZE]; int done = 1; for (int l=0; l<h; ++l) { buf1[l] = buf2[l] = random.Value(); } buf1[i/8] ^= (1 << (i%8)); if (j != i) { buf1[j/8] ^= (1 << (j%8)); } SpookyHashV1::Hash128(buf1, h, &measure[0][0], &measure[0][1]); SpookyHashV1::Hash128(buf2, h, &measure[1][0], &measure[1][1]); for (int l=0; l<2; ++l) { measure[2][l] = measure[0][l] ^ measure[1][l]; measure[3][l] = ~(measure[0][l] ^ measure[1][l]); measure[4][l] = measure[0][l] - measure[1][l]; measure[4][l] ^= (measure[4][l]>>1); measure[5][l] = measure[0][l] + measure[1][l]; measure[5][l] ^= (measure[4][l]>>1); } for (int l=0; l<2; ++l) { for (int m=0; m<MEASURES; ++m) { counter[m][l] |= measure[m][l]; if (~counter[m][l]) done = 0; } } if (done) break; } if (k == TRIES) { printf("failed %d %d %d\n", h, i, j); failed = true; } else if (k > maxk) { maxk = k; } } } printf("passed for buffer size %d max %d\n", h, maxk); } } #undef BUFSIZE #undef TRIES #undef MEASURES // test that hashing pieces has the same behavior as hashing the whole #define BUFSIZE 1024 void TestPieces() { printf("\ntesting pieces ...\n"); char buf[BUFSIZE]; for (int i=0; i<BUFSIZE; ++i) { buf[i] = i; } for (int i=0; i<BUFSIZE; ++i) { uint64_t a,b,c,d,seed1=1,seed2=2; SpookyHashV1 state; // all as one call a = seed1; b = seed2; SpookyHashV1::Hash128(buf, i, &a, &b); // all as one piece c = 0xdeadbeefdeadbeef; d = 0xbaceba11baceba11; state.Init(seed1, seed2); state.Update(buf, i); state.Final(&c, &d); if (a != c) { printf("wrong a %d: %.16" PRIx64 " %.16" PRIx64 "\n", i, a,c); failed = true; } if (b != d) { printf("wrong b %d: %.16" PRIx64 " %.16" PRIx64 "\n", i, b,d); failed = true; } // all possible two consecutive pieces for (int j=0; j<i; ++j) { c = seed1; d = seed2; state.Init(c, d); state.Update(&buf[0], j); state.Update(&buf[j], i-j); state.Final(&c, &d); if (a != c) { printf("wrong a %d %d: %.16" PRIx64 " %.16" PRIx64 "\n", j, i, a,c); failed = true; } if (b != d) { printf("wrong b %d %d: %.16" PRIx64 " %.16" PRIx64 "\n", j, i, b,d); failed = true; } } } } #undef BUFSIZE TEST(SpookyHashV1, Main) { TestResults(); TestAlignment(); TestPieces(); DoTimingBig(1); // tudorb@fb.com: Commented out slow tests #if 0 DoTimingSmall(argc); TestDeltas(argc); #endif CHECK_EQ(failed, 0); }
apache-2.0
BUGgs/FreeRDP
winpr/libwinpr/file/test/TestFilePatternMatch.c
60
4423
#include <stdio.h> #include <winpr/crt.h> #include <winpr/file.h> #include <winpr/windows.h> int TestFilePatternMatch(int argc, char* argv[]) { /* '*' expression */ if (!FilePatternMatchA("document.txt", "*")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "*"); return -1; } /* '*X' expression */ if (!FilePatternMatchA("document.txt", "*.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "*.txt"); return -1; } if (FilePatternMatchA("document.docx", "*.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.docx", "*.txt"); return -1; } if (FilePatternMatchA("document.txt.bak", "*.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt.bak", "*.txt"); return -1; } if (FilePatternMatchA("bak", "*.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "bak", "*.txt"); return -1; } /* 'X*' expression */ if (!FilePatternMatchA("document.txt", "document.*")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "document.*"); return -1; } /* 'X?' expression */ if (!FilePatternMatchA("document.docx", "document.doc?")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.docx", "document.doc?"); return -1; } if (FilePatternMatchA("document.doc", "document.doc?")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.doc", "document.doc?"); return -1; } /* no wildcards expression */ if (!FilePatternMatchA("document.txt", "document.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "document.txt"); return -1; } /* 'X * Y' expression */ if (!FilePatternMatchA("X123Y.txt", "X*Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y.txt", "X*Y.txt"); return -1; } if (!FilePatternMatchA("XY.txt", "X*Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XY.txt", "X*Y.txt"); return -1; } if (FilePatternMatchA("XZ.txt", "X*Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XZ.txt", "X*Y.txt"); return -1; } if (FilePatternMatchA("X123Z.txt", "X*Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Z.txt", "X*Y.txt"); return -1; } /* 'X * Y * Z' expression */ if (!FilePatternMatchA("X123Y456Z.txt", "X*Y*Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456Z.txt", "X*Y*Z.txt"); return -1; } if (!FilePatternMatchA("XYZ.txt", "X*Y*Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYZ.txt", "X*Y*Z.txt"); return -1; } if (!FilePatternMatchA("X123Y456W.txt", "X*Y*Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456W.txt", "X*Y*Z.txt"); return -1; } if (!FilePatternMatchA("XYW.txt", "X*Y*Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYW.txt", "X*Y*Z.txt"); return -1; } /* 'X ? Y' expression */ if (!FilePatternMatchA("X1Y.txt", "X?Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X1Y.txt", "X?Y.txt"); return -1; } if (FilePatternMatchA("XY.txt", "X?Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XY.txt", "X?Y.txt"); return -1; } if (FilePatternMatchA("XZ.txt", "X?Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XZ.txt", "X?Y.txt"); return -1; } if (FilePatternMatchA("X123Z.txt", "X?Y.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Z.txt", "X?Y.txt"); return -1; } /* 'X ? Y ? Z' expression */ if (!FilePatternMatchA("X123Y456Z.txt", "X?Y?Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456Z.txt", "X?Y?Z.txt"); return -1; } if (FilePatternMatchA("XYZ.txt", "X?Y?Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYZ.txt", "X?Y?Z.txt"); return -1; } if (!FilePatternMatchA("X123Y456W.txt", "X?Y?Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456W.txt", "X?Y?Z.txt"); return -1; } if (FilePatternMatchA("XYW.txt", "X?Y?Z.txt")) { printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYW.txt", "X?Y?Z.txt"); return -1; } return 0; }
apache-2.0
pradeep-gr/mbed-os5-onsemi
targets/TARGET_Maxim/TARGET_MAX32625/mxc/i2cs.c
78
6619
/** * @file i2cs.c * @brief This file contains the function implementations for the I2CS * (Inter-Integrated Circuit Slave) peripheral module. */ /* **************************************************************************** * Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of Maxim Integrated * Products, Inc. shall not be used except as stated in the Maxim Integrated * Products, Inc. Branding Policy. * * The mere transfer of this software does not imply any licenses * of trade secrets, proprietary technology, copyrights, patents, * trademarks, maskwork rights, or any other form of intellectual * property whatsoever. Maxim Integrated Products, Inc. retains all * ownership rights. * * $Date: 2016-08-15 20:05:48 -0500 (Mon, 15 Aug 2016) $ * $Revision: 24086 $ * *************************************************************************** */ /* **** Includes **** */ #include <string.h> #include "mxc_assert.h" #include "mxc_errors.h" #include "mxc_sys.h" #include "i2cs.h" /** * @ingroup i2cs * @{ */ /* **** Definitions **** */ /* **** Globals ***** */ // No Doxygen documentation for the items between here and endcond. /* Clock divider lookup table */ static const uint32_t clk_div_table[2][8] = { /* I2CS_SPEED_100KHZ */ { // 12000000 (6 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 24000000 (12 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 36000000 NOT SUPPORTED 0, // 48000000 (24 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 60000000 NOT SUPPORTED 0, // 72000000 NOT SUPPORTED 0, // 84000000 NOT SUPPORTED 0, // 96000000 (48 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS) }, /* I2CS_SPEED_400KHZ */ { // 12000000 (2 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 24000000 (3 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 36000000 NOT SUPPORTED 0, // 48000000 (6 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS), // 60000000 NOT SUPPORTED 0, // 72000000 NOT SUPPORTED 0, // 84000000 NOT SUPPORTED 0, // 96000000 (12 << MXC_F_I2CS_CLK_DIV_FS_FILTER_CLOCK_DIV_POS) }, }; static void (*callbacks[MXC_CFG_I2CS_INSTANCES][MXC_CFG_I2CS_BUFFER_SIZE])(uint8_t); /* **** Functions **** */ /* ************************************************************************* */ int I2CS_Init(mxc_i2cs_regs_t *i2cs, const sys_cfg_i2cs_t *sys_cfg, i2cs_speed_t speed, uint16_t address, i2cs_addr_t addr_len) { int err, i, i2cs_index; i2cs_index = MXC_I2CS_GET_IDX(i2cs); MXC_ASSERT(i2cs_index >= 0); // Set system level configurations if ((err = SYS_I2CS_Init(i2cs, sys_cfg)) != E_NO_ERROR) { return err; } // Compute clock array index int clki = ((SYS_I2CS_GetFreq(i2cs) / 12000000) - 1); // Get clock divider settings from lookup table if ((speed == I2CS_SPEED_100KHZ) && (clk_div_table[I2CS_SPEED_100KHZ][clki] > 0)) { i2cs->clk_div = clk_div_table[I2CS_SPEED_100KHZ][clki]; } else if ((speed == I2CS_SPEED_400KHZ) && (clk_div_table[I2CS_SPEED_400KHZ][clki] > 0)) { i2cs->clk_div = clk_div_table[I2CS_SPEED_400KHZ][clki]; } else { MXC_ASSERT_FAIL(); } // Clear the interrupt callbacks for(i = 0; i < MXC_CFG_I2CS_BUFFER_SIZE; i++) { callbacks[i2cs_index][i] = NULL; } // Reset module i2cs->dev_id = MXC_F_I2CS_DEV_ID_SLAVE_RESET; i2cs->dev_id = ((((address >> 0) << MXC_F_I2CS_DEV_ID_SLAVE_DEV_ID_POS) & MXC_F_I2CS_DEV_ID_SLAVE_DEV_ID) | addr_len); return E_NO_ERROR; } /* ************************************************************************* */ int I2CS_Shutdown(mxc_i2cs_regs_t *i2cs) { int err; // Disable and clear interrupts i2cs->inten = 0; i2cs->intfl = i2cs->intfl; // clears system level configurations if ((err = SYS_I2CS_Shutdown(i2cs)) != E_NO_ERROR) { return err; } return E_NO_ERROR; } /* ************************************************************************* */ void I2CS_Handler(mxc_i2cs_regs_t *i2cs) { uint32_t intfl; uint8_t i; int i2cs_index = MXC_I2CS_GET_IDX(i2cs); // Save and clear the interrupt flags intfl = i2cs->intfl; i2cs->intfl = intfl; // Process each interrupt for(i = 0; i < 32; i++) { if(intfl & (0x1 << i)) { if(callbacks[i2cs_index][i] != NULL) { callbacks[i2cs_index][i](i); } } } } /* ************************************************************************* */ void I2CS_RegisterCallback(mxc_i2cs_regs_t *i2cs, uint8_t addr, i2cs_callback_fn callback) { int i2cs_index = MXC_I2CS_GET_IDX(i2cs); // Make sure we don't overflow MXC_ASSERT(addr < MXC_CFG_I2CS_BUFFER_SIZE); if(callback != NULL) { // Save the callback address callbacks[i2cs_index][addr] = callback; // Clear and Enable the interrupt for the given byte i2cs->intfl = (0x1 << addr); i2cs->inten |= (0x1 << addr); } else { // Disable and clear the interrupt i2cs->inten &= ~(0x1 << addr); i2cs->intfl = (0x1 << addr); // Clear the callback address callbacks[i2cs_index][addr] = NULL; } } /**@} end of group i2cs*/
apache-2.0
ghostkim-sc/SMG920T_profiling_enabled
drivers/usb/serial/ipaq.c
2152
32579
/* * USB Compaq iPAQ driver * * Copyright (C) 2001 - 2002 * Ganesh Varadarajan <ganesh@veritas.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. */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #define KP_RETRIES 100 #define DRIVER_AUTHOR "Ganesh Varadarajan <ganesh@veritas.com>" #define DRIVER_DESC "USB PocketPC PDA driver" static int connect_retries = KP_RETRIES; static int initial_wait; /* Function prototypes for an ipaq */ static int ipaq_open(struct tty_struct *tty, struct usb_serial_port *port); static int ipaq_calc_num_ports(struct usb_serial *serial); static int ipaq_startup(struct usb_serial *serial); static struct usb_device_id ipaq_id_table [] = { { USB_DEVICE(0x0104, 0x00BE) }, /* Socket USB Sync */ { USB_DEVICE(0x03F0, 0x1016) }, /* HP USB Sync */ { USB_DEVICE(0x03F0, 0x1116) }, /* HP USB Sync 1611 */ { USB_DEVICE(0x03F0, 0x1216) }, /* HP USB Sync 1612 */ { USB_DEVICE(0x03F0, 0x2016) }, /* HP USB Sync 1620 */ { USB_DEVICE(0x03F0, 0x2116) }, /* HP USB Sync 1621 */ { USB_DEVICE(0x03F0, 0x2216) }, /* HP USB Sync 1622 */ { USB_DEVICE(0x03F0, 0x3016) }, /* HP USB Sync 1630 */ { USB_DEVICE(0x03F0, 0x3116) }, /* HP USB Sync 1631 */ { USB_DEVICE(0x03F0, 0x3216) }, /* HP USB Sync 1632 */ { USB_DEVICE(0x03F0, 0x4016) }, /* HP USB Sync 1640 */ { USB_DEVICE(0x03F0, 0x4116) }, /* HP USB Sync 1641 */ { USB_DEVICE(0x03F0, 0x4216) }, /* HP USB Sync 1642 */ { USB_DEVICE(0x03F0, 0x5016) }, /* HP USB Sync 1650 */ { USB_DEVICE(0x03F0, 0x5116) }, /* HP USB Sync 1651 */ { USB_DEVICE(0x03F0, 0x5216) }, /* HP USB Sync 1652 */ { USB_DEVICE(0x0409, 0x00D5) }, /* NEC USB Sync */ { USB_DEVICE(0x0409, 0x00D6) }, /* NEC USB Sync */ { USB_DEVICE(0x0409, 0x00D7) }, /* NEC USB Sync */ { USB_DEVICE(0x0409, 0x8024) }, /* NEC USB Sync */ { USB_DEVICE(0x0409, 0x8025) }, /* NEC USB Sync */ { USB_DEVICE(0x043E, 0x9C01) }, /* LGE USB Sync */ { USB_DEVICE(0x045E, 0x00CE) }, /* Microsoft USB Sync */ { USB_DEVICE(0x045E, 0x0400) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0401) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0402) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0403) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0404) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0405) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0406) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0407) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0408) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0409) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040A) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040B) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040C) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040D) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040E) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x040F) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0410) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0411) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0412) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0413) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0414) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0415) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0416) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0417) }, /* Windows Powered Pocket PC 2002 */ { USB_DEVICE(0x045E, 0x0432) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0433) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0434) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0435) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0436) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0437) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0438) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0439) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043A) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043B) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043C) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043D) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043E) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x043F) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0440) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0441) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0442) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0443) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0444) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0445) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0446) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0447) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0448) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0449) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044A) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044B) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044C) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044D) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044E) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x044F) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0450) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0451) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0452) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0453) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0454) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0455) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0456) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0457) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0458) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0459) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045A) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045B) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045C) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045D) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045E) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x045F) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0460) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0461) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0462) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0463) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0464) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0465) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0466) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0467) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0468) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0469) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046A) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046B) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046C) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046D) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046E) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x046F) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0470) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0471) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0472) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0473) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0474) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0475) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0476) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0477) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0478) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x0479) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x047A) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x047B) }, /* Windows Powered Pocket PC 2003 */ { USB_DEVICE(0x045E, 0x04C8) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04C9) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04CA) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04CB) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04CC) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04CD) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04CE) }, /* Windows Powered Smartphone 2002 */ { USB_DEVICE(0x045E, 0x04D7) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04D8) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04D9) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DA) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DB) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DC) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DD) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DE) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04DF) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E0) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E1) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E2) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E3) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E4) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E5) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E6) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E7) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E8) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04E9) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x045E, 0x04EA) }, /* Windows Powered Smartphone 2003 */ { USB_DEVICE(0x049F, 0x0003) }, /* Compaq iPAQ USB Sync */ { USB_DEVICE(0x049F, 0x0032) }, /* Compaq iPAQ USB Sync */ { USB_DEVICE(0x04A4, 0x0014) }, /* Hitachi USB Sync */ { USB_DEVICE(0x04AD, 0x0301) }, /* USB Sync 0301 */ { USB_DEVICE(0x04AD, 0x0302) }, /* USB Sync 0302 */ { USB_DEVICE(0x04AD, 0x0303) }, /* USB Sync 0303 */ { USB_DEVICE(0x04AD, 0x0306) }, /* GPS Pocket PC USB Sync */ { USB_DEVICE(0x04B7, 0x0531) }, /* MyGuide 7000 XL USB Sync */ { USB_DEVICE(0x04C5, 0x1058) }, /* FUJITSU USB Sync */ { USB_DEVICE(0x04C5, 0x1079) }, /* FUJITSU USB Sync */ { USB_DEVICE(0x04DA, 0x2500) }, /* Panasonic USB Sync */ { USB_DEVICE(0x04DD, 0x9102) }, /* SHARP WS003SH USB Modem */ { USB_DEVICE(0x04DD, 0x9121) }, /* SHARP WS004SH USB Modem */ { USB_DEVICE(0x04DD, 0x9123) }, /* SHARP WS007SH USB Modem */ { USB_DEVICE(0x04DD, 0x9151) }, /* SHARP S01SH USB Modem */ { USB_DEVICE(0x04DD, 0x91AC) }, /* SHARP WS011SH USB Modem */ { USB_DEVICE(0x04E8, 0x5F00) }, /* Samsung NEXiO USB Sync */ { USB_DEVICE(0x04E8, 0x5F01) }, /* Samsung NEXiO USB Sync */ { USB_DEVICE(0x04E8, 0x5F02) }, /* Samsung NEXiO USB Sync */ { USB_DEVICE(0x04E8, 0x5F03) }, /* Samsung NEXiO USB Sync */ { USB_DEVICE(0x04E8, 0x5F04) }, /* Samsung NEXiO USB Sync */ { USB_DEVICE(0x04E8, 0x6611) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6613) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6615) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6617) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6619) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x661B) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x662E) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6630) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04E8, 0x6632) }, /* Samsung MITs USB Sync */ { USB_DEVICE(0x04f1, 0x3011) }, /* JVC USB Sync */ { USB_DEVICE(0x04F1, 0x3012) }, /* JVC USB Sync */ { USB_DEVICE(0x0502, 0x1631) }, /* c10 Series */ { USB_DEVICE(0x0502, 0x1632) }, /* c20 Series */ { USB_DEVICE(0x0502, 0x16E1) }, /* Acer n10 Handheld USB Sync */ { USB_DEVICE(0x0502, 0x16E2) }, /* Acer n20 Handheld USB Sync */ { USB_DEVICE(0x0502, 0x16E3) }, /* Acer n30 Handheld USB Sync */ { USB_DEVICE(0x0536, 0x01A0) }, /* HHP PDT */ { USB_DEVICE(0x0543, 0x0ED9) }, /* ViewSonic Color Pocket PC V35 */ { USB_DEVICE(0x0543, 0x1527) }, /* ViewSonic Color Pocket PC V36 */ { USB_DEVICE(0x0543, 0x1529) }, /* ViewSonic Color Pocket PC V37 */ { USB_DEVICE(0x0543, 0x152B) }, /* ViewSonic Color Pocket PC V38 */ { USB_DEVICE(0x0543, 0x152E) }, /* ViewSonic Pocket PC */ { USB_DEVICE(0x0543, 0x1921) }, /* ViewSonic Communicator Pocket PC */ { USB_DEVICE(0x0543, 0x1922) }, /* ViewSonic Smartphone */ { USB_DEVICE(0x0543, 0x1923) }, /* ViewSonic Pocket PC V30 */ { USB_DEVICE(0x05E0, 0x2000) }, /* Symbol USB Sync */ { USB_DEVICE(0x05E0, 0x2001) }, /* Symbol USB Sync 0x2001 */ { USB_DEVICE(0x05E0, 0x2002) }, /* Symbol USB Sync 0x2002 */ { USB_DEVICE(0x05E0, 0x2003) }, /* Symbol USB Sync 0x2003 */ { USB_DEVICE(0x05E0, 0x2004) }, /* Symbol USB Sync 0x2004 */ { USB_DEVICE(0x05E0, 0x2005) }, /* Symbol USB Sync 0x2005 */ { USB_DEVICE(0x05E0, 0x2006) }, /* Symbol USB Sync 0x2006 */ { USB_DEVICE(0x05E0, 0x2007) }, /* Symbol USB Sync 0x2007 */ { USB_DEVICE(0x05E0, 0x2008) }, /* Symbol USB Sync 0x2008 */ { USB_DEVICE(0x05E0, 0x2009) }, /* Symbol USB Sync 0x2009 */ { USB_DEVICE(0x05E0, 0x200A) }, /* Symbol USB Sync 0x200A */ { USB_DEVICE(0x067E, 0x1001) }, /* Intermec Mobile Computer */ { USB_DEVICE(0x07CF, 0x2001) }, /* CASIO USB Sync 2001 */ { USB_DEVICE(0x07CF, 0x2002) }, /* CASIO USB Sync 2002 */ { USB_DEVICE(0x07CF, 0x2003) }, /* CASIO USB Sync 2003 */ { USB_DEVICE(0x0930, 0x0700) }, /* TOSHIBA USB Sync 0700 */ { USB_DEVICE(0x0930, 0x0705) }, /* TOSHIBA Pocket PC e310 */ { USB_DEVICE(0x0930, 0x0706) }, /* TOSHIBA Pocket PC e740 */ { USB_DEVICE(0x0930, 0x0707) }, /* TOSHIBA Pocket PC e330 Series */ { USB_DEVICE(0x0930, 0x0708) }, /* TOSHIBA Pocket PC e350 Series */ { USB_DEVICE(0x0930, 0x0709) }, /* TOSHIBA Pocket PC e750 Series */ { USB_DEVICE(0x0930, 0x070A) }, /* TOSHIBA Pocket PC e400 Series */ { USB_DEVICE(0x0930, 0x070B) }, /* TOSHIBA Pocket PC e800 Series */ { USB_DEVICE(0x094B, 0x0001) }, /* Linkup Systems USB Sync */ { USB_DEVICE(0x0960, 0x0065) }, /* BCOM USB Sync 0065 */ { USB_DEVICE(0x0960, 0x0066) }, /* BCOM USB Sync 0066 */ { USB_DEVICE(0x0960, 0x0067) }, /* BCOM USB Sync 0067 */ { USB_DEVICE(0x0961, 0x0010) }, /* Portatec USB Sync */ { USB_DEVICE(0x099E, 0x0052) }, /* Trimble GeoExplorer */ { USB_DEVICE(0x099E, 0x4000) }, /* TDS Data Collector */ { USB_DEVICE(0x0B05, 0x4200) }, /* ASUS USB Sync */ { USB_DEVICE(0x0B05, 0x4201) }, /* ASUS USB Sync */ { USB_DEVICE(0x0B05, 0x4202) }, /* ASUS USB Sync */ { USB_DEVICE(0x0B05, 0x420F) }, /* ASUS USB Sync */ { USB_DEVICE(0x0B05, 0x9200) }, /* ASUS USB Sync */ { USB_DEVICE(0x0B05, 0x9202) }, /* ASUS USB Sync */ { USB_DEVICE(0x0BB4, 0x00CE) }, /* HTC USB Sync */ { USB_DEVICE(0x0BB4, 0x00CF) }, /* HTC USB Modem */ { USB_DEVICE(0x0BB4, 0x0A01) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A02) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A03) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A04) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A05) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A06) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A07) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A08) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A09) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0A) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0B) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0C) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0D) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0E) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A0F) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A10) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A11) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A12) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A13) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A14) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A15) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A16) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A17) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A18) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A19) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1A) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1B) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1C) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1D) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1E) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A1F) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A20) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A21) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A22) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A23) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A24) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A25) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A26) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A27) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A28) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A29) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2A) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2B) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2C) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2D) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2E) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A2F) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A30) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A31) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A32) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A33) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A34) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A35) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A36) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A37) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A38) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A39) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3A) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3B) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3C) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3D) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3E) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A3F) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A40) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A41) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A42) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A43) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A44) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A45) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A46) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A47) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A48) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A49) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4A) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4B) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4C) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4D) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4E) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A4F) }, /* PocketPC USB Sync */ { USB_DEVICE(0x0BB4, 0x0A50) }, /* HTC SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A51) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A52) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A53) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A54) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A55) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A56) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A57) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A58) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A59) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5A) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5B) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5C) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5D) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5E) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A5F) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A60) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A61) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A62) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A63) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A64) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A65) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A66) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A67) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A68) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A69) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6A) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6B) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6C) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6D) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6E) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A6F) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A70) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A71) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A72) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A73) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A74) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A75) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A76) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A77) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A78) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A79) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7A) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7B) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7C) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7D) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7E) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A7F) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A80) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A81) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A82) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A83) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A84) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A85) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A86) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A87) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A88) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A89) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8A) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8B) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8C) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8D) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8E) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A8F) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A90) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A91) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A92) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A93) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A94) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A95) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A96) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A97) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A98) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A99) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9A) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9B) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9C) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9D) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9E) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0A9F) }, /* SmartPhone USB Sync */ { USB_DEVICE(0x0BB4, 0x0BCE) }, /* "High Tech Computer Corp" */ { USB_DEVICE(0x0BF8, 0x1001) }, /* Fujitsu Siemens Computers USB Sync */ { USB_DEVICE(0x0C44, 0x03A2) }, /* Motorola iDEN Smartphone */ { USB_DEVICE(0x0C8E, 0x6000) }, /* Cesscom Luxian Series */ { USB_DEVICE(0x0CAD, 0x9001) }, /* Motorola PowerPad Pocket PC Device */ { USB_DEVICE(0x0F4E, 0x0200) }, /* Freedom Scientific USB Sync */ { USB_DEVICE(0x0F98, 0x0201) }, /* Cyberbank USB Sync */ { USB_DEVICE(0x0FB8, 0x3001) }, /* Wistron USB Sync */ { USB_DEVICE(0x0FB8, 0x3002) }, /* Wistron USB Sync */ { USB_DEVICE(0x0FB8, 0x3003) }, /* Wistron USB Sync */ { USB_DEVICE(0x0FB8, 0x4001) }, /* Wistron USB Sync */ { USB_DEVICE(0x1066, 0x00CE) }, /* E-TEN USB Sync */ { USB_DEVICE(0x1066, 0x0300) }, /* E-TEN P3XX Pocket PC */ { USB_DEVICE(0x1066, 0x0500) }, /* E-TEN P5XX Pocket PC */ { USB_DEVICE(0x1066, 0x0600) }, /* E-TEN P6XX Pocket PC */ { USB_DEVICE(0x1066, 0x0700) }, /* E-TEN P7XX Pocket PC */ { USB_DEVICE(0x1114, 0x0001) }, /* Psion Teklogix Sync 753x */ { USB_DEVICE(0x1114, 0x0004) }, /* Psion Teklogix Sync netBookPro */ { USB_DEVICE(0x1114, 0x0006) }, /* Psion Teklogix Sync 7525 */ { USB_DEVICE(0x1182, 0x1388) }, /* VES USB Sync */ { USB_DEVICE(0x11D9, 0x1002) }, /* Rugged Pocket PC 2003 */ { USB_DEVICE(0x11D9, 0x1003) }, /* Rugged Pocket PC 2003 */ { USB_DEVICE(0x1231, 0xCE01) }, /* USB Sync 03 */ { USB_DEVICE(0x1231, 0xCE02) }, /* USB Sync 03 */ { USB_DEVICE(0x1690, 0x0601) }, /* Askey USB Sync */ { USB_DEVICE(0x22B8, 0x4204) }, /* Motorola MPx200 Smartphone */ { USB_DEVICE(0x22B8, 0x4214) }, /* Motorola MPc GSM */ { USB_DEVICE(0x22B8, 0x4224) }, /* Motorola MPx220 Smartphone */ { USB_DEVICE(0x22B8, 0x4234) }, /* Motorola MPc CDMA */ { USB_DEVICE(0x22B8, 0x4244) }, /* Motorola MPx100 Smartphone */ { USB_DEVICE(0x3340, 0x011C) }, /* Mio DigiWalker PPC StrongARM */ { USB_DEVICE(0x3340, 0x0326) }, /* Mio DigiWalker 338 */ { USB_DEVICE(0x3340, 0x0426) }, /* Mio DigiWalker 338 */ { USB_DEVICE(0x3340, 0x043A) }, /* Mio DigiWalker USB Sync */ { USB_DEVICE(0x3340, 0x051C) }, /* MiTAC USB Sync 528 */ { USB_DEVICE(0x3340, 0x053A) }, /* Mio DigiWalker SmartPhone USB Sync */ { USB_DEVICE(0x3340, 0x071C) }, /* MiTAC USB Sync */ { USB_DEVICE(0x3340, 0x0B1C) }, /* Generic PPC StrongARM */ { USB_DEVICE(0x3340, 0x0E3A) }, /* Generic PPC USB Sync */ { USB_DEVICE(0x3340, 0x0F1C) }, /* Itautec USB Sync */ { USB_DEVICE(0x3340, 0x0F3A) }, /* Generic SmartPhone USB Sync */ { USB_DEVICE(0x3340, 0x1326) }, /* Itautec USB Sync */ { USB_DEVICE(0x3340, 0x191C) }, /* YAKUMO USB Sync */ { USB_DEVICE(0x3340, 0x2326) }, /* Vobis USB Sync */ { USB_DEVICE(0x3340, 0x3326) }, /* MEDION Winodws Moble USB Sync */ { USB_DEVICE(0x3708, 0x20CE) }, /* Legend USB Sync */ { USB_DEVICE(0x3708, 0x21CE) }, /* Lenovo USB Sync */ { USB_DEVICE(0x4113, 0x0210) }, /* Mobile Media Technology USB Sync */ { USB_DEVICE(0x4113, 0x0211) }, /* Mobile Media Technology USB Sync */ { USB_DEVICE(0x4113, 0x0400) }, /* Mobile Media Technology USB Sync */ { USB_DEVICE(0x4113, 0x0410) }, /* Mobile Media Technology USB Sync */ { USB_DEVICE(0x413C, 0x4001) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4002) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4003) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4004) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4005) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4006) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4007) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4008) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x413C, 0x4009) }, /* Dell Axim USB Sync */ { USB_DEVICE(0x4505, 0x0010) }, /* Smartphone */ { USB_DEVICE(0x5E04, 0xCE00) }, /* SAGEM Wireless Assistant */ { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, ipaq_id_table); /* All of the device info needed for the Compaq iPAQ */ static struct usb_serial_driver ipaq_device = { .driver = { .owner = THIS_MODULE, .name = "ipaq", }, .description = "PocketPC PDA", .id_table = ipaq_id_table, .bulk_in_size = 256, .bulk_out_size = 256, .open = ipaq_open, .attach = ipaq_startup, .calc_num_ports = ipaq_calc_num_ports, }; static struct usb_serial_driver * const serial_drivers[] = { &ipaq_device, NULL }; static int ipaq_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; int result = 0; int retries = connect_retries; msleep(1000*initial_wait); /* * Send out control message observed in win98 sniffs. Not sure what * it does, but from empirical observations, it seems that the device * will start the chat sequence once one of these messages gets * through. Since this has a reasonably high failure rate, we retry * several times. */ while (retries--) { result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), 0x22, 0x21, 0x1, 0, NULL, 0, 100); if (!result) break; msleep(1000); } if (!retries && result) { dev_err(&port->dev, "%s - failed doing control urb, error %d\n", __func__, result); return result; } return usb_serial_generic_open(tty, port); } static int ipaq_calc_num_ports(struct usb_serial *serial) { /* * some devices have 3 endpoints, the 3rd of which * must be ignored as it would make the core * create a second port which oopses when used */ int ipaq_num_ports = 1; dev_dbg(&serial->dev->dev, "%s - numberofendpoints: %d\n", __func__, (int)serial->interface->cur_altsetting->desc.bNumEndpoints); /* * a few devices have 4 endpoints, seemingly Yakuma devices, * and we need the second pair, so let them have 2 ports * * TODO: can we drop port 1 ? */ if (serial->interface->cur_altsetting->desc.bNumEndpoints > 3) { ipaq_num_ports = 2; } return ipaq_num_ports; } static int ipaq_startup(struct usb_serial *serial) { /* Some of the devices in ipaq_id_table[] are composite, and we * shouldn't bind to all the interfaces. This test will rule out * some obviously invalid possibilities. */ if (serial->num_bulk_in < serial->num_ports || serial->num_bulk_out < serial->num_ports) return -ENODEV; if (serial->dev->actconfig->desc.bConfigurationValue != 1) { /* * FIXME: HP iPaq rx3715, possibly others, have 1 config that * is labeled as 2 */ dev_err(&serial->dev->dev, "active config #%d != 1 ??\n", serial->dev->actconfig->desc.bConfigurationValue); return -ENODEV; } dev_dbg(&serial->dev->dev, "%s - iPAQ module configured for %d ports\n", __func__, serial->num_ports); return usb_reset_configuration(serial->dev); } module_usb_serial_driver(serial_drivers, ipaq_id_table); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(connect_retries, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(connect_retries, "Maximum number of connect retries (one second each)"); module_param(initial_wait, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(initial_wait, "Time to wait before attempting a connection (in seconds)");
apache-2.0
TeamVee-Kanas/android_kernel_samsung_kanas
drivers/ata/pata_octeon_cf.c
1653
28243
/* * Driver for the Octeon bootbus compact flash. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2005 - 2012 Cavium Inc. * Copyright (C) 2008 Wind River Systems */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/libata.h> #include <linux/hrtimer.h> #include <linux/slab.h> #include <linux/irq.h> #include <linux/of.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <scsi/scsi_host.h> #include <asm/byteorder.h> #include <asm/octeon/octeon.h> /* * The Octeon bootbus compact flash interface is connected in at least * 3 different configurations on various evaluation boards: * * -- 8 bits no irq, no DMA * -- 16 bits no irq, no DMA * -- 16 bits True IDE mode with DMA, but no irq. * * In the last case the DMA engine can generate an interrupt when the * transfer is complete. For the first two cases only PIO is supported. * */ #define DRV_NAME "pata_octeon_cf" #define DRV_VERSION "2.2" /* Poll interval in nS. */ #define OCTEON_CF_BUSY_POLL_INTERVAL 500000 #define DMA_CFG 0 #define DMA_TIM 0x20 #define DMA_INT 0x38 #define DMA_INT_EN 0x50 struct octeon_cf_port { struct hrtimer delayed_finish; struct ata_port *ap; int dma_finished; void *c0; unsigned int cs0; unsigned int cs1; bool is_true_ide; u64 dma_base; }; static struct scsi_host_template octeon_cf_sht = { ATA_PIO_SHT(DRV_NAME), }; static int enable_dma; module_param(enable_dma, int, 0444); MODULE_PARM_DESC(enable_dma, "Enable use of DMA on interfaces that support it (0=no dma [default], 1=use dma)"); /** * Convert nanosecond based time to setting used in the * boot bus timing register, based on timing multiple */ static unsigned int ns_to_tim_reg(unsigned int tim_mult, unsigned int nsecs) { unsigned int val; /* * Compute # of eclock periods to get desired duration in * nanoseconds. */ val = DIV_ROUND_UP(nsecs * (octeon_get_io_clock_rate() / 1000000), 1000 * tim_mult); return val; } static void octeon_cf_set_boot_reg_cfg(int cs, unsigned int multiplier) { union cvmx_mio_boot_reg_cfgx reg_cfg; unsigned int tim_mult; switch (multiplier) { case 8: tim_mult = 3; break; case 4: tim_mult = 0; break; case 2: tim_mult = 2; break; default: tim_mult = 1; break; } reg_cfg.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_CFGX(cs)); reg_cfg.s.dmack = 0; /* Don't assert DMACK on access */ reg_cfg.s.tim_mult = tim_mult; /* Timing mutiplier */ reg_cfg.s.rd_dly = 0; /* Sample on falling edge of BOOT_OE */ reg_cfg.s.sam = 0; /* Don't combine write and output enable */ reg_cfg.s.we_ext = 0; /* No write enable extension */ reg_cfg.s.oe_ext = 0; /* No read enable extension */ reg_cfg.s.en = 1; /* Enable this region */ reg_cfg.s.orbit = 0; /* Don't combine with previous region */ reg_cfg.s.ale = 0; /* Don't do address multiplexing */ cvmx_write_csr(CVMX_MIO_BOOT_REG_CFGX(cs), reg_cfg.u64); } /** * Called after libata determines the needed PIO mode. This * function programs the Octeon bootbus regions to support the * timing requirements of the PIO mode. * * @ap: ATA port information * @dev: ATA device */ static void octeon_cf_set_piomode(struct ata_port *ap, struct ata_device *dev) { struct octeon_cf_port *cf_port = ap->private_data; union cvmx_mio_boot_reg_timx reg_tim; int T; struct ata_timing timing; unsigned int div; int use_iordy; int trh; int pause; /* These names are timing parameters from the ATA spec */ int t1; int t2; int t2i; /* * A divisor value of four will overflow the timing fields at * clock rates greater than 800MHz */ if (octeon_get_io_clock_rate() <= 800000000) div = 4; else div = 8; T = (int)((1000000000000LL * div) / octeon_get_io_clock_rate()); if (ata_timing_compute(dev, dev->pio_mode, &timing, T, T)) BUG(); t1 = timing.setup; if (t1) t1--; t2 = timing.active; if (t2) t2--; t2i = timing.act8b; if (t2i) t2i--; trh = ns_to_tim_reg(div, 20); if (trh) trh--; pause = (int)timing.cycle - (int)timing.active - (int)timing.setup - trh; if (pause < 0) pause = 0; if (pause) pause--; octeon_cf_set_boot_reg_cfg(cf_port->cs0, div); if (cf_port->is_true_ide) /* True IDE mode, program both chip selects. */ octeon_cf_set_boot_reg_cfg(cf_port->cs1, div); use_iordy = ata_pio_need_iordy(dev); reg_tim.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_TIMX(cf_port->cs0)); /* Disable page mode */ reg_tim.s.pagem = 0; /* Enable dynamic timing */ reg_tim.s.waitm = use_iordy; /* Pages are disabled */ reg_tim.s.pages = 0; /* We don't use multiplexed address mode */ reg_tim.s.ale = 0; /* Not used */ reg_tim.s.page = 0; /* Time after IORDY to coninue to assert the data */ reg_tim.s.wait = 0; /* Time to wait to complete the cycle. */ reg_tim.s.pause = pause; /* How long to hold after a write to de-assert CE. */ reg_tim.s.wr_hld = trh; /* How long to wait after a read to de-assert CE. */ reg_tim.s.rd_hld = trh; /* How long write enable is asserted */ reg_tim.s.we = t2; /* How long read enable is asserted */ reg_tim.s.oe = t2; /* Time after CE that read/write starts */ reg_tim.s.ce = ns_to_tim_reg(div, 5); /* Time before CE that address is valid */ reg_tim.s.adr = 0; /* Program the bootbus region timing for the data port chip select. */ cvmx_write_csr(CVMX_MIO_BOOT_REG_TIMX(cf_port->cs0), reg_tim.u64); if (cf_port->is_true_ide) /* True IDE mode, program both chip selects. */ cvmx_write_csr(CVMX_MIO_BOOT_REG_TIMX(cf_port->cs1), reg_tim.u64); } static void octeon_cf_set_dmamode(struct ata_port *ap, struct ata_device *dev) { struct octeon_cf_port *cf_port = ap->private_data; union cvmx_mio_boot_pin_defs pin_defs; union cvmx_mio_boot_dma_timx dma_tim; unsigned int oe_a; unsigned int oe_n; unsigned int dma_ackh; unsigned int dma_arq; unsigned int pause; unsigned int T0, Tkr, Td; unsigned int tim_mult; int c; const struct ata_timing *timing; timing = ata_timing_find_mode(dev->dma_mode); T0 = timing->cycle; Td = timing->active; Tkr = timing->recover; dma_ackh = timing->dmack_hold; dma_tim.u64 = 0; /* dma_tim.s.tim_mult = 0 --> 4x */ tim_mult = 4; /* not spec'ed, value in eclocks, not affected by tim_mult */ dma_arq = 8; pause = 25 - dma_arq * 1000 / (octeon_get_io_clock_rate() / 1000000); /* Tz */ oe_a = Td; /* Tkr from cf spec, lengthened to meet T0 */ oe_n = max(T0 - oe_a, Tkr); pin_defs.u64 = cvmx_read_csr(CVMX_MIO_BOOT_PIN_DEFS); /* DMA channel number. */ c = (cf_port->dma_base & 8) >> 3; /* Invert the polarity if the default is 0*/ dma_tim.s.dmack_pi = (pin_defs.u64 & (1ull << (11 + c))) ? 0 : 1; dma_tim.s.oe_n = ns_to_tim_reg(tim_mult, oe_n); dma_tim.s.oe_a = ns_to_tim_reg(tim_mult, oe_a); /* * This is tI, C.F. spec. says 0, but Sony CF card requires * more, we use 20 nS. */ dma_tim.s.dmack_s = ns_to_tim_reg(tim_mult, 20); dma_tim.s.dmack_h = ns_to_tim_reg(tim_mult, dma_ackh); dma_tim.s.dmarq = dma_arq; dma_tim.s.pause = ns_to_tim_reg(tim_mult, pause); dma_tim.s.rd_dly = 0; /* Sample right on edge */ /* writes only */ dma_tim.s.we_n = ns_to_tim_reg(tim_mult, oe_n); dma_tim.s.we_a = ns_to_tim_reg(tim_mult, oe_a); pr_debug("ns to ticks (mult %d) of %d is: %d\n", tim_mult, 60, ns_to_tim_reg(tim_mult, 60)); pr_debug("oe_n: %d, oe_a: %d, dmack_s: %d, dmack_h: %d, dmarq: %d, pause: %d\n", dma_tim.s.oe_n, dma_tim.s.oe_a, dma_tim.s.dmack_s, dma_tim.s.dmack_h, dma_tim.s.dmarq, dma_tim.s.pause); cvmx_write_csr(cf_port->dma_base + DMA_TIM, dma_tim.u64); } /** * Handle an 8 bit I/O request. * * @dev: Device to access * @buffer: Data buffer * @buflen: Length of the buffer. * @rw: True to write. */ static unsigned int octeon_cf_data_xfer8(struct ata_device *dev, unsigned char *buffer, unsigned int buflen, int rw) { struct ata_port *ap = dev->link->ap; void __iomem *data_addr = ap->ioaddr.data_addr; unsigned long words; int count; words = buflen; if (rw) { count = 16; while (words--) { iowrite8(*buffer, data_addr); buffer++; /* * Every 16 writes do a read so the bootbus * FIFO doesn't fill up. */ if (--count == 0) { ioread8(ap->ioaddr.altstatus_addr); count = 16; } } } else { ioread8_rep(data_addr, buffer, words); } return buflen; } /** * Handle a 16 bit I/O request. * * @dev: Device to access * @buffer: Data buffer * @buflen: Length of the buffer. * @rw: True to write. */ static unsigned int octeon_cf_data_xfer16(struct ata_device *dev, unsigned char *buffer, unsigned int buflen, int rw) { struct ata_port *ap = dev->link->ap; void __iomem *data_addr = ap->ioaddr.data_addr; unsigned long words; int count; words = buflen / 2; if (rw) { count = 16; while (words--) { iowrite16(*(uint16_t *)buffer, data_addr); buffer += sizeof(uint16_t); /* * Every 16 writes do a read so the bootbus * FIFO doesn't fill up. */ if (--count == 0) { ioread8(ap->ioaddr.altstatus_addr); count = 16; } } } else { while (words--) { *(uint16_t *)buffer = ioread16(data_addr); buffer += sizeof(uint16_t); } } /* Transfer trailing 1 byte, if any. */ if (unlikely(buflen & 0x01)) { __le16 align_buf[1] = { 0 }; if (rw == READ) { align_buf[0] = cpu_to_le16(ioread16(data_addr)); memcpy(buffer, align_buf, 1); } else { memcpy(align_buf, buffer, 1); iowrite16(le16_to_cpu(align_buf[0]), data_addr); } words++; } return buflen; } /** * Read the taskfile for 16bit non-True IDE only. */ static void octeon_cf_tf_read16(struct ata_port *ap, struct ata_taskfile *tf) { u16 blob; /* The base of the registers is at ioaddr.data_addr. */ void __iomem *base = ap->ioaddr.data_addr; blob = __raw_readw(base + 0xc); tf->feature = blob >> 8; blob = __raw_readw(base + 2); tf->nsect = blob & 0xff; tf->lbal = blob >> 8; blob = __raw_readw(base + 4); tf->lbam = blob & 0xff; tf->lbah = blob >> 8; blob = __raw_readw(base + 6); tf->device = blob & 0xff; tf->command = blob >> 8; if (tf->flags & ATA_TFLAG_LBA48) { if (likely(ap->ioaddr.ctl_addr)) { iowrite8(tf->ctl | ATA_HOB, ap->ioaddr.ctl_addr); blob = __raw_readw(base + 0xc); tf->hob_feature = blob >> 8; blob = __raw_readw(base + 2); tf->hob_nsect = blob & 0xff; tf->hob_lbal = blob >> 8; blob = __raw_readw(base + 4); tf->hob_lbam = blob & 0xff; tf->hob_lbah = blob >> 8; iowrite8(tf->ctl, ap->ioaddr.ctl_addr); ap->last_ctl = tf->ctl; } else { WARN_ON(1); } } } static u8 octeon_cf_check_status16(struct ata_port *ap) { u16 blob; void __iomem *base = ap->ioaddr.data_addr; blob = __raw_readw(base + 6); return blob >> 8; } static int octeon_cf_softreset16(struct ata_link *link, unsigned int *classes, unsigned long deadline) { struct ata_port *ap = link->ap; void __iomem *base = ap->ioaddr.data_addr; int rc; u8 err; DPRINTK("about to softreset\n"); __raw_writew(ap->ctl, base + 0xe); udelay(20); __raw_writew(ap->ctl | ATA_SRST, base + 0xe); udelay(20); __raw_writew(ap->ctl, base + 0xe); rc = ata_sff_wait_after_reset(link, 1, deadline); if (rc) { ata_link_err(link, "SRST failed (errno=%d)\n", rc); return rc; } /* determine by signature whether we have ATA or ATAPI devices */ classes[0] = ata_sff_dev_classify(&link->device[0], 1, &err); DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]); return 0; } /** * Load the taskfile for 16bit non-True IDE only. The device_addr is * not loaded, we do this as part of octeon_cf_exec_command16. */ static void octeon_cf_tf_load16(struct ata_port *ap, const struct ata_taskfile *tf) { unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR; /* The base of the registers is at ioaddr.data_addr. */ void __iomem *base = ap->ioaddr.data_addr; if (tf->ctl != ap->last_ctl) { iowrite8(tf->ctl, ap->ioaddr.ctl_addr); ap->last_ctl = tf->ctl; ata_wait_idle(ap); } if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) { __raw_writew(tf->hob_feature << 8, base + 0xc); __raw_writew(tf->hob_nsect | tf->hob_lbal << 8, base + 2); __raw_writew(tf->hob_lbam | tf->hob_lbah << 8, base + 4); VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n", tf->hob_feature, tf->hob_nsect, tf->hob_lbal, tf->hob_lbam, tf->hob_lbah); } if (is_addr) { __raw_writew(tf->feature << 8, base + 0xc); __raw_writew(tf->nsect | tf->lbal << 8, base + 2); __raw_writew(tf->lbam | tf->lbah << 8, base + 4); VPRINTK("feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n", tf->feature, tf->nsect, tf->lbal, tf->lbam, tf->lbah); } ata_wait_idle(ap); } static void octeon_cf_dev_select(struct ata_port *ap, unsigned int device) { /* There is only one device, do nothing. */ return; } /* * Issue ATA command to host controller. The device_addr is also sent * as it must be written in a combined write with the command. */ static void octeon_cf_exec_command16(struct ata_port *ap, const struct ata_taskfile *tf) { /* The base of the registers is at ioaddr.data_addr. */ void __iomem *base = ap->ioaddr.data_addr; u16 blob; if (tf->flags & ATA_TFLAG_DEVICE) { VPRINTK("device 0x%X\n", tf->device); blob = tf->device; } else { blob = 0; } DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command); blob |= (tf->command << 8); __raw_writew(blob, base + 6); ata_wait_idle(ap); } static void octeon_cf_ata_port_noaction(struct ata_port *ap) { } static void octeon_cf_dma_setup(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct octeon_cf_port *cf_port; cf_port = ap->private_data; DPRINTK("ENTER\n"); /* issue r/w command */ qc->cursg = qc->sg; cf_port->dma_finished = 0; ap->ops->sff_exec_command(ap, &qc->tf); DPRINTK("EXIT\n"); } /** * Start a DMA transfer that was already setup * * @qc: Information about the DMA */ static void octeon_cf_dma_start(struct ata_queued_cmd *qc) { struct octeon_cf_port *cf_port = qc->ap->private_data; union cvmx_mio_boot_dma_cfgx mio_boot_dma_cfg; union cvmx_mio_boot_dma_intx mio_boot_dma_int; struct scatterlist *sg; VPRINTK("%d scatterlists\n", qc->n_elem); /* Get the scatter list entry we need to DMA into */ sg = qc->cursg; BUG_ON(!sg); /* * Clear the DMA complete status. */ mio_boot_dma_int.u64 = 0; mio_boot_dma_int.s.done = 1; cvmx_write_csr(cf_port->dma_base + DMA_INT, mio_boot_dma_int.u64); /* Enable the interrupt. */ cvmx_write_csr(cf_port->dma_base + DMA_INT_EN, mio_boot_dma_int.u64); /* Set the direction of the DMA */ mio_boot_dma_cfg.u64 = 0; #ifdef __LITTLE_ENDIAN mio_boot_dma_cfg.s.endian = 1; #endif mio_boot_dma_cfg.s.en = 1; mio_boot_dma_cfg.s.rw = ((qc->tf.flags & ATA_TFLAG_WRITE) != 0); /* * Don't stop the DMA if the device deasserts DMARQ. Many * compact flashes deassert DMARQ for a short time between * sectors. Instead of stopping and restarting the DMA, we'll * let the hardware do it. If the DMA is really stopped early * due to an error condition, a later timeout will force us to * stop. */ mio_boot_dma_cfg.s.clr = 0; /* Size is specified in 16bit words and minus one notation */ mio_boot_dma_cfg.s.size = sg_dma_len(sg) / 2 - 1; /* We need to swap the high and low bytes of every 16 bits */ mio_boot_dma_cfg.s.swap8 = 1; mio_boot_dma_cfg.s.adr = sg_dma_address(sg); VPRINTK("%s %d bytes address=%p\n", (mio_boot_dma_cfg.s.rw) ? "write" : "read", sg->length, (void *)(unsigned long)mio_boot_dma_cfg.s.adr); cvmx_write_csr(cf_port->dma_base + DMA_CFG, mio_boot_dma_cfg.u64); } /** * * LOCKING: * spin_lock_irqsave(host lock) * */ static unsigned int octeon_cf_dma_finished(struct ata_port *ap, struct ata_queued_cmd *qc) { struct ata_eh_info *ehi = &ap->link.eh_info; struct octeon_cf_port *cf_port = ap->private_data; union cvmx_mio_boot_dma_cfgx dma_cfg; union cvmx_mio_boot_dma_intx dma_int; u8 status; VPRINTK("ata%u: protocol %d task_state %d\n", ap->print_id, qc->tf.protocol, ap->hsm_task_state); if (ap->hsm_task_state != HSM_ST_LAST) return 0; dma_cfg.u64 = cvmx_read_csr(cf_port->dma_base + DMA_CFG); if (dma_cfg.s.size != 0xfffff) { /* Error, the transfer was not complete. */ qc->err_mask |= AC_ERR_HOST_BUS; ap->hsm_task_state = HSM_ST_ERR; } /* Stop and clear the dma engine. */ dma_cfg.u64 = 0; dma_cfg.s.size = -1; cvmx_write_csr(cf_port->dma_base + DMA_CFG, dma_cfg.u64); /* Disable the interrupt. */ dma_int.u64 = 0; cvmx_write_csr(cf_port->dma_base + DMA_INT_EN, dma_int.u64); /* Clear the DMA complete status */ dma_int.s.done = 1; cvmx_write_csr(cf_port->dma_base + DMA_INT, dma_int.u64); status = ap->ops->sff_check_status(ap); ata_sff_hsm_move(ap, qc, status, 0); if (unlikely(qc->err_mask) && (qc->tf.protocol == ATA_PROT_DMA)) ata_ehi_push_desc(ehi, "DMA stat 0x%x", status); return 1; } /* * Check if any queued commands have more DMAs, if so start the next * transfer, else do end of transfer handling. */ static irqreturn_t octeon_cf_interrupt(int irq, void *dev_instance) { struct ata_host *host = dev_instance; struct octeon_cf_port *cf_port; int i; unsigned int handled = 0; unsigned long flags; spin_lock_irqsave(&host->lock, flags); DPRINTK("ENTER\n"); for (i = 0; i < host->n_ports; i++) { u8 status; struct ata_port *ap; struct ata_queued_cmd *qc; union cvmx_mio_boot_dma_intx dma_int; union cvmx_mio_boot_dma_cfgx dma_cfg; ap = host->ports[i]; cf_port = ap->private_data; dma_int.u64 = cvmx_read_csr(cf_port->dma_base + DMA_INT); dma_cfg.u64 = cvmx_read_csr(cf_port->dma_base + DMA_CFG); qc = ata_qc_from_tag(ap, ap->link.active_tag); if (!qc || (qc->tf.flags & ATA_TFLAG_POLLING)) continue; if (dma_int.s.done && !dma_cfg.s.en) { if (!sg_is_last(qc->cursg)) { qc->cursg = sg_next(qc->cursg); handled = 1; octeon_cf_dma_start(qc); continue; } else { cf_port->dma_finished = 1; } } if (!cf_port->dma_finished) continue; status = ioread8(ap->ioaddr.altstatus_addr); if (status & (ATA_BUSY | ATA_DRQ)) { /* * We are busy, try to handle it later. This * is the DMA finished interrupt, and it could * take a little while for the card to be * ready for more commands. */ /* Clear DMA irq. */ dma_int.u64 = 0; dma_int.s.done = 1; cvmx_write_csr(cf_port->dma_base + DMA_INT, dma_int.u64); hrtimer_start_range_ns(&cf_port->delayed_finish, ns_to_ktime(OCTEON_CF_BUSY_POLL_INTERVAL), OCTEON_CF_BUSY_POLL_INTERVAL / 5, HRTIMER_MODE_REL); handled = 1; } else { handled |= octeon_cf_dma_finished(ap, qc); } } spin_unlock_irqrestore(&host->lock, flags); DPRINTK("EXIT\n"); return IRQ_RETVAL(handled); } static enum hrtimer_restart octeon_cf_delayed_finish(struct hrtimer *hrt) { struct octeon_cf_port *cf_port = container_of(hrt, struct octeon_cf_port, delayed_finish); struct ata_port *ap = cf_port->ap; struct ata_host *host = ap->host; struct ata_queued_cmd *qc; unsigned long flags; u8 status; enum hrtimer_restart rv = HRTIMER_NORESTART; spin_lock_irqsave(&host->lock, flags); /* * If the port is not waiting for completion, it must have * handled it previously. The hsm_task_state is * protected by host->lock. */ if (ap->hsm_task_state != HSM_ST_LAST || !cf_port->dma_finished) goto out; status = ioread8(ap->ioaddr.altstatus_addr); if (status & (ATA_BUSY | ATA_DRQ)) { /* Still busy, try again. */ hrtimer_forward_now(hrt, ns_to_ktime(OCTEON_CF_BUSY_POLL_INTERVAL)); rv = HRTIMER_RESTART; goto out; } qc = ata_qc_from_tag(ap, ap->link.active_tag); if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING))) octeon_cf_dma_finished(ap, qc); out: spin_unlock_irqrestore(&host->lock, flags); return rv; } static void octeon_cf_dev_config(struct ata_device *dev) { /* * A maximum of 2^20 - 1 16 bit transfers are possible with * the bootbus DMA. So we need to throttle max_sectors to * (2^12 - 1 == 4095) to assure that this can never happen. */ dev->max_sectors = min(dev->max_sectors, 4095U); } /* * We don't do ATAPI DMA so return 0. */ static int octeon_cf_check_atapi_dma(struct ata_queued_cmd *qc) { return 0; } static unsigned int octeon_cf_qc_issue(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; switch (qc->tf.protocol) { case ATA_PROT_DMA: WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING); ap->ops->sff_tf_load(ap, &qc->tf); /* load tf registers */ octeon_cf_dma_setup(qc); /* set up dma */ octeon_cf_dma_start(qc); /* initiate dma */ ap->hsm_task_state = HSM_ST_LAST; break; case ATAPI_PROT_DMA: dev_err(ap->dev, "Error, ATAPI not supported\n"); BUG(); default: return ata_sff_qc_issue(qc); } return 0; } static struct ata_port_operations octeon_cf_ops = { .inherits = &ata_sff_port_ops, .check_atapi_dma = octeon_cf_check_atapi_dma, .qc_prep = ata_noop_qc_prep, .qc_issue = octeon_cf_qc_issue, .sff_dev_select = octeon_cf_dev_select, .sff_irq_on = octeon_cf_ata_port_noaction, .sff_irq_clear = octeon_cf_ata_port_noaction, .cable_detect = ata_cable_40wire, .set_piomode = octeon_cf_set_piomode, .set_dmamode = octeon_cf_set_dmamode, .dev_config = octeon_cf_dev_config, }; static int octeon_cf_probe(struct platform_device *pdev) { struct resource *res_cs0, *res_cs1; bool is_16bit; const __be32 *cs_num; struct property *reg_prop; int n_addr, n_size, reg_len; struct device_node *node; const void *prop; void __iomem *cs0; void __iomem *cs1 = NULL; struct ata_host *host; struct ata_port *ap; int irq = 0; irq_handler_t irq_handler = NULL; void __iomem *base; struct octeon_cf_port *cf_port; int rv = -ENOMEM; node = pdev->dev.of_node; if (node == NULL) return -EINVAL; cf_port = kzalloc(sizeof(*cf_port), GFP_KERNEL); if (!cf_port) return -ENOMEM; cf_port->is_true_ide = (of_find_property(node, "cavium,true-ide", NULL) != NULL); prop = of_get_property(node, "cavium,bus-width", NULL); if (prop) is_16bit = (be32_to_cpup(prop) == 16); else is_16bit = false; n_addr = of_n_addr_cells(node); n_size = of_n_size_cells(node); reg_prop = of_find_property(node, "reg", &reg_len); if (!reg_prop || reg_len < sizeof(__be32)) { rv = -EINVAL; goto free_cf_port; } cs_num = reg_prop->value; cf_port->cs0 = be32_to_cpup(cs_num); if (cf_port->is_true_ide) { struct device_node *dma_node; dma_node = of_parse_phandle(node, "cavium,dma-engine-handle", 0); if (dma_node) { struct platform_device *dma_dev; dma_dev = of_find_device_by_node(dma_node); if (dma_dev) { struct resource *res_dma; int i; res_dma = platform_get_resource(dma_dev, IORESOURCE_MEM, 0); if (!res_dma) { of_node_put(dma_node); rv = -EINVAL; goto free_cf_port; } cf_port->dma_base = (u64)devm_ioremap_nocache(&pdev->dev, res_dma->start, resource_size(res_dma)); if (!cf_port->dma_base) { of_node_put(dma_node); rv = -EINVAL; goto free_cf_port; } irq_handler = octeon_cf_interrupt; i = platform_get_irq(dma_dev, 0); if (i > 0) irq = i; } of_node_put(dma_node); } res_cs1 = platform_get_resource(pdev, IORESOURCE_MEM, 1); if (!res_cs1) { rv = -EINVAL; goto free_cf_port; } cs1 = devm_ioremap_nocache(&pdev->dev, res_cs1->start, resource_size(res_cs1)); if (!cs1) goto free_cf_port; if (reg_len < (n_addr + n_size + 1) * sizeof(__be32)) { rv = -EINVAL; goto free_cf_port; } cs_num += n_addr + n_size; cf_port->cs1 = be32_to_cpup(cs_num); } res_cs0 = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res_cs0) { rv = -EINVAL; goto free_cf_port; } cs0 = devm_ioremap_nocache(&pdev->dev, res_cs0->start, resource_size(res_cs0)); if (!cs0) goto free_cf_port; /* allocate host */ host = ata_host_alloc(&pdev->dev, 1); if (!host) goto free_cf_port; ap = host->ports[0]; ap->private_data = cf_port; pdev->dev.platform_data = cf_port; cf_port->ap = ap; ap->ops = &octeon_cf_ops; ap->pio_mask = ATA_PIO6; ap->flags |= ATA_FLAG_NO_ATAPI | ATA_FLAG_PIO_POLLING; if (!is_16bit) { base = cs0 + 0x800; ap->ioaddr.cmd_addr = base; ata_sff_std_ports(&ap->ioaddr); ap->ioaddr.altstatus_addr = base + 0xe; ap->ioaddr.ctl_addr = base + 0xe; octeon_cf_ops.sff_data_xfer = octeon_cf_data_xfer8; } else if (cf_port->is_true_ide) { base = cs0; ap->ioaddr.cmd_addr = base + (ATA_REG_CMD << 1) + 1; ap->ioaddr.data_addr = base + (ATA_REG_DATA << 1); ap->ioaddr.error_addr = base + (ATA_REG_ERR << 1) + 1; ap->ioaddr.feature_addr = base + (ATA_REG_FEATURE << 1) + 1; ap->ioaddr.nsect_addr = base + (ATA_REG_NSECT << 1) + 1; ap->ioaddr.lbal_addr = base + (ATA_REG_LBAL << 1) + 1; ap->ioaddr.lbam_addr = base + (ATA_REG_LBAM << 1) + 1; ap->ioaddr.lbah_addr = base + (ATA_REG_LBAH << 1) + 1; ap->ioaddr.device_addr = base + (ATA_REG_DEVICE << 1) + 1; ap->ioaddr.status_addr = base + (ATA_REG_STATUS << 1) + 1; ap->ioaddr.command_addr = base + (ATA_REG_CMD << 1) + 1; ap->ioaddr.altstatus_addr = cs1 + (6 << 1) + 1; ap->ioaddr.ctl_addr = cs1 + (6 << 1) + 1; octeon_cf_ops.sff_data_xfer = octeon_cf_data_xfer16; ap->mwdma_mask = enable_dma ? ATA_MWDMA4 : 0; /* True IDE mode needs a timer to poll for not-busy. */ hrtimer_init(&cf_port->delayed_finish, CLOCK_MONOTONIC, HRTIMER_MODE_REL); cf_port->delayed_finish.function = octeon_cf_delayed_finish; } else { /* 16 bit but not True IDE */ base = cs0 + 0x800; octeon_cf_ops.sff_data_xfer = octeon_cf_data_xfer16; octeon_cf_ops.softreset = octeon_cf_softreset16; octeon_cf_ops.sff_check_status = octeon_cf_check_status16; octeon_cf_ops.sff_tf_read = octeon_cf_tf_read16; octeon_cf_ops.sff_tf_load = octeon_cf_tf_load16; octeon_cf_ops.sff_exec_command = octeon_cf_exec_command16; ap->ioaddr.data_addr = base + ATA_REG_DATA; ap->ioaddr.nsect_addr = base + ATA_REG_NSECT; ap->ioaddr.lbal_addr = base + ATA_REG_LBAL; ap->ioaddr.ctl_addr = base + 0xe; ap->ioaddr.altstatus_addr = base + 0xe; } cf_port->c0 = ap->ioaddr.ctl_addr; pdev->dev.coherent_dma_mask = DMA_BIT_MASK(64); pdev->dev.dma_mask = &pdev->dev.coherent_dma_mask; ata_port_desc(ap, "cmd %p ctl %p", base, ap->ioaddr.ctl_addr); dev_info(&pdev->dev, "version " DRV_VERSION" %d bit%s.\n", is_16bit ? 16 : 8, cf_port->is_true_ide ? ", True IDE" : ""); return ata_host_activate(host, irq, irq_handler, IRQF_SHARED, &octeon_cf_sht); free_cf_port: kfree(cf_port); return rv; } static void octeon_cf_shutdown(struct device *dev) { union cvmx_mio_boot_dma_cfgx dma_cfg; union cvmx_mio_boot_dma_intx dma_int; struct octeon_cf_port *cf_port = dev->platform_data; if (cf_port->dma_base) { /* Stop and clear the dma engine. */ dma_cfg.u64 = 0; dma_cfg.s.size = -1; cvmx_write_csr(cf_port->dma_base + DMA_CFG, dma_cfg.u64); /* Disable the interrupt. */ dma_int.u64 = 0; cvmx_write_csr(cf_port->dma_base + DMA_INT_EN, dma_int.u64); /* Clear the DMA complete status */ dma_int.s.done = 1; cvmx_write_csr(cf_port->dma_base + DMA_INT, dma_int.u64); __raw_writeb(0, cf_port->c0); udelay(20); __raw_writeb(ATA_SRST, cf_port->c0); udelay(20); __raw_writeb(0, cf_port->c0); mdelay(100); } } static struct of_device_id octeon_cf_match[] = { { .compatible = "cavium,ebt3000-compact-flash", }, {}, }; MODULE_DEVICE_TABLE(of, octeon_i2c_match); static struct platform_driver octeon_cf_driver = { .probe = octeon_cf_probe, .driver = { .name = DRV_NAME, .owner = THIS_MODULE, .of_match_table = octeon_cf_match, .shutdown = octeon_cf_shutdown }, }; static int __init octeon_cf_init(void) { return platform_driver_register(&octeon_cf_driver); } MODULE_AUTHOR("David Daney <ddaney@caviumnetworks.com>"); MODULE_DESCRIPTION("low-level driver for Cavium OCTEON Compact Flash PATA"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); MODULE_ALIAS("platform:" DRV_NAME); module_init(octeon_cf_init);
apache-2.0
catiedev/mbed-os
targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/drivers/fsl_smc.c
119
12246
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fsl_smc.h" #include "fsl_flash.h" #if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) void SMC_GetParam(SMC_Type *base, smc_param_t *param) { uint32_t reg = base->PARAM; param->hsrunEnable = (bool)(reg & SMC_PARAM_EHSRUN_MASK); param->llsEnable = (bool)(reg & SMC_PARAM_ELLS_MASK); param->lls2Enable = (bool)(reg & SMC_PARAM_ELLS2_MASK); param->vlls0Enable = (bool)(reg & SMC_PARAM_EVLLS0_MASK); } #endif /* FSL_FEATURE_SMC_HAS_PARAM */ void SMC_PreEnterStopModes(void) { flash_prefetch_speculation_status_t speculationStatus = { kFLASH_prefetchSpeculationOptionDisable, /* Disable instruction speculation.*/ kFLASH_prefetchSpeculationOptionDisable, /* Disable data speculation.*/ }; __disable_irq(); __ISB(); /* * Before enter stop modes, the flash cache prefetch should be disabled. * Otherwise the prefetch might be interrupted by stop, then the data and * and instruction from flash are wrong. */ FLASH_PflashSetPrefetchSpeculation(&speculationStatus); } void SMC_PostExitStopModes(void) { flash_prefetch_speculation_status_t speculationStatus = { kFLASH_prefetchSpeculationOptionEnable, /* Enable instruction speculation.*/ kFLASH_prefetchSpeculationOptionEnable, /* Enable data speculation.*/ }; FLASH_PflashSetPrefetchSpeculation(&speculationStatus); __enable_irq(); __ISB(); } status_t SMC_SetPowerModeRun(SMC_Type *base) { uint8_t reg; reg = base->PMCTRL; /* configure Normal RUN mode */ reg &= ~SMC_PMCTRL_RUNM_MASK; reg |= (kSMC_RunNormal << SMC_PMCTRL_RUNM_SHIFT); base->PMCTRL = reg; return kStatus_Success; } #if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) status_t SMC_SetPowerModeHsrun(SMC_Type *base) { uint8_t reg; reg = base->PMCTRL; /* configure High Speed RUN mode */ reg &= ~SMC_PMCTRL_RUNM_MASK; reg |= (kSMC_Hsrun << SMC_PMCTRL_RUNM_SHIFT); base->PMCTRL = reg; return kStatus_Success; } #endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ status_t SMC_SetPowerModeWait(SMC_Type *base) { /* configure Normal Wait mode */ SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; __DSB(); __WFI(); __ISB(); return kStatus_Success; } status_t SMC_SetPowerModeStop(SMC_Type *base, smc_partial_stop_option_t option) { uint8_t reg; #if (defined(FSL_FEATURE_SMC_HAS_PSTOPO) && FSL_FEATURE_SMC_HAS_PSTOPO) /* configure the Partial Stop mode in Noraml Stop mode */ reg = base->STOPCTRL; reg &= ~SMC_STOPCTRL_PSTOPO_MASK; reg |= ((uint32_t)option << SMC_STOPCTRL_PSTOPO_SHIFT); base->STOPCTRL = reg; #endif /* configure Normal Stop mode */ reg = base->PMCTRL; reg &= ~SMC_PMCTRL_STOPM_MASK; reg |= (kSMC_StopNormal << SMC_PMCTRL_STOPM_SHIFT); base->PMCTRL = reg; /* Set the SLEEPDEEP bit to enable deep sleep mode (stop mode) */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* read back to make sure the configuration valid before enter stop mode */ (void)base->PMCTRL; __DSB(); __WFI(); __ISB(); /* check whether the power mode enter Stop mode succeed */ if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) { return kStatus_SMC_StopAbort; } else { return kStatus_Success; } } status_t SMC_SetPowerModeVlpr(SMC_Type *base #if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) , bool wakeupMode #endif ) { uint8_t reg; reg = base->PMCTRL; #if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) /* configure whether the system remains in VLP mode on an interrupt */ if (wakeupMode) { /* exits to RUN mode on an interrupt */ reg |= SMC_PMCTRL_LPWUI_MASK; } else { /* remains in VLP mode on an interrupt */ reg &= ~SMC_PMCTRL_LPWUI_MASK; } #endif /* FSL_FEATURE_SMC_HAS_LPWUI */ /* configure VLPR mode */ reg &= ~SMC_PMCTRL_RUNM_MASK; reg |= (kSMC_RunVlpr << SMC_PMCTRL_RUNM_SHIFT); base->PMCTRL = reg; return kStatus_Success; } status_t SMC_SetPowerModeVlpw(SMC_Type *base) { /* configure VLPW mode */ /* Set the SLEEPDEEP bit to enable deep sleep mode */ SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; __DSB(); __WFI(); __ISB(); return kStatus_Success; } status_t SMC_SetPowerModeVlps(SMC_Type *base) { uint8_t reg; /* configure VLPS mode */ reg = base->PMCTRL; reg &= ~SMC_PMCTRL_STOPM_MASK; reg |= (kSMC_StopVlps << SMC_PMCTRL_STOPM_SHIFT); base->PMCTRL = reg; /* Set the SLEEPDEEP bit to enable deep sleep mode */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* read back to make sure the configuration valid before enter stop mode */ (void)base->PMCTRL; __DSB(); __WFI(); __ISB(); /* check whether the power mode enter VLPS mode succeed */ if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) { return kStatus_SMC_StopAbort; } else { return kStatus_Success; } } #if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) status_t SMC_SetPowerModeLls(SMC_Type *base #if ((defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO)) , const smc_power_mode_lls_config_t *config #endif ) { uint8_t reg; /* configure to LLS mode */ reg = base->PMCTRL; reg &= ~SMC_PMCTRL_STOPM_MASK; reg |= (kSMC_StopLls << SMC_PMCTRL_STOPM_SHIFT); base->PMCTRL = reg; /* configure LLS sub-mode*/ #if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) reg = base->STOPCTRL; reg &= ~SMC_STOPCTRL_LLSM_MASK; reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_LLSM_SHIFT); base->STOPCTRL = reg; #endif /* FSL_FEATURE_SMC_HAS_LLS_SUBMODE */ #if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) if (config->enableLpoClock) { base->STOPCTRL &= ~SMC_STOPCTRL_LPOPO_MASK; } else { base->STOPCTRL |= SMC_STOPCTRL_LPOPO_MASK; } #endif /* FSL_FEATURE_SMC_HAS_LPOPO */ /* Set the SLEEPDEEP bit to enable deep sleep mode */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* read back to make sure the configuration valid before enter stop mode */ (void)base->PMCTRL; __DSB(); __WFI(); __ISB(); /* check whether the power mode enter LLS mode succeed */ if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) { return kStatus_SMC_StopAbort; } else { return kStatus_Success; } } #endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ #if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) status_t SMC_SetPowerModeVlls(SMC_Type *base, const smc_power_mode_vlls_config_t *config) { uint8_t reg; #if (defined(FSL_FEATURE_SMC_HAS_PORPO) && FSL_FEATURE_SMC_HAS_PORPO) #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) if (config->subMode == kSMC_StopSub0) #endif { /* configure whether the Por Detect work in Vlls0 mode */ if (config->enablePorDetectInVlls0) { #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) base->VLLSCTRL &= ~SMC_VLLSCTRL_PORPO_MASK; #else base->STOPCTRL &= ~SMC_STOPCTRL_PORPO_MASK; #endif } else { #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) base->VLLSCTRL |= SMC_VLLSCTRL_PORPO_MASK; #else base->STOPCTRL |= SMC_STOPCTRL_PORPO_MASK; #endif } } #endif /* FSL_FEATURE_SMC_HAS_PORPO */ #if (defined(FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) && FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) else if (config->subMode == kSMC_StopSub2) { /* configure whether the Por Detect work in Vlls0 mode */ if (config->enableRam2InVlls2) { #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) base->VLLSCTRL |= SMC_VLLSCTRL_RAM2PO_MASK; #else base->STOPCTRL |= SMC_STOPCTRL_RAM2PO_MASK; #endif } else { #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) base->VLLSCTRL &= ~SMC_VLLSCTRL_RAM2PO_MASK; #else base->STOPCTRL &= ~SMC_STOPCTRL_RAM2PO_MASK; #endif } } else { } #endif /* FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION */ /* configure to VLLS mode */ reg = base->PMCTRL; reg &= ~SMC_PMCTRL_STOPM_MASK; reg |= (kSMC_StopVlls << SMC_PMCTRL_STOPM_SHIFT); base->PMCTRL = reg; /* configure the VLLS sub-mode */ #if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) reg = base->VLLSCTRL; reg &= ~SMC_VLLSCTRL_VLLSM_MASK; reg |= ((uint32_t)config->subMode << SMC_VLLSCTRL_VLLSM_SHIFT); base->VLLSCTRL = reg; #else #if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) reg = base->STOPCTRL; reg &= ~SMC_STOPCTRL_LLSM_MASK; reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_LLSM_SHIFT); base->STOPCTRL = reg; #else reg = base->STOPCTRL; reg &= ~SMC_STOPCTRL_VLLSM_MASK; reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_VLLSM_SHIFT); base->STOPCTRL = reg; #endif /* FSL_FEATURE_SMC_HAS_LLS_SUBMODE */ #endif #if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) if (config->enableLpoClock) { base->STOPCTRL &= ~SMC_STOPCTRL_LPOPO_MASK; } else { base->STOPCTRL |= SMC_STOPCTRL_LPOPO_MASK; } #endif /* FSL_FEATURE_SMC_HAS_LPOPO */ /* Set the SLEEPDEEP bit to enable deep sleep mode */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* read back to make sure the configuration valid before enter stop mode */ (void)base->PMCTRL; __DSB(); __WFI(); __ISB(); /* check whether the power mode enter LLS mode succeed */ if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) { return kStatus_SMC_StopAbort; } else { return kStatus_Success; } } #endif /* FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE */
apache-2.0
ybellavance/python-for-android
python-modules/twisted/jni/python/_initgroups.c
125
1686
/***************************************************************************** Copyright (c) 2002 Zope Corporation and Contributors. All Rights Reserved. This software is subject to the provisions of the Zope Public License, Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ****************************************************************************/ /* * This has been reported for inclusion in Python here: http://bugs.python.org/issue7333 * Hopefully we may be able to remove this file in some years. */ #include "Python.h" #if defined(__unix__) || defined(unix) || defined(__NetBSD__) || defined(__MACH__) /* Mac OS X */ #include <grp.h> #include <sys/types.h> #include <unistd.h> static PyObject * initgroups_initgroups(PyObject *self, PyObject *args) { char *username; unsigned int igid; gid_t gid; if (!PyArg_ParseTuple(args, "sI:initgroups", &username, &igid)) return NULL; gid = igid; if (initgroups(username, gid) == -1) return PyErr_SetFromErrno(PyExc_OSError); Py_INCREF(Py_None); return Py_None; } static PyMethodDef InitgroupsMethods[] = { {"initgroups", initgroups_initgroups, METH_VARARGS}, {NULL, NULL} }; #else /* This module is empty on non-UNIX systems. */ static PyMethodDef InitgroupsMethods[] = { {NULL, NULL} }; #endif /* defined(__unix__) || defined(unix) */ void init_initgroups(void) { Py_InitModule("_initgroups", InitgroupsMethods); }
apache-2.0
weolar/miniblink49
node/openssl/openssl/crypto/lhash/lh_test.c
130
3752
/* crypto/lhash/lh_test.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/lhash.h> main() { LHASH *conf; char buf[256]; int i; conf = lh_new(lh_strhash, strcmp); for (;;) { char *p; buf[0] = '\0'; fgets(buf, 256, stdin); if (buf[0] == '\0') break; i = strlen(buf); p = OPENSSL_malloc(i + 1); memcpy(p, buf, i + 1); lh_insert(conf, p); } lh_node_stats(conf, stdout); lh_stats(conf, stdout); lh_node_usage_stats(conf, stdout); exit(0); }
apache-2.0
andreparrish/python-for-android
python3-alpha/python3-src/Modules/_ctypes/libffi_msvc/types.c
138
3538
/* ----------------------------------------------------------------------- types.c - Copyright (c) 1996, 1998 Red Hat, Inc. Predefined ffi_types needed by libffi. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include <ffi.h> #include <ffi_common.h> /* Type definitions */ #define FFI_INTEGRAL_TYPEDEF(n, s, a, t) ffi_type ffi_type_##n = { s, a, t, NULL } #define FFI_AGGREGATE_TYPEDEF(n, e) ffi_type ffi_type_##n = { 0, 0, FFI_TYPE_STRUCT, e } /* Size and alignment are fake here. They must not be 0. */ FFI_INTEGRAL_TYPEDEF(void, 1, 1, FFI_TYPE_VOID); FFI_INTEGRAL_TYPEDEF(uint8, 1, 1, FFI_TYPE_UINT8); FFI_INTEGRAL_TYPEDEF(sint8, 1, 1, FFI_TYPE_SINT8); FFI_INTEGRAL_TYPEDEF(uint16, 2, 2, FFI_TYPE_UINT16); FFI_INTEGRAL_TYPEDEF(sint16, 2, 2, FFI_TYPE_SINT16); FFI_INTEGRAL_TYPEDEF(uint32, 4, 4, FFI_TYPE_UINT32); FFI_INTEGRAL_TYPEDEF(sint32, 4, 4, FFI_TYPE_SINT32); FFI_INTEGRAL_TYPEDEF(float, 4, 4, FFI_TYPE_FLOAT); #if defined ALPHA || defined SPARC64 || defined X86_64 || defined S390X \ || defined IA64 FFI_INTEGRAL_TYPEDEF(pointer, 8, 8, FFI_TYPE_POINTER); #else FFI_INTEGRAL_TYPEDEF(pointer, 4, 4, FFI_TYPE_POINTER); #endif #if defined X86 || defined X86_WIN32 || defined ARM || defined M68K FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); #elif defined SH FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); #else FFI_INTEGRAL_TYPEDEF(uint64, 8, 8, FFI_TYPE_UINT64); FFI_INTEGRAL_TYPEDEF(sint64, 8, 8, FFI_TYPE_SINT64); #endif #if defined X86 || defined X86_WIN32 || defined M68K FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); FFI_INTEGRAL_TYPEDEF(longdouble, 12, 4, FFI_TYPE_LONGDOUBLE); #elif defined ARM || defined SH || defined POWERPC_AIX || defined POWERPC_DARWIN FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); FFI_INTEGRAL_TYPEDEF(longdouble, 8, 4, FFI_TYPE_LONGDOUBLE); #elif defined SPARC FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); #ifdef SPARC64 FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); #else FFI_INTEGRAL_TYPEDEF(longdouble, 16, 8, FFI_TYPE_LONGDOUBLE); #endif #elif defined X86_64 FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); #else FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); FFI_INTEGRAL_TYPEDEF(longdouble, 8, 8, FFI_TYPE_LONGDOUBLE); #endif
apache-2.0
lzo/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/contrib/libwebhdfs/src/hdfs_json_parser.c
144
19813
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "exception.h" #include "hdfs.h" /* for hdfsFileInfo */ #include "hdfs_json_parser.h" #include <stdlib.h> #include <string.h> #include <ctype.h> #include <jansson.h> static const char * const temporaryRedirectCode = "307 TEMPORARY_REDIRECT"; static const char * const twoHundredOKCode = "200 OK"; static const char * const twoHundredOneCreatedCode = "201 Created"; static const char * const httpHeaderString = "HTTP/1.1"; /** * Exception information after calling JSON operations */ struct jsonException { const char *exception; const char *javaClassName; const char *message; }; /** Print out the JSON exception information */ static int printJsonExceptionV(struct jsonException *exc, int noPrintFlags, const char *fmt, va_list ap) { char *javaClassName = NULL; int excErrno = EINTERNAL, shouldPrint = 0; if (!exc) { fprintf(stderr, "printJsonExceptionV: the jsonException is NULL\n"); return EINTERNAL; } javaClassName = strdup(exc->javaClassName); if (!javaClassName) { fprintf(stderr, "printJsonExceptionV: internal out of memory error\n"); return EINTERNAL; } getExceptionInfo(javaClassName, noPrintFlags, &excErrno, &shouldPrint); free(javaClassName); if (shouldPrint) { vfprintf(stderr, fmt, ap); fprintf(stderr, " error:\n"); fprintf(stderr, "Exception: %s\nJavaClassName: %s\nMessage: %s\n", exc->exception, exc->javaClassName, exc->message); } free(exc); return excErrno; } /** * Print out JSON exception information. * * @param exc The exception information to print and free * @param noPrintFlags Flags which determine which exceptions we should NOT * print. * @param fmt Printf-style format list * @param ... Printf-style varargs * * @return The POSIX error number associated with the exception * object. */ static int printJsonException(struct jsonException *exc, int noPrintFlags, const char *fmt, ...) { va_list ap; int ret = 0; va_start(ap, fmt); ret = printJsonExceptionV(exc, noPrintFlags, fmt, ap); va_end(ap); return ret; } /** Parse the exception information from JSON */ static struct jsonException *parseJsonException(json_t *jobj) { const char *key = NULL; json_t *value = NULL; struct jsonException *exception = NULL; void *iter = NULL; exception = calloc(1, sizeof(*exception)); if (!exception) { return NULL; } iter = json_object_iter(jobj); while (iter) { key = json_object_iter_key(iter); value = json_object_iter_value(iter); if (!strcmp(key, "exception")) { exception->exception = json_string_value(value); } else if (!strcmp(key, "javaClassName")) { exception->javaClassName = json_string_value(value); } else if (!strcmp(key, "message")) { exception->message = json_string_value(value); } iter = json_object_iter_next(jobj, iter); } return exception; } /** * Parse the exception information which is presented in JSON * * @param content Exception information in JSON * @return jsonException for printing out */ static struct jsonException *parseException(const char *content) { json_error_t error; size_t flags = 0; const char *key = NULL; json_t *value; json_t *jobj; struct jsonException *exception = NULL; if (!content) { return NULL; } jobj = json_loads(content, flags, &error); if (!jobj) { fprintf(stderr, "JSon parsing error: on line %d: %s\n", error.line, error.text); return NULL; } void *iter = json_object_iter(jobj); while(iter) { key = json_object_iter_key(iter); value = json_object_iter_value(iter); if (!strcmp(key, "RemoteException") && json_typeof(value) == JSON_OBJECT) { exception = parseJsonException(value); break; } iter = json_object_iter_next(jobj, iter); } json_decref(jobj); return exception; } /** * Parse the response information which uses TRUE/FALSE * to indicate whether the operation succeeded * * @param response Response information * @return 0 to indicate success */ static int parseBoolean(const char *response) { json_t *root, *value; json_error_t error; size_t flags = 0; int result = 0; root = json_loads(response, flags, &error); if (!root) { fprintf(stderr, "JSon parsing error: on line %d: %s\n", error.line, error.text); return EIO; } void *iter = json_object_iter(root); value = json_object_iter_value(iter); if (json_typeof(value) == JSON_TRUE) { result = 0; } else { result = EIO; // FALSE means error in remote NN/DN } json_decref(root); return result; } int parseMKDIR(const char *response) { return parseBoolean(response); } int parseRENAME(const char *response) { return parseBoolean(response); } int parseDELETE(const char *response) { return parseBoolean(response); } int parseSETREPLICATION(const char *response) { return parseBoolean(response); } /** * Check the header of response to see if it's 200 OK * * @param header Header information for checking * @param content Stores exception information if there are errors * @param operation Indicate the operation for exception printing * @return 0 for success */ static int checkHeader(const char *header, const char *content, const char *operation) { char *result = NULL; const char delims[] = ":"; char *savepter; int ret = 0; if (!header || strncmp(header, "HTTP/", strlen("HTTP/"))) { return EINVAL; } if (!(strstr(header, twoHundredOKCode)) || !(result = strstr(header, "Content-Length"))) { struct jsonException *exc = parseException(content); if (exc) { ret = printJsonException(exc, PRINT_EXC_ALL, "Calling WEBHDFS (%s)", operation); } else { ret = EIO; } return ret; } result = strtok_r(result, delims, &savepter); result = strtok_r(NULL, delims, &savepter); while (isspace(*result)) { result++; } // Content-Length should be equal to 0, // and the string should be "0\r\nServer" if (strncmp(result, "0\r\n", 3)) { ret = EIO; } return ret; } int parseCHMOD(const char *header, const char *content) { return checkHeader(header, content, "CHMOD"); } int parseCHOWN(const char *header, const char *content) { return checkHeader(header, content, "CHOWN"); } int parseUTIMES(const char *header, const char *content) { return checkHeader(header, content, "SETTIMES"); } /** * Check if the header contains correct information * ("307 TEMPORARY_REDIRECT" and "Location") * * @param header Header for parsing * @param content Contains exception information * if the remote operation failed * @param operation Specify the remote operation when printing out exception * @return 0 for success */ static int checkRedirect(const char *header, const char *content, const char *operation) { const char *locTag = "Location"; int ret = 0, offset = 0; // The header must start with "HTTP/1.1" if (!header || strncmp(header, httpHeaderString, strlen(httpHeaderString))) { return EINVAL; } offset += strlen(httpHeaderString); while (isspace(header[offset])) { offset++; } // Looking for "307 TEMPORARY_REDIRECT" in header if (strncmp(header + offset, temporaryRedirectCode, strlen(temporaryRedirectCode))) { // Process possible exception information struct jsonException *exc = parseException(content); if (exc) { ret = printJsonException(exc, PRINT_EXC_ALL, "Calling WEBHDFS (%s)", operation); } else { ret = EIO; } return ret; } // Here we just simply check if header contains "Location" tag, // detailed processing is in parseDnLoc if (!(strstr(header, locTag))) { ret = EIO; } return ret; } int parseNnWRITE(const char *header, const char *content) { return checkRedirect(header, content, "Write(NameNode)"); } int parseNnAPPEND(const char *header, const char *content) { return checkRedirect(header, content, "Append(NameNode)"); } /** 0 for success , -1 for out of range, other values for error */ int parseOPEN(const char *header, const char *content) { int ret = 0, offset = 0; if (!header || strncmp(header, httpHeaderString, strlen(httpHeaderString))) { return EINVAL; } offset += strlen(httpHeaderString); while (isspace(header[offset])) { offset++; } if (strncmp(header + offset, temporaryRedirectCode, strlen(temporaryRedirectCode)) || !strstr(header, twoHundredOKCode)) { struct jsonException *exc = parseException(content); if (exc) { // If the exception is an IOException and it is because // the offset is out of the range, do not print out the exception if (!strcasecmp(exc->exception, "IOException") && strstr(exc->message, "out of the range")) { ret = -1; } else { ret = printJsonException(exc, PRINT_EXC_ALL, "Calling WEBHDFS (OPEN)"); } } else { ret = EIO; } } return ret; } int parseDnLoc(char *content, char **dn) { char *url = NULL, *dnLocation = NULL, *savepter, *tempContent; const char *prefix = "Location: http://"; const char *prefixToRemove = "Location: "; const char *delims = "\r\n"; tempContent = strdup(content); if (!tempContent) { return ENOMEM; } dnLocation = strtok_r(tempContent, delims, &savepter); while (dnLocation && strncmp(dnLocation, "Location:", strlen("Location:"))) { dnLocation = strtok_r(NULL, delims, &savepter); } if (!dnLocation) { return EIO; } while (isspace(*dnLocation)) { dnLocation++; } if (strncmp(dnLocation, prefix, strlen(prefix))) { return EIO; } url = strdup(dnLocation + strlen(prefixToRemove)); if (!url) { return ENOMEM; } *dn = url; return 0; } int parseDnWRITE(const char *header, const char *content) { int ret = 0; if (header == NULL || header[0] == '\0' || strncmp(header, "HTTP/", strlen("HTTP/"))) { return EINVAL; } if (!(strstr(header, twoHundredOneCreatedCode))) { struct jsonException *exc = parseException(content); if (exc) { ret = printJsonException(exc, PRINT_EXC_ALL, "Calling WEBHDFS (WRITE(DataNode))"); } else { ret = EIO; } } return ret; } int parseDnAPPEND(const char *header, const char *content) { int ret = 0; if (header == NULL || header[0] == '\0' || strncmp(header, "HTTP/", strlen("HTTP/"))) { return EINVAL; } if (!(strstr(header, twoHundredOKCode))) { struct jsonException *exc = parseException(content); if (exc) { ret = printJsonException(exc, PRINT_EXC_ALL, "Calling WEBHDFS (APPEND(DataNode))"); } else { ret = EIO; } } return ret; } /** * Retrieve file status from the JSON object * * @param jobj JSON object for parsing, which contains * file status information * @param fileStat hdfsFileInfo handle to hold file status information * @return 0 on success */ static int parseJsonForFileStatus(json_t *jobj, hdfsFileInfo *fileStat) { const char *key, *tempstr; json_t *value; void *iter = NULL; iter = json_object_iter(jobj); while (iter) { key = json_object_iter_key(iter); value = json_object_iter_value(iter); if (!strcmp(key, "accessTime")) { // json field contains time in milliseconds, // hdfsFileInfo is counted in seconds fileStat->mLastAccess = json_integer_value(value) / 1000; } else if (!strcmp(key, "blockSize")) { fileStat->mBlockSize = json_integer_value(value); } else if (!strcmp(key, "length")) { fileStat->mSize = json_integer_value(value); } else if (!strcmp(key, "modificationTime")) { fileStat->mLastMod = json_integer_value(value) / 1000; } else if (!strcmp(key, "replication")) { fileStat->mReplication = json_integer_value(value); } else if (!strcmp(key, "group")) { fileStat->mGroup = strdup(json_string_value(value)); if (!fileStat->mGroup) { return ENOMEM; } } else if (!strcmp(key, "owner")) { fileStat->mOwner = strdup(json_string_value(value)); if (!fileStat->mOwner) { return ENOMEM; } } else if (!strcmp(key, "pathSuffix")) { fileStat->mName = strdup(json_string_value(value)); if (!fileStat->mName) { return ENOMEM; } } else if (!strcmp(key, "permission")) { tempstr = json_string_value(value); fileStat->mPermissions = (short) strtol(tempstr, NULL, 8); } else if (!strcmp(key, "type")) { tempstr = json_string_value(value); if (!strcmp(tempstr, "DIRECTORY")) { fileStat->mKind = kObjectKindDirectory; } else { fileStat->mKind = kObjectKindFile; } } // Go to the next key-value pair in the json object iter = json_object_iter_next(jobj, iter); } return 0; } int parseGFS(const char *response, hdfsFileInfo *fileStat, int printError) { int ret = 0, printFlag; json_error_t error; size_t flags = 0; json_t *jobj, *value; const char *key; void *iter = NULL; if (!response || !fileStat) { return EIO; } jobj = json_loads(response, flags, &error); if (!jobj) { fprintf(stderr, "error while parsing json: on line %d: %s\n", error.line, error.text); return EIO; } iter = json_object_iter(jobj); key = json_object_iter_key(iter); value = json_object_iter_value(iter); if (json_typeof(value) == JSON_OBJECT) { if (!strcmp(key, "RemoteException")) { struct jsonException *exception = parseJsonException(value); if (exception) { if (printError) { printFlag = PRINT_EXC_ALL; } else { printFlag = NOPRINT_EXC_FILE_NOT_FOUND | NOPRINT_EXC_ACCESS_CONTROL | NOPRINT_EXC_PARENT_NOT_DIRECTORY; } ret = printJsonException(exception, printFlag, "Calling WEBHDFS GETFILESTATUS"); } else { ret = EIO; } } else if (!strcmp(key, "FileStatus")) { ret = parseJsonForFileStatus(value, fileStat); } else { ret = EIO; } } else { ret = EIO; } json_decref(jobj); return ret; } /** * Parse the JSON array. Called to parse the result of * the LISTSTATUS operation. Thus each element of the JSON array is * a JSON object with the information of a file entry contained * in the folder. * * @param jobj The JSON array to be parsed * @param fileStat The hdfsFileInfo handle used to * store a group of file information * @param numEntries Capture the number of files in the folder * @return 0 for success */ static int parseJsonArrayForFileStatuses(json_t *jobj, hdfsFileInfo **fileStat, int *numEntries) { json_t *jvalue = NULL; int i = 0, ret = 0, arraylen = 0; hdfsFileInfo *fileInfo = NULL; arraylen = (int) json_array_size(jobj); if (arraylen > 0) { fileInfo = calloc(arraylen, sizeof(hdfsFileInfo)); if (!fileInfo) { return ENOMEM; } } for (i = 0; i < arraylen; i++) { //Getting the array element at position i jvalue = json_array_get(jobj, i); if (json_is_object(jvalue)) { ret = parseJsonForFileStatus(jvalue, &fileInfo[i]); if (ret) { goto done; } } else { ret = EIO; goto done; } } done: if (ret) { free(fileInfo); } else { *numEntries = arraylen; *fileStat = fileInfo; } return ret; } int parseLS(const char *response, hdfsFileInfo **fileStats, int *numOfEntries) { int ret = 0; json_error_t error; size_t flags = 0; json_t *jobj, *value; const char *key; void *iter = NULL; if (!response || response[0] == '\0' || !fileStats) { return EIO; } jobj = json_loads(response, flags, &error); if (!jobj) { fprintf(stderr, "error while parsing json: on line %d: %s\n", error.line, error.text); return EIO; } iter = json_object_iter(jobj); key = json_object_iter_key(iter); value = json_object_iter_value(iter); if (json_typeof(value) == JSON_OBJECT) { if (!strcmp(key, "RemoteException")) { struct jsonException *exception = parseJsonException(value); if (exception) { ret = printJsonException(exception, PRINT_EXC_ALL, "Calling WEBHDFS GETFILESTATUS"); } else { ret = EIO; } } else if (!strcmp(key, "FileStatuses")) { iter = json_object_iter(value); value = json_object_iter_value(iter); if (json_is_array(value)) { ret = parseJsonArrayForFileStatuses(value, fileStats, numOfEntries); } else { ret = EIO; } } else { ret = EIO; } } else { ret = EIO; } json_decref(jobj); return ret; }
apache-2.0
MRSDTeamI/bud-e
ROS/src/BUD-E/hearbo_2dnav/hearbo_cart_ts/hearbo_cart_joy/build/CMakeFiles/CompilerIdC/CMakeCCompilerId.c
239
5973
#ifdef __cplusplus # error "A C++ compiler has been selected for C." #endif #if defined(__18CXX) # define ID_VOID_MAIN #endif #if defined(__INTEL_COMPILER) || defined(__ICC) # define COMPILER_ID "Intel" #elif defined(__clang__) # define COMPILER_ID "Clang" #elif defined(__BORLANDC__) # define COMPILER_ID "Borland" #elif defined(__WATCOMC__) # define COMPILER_ID "Watcom" #elif defined(__SUNPRO_C) # define COMPILER_ID "SunPro" #elif defined(__HP_cc) # define COMPILER_ID "HP" #elif defined(__DECC) # define COMPILER_ID "Compaq" #elif defined(__IBMC__) # if defined(__COMPILER_VER__) # define COMPILER_ID "zOS" # elif __IBMC__ >= 800 # define COMPILER_ID "XL" # else # define COMPILER_ID "VisualAge" # endif #elif defined(__PGI) # define COMPILER_ID "PGI" #elif defined(__PATHSCALE__) # define COMPILER_ID "PathScale" #elif defined(_CRAYC) # define COMPILER_ID "Cray" #elif defined(__TI_COMPILER_VERSION__) # define COMPILER_ID "TI_DSP" #elif defined(__TINYC__) # define COMPILER_ID "TinyCC" #elif defined(__SCO_VERSION__) # define COMPILER_ID "SCO" #elif defined(__GNUC__) # define COMPILER_ID "GNU" #elif defined(_MSC_VER) # define COMPILER_ID "MSVC" #elif defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) /* Analog Devices C++ compiler for Blackfin, TigerSHARC and SHARC (21000) DSPs */ # define COMPILER_ID "ADSP" /* IAR Systems compiler for embedded systems. http://www.iar.com Not supported yet by CMake #elif defined(__IAR_SYSTEMS_ICC__) # define COMPILER_ID "IAR" */ /* sdcc, the small devices C compiler for embedded systems, http://sdcc.sourceforge.net */ #elif defined(SDCC) # define COMPILER_ID "SDCC" #elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION) # define COMPILER_ID "MIPSpro" /* This compiler is either not known or is too old to define an identification macro. Try to identify the platform and guess that it is the native compiler. */ #elif defined(__sgi) # define COMPILER_ID "MIPSpro" #elif defined(__hpux) || defined(__hpua) # define COMPILER_ID "HP" #else /* unknown compiler */ # define COMPILER_ID "" #endif /* Construct the string literal in pieces to prevent the source from getting matched. Store it in a pointer rather than an array because some compilers will just produce instructions to fill the array rather than assigning a pointer to a static array. */ char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; /* Identify known platforms by name. */ #if defined(__linux) || defined(__linux__) || defined(linux) # define PLATFORM_ID "Linux" #elif defined(__CYGWIN__) # define PLATFORM_ID "Cygwin" #elif defined(__MINGW32__) # define PLATFORM_ID "MinGW" #elif defined(__APPLE__) # define PLATFORM_ID "Darwin" #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) # define PLATFORM_ID "Windows" #elif defined(__FreeBSD__) || defined(__FreeBSD) # define PLATFORM_ID "FreeBSD" #elif defined(__NetBSD__) || defined(__NetBSD) # define PLATFORM_ID "NetBSD" #elif defined(__OpenBSD__) || defined(__OPENBSD) # define PLATFORM_ID "OpenBSD" #elif defined(__sun) || defined(sun) # define PLATFORM_ID "SunOS" #elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) # define PLATFORM_ID "AIX" #elif defined(__sgi) || defined(__sgi__) || defined(_SGI) # define PLATFORM_ID "IRIX" #elif defined(__hpux) || defined(__hpux__) # define PLATFORM_ID "HP-UX" #elif defined(__HAIKU) || defined(__HAIKU__) || defined(_HAIKU) # define PLATFORM_ID "Haiku" /* Haiku also defines __BEOS__ so we must put it prior to the check for __BEOS__ */ #elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) # define PLATFORM_ID "BeOS" #elif defined(__QNX__) || defined(__QNXNTO__) # define PLATFORM_ID "QNX" #elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) # define PLATFORM_ID "Tru64" #elif defined(__riscos) || defined(__riscos__) # define PLATFORM_ID "RISCos" #elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) # define PLATFORM_ID "SINIX" #elif defined(__UNIX_SV__) # define PLATFORM_ID "UNIX_SV" #elif defined(__bsdos__) # define PLATFORM_ID "BSDOS" #elif defined(_MPRAS) || defined(MPRAS) # define PLATFORM_ID "MP-RAS" #elif defined(__osf) || defined(__osf__) # define PLATFORM_ID "OSF1" #elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) # define PLATFORM_ID "SCO_SV" #elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) # define PLATFORM_ID "ULTRIX" #elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) # define PLATFORM_ID "Xenix" #else /* unknown platform */ # define PLATFORM_ID "" #endif /* For windows compilers MSVC and Intel we can determine the architecture of the compiler being used. This is because the compilers do not have flags that can change the architecture, but rather depend on which compiler is being used */ #if defined(_WIN32) && defined(_MSC_VER) # if defined(_M_IA64) # define ARCHITECTURE_ID "IA64" # elif defined(_M_X64) || defined(_M_AMD64) # define ARCHITECTURE_ID "x64" # elif defined(_M_IX86) # define ARCHITECTURE_ID "X86" # else /* unknown architecture */ # define ARCHITECTURE_ID "" # endif #else # define ARCHITECTURE_ID "" #endif /* Construct the string literal in pieces to prevent the source from getting matched. Store it in a pointer rather than an array because some compilers will just produce instructions to fill the array rather than assigning a pointer to a static array. */ char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; /*--------------------------------------------------------------------------*/ #ifdef ID_VOID_MAIN void main() {} #else int main(int argc, char* argv[]) { int require = 0; require += info_compiler[argc]; require += info_platform[argc]; require += info_arch[argc]; (void)argv; return require; } #endif
apache-2.0
Alloyed/Play--CodeGen
tests/Shift64Test.cpp
1
4362
#include "Shift64Test.h" #include "MemStream.h" #define CONSTANT_1 (0x8000FFFF01234567ULL) #define CONSTANT_2 (0x0123456789ABCDEFULL) CShift64Test::CShift64Test(uint32 shiftAmount) : m_shiftAmount(shiftAmount) { } CShift64Test::~CShift64Test() { } void CShift64Test::Run() { memset(&m_context, 0, sizeof(m_context)); m_context.value0 = CONSTANT_1; m_context.value1 = CONSTANT_2; m_context.shiftAmount = m_shiftAmount; m_function(&m_context); //Amounts are masked here because shift operations are expected to mask the shift amounts TEST_VERIFY(m_context.resultSra0 == static_cast<int64>(CONSTANT_1) >> static_cast<int32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSra1 == static_cast<int64>(CONSTANT_2) >> static_cast<int32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSraVar0 == static_cast<int64>(CONSTANT_1) >> static_cast<int32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSraVar1 == static_cast<int64>(CONSTANT_2) >> static_cast<int32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSrl0 == static_cast<uint64>(CONSTANT_1) >> static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSrl1 == static_cast<uint64>(CONSTANT_2) >> static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSrlVar0 == static_cast<uint64>(CONSTANT_1) >> static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultSrlVar1 == static_cast<uint64>(CONSTANT_2) >> static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultShl0 == static_cast<uint64>(CONSTANT_1) << static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultShl1 == static_cast<uint64>(CONSTANT_2) << static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultShlVar0 == static_cast<uint64>(CONSTANT_1) << static_cast<uint32>(m_shiftAmount & 0x3F)); TEST_VERIFY(m_context.resultShlVar1 == static_cast<uint64>(CONSTANT_2) << static_cast<uint32>(m_shiftAmount & 0x3F)); } void CShift64Test::Compile(Jitter::CJitter& jitter) { Framework::CMemStream codeStream; jitter.SetStream(&codeStream); jitter.Begin(); { //------------------ //SRA Constant jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.Sra64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultSra0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.Sra64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultSra1)); //------------------ //SRA Variable jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Sra64(); jitter.PullRel64(offsetof(CONTEXT, resultSraVar0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Sra64(); jitter.PullRel64(offsetof(CONTEXT, resultSraVar1)); //------------------ //SRL Constant jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.Srl64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultSrl0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.Srl64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultSrl1)); //------------------ //SRL Variable jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Srl64(); jitter.PullRel64(offsetof(CONTEXT, resultSrlVar0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Srl64(); jitter.PullRel64(offsetof(CONTEXT, resultSrlVar1)); //------------------ //SHL Constant jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.Shl64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultShl0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.Shl64(m_shiftAmount); jitter.PullRel64(offsetof(CONTEXT, resultShl1)); //------------------ //SHL Variable jitter.PushRel64(offsetof(CONTEXT, value0)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Shl64(); jitter.PullRel64(offsetof(CONTEXT, resultShlVar0)); jitter.PushRel64(offsetof(CONTEXT, value1)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.Shl64(); jitter.PullRel64(offsetof(CONTEXT, resultShlVar1)); } jitter.End(); m_function = CMemoryFunction(codeStream.GetBuffer(), codeStream.GetSize()); }
bsd-2-clause
dplbsd/soc2013
head/sys/boot/i386/libi386/bioscd.c
2
9039
/*- * Copyright (c) 1998 Michael Smith <msmith@freebsd.org> * Copyright (c) 2001 John H. Baldwin <jhb@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: soc2013/dpl/head/sys/boot/i386/libi386/bioscd.c 227670 2011-11-09 14:37:47Z jhb $"); /* * BIOS CD device handling for CD's that have been booted off of via no * emulation booting as defined in the El Torito standard. * * Ideas and algorithms from: * * - FreeBSD libi386/biosdisk.c * */ #include <stand.h> #include <sys/param.h> #include <machine/bootinfo.h> #include <stdarg.h> #include <bootstrap.h> #include <btxv86.h> #include <edd.h> #include "libi386.h" #define BIOSCD_SECSIZE 2048 #define BUFSIZE (1 * BIOSCD_SECSIZE) #define MAXBCDEV 1 /* Major numbers for devices we frontend for. */ #define ACDMAJOR 117 #define CDMAJOR 15 #ifdef DISK_DEBUG # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else # define DEBUG(fmt, args...) #endif struct specification_packet { u_char sp_size; u_char sp_bootmedia; u_char sp_drive; u_char sp_controller; u_int sp_lba; u_short sp_devicespec; u_short sp_buffersegment; u_short sp_loadsegment; u_short sp_sectorcount; u_short sp_cylsec; u_char sp_head; }; /* * List of BIOS devices, translation from disk unit number to * BIOS unit number. */ static struct bcinfo { int bc_unit; /* BIOS unit number */ struct specification_packet bc_sp; } bcinfo [MAXBCDEV]; static int nbcinfo = 0; static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest); static int bc_init(void); static int bc_strategy(void *devdata, int flag, daddr_t dblk, size_t size, char *buf, size_t *rsize); static int bc_open(struct open_file *f, ...); static int bc_close(struct open_file *f); static void bc_print(int verbose); struct devsw bioscd = { "cd", DEVT_CD, bc_init, bc_strategy, bc_open, bc_close, noioctl, bc_print, NULL }; /* * Translate between BIOS device numbers and our private unit numbers. */ int bc_bios2unit(int biosdev) { int i; DEBUG("looking for bios device 0x%x", biosdev); for (i = 0; i < nbcinfo; i++) { DEBUG("bc unit %d is BIOS device 0x%x", i, bcinfo[i].bc_unit); if (bcinfo[i].bc_unit == biosdev) return(i); } return(-1); } int bc_unit2bios(int unit) { if ((unit >= 0) && (unit < nbcinfo)) return(bcinfo[unit].bc_unit); return(-1); } /* * We can't quiz, we have to be told what device to use, so this functoin * doesn't do anything. Instead, the loader calls bc_add() with the BIOS * device number to add. */ static int bc_init(void) { return (0); } int bc_add(int biosdev) { if (nbcinfo >= MAXBCDEV) return (-1); bcinfo[nbcinfo].bc_unit = biosdev; v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4b01; v86.edx = biosdev; v86.ds = VTOPSEG(&bcinfo[nbcinfo].bc_sp); v86.esi = VTOPOFF(&bcinfo[nbcinfo].bc_sp); v86int(); if ((v86.eax & 0xff00) != 0) return (-1); printf("BIOS CD is cd%d\n", nbcinfo); nbcinfo++; return(0); } /* * Print information about disks */ static void bc_print(int verbose) { char line[80]; int i; for (i = 0; i < nbcinfo; i++) { sprintf(line, " cd%d: Device 0x%x\n", i, bcinfo[i].bc_sp.sp_devicespec); pager_output(line); } } /* * Attempt to open the disk described by (dev) for use by (f). */ static int bc_open(struct open_file *f, ...) { va_list ap; struct i386_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct i386_devdesc *); va_end(ap); if (dev->d_unit >= nbcinfo) { DEBUG("attempt to open nonexistent disk"); return(ENXIO); } return(0); } static int bc_close(struct open_file *f) { return(0); } static int bc_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize) { struct i386_devdesc *dev; int unit; int blks; #ifdef BD_SUPPORT_FRAGS char fragbuf[BIOSCD_SECSIZE]; size_t fragsize; fragsize = size % BIOSCD_SECSIZE; #else if (size % BIOSCD_SECSIZE) return (EINVAL); #endif if (rw != F_READ) return(EROFS); dev = (struct i386_devdesc *)devdata; unit = dev->d_unit; blks = size / BIOSCD_SECSIZE; if (dblk % (BIOSCD_SECSIZE / DEV_BSIZE) != 0) return (EINVAL); dblk /= (BIOSCD_SECSIZE / DEV_BSIZE); DEBUG("read %d from %lld to %p", blks, dblk, buf); if (rsize) *rsize = 0; if (blks && bc_read(unit, dblk, blks, buf)) { DEBUG("read error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS DEBUG("frag read %d from %lld+%d to %p", fragsize, dblk, blks, buf + (blks * BIOSCD_SECSIZE)); if (fragsize && bc_read(unit, dblk + blks, 1, fragbuf)) { DEBUG("frag read error"); return(EIO); } bcopy(fragbuf, buf + (blks * BIOSCD_SECSIZE), fragsize); #endif if (rsize) *rsize = size; return (0); } /* Max number of sectors to bounce-buffer at a time. */ #define CD_BOUNCEBUF 8 static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest) { u_int maxfer, resid, result, retry, x; caddr_t bbuf, p, xp; static struct edd_packet packet; int biosdev; #ifdef DISK_DEBUG int error; #endif /* Just in case some idiot actually tries to read -1 blocks... */ if (blks < 0) return (-1); /* If nothing to do, just return succcess. */ if (blks == 0) return (0); /* Decide whether we have to bounce */ if (VTOP(dest) >> 20 != 0) { /* * The destination buffer is above first 1MB of * physical memory so we have to arrange a suitable * bounce buffer. */ x = min(CD_BOUNCEBUF, (unsigned)blks); bbuf = alloca(x * BIOSCD_SECSIZE); maxfer = x; } else { bbuf = NULL; maxfer = 0; } biosdev = bc_unit2bios(unit); resid = blks; p = dest; while (resid > 0) { if (bbuf) xp = bbuf; else xp = p; x = resid; if (maxfer > 0) x = min(x, maxfer); /* * Loop retrying the operation a couple of times. The BIOS * may also retry. */ for (retry = 0; retry < 3; retry++) { /* If retrying, reset the drive */ if (retry > 0) { v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0; v86.edx = biosdev; v86int(); } packet.len = sizeof(struct edd_packet); packet.count = x; packet.off = VTOPOFF(xp); packet.seg = VTOPSEG(xp); packet.lba = dblk; v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4200; v86.edx = biosdev; v86.ds = VTOPSEG(&packet); v86.esi = VTOPOFF(&packet); v86int(); result = V86_CY(v86.efl); if (result == 0) break; } #ifdef DISK_DEBUG error = (v86.eax >> 8) & 0xff; #endif DEBUG("%d sectors from %lld to %p (0x%x) %s", x, dblk, p, VTOP(p), result ? "failed" : "ok"); DEBUG("unit %d status 0x%x", unit, error); if (bbuf != NULL) bcopy(bbuf, p, x * BIOSCD_SECSIZE); p += (x * BIOSCD_SECSIZE); dblk += x; resid -= x; } /* hexdump(dest, (blks * BIOSCD_SECSIZE)); */ return(0); } /* * Return a suitable dev_t value for (dev). */ int bc_getdev(struct i386_devdesc *dev) { int biosdev, unit; int major; int rootdev; unit = dev->d_unit; biosdev = bc_unit2bios(unit); DEBUG("unit %d BIOS device %d", unit, biosdev); if (biosdev == -1) /* not a BIOS device */ return(-1); /* * XXX: Need to examine device spec here to figure out if SCSI or * ATAPI. No idea on how to figure out device number. All we can * really pass to the kernel is what bus and device on which bus we * were booted from, which dev_t isn't well suited to since those * number don't match to unit numbers very well. We may just need * to engage in a hack where we pass -C to the boot args if we are * the boot device. */ major = ACDMAJOR; unit = 0; /* XXX */ /* XXX: Assume partition 'a'. */ rootdev = MAKEBOOTDEV(major, 0, unit, 0); DEBUG("dev is 0x%x\n", rootdev); return(rootdev); }
bsd-2-clause
Treeeater/WebPermission
html/InputType.cpp
2
17086
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. * (C) 2006 Alexey Proskuryakov (ap@nypop.com) * Copyright (C) 2007 Samuel Weinig (sam@webkit.org) * Copyright (C) 2010 Google 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. * */ #include "config.h" #include "InputType.h" #include "BeforeTextInsertedEvent.h" #include "ButtonInputType.h" #include "CheckboxInputType.h" #include "ColorInputType.h" #include "DateComponents.h" #include "DateInputType.h" #include "DateTimeInputType.h" #include "DateTimeLocalInputType.h" #include "EmailInputType.h" #include "ExceptionCode.h" #include "FileInputType.h" #include "FormDataList.h" #include "HTMLFormElement.h" #include "HTMLInputElement.h" #include "HiddenInputType.h" #include "ImageInputType.h" #include "IsIndexInputType.h" #include "KeyboardEvent.h" #include "LocalizedStrings.h" #include "MonthInputType.h" #include "NumberInputType.h" #include "Page.h" #include "PasswordInputType.h" #include "RadioInputType.h" #include "RangeInputType.h" #include "RegularExpression.h" #include "RenderObject.h" #include "ResetInputType.h" #include "SearchInputType.h" #include "ShadowRoot.h" #include "SubmitInputType.h" #include "TelephoneInputType.h" #include "TextInputType.h" #include "TimeInputType.h" #include "URLInputType.h" #include "WeekInputType.h" #include <limits> #include <wtf/Assertions.h> #include <wtf/HashMap.h> #include <wtf/text/StringHash.h> namespace WebCore { using namespace std; typedef PassOwnPtr<InputType> (*InputTypeFactoryFunction)(HTMLInputElement*); typedef HashMap<String, InputTypeFactoryFunction, CaseFoldingHash> InputTypeFactoryMap; static PassOwnPtr<InputTypeFactoryMap> createInputTypeFactoryMap() { OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap); map->add(InputTypeNames::button(), ButtonInputType::create); map->add(InputTypeNames::checkbox(), CheckboxInputType::create); #if ENABLE(INPUT_COLOR) map->add(InputTypeNames::color(), ColorInputType::create); #endif map->add(InputTypeNames::date(), DateInputType::create); map->add(InputTypeNames::datetime(), DateTimeInputType::create); map->add(InputTypeNames::datetimelocal(), DateTimeLocalInputType::create); map->add(InputTypeNames::email(), EmailInputType::create); map->add(InputTypeNames::file(), FileInputType::create); map->add(InputTypeNames::hidden(), HiddenInputType::create); map->add(InputTypeNames::image(), ImageInputType::create); map->add(InputTypeNames::isindex(), IsIndexInputType::create); map->add(InputTypeNames::month(), MonthInputType::create); map->add(InputTypeNames::number(), NumberInputType::create); map->add(InputTypeNames::password(), PasswordInputType::create); map->add(InputTypeNames::radio(), RadioInputType::create); map->add(InputTypeNames::range(), RangeInputType::create); map->add(InputTypeNames::reset(), ResetInputType::create); map->add(InputTypeNames::search(), SearchInputType::create); map->add(InputTypeNames::submit(), SubmitInputType::create); map->add(InputTypeNames::telephone(), TelephoneInputType::create); map->add(InputTypeNames::time(), TimeInputType::create); map->add(InputTypeNames::url(), URLInputType::create); map->add(InputTypeNames::week(), WeekInputType::create); // No need to register "text" because it is the default type. return map.release(); } PassOwnPtr<InputType> InputType::create(HTMLInputElement* element, const String& typeName) { static const InputTypeFactoryMap* factoryMap = createInputTypeFactoryMap().leakPtr(); PassOwnPtr<InputType> (*factory)(HTMLInputElement*) = typeName.isEmpty() ? 0 : factoryMap->get(typeName); if (!factory) factory = TextInputType::create; return factory(element); } PassOwnPtr<InputType> InputType::createText(HTMLInputElement* element) { return TextInputType::create(element); } InputType::~InputType() { } bool InputType::isTextField() const { return false; } bool InputType::isTextType() const { return false; } bool InputType::isRangeControl() const { return false; } bool InputType::saveFormControlState(String& result) const { String currentValue = element()->value(); if (currentValue == element()->defaultValue()) return false; result = currentValue; return true; } void InputType::restoreFormControlState(const String& state) const { element()->setValue(state); } bool InputType::isFormDataAppendable() const { // There is no form data unless there's a name for non-image types. return !element()->name().isEmpty(); } bool InputType::appendFormData(FormDataList& encoding, bool) const { // Always successful. encoding.appendData(element()->name(), element()->value()); return true; } double InputType::valueAsDate() const { return DateComponents::invalidMilliseconds(); } void InputType::setValueAsDate(double, ExceptionCode& ec) const { ec = INVALID_STATE_ERR; } double InputType::valueAsNumber() const { return numeric_limits<double>::quiet_NaN(); } void InputType::setValueAsNumber(double, bool, ExceptionCode& ec) const { ec = INVALID_STATE_ERR; } bool InputType::supportsValidation() const { return true; } bool InputType::typeMismatchFor(const String&) const { return false; } bool InputType::typeMismatch() const { return false; } bool InputType::supportsRequired() const { // Almost all validatable types support @required. return supportsValidation(); } bool InputType::valueMissing(const String&) const { return false; } bool InputType::patternMismatch(const String&) const { return false; } bool InputType::rangeUnderflow(const String&) const { return false; } bool InputType::rangeOverflow(const String&) const { return false; } bool InputType::supportsRangeLimitation() const { return false; } double InputType::defaultValueForStepUp() const { return 0; } double InputType::minimum() const { ASSERT_NOT_REACHED(); return 0; } double InputType::maximum() const { ASSERT_NOT_REACHED(); return 0; } bool InputType::sizeShouldIncludeDecoration(int, int& preferredSize) const { preferredSize = element()->size(); return false; } bool InputType::stepMismatch(const String&, double) const { // Non-supported types should be rejected by HTMLInputElement::getAllowedValueStep(). ASSERT_NOT_REACHED(); return false; } double InputType::stepBase() const { ASSERT_NOT_REACHED(); return 0; } double InputType::stepBaseWithDecimalPlaces(unsigned* decimalPlaces) const { if (decimalPlaces) *decimalPlaces = 0; return stepBase(); } double InputType::defaultStep() const { return numeric_limits<double>::quiet_NaN(); } double InputType::stepScaleFactor() const { return numeric_limits<double>::quiet_NaN(); } bool InputType::parsedStepValueShouldBeInteger() const { return false; } bool InputType::scaledStepValueShouldBeInteger() const { return false; } double InputType::acceptableError(double) const { return 0; } String InputType::typeMismatchText() const { return validationMessageTypeMismatchText(); } String InputType::valueMissingText() const { return validationMessageValueMissingText(); } void InputType::handleClickEvent(MouseEvent*) { } void InputType::handleMouseDownEvent(MouseEvent*) { } void InputType::handleDOMActivateEvent(Event*) { } void InputType::handleKeydownEvent(KeyboardEvent*) { } void InputType::handleKeypressEvent(KeyboardEvent*) { } void InputType::handleKeyupEvent(KeyboardEvent*) { } void InputType::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*) { } void InputType::handleWheelEvent(WheelEvent*) { } void InputType::forwardEvent(Event*) { } bool InputType::shouldSubmitImplicitly(Event* event) { return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && static_cast<KeyboardEvent*>(event)->charCode() == '\r'; } PassRefPtr<HTMLFormElement> InputType::formForSubmission() const { return element()->form(); } RenderObject* InputType::createRenderer(RenderArena*, RenderStyle* style) const { return RenderObject::createObject(element(), style); } void InputType::createShadowSubtree() { } void InputType::destroyShadowSubtree() { element()->removeShadowRoot(); } double InputType::parseToDouble(const String&, double defaultValue) const { return defaultValue; } double InputType::parseToDoubleWithDecimalPlaces(const String& src, double defaultValue, unsigned *decimalPlaces) const { if (decimalPlaces) *decimalPlaces = 0; return parseToDouble(src, defaultValue); } bool InputType::parseToDateComponents(const String&, DateComponents*) const { ASSERT_NOT_REACHED(); return false; } String InputType::serialize(double) const { ASSERT_NOT_REACHED(); return String(); } void InputType::dispatchSimulatedClickIfActive(KeyboardEvent* event) const { if (element()->active()) element()->dispatchSimulatedClick(event); event->setDefaultHandled(); } Chrome* InputType::chrome() const { if (Page* page = element()->document()->page()) return page->chrome(); return 0; } bool InputType::canSetStringValue() const { return true; } bool InputType::isKeyboardFocusable() const { return true; } bool InputType::shouldUseInputMethod() const { return false; } void InputType::willBlur() { } void InputType::accessKeyAction(bool) { element()->focus(false); } void InputType::attach() { } void InputType::detach() { } void InputType::altAttributeChanged() { } void InputType::srcAttributeChanged() { } void InputType::willMoveToNewOwnerDocument() { } bool InputType::shouldRespectAlignAttribute() { return false; } bool InputType::canChangeFromAnotherType() const { return true; } void InputType::minOrMaxAttributeChanged() { } void InputType::stepAttributeChanged() { } bool InputType::canBeSuccessfulSubmitButton() { return false; } HTMLElement* InputType::placeholderElement() const { return 0; } bool InputType::rendererIsNeeded() { return true; } FileList* InputType::files() { return 0; } bool InputType::getTypeSpecificValue(String&) { return false; } String InputType::fallbackValue() { return String(); } String InputType::defaultValue() { return String(); } bool InputType::canSetSuggestedValue() { return false; } bool InputType::shouldSendChangeEventAfterCheckedChanged() { return true; } bool InputType::storesValueSeparateFromAttribute() { return true; } void InputType::setValue(const String& sanitizedValue, bool, bool sendChangeEvent) { element()->setValueInternal(sanitizedValue, sendChangeEvent); element()->setNeedsStyleRecalc(); } void InputType::dispatchChangeEventInResponseToSetValue() { element()->dispatchFormControlChangeEvent(); } bool InputType::canSetValue(const String&) { return true; } PassOwnPtr<ClickHandlingState> InputType::willDispatchClick() { return nullptr; } void InputType::didDispatchClick(Event*, const ClickHandlingState&) { } String InputType::visibleValue() const { return element()->value(); } String InputType::convertFromVisibleValue(const String& visibleValue) const { return visibleValue; } bool InputType::isAcceptableValue(const String&) { return true; } String InputType::sanitizeValue(const String& proposedValue) { return proposedValue; } bool InputType::hasUnacceptableValue() { return false; } void InputType::receiveDroppedFiles(const Vector<String>&) { ASSERT_NOT_REACHED(); } Icon* InputType::icon() const { ASSERT_NOT_REACHED(); return 0; } bool InputType::shouldResetOnDocumentActivation() { return false; } bool InputType::shouldRespectListAttribute() { return false; } bool InputType::shouldRespectSpeechAttribute() { return false; } bool InputType::isTextButton() const { return false; } bool InputType::isRadioButton() const { return false; } bool InputType::isSearchField() const { return false; } bool InputType::isHiddenType() const { return false; } bool InputType::isPasswordField() const { return false; } bool InputType::isCheckbox() const { return false; } bool InputType::isEmailField() const { return false; } bool InputType::isFileUpload() const { return false; } bool InputType::isImageButton() const { return false; } bool InputType::isNumberField() const { return false; } bool InputType::isSubmitButton() const { return false; } bool InputType::isTelephoneField() const { return false; } bool InputType::isURLField() const { return false; } bool InputType::isEnumeratable() { return true; } bool InputType::isCheckable() { return false; } bool InputType::isSteppable() const { return false; } #if ENABLE(INPUT_COLOR) bool InputType::isColorControl() const { return false; } #endif bool InputType::shouldRespectHeightAndWidthAttributes() { return false; } bool InputType::supportsPlaceholder() const { return false; } void InputType::updatePlaceholderText() { } void InputType::multipleAttributeChanged() { } void InputType::disabledAttributeChanged() { } void InputType::readonlyAttributeChanged() { } namespace InputTypeNames { // The type names must be lowercased because they will be the return values of // input.type and input.type must be lowercase according to DOM Level 2. const AtomicString& button() { DEFINE_STATIC_LOCAL(AtomicString, name, ("button")); return name; } const AtomicString& checkbox() { DEFINE_STATIC_LOCAL(AtomicString, name, ("checkbox")); return name; } #if ENABLE(INPUT_COLOR) const AtomicString& color() { DEFINE_STATIC_LOCAL(AtomicString, name, ("color")); return name; } #endif const AtomicString& date() { DEFINE_STATIC_LOCAL(AtomicString, name, ("date")); return name; } const AtomicString& datetime() { DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime")); return name; } const AtomicString& datetimelocal() { DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime-local")); return name; } const AtomicString& email() { DEFINE_STATIC_LOCAL(AtomicString, name, ("email")); return name; } const AtomicString& file() { DEFINE_STATIC_LOCAL(AtomicString, name, ("file")); return name; } const AtomicString& hidden() { DEFINE_STATIC_LOCAL(AtomicString, name, ("hidden")); return name; } const AtomicString& image() { DEFINE_STATIC_LOCAL(AtomicString, name, ("image")); return name; } const AtomicString& isindex() { DEFINE_STATIC_LOCAL(AtomicString, name, ("khtml_isindex")); return name; } const AtomicString& month() { DEFINE_STATIC_LOCAL(AtomicString, name, ("month")); return name; } const AtomicString& number() { DEFINE_STATIC_LOCAL(AtomicString, name, ("number")); return name; } const AtomicString& password() { DEFINE_STATIC_LOCAL(AtomicString, name, ("password")); return name; } const AtomicString& radio() { DEFINE_STATIC_LOCAL(AtomicString, name, ("radio")); return name; } const AtomicString& range() { DEFINE_STATIC_LOCAL(AtomicString, name, ("range")); return name; } const AtomicString& reset() { DEFINE_STATIC_LOCAL(AtomicString, name, ("reset")); return name; } const AtomicString& search() { DEFINE_STATIC_LOCAL(AtomicString, name, ("search")); return name; } const AtomicString& submit() { DEFINE_STATIC_LOCAL(AtomicString, name, ("submit")); return name; } const AtomicString& telephone() { DEFINE_STATIC_LOCAL(AtomicString, name, ("tel")); return name; } const AtomicString& text() { DEFINE_STATIC_LOCAL(AtomicString, name, ("text")); return name; } const AtomicString& time() { DEFINE_STATIC_LOCAL(AtomicString, name, ("time")); return name; } const AtomicString& url() { DEFINE_STATIC_LOCAL(AtomicString, name, ("url")); return name; } const AtomicString& week() { DEFINE_STATIC_LOCAL(AtomicString, name, ("week")); return name; } } // namespace WebCore::InputTypeNames } // namespace WebCore
bsd-2-clause
dplbsd/soc2013
head/usr.sbin/fdwrite/fdwrite.c
2
4711
/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- * * $FreeBSD: soc2013/dpl/head/usr.sbin/fdwrite/fdwrite.c 194935 2009-06-24 19:47:53Z joerg $ * */ #include <ctype.h> #include <err.h> #include <fcntl.h> #include <paths.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/fdcio.h> static int format_track(int fd, int cyl, int secs, int head, int rate, int gaplen, int secsize, int fill, int interleave) { struct fd_formb f; register int i,j; int il[100]; memset(il,0,sizeof il); for(j = 0, i = 1; i <= secs; i++) { while(il[(j%secs)+1]) j++; il[(j%secs)+1] = i; j += interleave; } f.format_version = FD_FORMAT_VERSION; f.head = head; f.cyl = cyl; f.transfer_rate = rate; f.fd_formb_secshift = secsize; f.fd_formb_nsecs = secs; f.fd_formb_gaplen = gaplen; f.fd_formb_fillbyte = fill; for(i = 0; i < secs; i++) { f.fd_formb_cylno(i) = cyl; f.fd_formb_headno(i) = head; f.fd_formb_secno(i) = il[i+1]; f.fd_formb_secsize(i) = secsize; } return ioctl(fd, FD_FORM, (caddr_t)&f); } static void usage(void) { fprintf(stderr, "usage: fdwrite [-v] [-y] [-f inputfile] [-d device]\n"); exit(2); } int main(int argc, char **argv) { int inputfd = -1, c, fdn = 0, i,j,fd; int bpt, verbose=1, nbytes=0, track; int interactive = 1; const char *device= "/dev/fd0"; char *trackbuf = 0,*vrfybuf = 0; struct fd_type fdt; FILE *tty; setbuf(stdout,0); while((c = getopt(argc, argv, "d:f:vy")) != -1) switch(c) { case 'd': /* Which drive */ device = optarg; break; case 'f': /* input file */ if (inputfd >= 0) close(inputfd); inputfd = open(optarg,O_RDONLY); if (inputfd < 0) err(1, "%s", optarg); break; case 'v': /* Toggle verbosity */ verbose = !verbose; break; case 'y': /* Don't confirm? */ interactive = 0; break; case '?': default: usage(); } if (inputfd < 0) inputfd = 0; if (!isatty(1)) interactive = 0; if(optind < argc) usage(); tty = fopen(_PATH_TTY,"r+"); if(!tty) err(1, _PATH_TTY); setbuf(tty,0); for(j=1;j > 0;) { fdn++; if (interactive) { fprintf(tty, "Please insert floppy #%d in drive %s and press return >", fdn,device); while(1) { i = getc(tty); if(i == '\n') break; } } if((fd = open(device, O_RDWR)) < 0) err(1, "%s", device); if(ioctl(fd, FD_GTYPE, &fdt) < 0) errx(1, "not a floppy disk: %s", device); bpt = fdt.sectrac * (1<<fdt.secsize) * 128; if(!trackbuf) { trackbuf = malloc(bpt); if(!trackbuf) errx(1, "malloc"); } if(!vrfybuf) { vrfybuf = malloc(bpt); if(!vrfybuf) errx(1, "malloc"); } if(fdn == 1) { if(verbose) { printf("Format: %d cylinders, %d heads, %d sectors, %d bytes = %dkb\n", fdt.tracks,fdt.heads,fdt.sectrac,(1<<fdt.secsize) * 128, fdt.tracks*bpt*fdt.heads/1024); } memset(trackbuf,0,bpt); for(j=0;inputfd >= 0 && j<bpt;j+=i) { if(!(i = read(inputfd,trackbuf+j,bpt-j))) { close(inputfd); inputfd = -1; break; } nbytes += i; } } for (track = 0; track < fdt.tracks * fdt.heads; track++) { if(verbose) printf("\r%3d ",fdt.tracks * fdt.heads-track); if(verbose) putc((j ? 'I':'Z'),stdout); format_track(fd, track / fdt.heads, fdt.sectrac, track % fdt.heads, fdt.trans, fdt.f_gap, fdt.secsize, 0xe6, fdt.f_inter); if(verbose) putc('F',stdout); if (lseek (fd, (long) track*bpt, 0) < 0) err(1, "lseek"); if (write (fd, trackbuf, bpt) != bpt) err(1, "write"); if(verbose) putc('W',stdout); if (lseek (fd, (long) track*bpt, 0) < 0) err(1, "lseek"); if (read (fd, vrfybuf, bpt) != bpt) err(1, "read"); if(verbose) putc('R',stdout); if (memcmp(trackbuf,vrfybuf,bpt)) err(1, "compare"); if(verbose) putc('C',stdout); memset(trackbuf,0,bpt); for(j=0;inputfd >= 0 && j<bpt;j+=i) { if(!(i = read(inputfd,trackbuf+j,bpt-j))) { close(inputfd); inputfd = -1; break; } nbytes += i; } } close(fd); putc('\r',stdout); } if(verbose) printf("%d bytes on %d flopp%s\n",nbytes,fdn,fdn==1?"y":"ies"); exit(0); }
bsd-2-clause
brunolauze/pegasus-providers
tests/UNIXProviders.Tests/UNIX_BGPClusterFixture.cpp
2
2752
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include "UNIX_BGPClusterFixture.h" #include <BGPCluster/UNIX_BGPClusterProvider.h> UNIX_BGPClusterFixture::UNIX_BGPClusterFixture() { } UNIX_BGPClusterFixture::~UNIX_BGPClusterFixture() { } void UNIX_BGPClusterFixture::Run() { CIMName className("UNIX_BGPCluster"); CIMNamespaceName nameSpace("root/cimv2"); UNIX_BGPCluster _p; UNIX_BGPClusterProvider _provider; Uint32 propertyCount; CIMOMHandle omHandle; _provider.initialize(omHandle); _p.initialize(); for(int pIndex = 0; _p.load(pIndex); pIndex++) { CIMInstance instance = _provider.constructInstance(className, nameSpace, _p); CIMObjectPath path = instance.getPath(); cout << path.toString() << endl; propertyCount = instance.getPropertyCount(); for(Uint32 i = 0; i < propertyCount; i++) { CIMProperty propertyItem = instance.getProperty(i); cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl; } cout << "------------------------------------" << endl; cout << endl; } _p.finalize(); }
bsd-2-clause
tridge/SiK
Firmware/radio/parameters.c
3
14766
// -*- Mode: C; c-basic-offset: 8; -*- // // Copyright (c) 2011 Michael Smith, All Rights Reserved // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // o Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // o Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // /// /// @file parameters.c /// /// Storage for program parameters. /// /// Parameters are held in a contiguous array of 16-bit values. /// It is up to the caller to decide how large a parameter is and to /// access it accordingly. /// /// When saved, parameters are copied bitwise to the flash scratch page, /// with an 8-bit XOR checksum appended to the end of the flash range. /// #include "radio.h" #include "tdm.h" #include "crc.h" #include <flash_layout.h> #ifdef INCLUDE_AES #include "AES/aes.h" #endif // INCLUDE_AES /// In-ROM parameter info table. /// __code const struct parameter_info { const char *name; param_t default_value; } parameter_info[PARAM_MAX] = { {"FORMAT", PARAM_FORMAT_CURRENT}, {"SERIAL_SPEED", 57}, // match APM default of 57600 {"AIR_SPEED", 64}, // relies on MAVLink flow control {"NETID", 25}, {"TXPOWER", 20}, {"ECC", 0}, {"MAVLINK", 1}, {"OPPRESEND", 0}, {"MIN_FREQ", 0}, {"MAX_FREQ", 0}, {"NUM_CHANNELS", 0}, {"DUTY_CYCLE", 100}, {"LBT_RSSI", 0}, {"MANCHESTER", 0}, {"RTSCTS", 0}, {"MAX_WINDOW", 131}, #ifdef INCLUDE_AES {"ENCRYPTION_LEVEL", 0}, // no Enycryption (0), 128 or 256 bit key #endif }; /// In-RAM parameter store. /// /// It seems painful to have to do this, but we need somewhere to /// hold all the parameters when we're rewriting the scratchpad /// page anyway. /// __xdata param_t parameter_values[PARAM_MAX]; // Three extra bytes, 1 for the number of params and 2 for the checksum #define PARAM_FLASH_START 0 #define PARAM_FLASH_END (PARAM_FLASH_START + sizeof(parameter_values) + 3) #if PIN_MAX > 0 __code const pins_user_info_t pins_defaults = PINS_USER_INFO_DEFAULT; __xdata pins_user_info_t pin_values[PIN_MAX]; // Place the start away from the other params to allow for expantion 2<<7 = 256 #define PIN_FLASH_START (2<<7) #define PIN_FLASH_END (PIN_FLASH_START + sizeof(pin_values) + 3) // Check to make sure the End of the r and the beginning of pins dont overlap typedef char r2pCheck[(PARAM_FLASH_END < PIN_FLASH_START) ? 0 : -1]; #else // PIN_MAX #define PIN_FLASH_END PARAM_FLASH_END #endif // PIN_MAX // Place the start away from the other params to allow for expantion 2<<7 +128 = 384 #ifdef INCLUDE_AES // Holds the encrpytion string __xdata uint8_t encryption_key[32]; #define PARAM_E_FLASH_START (2<<7) + 128 #define PARAM_E_FLASH_END (PARAM_E_FLASH_START + sizeof(encryption_key) + 3) // Check to make sure the End of the pins and the beginning of encryption dont overlap typedef char p2eCheck[(PIN_FLASH_END < PARAM_E_FLASH_START) ? 0 : -1]; #else #define PARAM_E_FLASH_END PIN_FLASH_END #endif // INCLUDE_AES // Check to make sure we dont overflow off the page typedef char endCheck[(PARAM_E_FLASH_END < 1023) ? 0 : -1]; static bool param_check(__pdata enum ParamID id, __data uint32_t val) { // parameter value out of range - fail if (id >= PARAM_MAX) return false; switch (id) { case PARAM_FORMAT: return false; case PARAM_SERIAL_SPEED: return serial_device_valid_speed(val); case PARAM_AIR_SPEED: if (val > 256) return false; break; case PARAM_NETID: // all values are OK return true; case PARAM_TXPOWER: if (val > BOARD_MAXTXPOWER) return false; break; case PARAM_ECC: case PARAM_OPPRESEND: // boolean 0/1 only if (val > 1) return false; break; case PARAM_MAVLINK: if (val > 2) return false; break; case PARAM_MAX_WINDOW: // 131 milliseconds == 0x1FFF 16 usec ticks, // which is the maximum we can handle with a 13 // bit trailer for window remaining if (val > 131) return false; break; default: // no sanity check for this value break; } return true; } bool param_set(__data enum ParamID param, __pdata param_t value) { // Sanity-check the parameter value first. if (!param_check(param, value)) return false; // some parameters we update immediately switch (param) { case PARAM_TXPOWER: // useful to update power level immediately when range // testing in RSSI mode radio_set_transmit_power(value); value = radio_get_transmit_power(); break; case PARAM_DUTY_CYCLE: // update duty cycle immediately value = constrain(value, 0, 100); duty_cycle = value; break; case PARAM_LBT_RSSI: // update LBT RSSI immediately if (value != 0) { value = constrain(value, 25, 220); } lbt_rssi = value; break; case PARAM_MAVLINK: feature_mavlink_framing = (uint8_t) value; value = feature_mavlink_framing; break; case PARAM_OPPRESEND: break; case PARAM_RTSCTS: feature_rtscts = value?true:false; value = feature_rtscts?1:0; break; default: break; } parameter_values[param] = value; return true; } param_t param_get(__data enum ParamID param) { if (param >= PARAM_MAX) return 0; return parameter_values[param]; } bool read_params(__xdata uint8_t * __data input, uint16_t start, uint8_t size) { uint16_t i; for (i = start; i < start+size; i ++) input[i-start] = flash_read_scratch(i); // verify checksum if (crc16(size, input) != ((uint16_t) flash_read_scratch(i+1)<<8 | flash_read_scratch(i))) return false; return true; } void write_params(__xdata uint8_t * __data input, uint16_t start, uint8_t size) { uint16_t i, checksum; // save parameters to the scratch page for (i = start; i < start+size; i ++) flash_write_scratch(i, input[i-start]); // write checksum checksum = crc16(size, input); flash_write_scratch(i, checksum&0xFF); flash_write_scratch(i+1, checksum>>8); } bool param_load(void) __critical { __pdata uint8_t i, expected; // Start with default values param_default(); // loop reading the parameters array expected = flash_read_scratch(PARAM_FLASH_START); if (expected > sizeof(parameter_values) || expected < 12*sizeof(param_t)) return false; // read and verify params if(!read_params((__xdata uint8_t *)parameter_values, PARAM_FLASH_START+1, expected)) return false; // decide whether we read a supported version of the structure if (param_get(PARAM_FORMAT) != PARAM_FORMAT_CURRENT) { debug("parameter format %lu expecting %lu", parameters[PARAM_FORMAT], PARAM_FORMAT_CURRENT); return false; } for (i = 0; i < sizeof(parameter_values); i++) { if (!param_check(i, parameter_values[i])) { parameter_values[i] = parameter_info[i].default_value; } } // read and verify pin params #if PIN_MAX > 0 if(!read_params((__xdata uint8_t *)pin_values, PIN_FLASH_START+1, sizeof(pin_values))) return false; #endif // read and verify encryption params #ifdef INCLUDE_AES if(!read_params((__xdata uint8_t *)encryption_key, PARAM_E_FLASH_START+1, sizeof(encryption_key))) return false; #endif // INCLUDE_AES return true; } void param_save(void) __critical { // tag parameters with the current format parameter_values[PARAM_FORMAT] = PARAM_FORMAT_CURRENT; // erase the scratch space flash_erase_scratch(); // write param array length flash_write_scratch(PARAM_FLASH_START, sizeof(parameter_values)); // write params write_params((__xdata uint8_t *)parameter_values, PARAM_FLASH_START+1, sizeof(parameter_values)); // write pin params #if PIN_MAX > 0 flash_write_scratch(PIN_FLASH_START, sizeof(pin_values)); write_params((__xdata uint8_t *)pin_values, PIN_FLASH_START+1, sizeof(pin_values)); #endif // write encryption params #ifdef INCLUDE_AES flash_write_scratch(PARAM_E_FLASH_START, sizeof(encryption_key)); write_params((__xdata uint8_t *)encryption_key, PARAM_E_FLASH_START+1, sizeof(encryption_key)); #endif // INCLUDE_AES } void param_default(void) { __pdata uint8_t i; // set all parameters to their default values for (i = 0; i < PARAM_MAX; i++) { parameter_values[i] = parameter_info[i].default_value; } #if PIN_MAX > 0 for (i = 0; i < PIN_MAX; i ++) { pin_values[i].output = pins_defaults.output; pin_values[i].pin_dir = pins_defaults.pin_dir; pin_values[i].pin_mirror = pins_defaults.pin_mirror; } #endif // PIN_MAX } enum ParamID param_id(__data char * __pdata name) { __pdata uint8_t i; for (i = 0; i < PARAM_MAX; i++) { if (!strcmp(name, parameter_info[i].name)) break; } return i; } const char *__code param_name(__data enum ParamID param) { if (param < PARAM_MAX) { return parameter_info[param].name; } return 0; } // constraint for parameter values uint32_t constrain(__pdata uint32_t v, __pdata uint32_t min, __pdata uint32_t max) { if (v < min) v = min; if (v > max) v = max; return v; } // rfd900a calibration stuff // Change for next rfd900 revision #if defined BOARD_rfd900a || defined BOARD_rfd900p static __at(FLASH_CALIBRATION_AREA) uint8_t __code calibration[FLASH_CALIBRATION_AREA_SIZE]; static __at(FLASH_CALIBRATION_CRC) uint8_t __code calibration_crc; static void flash_write_byte(uint16_t address, uint8_t c) __reentrant __critical { PSCTL = 0x01; // set PSWE, clear PSEE FLKEY = 0xa5; FLKEY = 0xf1; *(uint8_t __xdata *)address = c; // write the byte PSCTL = 0x00; // disable PSWE/PSEE } static uint8_t flash_read_byte(uint16_t address) __reentrant { // will cause reset if the byte is in a locked page return *(uint8_t __code *)address; } bool calibration_set(uint8_t idx, uint8_t value) __reentrant { #ifdef CPU_SI1030 PSBANK = 0x33; #endif // if level is valid if (idx <= BOARD_MAXTXPOWER && value != 0xFF) { // if the target byte isn't yet written if (flash_read_byte(FLASH_CALIBRATION_AREA_HIGH + idx) == 0xFF) { flash_write_byte(FLASH_CALIBRATION_AREA_HIGH + idx, value); return true; } } return false; } uint8_t calibration_get(uint8_t level) __reentrant { uint8_t idx; uint8_t crc = 0; #ifdef CPU_SI1030 PSBANK = 0x33; #endif // Change for next board revision for (idx = 0; idx < FLASH_CALIBRATION_AREA_SIZE; idx++) { crc ^= calibration[idx]; } if (calibration_crc != 0xFF && calibration_crc == crc && level <= BOARD_MAXTXPOWER) { return calibration[level]; } return 0xFF; } uint8_t calibration_force_get(uint8_t idx) __reentrant { return flash_read_byte(FLASH_CALIBRATION_AREA_HIGH + idx); } bool calibration_lock() __reentrant { uint8_t idx; uint8_t crc = 0; #ifdef CPU_SI1030 PSBANK = 0x33; #endif // check that all entries are written if (flash_read_byte(FLASH_CALIBRATION_CRC_HIGH) == 0xFF) { for (idx=0; idx < FLASH_CALIBRATION_AREA_SIZE; idx++) { uint8_t cal = flash_read_byte(FLASH_CALIBRATION_AREA_HIGH + idx); crc ^= cal; if (cal == 0xFF) { printf("dBm level %u not calibrated\n",idx); return false; } } // write crc flash_write_byte(FLASH_CALIBRATION_CRC_HIGH, crc); // lock the first and last pages // can only be reverted by reflashing the bootloader flash_write_byte(FLASH_LOCK_BYTE, 0xFE); return true; } return false; } #endif // BOARD_rfd900a/p #ifdef INCLUDE_AES // Used to convert individial Hex digits into Integers // uint8_t read_hex_nibble(const uint8_t c) __reentrant { if ((c >='0') && (c <= '9')) { return c - '0'; } else if ((c >='A') && (c <= 'F')) { return c - 'A' + 10; } else if ((c >='a') && (c <= 'f')) { return c - 'a' + 10; } else { // printf("[%u] read_hex_nibble: Error char not in supported range",nodeId); return 0; } } /// Convert string to hex codes /// void convert_to_hex(__xdata unsigned char *str_in, __xdata unsigned char *str_out, __pdata uint8_t key_length) { __pdata uint8_t i, num; for (i=0;i<key_length;i++) { num = read_hex_nibble(str_in[2 * i])<<4; num += read_hex_nibble(str_in[2 * i + 1]); str_out[i] = num; } } /// Set default encryption key // void param_set_default_encryption_key(__pdata uint8_t key_length) { __pdata uint8_t i; __xdata uint8_t b[] = {0x62}; for (i=0;i< key_length;i++) { // Set default key to b's memcpy(&encryption_key[i], &b, 1); } } /// set the encryption key /// /// Note: There is a reliance on the encryption level as this determines /// how many characters we need. So we need to set ATS16 first, THEN /// save and then Set the encryption key. /// bool param_set_encryption_key(__xdata unsigned char *key) { __pdata uint8_t len, key_length; // Use the new encryption level to help with key changes before reboot // Deduce key length (bytes) from level 1 -> 16, 2 -> 24, 3 -> 32 key_length = AES_KEY_LENGTH(param_get(PARAM_ENCRYPTION)); len = strlen(key); // If not enough characters (2 char per byte), then set default if (len < 2 * key_length ) { param_set_default_encryption_key(key_length); //printf("%s\n",key); printf("ERROR - Key length:%u, Required %u\n",len, 2 * key_length); return true; } else { // We have sufficient characters for the encryption key. // If too many characters, then it will just ignore extra ones printf("key len %d\n",key_length); convert_to_hex(key, encryption_key, key_length); } return true; } /// Print hex codes for given string /// void print_encryption_key() { __pdata uint8_t i; __pdata uint8_t key_length = AES_KEY_LENGTH(param_get(PARAM_ENCRYPTION)); for (i=0; i<key_length; i++) { if (0xF >= encryption_key[i]) { printf("0"); } printf("%x",encryption_key[i]); } printf("\n"); } /// get the encryption key /// __xdata uint8_t* param_get_encryption_key() { return encryption_key; } #endif // INCLUDE_AES
bsd-2-clause
BloodyKnight/nginx-openresty-windows
LuaJIT-2.1-20150622/src/lib_base.c
32
16556
/* ** Base and coroutine library. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h ** ** Major portions taken verbatim or adapted from the Lua interpreter. ** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #include <stdio.h> #define lib_base_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "lj_obj.h" #include "lj_gc.h" #include "lj_err.h" #include "lj_debug.h" #include "lj_str.h" #include "lj_tab.h" #include "lj_meta.h" #include "lj_state.h" #if LJ_HASFFI #include "lj_ctype.h" #include "lj_cconv.h" #endif #include "lj_bc.h" #include "lj_ff.h" #include "lj_dispatch.h" #include "lj_char.h" #include "lj_strscan.h" #include "lj_strfmt.h" #include "lj_lib.h" /* -- Base library: checks ------------------------------------------------ */ #define LJLIB_MODULE_base LJLIB_ASM(assert) LJLIB_REC(.) { GCstr *s; lj_lib_checkany(L, 1); s = lj_lib_optstr(L, 2); if (s) lj_err_callermsg(L, strdata(s)); else lj_err_caller(L, LJ_ERR_ASSERT); return FFH_UNREACHABLE; } /* ORDER LJ_T */ LJLIB_PUSH("nil") LJLIB_PUSH("boolean") LJLIB_PUSH(top-1) /* boolean */ LJLIB_PUSH("userdata") LJLIB_PUSH("string") LJLIB_PUSH("upval") LJLIB_PUSH("thread") LJLIB_PUSH("proto") LJLIB_PUSH("function") LJLIB_PUSH("trace") LJLIB_PUSH("cdata") LJLIB_PUSH("table") LJLIB_PUSH(top-9) /* userdata */ LJLIB_PUSH("number") LJLIB_ASM_(type) LJLIB_REC(.) /* Recycle the lj_lib_checkany(L, 1) from assert. */ /* -- Base library: iterators --------------------------------------------- */ /* This solves a circular dependency problem -- change FF_next_N as needed. */ LJ_STATIC_ASSERT((int)FF_next == FF_next_N); LJLIB_ASM(next) { lj_lib_checktab(L, 1); return FFH_UNREACHABLE; } #if LJ_52 || LJ_HASFFI static int ffh_pairs(lua_State *L, MMS mm) { TValue *o = lj_lib_checkany(L, 1); cTValue *mo = lj_meta_lookup(L, o, mm); if ((LJ_52 || tviscdata(o)) && !tvisnil(mo)) { L->top = o+1; /* Only keep one argument. */ copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */ return FFH_TAILCALL; } else { if (!tvistab(o)) lj_err_argt(L, 1, LUA_TTABLE); if (LJ_FR2) { copyTV(L, o-1, o); o--; } setfuncV(L, o-1, funcV(lj_lib_upvalue(L, 1))); if (mm == MM_pairs) setnilV(o+1); else setintV(o+1, 0); return FFH_RES(3); } } #else #define ffh_pairs(L, mm) (lj_lib_checktab(L, 1), FFH_UNREACHABLE) #endif LJLIB_PUSH(lastcl) LJLIB_ASM(pairs) LJLIB_REC(xpairs 0) { return ffh_pairs(L, MM_pairs); } LJLIB_NOREGUV LJLIB_ASM(ipairs_aux) LJLIB_REC(.) { lj_lib_checktab(L, 1); lj_lib_checkint(L, 2); return FFH_UNREACHABLE; } LJLIB_PUSH(lastcl) LJLIB_ASM(ipairs) LJLIB_REC(xpairs 1) { return ffh_pairs(L, MM_ipairs); } /* -- Base library: getters and setters ----------------------------------- */ LJLIB_ASM_(getmetatable) LJLIB_REC(.) /* Recycle the lj_lib_checkany(L, 1) from assert. */ LJLIB_ASM(setmetatable) LJLIB_REC(.) { GCtab *t = lj_lib_checktab(L, 1); GCtab *mt = lj_lib_checktabornil(L, 2); if (!tvisnil(lj_meta_lookup(L, L->base, MM_metatable))) lj_err_caller(L, LJ_ERR_PROTMT); setgcref(t->metatable, obj2gco(mt)); if (mt) { lj_gc_objbarriert(L, t, mt); } settabV(L, L->base-1-LJ_FR2, t); return FFH_RES(1); } LJLIB_CF(getfenv) LJLIB_REC(.) { GCfunc *fn; cTValue *o = L->base; if (!(o < L->top && tvisfunc(o))) { int level = lj_lib_optint(L, 1, 1); o = lj_debug_frame(L, level, &level); if (o == NULL) lj_err_arg(L, 1, LJ_ERR_INVLVL); if (LJ_FR2) o--; } fn = &gcval(o)->fn; settabV(L, L->top++, isluafunc(fn) ? tabref(fn->l.env) : tabref(L->env)); return 1; } LJLIB_CF(setfenv) { GCfunc *fn; GCtab *t = lj_lib_checktab(L, 2); cTValue *o = L->base; if (!(o < L->top && tvisfunc(o))) { int level = lj_lib_checkint(L, 1); if (level == 0) { /* NOBARRIER: A thread (i.e. L) is never black. */ setgcref(L->env, obj2gco(t)); return 0; } o = lj_debug_frame(L, level, &level); if (o == NULL) lj_err_arg(L, 1, LJ_ERR_INVLVL); if (LJ_FR2) o--; } fn = &gcval(o)->fn; if (!isluafunc(fn)) lj_err_caller(L, LJ_ERR_SETFENV); setgcref(fn->l.env, obj2gco(t)); lj_gc_objbarrier(L, obj2gco(fn), t); setfuncV(L, L->top++, fn); return 1; } LJLIB_ASM(rawget) LJLIB_REC(.) { lj_lib_checktab(L, 1); lj_lib_checkany(L, 2); return FFH_UNREACHABLE; } LJLIB_CF(rawset) LJLIB_REC(.) { lj_lib_checktab(L, 1); lj_lib_checkany(L, 2); L->top = 1+lj_lib_checkany(L, 3); lua_rawset(L, 1); return 1; } LJLIB_CF(rawequal) LJLIB_REC(.) { cTValue *o1 = lj_lib_checkany(L, 1); cTValue *o2 = lj_lib_checkany(L, 2); setboolV(L->top-1, lj_obj_equal(o1, o2)); return 1; } #if LJ_52 LJLIB_CF(rawlen) LJLIB_REC(.) { cTValue *o = L->base; int32_t len; if (L->top > o && tvisstr(o)) len = (int32_t)strV(o)->len; else len = (int32_t)lj_tab_len(lj_lib_checktab(L, 1)); setintV(L->top-1, len); return 1; } #endif LJLIB_CF(unpack) { GCtab *t = lj_lib_checktab(L, 1); int32_t n, i = lj_lib_optint(L, 2, 1); int32_t e = (L->base+3-1 < L->top && !tvisnil(L->base+3-1)) ? lj_lib_checkint(L, 3) : (int32_t)lj_tab_len(t); if (i > e) return 0; n = e - i + 1; if (n <= 0 || !lua_checkstack(L, n)) lj_err_caller(L, LJ_ERR_UNPACK); do { cTValue *tv = lj_tab_getint(t, i); if (tv) { copyTV(L, L->top++, tv); } else { setnilV(L->top++); } } while (i++ < e); return n; } LJLIB_CF(select) LJLIB_REC(.) { int32_t n = (int32_t)(L->top - L->base); if (n >= 1 && tvisstr(L->base) && *strVdata(L->base) == '#') { setintV(L->top-1, n-1); return 1; } else { int32_t i = lj_lib_checkint(L, 1); if (i < 0) i = n + i; else if (i > n) i = n; if (i < 1) lj_err_arg(L, 1, LJ_ERR_IDXRNG); return n - i; } } /* -- Base library: conversions ------------------------------------------- */ LJLIB_ASM(tonumber) LJLIB_REC(.) { int32_t base = lj_lib_optint(L, 2, 10); if (base == 10) { TValue *o = lj_lib_checkany(L, 1); if (lj_strscan_numberobj(o)) { copyTV(L, L->base-1-LJ_FR2, o); return FFH_RES(1); } #if LJ_HASFFI if (tviscdata(o)) { CTState *cts = ctype_cts(L); CType *ct = lj_ctype_rawref(cts, cdataV(o)->ctypeid); if (ctype_isenum(ct->info)) ct = ctype_child(cts, ct); if (ctype_isnum(ct->info) || ctype_iscomplex(ct->info)) { if (LJ_DUALNUM && ctype_isinteger_or_bool(ct->info) && ct->size <= 4 && !(ct->size == 4 && (ct->info & CTF_UNSIGNED))) { int32_t i; lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o, 0); setintV(L->base-1-LJ_FR2, i); return FFH_RES(1); } lj_cconv_ct_tv(cts, ctype_get(cts, CTID_DOUBLE), (uint8_t *)&(L->base-1-LJ_FR2)->n, o, 0); return FFH_RES(1); } } #endif } else { const char *p = strdata(lj_lib_checkstr(L, 1)); char *ep; unsigned long ul; if (base < 2 || base > 36) lj_err_arg(L, 2, LJ_ERR_BASERNG); ul = strtoul(p, &ep, base); if (p != ep) { while (lj_char_isspace((unsigned char)(*ep))) ep++; if (*ep == '\0') { if (LJ_DUALNUM && LJ_LIKELY(ul < 0x80000000u)) setintV(L->base-1-LJ_FR2, (int32_t)ul); else setnumV(L->base-1-LJ_FR2, (lua_Number)ul); return FFH_RES(1); } } } setnilV(L->base-1-LJ_FR2); return FFH_RES(1); } LJLIB_ASM(tostring) LJLIB_REC(.) { TValue *o = lj_lib_checkany(L, 1); cTValue *mo; L->top = o+1; /* Only keep one argument. */ if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) { copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */ return FFH_TAILCALL; } lj_gc_check(L); setstrV(L, L->base-1-LJ_FR2, lj_strfmt_obj(L, L->base)); return FFH_RES(1); } /* -- Base library: throw and catch errors -------------------------------- */ LJLIB_CF(error) { int32_t level = lj_lib_optint(L, 2, 1); lua_settop(L, 1); if (lua_isstring(L, 1) && level > 0) { luaL_where(L, level); lua_pushvalue(L, 1); lua_concat(L, 2); } return lua_error(L); } LJLIB_ASM(pcall) LJLIB_REC(.) { lj_lib_checkany(L, 1); lj_lib_checkfunc(L, 2); /* For xpcall only. */ return FFH_UNREACHABLE; } LJLIB_ASM_(xpcall) LJLIB_REC(.) /* -- Base library: load Lua code ----------------------------------------- */ static int load_aux(lua_State *L, int status, int envarg) { if (status == 0) { if (tvistab(L->base+envarg-1)) { GCfunc *fn = funcV(L->top-1); GCtab *t = tabV(L->base+envarg-1); setgcref(fn->c.env, obj2gco(t)); lj_gc_objbarrier(L, fn, t); } return 1; } else { setnilV(L->top-2); return 2; } } LJLIB_CF(loadfile) { GCstr *fname = lj_lib_optstr(L, 1); GCstr *mode = lj_lib_optstr(L, 2); int status; lua_settop(L, 3); /* Ensure env arg exists. */ status = luaL_loadfilex(L, fname ? strdata(fname) : NULL, mode ? strdata(mode) : NULL); return load_aux(L, status, 3); } static const char *reader_func(lua_State *L, void *ud, size_t *size) { UNUSED(ud); luaL_checkstack(L, 2, "too many nested functions"); copyTV(L, L->top++, L->base); lua_call(L, 0, 1); /* Call user-supplied function. */ L->top--; if (tvisnil(L->top)) { *size = 0; return NULL; } else if (tvisstr(L->top) || tvisnumber(L->top)) { copyTV(L, L->base+4, L->top); /* Anchor string in reserved stack slot. */ return lua_tolstring(L, 5, size); } else { lj_err_caller(L, LJ_ERR_RDRSTR); return NULL; } } LJLIB_CF(load) { GCstr *name = lj_lib_optstr(L, 2); GCstr *mode = lj_lib_optstr(L, 3); int status; if (L->base < L->top && (tvisstr(L->base) || tvisnumber(L->base))) { GCstr *s = lj_lib_checkstr(L, 1); lua_settop(L, 4); /* Ensure env arg exists. */ status = luaL_loadbufferx(L, strdata(s), s->len, strdata(name ? name : s), mode ? strdata(mode) : NULL); } else { lj_lib_checkfunc(L, 1); lua_settop(L, 5); /* Reserve a slot for the string from the reader. */ status = lua_loadx(L, reader_func, NULL, name ? strdata(name) : "=(load)", mode ? strdata(mode) : NULL); } return load_aux(L, status, 4); } LJLIB_CF(loadstring) { return lj_cf_load(L); } LJLIB_CF(dofile) { GCstr *fname = lj_lib_optstr(L, 1); setnilV(L->top); L->top = L->base+1; if (luaL_loadfile(L, fname ? strdata(fname) : NULL) != 0) lua_error(L); lua_call(L, 0, LUA_MULTRET); return (int)(L->top - L->base) - 1; } /* -- Base library: GC control -------------------------------------------- */ LJLIB_CF(gcinfo) { setintV(L->top++, (int32_t)(G(L)->gc.total >> 10)); return 1; } LJLIB_CF(collectgarbage) { int opt = lj_lib_checkopt(L, 1, LUA_GCCOLLECT, /* ORDER LUA_GC* */ "\4stop\7restart\7collect\5count\1\377\4step\10setpause\12setstepmul"); int32_t data = lj_lib_optint(L, 2, 0); if (opt == LUA_GCCOUNT) { setnumV(L->top, (lua_Number)G(L)->gc.total/1024.0); } else { int res = lua_gc(L, opt, data); if (opt == LUA_GCSTEP) setboolV(L->top, res); else setintV(L->top, res); } L->top++; return 1; } /* -- Base library: miscellaneous functions ------------------------------- */ LJLIB_PUSH(top-2) /* Upvalue holds weak table. */ LJLIB_CF(newproxy) { lua_settop(L, 1); lua_newuserdata(L, 0); if (lua_toboolean(L, 1) == 0) { /* newproxy(): without metatable. */ return 1; } else if (lua_isboolean(L, 1)) { /* newproxy(true): with metatable. */ lua_newtable(L); lua_pushvalue(L, -1); lua_pushboolean(L, 1); lua_rawset(L, lua_upvalueindex(1)); /* Remember mt in weak table. */ } else { /* newproxy(proxy): inherit metatable. */ int validproxy = 0; if (lua_getmetatable(L, 1)) { lua_rawget(L, lua_upvalueindex(1)); validproxy = lua_toboolean(L, -1); lua_pop(L, 1); } if (!validproxy) lj_err_arg(L, 1, LJ_ERR_NOPROXY); lua_getmetatable(L, 1); } lua_setmetatable(L, 2); return 1; } LJLIB_PUSH("tostring") LJLIB_CF(print) { ptrdiff_t i, nargs = L->top - L->base; cTValue *tv = lj_tab_getstr(tabref(L->env), strV(lj_lib_upvalue(L, 1))); int shortcut; if (tv && !tvisnil(tv)) { copyTV(L, L->top++, tv); } else { setstrV(L, L->top++, strV(lj_lib_upvalue(L, 1))); lua_gettable(L, LUA_GLOBALSINDEX); tv = L->top-1; } shortcut = (tvisfunc(tv) && funcV(tv)->c.ffid == FF_tostring); for (i = 0; i < nargs; i++) { cTValue *o = &L->base[i]; char buf[STRFMT_MAXBUF_NUM]; const char *str; size_t size; MSize len; if (shortcut && (str = lj_strfmt_wstrnum(buf, o, &len)) != NULL) { size = len; } else { copyTV(L, L->top+1, o); copyTV(L, L->top, L->top-1); L->top += 2; lua_call(L, 1, 1); str = lua_tolstring(L, -1, &size); if (!str) lj_err_caller(L, LJ_ERR_PRTOSTR); L->top--; } if (i) putchar('\t'); fwrite(str, 1, size, stdout); } putchar('\n'); return 0; } LJLIB_PUSH(top-3) LJLIB_SET(_VERSION) #include "lj_libdef.h" /* -- Coroutine library --------------------------------------------------- */ #define LJLIB_MODULE_coroutine LJLIB_CF(coroutine_status) { const char *s; lua_State *co; if (!(L->top > L->base && tvisthread(L->base))) lj_err_arg(L, 1, LJ_ERR_NOCORO); co = threadV(L->base); if (co == L) s = "running"; else if (co->status == LUA_YIELD) s = "suspended"; else if (co->status != 0) s = "dead"; else if (co->base > tvref(co->stack)+1+LJ_FR2) s = "normal"; else if (co->top == co->base) s = "dead"; else s = "suspended"; lua_pushstring(L, s); return 1; } LJLIB_CF(coroutine_running) { #if LJ_52 int ismain = lua_pushthread(L); setboolV(L->top++, ismain); return 2; #else if (lua_pushthread(L)) setnilV(L->top++); return 1; #endif } LJLIB_CF(coroutine_create) { lua_State *L1; if (!(L->base < L->top && tvisfunc(L->base))) lj_err_argt(L, 1, LUA_TFUNCTION); L1 = lua_newthread(L); setfuncV(L, L1->top++, funcV(L->base)); return 1; } LJLIB_ASM(coroutine_yield) { lj_err_caller(L, LJ_ERR_CYIELD); return FFH_UNREACHABLE; } static int ffh_resume(lua_State *L, lua_State *co, int wrap) { if (co->cframe != NULL || co->status > LUA_YIELD || (co->status == 0 && co->top == co->base)) { ErrMsg em = co->cframe ? LJ_ERR_CORUN : LJ_ERR_CODEAD; if (wrap) lj_err_caller(L, em); setboolV(L->base-1-LJ_FR2, 0); setstrV(L, L->base-LJ_FR2, lj_err_str(L, em)); return FFH_RES(2); } lj_state_growstack(co, (MSize)(L->top - L->base)); return FFH_RETRY; } LJLIB_ASM(coroutine_resume) { if (!(L->top > L->base && tvisthread(L->base))) lj_err_arg(L, 1, LJ_ERR_NOCORO); return ffh_resume(L, threadV(L->base), 0); } LJLIB_NOREG LJLIB_ASM(coroutine_wrap_aux) { return ffh_resume(L, threadV(lj_lib_upvalue(L, 1)), 1); } /* Inline declarations. */ LJ_ASMF void lj_ff_coroutine_wrap_aux(void); #if !(LJ_TARGET_MIPS && defined(ljamalg_c)) LJ_FUNCA_NORET void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L, lua_State *co); #endif /* Error handler, called from assembler VM. */ void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L, lua_State *co) { co->top--; copyTV(L, L->top, co->top); L->top++; if (tvisstr(L->top-1)) lj_err_callermsg(L, strVdata(L->top-1)); else lj_err_run(L); } /* Forward declaration. */ static void setpc_wrap_aux(lua_State *L, GCfunc *fn); LJLIB_CF(coroutine_wrap) { GCfunc *fn; lj_cf_coroutine_create(L); fn = lj_lib_pushcc(L, lj_ffh_coroutine_wrap_aux, FF_coroutine_wrap_aux, 1); setpc_wrap_aux(L, fn); return 1; } #include "lj_libdef.h" /* Fix the PC of wrap_aux. Really ugly workaround. */ static void setpc_wrap_aux(lua_State *L, GCfunc *fn) { setmref(fn->c.pc, &L2GG(L)->bcff[lj_lib_init_coroutine[1]+2]); } /* ------------------------------------------------------------------------ */ static void newproxy_weaktable(lua_State *L) { /* NOBARRIER: The table is new (marked white). */ GCtab *t = lj_tab_new(L, 0, 1); settabV(L, L->top++, t); setgcref(t->metatable, obj2gco(t)); setstrV(L, lj_tab_setstr(L, t, lj_str_newlit(L, "__mode")), lj_str_newlit(L, "kv")); t->nomm = (uint8_t)(~(1u<<MM_mode)); } LUALIB_API int luaopen_base(lua_State *L) { /* NOBARRIER: Table and value are the same. */ GCtab *env = tabref(L->env); settabV(L, lj_tab_setstr(L, env, lj_str_newlit(L, "_G")), env); lua_pushliteral(L, LUA_VERSION); /* top-3. */ newproxy_weaktable(L); /* top-2. */ LJ_LIB_REG(L, "_G", base); LJ_LIB_REG(L, LUA_COLIBNAME, coroutine); return 2; }
bsd-2-clause
sydtju/nginx-1.0.14_comment
src/event/modules/ngx_win32_select_module.c
57
10590
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_event.h> static ngx_int_t ngx_select_init(ngx_cycle_t *cycle, ngx_msec_t timer); static void ngx_select_done(ngx_cycle_t *cycle); static ngx_int_t ngx_select_add_event(ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags); static ngx_int_t ngx_select_del_event(ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags); static ngx_int_t ngx_select_process_events(ngx_cycle_t *cycle, ngx_msec_t timer, ngx_uint_t flags); static void ngx_select_repair_fd_sets(ngx_cycle_t *cycle); static char *ngx_select_init_conf(ngx_cycle_t *cycle, void *conf); static fd_set master_read_fd_set; static fd_set master_write_fd_set; static fd_set work_read_fd_set; static fd_set work_write_fd_set; static ngx_uint_t max_read; static ngx_uint_t max_write; static ngx_uint_t nevents; static ngx_event_t **event_index; static ngx_str_t select_name = ngx_string("select"); ngx_event_module_t ngx_select_module_ctx = { &select_name, NULL, /* create configuration */ ngx_select_init_conf, /* init configuration */ { ngx_select_add_event, /* add an event */ ngx_select_del_event, /* delete an event */ ngx_select_add_event, /* enable an event */ ngx_select_del_event, /* disable an event */ NULL, /* add an connection */ NULL, /* delete an connection */ NULL, /* process the changes */ ngx_select_process_events, /* process the events */ ngx_select_init, /* init the events */ ngx_select_done /* done the events */ } }; ngx_module_t ngx_select_module = { NGX_MODULE_V1, &ngx_select_module_ctx, /* module context */ NULL, /* module directives */ NGX_EVENT_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_select_init(ngx_cycle_t *cycle, ngx_msec_t timer) { ngx_event_t **index; if (event_index == NULL) { FD_ZERO(&master_read_fd_set); FD_ZERO(&master_write_fd_set); nevents = 0; } if (ngx_process >= NGX_PROCESS_WORKER || cycle->old_cycle == NULL || cycle->old_cycle->connection_n < cycle->connection_n) { index = ngx_alloc(sizeof(ngx_event_t *) * 2 * cycle->connection_n, cycle->log); if (index == NULL) { return NGX_ERROR; } if (event_index) { ngx_memcpy(index, event_index, sizeof(ngx_event_t *) * nevents); ngx_free(event_index); } event_index = index; } ngx_io = ngx_os_io; ngx_event_actions = ngx_select_module_ctx.actions; ngx_event_flags = NGX_USE_LEVEL_EVENT; max_read = 0; max_write = 0; return NGX_OK; } static void ngx_select_done(ngx_cycle_t *cycle) { ngx_free(event_index); event_index = NULL; } static ngx_int_t ngx_select_add_event(ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags) { ngx_connection_t *c; c = ev->data; ngx_log_debug2(NGX_LOG_DEBUG_EVENT, ev->log, 0, "select add event fd:%d ev:%i", c->fd, event); if (ev->index != NGX_INVALID_INDEX) { ngx_log_error(NGX_LOG_ALERT, ev->log, 0, "select event fd:%d ev:%i is already set", c->fd, event); return NGX_OK; } if ((event == NGX_READ_EVENT && ev->write) || (event == NGX_WRITE_EVENT && !ev->write)) { ngx_log_error(NGX_LOG_ALERT, ev->log, 0, "invalid select %s event fd:%d ev:%i", ev->write ? "write" : "read", c->fd, event); return NGX_ERROR; } if ((event == NGX_READ_EVENT) && (max_read >= FD_SETSIZE) || (event == NGX_WRITE_EVENT) && (max_write >= FD_SETSIZE)) { ngx_log_error(NGX_LOG_ERR, ev->log, 0, "maximum number of descriptors " "supported by select() is %d", FD_SETSIZE); return NGX_ERROR; } if (event == NGX_READ_EVENT) { FD_SET(c->fd, &master_read_fd_set); max_read++; } else if (event == NGX_WRITE_EVENT) { FD_SET(c->fd, &master_write_fd_set); max_write++; } ev->active = 1; event_index[nevents] = ev; ev->index = nevents; nevents++; return NGX_OK; } static ngx_int_t ngx_select_del_event(ngx_event_t *ev, ngx_int_t event, ngx_uint_t flags) { ngx_event_t *e; ngx_connection_t *c; c = ev->data; ev->active = 0; if (ev->index == NGX_INVALID_INDEX) { return NGX_OK; } ngx_log_debug2(NGX_LOG_DEBUG_EVENT, ev->log, 0, "select del event fd:%d ev:%i", c->fd, event); if (event == NGX_READ_EVENT) { FD_CLR(c->fd, &master_read_fd_set); max_read--; } else if (event == NGX_WRITE_EVENT) { FD_CLR(c->fd, &master_write_fd_set); max_write--; } if (ev->index < --nevents) { e = event_index[nevents]; event_index[ev->index] = e; e->index = ev->index; } ev->index = NGX_INVALID_INDEX; return NGX_OK; } static ngx_int_t ngx_select_process_events(ngx_cycle_t *cycle, ngx_msec_t timer, ngx_uint_t flags) { int ready, nready; ngx_err_t err; ngx_uint_t i, found; ngx_event_t *ev, **queue; struct timeval tv, *tp; ngx_connection_t *c; #if (NGX_DEBUG) if (cycle->log->log_level & NGX_LOG_DEBUG_ALL) { for (i = 0; i < nevents; i++) { ev = event_index[i]; c = ev->data; ngx_log_debug2(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "select event: fd:%d wr:%d", c->fd, ev->write); } } #endif if (timer == NGX_TIMER_INFINITE) { tp = NULL; } else { tv.tv_sec = (long) (timer / 1000); tv.tv_usec = (long) ((timer % 1000) * 1000); tp = &tv; } ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "select timer: %M", timer); work_read_fd_set = master_read_fd_set; work_write_fd_set = master_write_fd_set; if (max_read || max_write) { ready = select(0, &work_read_fd_set, &work_write_fd_set, NULL, tp); } else { /* * Winsock select() requires that at least one descriptor set must be * be non-null, and any non-null descriptor set must contain at least * one handle to a socket. Otherwise select() returns WSAEINVAL. */ ngx_msleep(timer); ready = 0; } err = (ready == -1) ? ngx_socket_errno : 0; if (flags & NGX_UPDATE_TIME) { ngx_time_update(); } ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "select ready %d", ready); if (err) { ngx_log_error(NGX_LOG_ALERT, cycle->log, err, "select() failed"); if (err == WSAENOTSOCK) { ngx_select_repair_fd_sets(cycle); } return NGX_ERROR; } if (ready == 0) { if (timer != NGX_TIMER_INFINITE) { return NGX_OK; } ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "select() returned no events without timeout"); return NGX_ERROR; } ngx_mutex_lock(ngx_posted_events_mutex); nready = 0; for (i = 0; i < nevents; i++) { ev = event_index[i]; c = ev->data; found = 0; if (ev->write) { if (FD_ISSET(c->fd, &work_write_fd_set)) { found = 1; ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "select write %d", c->fd); } } else { if (FD_ISSET(c->fd, &work_read_fd_set)) { found = 1; ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "select read %d", c->fd); } } if (found) { ev->ready = 1; queue = (ngx_event_t **) (ev->accept ? &ngx_posted_accept_events: &ngx_posted_events); ngx_locked_post_event(ev, queue); nready++; } } ngx_mutex_unlock(ngx_posted_events_mutex); if (ready != nready) { ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "select ready != events: %d:%d", ready, nready); ngx_select_repair_fd_sets(cycle); } return NGX_OK; } static void ngx_select_repair_fd_sets(ngx_cycle_t *cycle) { int n; u_int i; socklen_t len; ngx_err_t err; ngx_socket_t s; for (i = 0; i < master_read_fd_set.fd_count; i++) { s = master_read_fd_set.fd_array[i]; len = sizeof(int); if (getsockopt(s, SOL_SOCKET, SO_TYPE, (char *) &n, &len) == -1) { err = ngx_socket_errno; ngx_log_error(NGX_LOG_ALERT, cycle->log, err, "invalid descriptor #%d in read fd_set", s); FD_CLR(s, &master_read_fd_set); } } for (i = 0; i < master_write_fd_set.fd_count; i++) { s = master_write_fd_set.fd_array[i]; len = sizeof(int); if (getsockopt(s, SOL_SOCKET, SO_TYPE, (char *) &n, &len) == -1) { err = ngx_socket_errno; ngx_log_error(NGX_LOG_ALERT, cycle->log, err, "invalid descriptor #%d in write fd_set", s); FD_CLR(s, &master_write_fd_set); } } } static char * ngx_select_init_conf(ngx_cycle_t *cycle, void *conf) { ngx_event_conf_t *ecf; ecf = ngx_event_get_conf(cycle->conf_ctx, ngx_event_core_module); if (ecf->use != ngx_select_module.ctx_index) { return NGX_CONF_OK; } return NGX_CONF_OK; }
bsd-2-clause
ssdr/nginx-1.6.0-annotated
src/os/unix/ngx_posix_init.c
69
2412
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <nginx.h> ngx_int_t ngx_ncpu; ngx_int_t ngx_max_sockets; ngx_uint_t ngx_inherited_nonblocking; ngx_uint_t ngx_tcp_nodelay_and_tcp_nopush; struct rlimit rlmt; ngx_os_io_t ngx_os_io = { ngx_unix_recv, ngx_readv_chain, ngx_udp_unix_recv, ngx_unix_send, ngx_writev_chain, 0 }; ngx_int_t ngx_os_init(ngx_log_t *log) { ngx_uint_t n; #if (NGX_HAVE_OS_SPECIFIC_INIT) if (ngx_os_specific_init(log) != NGX_OK) { return NGX_ERROR; } #endif ngx_init_setproctitle(log); ngx_pagesize = getpagesize(); ngx_cacheline_size = NGX_CPU_CACHE_LINE; for (n = ngx_pagesize; n >>= 1; ngx_pagesize_shift++) { /* void */ } #if (NGX_HAVE_SC_NPROCESSORS_ONLN) if (ngx_ncpu == 0) { ngx_ncpu = sysconf(_SC_NPROCESSORS_ONLN); } #endif if (ngx_ncpu < 1) { ngx_ncpu = 1; } ngx_cpuinfo(); if (getrlimit(RLIMIT_NOFILE, &rlmt) == -1) { ngx_log_error(NGX_LOG_ALERT, log, errno, "getrlimit(RLIMIT_NOFILE) failed)"); return NGX_ERROR; } ngx_max_sockets = (ngx_int_t) rlmt.rlim_cur; #if (NGX_HAVE_INHERITED_NONBLOCK || NGX_HAVE_ACCEPT4) ngx_inherited_nonblocking = 1; #else ngx_inherited_nonblocking = 0; #endif srandom(ngx_time()); return NGX_OK; } void ngx_os_status(ngx_log_t *log) { ngx_log_error(NGX_LOG_NOTICE, log, 0, NGINX_VER); #ifdef NGX_COMPILER ngx_log_error(NGX_LOG_NOTICE, log, 0, "built by " NGX_COMPILER); #endif #if (NGX_HAVE_OS_SPECIFIC_INIT) ngx_os_specific_status(log); #endif ngx_log_error(NGX_LOG_NOTICE, log, 0, "getrlimit(RLIMIT_NOFILE): %r:%r", rlmt.rlim_cur, rlmt.rlim_max); } #if 0 ngx_int_t ngx_posix_post_conf_init(ngx_log_t *log) { ngx_fd_t pp[2]; if (pipe(pp) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "pipe() failed"); return NGX_ERROR; } if (dup2(pp[1], STDERR_FILENO) == -1) { ngx_log_error(NGX_LOG_EMERG, log, errno, "dup2(STDERR) failed"); return NGX_ERROR; } if (pp[1] > STDERR_FILENO) { if (close(pp[1]) == -1) { ngx_log_error(NGX_LOG_EMERG, log, errno, "close() failed"); return NGX_ERROR; } } return NGX_OK; } #endif
bsd-2-clause
sdgdsffdsfff/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.2d/ssl/s2_enc.c
183
7055
/* ssl/s2_enc.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include "ssl_locl.h" #ifndef OPENSSL_NO_SSL2 # include <stdio.h> int ssl2_enc_init(SSL *s, int client) { /* Max number of bytes needed */ EVP_CIPHER_CTX *rs, *ws; const EVP_CIPHER *c; const EVP_MD *md; int num; if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) { ssl2_return_error(s, SSL2_PE_NO_CIPHER); SSLerr(SSL_F_SSL2_ENC_INIT, SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); return (0); } ssl_replace_hash(&s->read_hash, md); ssl_replace_hash(&s->write_hash, md); if ((s->enc_read_ctx == NULL) && ((s->enc_read_ctx = (EVP_CIPHER_CTX *) OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)) goto err; /* * make sure it's intialized in case the malloc for enc_write_ctx fails * and we exit with an error */ rs = s->enc_read_ctx; EVP_CIPHER_CTX_init(rs); if ((s->enc_write_ctx == NULL) && ((s->enc_write_ctx = (EVP_CIPHER_CTX *) OPENSSL_malloc(sizeof (EVP_CIPHER_CTX))) == NULL)) goto err; ws = s->enc_write_ctx; EVP_CIPHER_CTX_init(ws); num = c->key_len; s->s2->key_material_length = num * 2; OPENSSL_assert(s->s2->key_material_length <= sizeof s->s2->key_material); if (ssl2_generate_key_material(s) <= 0) return 0; OPENSSL_assert(c->iv_len <= (int)sizeof(s->session->key_arg)); EVP_EncryptInit_ex(ws, c, NULL, &(s->s2->key_material[(client) ? num : 0]), s->session->key_arg); EVP_DecryptInit_ex(rs, c, NULL, &(s->s2->key_material[(client) ? 0 : num]), s->session->key_arg); s->s2->read_key = &(s->s2->key_material[(client) ? 0 : num]); s->s2->write_key = &(s->s2->key_material[(client) ? num : 0]); return (1); err: SSLerr(SSL_F_SSL2_ENC_INIT, ERR_R_MALLOC_FAILURE); return (0); } /* * read/writes from s->s2->mac_data using length for encrypt and decrypt. * It sets s->s2->padding and s->[rw]length if we are encrypting Returns 0 on * error and 1 on success */ int ssl2_enc(SSL *s, int send) { EVP_CIPHER_CTX *ds; unsigned long l; int bs; if (send) { ds = s->enc_write_ctx; l = s->s2->wlength; } else { ds = s->enc_read_ctx; l = s->s2->rlength; } /* check for NULL cipher */ if (ds == NULL) return 1; bs = ds->cipher->block_size; /* * This should be using (bs-1) and bs instead of 7 and 8, but what the * hell. */ if (bs == 8) l = (l + 7) / 8 * 8; if (EVP_Cipher(ds, s->s2->mac_data, s->s2->mac_data, l) < 1) return 0; return 1; } void ssl2_mac(SSL *s, unsigned char *md, int send) { EVP_MD_CTX c; unsigned char sequence[4], *p, *sec, *act; unsigned long seq; unsigned int len; if (send) { seq = s->s2->write_sequence; sec = s->s2->write_key; len = s->s2->wact_data_length; act = s->s2->wact_data; } else { seq = s->s2->read_sequence; sec = s->s2->read_key; len = s->s2->ract_data_length; act = s->s2->ract_data; } p = &(sequence[0]); l2n(seq, p); /* There has to be a MAC algorithm. */ EVP_MD_CTX_init(&c); EVP_MD_CTX_copy(&c, s->read_hash); EVP_DigestUpdate(&c, sec, EVP_CIPHER_CTX_key_length(s->enc_read_ctx)); EVP_DigestUpdate(&c, act, len); /* the above line also does the pad data */ EVP_DigestUpdate(&c, sequence, 4); EVP_DigestFinal_ex(&c, md, NULL); EVP_MD_CTX_cleanup(&c); } #else /* !OPENSSL_NO_SSL2 */ # if PEDANTIC static void *dummy = &dummy; # endif #endif
bsd-2-clause
pinghe/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.1p/crypto/pem/pem_x509.c
184
2959
/* pem_x509.c */ /* * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project * 2001. */ /* ==================================================================== * Copyright (c) 2001 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> IMPLEMENT_PEM_rw(X509, X509, PEM_STRING_X509, X509)
bsd-2-clause
PopCap/GameIdea
Engine/Source/ThirdParty/ICU/icu4c-53_1/source/i18n/ucol_sit.cpp
197
21628
/* ******************************************************************************* * Copyright (C) 2004-2014, International Business Machines * Corporation and others. All Rights Reserved. ******************************************************************************* * file name: ucol_sit.cpp * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * Modification history * Date Name Comments * 03/12/2004 weiv Creation */ #include "unicode/ustring.h" #include "unicode/udata.h" #include "unicode/utf16.h" #include "utracimp.h" #include "ucol_imp.h" #include "cmemory.h" #include "cstring.h" #include "uresimp.h" #include "unicode/coll.h" #ifdef UCOL_TRACE_SIT # include <stdio.h> #endif #if !UCONFIG_NO_COLLATION #include "unicode/tblcoll.h" enum OptionsList { UCOL_SIT_LANGUAGE = 0, UCOL_SIT_SCRIPT = 1, UCOL_SIT_REGION = 2, UCOL_SIT_VARIANT = 3, UCOL_SIT_KEYWORD = 4, UCOL_SIT_PROVIDER = 5, UCOL_SIT_LOCELEMENT_MAX = UCOL_SIT_PROVIDER, /* the last element that's part of LocElements */ UCOL_SIT_BCP47, UCOL_SIT_STRENGTH, UCOL_SIT_CASE_LEVEL, UCOL_SIT_CASE_FIRST, UCOL_SIT_NUMERIC_COLLATION, UCOL_SIT_ALTERNATE_HANDLING, UCOL_SIT_NORMALIZATION_MODE, UCOL_SIT_FRENCH_COLLATION, UCOL_SIT_HIRAGANA_QUATERNARY, UCOL_SIT_VARIABLE_TOP, UCOL_SIT_VARIABLE_TOP_VALUE, UCOL_SIT_ITEMS_COUNT }; /* option starters chars. */ static const char alternateHArg = 'A'; static const char variableTopValArg = 'B'; static const char caseFirstArg = 'C'; static const char numericCollArg = 'D'; static const char caseLevelArg = 'E'; static const char frenchCollArg = 'F'; static const char hiraganaQArg = 'H'; static const char keywordArg = 'K'; static const char languageArg = 'L'; static const char normArg = 'N'; static const char providerArg = 'P'; static const char regionArg = 'R'; static const char strengthArg = 'S'; static const char variableTopArg = 'T'; static const char variantArg = 'V'; static const char RFC3066Arg = 'X'; static const char scriptArg = 'Z'; static const char collationKeyword[] = "@collation="; static const char providerKeyword[] = "@sp="; static const int32_t locElementCount = UCOL_SIT_LOCELEMENT_MAX+1; static const int32_t locElementCapacity = 32; static const int32_t loc3066Capacity = 256; static const int32_t locProviderCapacity = 10; static const int32_t internalBufferSize = 512; /* structure containing specification of a collator. Initialized * from a short string. Also used to construct a short string from a * collator instance */ struct CollatorSpec { char locElements[locElementCount][locElementCapacity]; char locale[loc3066Capacity]; char provider[locProviderCapacity]; UColAttributeValue options[UCOL_ATTRIBUTE_COUNT]; uint32_t variableTopValue; UChar variableTopString[locElementCapacity]; int32_t variableTopStringLen; UBool variableTopSet; struct { const char *start; int32_t len; } entries[UCOL_SIT_ITEMS_COUNT]; }; /* structure for converting between character attribute * representation and real collation attribute value. */ struct AttributeConversion { char letter; UColAttributeValue value; }; static const AttributeConversion conversions[12] = { { '1', UCOL_PRIMARY }, { '2', UCOL_SECONDARY }, { '3', UCOL_TERTIARY }, { '4', UCOL_QUATERNARY }, { 'D', UCOL_DEFAULT }, { 'I', UCOL_IDENTICAL }, { 'L', UCOL_LOWER_FIRST }, { 'N', UCOL_NON_IGNORABLE }, { 'O', UCOL_ON }, { 'S', UCOL_SHIFTED }, { 'U', UCOL_UPPER_FIRST }, { 'X', UCOL_OFF } }; static UColAttributeValue ucol_sit_letterToAttributeValue(char letter, UErrorCode *status) { uint32_t i = 0; for(i = 0; i < sizeof(conversions)/sizeof(conversions[0]); i++) { if(conversions[i].letter == letter) { return conversions[i].value; } } *status = U_ILLEGAL_ARGUMENT_ERROR; #ifdef UCOL_TRACE_SIT fprintf(stderr, "%s:%d: unknown letter %c: %s\n", __FILE__, __LINE__, letter, u_errorName(*status)); #endif return UCOL_DEFAULT; } /* function prototype for functions used to parse a short string */ U_CDECL_BEGIN typedef const char* U_CALLCONV ActionFunction(CollatorSpec *spec, uint32_t value1, const char* string, UErrorCode *status); U_CDECL_END U_CDECL_BEGIN static const char* U_CALLCONV _processLocaleElement(CollatorSpec *spec, uint32_t value, const char* string, UErrorCode *status) { int32_t len = 0; do { if(value == UCOL_SIT_LANGUAGE || value == UCOL_SIT_KEYWORD || value == UCOL_SIT_PROVIDER) { spec->locElements[value][len++] = uprv_tolower(*string); } else { spec->locElements[value][len++] = *string; } } while(*(++string) != '_' && *string && len < locElementCapacity); if(len >= locElementCapacity) { *status = U_BUFFER_OVERFLOW_ERROR; return string; } // don't skip the underscore at the end return string; } U_CDECL_END U_CDECL_BEGIN static const char* U_CALLCONV _processRFC3066Locale(CollatorSpec *spec, uint32_t, const char* string, UErrorCode *status) { char terminator = *string; string++; const char *end = uprv_strchr(string+1, terminator); if(end == NULL || end - string >= loc3066Capacity) { *status = U_BUFFER_OVERFLOW_ERROR; return string; } else { uprv_strncpy(spec->locale, string, end-string); return end+1; } } U_CDECL_END U_CDECL_BEGIN static const char* U_CALLCONV _processCollatorOption(CollatorSpec *spec, uint32_t option, const char* string, UErrorCode *status) { spec->options[option] = ucol_sit_letterToAttributeValue(*string, status); if((*(++string) != '_' && *string) || U_FAILURE(*status)) { #ifdef UCOL_TRACE_SIT fprintf(stderr, "%s:%d: unknown collator option at '%s': %s\n", __FILE__, __LINE__, string, u_errorName(*status)); #endif *status = U_ILLEGAL_ARGUMENT_ERROR; } return string; } U_CDECL_END static UChar readHexCodeUnit(const char **string, UErrorCode *status) { UChar result = 0; int32_t value = 0; char c; int32_t noDigits = 0; while((c = **string) != 0 && noDigits < 4) { if( c >= '0' && c <= '9') { value = c - '0'; } else if ( c >= 'a' && c <= 'f') { value = c - 'a' + 10; } else if ( c >= 'A' && c <= 'F') { value = c - 'A' + 10; } else { *status = U_ILLEGAL_ARGUMENT_ERROR; #ifdef UCOL_TRACE_SIT fprintf(stderr, "%s:%d: Bad hex char at '%s': %s\n", __FILE__, __LINE__, *string, u_errorName(*status)); #endif return 0; } result = (result << 4) | (UChar)value; noDigits++; (*string)++; } // if the string was terminated before we read 4 digits, set an error if(noDigits < 4) { *status = U_ILLEGAL_ARGUMENT_ERROR; #ifdef UCOL_TRACE_SIT fprintf(stderr, "%s:%d: Short (only %d digits, wanted 4) at '%s': %s\n", __FILE__, __LINE__, noDigits,*string, u_errorName(*status)); #endif } return result; } U_CDECL_BEGIN static const char* U_CALLCONV _processVariableTop(CollatorSpec *spec, uint32_t value1, const char* string, UErrorCode *status) { // get four digits int32_t i = 0; if(!value1) { while(U_SUCCESS(*status) && i < locElementCapacity && *string != 0 && *string != '_') { spec->variableTopString[i++] = readHexCodeUnit(&string, status); } spec->variableTopStringLen = i; if(i == locElementCapacity && *string != 0 && *string != '_') { *status = U_BUFFER_OVERFLOW_ERROR; } } else { spec->variableTopValue = readHexCodeUnit(&string, status); } if(U_SUCCESS(*status)) { spec->variableTopSet = TRUE; } return string; } U_CDECL_END /* Table for parsing short strings */ struct ShortStringOptions { char optionStart; ActionFunction *action; uint32_t attr; }; static const ShortStringOptions options[UCOL_SIT_ITEMS_COUNT] = { /* 10 ALTERNATE_HANDLING */ {alternateHArg, _processCollatorOption, UCOL_ALTERNATE_HANDLING }, // alternate N, S, D /* 15 VARIABLE_TOP_VALUE */ {variableTopValArg, _processVariableTop, 1 }, /* 08 CASE_FIRST */ {caseFirstArg, _processCollatorOption, UCOL_CASE_FIRST }, // case first L, U, X, D /* 09 NUMERIC_COLLATION */ {numericCollArg, _processCollatorOption, UCOL_NUMERIC_COLLATION }, // codan O, X, D /* 07 CASE_LEVEL */ {caseLevelArg, _processCollatorOption, UCOL_CASE_LEVEL }, // case level O, X, D /* 12 FRENCH_COLLATION */ {frenchCollArg, _processCollatorOption, UCOL_FRENCH_COLLATION }, // french O, X, D /* 13 HIRAGANA_QUATERNARY] */ {hiraganaQArg, _processCollatorOption, UCOL_HIRAGANA_QUATERNARY_MODE }, // hiragana O, X, D /* 04 KEYWORD */ {keywordArg, _processLocaleElement, UCOL_SIT_KEYWORD }, // keyword /* 00 LANGUAGE */ {languageArg, _processLocaleElement, UCOL_SIT_LANGUAGE }, // language /* 11 NORMALIZATION_MODE */ {normArg, _processCollatorOption, UCOL_NORMALIZATION_MODE }, // norm O, X, D /* 02 REGION */ {regionArg, _processLocaleElement, UCOL_SIT_REGION }, // region /* 06 STRENGTH */ {strengthArg, _processCollatorOption, UCOL_STRENGTH }, // strength 1, 2, 3, 4, I, D /* 14 VARIABLE_TOP */ {variableTopArg, _processVariableTop, 0 }, /* 03 VARIANT */ {variantArg, _processLocaleElement, UCOL_SIT_VARIANT }, // variant /* 05 RFC3066BIS */ {RFC3066Arg, _processRFC3066Locale, 0 }, // rfc3066bis locale name /* 01 SCRIPT */ {scriptArg, _processLocaleElement, UCOL_SIT_SCRIPT }, // script /* PROVIDER */ {providerArg, _processLocaleElement, UCOL_SIT_PROVIDER } }; static const char* ucol_sit_readOption(const char *start, CollatorSpec *spec, UErrorCode *status) { int32_t i = 0; for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) { if(*start == options[i].optionStart) { spec->entries[i].start = start; const char* end = options[i].action(spec, options[i].attr, start+1, status); spec->entries[i].len = (int32_t)(end - start); return end; } } *status = U_ILLEGAL_ARGUMENT_ERROR; #ifdef UCOL_TRACE_SIT fprintf(stderr, "%s:%d: Unknown option at '%s': %s\n", __FILE__, __LINE__, start, u_errorName(*status)); #endif return start; } static void ucol_sit_initCollatorSpecs(CollatorSpec *spec) { // reset everything uprv_memset(spec, 0, sizeof(CollatorSpec)); // set collation options to default int32_t i = 0; for(i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) { spec->options[i] = UCOL_DEFAULT; } } static const char* ucol_sit_readSpecs(CollatorSpec *s, const char *string, UParseError *parseError, UErrorCode *status) { const char *definition = string; while(U_SUCCESS(*status) && *string) { string = ucol_sit_readOption(string, s, status); // advance over '_' while(*string && *string == '_') { string++; } } if(U_FAILURE(*status)) { parseError->offset = (int32_t)(string - definition); } return string; } static int32_t ucol_sit_dumpSpecs(CollatorSpec *s, char *destination, int32_t capacity, UErrorCode *status) { int32_t i = 0, j = 0; int32_t len = 0; char optName; if(U_SUCCESS(*status)) { for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) { if(s->entries[i].start) { if(len) { if(len < capacity) { uprv_strcat(destination, "_"); } len++; } optName = *(s->entries[i].start); if(optName == languageArg || optName == regionArg || optName == variantArg || optName == keywordArg) { for(j = 0; j < s->entries[i].len; j++) { if(len + j < capacity) { destination[len+j] = uprv_toupper(*(s->entries[i].start+j)); } } len += s->entries[i].len; } else { len += s->entries[i].len; if(len < capacity) { uprv_strncat(destination,s->entries[i].start, s->entries[i].len); } } } } return len; } else { return 0; } } static void ucol_sit_calculateWholeLocale(CollatorSpec *s) { // put the locale together, unless we have a done // locale if(s->locale[0] == 0) { // first the language uprv_strcat(s->locale, s->locElements[UCOL_SIT_LANGUAGE]); // then the script, if present if(*(s->locElements[UCOL_SIT_SCRIPT])) { uprv_strcat(s->locale, "_"); uprv_strcat(s->locale, s->locElements[UCOL_SIT_SCRIPT]); } // then the region, if present if(*(s->locElements[UCOL_SIT_REGION])) { uprv_strcat(s->locale, "_"); uprv_strcat(s->locale, s->locElements[UCOL_SIT_REGION]); } else if(*(s->locElements[UCOL_SIT_VARIANT])) { // if there is a variant, we need an underscore uprv_strcat(s->locale, "_"); } // add variant, if there if(*(s->locElements[UCOL_SIT_VARIANT])) { uprv_strcat(s->locale, "_"); uprv_strcat(s->locale, s->locElements[UCOL_SIT_VARIANT]); } // if there is a collation keyword, add that too if(*(s->locElements[UCOL_SIT_KEYWORD])) { uprv_strcat(s->locale, collationKeyword); uprv_strcat(s->locale, s->locElements[UCOL_SIT_KEYWORD]); } // if there is a provider keyword, add that too if(*(s->locElements[UCOL_SIT_PROVIDER])) { uprv_strcat(s->locale, providerKeyword); uprv_strcat(s->locale, s->locElements[UCOL_SIT_PROVIDER]); } } } U_CAPI void U_EXPORT2 ucol_prepareShortStringOpen( const char *definition, UBool, UParseError *parseError, UErrorCode *status) { if(U_FAILURE(*status)) return; UParseError internalParseError; if(!parseError) { parseError = &internalParseError; } parseError->line = 0; parseError->offset = 0; parseError->preContext[0] = 0; parseError->postContext[0] = 0; // first we want to pick stuff out of short string. // we'll end up with an UCA version, locale and a bunch of // settings // analyse the string in order to get everything we need. CollatorSpec s; ucol_sit_initCollatorSpecs(&s); ucol_sit_readSpecs(&s, definition, parseError, status); ucol_sit_calculateWholeLocale(&s); char buffer[internalBufferSize]; uprv_memset(buffer, 0, internalBufferSize); uloc_canonicalize(s.locale, buffer, internalBufferSize, status); UResourceBundle *b = ures_open(U_ICUDATA_COLL, buffer, status); /* we try to find stuff from keyword */ UResourceBundle *collations = ures_getByKey(b, "collations", NULL, status); UResourceBundle *collElem = NULL; char keyBuffer[256]; // if there is a keyword, we pick it up and try to get elements if(!uloc_getKeywordValue(buffer, "collation", keyBuffer, 256, status)) { // no keyword. we try to find the default setting, which will give us the keyword value UResourceBundle *defaultColl = ures_getByKeyWithFallback(collations, "default", NULL, status); if(U_SUCCESS(*status)) { int32_t defaultKeyLen = 0; const UChar *defaultKey = ures_getString(defaultColl, &defaultKeyLen, status); u_UCharsToChars(defaultKey, keyBuffer, defaultKeyLen); keyBuffer[defaultKeyLen] = 0; } else { *status = U_INTERNAL_PROGRAM_ERROR; return; } ures_close(defaultColl); } collElem = ures_getByKeyWithFallback(collations, keyBuffer, collElem, status); ures_close(collElem); ures_close(collations); ures_close(b); } U_CAPI UCollator* U_EXPORT2 ucol_openFromShortString( const char *definition, UBool forceDefaults, UParseError *parseError, UErrorCode *status) { UTRACE_ENTRY_OC(UTRACE_UCOL_OPEN_FROM_SHORT_STRING); UTRACE_DATA1(UTRACE_INFO, "short string = \"%s\"", definition); if(U_FAILURE(*status)) return 0; UParseError internalParseError; if(!parseError) { parseError = &internalParseError; } parseError->line = 0; parseError->offset = 0; parseError->preContext[0] = 0; parseError->postContext[0] = 0; // first we want to pick stuff out of short string. // we'll end up with an UCA version, locale and a bunch of // settings // analyse the string in order to get everything we need. const char *string = definition; CollatorSpec s; ucol_sit_initCollatorSpecs(&s); string = ucol_sit_readSpecs(&s, definition, parseError, status); ucol_sit_calculateWholeLocale(&s); char buffer[internalBufferSize]; uprv_memset(buffer, 0, internalBufferSize); uloc_canonicalize(s.locale, buffer, internalBufferSize, status); UCollator *result = ucol_open(buffer, status); int32_t i = 0; for(i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) { if(s.options[i] != UCOL_DEFAULT) { if(forceDefaults || ucol_getAttribute(result, (UColAttribute)i, status) != s.options[i]) { ucol_setAttribute(result, (UColAttribute)i, s.options[i], status); } if(U_FAILURE(*status)) { parseError->offset = (int32_t)(string - definition); ucol_close(result); return NULL; } } } if(s.variableTopSet) { if(s.variableTopString[0]) { ucol_setVariableTop(result, s.variableTopString, s.variableTopStringLen, status); } else { // we set by value, using 'B' ucol_restoreVariableTop(result, s.variableTopValue, status); } } if(U_FAILURE(*status)) { // here it can only be a bogus value ucol_close(result); result = NULL; } UTRACE_EXIT_PTR_STATUS(result, *status); return result; } U_CAPI int32_t U_EXPORT2 ucol_getShortDefinitionString(const UCollator *coll, const char *locale, char *dst, int32_t capacity, UErrorCode *status) { if(U_FAILURE(*status)) return 0; if(coll == NULL) { *status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } return ((icu::Collator*)coll)->internalGetShortDefinitionString(locale,dst,capacity,*status); } U_CAPI int32_t U_EXPORT2 ucol_normalizeShortDefinitionString(const char *definition, char *destination, int32_t capacity, UParseError *parseError, UErrorCode *status) { if(U_FAILURE(*status)) { return 0; } if(destination) { uprv_memset(destination, 0, capacity*sizeof(char)); } UParseError pe; if(!parseError) { parseError = &pe; } // validate CollatorSpec s; ucol_sit_initCollatorSpecs(&s); ucol_sit_readSpecs(&s, definition, parseError, status); return ucol_sit_dumpSpecs(&s, destination, capacity, status); } /** * Get a set containing the contractions defined by the collator. The set includes * both the UCA contractions and the contractions defined by the collator * @param coll collator * @param conts the set to hold the result * @param status to hold the error code * @return the size of the contraction set */ U_CAPI int32_t U_EXPORT2 ucol_getContractions( const UCollator *coll, USet *contractions, UErrorCode *status) { ucol_getContractionsAndExpansions(coll, contractions, NULL, FALSE, status); return uset_getItemCount(contractions); } /** * Get a set containing the expansions defined by the collator. The set includes * both the UCA expansions and the expansions defined by the tailoring * @param coll collator * @param conts the set to hold the result * @param addPrefixes add the prefix contextual elements to contractions * @param status to hold the error code * * @draft ICU 3.4 */ U_CAPI void U_EXPORT2 ucol_getContractionsAndExpansions( const UCollator *coll, USet *contractions, USet *expansions, UBool addPrefixes, UErrorCode *status) { if(U_FAILURE(*status)) { return; } if(coll == NULL) { *status = U_ILLEGAL_ARGUMENT_ERROR; return; } const icu::RuleBasedCollator *rbc = icu::RuleBasedCollator::rbcFromUCollator(coll); if(rbc == NULL) { *status = U_UNSUPPORTED_ERROR; return; } rbc->internalGetContractionsAndExpansions( icu::UnicodeSet::fromUSet(contractions), icu::UnicodeSet::fromUSet(expansions), addPrefixes, *status); } #endif
bsd-2-clause
maxim2266/OCR
src/ocr_ls.c
1
3370
#include "list_pages.h" #include <limits.h> #include <getopt.h> #include <fcntl.h> #include <sys/uio.h> static const char usage_string[] = "Usage:\t" PROG_NAME " [OPTION]... [DIR]\n" "List image or text files (aka pages) produced by ocr-* tools, from the directory DIR,\n" "ordered by page number.\n\n" "Options:\n" " -0,--null\n" " Output items are terminated by a null character instead of by newline.\n\n" " -t,--text\n" " List text files instead of images.\n\n" " -p,--pages=SPEC\n" " Pages to list. A page specification contains one or more comma-separated page\n" " ranges. A page range is either a page number, or two page numbers separated by\n" " a dash. In the last range, the second page number may be omitted, meaning all\n" " the remaining pages of the document. For instance, specification \"1-10\" outputs\n" " pages 1 to 10, and specification \"1,3,5-\" outputs pages 1 and 3, followed by\n" " all the pages starting from page 5 to the end of the document.\n" " (optional, default: all pages)\n\n" " -f,--fail-on-empty\n" " Fail if no files found.\n\n" " -h,--help\n" " Show help and exit.\n\n" " -v,--version\n" " Show version and exit.\n"; // command line parameters typedef struct { const char *dir, *ext; const page_spec* spec; char delim; } command; // option parser static bool fail_on_empty = false; static void parse_options(command* const cmd, int argc, char** argv) { // options specification static const struct option long_options[] = { {"null", no_argument, NULL, '0'}, {"text", no_argument, NULL, 't'}, {"pages", required_argument, NULL, 'p'}, {"fail-on-empty", no_argument, NULL, 'f'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0} }; // prepare target *cmd = (command){ .dir = ".", .ext = "pgm", .delim = '\n' }; // parser loop int opt, option_index = 0; while((opt = getopt_long(argc, argv, "+0tp:fhv", long_options, &option_index)) >= 0) { switch(opt) { case '0': cmd->delim = 0; break; case 't': cmd->ext = "txt"; break; case 'p': if(cmd->spec) free((void*)cmd->spec); if(!(cmd->spec = parse_page_spec(optarg))) die(0, "empty parameter specified for -p,--pages option"); break; case 'f': fail_on_empty = true; break; case 'h': show_usage_and_exit(usage_string); break; case 'v': show_version_and_exit(); break; case '?': exit(1); default: die(0, "internal error (getopt_long(3) returned %d)", opt); } } // directory switch(argc - optind) { case 0: break; case 1: cmd->dir = argv[optind]; break; default: die(0, "cannot process more than one directory"); } } int main(int argc, char** argv) { command cmd; parse_options(&cmd, argc, argv); // make sure stdin is closed on exec just(fcntl(STDIN_FILENO, F_SETFD, fcntl(STDIN_FILENO, F_GETFD) | FD_CLOEXEC)); // get file list str_list* const list = list_files(cmd.dir, cmd.spec, cmd.ext); if(!str_list_is_empty(list)) { str_join_range(stdout, str_ref_chars(&cmd.delim, 1), list->strings, list->len); just(putchar(cmd.delim)); } else if(fail_on_empty) error(2, 0, "no files found"); str_list_free(list); // useless... return 0; }
bsd-3-clause
dava/dava.engine
Programs/ColladaConverter/Collada15/FCollada/FCDocument/FCDAnimationKey.cpp
1
1418
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ #include "StdAfx.h" #include "FCDocument/FCDAnimationKey.h" // // FCDAnimationMKey // FCDAnimationMKey::FCDAnimationMKey(uint32 _dimension) : dimension(_dimension) { output = new float[dimension]; } FCDAnimationMKey::~FCDAnimationMKey() { SAFE_DELETE_ARRAY(output); } // // FCDAnimationMKeyBezier // FCDAnimationMKeyBezier::FCDAnimationMKeyBezier(uint32 dimension) : FCDAnimationMKey(dimension) { inTangent = new FMVector2[dimension]; outTangent = new FMVector2[dimension]; } FCDAnimationMKeyBezier::~FCDAnimationMKeyBezier() { SAFE_DELETE_ARRAY(inTangent); SAFE_DELETE_ARRAY(outTangent); } // // FCDAnimationMKeyTCB // FCDAnimationMKeyTCB::FCDAnimationMKeyTCB(uint32 dimension) : FCDAnimationMKey(dimension) { tension = new float[dimension]; continuity = new float[dimension]; bias = new float[dimension]; easeIn = new float[dimension]; easeOut = new float[dimension]; } FCDAnimationMKeyTCB::~FCDAnimationMKeyTCB() { SAFE_DELETE_ARRAY(tension); SAFE_DELETE_ARRAY(continuity); SAFE_DELETE_ARRAY(bias); SAFE_DELETE_ARRAY(easeIn); SAFE_DELETE_ARRAY(easeOut); }
bsd-3-clause
sbranden/arm-trusted-firmware
plat/arm/board/common/board_css_common.c
1
2641
/* * Copyright (c) 2015-2016, ARM Limited and Contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of ARM nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <arm_def.h> #include <plat_arm.h> /* * Table of memory regions for different BL stages to map using the MMU. * This doesn't include Trusted SRAM as arm_setup_page_tables() already * takes care of mapping it. */ #ifdef IMAGE_BL1 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_FLASH0_RO, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, SOC_CSS_MAP_DEVICE, #if TRUSTED_BOARD_BOOT ARM_MAP_NS_DRAM1, #endif {0} }; #endif #ifdef IMAGE_BL2 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_FLASH0_RO, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, SOC_CSS_MAP_DEVICE, ARM_MAP_NS_DRAM1, ARM_MAP_TSP_SEC_MEM, {0} }; #endif #ifdef IMAGE_BL2U const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, CSS_MAP_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif #ifdef IMAGE_BL31 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif #ifdef IMAGE_BL32 const mmap_region_t plat_arm_mmap[] = { V2M_MAP_IOFPGA, CSS_MAP_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif ARM_CASSERT_MMAP
bsd-3-clause
cgaebel/mordor
mordor/http/client.cpp
1
51379
// Copyright (c) 2009 - Decho Corporation #include "client.h" #include <algorithm> #include <boost/bind.hpp> #include "chunked.h" #include "mordor/assert.h" #include "mordor/fiber.h" #include "mordor/log.h" #include "mordor/scheduler.h" #include "mordor/streams/limited.h" #include "mordor/streams/notify.h" #include "mordor/streams/null.h" #include "mordor/streams/timeout.h" #include "mordor/streams/transfer.h" #include "mordor/timer.h" #include "mordor/util.h" #include "mordor/atomic.h" #include "multipart.h" #include "parser.h" namespace Mordor { namespace HTTP { static Logger::ptr g_log = Log::lookup("mordor:http:client"); ClientConnection::ClientConnection(Stream::ptr stream, TimerManager *timerManager) : Connection(stream), m_readTimeout(~0ull), m_idleTimeout(~0ull), m_timerManager(timerManager), m_currentRequest(m_pendingRequests.end()), m_allowNewRequests(true), m_priorRequestFailed(false), m_requestCount(0), m_priorResponseFailed(~0ull), m_priorResponseClosed(~0ull) { static Atomic<size_t> connectionCount(0); m_connectionNumber = ++connectionCount; MORDOR_LOG_TRACE(g_log) << "ClientConnection " << m_connectionNumber << " = " << this; if (timerManager) { FilterStream::ptr previous; FilterStream::ptr filter = boost::dynamic_pointer_cast<FilterStream>(m_stream); while (filter) { previous = filter; filter = boost::dynamic_pointer_cast<FilterStream>(filter->parent()); } // Put the timeout stream as close to the actual source stream as // possible, to avoid registering timeouts for stuff that's going to // complete immediately anyway if (previous) { m_timeoutStream.reset(new TimeoutStream(previous->parent(), *timerManager)); previous->parent(m_timeoutStream); } else { m_timeoutStream.reset(new TimeoutStream(m_stream, *timerManager)); m_stream = m_timeoutStream; } } } ClientConnection::~ClientConnection() { if (m_idleTimer) m_idleTimer->cancel(); } ClientRequest::ptr ClientConnection::request(const Request &requestHeaders) { ClientRequest::ptr request(new ClientRequest(shared_from_this(), requestHeaders)); request->waitForRequest(); return request; } bool ClientConnection::newRequestsAllowed() { boost::mutex::scoped_lock lock(m_mutex); return m_allowNewRequests && m_priorResponseClosed == ~0ull && !m_priorRequestFailed && m_priorResponseFailed == ~0ull; } size_t ClientConnection::outstandingRequests() { boost::mutex::scoped_lock lock(m_mutex); invariant(); return m_pendingRequests.size(); } bool ClientConnection::supportsTimeouts() const { return !!m_timerManager; } void ClientConnection::readTimeout(unsigned long long us) { MORDOR_ASSERT(m_timeoutStream); m_readTimeout = us; } void ClientConnection::writeTimeout(unsigned long long us) { MORDOR_ASSERT(m_timeoutStream); m_timeoutStream->writeTimeout(us); } void ClientConnection::idleTimeout(unsigned long long us, boost::function<void ()> dg) { MORDOR_ASSERT(m_timerManager); boost::mutex::scoped_lock lock(m_mutex); if (m_idleTimer) { m_idleTimer->cancel(); m_idleTimer.reset(); } m_idleTimeout = us; m_idleDg = dg; if (m_idleTimeout != ~0ull && m_pendingRequests.empty()) m_idleTimer = m_timerManager->registerTimer(m_idleTimeout, dg); } void ClientConnection::scheduleNextRequest(ClientRequest *request) { bool flush = false; boost::mutex::scoped_lock lock(m_mutex); invariant(); MORDOR_ASSERT(m_currentRequest != m_pendingRequests.end()); MORDOR_ASSERT(request == *m_currentRequest); MORDOR_ASSERT(request->m_requestState == ClientRequest::BODY || request->m_requestState == ClientRequest::HEADERS); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " request complete"; std::list<ClientRequest *>::iterator it(m_currentRequest); ++it; if (it == m_pendingRequests.end()) { // Do *not* advance m_currentRequest, because we can't let someone else // start another request until our flush completes below flush = true; } else { request->m_requestState = ClientRequest::COMPLETE; if (request->m_responseState >= ClientRequest::COMPLETE) { MORDOR_ASSERT(request == m_pendingRequests.front()); m_pendingRequests.pop_front(); } m_currentRequest = it; request = *it; request->m_requestState = ClientRequest::HEADERS; MORDOR_ASSERT(request->m_scheduler); MORDOR_ASSERT(request->m_fiber); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " scheduling request"; request->m_scheduler->schedule(request->m_fiber); request->m_scheduler = NULL; request->m_fiber.reset(); } bool close = false; if (flush) { // Take a trip through the Scheduler, trying to let someone else // attempt to pipeline if (Scheduler::getThis()) { lock.unlock(); Scheduler::yield(); lock.lock(); } invariant(); std::list<ClientRequest *>::iterator it(m_currentRequest); ++it; if (it == m_pendingRequests.end()) { // Nope, still the end, we really do have to flush lock.unlock(); } else { flush = false; } if (flush) { flush = false; try { MORDOR_LOG_TRACE(g_log) << m_connectionNumber << " flushing"; m_stream->flush(); } catch (...) { request->requestFailed(); throw; } lock.lock(); invariant(); } request->m_requestState = ClientRequest::COMPLETE; ++m_currentRequest; if (request->m_responseState >= ClientRequest::COMPLETE) { MORDOR_ASSERT(request == m_pendingRequests.front()); m_pendingRequests.pop_front(); if (m_priorResponseClosed <= request->m_requestNumber || m_priorResponseFailed <= request->m_requestNumber) { MORDOR_ASSERT(m_pendingRequests.empty()); close = true; lock.unlock(); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << " closing"; } } // Someone else may have queued up while we were flushing if (!flush && m_currentRequest != m_pendingRequests.end()) { request = *m_currentRequest; request->m_requestState = ClientRequest::HEADERS; MORDOR_ASSERT(request->m_scheduler); MORDOR_ASSERT(request->m_fiber); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " scheduling request"; request->m_scheduler->schedule(request->m_fiber); request->m_scheduler = NULL; request->m_fiber.reset(); } else { if (m_timeoutStream) m_timeoutStream->readTimeout(m_readTimeout); } } if (close) { try { m_stream->close(); } catch (...) { } } } void ClientConnection::scheduleNextResponse(ClientRequest *request) { bool close = false; { boost::mutex::scoped_lock lock(m_mutex); invariant(); MORDOR_ASSERT(!m_pendingRequests.empty()); MORDOR_ASSERT(request == m_pendingRequests.front()); MORDOR_ASSERT(request->m_responseState == ClientRequest::BODY || request->m_responseState == ClientRequest::HEADERS); request->m_responseState = ClientRequest::COMPLETE; MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " response complete"; std::list<ClientRequest *>::iterator it = m_pendingRequests.begin(); ++it; if (request->m_requestState >= ClientRequest::COMPLETE) { m_pendingRequests.pop_front(); if (m_priorResponseClosed <= request->m_requestNumber || m_priorResponseFailed <= request->m_requestNumber) close = true; } if (it != m_pendingRequests.end()) { request = *it; MORDOR_ASSERT(request); MORDOR_ASSERT(request->m_responseState <= ClientRequest::WAITING || request->m_responseState > ClientRequest::COMPLETE); if (request->m_responseState == ClientRequest::WAITING) { std::set<ClientRequest *>::iterator it2 = m_waitingResponses.find(request); MORDOR_ASSERT(it2 != m_waitingResponses.end()); m_waitingResponses.erase(it2); request->m_responseState = ClientRequest::HEADERS; MORDOR_ASSERT(request->m_scheduler); MORDOR_ASSERT(request->m_fiber); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " scheduling response"; request->m_scheduler->schedule(request->m_fiber); request->m_scheduler = NULL; request->m_fiber.reset(); request = NULL; } else if (request->m_responseState == ClientRequest::PENDING || request->m_responseState == ClientRequest::ERROR) { request = NULL; } } else { if (m_idleTimeout != ~0ull) { MORDOR_ASSERT(!m_idleTimer); MORDOR_ASSERT(m_timerManager); MORDOR_ASSERT(m_idleDg); m_idleTimer = m_timerManager->registerTimer(m_idleTimeout, m_idleDg); } request = NULL; } } if (request) { MORDOR_ASSERT(request->m_responseState == ClientRequest::CANCELED); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " skipping response"; request->finish(); request = NULL; } if (close && m_stream->supportsHalfClose()) { MORDOR_ASSERT(!request); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << " closing"; try { m_stream->close(Stream::READ); } catch (...) { } } } void ClientConnection::scheduleAllWaitingRequests() { MORDOR_ASSERT(m_priorRequestFailed || m_priorResponseFailed != ~0ull || m_priorResponseClosed != ~0ull); // MORDOR_ASSERT(m_mutex.locked()); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << " scheduling all requests"; for (std::list<ClientRequest *>::iterator it(m_currentRequest); it != m_pendingRequests.end(); ) { ClientRequest *request = *it; MORDOR_ASSERT(request->m_requestState != ClientRequest::COMPLETE); if (request->m_requestState == ClientRequest::WAITING) { MORDOR_ASSERT(request->m_scheduler); MORDOR_ASSERT(request->m_fiber); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " scheduling request"; request->m_scheduler->schedule(request->m_fiber); request->m_scheduler = NULL; request->m_fiber.reset(); if (m_currentRequest == it) { m_currentRequest = it = m_pendingRequests.erase(it); } else { it = m_pendingRequests.erase(it); } } else { ++it; } } } void ClientConnection::scheduleAllWaitingResponses() { MORDOR_ASSERT(m_priorResponseFailed != ~0ull || m_priorResponseClosed != ~0ull); // MORDOR_ASSERT(m_mutex.locked()); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << " scheduling all responses"; unsigned long long firstResponseToSchedule = std::min(m_priorResponseFailed, m_priorResponseClosed); std::list<ClientRequest *>::iterator end = m_currentRequest; if (end != m_pendingRequests.end()) ++end; for (std::list<ClientRequest *>::iterator it(m_pendingRequests.begin()); it != end;) { ClientRequest *request = *it; if (request->m_requestNumber > firstResponseToSchedule) { switch (request->m_responseState) { case ClientRequest::PENDING: case ClientRequest::ERROR: ++it; continue; case ClientRequest::WAITING: { std::set<ClientRequest *>::iterator waiting = m_waitingResponses.find(request); MORDOR_ASSERT(waiting != m_waitingResponses.end()); MORDOR_ASSERT(request->m_scheduler); MORDOR_ASSERT(request->m_fiber); MORDOR_ASSERT(request->m_responseState == ClientRequest::WAITING); MORDOR_LOG_TRACE(g_log) << m_connectionNumber << "-" << request->m_requestNumber << " scheduling response"; request->m_responseState = ClientRequest::ERROR; request->m_scheduler->schedule(request->m_fiber); request->m_scheduler = NULL; request->m_fiber.reset(); if (request->m_requestState >= ClientRequest::COMPLETE) it = m_pendingRequests.erase(it); m_waitingResponses.erase(waiting); continue; } default: MORDOR_NOTREACHED(); } } ++it; } } void ClientConnection::invariant() const { #ifdef DEBUG // MORDOR_ASSERT(m_mutex.locked()); bool seenFirstUnrequested = false; unsigned long long lastRequestNumber = 0; for (std::list<ClientRequest *>::const_iterator it(m_pendingRequests.begin()); it != m_pendingRequests.end(); ++it) { ClientRequest *request = *it; MORDOR_ASSERT(request->m_requestNumber != 0); if (lastRequestNumber == 0) { lastRequestNumber = request->m_requestNumber; } else { MORDOR_ASSERT(lastRequestNumber + 1 == request->m_requestNumber || request->m_requestNumber >= m_priorResponseFailed || request->m_requestNumber >= m_priorResponseClosed); lastRequestNumber = request->m_requestNumber; } MORDOR_ASSERT(request->m_requestState < ClientRequest::COMPLETE || request->m_responseState < ClientRequest::COMPLETE || request->m_responseState == ClientRequest::CANCELED); // NOTE: it is allowed to have a response complete before the request // completes, BUT you can't have a response start before the request // starts if (request->m_responseState > ClientRequest::WAITING) MORDOR_ASSERT(request->m_requestState > ClientRequest::WAITING); if (!seenFirstUnrequested) { if (request->m_requestState < ClientRequest::COMPLETE) { seenFirstUnrequested = true; MORDOR_ASSERT(request->m_requestState > ClientRequest::WAITING); MORDOR_ASSERT(m_currentRequest == it); } } else { MORDOR_ASSERT(request->m_requestState == ClientRequest::WAITING); } if (it != m_pendingRequests.begin()) MORDOR_ASSERT(request->m_responseState <= ClientRequest::WAITING || request->m_responseState > ClientRequest::COMPLETE); } if (!seenFirstUnrequested) MORDOR_ASSERT(m_currentRequest == m_pendingRequests.end()); std::list<ClientRequest *>::const_iterator end = m_currentRequest; if (end != m_pendingRequests.end()) ++end; for (std::set<ClientRequest *>::const_iterator it(m_waitingResponses.begin()); it != m_waitingResponses.end(); ++it) { ClientRequest *request = *it; MORDOR_ASSERT(request); MORDOR_ASSERT(request->m_responseState == ClientRequest::WAITING); MORDOR_ASSERT(std::find<std::list<ClientRequest *>::const_iterator> (m_pendingRequests.begin(), end, request) != end); } #endif } ClientRequest::ClientRequest(ClientConnection::ptr conn, const Request &request) : m_conn(conn), m_requestNumber(0), m_scheduler(NULL), m_request(request), m_requestState(WAITING), m_responseState(PENDING), m_badTrailer(false), m_incompleteTrailer(false), m_hasResponseBody(false) { MORDOR_ASSERT(m_conn); } ClientRequest::~ClientRequest() { cancel(true); #ifdef DEBUG MORDOR_ASSERT(m_conn); boost::mutex::scoped_lock lock(m_conn->m_mutex); MORDOR_ASSERT(std::find(m_conn->m_pendingRequests.begin(), m_conn->m_pendingRequests.end(), this) == m_conn->m_pendingRequests.end()); MORDOR_ASSERT(m_conn->m_waitingResponses.find(this) == m_conn->m_waitingResponses.end()); #endif } Request & ClientRequest::request() { return m_request; } bool ClientRequest::hasRequestBody() const { return Connection::hasMessageBody(m_request.general, m_request.entity, m_request.requestLine.method, INVALID, false); } Stream::ptr ClientRequest::requestStream() { if (m_requestStream) { MORDOR_ASSERT(m_request.entity.contentType.type != "multipart"); return m_requestStream; } doRequest(); MORDOR_ASSERT(!m_requestMultipart); MORDOR_ASSERT(m_request.entity.contentType.type != "multipart"); if (!hasRequestBody()) { m_requestStream = Stream::ptr(&NullStream::get(), &nop<Stream *>); m_requestStream.reset(new LimitedStream(m_requestStream, 0)); return m_requestStream; } MORDOR_ASSERT(m_requestState == BODY); return m_requestStream = m_conn->getStream(m_request.general, m_request.entity, m_request.requestLine.method, INVALID, boost::bind(&ClientRequest::requestDone, this), boost::bind(&ClientRequest::requestFailed, this), false); } Multipart::ptr ClientRequest::requestMultipart() { if (m_requestMultipart) return m_requestMultipart; doRequest(); MORDOR_ASSERT(m_request.entity.contentType.type == "multipart"); MORDOR_ASSERT(!m_requestStream); MORDOR_ASSERT(m_requestState == BODY); StringMap::const_iterator it = m_request.entity.contentType.parameters.find("boundary"); if (it == m_request.entity.contentType.parameters.end()) { MORDOR_THROW_EXCEPTION(MissingMultipartBoundaryException()); } m_requestStream = m_conn->getStream(m_request.general, m_request.entity, m_request.requestLine.method, INVALID, boost::bind(&ClientRequest::requestDone, this), boost::bind(&ClientRequest::requestFailed, this), false); m_requestMultipart.reset(new Multipart(m_requestStream, it->second)); m_requestMultipart->multipartFinished = boost::bind(&ClientRequest::requestMultipartDone, shared_from_this()); return m_requestMultipart; } EntityHeaders & ClientRequest::requestTrailer() { // If transferEncoding is not empty, it must include chunked, // and it must include chunked in order to have a trailer MORDOR_ASSERT(!m_request.general.transferEncoding.empty()); return m_requestTrailer; } const Response & ClientRequest::response() { ensureResponse(); return m_response; } bool ClientRequest::hasResponseBody() { ensureResponse(); if (m_hasResponseBody) return true; return Connection::hasMessageBody(m_response.general, m_response.entity, m_request.requestLine.method, m_response.status.status); } Stream::ptr ClientRequest::responseStream() { Stream::ptr result = m_responseStream.lock(); if (result || m_hasResponseBody) { MORDOR_ASSERT(result && "responseStream() can only be accessed once without caching it"); MORDOR_ASSERT(m_response.entity.contentType.type != "multipart"); return result; } ensureResponse(); if (m_responseState >= COMPLETE) { m_hasResponseBody = true; result.reset(&NullStream::get(), &nop<Stream *>); m_responseStream = result; return result; } MORDOR_ASSERT(m_responseState == BODY); MORDOR_ASSERT(m_response.entity.contentType.type != "multipart"); result = m_conn->getStream(m_response.general, m_response.entity, m_request.requestLine.method, m_response.status.status, boost::bind(&ClientRequest::responseDone, shared_from_this()), boost::bind(&ClientRequest::cancel, shared_from_this(), true, true), true); m_hasResponseBody = true; m_responseStream = result; return result; } const EntityHeaders & ClientRequest::responseTrailer() const { if (m_badTrailer) MORDOR_THROW_EXCEPTION(BadMessageHeaderException()); if (m_incompleteTrailer) MORDOR_THROW_EXCEPTION(IncompleteMessageHeaderException()); MORDOR_ASSERT(m_responseState >= COMPLETE); MORDOR_ASSERT(!m_response.general.transferEncoding.empty()); return m_responseTrailer; } Stream::ptr ClientRequest::stream() { MORDOR_ASSERT(m_request.requestLine.method == CONNECT); ensureResponse(); MORDOR_ASSERT(m_response.status.status == OK); return m_conn->m_stream; } Multipart::ptr ClientRequest::responseMultipart() { Multipart::ptr result = m_responseMultipart.lock(); if (result) return result; // You can only ask for the response stream once // (to avoid circular references) MORDOR_ASSERT(!m_hasResponseBody); ensureResponse(); MORDOR_ASSERT(m_responseState == BODY); MORDOR_ASSERT(m_response.entity.contentType.type == "multipart"); StringMap::const_iterator it = m_response.entity.contentType.parameters.find("boundary"); if (it == m_response.entity.contentType.parameters.end()) { MORDOR_THROW_EXCEPTION(MissingMultipartBoundaryException()); } Stream::ptr stream = m_conn->getStream(m_response.general, m_response.entity, m_request.requestLine.method, m_response.status.status, NULL, boost::bind(&ClientRequest::cancel, shared_from_this(), true, true), true); m_responseStream = stream; result.reset(new Multipart(stream, it->second)); result->multipartFinished = boost::bind(&ClientRequest::responseDone, shared_from_this()); m_responseMultipart = result; return result; } void ClientRequest::cancel(bool abort, bool error) { if (m_requestState >= COMPLETE && m_responseState >= COMPLETE) return; MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << (abort ? " aborting" : " cancelling"); if (!abort && m_requestState == WAITING && m_responseState <= WAITING) { // Just abandon it m_requestState = CANCELED; m_responseState = CANCELED; boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); std::list<ClientRequest *>::iterator it = std::find(m_conn->m_pendingRequests.begin(), m_conn->m_pendingRequests.end(), this); MORDOR_ASSERT(it != m_conn->m_pendingRequests.end()); m_conn->m_pendingRequests.erase(it); if (m_responseState == WAITING) { std::set<ClientRequest *>::iterator waitIt = m_conn->m_waitingResponses.find(this); MORDOR_ASSERT(waitIt != m_conn->m_waitingResponses.end()); m_conn->m_waitingResponses.erase(waitIt); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " scheduling response"; m_scheduler->schedule(m_fiber); m_scheduler = NULL; m_fiber.reset(); } return; } if (m_requestStream) { FilterStream *filter = static_cast<FilterStream *>(m_requestStream.get()); if (filter->parent().get() != &NullStream::get()) { // Break the circular reference NotifyStream::ptr notify = boost::dynamic_pointer_cast<NotifyStream>(m_requestStream); MORDOR_ASSERT(notify); notify->notifyOnClose = NULL; notify->notifyOnEof = NULL; notify->notifyOnException = NULL; notify->parent(Stream::ptr(new Stream())); } } Stream::ptr responseStream = m_responseStream.lock(); ClientRequest::ptr self; if (responseStream) { // notify may be holding the last reference to this, so keep ourself in scope self = shared_from_this(); NotifyStream::ptr notify = boost::dynamic_pointer_cast<NotifyStream>(responseStream); MORDOR_ASSERT(notify); notify->notifyOnClose = NULL; notify->notifyOnEof = NULL; notify->notifyOnException = NULL; } bool close = false, waiting = m_responseState == WAITING; if (m_responseState != HEADERS) abort = true; { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); m_conn->m_priorResponseFailed = m_requestNumber; if (m_requestState < COMPLETE) m_requestState = error ? ERROR : CANCELED; if (m_responseState < COMPLETE && abort) m_responseState = error ? ERROR : CANCELED; std::list<ClientRequest *>::iterator it = std::find(m_conn->m_pendingRequests.begin(), m_conn->m_pendingRequests.end(), this); MORDOR_ASSERT(it != m_conn->m_pendingRequests.end()); close = it == m_conn->m_pendingRequests.begin(); if (abort) { if (it == m_conn->m_currentRequest) m_conn->m_currentRequest = m_conn->m_pendingRequests.erase(it); else m_conn->m_pendingRequests.erase(it); } else if (it == m_conn->m_currentRequest) { ++m_conn->m_currentRequest; } if (waiting) { std::set<ClientRequest *>::iterator waitIt = m_conn->m_waitingResponses.find(this); MORDOR_ASSERT(waitIt != m_conn->m_waitingResponses.end()); m_conn->m_waitingResponses.erase(waitIt); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " scheduling response"; m_scheduler->schedule(m_fiber); m_scheduler = NULL; m_fiber.reset(); } m_conn->scheduleAllWaitingRequests(); m_conn->scheduleAllWaitingResponses(); } if (close) m_conn->m_stream->cancelRead(); m_conn->m_stream->cancelWrite(); } void ClientRequest::finish() { if (m_requestState != COMPLETE) { cancel(true); return; } if (hasResponseBody()) { if (m_response.entity.contentType.type == "multipart") { Multipart::ptr multipart; if (m_hasResponseBody) multipart = m_responseMultipart.lock(); else multipart = responseMultipart(); if (!multipart) cancel(true); else while(multipart->nextPart()); } else { Stream::ptr stream; if (m_hasResponseBody) stream = m_responseStream.lock(); else stream = responseStream(); if (!stream) cancel(true); else transferStream(stream, NullStream::get()); } } } void ClientRequest::waitForRequest() { bool firstRequest; // Put the request in the queue { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); if (!m_conn->m_allowNewRequests || m_conn->m_priorResponseClosed != ~0ull) { m_requestState = m_responseState = ERROR; MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); } if (m_conn->m_priorRequestFailed || m_conn->m_priorResponseFailed != ~0ull) { m_requestState = m_responseState = ERROR; MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); } if (m_conn->m_idleTimer) { m_conn->m_idleTimer->cancel(); m_conn->m_idleTimer.reset(); } firstRequest = m_conn->m_currentRequest == m_conn->m_pendingRequests.end(); m_requestNumber = ++m_conn->m_requestCount; m_conn->m_pendingRequests.push_back(this); if (firstRequest) { m_conn->m_currentRequest = m_conn->m_pendingRequests.end(); --m_conn->m_currentRequest; m_requestState = HEADERS; // Disable read timeouts while a request is in progress if (m_conn->m_timeoutStream) m_conn->m_timeoutStream->readTimeout(~0ull); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " requesting"; } else { m_scheduler = Scheduler::getThis(); m_fiber = Fiber::getThis(); MORDOR_ASSERT(m_scheduler); MORDOR_ASSERT(m_fiber); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " waiting to request"; } } // If we weren't the first request in the queue, we have to wait for // another request to schedule us if (!firstRequest) { Scheduler::yieldTo(); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " requesting"; // Check for problems that occurred while we were waiting boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); if (m_conn->m_priorResponseClosed != ~0ull || m_conn->m_priorRequestFailed || m_conn->m_priorResponseFailed != ~0ull) { if (m_requestState == HEADERS) { MORDOR_ASSERT(m_conn->m_currentRequest != m_conn->m_pendingRequests.end()); MORDOR_ASSERT(*m_conn->m_currentRequest == this); m_conn->m_currentRequest = m_conn->m_pendingRequests.erase(m_conn->m_currentRequest); MORDOR_ASSERT(m_conn->m_currentRequest == m_conn->m_pendingRequests.end()); } m_requestState = m_responseState = ERROR; if (m_conn->m_priorResponseClosed != ~0ull) MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); else MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); } } MORDOR_ASSERT(m_requestState == HEADERS); } void ClientRequest::doRequest() { if (m_requestState > HEADERS) return; RequestLine &requestLine = m_request.requestLine; // 1.0, 1.1, or defaulted MORDOR_ASSERT(requestLine.ver == Version() || requestLine.ver == Version(1, 0) || requestLine.ver == Version(1, 1)); // Have to request *something* MORDOR_ASSERT(requestLine.uri.isDefined()); // Host header required with HTTP/1.1 MORDOR_ASSERT(!m_request.request.host.empty() || requestLine.ver != Version(1, 1)); // If any transfer encodings, must include chunked, must have chunked only once, and must be the last one const ParameterizedList &transferEncoding = m_request.general.transferEncoding; if (!transferEncoding.empty()) { MORDOR_ASSERT(transferEncoding.back().value == "chunked"); for (ParameterizedList::const_iterator it(transferEncoding.begin()); it + 1 != transferEncoding.end(); ++it) { // Only the last one can be chunked MORDOR_ASSERT(it->value != "chunked"); // identity is only acceptable in the TE header field MORDOR_ASSERT(it->value != "identity"); if (it->value == "gzip" || it->value == "x-gzip" || it->value == "deflate") { // Known Transfer-Codings continue; } else if (it->value == "compress" || it->value == "x-compress") { // Unsupported Transfer-Codings MORDOR_NOTREACHED(); } else { // Unknown Transfer-Coding MORDOR_NOTREACHED(); } } } bool close; // Default HTTP version... 1.1 if possible if (requestLine.ver == Version()) { if (m_request.request.host.empty()) requestLine.ver = Version(1, 0); else requestLine.ver = Version(1, 1); } // If not specified, try to keep the connection open StringSet &connection = m_request.general.connection; if (connection.find("close") == connection.end() && requestLine.ver == Version(1, 0)) { connection.insert("Keep-Alive"); } // Determine if we're closing the connection after this request if (requestLine.ver == Version(1, 0)) { if (connection.find("Keep-Alive") != connection.end()) { close = false; } else { close = true; connection.insert("close"); } } else { if (connection.find("close") != connection.end()) { close = true; } else { close = false; } } if (close) { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); m_conn->m_allowNewRequests = false; } // TE is a connection-specific header if (!m_request.request.te.empty()) m_request.general.connection.insert("TE"); try { // Do the request std::ostringstream os; os << m_request; std::string str = os.str(); if (g_log->enabled(Log::DEBUG)) { std::string webAuth, proxyAuth; if (stricmp(m_request.request.authorization.scheme.c_str(), "Basic") == 0) { webAuth = m_request.request.authorization.base64; m_request.request.authorization.base64 = "<hidden>"; } if (stricmp(m_request.request.proxyAuthorization.scheme.c_str(), "Basic") == 0) { proxyAuth = m_request.request.proxyAuthorization.base64; m_request.request.proxyAuthorization.base64 = "<hidden>"; } MORDOR_LOG_DEBUG(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber<< " " << m_request; if (!webAuth.empty()) m_request.request.authorization.base64 = webAuth; if (!proxyAuth.empty()) m_request.request.proxyAuthorization.base64 = proxyAuth; } else { MORDOR_LOG_VERBOSE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " " << m_request.requestLine; } m_conn->m_stream->write(str.c_str(), str.size()); if (!Connection::hasMessageBody(m_request.general, m_request.entity, requestLine.method, INVALID, false)) { MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " no request body"; m_conn->scheduleNextRequest(this); } else { m_requestState = BODY; } } catch(...) { requestFailed(); throw; } } void ClientRequest::ensureResponse() { if (m_priorResponseException) ::Mordor::rethrow_exception(m_priorResponseException); if (m_responseState == BODY || m_responseState >= COMPLETE) return; try { bool wait = false; MORDOR_ASSERT(m_responseState == PENDING); { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); if (m_conn->m_priorResponseFailed <= m_requestNumber || m_conn->m_priorResponseClosed <= m_requestNumber) { if (m_requestState >= COMPLETE) { std::list<ClientRequest *>::iterator it; it = std::find(m_conn->m_pendingRequests.begin(), m_conn->m_pendingRequests.end(), this); MORDOR_ASSERT(it != m_conn->m_pendingRequests.end()); m_conn->m_pendingRequests.erase(it); } m_responseState = ERROR; if (m_conn->m_priorResponseClosed <= m_requestNumber) MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); else MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); } MORDOR_ASSERT(!m_conn->m_pendingRequests.empty()); ClientRequest *request = m_conn->m_pendingRequests.front(); if (request != this) { m_scheduler = Scheduler::getThis(); m_fiber = Fiber::getThis(); MORDOR_ASSERT(m_scheduler); MORDOR_ASSERT(m_fiber); #ifdef DEBUG bool inserted = #endif m_conn->m_waitingResponses.insert(this) #ifdef DEBUG .second #endif ; MORDOR_ASSERT(inserted); wait = true; m_responseState = WAITING; MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber<< " waiting for response"; } else { m_responseState = HEADERS; MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " reading response"; } } // If we weren't the first response in the queue, wait for someone // else to schedule us if (wait) { Scheduler::yieldTo(); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " reading response"; // Check for problems that occurred while we were waiting boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); if (m_responseState == CANCELED) MORDOR_THROW_EXCEPTION(OperationAbortedException()); if (m_responseState == ERROR) { if (m_conn->m_priorResponseClosed <= m_requestNumber) MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); else MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); } // Probably means that the Scheduler exited in the above yieldTo, // and returned to us, because there is no other work to be done try { MORDOR_ASSERT(!m_conn->m_pendingRequests.empty()); MORDOR_ASSERT(m_conn->m_pendingRequests.front() == this); } catch(...) { m_responseState = PENDING; std::set<ClientRequest *>::iterator it = m_conn->m_waitingResponses.find(this); if (it != m_conn->m_waitingResponses.end()) m_conn->m_waitingResponses.erase(it); throw; } } try { MORDOR_ASSERT(m_responseState == HEADERS); // Read and parse headers ResponseParser parser(m_response); unsigned long long read = parser.run(m_conn->m_stream); MORDOR_ASSERT(m_responseState == HEADERS || m_responseState > COMPLETE); if (m_responseState > COMPLETE) MORDOR_THROW_EXCEPTION(OperationAbortedException()); if (read == 0ull) MORDOR_THROW_EXCEPTION(UnexpectedEofException()); if (parser.error()) MORDOR_THROW_EXCEPTION(BadMessageHeaderException()); if (!parser.complete()) MORDOR_THROW_EXCEPTION(IncompleteMessageHeaderException()); if (g_log->enabled(Log::DEBUG)) { MORDOR_LOG_DEBUG(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " " << m_response; } else { MORDOR_LOG_VERBOSE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " " << m_response.status; } bool close = false; StringSet &connection = m_response.general.connection; if (m_response.status.ver == Version(1, 0)) { if (connection.find("Keep-Alive") == connection.end()) close = true; } else if (m_response.status.ver == Version(1, 1)) { if (connection.find("close") != connection.end()) close = true; } else { MORDOR_THROW_EXCEPTION(BadMessageHeaderException()); } // NON-STANDARD!!! StringSet &proxyConnection = m_response.general.proxyConnection; if (proxyConnection.find("close") != proxyConnection.end()) close = true; ParameterizedList &transferEncoding = m_response.general.transferEncoding; // Remove identity from the Transfer-Encodings for (ParameterizedList::iterator it(transferEncoding.begin()); it != transferEncoding.end(); ++it) { if (stricmp(it->value.c_str(), "identity") == 0) { it = transferEncoding.erase(it); --it; } } if (!transferEncoding.empty()) { if (stricmp(transferEncoding.back().value.c_str(), "chunked") != 0) { MORDOR_THROW_EXCEPTION(InvalidTransferEncodingException("The last transfer-coding is not chunked.")); } for (ParameterizedList::const_iterator it(transferEncoding.begin()); it + 1 != transferEncoding.end(); ++it) { if (stricmp(it->value.c_str(), "chunked") == 0) { MORDOR_THROW_EXCEPTION(InvalidTransferEncodingException("chunked transfer-coding applied multiple times")); } else if (stricmp(it->value.c_str(), "deflate") == 0 || stricmp(it->value.c_str(), "gzip") == 0 || stricmp(it->value.c_str(), "x-gzip") == 0) { // Supported transfer-codings } else if (stricmp(it->value.c_str(), "compress") == 0 || stricmp(it->value.c_str(), "x-compress") == 0) { MORDOR_THROW_EXCEPTION(InvalidTransferEncodingException("compress transfer-coding is unsupported")); } else { MORDOR_THROW_EXCEPTION(InvalidTransferEncodingException("Unrecognized transfer-coding: " + it->value)); } } } // If the there is a message body, but it's undelimited, make sure we're // closing the connection bool hasBody = Connection::hasMessageBody(m_response.general, m_response.entity, m_request.requestLine.method, m_response.status.status, false); if (hasBody && transferEncoding.empty() && m_response.entity.contentLength == ~0ull && m_response.entity.contentType.type != "multipart") { close = true; } bool connect = m_request.requestLine.method == CONNECT && m_response.status.status == OK; if (connect) close = true; if (close) { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); m_conn->m_priorResponseClosed = m_requestNumber; MORDOR_ASSERT(!m_conn->m_pendingRequests.empty()); MORDOR_ASSERT(m_conn->m_pendingRequests.front() == this); if (!hasBody && m_requestState >= COMPLETE) m_conn->m_pendingRequests.pop_front(); m_responseState = hasBody ? BODY : COMPLETE; m_conn->scheduleAllWaitingRequests(); m_conn->scheduleAllWaitingResponses(); } else { m_responseState = connect ? COMPLETE : BODY; } if (!hasBody && !connect) { MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " no response body"; if (close) { if (m_conn->m_stream->supportsHalfClose()) { try { m_conn->m_stream->close(Stream::READ); } catch (...) { } } } else { m_conn->scheduleNextResponse(this); } } } catch (...) { boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); m_conn->m_priorResponseFailed = std::min(m_requestNumber, m_conn->m_priorResponseFailed); m_responseState = ERROR; if (!m_conn->m_pendingRequests.empty() && m_conn->m_pendingRequests.front() == this) { if (m_requestState >= COMPLETE) m_conn->m_pendingRequests.pop_front(); m_conn->scheduleAllWaitingRequests(); m_conn->scheduleAllWaitingResponses(); } if (m_conn->m_priorResponseClosed < m_requestNumber) MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); if (m_conn->m_priorResponseFailed < m_requestNumber) MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); throw; } } catch (...) { m_priorResponseException = boost::current_exception(); throw; } } void ClientRequest::requestMultipartDone() { MORDOR_ASSERT(m_requestStream); m_requestStream->close(); } void ClientRequest::requestDone() { MORDOR_ASSERT(m_requestState == BODY); MORDOR_ASSERT(m_requestStream); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " request complete"; // Break the circular reference NotifyStream::ptr notify = boost::dynamic_pointer_cast<NotifyStream>(m_requestStream); MORDOR_ASSERT(notify); notify->notifyOnClose = NULL; notify->notifyOnEof = NULL; notify->notifyOnException = NULL; if (m_requestStream->supportsSize() && m_requestStream->supportsTell()) MORDOR_ASSERT(m_requestStream->size() == m_requestStream->tell()); if (!m_request.general.transferEncoding.empty()) { std::ostringstream os; os << m_requestTrailer << "\r\n"; std::string str = os.str(); MORDOR_LOG_DEBUG(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " " << str; m_conn->m_stream->write(str.c_str(), str.size()); } m_conn->scheduleNextRequest(this); } void ClientRequest::requestFailed() { if (m_requestState == ERROR) return; MORDOR_ASSERT(m_requestState == BODY || m_requestState == HEADERS); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " request failed"; if (m_requestStream) { // Break the circular reference NotifyStream::ptr notify = boost::dynamic_pointer_cast<NotifyStream>(m_requestStream); MORDOR_ASSERT(notify); notify->notifyOnClose = NULL; notify->notifyOnEof = NULL; notify->notifyOnException = NULL; } boost::mutex::scoped_lock lock(m_conn->m_mutex); m_conn->invariant(); MORDOR_ASSERT(!m_conn->m_pendingRequests.empty()); MORDOR_ASSERT(this == *m_conn->m_currentRequest); m_conn->m_priorRequestFailed = true; if (m_requestState == HEADERS) { switch (m_responseState) { case PENDING: m_responseState = CANCELED; m_conn->m_currentRequest = m_conn->m_pendingRequests.erase(m_conn->m_currentRequest); break; case WAITING: MORDOR_ASSERT(m_conn->m_waitingResponses.find(this) != m_conn->m_waitingResponses.end()); m_conn->m_waitingResponses.erase(this); m_conn->m_currentRequest = m_conn->m_pendingRequests.erase(m_conn->m_currentRequest); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " scheduling response"; m_scheduler->schedule(m_fiber); m_scheduler = NULL; m_fiber.reset(); m_responseState = CANCELED; break; case HEADERS: m_conn->m_stream->cancelRead(); case BODY: ++m_conn->m_currentRequest; break; default: MORDOR_ASSERT(this == m_conn->m_pendingRequests.front()); ++m_conn->m_currentRequest; m_conn->m_pendingRequests.pop_front(); break; } } else if (m_responseState >= COMPLETE) { MORDOR_ASSERT(this == m_conn->m_pendingRequests.front()); ++m_conn->m_currentRequest; m_conn->m_pendingRequests.pop_front(); } else { ++m_conn->m_currentRequest; } m_requestState = ERROR; m_conn->scheduleAllWaitingRequests(); // Throw an HTTP exception if we can if (m_conn->m_priorResponseClosed <= m_requestNumber) MORDOR_THROW_EXCEPTION(ConnectionVoluntarilyClosedException()); if (m_conn->m_priorResponseFailed <= m_requestNumber) MORDOR_THROW_EXCEPTION(PriorRequestFailedException()); } void ClientRequest::responseDone() { MORDOR_ASSERT(m_responseState == BODY); MORDOR_LOG_TRACE(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " response complete"; // Keep an extra ref to ourself around so we don't destruct if the only ref // is in the response stream ClientRequest::ptr self; try { self = shared_from_this(); } catch (boost::bad_weak_ptr &) { // means we're in the destructor } Stream::ptr stream = m_responseStream.lock(); MORDOR_ASSERT(stream); NotifyStream::ptr notify = boost::dynamic_pointer_cast<NotifyStream>(stream); MORDOR_ASSERT(notify); notify->notifyOnClose = NULL; notify->notifyOnEof = NULL; notify->notifyOnException = NULL; // Make sure every stream in the stack gets a proper EOF FilterStream::ptr filter = boost::dynamic_pointer_cast<FilterStream>(notify->parent()); Stream::ptr chunked, limited; while (filter && !chunked && !limited) { chunked = boost::dynamic_pointer_cast<ChunkedStream>(filter); limited = boost::dynamic_pointer_cast<LimitedStream>(filter); transferStream(filter, NullStream::get()); filter = boost::dynamic_pointer_cast<FilterStream>(filter->parent()); } if (!m_response.general.transferEncoding.empty()) { // Read and parse the trailer TrailerParser parser(m_responseTrailer); parser.run(m_conn->m_stream); if (parser.error()) { cancel(true); m_badTrailer = true; return; } if (!parser.complete()) { cancel(true); m_incompleteTrailer = true; return; } MORDOR_LOG_DEBUG(g_log) << m_conn->m_connectionNumber << "-" << m_requestNumber << " " << m_responseTrailer; } m_conn->scheduleNextResponse(this); } }}
bsd-3-clause
adtools/clib2
library/math_kernel_tanf.c
1
4357
/* * $Id: math_kernel_tanf.c,v 1.2 2006-01-08 12:04:23 obarthel Exp $ * * :ts=4 * * Portable ISO 'C' (1994) runtime library for the Amiga computer * Copyright (c) 2002-2015 by Olaf Barthel <obarthel (at) gmx.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Neither the name of Olaf Barthel nor the names of 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. * * * PowerPC math library based in part on work by Sun Microsystems * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * * * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ #ifndef _MATH_HEADERS_H #include "math_headers.h" #endif /* _MATH_HEADERS_H */ /****************************************************************************/ #if defined(FLOATING_POINT_SUPPORT) /****************************************************************************/ static const float one = 1.0000000000e+00, /* 0x3f800000 */ pio4 = 7.8539812565e-01, /* 0x3f490fda */ pio4lo= 3.7748947079e-08, /* 0x33222168 */ T[] = { 3.3333334327e-01, /* 0x3eaaaaab */ 1.3333334029e-01, /* 0x3e088889 */ 5.3968254477e-02, /* 0x3d5d0dd1 */ 2.1869488060e-02, /* 0x3cb327a4 */ 8.8632395491e-03, /* 0x3c11371f */ 3.5920790397e-03, /* 0x3b6b6916 */ 1.4562094584e-03, /* 0x3abede48 */ 5.8804126456e-04, /* 0x3a1a26c8 */ 2.4646313977e-04, /* 0x398137b9 */ 7.8179444245e-05, /* 0x38a3f445 */ 7.1407252108e-05, /* 0x3895c07a */ -1.8558637748e-05, /* 0xb79bae5f */ 2.5907305826e-05, /* 0x37d95384 */ }; float __kernel_tanf(float x, float y, int iy) { float z,r,v,w,s; LONG ix,hx; GET_FLOAT_WORD(hx,x); ix = hx&0x7fffffff; /* high word of |x| */ if(ix<0x31800000) /* x < 2**-28 */ {if((int)x==0) { /* generate inexact */ if((ix|(iy+1))==0) return one/fabsf(x); else return (iy==1)? x: -one/x; } } if(ix>=0x3f2ca140) { /* |x|>=0.6744 */ if(hx<0) {x = -x; y = -y;} z = pio4-x; w = pio4lo-y; x = z+w; y = 0.0; } z = x*x; w = z*z; /* Break x^5*(T[1]+x^2*T[2]+...) into * x^5(T[1]+x^4*T[3]+...+x^20*T[11]) + * x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12])) */ r = T[1]+w*(T[3]+w*(T[5]+w*(T[7]+w*(T[9]+w*T[11])))); v = z*(T[2]+w*(T[4]+w*(T[6]+w*(T[8]+w*(T[10]+w*T[12]))))); s = z*x; r = y + z*(s*(r+v)+y); r += T[0]*s; w = x+r; if(ix>=0x3f2ca140) { v = (float)iy; return (float)(1-((hx>>30)&2))*(v-(float)2.0*(x-(w*w/(w+v)-r))); } if(iy==1) return w; else { /* if allow error up to 2 ulp, simply return -1.0/(x+r) here */ /* compute -1.0/(x+r) accurately */ float a,t; LONG i; z = w; GET_FLOAT_WORD(i,z); SET_FLOAT_WORD(z,i&0xfffff000U); v = r-(z - x); /* z+v = r+x */ t = a = -(float)1.0/w; /* a = -1.0/w */ GET_FLOAT_WORD(i,t); SET_FLOAT_WORD(t,i&0xfffff000U); s = (float)1.0+t*z; return t+a*(s+t*v); } } /****************************************************************************/ #endif /* FLOATING_POINT_SUPPORT */
bsd-3-clause
wfnex/openbras
src/PPP/CPPPFsm.cpp
1
22750
/*********************************************************************** Copyright (c) 2017, The OpenBRAS project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of OpenBRAS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ #include "CPPPFsm.h" CPPPFsm::CPPPFsm(IFsmSink *psink, int protocol, const std::string &protname) :m_protocol(protocol) ,m_state(INITIAL) ,m_flags(0) ,m_id(0) ,m_reqid(0) ,m_seen_ack(0) ,m_timeouttime(DEFTIMEOUT) ,m_maxconfreqtransmits(DEFMAXCONFREQS) ,m_retransmits(0) ,m_maxtermtransmits(DEFMAXTERMREQS) ,m_nakloops(0) ,m_rnakloops(0) ,m_maxnakloops(DEFMAXNAKLOOPS) ,m_callbacks(psink) ,m_term_reason_len(0) ,m_strProtoName(protname) { ::memset(m_outpacket_buf, 0, sizeof(m_outpacket_buf)); } CPPPFsm::~CPPPFsm() { ACE_DEBUG ((LM_DEBUG, "CPPPFsm::~CPPPFsm\n")); CancelTimer(); } void CPPPFsm::Init() { m_state = INITIAL; m_flags = 0; m_id = 0; /* XXX Start with random id? */ m_timeouttime = DEFTIMEOUT; m_maxconfreqtransmits = DEFMAXCONFREQS; m_maxtermtransmits = DEFMAXTERMREQS; m_maxnakloops = DEFMAXNAKLOOPS; m_term_reason_len = 0; } /* * fsm_lowerup - The lower layer is up. */ void CPPPFsm::LowerUp() { switch (m_state) { case INITIAL: { this->m_state = CLOSED; break; } case STARTING: { if ( this->m_flags & OPT_SILENT ) { this->m_state = STOPPED; } else { /* Send an initial configure-request */ SendConfReq(0); this->m_state = REQSENT; } break; } } } /* * fsm_lowerdown - The lower layer is down. * * Cancel all timeouts and inform upper layers. */ void CPPPFsm::LowerDown() { switch ( this->m_state ) { case CLOSED: { this->m_state = INITIAL; break; } case STOPPED: { this->m_state = STARTING; m_callbacks->Starting(this); break; } case CLOSING: { this->m_state = INITIAL; CancelTimer(); break; } case STOPPING: case REQSENT: case ACKRCVD: case ACKSENT: { this->m_state = STARTING; CancelTimer(); break; } case OPENED: { m_callbacks->Down(this); this->m_state = STARTING; break; } } } //Cancel Timer void CPPPFsm::CancelTimer() { ACE_DEBUG ((LM_DEBUG, "CPPPFsm::CancelTimer\n")); ACE_Reactor::instance()->cancel_timer(this); } //Start Timer void CPPPFsm::StartTime(int seconds) { ACE_DEBUG ((LM_DEBUG, "CPPPFsm::StartTime, seconds = %d\n", seconds)); CancelTimer(); ACE_Time_Value delay(seconds); ACE_Reactor::instance()->schedule_timer(this, 0, delay, delay); } /* * fsm_open - Link is allowed to come up. */ void CPPPFsm::Open() { switch( this->m_state ){ case INITIAL: this->m_state = STARTING; m_callbacks->Starting(this); break; case CLOSED: if( this->m_flags & OPT_SILENT ) this->m_state = STOPPED; else { /* Send an initial configure-request */ SendConfReq(0); this->m_state = REQSENT; } break; case CLOSING: this->m_state = STOPPING; /* fall through */ case STOPPED: case OPENED: if( this->m_flags & OPT_RESTART ){ LowerDown(); LowerUp(); } break; } } /* * terminate_layer - Start process of shutting down the FSM * * Cancel any timeout running, notify upper layers we're done, and * send a terminate-request message as configured. */ void CPPPFsm::TerminateLayer(int nextstate) { ACE_DEBUG((LM_DEBUG, "CPPPFsm::TerminateLayer, nextstate=%d\n", nextstate)); if ( this->m_state != OPENED ) { CancelTimer(); } m_callbacks->Down(this);/* Inform upper layers we're down */ /* Init restart counter and send Terminate-Request */ this->m_retransmits = this->m_maxtermtransmits; ACE_DEBUG((LM_DEBUG, "send terminate request, protocol=%#x, reqId=%d, reason=%.*s\n", m_protocol, m_id + 1, m_term_reason_len, m_term_reason.c_str())); SendData(TERMREQ, this->m_reqid = ++this->m_id, (u_char *) this->m_term_reason.c_str(), this->m_term_reason.size()); if (this->m_retransmits == 0) { /* * User asked for no terminate requests at all; just close it. * We've already fired off one Terminate-Request just to be nice * to the peer, but we're not going to wait for a reply. */ this->m_state = nextstate == CLOSING ? CLOSED : STOPPED; m_callbacks->Finished(this); return; } StartTime(this->m_timeouttime); --this->m_retransmits; this->m_state = nextstate; } /* * fsm_close - Start closing connection. * * Cancel timeouts and either initiate close or possibly go directly to * the CLOSED state. */ void CPPPFsm::Close(char *reason) { this->m_term_reason = std::string(reason, strlen(reason)); this->m_term_reason_len = (reason == NULL ? 0 : strlen(reason)); switch ( this->m_state ) { case STARTING: { this->m_state = INITIAL; break; } case STOPPED: { this->m_state = CLOSED; break; } case STOPPING: { this->m_state = CLOSING; break; } case REQSENT: case ACKRCVD: case ACKSENT: case OPENED: { TerminateLayer(CLOSING); break; } } } //Timeout Handle int CPPPFsm::handle_timeout (const ACE_Time_Value &current_time, const void *act) { Timeout(NULL); } /* * fsm_timeout - Timeout expired. */ void CPPPFsm::Timeout(void *arg) { ACE_DEBUG((LM_DEBUG, "CPPPFsm::Timeout(), state=%d\n", this->m_state)); switch (this->m_state) { case CLOSING: case STOPPING: if( this->m_retransmits <= 0 ){ /* * We've waited for an ack long enough. Peer probably heard us. */ this->m_state = (this->m_state == CLOSING)? CLOSED: STOPPED; m_callbacks->Finished(this); } else { /* Send Terminate-Request */ SendData(TERMREQ, this->m_reqid = ++this->m_id, (u_char *) this->m_term_reason.c_str(), this->m_term_reason_len); StartTime(this->m_timeouttime); --this->m_retransmits; } break; case REQSENT: case ACKRCVD: case ACKSENT: if (this->m_retransmits <= 0) { this->m_state = STOPPED; if( (this->m_flags & OPT_PASSIVE) == 0) m_callbacks->Finished(this); } else { /* Retransmit the configure-request */ m_callbacks->Retransmit(this); SendConfReq(1); /* Re-send Configure-Request */ if( this->m_state == ACKRCVD ) this->m_state = REQSENT; } break; } } /* * fsm_input - Input packet. */ void CPPPFsm::Input(u_char *inpacket, int l) { u_char *inp; u_char code, id; int len; /* * Parse header (code, id and length). * If packet too short, drop it. */ inp = inpacket; if (l < HEADERLEN) { ACE_DEBUG((LM_ERROR, "CPPPFsm::Input, argument l too short(%d)\n", l)); return; } GETCHAR(code, inp); GETCHAR(id, inp); GETSHORT(len, inp); if (len < HEADERLEN) { ACE_DEBUG((LM_ERROR, "CPPPFsm::Input, length field in the pkt too short(%d)\n", len)); return; } if (len > l) { ACE_DEBUG((LM_ERROR, "CPPPFsm::Input, invalid length, len=%d, l=%d\n", len, l)); return; } len -= HEADERLEN; /* subtract header length */ if( this->m_state == INITIAL || this->m_state == STARTING ) { ACE_DEBUG((LM_INFO, "CPPPFsm::Input, improper state(%d), just discard the pkt\n", this->m_state)); return; } /* * Action depends on code. */ switch (code) { case CONFREQ: { RcvConfReq(id, inp, len); break; } case CONFACK: { RcvConfAck(id, inp, len); break; } case CONFNAK: case CONFREJ: { RcvConfNakRej(code, id, inp, len); break; } case TERMREQ: { RcvTermReq(id, inp, len); break; } case TERMACK: { RcvTermack(); break; } case CODEREJ: { RcvCodeReject(inp, len); break; } default: { if (!m_callbacks->ExtCode(this, code, id, inp, len) ) { SendData(CODEREJ, ++this->m_id, inpacket, len + HEADERLEN); } break; } } } /* * fsm_rconfreq - Receive Configure-Request. */ void CPPPFsm::RcvConfReq(u_char id, u_char *inp, int len) { int code, reject_if_disagree; /* ¶Ô´ËswitchÓï¾äµÄ˵Ã÷: ²»ÄÜΪÁ˱à³Ì¹æ·¶µÄÒªÇó¶ø¼òµ¥µÄ¼ÓÉÏdefault·ÖÖ§¡£ * Ô­Òò: default°üº¬ÒÔÏÂÁ½Àà״̬: (Initial Starting)¡¢(Req-Sent Ack-Rcvd Ack-Sent)£¬µÚÒ»ÀàÔÚPPPXCP.InputÖÐÖ±½Ó·µ»Ø * ÁË£¬²»»á×ßµ½ÕâÀï¡£µ«²»Äܽö½öÒÀÀµÍⲿº¯Êý¡£µÚ¶þÀàÐèÒªÖ´ÐÐswitchÏÂÃæµÄ·ÖÖ§¡£ * Èç¹ûÒª¸Ä£¬¿ÉÒÔÕâÑù¸Ä: * case INITIAL: * case STARTING: * return; * case REQSENT: * case ACKRCVD: * case ACKSENT: * default: * break; */ switch ( this->m_state ) { case CLOSED: { /* Go away, we're closed */ SendData(TERMACK, id, NULL, 0); return; } case STOPPED: { /* Negotiation started by our peer */ SendConfReq(0); /* Send initial Configure-Request */ this->m_state = REQSENT; break; } case CLOSING: case STOPPING: { return; } case OPENED: { m_callbacks->Down(this);/* Inform upper layers */ SendConfReq(0); /* Send initial Configure-Request */ this->m_state = REQSENT; break; } } /* * Pass the requested configuration options * to protocol-specific code for checking. */ reject_if_disagree = (this->m_nakloops >= this->m_maxnakloops); code = m_callbacks->Reqci(this, inp, &len, reject_if_disagree); if (code == -1) { if (len) code = CONFREJ; /* Reject all CI */ else code = CONFACK; } /* send the Ack, Nak or Rej to the peer */ SendData(code, id, inp, len); if (code == CONFACK) { if (this->m_state == ACKRCVD) { CancelTimer(); /* Cancel timeout */ this->m_state = OPENED; m_callbacks->Up(this);/* Inform upper layers */ } else { this->m_state = ACKSENT; } this->m_nakloops = 0; } else { /* we sent CONFACK or CONFREJ */ if (this->m_state != ACKRCVD) { this->m_state = REQSENT; } if ( code == CONFNAK ) { ++this->m_nakloops; } } } /* * fsm_rconfack - Receive Configure-Ack. */ void CPPPFsm::RcvConfAck(int id, u_char *inp, int len) { if (id != this->m_reqid || this->m_seen_ack)/* Expected id? */ { ACE_DEBUG((LM_ERROR, "CPPPFsm::RcvConfAck, id dismatch or already received valid Ack/Nak/Rej to Req\n")); ACE_DEBUG((LM_ERROR, "id=%d, this->m_reqid=%u, this->m_seen_ack=%u\n", id, this->m_reqid, this->m_seen_ack)); return; /* Nope, toss... */ } if(!m_callbacks->Ackci(this, inp, len)) { /* Ack is bad - ignore it */ ACE_DEBUG((LM_ERROR, "CPPPFsm::RcvConfAck, Ack is bad\n")); return; } this->m_seen_ack = 1; this->m_rnakloops = 0; switch (this->m_state) { case CLOSED: case STOPPED: { SendData(TERMACK, id, NULL, 0); break; } case REQSENT: { this->m_state = ACKRCVD; this->m_retransmits = this->m_maxconfreqtransmits; break; } case ACKRCVD: { /* Huh? an extra valid Ack? oh well... */ CancelTimer(); /* Cancel timeout */ SendConfReq(0); this->m_state = REQSENT; break; } case ACKSENT: { CancelTimer(); /* Cancel timeout */ this->m_state = OPENED; this->m_retransmits = this->m_maxconfreqtransmits; m_callbacks->Up(this); /* Inform upper layers */ break; } case OPENED: { /* Go down and restart negotiation */ m_callbacks->Down(this); /* Inform upper layers */ SendConfReq(0); /* Send initial Configure-Request */ this->m_state = REQSENT; break; } } } /* * fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject. */ void CPPPFsm::RcvConfNakRej(int code, int id, u_char *inp, int len) { int ret; int treat_as_reject; if (id != this->m_reqid || this->m_seen_ack) /* Expected id? */ { ACE_DEBUG((LM_ERROR, "CPPPFsm::RcvConfNakRej, id dismatch or already received valid Ack/Nak/Rej to Req\n")); ACE_DEBUG((LM_ERROR, "id=%d, this->m_reqid=%u, this->m_seen_ack=%u\n", id, m_reqid, m_seen_ack)); return; /* Nope, toss... */ } if (code == CONFNAK) { ++this->m_rnakloops; treat_as_reject = (this->m_rnakloops >= this->m_maxnakloops); if (!(ret = m_callbacks->Nakci(this, inp, len, treat_as_reject))) { ACE_DEBUG((LM_ERROR, "CPPPFsm::RcvConfNakRej, received bad nak.\n")); return; } } else { this->m_rnakloops = 0; if (!(ret = m_callbacks->Rejci(this, inp, len))) { ACE_DEBUG((LM_ERROR, "CPPPFsm::RcvConfNakRej, received bad reject.\n")); return; } } this->m_seen_ack = 1; switch (this->m_state) { case CLOSED: case STOPPED: SendData(TERMACK, id, NULL, 0); break; case REQSENT: case ACKSENT: /* They didn't agree to what we wanted - try another request */ CancelTimer(); if (ret < 0) this->m_state = STOPPED; /* kludge for stopping CCP */ else SendConfReq(0); /* Send Configure-Request */ break; case ACKRCVD: /* Got a Nak/reject when we had already had an Ack?? oh well... */ CancelTimer(); /* Cancel timeout */ SendConfReq(0); this->m_state = REQSENT; break; case OPENED: /* Go down and restart negotiation */ m_callbacks->Down(this); /* Inform upper layers */ SendConfReq(0); /* Send initial Configure-Request */ this->m_state = REQSENT; break; } } /* * fsm_rtermreq - Receive Terminate-Req. */ void CPPPFsm::RcvTermReq(int id, u_char *p, int len) { switch (this->m_state) { case ACKRCVD: case ACKSENT: { this->m_state = REQSENT; /* Start over but keep trying */ break; } case OPENED: { if (len > 0) { ACE_DEBUG ((LM_DEBUG,"%s terminated by peer (%.*s)\n", m_strProtoName.c_str(), len, p)); } else { ACE_DEBUG ((LM_DEBUG,"%s terminated by peer\n", m_strProtoName.c_str())); } this->m_retransmits = 0; this->m_state = STOPPING; SendData(TERMACK, id, NULL, 0); // Revised by mazhh as m_callbacks->Down will free the session memory, where // CPPPLCP and CPPPFsm lie. m_callbacks->Down(this); /* Inform upper layers */ StartTime(this->m_timeouttime); return; } } SendData(TERMACK, id, NULL, 0); } /* * fsm_rtermack - Receive Terminate-Ack. */ void CPPPFsm::RcvTermack() { switch (this->m_state) { case CLOSING: CancelTimer(); this->m_state = CLOSED; if (m_callbacks) { m_callbacks->Finished(this); } break; case STOPPING: CancelTimer(); this->m_state = STOPPED; if (m_callbacks) { m_callbacks->Finished(this); } break; case ACKRCVD: this->m_state = REQSENT; break; case OPENED: if (m_callbacks) { m_callbacks->Down(this);/* Inform upper layers */ } SendConfReq(0); this->m_state = REQSENT; break; } } /* * fsm_rcoderej - Receive an Code-Reject. */ void CPPPFsm::RcvCodeReject(u_char *inp, int len) { u_char code, id; if (len < HEADERLEN) { ACE_DEBUG ((LM_ERROR, "CPPPFsm::RcvCodeReject: Rcvd short Code-Reject packet! len=%d\n", len)); return; } GETCHAR(code, inp); GETCHAR(id, inp); ACE_DEBUG ((LM_DEBUG,"%s: Rcvd Code-Reject for code %d, id %d\n", m_strProtoName.c_str(), m_state, id)); if ( this->m_state == ACKRCVD ) { this->m_state = REQSENT; } } /* * fsm_protreject - Peer doesn't speak this protocol. * * Treat this as a catastrophic error (RXJ-). */ void CPPPFsm::ProtReject() { switch( this->m_state ) { case CLOSING: CancelTimer(); /* fall through */ case CLOSED: this->m_state = CLOSED; m_callbacks->Finished(this); break; case STOPPING: case REQSENT: case ACKRCVD: case ACKSENT: CancelTimer(); /* fall through */ case STOPPED: this->m_state = STOPPED; m_callbacks->Finished(this); break; case OPENED: TerminateLayer(STOPPING); break; default: ACE_DEBUG ((LM_DEBUG,"CPPPFsm::ProtReject %s: Protocol-reject event in state %d!", m_strProtoName.c_str(), m_state)); } } /* * fsm_sconfreq - Send a Configure-Request. */ void CPPPFsm::SendConfReq(int retransmit) { u_char *outp; int cilen; if( this->m_state != REQSENT && this->m_state != ACKRCVD && this->m_state != ACKSENT ){ /* Not currently negotiating - reset options */ m_callbacks->Resetci(this); this->m_nakloops = 0; this->m_rnakloops = 0; } if( !retransmit ){ /* New request - reset retransmission counter, use new ID */ this->m_retransmits = this->m_maxconfreqtransmits; this->m_reqid = ++this->m_id; } this->m_seen_ack = 0; /* * Make up the request packet */ outp = m_outpacket_buf + PPP_HDRLEN + HEADERLEN; cilen = m_callbacks->Cilen(this); if (cilen >PPP_MRU - HEADERLEN) { cilen = PPP_MRU - HEADERLEN; } m_callbacks->Addci(this,outp,&cilen); /* send the request to our peer */ SendData(CONFREQ, this->m_reqid, outp, cilen); /* start the retransmit timer */ --this->m_retransmits; StartTime(this->m_timeouttime); } /* * fsm_sdata - Send some data. * * Used for all packets sent to our peer by this module. */ void CPPPFsm::SendData(u_char code, u_char id, u_char *data, int datalen) { unsigned char *outp = NULL; int outlen = 0; /* Adjust length to be smaller than MTU */ outp = m_outpacket_buf; if (datalen > PPP_MRU - HEADERLEN) { datalen = PPP_MRU - HEADERLEN; } if (datalen && data != outp + PPP_HDRLEN + HEADERLEN) { BCOPY(data, outp + PPP_HDRLEN + HEADERLEN, datalen); } outlen = datalen + HEADERLEN; MAKEHEADER(outp, this->m_protocol); PUTCHAR(code, outp); PUTCHAR(id, outp); PUTSHORT(outlen, outp); Output(m_outpacket_buf, outlen + PPP_HDRLEN); } //Output Packet void CPPPFsm::Output(u_char *data, int datalen) { if (m_callbacks) { m_callbacks->OutputPacket(data, datalen); } return; } //Fsm status int CPPPFsm::State() { return m_state; } //Enable Flag void CPPPFsm::EnableFlag(int flag) { m_flags |=flag; } //Disable Flag void CPPPFsm::DisableFlag(int flag) { m_flags &=~flag; } //Get Id int CPPPFsm::GetId() { m_id++; return m_id; }
bsd-3-clause
MRPT/mrpt
libs/ros1bridge/src/map.cpp
1
6511
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <mrpt/config/CConfigFile.h> #include <mrpt/io/CFileGZInputStream.h> #include <mrpt/maps/CMultiMetricMap.h> #include <mrpt/maps/COccupancyGridMap2D.h> #include <mrpt/maps/CSimpleMap.h> #include <mrpt/ros1bridge/map.h> #include <mrpt/ros1bridge/pose.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/system/filesystem.h> // for fileExists() #include <mrpt/system/string_utils.h> // for lowerCase() #include <mrpt/version.h> #include <nav_msgs/OccupancyGrid.h> #include <ros/console.h> using namespace mrpt::config; using namespace mrpt::io; using mrpt::maps::CLogOddsGridMapLUT; using mrpt::maps::CMultiMetricMap; using mrpt::maps::COccupancyGridMap2D; using mrpt::maps::CSimpleMap; #ifndef INT8_MAX // avoid duplicated #define's #define INT8_MAX 0x7f #define INT8_MIN (-INT8_MAX - 1) #define INT16_MAX 0x7fff #define INT16_MIN (-INT16_MAX - 1) #endif // INT8_MAX using namespace mrpt::ros1bridge; MapHdl::MapHdl() { // MRPT -> ROS LUT: CLogOddsGridMapLUT<COccupancyGridMap2D::cellType> table; #ifdef OCCUPANCY_GRIDMAP_CELL_SIZE_8BITS const int i_min = INT8_MIN, i_max = INT8_MAX; #else const int i_min = INT16_MIN, i_max = INT16_MAX; #endif for (int i = i_min; i <= i_max; i++) { int8_t ros_val; if (i == 0) { // Unknown cell (no evidence data): ros_val = -1; } else { float p = 1.0 - table.l2p(i); ros_val = round(p * 100.); // printf("- cell -> ros = %4i -> %4i, p=%4.3f\n", i, ros_val, p); } lut_cellmrpt2ros[static_cast<int>(i) - i_min] = ros_val; } // ROS -> MRPT: [0,100] -> for (int i = 0; i <= 100; i++) { const float p = 1.0 - (i / 100.0); lut_cellros2mrpt[i] = table.p2l(p); // printf("- ros->cell=%4i->%4i p=%4.3f\n",i, lut_cellros2mrpt[i], p); } } MapHdl* MapHdl::instance() { static MapHdl m; // singeleton instance return &m; } bool mrpt::ros1bridge::fromROS( const nav_msgs::OccupancyGrid& src, COccupancyGridMap2D& des) { MRPT_START if ((src.info.origin.orientation.x != 0) || (src.info.origin.orientation.y != 0) || (src.info.origin.orientation.z != 0) || (src.info.origin.orientation.w != 1)) { std::cerr << "[fromROS] Rotated maps are not supported!\n"; return false; } float xmin = src.info.origin.position.x; float ymin = src.info.origin.position.y; float xmax = xmin + src.info.width * src.info.resolution; float ymax = ymin + src.info.height * src.info.resolution; des.setSize(xmin, xmax, ymin, ymax, src.info.resolution); auto inst = MapHdl::instance(); for (unsigned int h = 0; h < src.info.height; h++) { COccupancyGridMap2D::cellType* pDes = des.getRow(h); const int8_t* pSrc = &src.data[h * src.info.width]; for (unsigned int w = 0; w < src.info.width; w++) *pDes++ = inst->cellRos2Mrpt(*pSrc++); } return true; MRPT_END } bool mrpt::ros1bridge::toROS( const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des, const std_msgs::Header& header) { des.header = header; return toROS(src, des); } bool mrpt::ros1bridge::toROS( const COccupancyGridMap2D& src, nav_msgs::OccupancyGrid& des) { des.info.width = src.getSizeX(); des.info.height = src.getSizeY(); des.info.resolution = src.getResolution(); des.info.origin.position.x = src.getXMin(); des.info.origin.position.y = src.getYMin(); des.info.origin.position.z = 0; des.info.origin.orientation.x = 0; des.info.origin.orientation.y = 0; des.info.origin.orientation.z = 0; des.info.origin.orientation.w = 1; // I hope the data is always aligned des.data.resize(des.info.width * des.info.height); for (unsigned int h = 0; h < des.info.height; h++) { const COccupancyGridMap2D::cellType* pSrc = src.getRow(h); int8_t* pDes = &des.data[h * des.info.width]; for (unsigned int w = 0; w < des.info.width; w++) { *pDes++ = MapHdl::instance()->cellMrpt2Ros(*pSrc++); } } return true; } bool MapHdl::loadMap( CMultiMetricMap& _metric_map, const CConfigFileBase& _config_file, const std::string& _map_file, const std::string& _section_name, bool _debug) { using namespace mrpt::maps; TSetOfMetricMapInitializers mapInitializers; mapInitializers.loadFromConfigFile(_config_file, _section_name); CSimpleMap simpleMap; // Load the set of metric maps to consider in the experiments: _metric_map.setListOfMaps(mapInitializers); if (_debug) mapInitializers.dumpToConsole(); if (_debug) printf( "%s, _map_file.size() = %zu\n", _map_file.c_str(), _map_file.size()); // Load the map (if any): if (_map_file.size() < 3) { if (_debug) printf("No mrpt map file!\n"); return false; } else { ASSERT_(mrpt::system::fileExists(_map_file)); // Detect file extension: std::string mapExt = mrpt::system::lowerCase(mrpt::system::extractFileExtension( _map_file, true)); // Ignore possible .gz extensions if (!mapExt.compare("simplemap")) { // It's a ".simplemap": if (_debug) printf("Loading '.simplemap' file..."); CFileGZInputStream f(_map_file); mrpt::serialization::archiveFrom(f) >> simpleMap; printf("Ok\n"); ASSERTMSG_( simpleMap.size() > 0, "Simplemap was aparently loaded OK, but it is empty!"); // Build metric map: if (_debug) printf("Building metric map(s) from '.simplemap'..."); _metric_map.loadFromSimpleMap(simpleMap); if (_debug) printf("Ok\n"); } else if (!mapExt.compare("gridmap")) { // It's a ".gridmap": if (_debug) printf("Loading gridmap from '.gridmap'..."); ASSERTMSG_( _metric_map.countMapsByClass<COccupancyGridMap2D>() == 1, "Error: Trying to load a gridmap into a multi-metric map " "requires 1 gridmap member."); CFileGZInputStream fm(_map_file); mrpt::serialization::archiveFrom(fm) >> (*_metric_map.mapByClass<COccupancyGridMap2D>()); if (_debug) printf("Ok\n"); } else { THROW_EXCEPTION(mrpt::format( "Map file has unknown extension: '%s'", mapExt.c_str())); return false; } } return true; }
bsd-3-clause
profdevi/JangData
src/MStringList.cpp
1
7439
/* Copyright (C) 2011-2014, Comine.com ( profdevi@ymail.com ) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - The the names of the contributors of this project may not 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 FOUNDATION 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. */ //v1.18 copyright Comine.com 20150816U2133 #include "MStdLib.h" #include "MStringList.h" //******************************************************************** //** Module Elements //******************************************************************** struct GNode { char *Data; GNode *Next; }; //******************************************************************** //** MStringList //******************************************************************** void MStringList::ClearObject(void) { mFirstNode=NULL; mLastNode=NULL; mCurrent=NULL; mCount=0; } ////////////////////////////////////////////////////////////// MStringList::MStringList(void) { ClearObject(); } ////////////////////////////////////////////////////////////// MStringList::MStringList(bool create) { ClearObject(); if(create==true && Create()==false) { return; } } ////////////////////////////////////////////////////////////// MStringList::MStringList(MStringList &reflist) { ClearObject(); if(Create(reflist)==false) { return; } } ////////////////////////////////////////////////////////////// MStringList::~MStringList(void) { Destroy(); } ////////////////////////////////////////////////////////////// bool MStringList::Create(void) { Destroy(); return true; } ////////////////////////////////////////////////////////////// bool MStringList::Create(MStringList &reflist) { Destroy(); if(Create()==false) { Destroy(); return false; } // Iterate through the list GNode *p; for(p=reflist.mFirstNode;p!=NULL;p=p->Next) { MStdAssert(p->Data!=NULL); if(AddString(p->Data)==false) { Destroy(); return false; } } return true; } ///////////////////////////////////////////////////////////// bool MStringList::Destroy(void) { GNode *pnode; GNode *tmp; for(pnode=mFirstNode;pnode!=NULL; pnode=tmp) { tmp=pnode->Next; if(pnode->Data!=NULL) { delete[] pnode->Data; pnode->Data=NULL; } delete pnode; } ClearObject(); return true; } ////////////////////////////////////////////////////////////// bool MStringList::AddString(const char *string) // Add to the end of the list { if(string==NULL) { return false; } GNode *newnode; newnode=new(std::nothrow) GNode; if(newnode==NULL) { return false; } newnode->Data=new(std::nothrow) char[MStdStrLen(string)+1]; if(newnode->Data==NULL) { delete newnode; return false; } MStdStrCpy(newnode->Data,string); newnode->Next=NULL; // Increment count mCount = mCount + 1; if(mFirstNode==NULL) { mCurrent=mFirstNode=mLastNode=newnode; return true; } mLastNode->Next=newnode; mLastNode=newnode; return true; } //////////////////////////////////////////////////////////// bool MStringList::AddList(MStringList &list) { GNode *p; for(p=list.mFirstNode;p!=NULL;p=p->Next) { if(AddString(p->Data)==false) { return false; } } return true; } //////////////////////////////////////////////////////////// bool MStringList::ReadReset(void) // Will Reset to the first item again { mCurrent=mFirstNode; return true; } //////////////////////////////////////////////////////////// const char *MStringList::ReadString(void) // Read a string untill NULL { if(mCurrent==NULL) { return NULL; } const char *retstr=mCurrent->Data; mCurrent=mCurrent->Next; return retstr; } ///////////////////////////////////////////////////////////// bool MStringList::IsMember(const char *string,bool casematch) { if(string==NULL) { return false; } // Search through all items if(casematch==true) { GNode *p; for(p=mFirstNode;p!=NULL;p=p->Next) { if(MStdStrCmp(p->Data,string)==0) { return true; } } } else { GNode *p; for(p=mFirstNode;p!=NULL;p=p->Next) { if(MStdStrICmp(p->Data,string)==0) { return true; } } } return false; } //////////////////////////////////////////////////////////////// int MStringList::GetCount(void) { return mCount; } /////////////////////////////////////////////////////////////// bool MStringList::Remove(const char *string) { if(mFirstNode==NULL) { // List is empty return false; } // Check if first node is the element to remove if(MStdStrCmp(mFirstNode->Data,string)==0) { //=We have found the string in the first node GNode *tmpnode=mFirstNode; mFirstNode=tmpnode->Next; if(mFirstNode==NULL) { mLastNode=mFirstNode; } // Update current node if(mCurrent==tmpnode) { mCurrent=mFirstNode; } // Release memory delete [] tmpnode->Data; delete tmpnode; mCount=mCount-1; return true; } // Remove a node GNode *p; for(p=mFirstNode;p->Next!=NULL;p=p->Next) { if(MStdStrCmp(p->Next->Data,string)==0) { GNode *tmpnode=p->Next; // Link past node p->Next=tmpnode->Next; // Update current node if(mCurrent==tmpnode) { mCurrent=p->Next; } // Update the last node if(mLastNode==tmpnode) { mLastNode=p; } // Release memory delete []tmpnode->Data; delete tmpnode; mCount=mCount-1; return true; } //=Keep Searching in next node } // We have not found the string return false; } //////////////////////////////////////////////////////// bool MStringList::Swap(MStringList &list) { GNode *tmp; tmp=mFirstNode; mFirstNode=list.mFirstNode; list.mFirstNode=tmp; tmp=mLastNode; mLastNode=list.mLastNode; list.mLastNode=tmp; tmp=mCurrent; mCurrent=list.mCurrent; list.mCurrent=tmp; int tmpcount; tmpcount=mCount; mCount=list.mCount; list.mCount=tmpcount; return true; }
bsd-3-clause
hpbader42/Klampt
Interface/RobotPoseGUI.cpp
1
29076
#include "RobotPoseGUI.h" #include <KrisLibrary/GLdraw/drawMesh.h> #include <KrisLibrary/GLdraw/drawgeometry.h> #include <KrisLibrary/geometry/Conversions.h> #include <KrisLibrary/meshing/VolumeGrid.h> #include "Modeling/MultiPath.h" #include <KrisLibrary/robotics/IKFunctions.h> #include "Contact/Utils.h" #include "Planning/RobotCSpace.h" #include "Planning/RobotConstrainedInterpolator.h" #include "Planning/RobotTimeScaling.h" #include "Modeling/MultiPath.h" #include "Modeling/Interpolate.h" #include <sstream> RobotPoseBackend::RobotPoseBackend(RobotWorld* world,ResourceManager* library) : ResourceGUIBackend(world,library),settings("Klampt") { settings["cleanContactsNTol"]= 0.01; settings["pathOptimize"]["contactTol"] = 0.05; settings["pathOptimize"]["outputResolution"] = 0.01; settings["contact"]["forceScale"]= 0.01; settings["contact"]["pointSize"]= 5; settings["contact"]["normalLength"]= 0.05; settings["linkCOMRadius"] = 0.01; settings["flatContactTolerance"] = 0.001; settings["nearbyContactTolerance"] = 0.005; settings["selfCollideColor"][0] = 1; settings["selfCollideColor"][1] = 0; settings["selfCollideColor"][2] = 0; settings["selfCollideColor"][3] = 1; settings["movieWidth"] = 640; settings["hoverColor"][0] = 1; settings["hoverColor"][1] = 1; settings["hoverColor"][2] = 0; settings["hoverColor"][3] = 1; settings["robotColor"][0] = 0.5; settings["robotColor"][1] = 0.5; settings["robotColor"][2] = 0.5; settings["robotColor"][3] = 1; settings["movieHeight"] = 480; settings["envCollideColor"][0] = 1; settings["envCollideColor"][1] = 0.5; settings["envCollideColor"][2] = 0; settings["envCollideColor"][3] = 1; settings["poser"]["color"][0] = 1; settings["poser"]["color"][1] = 1; settings["poser"]["color"][2] = 0; settings["poser"]["color"][3] = 0.5; settings["defaultStanceFriction"] = 0.5; settings["configResourceColor"][0] = 0.5; settings["configResourceColor"][1] = 0.5; settings["configResourceColor"][2] = 0.5; settings["configResourceColor"][3] = 0.25; settings["linkFrameSize"] = 0.2; settings["cleanContactsXTol"] = 0.01; } void RobotPoseBackend::Start() { if(!settings.read("robotpose.settings")) { printf("Didn't read settings from [APPDATA]/robotpose.settings\n"); if(!settings.write("robotpose.settings")) printf("ERROR: couldn't write default settings to [APPDATA]/robotpose.settings\n"); else printf("Wrote default settings to [APPDATA]/robotpose.settings\n"); } WorldGUIBackend::Start(); world->InitCollisions(); robot = world->robots[0]; cur_link=0; cur_driver=0; draw_geom = 1; draw_poser = 1; draw_bbs = 0; draw_com = 0; draw_frame = 0; draw_sensors = 0; robotWidgets.resize(world->robots.size()); for(size_t i=0;i<world->robots.size();i++) { robotWidgets[i].Set(world->robots[i],&world->robotViews[i]); robotWidgets[i].linkPoser.highlightColor.set(0.75,0.75,0); } objectWidgets.resize(world->rigidObjects.size()); for(size_t i=0;i<world->rigidObjects.size();i++) objectWidgets[i].Set(world->rigidObjects[i]); for(size_t i=0;i<world->robots.size();i++) allWidgets.widgets.push_back(&robotWidgets[i]); for(size_t i=0;i<world->rigidObjects.size();i++) allWidgets.widgets.push_back(&objectWidgets[i]); objectWidgets.resize(world->rigidObjects.size()); self_colliding.resize(robot->links.size(),false); env_colliding.resize(robot->links.size(),false); UpdateConfig(); MapButtonToggle("draw_geom",&draw_geom); MapButtonToggle("draw_poser",&draw_poser); MapButtonToggle("draw_bbs",&draw_bbs); MapButtonToggle("draw_com",&draw_com); MapButtonToggle("draw_frame",&draw_frame); MapButtonToggle("draw_sensors",&draw_sensors); } void RobotPoseBackend::UpdateConfig() { for(size_t i=0;i<robotWidgets.size();i++) world->robots[i]->UpdateConfig(robotWidgets[i].Pose()); //update collisions for(size_t i=0;i<robot->links.size();i++) self_colliding[i]=false; robot->UpdateGeometry(); for(size_t i=0;i<robot->links.size();i++) { for(size_t j=i+1;j<robot->links.size();j++) { if(robot->SelfCollision(i,j)) { self_colliding[i]=self_colliding[j]=true; } } } for(size_t i=0;i<robot->links.size();i++) { for(size_t j=i+1;j<robot->links.size();j++) { if(robot->SelfCollision(i,j)) { self_colliding[i]=self_colliding[j]=true; } } } SendCommand("update_config",""); } void RobotPoseBackend::RenderWorld() { Robot* robot = world->robots[0]; ViewRobot& viewRobot = world->robotViews[0]; //want conditional drawing of the robot geometry //ResourceBrowserProgram::RenderWorld(); for(size_t i=0;i<world->terrains.size();i++) world->terrains[i]->DrawGL(); for(size_t i=0;i<world->rigidObjects.size();i++) world->rigidObjects[i]->DrawGL(); if(draw_sensors) { if(robotSensors.sensors.empty()) { robotSensors.MakeDefault(robot); } for(size_t i=0;i<robotSensors.sensors.size();i++) { vector<double> measurements; robotSensors.sensors[i]->DrawGL(*robot,measurements); } } if(draw_geom) { //set the robot colors GLColor robotColor(settings["robotColor"][0],settings["robotColor"][1],settings["robotColor"][2],settings["robotColor"][3]); GLColor highlight(settings["hoverColor"][0],settings["hoverColor"][1],settings["hoverColor"][2],settings["hoverColor"][3]); GLColor selfcolliding(settings["selfCollideColor"][0],settings["selfCollideColor"][1],settings["selfCollideColor"][2],settings["selfCollideColor"][3]); GLColor envcolliding(settings["envCollideColor"][0],settings["envCollideColor"][1],settings["envCollideColor"][2],settings["envCollideColor"][3]); viewRobot.SetColors(robotColor); for(size_t i=0;i<robot->links.size();i++) { if(self_colliding[i]) viewRobot.SetColor(i,selfcolliding); if(env_colliding[i]) viewRobot.SetColor(i,envcolliding); else if((int)i == cur_link) viewRobot.SetColor(i,highlight); } if(draw_poser) allWidgets.DrawGL(viewport); else viewRobot.Draw(); } else { if(draw_frame && draw_poser) { //drawing frames, still should draw poser viewRobot.SetColors(GLColor(0,0,0,0)); allWidgets.DrawGL(viewport); } } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); ResourceGUIBackend::RenderCurResource(); glDisable(GL_BLEND); if(draw_com) { viewRobot.DrawCenterOfMass(); Real comSize = settings["linkCOMRadius"]; for(size_t i=0;i<robot->links.size();i++) viewRobot.DrawLinkCenterOfMass(i,comSize); } if(draw_frame) { viewRobot.DrawLinkFrames(settings["linkFrameSize"]); viewRobot.DrawLinkSkeleton(); glDisable(GL_DEPTH_TEST); glPushMatrix(); glMultMatrix((Matrix4)robot->links[cur_link].T_World); drawCoords(settings["linkFrameSize"]); glPopMatrix(); glEnable(GL_DEPTH_TEST); } //draw bounding boxes if(draw_bbs) { // sim.UpdateModel(); for(size_t i=0;i<world->robots.size();i++) { for(size_t j=0;j<world->robots[i]->geometry.size();j++) { if(world->robots[i]->IsGeometryEmpty(j)) continue; Box3D bbox = world->robots[i]->geometry[j]->GetBB(); Matrix4 basis; bbox.getBasis(basis); glColor3f(1,0,0); drawOrientedWireBox(bbox.dims.x,bbox.dims.y,bbox.dims.z,basis); } } for(size_t i=0;i<world->rigidObjects.size();i++) { Box3D bbox = world->rigidObjects[i]->geometry->GetBB(); Matrix4 basis; bbox.getBasis(basis); glColor3f(1,0,0); drawOrientedWireBox(bbox.dims.x,bbox.dims.y,bbox.dims.z,basis); } for(size_t i=0;i<world->terrains.size();i++) { Box3D bbox = world->terrains[i]->geometry->GetBB(); Matrix4 basis; bbox.getBasis(basis); glColor3f(1,0.5,0); drawOrientedWireBox(bbox.dims.x,bbox.dims.y,bbox.dims.z,basis); } } } Stance RobotPoseBackend::GetFlatStance(Real tolerance) { if(tolerance==0) tolerance = settings["flatContactTolerance"]; Robot* robot = world->robots[0]; Stance s; if(robotWidgets[0].ikPoser.poseGoals.empty()) { printf("Computing stance as though robot were standing on flat ground\n"); ContactFormation cf; GetFlatContacts(*robot,tolerance,cf); Real friction = settings["defaultStanceFriction"]; for(size_t i=0;i<cf.links.size();i++) { //assign default friction for(size_t j=0;j<cf.contacts[i].size();j++) cf.contacts[i][j].kFriction = friction; Hold h; LocalContactsToHold(cf.contacts[i],cf.links[i],*robot,h); s.insert(h); } } else { printf("Computing flat-ground stance only for IK-posed links\n"); for(size_t i=0;i<robotWidgets[0].ikPoser.poseGoals.size();i++) { int link = robotWidgets[0].ikPoser.poseGoals[i].link; vector<ContactPoint> cps; GetFlatContacts(*robot,link,tolerance,cps); if(cps.empty()) continue; Real friction = settings["defaultStanceFriction"]; //assign default friction for(size_t j=0;j<cps.size();j++) cps[j].kFriction = friction; Hold h; LocalContactsToHold(cps,link,*robot,h); h.ikConstraint = robotWidgets[0].ikPoser.poseGoals[i]; s.insert(h); } } return s; } Stance RobotPoseBackend::GetNearbyStance(Real tolerance) { if(tolerance==0) tolerance = settings["nearbyContactTolerance"]; Robot* robot = world->robots[0]; Stance s; if(robotWidgets[0].ikPoser.poseGoals.empty()) { printf("Calculating stance from all points on robot near environment / objects\n"); ContactFormation cf; GetNearbyContacts(*robot,*world,tolerance,cf); Real friction = settings["defaultStanceFriction"]; for(size_t i=0;i<cf.links.size();i++) { //assign default friction for(size_t j=0;j<cf.contacts[i].size();j++) cf.contacts[i][j].kFriction = friction; Hold h; LocalContactsToHold(cf.contacts[i],cf.links[i],*robot,h); s.insert(h); } } else { printf("Calculating near-environment stance only for IK-posed links\n"); for(size_t i=0;i<robotWidgets[0].ikPoser.poseGoals.size();i++) { int link = robotWidgets[0].ikPoser.poseGoals[i].link; vector<ContactPoint> cps; GetNearbyContacts(*robot,link,*world,tolerance,cps); if(cps.empty()) continue; Real friction = settings["defaultStanceFriction"]; //assign default friction for(size_t j=0;j<cps.size();j++) cps[j].kFriction = friction; Hold h; LocalContactsToHold(cps,link,*robot,h); h.ikConstraint = robotWidgets[0].ikPoser.poseGoals[i]; s.insert(h); } } return s; } ResourcePtr RobotPoseBackend::PoserToResource(const string& type) { Robot* robot = world->robots[0]; if(type == "Config") return MakeResource("",robot->q); else if(type == "IKGoal") { int ind = robotWidgets[0].ikPoser.ActiveWidget(); if(ind < 0) { vector<IKGoal>& constraints = robotWidgets[0].Constraints(); if(constraints.size() == 0) { printf("Not hovering over any IK widget\n"); return NULL; } else { return MakeResource("",constraints[0]); } } return MakeResource("",robotWidgets[0].ikPoser.poseGoals[ind]); } else if(type == "Stance") { printf("Creating stance from IK goals and contacts from flat-ground assumption\n"); Stance s = GetFlatStance(); return MakeResource("",s); } else if(type == "Grasp") { int link = 0; cout<<"Which robot link to use? > "; cout.flush(); cin >> link; cin.ignore(256,'\n'); Grasp g; g.constraints.resize(1); g.constraints[0].SetFixedTransform(robot->links[link].T_World); g.constraints[0].link = link; vector<bool> descendant; robot->GetDescendants(link,descendant); for(size_t i=0;i<descendant.size();i++) if(descendant[i]) { g.fixedDofs.push_back(i); g.fixedValues.push_back(robot->q[i]); } ResourcePtr r=ResourceGUIBackend::CurrentResource(); const GeometricPrimitive3DResource* gr = dynamic_cast<const GeometricPrimitive3DResource*>((const ResourceBase*)r); if(gr) { cout<<"Making grasp relative to "<<gr->name<<endl; //TODO: detect contacts RigidTransform T = gr->data.GetFrame(); RigidTransform Tinv; Tinv.setInverse(T); g.Transform(Tinv); } else { const RigidObjectResource* obj = dynamic_cast<const RigidObjectResource*>((const ResourceBase*)r); if(obj) { cout<<"Making grasp relative to "<<obj->name<<endl; //TODO: detect contacts RigidTransform T = obj->object.T; RigidTransform Tinv; Tinv.setInverse(T); g.Transform(Tinv); } } return MakeResource("",g); } else { fprintf(stderr,"Poser does not contain items of the selected type\n"); return NULL; } } void RobotPoseBackend::CleanContacts(Hold& h,Real xtol,Real ntol) { if(xtol==0) xtol = settings["cleanContactsXTol"]; if(ntol==0) ntol = settings["cleanContactsNTol"]; CHContacts(h.contacts,ntol,xtol); } //BUTTON HANDLING METHODS bool RobotPoseBackend::OnCommand(const string& cmd,const string& args) { Robot* robot = world->robots[0]; stringstream ss(args); if(cmd=="pose_mode") { for(size_t i=0;i<robotWidgets.size();i++) robotWidgets[i].SetFixedPoseIKMode(false); } else if(cmd=="constrain_link_mode") { for(size_t i=0;i<robotWidgets.size();i++) robotWidgets[i].SetFixedPoseIKMode(true); } else if(cmd=="constrain_point_mode") { for(size_t i=0;i<robotWidgets.size();i++) robotWidgets[i].SetPoseIKMode(true); } else if(cmd=="delete_constraint_mode") { for(size_t i=0;i<robotWidgets.size();i++) robotWidgets[i].SetDeleteIKMode(true); } else if(cmd == "poser_to_resource") { ResourcePtr r=PoserToResource(args); if(r) { ResourceGUIBackend::Add(r); } } else if(cmd=="constrain_current_point"){ robotWidgets[0].FixCurrentPoint(); } else if(cmd == "delete_current_constraint") { robotWidgets[0].DeleteConstraint(); } else if(cmd=="constrain_current_link") { robotWidgets[0].FixCurrent(); } else if(cmd == "poser_to_resource_overwrite") { ResourcePtr oldr = ResourceGUIBackend::CurrentResource(); if(!oldr) { printf("No resource selected\n"); return true; } ResourcePtr r = PoserToResource(oldr->Type()); if(r) { r->name = oldr->name; r->fileName = oldr->fileName; resources->selected->resource = r; resources->selected->SetChanged(); if(resources->selected->IsExpanded()) { fprintf(stderr,"Warning, don't know how clearing children will be reflected in GUI\n"); resources->selected->ClearExpansion(); } } } else if(cmd == "resource_to_poser") { ResourcePtr r=ResourceGUIBackend::CurrentResource(); const ConfigResource* rc = dynamic_cast<const ConfigResource*>((const ResourceBase*)r); if(rc) { Vector q = robotWidgets[0].Pose(); q=rc->data; if(q.n == robot->q.n) { robotWidgets[0].SetPose(q); /* robotWidgets[0].SetPose(rc->data); robot->NormalizeAngles(robotWidgets[0].linkPoser.poseConfig); if(robotWidgets[0].linkPoser.poseConfig != rc->data) printf("Warning: config in library is not normalized\n"); */ UpdateConfig(); } else { fprintf(stderr,"Can't copy this Config to the poser, it is not the same size\n"); } } else { const IKGoalResource* rc = dynamic_cast<const IKGoalResource*>((const ResourceBase*)r); if(rc) { robotWidgets[0].ikPoser.ClearLink(rc->goal.link); robotWidgets[0].ikPoser.Add(rc->goal); } else { const StanceResource* rc = dynamic_cast<const StanceResource*>((const ResourceBase*)r); if(rc) { robotWidgets[0].ikPoser.poseGoals.clear(); robotWidgets[0].ikPoser.poseWidgets.clear(); for(Stance::const_iterator i=rc->stance.begin();i!=rc->stance.end();i++) { Assert(i->first == i->second.ikConstraint.link); robotWidgets[0].ikPoser.Add(i->second.ikConstraint); } } else { const HoldResource* rc = dynamic_cast<const HoldResource*>((const ResourceBase*)r); if(rc) { robotWidgets[0].ikPoser.ClearLink(rc->hold.link); robotWidgets[0].ikPoser.Add(rc->hold.ikConstraint); } else { const GraspResource* rc = dynamic_cast<const GraspResource*>((const ResourceBase*)r); if(rc) { robotWidgets[0].ikPoser.poseGoals.clear(); robotWidgets[0].ikPoser.poseWidgets.clear(); Stance s; rc->grasp.GetStance(s); for(Stance::const_iterator i=s.begin();i!=s.end();i++) robotWidgets[0].ikPoser.Add(i->second.ikConstraint); } else { const LinearPathResource* rc = dynamic_cast<const LinearPathResource*>((const ResourceBase*)r); if(rc) { Config q; ResourceGUIBackend::viewResource.GetAnimConfig(r,q); robotWidgets[0].SetPose(q); } else { const MultiPathResource* rc = dynamic_cast<const MultiPathResource*>((const ResourceBase*)r); if(rc) { Config q; ResourceGUIBackend::viewResource.GetAnimConfig(r,q); robotWidgets[0].SetPose(q); } } } } } } } } else if(cmd == "create_path") { vector<Real> times; vector<Config> configs,milestones; ResourcePtr r=ResourceGUIBackend::CurrentResource(); const ConfigResource* rc = dynamic_cast<const ConfigResource*>((const ResourceBase*)r); if(rc) { Config a,b; a = rc->data; b = robot->q; if(a.n != b.n) { fprintf(stderr,"Incorrect start and end config size\n"); return true; } milestones.resize(2); milestones[0] = a; milestones[1] = b; times.resize(2); times[0] = 0; times[1] = 1; } else { const ConfigsResource* rc = dynamic_cast<const ConfigsResource*>((const ResourceBase*)r); if(rc) { milestones = rc->configs; times.resize(rc->configs.size()); for(size_t i=0;i<rc->configs.size();i++) times[i] = Real(i)/(rc->configs.size()-1); } else { return true; } } /* if(robotWidgets[0].Constraints().empty()) { //straight line interpolator configs = milestones; } else { Robot* robot=world->robots[0]; Timer timer; if(!InterpolateConstrainedPath(*robot,milestones,robotWidgets[0].Constraints(),configs,1e-2)) return; //int numdivs = (configs.size()-1)*10+1; int numdivs = (configs.size()-1); vector<Real> newtimes; vector<Config> newconfigs; printf("Discretizing at resolution %g\n",1.0/Real(numdivs)); SmoothDiscretizePath(*robot,configs,numdivs,newtimes,newconfigs); cout<<"Smoothed to "<<newconfigs.size()<<" milestones"<<endl; cout<<"Total time "<<timer.ElapsedTime()<<endl; swap(times,newtimes); swap(configs,newconfigs); } ResourceGUIBackend::Add("",times,configs); */ MultiPath path; path.SetMilestones(milestones); path.SetIKProblem(robotWidgets[0].Constraints()); ResourceGUIBackend::Add("",path); ResourceGUIBackend::SetLastActive(); ResourceGUIBackend::viewResource.pathTime = 0; } else if(cmd == "split_path") { ResourcePtr r=ResourceGUIBackend::CurrentResource(); const LinearPathResource* lp = dynamic_cast<const LinearPathResource*>((const ResourceBase*)r); double t = viewResource.pathTime; fprintf(stderr,"TODO: split paths\n"); if(lp) { //ResourceGUIBackend::Add("",newtimes,newconfigs); //ResourceGUIBackend::SetLastActive(); //ResourceGUIBackend::viewResource.pathTime = 0; } const MultiPathResource* mp = dynamic_cast<const MultiPathResource*>((const ResourceBase*)r); if(mp) { //ResourceGUIBackend::Add("",path); //ResourceGUIBackend::SetLastActive(); //ResourceGUIBackend::viewResource.pathTime = 0; } } else if(cmd == "discretize_path") { int num; stringstream ss(args); ss>>num; ResourcePtr r=ResourceGUIBackend::CurrentResource(); const ConfigsResource* cp = dynamic_cast<const ConfigsResource*>((const ResourceBase*)r); if(cp) { for(size_t i=0;i<cp->configs.size();i++) { stringstream ss; ss<<cp->name<<"["<<i+1<<"/"<<cp->configs.size()<<"]"; Add(ss.str(),cp->configs[i]); } ResourceGUIBackend::SetLastActive(); } const LinearPathResource* lp = dynamic_cast<const LinearPathResource*>((const ResourceBase*)r); if(lp) { for(int i=0;i<num;i++) { Real t = Real(lp->times.size()-1)*Real(i+1)/(num+1); int seg = (int)Floor(t); Real u = t - Floor(t); Config q; Assert(seg >= 0 && seg+1 <(int)lp->milestones.size()); Interpolate(*robot,lp->milestones[seg],lp->milestones[seg+1],u,q); stringstream ss; ss<<lp->name<<"["<<i+1<<"/"<<num<<"]"; Add(ss.str(),q); } ResourceGUIBackend::SetLastActive(); } const MultiPathResource* mp = dynamic_cast<const MultiPathResource*>((const ResourceBase*)r); if(mp) { Real minTime = 0, maxTime = 1; if(mp->path.HasTiming()) { minTime = mp->path.sections.front().times.front(); maxTime = mp->path.sections.back().times.back(); } Config q; for(int i=0;i<num;i++) { Real t = minTime + (maxTime - minTime)*Real(i+1)/(num+1); EvaluateMultiPath(*robot,mp->path,t,q); stringstream ss; ss<<mp->name<<"["<<i+1<<"/"<<num<<"]"; Add(ss.str(),q); } ResourceGUIBackend::SetLastActive(); } } else if(cmd == "optimize_path") { ResourcePtr r=ResourceGUIBackend::CurrentResource(); const LinearPathResource* lp = dynamic_cast<const LinearPathResource*>((const ResourceBase*)r); if(lp) { Real dt = settings["pathOptimize"]["outputResolution"]; vector<double> newtimes; vector<Config> newconfigs; if(!TimeOptimizePath(*robot,lp->times,lp->milestones,dt,newtimes,newconfigs)) { fprintf(stderr,"Error optimizing path\n"); return true; } ResourceGUIBackend::Add("",newtimes,newconfigs); ResourceGUIBackend::SetLastActive(); ResourceGUIBackend::viewResource.pathTime = 0; } const MultiPathResource* mp = dynamic_cast<const MultiPathResource*>((const ResourceBase*)r); if(mp) { Real xtol = settings["pathOptimize"]["contactTol"]; Real dt = settings["pathOptimize"]["outputResolution"]; MultiPath path = mp->path; if(!GenerateAndTimeOptimizeMultiPath(*robot,path,xtol,dt)) { fprintf(stderr,"Error optimizing path\n"); return true; } ResourceGUIBackend::Add("",path); ResourceGUIBackend::SetLastActive(); ResourceGUIBackend::viewResource.pathTime = 0; } const ConfigsResource* rc = dynamic_cast<const ConfigsResource*>((const ResourceBase*)r); if(rc) { MultiPath path; path.sections.resize(1); path.sections[0].milestones = rc->configs; path.SetIKProblem(robotWidgets[0].Constraints(),0); Real xtol = settings["pathOptimize"]["contactTol"]; Real dt = settings["pathOptimize"]["outputResolution"]; if(!GenerateAndTimeOptimizeMultiPath(*robot,path,xtol,dt)) { fprintf(stderr,"Error optimizing path\n"); return true; } ResourceGUIBackend::Add("",path); ResourceGUIBackend::SetLastActive(); ResourceGUIBackend::viewResource.pathTime = 0; } } else if(cmd == "store_flat_contacts") { Real tolerance = 0; if(!args.empty()) { stringstream ss(args); ss>>tolerance; } Stance s = GetFlatStance(tolerance); ResourcePtr r = MakeResource("",s); if(r) { ResourceGUIBackend::Add(r); ResourceGUIBackend::SetLastActive(); } } else if(cmd == "get_flat_contacts") { ResourcePtr r=ResourceGUIBackend::CurrentResource(); StanceResource* sp = dynamic_cast<StanceResource*>((ResourceBase*)r); if(sp) { Real tolerance = 0; if(!args.empty()) { stringstream ss(args); ss>>tolerance; } Stance s = GetFlatStance(tolerance); sp->stance = s; } else { printf("Need to be selecting a Stance resource\n"); } } else if(cmd == "get_nearby_contacts") { ResourcePtr r=ResourceGUIBackend::CurrentResource(); StanceResource* sp = dynamic_cast<StanceResource*>((ResourceBase*)r); if(sp) { Real tolerance = 0; if(!args.empty()) { stringstream ss(args); ss>>tolerance; } Stance s = GetNearbyStance(tolerance); sp->stance = s; } else { printf("Need to be selecting a Stance resource\n"); } } else if(cmd == "clean_contacts") { Real xtol,ntol; stringstream ss(args); ss >> xtol >> ntol; if(ss.bad()) xtol = ntol = 0; ResourcePtr r=ResourceGUIBackend::CurrentResource(); const StanceResource* sp = dynamic_cast<const StanceResource*>((const ResourceBase*)r); if(sp) { Stance s=sp->stance; for(Stance::iterator i=s.begin();i!=s.end();i++) CleanContacts(i->second,xtol,ntol); ResourcePtr r = MakeResource(sp->name+"_clean",s); if(r) { ResourceGUIBackend::Add(r); ResourceGUIBackend::SetLastActive(); } } const HoldResource* hp = dynamic_cast<const HoldResource*>((const ResourceBase*)r); if(hp) { Hold h = hp->hold; CleanContacts(h,xtol,ntol); ResourcePtr r = MakeResource(hp->name+"_clean",h); if(r) { ResourceGUIBackend::Add(r); ResourceGUIBackend::SetLastActive(); } } } else if(cmd == "resample") { stringstream ss(args); Real res; ss >> res; ResourcePtr r=ResourceGUIBackend::CurrentResource(); const TriMeshResource* tr = dynamic_cast<const TriMeshResource*>((const ResourceBase*)r); if(tr) { Meshing::VolumeGrid grid; Geometry::CollisionMesh mesh(tr->data); mesh.CalcTriNeighbors(); mesh.InitCollisions(); Geometry::MeshToImplicitSurface_SpaceCarving(mesh,grid,res); //Geometry::MeshToImplicitSurface_FMM(mesh,grid,res); Meshing::TriMesh newMesh; Geometry::ImplicitSurfaceToMesh(grid,newMesh); ResourcePtr r = MakeResource(tr->name+"_simplified",newMesh); if(r) { ResourceGUIBackend::Add(r); ResourceGUIBackend::SetLastActive(); } } } else if(cmd=="constrain_link") { robotWidgets[0].FixCurrent(); } else if(cmd=="constrain_link_point"){ robotWidgets[0].FixCurrentPoint(); } else if(cmd == "delete_constraint") { robotWidgets[0].DeleteConstraint(); } else if(cmd=="set_link") { ss >> cur_link; } else if(cmd=="set_link_value") { double value; ss>>value; Vector q = robotWidgets[0].Pose(); q(cur_link)=value; robotWidgets[0].SetPose(q); } else if(cmd=="set_driver") { ss >> cur_driver; } else if(cmd=="set_driver_value") { double driver_value; ss>>driver_value; Robot* robot = world->robots[0]; robot->UpdateConfig(robotWidgets[0].Pose()); robot->SetDriverValue(cur_driver,driver_value); robotWidgets[0].SetPose(robot->q); } else if(cmd == "undo_pose") { for(size_t i=0;i<world->robots.size();i++) if(lastActiveWidget == &robotWidgets[i]) { printf("Undoing robot poser %d\n",i); robotWidgets[i].Undo(); UpdateConfig(); } } else { return ResourceGUIBackend::OnCommand(cmd,args); } SendRefresh(); return true; } void RobotPoseBackend::BeginDrag(int x,int y,int button,int modifiers) { Robot* robot = world->robots[0]; if(button == GLUT_RIGHT_BUTTON) { double d; if(allWidgets.BeginDrag(x,viewport.h-y,viewport,d)) { allWidgets.SetFocus(true); lastActiveWidget = allWidgets.activeWidget; } else allWidgets.SetFocus(false); if(allWidgets.requestRedraw) { SendRefresh(); allWidgets.requestRedraw=false; } } } void RobotPoseBackend::EndDrag(int x,int y,int button,int modifiers) { if(button == GLUT_RIGHT_BUTTON) { if(allWidgets.hasFocus) { allWidgets.EndDrag(); allWidgets.SetFocus(false); } } } void RobotPoseBackend::DoFreeDrag(int dx,int dy,int button) { if(button == GLUT_LEFT_BUTTON) DragRotate(dx,dy); else if(button == GLUT_RIGHT_BUTTON) { if(allWidgets.hasFocus) { allWidgets.Drag(dx,-dy,viewport); if(allWidgets.requestRedraw) { allWidgets.requestRedraw = false; SendRefresh(); UpdateConfig(); } } } } void RobotPoseBackend::DoPassiveMouseMove(int x, int y) { double d; if(allWidgets.Hover(x,viewport.h-y,viewport,d)) allWidgets.SetHighlight(true); else allWidgets.SetHighlight(false); if(allWidgets.requestRedraw) { SendRefresh(); allWidgets.requestRedraw=false; } } bool RobotPoseBackend::OnButtonPress(const string& button) { if(!GenericBackendBase::OnButtonPress(button)) { cout<<"RobotTestBackend: Unknown button: "<<button<<endl; return false; } return true; } bool RobotPoseBackend::OnButtonToggle(const string& button,int checked) { if(!GenericBackendBase::OnButtonToggle(button,checked)) { cout<<"RobotTestBackend: Unknown button: "<<button<<endl; return false; } return true; }
bsd-3-clause
vaplv/sl
src/sl_wstring.c
1
1566
#define SL_STRING_TYPE SL_STRING_WIDE #include "sl_string.c.def" #undef SL_STRING_TYPE #include "sl_wstring.h" #include <stdlib.h> EXPORT_SYM enum sl_error sl_wstring_insert_cstr(struct sl_wstring* str, size_t id, const char* cstr) { enum sl_error sl_err = SL_NO_ERROR; if(!str || !cstr || id > str->len || IS_MEMORY_OVERLAPPED(str->cstr, str->allocated, cstr, strlen(cstr)+1)) { sl_err = SL_INVALID_ARGUMENT; goto error; } if(id == str->len) { sl_err = sl_wstring_append_cstr(str, cstr); if(sl_err != SL_NO_ERROR) goto error; } else { const size_t len = strlen(cstr); sl_err = ensure_allocated(str, len + str->len + 1, true); if(sl_err != SL_NO_ERROR) goto error; memmove (str->cstr + id + len, str->cstr + id, (str->len - id) * sizeof(wchar_t)); mbstowcs(str->cstr + id, cstr, len); str->len = str->len + len; str->cstr[str->len] = L'\0'; } exit: return sl_err; error: goto exit; } EXPORT_SYM enum sl_error sl_wstring_append_cstr(struct sl_wstring* str, const char* cstr) { enum sl_error sl_err = SL_NO_ERROR; const size_t len = cstr ? strlen(cstr) : 0; if(!str || !cstr || IS_MEMORY_OVERLAPPED(str->cstr, str->allocated, cstr, len + 1)) { sl_err = SL_INVALID_ARGUMENT; goto error; } sl_err = ensure_allocated(str, len + str->len + 1, true); if(sl_err != SL_NO_ERROR) goto error; mbstowcs(str->cstr + str->len, cstr, len); str->len = str->len + len; str->cstr[str->len] = L'\0'; exit: return sl_err; error: goto exit; }
bsd-3-clause
krbeverx/Firmware
src/lib/sensor_calibration/Utilities.cpp
1
5161
/**************************************************************************** * * Copyright (c) 2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <px4_platform_common/px4_config.h> #include <px4_platform_common/log.h> #include <lib/conversion/rotation.h> #include <lib/mathlib/mathlib.h> #include <lib/parameters/param.h> using math::radians; using matrix::Eulerf; using matrix::Dcmf; using matrix::Vector3f; namespace calibration { int8_t FindCalibrationIndex(const char *sensor_type, uint32_t device_id) { if (device_id == 0) { return -1; } for (unsigned i = 0; i < 4; ++i) { char str[20] {}; sprintf(str, "CAL_%s%u_ID", sensor_type, i); int32_t device_id_val = 0; param_t param_handle = param_find_no_notification(str); if (param_handle == PARAM_INVALID) { continue; } // find again and get value, but this time mark it active if (param_get(param_find(str), &device_id_val) != OK) { continue; } if ((uint32_t)device_id_val == device_id) { return i; } } return -1; } int32_t GetCalibrationParam(const char *sensor_type, const char *cal_type, uint8_t instance) { // eg CAL_MAGn_ID/CAL_MAGn_ROT char str[20] {}; sprintf(str, "CAL_%s%u_%s", sensor_type, instance, cal_type); int32_t value = 0; if (param_get(param_find(str), &value) != 0) { PX4_ERR("failed to get %s", str); } return value; } bool SetCalibrationParam(const char *sensor_type, const char *cal_type, uint8_t instance, int32_t value) { char str[20] {}; // eg CAL_MAGn_ID/CAL_MAGn_ROT sprintf(str, "CAL_%s%u_%s", sensor_type, instance, cal_type); int ret = param_set_no_notification(param_find(str), &value); if (ret != PX4_OK) { PX4_ERR("failed to set %s = %d", str, value); } return ret == PX4_OK; } Vector3f GetCalibrationParamsVector3f(const char *sensor_type, const char *cal_type, uint8_t instance) { Vector3f values{0.f, 0.f, 0.f}; char str[20] {}; for (int axis = 0; axis < 3; axis++) { char axis_char = 'X' + axis; // eg CAL_MAGn_{X,Y,Z}OFF sprintf(str, "CAL_%s%u_%c%s", sensor_type, instance, axis_char, cal_type); if (param_get(param_find(str), &values(axis)) != 0) { PX4_ERR("failed to get %s", str); } } return values; } bool SetCalibrationParamsVector3f(const char *sensor_type, const char *cal_type, uint8_t instance, Vector3f values) { int ret = PX4_OK; char str[20] {}; for (int axis = 0; axis < 3; axis++) { char axis_char = 'X' + axis; // eg CAL_MAGn_{X,Y,Z}OFF sprintf(str, "CAL_%s%u_%c%s", sensor_type, instance, axis_char, cal_type); if (param_set_no_notification(param_find(str), &values(axis)) != 0) { PX4_ERR("failed to set %s = %.4f", str, (double)values(axis)); ret = PX4_ERROR; } } return ret == PX4_OK; } Eulerf GetSensorLevelAdjustment() { float x_offset = 0.f; float y_offset = 0.f; float z_offset = 0.f; param_get(param_find("SENS_BOARD_X_OFF"), &x_offset); param_get(param_find("SENS_BOARD_Y_OFF"), &y_offset); param_get(param_find("SENS_BOARD_Z_OFF"), &z_offset); return Eulerf{radians(x_offset), radians(y_offset), radians(z_offset)}; } enum Rotation GetBoardRotation() { // get transformation matrix from sensor/board to body frame int32_t board_rot = -1; param_get(param_find("SENS_BOARD_ROT"), &board_rot); if (board_rot >= 0 && board_rot <= Rotation::ROTATION_MAX) { return static_cast<enum Rotation>(board_rot); } else { PX4_ERR("invalid SENS_BOARD_ROT: %d", board_rot); } return Rotation::ROTATION_NONE; } Dcmf GetBoardRotationMatrix() { return get_rot_matrix(GetBoardRotation()); } } // namespace calibration
bsd-3-clause
jlblancoc/suitesparse-metis-for-windows
SuiteSparse/GraphBLAS/Source/Generated/GB_AxB__plus_plus_uint8.c
1
8219
//------------------------------------------------------------------------------ // GB_AxB: hard-coded C=A*B and C<M>=A*B //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. // If this filename has a double underscore in its name ("__") then it has been // automatically constructed from Generator/GB_AxB.c, via the Source/axb*.m // scripts, and should not be editted. Edit the original source file instead. //------------------------------------------------------------------------------ #include "GB.h" #ifndef GBCOMPACT #include "GB_heap.h" #include "GB_AxB__semirings.h" // The C=A*B semiring is defined by the following types and operators: // A*B function (Gustavon): GB_AgusB__plus_plus_uint8 // A'*B function (dot): GB_AdotB__plus_plus_uint8 // A*B function (heap): GB_AheapB__plus_plus_uint8 // Z type: uint8_t (the type of C) // X type: uint8_t (the type of x for z=mult(x,y)) // Y type: uint8_t (the type of y for z=mult(x,y)) // handle flipxy: 0 (0 if mult(x,y) is commutative, 1 otherwise) // Identity: 0 (where cij += identity does not change cij) // Multiply: z = x + y // Add: cij += z #define GB_XTYPE \ uint8_t #define GB_YTYPE \ uint8_t #define GB_HANDLE_FLIPXY \ 0 #define GB_MULTOP(z,x,y) \ z = x + y //------------------------------------------------------------------------------ // C<M>=A*B and C=A*B: gather/scatter saxpy-based method (Gustavson) //------------------------------------------------------------------------------ #define GB_IDENTITY \ 0 // x [i] = y #define GB_COPY_SCALAR_TO_ARRAY(x,i,y,s) \ x [i] = y ; // x = y [i] #define GB_COPY_ARRAY_TO_SCALAR(x,y,i,s) \ GB_btype x = y [i] ; // x [i] = y [i] #define GB_COPY_ARRAY_TO_ARRAY(x,i,y,j,s) \ x [i] = y [j] ; // mult-add operation (no mask) #define GB_MULTADD_NOMASK \ { \ /* Sauna_Work [i] += A(i,k) * B(k,j) */ \ GB_atype aik = Ax [pA] ; \ uint8_t t ; \ GB_MULTIPLY (t, aik, bkj) ; \ Sauna_Work [i] += t ; \ } // mult-add operation (with mask) #define GB_MULTADD_WITH_MASK \ { \ /* Sauna_Work [i] += A(i,k) * B(k,j) */ \ GB_atype aik = Ax [pA] ; \ uint8_t t ; \ GB_MULTIPLY (t, aik, bkj) ; \ if (mark == hiwater) \ { \ /* first time C(i,j) seen */ \ Sauna_Mark [i] = hiwater + 1 ; \ Sauna_Work [i] = t ; \ } \ else \ { \ /* C(i,j) seen before, update it */ \ Sauna_Work [i] += t ; \ } \ } GrB_Info GB_AgusB__plus_plus_uint8 ( GrB_Matrix C, const GrB_Matrix M, const GrB_Matrix A, const GrB_Matrix B, bool flipxy, // if true, A and B have been swapped GB_Sauna Sauna, // sparse accumulator GB_Context Context ) { uint8_t *restrict Sauna_Work = Sauna->Sauna_Work ; // size C->vlen*zsize uint8_t *restrict Cx = C->x ; GrB_Info info = GrB_SUCCESS ; #include "GB_AxB_Gustavson_flipxy.c" return (info) ; } //------------------------------------------------------------------------------ // C<M>=A'*B or C=A'*B: dot product //------------------------------------------------------------------------------ // get A(k,i) #define GB_DOT_GETA(pA) \ GB_atype aki = Ax [pA] ; // get B(k,j) #define GB_DOT_GETB(pB) \ GB_btype bkj = Bx [pB] ; // t = aki*bkj #define GB_DOT_MULT(bkj) \ uint8_t t ; \ GB_MULTIPLY (t, aki, bkj) ; // cij += t #define GB_DOT_ADD \ cij += t ; // cij = t #define GB_DOT_COPY \ cij = t ; // cij is not a pointer but a scalar; nothing to do #define GB_DOT_REACQUIRE ; // clear cij #define GB_DOT_CLEAR \ cij = 0 ; // save the value of C(i,j) #define GB_DOT_SAVE \ Cx [cnz] = cij ; #define GB_DOT_WORK_TYPE \ GB_btype #define GB_DOT_WORK(k) Work [k] // Work [k] = Bx [pB] #define GB_DOT_SCATTER \ Work [k] = Bx [pB] ; GrB_Info GB_AdotB__plus_plus_uint8 ( GrB_Matrix *Chandle, const GrB_Matrix M, const GrB_Matrix A, const GrB_Matrix B, bool flipxy, // if true, A and B have been swapped GB_Context Context ) { GrB_Matrix C = (*Chandle) ; uint8_t *restrict Cx = C->x ; uint8_t cij ; GrB_Info info = GrB_SUCCESS ; size_t bkj_size = B->type->size ; // no typecasting here #include "GB_AxB_dot_flipxy.c" return (info) ; } //------------------------------------------------------------------------------ // C<M>=A*B and C=A*B: heap saxpy-based method //------------------------------------------------------------------------------ #define GB_CIJ_GETB(pB) \ GB_btype bkj = Bx [pB] ; // C(i,j) = A(i,k) * bkj #define GB_CIJ_MULT(pA) \ { \ GB_atype aik = Ax [pA] ; \ GB_MULTIPLY (cij, aik, bkj) ; \ } // C(i,j) += A(i,k) * B(k,j) #define GB_CIJ_MULTADD(pA,pB) \ { \ GB_atype aik = Ax [pA] ; \ GB_btype bkj = Bx [pB] ; \ uint8_t t ; \ GB_MULTIPLY (t, aik, bkj) ; \ cij += t ; \ } // cij is not a pointer but a scalar; nothing to do #define GB_CIJ_REACQUIRE ; // cij = identity #define GB_CIJ_CLEAR \ cij = 0 ; // save the value of C(i,j) #define GB_CIJ_SAVE \ Cx [cnz] = cij ; GrB_Info GB_AheapB__plus_plus_uint8 ( GrB_Matrix *Chandle, const GrB_Matrix M, const GrB_Matrix A, const GrB_Matrix B, bool flipxy, // if true, A and B have been swapped int64_t *restrict List, GB_pointer_pair *restrict pA_pair, GB_Element *restrict Heap, const int64_t bjnz_max, GB_Context Context ) { GrB_Matrix C = (*Chandle) ; uint8_t *restrict Cx = C->x ; uint8_t cij ; int64_t cvlen = C->vlen ; GrB_Info info = GrB_SUCCESS ; GB_CIJ_CLEAR ; #include "GB_AxB_heap_flipxy.c" return (info) ; } //------------------------------------------------------------------------------ // clear macro definitions //------------------------------------------------------------------------------ #undef GB_XTYPE #undef GB_YTYPE #undef GB_HANDLE_FLIPXY #undef GB_MULTOP #undef GB_IDENTITY #undef GB_COPY_SCALAR_TO_ARRAY #undef GB_COPY_ARRAY_TO_SCALAR #undef GB_COPY_ARRAY_TO_ARRAY #undef GB_MULTADD_NOMASK #undef GB_MULTADD_WITH_MASK #undef GB_DOT_GETA #undef GB_DOT_GETB #undef GB_DOT_MULT #undef GB_DOT_ADD #undef GB_DOT_COPY #undef GB_DOT_REACQUIRE #undef GB_DOT_CLEAR #undef GB_DOT_SAVE #undef GB_DOT_WORK_TYPE #undef GB_DOT_WORK #undef GB_DOT_SCATTER #undef GB_CIJ_GETB #undef GB_CIJ_MULT #undef GB_CIJ_MULTADD #undef GB_CIJ_REACQUIRE #undef GB_CIJ_CLEAR #undef GB_CIJ_SAVE #undef GB_MULTIPLY #endif
bsd-3-clause
xianyi/OpenBLAS
lapack-netlib/SRC/cspcon.c
1
20496
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; /* > \brief \b CSPCON */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download CSPCON + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cspcon. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cspcon. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cspcon. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE CSPCON( UPLO, N, AP, IPIV, ANORM, RCOND, WORK, INFO ) */ /* CHARACTER UPLO */ /* INTEGER INFO, N */ /* REAL ANORM, RCOND */ /* INTEGER IPIV( * ) */ /* COMPLEX AP( * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CSPCON estimates the reciprocal of the condition number (in the */ /* > 1-norm) of a complex symmetric packed matrix A using the */ /* > factorization A = U*D*U**T or A = L*D*L**T computed by CSPTRF. */ /* > */ /* > An estimate is obtained for norm(inv(A)), and the reciprocal of the */ /* > condition number is computed as RCOND = 1 / (ANORM * norm(inv(A))). */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > Specifies whether the details of the factorization are stored */ /* > as an upper or lower triangular matrix. */ /* > = 'U': Upper triangular, form is A = U*D*U**T; */ /* > = 'L': Lower triangular, form is A = L*D*L**T. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] AP */ /* > \verbatim */ /* > AP is COMPLEX array, dimension (N*(N+1)/2) */ /* > The block diagonal matrix D and the multipliers used to */ /* > obtain the factor U or L as computed by CSPTRF, stored as a */ /* > packed triangular matrix. */ /* > \endverbatim */ /* > */ /* > \param[in] IPIV */ /* > \verbatim */ /* > IPIV is INTEGER array, dimension (N) */ /* > Details of the interchanges and the block structure of D */ /* > as determined by CSPTRF. */ /* > \endverbatim */ /* > */ /* > \param[in] ANORM */ /* > \verbatim */ /* > ANORM is REAL */ /* > The 1-norm of the original matrix A. */ /* > \endverbatim */ /* > */ /* > \param[out] RCOND */ /* > \verbatim */ /* > RCOND is REAL */ /* > The reciprocal of the condition number of the matrix A, */ /* > computed as RCOND = 1/(ANORM * AINVNM), where AINVNM is an */ /* > estimate of the 1-norm of inv(A) computed in this routine. */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is COMPLEX array, dimension (2*N) */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complexOTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int cspcon_(char *uplo, integer *n, complex *ap, integer * ipiv, real *anorm, real *rcond, complex *work, integer *info) { /* System generated locals */ integer i__1, i__2; /* Local variables */ integer kase, i__; extern logical lsame_(char *, char *); integer isave[3]; logical upper; extern /* Subroutine */ int clacn2_(integer *, complex *, complex *, real *, integer *, integer *); integer ip; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); real ainvnm; extern /* Subroutine */ int csptrs_(char *, integer *, integer *, complex *, integer *, complex *, integer *, integer *); /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --work; --ipiv; --ap; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*anorm < 0.f) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CSPCON", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ *rcond = 0.f; if (*n == 0) { *rcond = 1.f; return 0; } else if (*anorm <= 0.f) { return 0; } /* Check that the diagonal matrix D is nonsingular. */ if (upper) { /* Upper triangular storage: examine D from bottom to top */ ip = *n * (*n + 1) / 2; for (i__ = *n; i__ >= 1; --i__) { i__1 = ip; if (ipiv[i__] > 0 && (ap[i__1].r == 0.f && ap[i__1].i == 0.f)) { return 0; } ip -= i__; /* L10: */ } } else { /* Lower triangular storage: examine D from top to bottom. */ ip = 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ip; if (ipiv[i__] > 0 && (ap[i__2].r == 0.f && ap[i__2].i == 0.f)) { return 0; } ip = ip + *n - i__ + 1; /* L20: */ } } /* Estimate the 1-norm of the inverse. */ kase = 0; L30: clacn2_(n, &work[*n + 1], &work[1], &ainvnm, &kase, isave); if (kase != 0) { /* Multiply by inv(L*D*L**T) or inv(U*D*U**T). */ csptrs_(uplo, n, &c__1, &ap[1], &ipiv[1], &work[1], n, info); goto L30; } /* Compute the estimate of the reciprocal condition number. */ if (ainvnm != 0.f) { *rcond = 1.f / ainvnm / *anorm; } return 0; /* End of CSPCON */ } /* cspcon_ */
bsd-3-clause
maxhutch/magma
src/zgehrd_m.cpp
1
10897
/* -- MAGMA (version 2.1.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date August 2016 @precisions normal z -> s d c @author Mark Gates */ #include "magma_internal.h" /***************************************************************************//** Purpose ------- ZGEHRD reduces a COMPLEX_16 general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: Q' * A * Q = H . This version stores the triangular matrices used in the factorization so that they can be applied directly (i.e., without being recomputed) later. As a result, the application of Q is much faster. Arguments --------- @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in] ilo INTEGER @param[in] ihi INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to ZGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. @param[in,out] A COMPLEX_16 array, dimension (LDA,N) On entry, the N-by-N general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. @param[in] lda INTEGER The leading dimension of the array A. LDA >= max(1,N). @param[out] tau COMPLEX_16 array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to zero. @param[out] work (workspace) COMPLEX_16 array, dimension (LWORK) On exit, if INFO = 0, WORK[0] returns the optimal LWORK. @param[in] lwork INTEGER The length of the array WORK. LWORK >= N*NB. where NB is the optimal blocksize. \n If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. @param[out] T COMPLEX_16 array, dimension NB*N, where NB is the optimal blocksize. It stores the NB*NB blocks of the triangular T matrices used in the reduction. @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value. Further Details --------------- The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: @verbatim on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) @endverbatim where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). This implementation follows the hybrid algorithm and notations described in S. Tomov and J. Dongarra, "Accelerating the reduction to upper Hessenberg form through hybrid GPU-based computing," University of Tennessee Computer Science Technical Report, UT-CS-09-642 (also LAPACK Working Note 219), May 24, 2009. This version stores the T matrices, for later use in magma_zunghr. @ingroup magma_gehrd *******************************************************************************/ extern "C" magma_int_t magma_zgehrd_m( magma_int_t n, magma_int_t ilo, magma_int_t ihi, magmaDoubleComplex *A, magma_int_t lda, magmaDoubleComplex *tau, magmaDoubleComplex *work, magma_int_t lwork, magmaDoubleComplex *T, magma_int_t *info) { #define A( i, j ) (A + (i) + (j)*lda) #define dA( dev, i, j ) (data.dA[dev] + (i) + (j)*ldda) magmaDoubleComplex c_one = MAGMA_Z_ONE; magmaDoubleComplex c_zero = MAGMA_Z_ZERO; magma_int_t nb = magma_get_zgehrd_nb(n); magma_int_t nh, iws, ldda, min_lblocks, max_lblocks, last_dev, dev; magma_int_t dpanel, di, nlocal, i, i2, ib, ldwork; magma_int_t iinfo; magma_int_t lquery; struct zgehrd_data data; magma_int_t ngpu = magma_num_gpus(); *info = 0; iws = n*(nb + nb*ngpu); work[0] = magma_zmake_lwork( iws ); lquery = (lwork == -1); if (n < 0) { *info = -1; } else if (ilo < 1 || ilo > max(1,n)) { *info = -2; } else if (ihi < min(ilo,n) || ihi > n) { *info = -3; } else if (lda < max(1,n)) { *info = -5; } else if (lwork < iws && ! lquery) { *info = -8; } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } else if (lquery) return *info; // Adjust from 1-based indexing ilo -= 1; // Quick return if possible nh = ihi - ilo; if (nh <= 1) { work[0] = c_one; return *info; } magma_device_t orig_dev; magma_getdevice( &orig_dev ); // Set elements 0:ILO-1 and IHI-1:N-2 of TAU to zero for (i = 0; i < ilo; ++i) tau[i] = c_zero; for (i = max(0,ihi-1); i < n-1; ++i) tau[i] = c_zero; // set T to zero lapackf77_zlaset( "Full", &nb, &n, &c_zero, &c_zero, T, &nb ); // set to null, to simplify cleanup code for( dev = 0; dev < ngpu; ++dev ) { data.dA[dev] = NULL; data.queues[dev] = NULL; } // Now requires lwork >= iws; else dT won't be computed in unblocked code. // If not enough workspace, use unblocked code //if ( lwork < iws ) { // nb = 1; //} if (nb == 1 || nb >= nh) { // Use unblocked code below i = ilo; } else { // Use blocked code // allocate memory on GPUs for A and workspaces ldda = magma_roundup( n, 32 ); min_lblocks = (n / nb) / ngpu; max_lblocks = ((n-1) / nb) / ngpu + 1; last_dev = (n / nb) % ngpu; // V and Vd need to be padded for copying in mzlahr2 data.ngpu = ngpu; data.ldda = ldda; data.ldv = nb*max_lblocks*ngpu; data.ldvd = nb*max_lblocks; for( dev = 0; dev < ngpu; ++dev ) { magma_setdevice( dev ); nlocal = min_lblocks*nb; if ( dev < last_dev ) { nlocal += nb; } else if ( dev == last_dev ) { nlocal += (n % nb); } ldwork = nlocal*ldda // A + nb*data.ldv // V + nb*data.ldvd // Vd + nb*ldda // Y + nb*ldda // W + nb*nb; // Ti if ( MAGMA_SUCCESS != magma_zmalloc( &data.dA[dev], ldwork )) { *info = MAGMA_ERR_DEVICE_ALLOC; goto CLEANUP; } data.dV [dev] = data.dA [dev] + nlocal*ldda; data.dVd[dev] = data.dV [dev] + nb*data.ldv; data.dY [dev] = data.dVd[dev] + nb*data.ldvd; data.dW [dev] = data.dY [dev] + nb*ldda; data.dTi[dev] = data.dW [dev] + nb*ldda; magma_queue_create( dev, &data.queues[dev] ); } // Copy the matrix to GPUs magma_zsetmatrix_1D_col_bcyclic( ngpu, n, n, nb, A, lda, data.dA, ldda, data.queues ); // round ilo down to block boundary ilo = (ilo/nb)*nb; for (i = ilo; i < ihi - 1 - nb; i += nb) { // Reduce columns i:i+nb-1 to Hessenberg form, returning the // matrices V and T of the block reflector H = I - V*T*V' // which performs the reduction, and also the matrix Y = A*V*T // Get the current panel (no need for the 1st iteration) dpanel = (i / nb) % ngpu; di = ((i / nb) / ngpu) * nb; if ( i > ilo ) { magma_setdevice( dpanel ); magma_zgetmatrix( ihi-i, nb, dA(dpanel, i, di), ldda, A(i,i), lda, data.queues[dpanel] ); } // add 1 to i for 1-based index magma_zlahr2_m( ihi, i+1, nb, A(0,i), lda, &tau[i], &T[i*nb], nb, work, n, &data ); magma_zlahru_m( n, ihi, i, nb, A, lda, &data ); // copy first i rows above panel to host magma_setdevice( dpanel ); magma_zgetmatrix_async( i, nb, dA(dpanel, 0, di), ldda, A(0,i), lda, data.queues[dpanel] ); } // Copy remainder to host, block-by-block for( i2 = i; i2 < n; i2 += nb ) { ib = min( nb, n-i2 ); dev = (i2 / nb) % ngpu; di = (i2 / nb) / ngpu * nb; magma_setdevice( dev ); magma_zgetmatrix( n, ib, dA(dev, 0, di), ldda, A(0,i2), lda, data.queues[dev] ); } } // Use unblocked code to reduce the rest of the matrix // add 1 to i for 1-based index i += 1; lapackf77_zgehd2(&n, &i, &ihi, A, &lda, tau, work, &iinfo); work[0] = magma_zmake_lwork( iws ); CLEANUP: for( dev = 0; dev < ngpu; ++dev ) { magma_setdevice( dev ); magma_free( data.dA[dev] ); magma_queue_destroy( data.queues[dev] ); } magma_setdevice( orig_dev ); return *info; } /* magma_zgehrd */
bsd-3-clause
guiquanz/lockfree
ptst.c
1
3346
/****************************************************************************** * ptst.c * * Per-thread state management. Essentially the state management parts * of MB's garbage-collection code have been pulled out and placed here, * for the use of other utility routines. * * Copyright (c) 2002-2003, K A Fraser * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "portable_defns.h" #include "ptst.h" pthread_key_t ptst_key; ptst_t *ptst_list; static unsigned int next_id; ptst_t *critical_enter(void) { ptst_t *ptst, *next, *new_next; unsigned int id, oid; ptst = (ptst_t *)pthread_getspecific(ptst_key); if ( ptst == NULL ) { for ( ptst = ptst_first(); ptst != NULL; ptst = ptst_next(ptst) ) { if ( (ptst->count == 0) && (CASIO(&ptst->count, 0, 1) == 0) ) { break; } } if ( ptst == NULL ) { ptst = ALIGNED_ALLOC(sizeof(*ptst)); if ( ptst == NULL ) exit(1); memset(ptst, 0, sizeof(*ptst)); ptst->gc = gc_init(); rand_init(ptst); ptst->count = 1; id = next_id; while ( (oid = CASIO(&next_id, id, id+1)) != id ) id = oid; ptst->id = id; new_next = ptst_list; do { ptst->next = next = new_next; WMB_NEAR_CAS(); } while ( (new_next = CASPO(&ptst_list, next, ptst)) != next ); } pthread_setspecific(ptst_key, ptst); } gc_enter(ptst); return(ptst); } static void ptst_destructor(ptst_t *ptst) { ptst->count = 0; } void _init_ptst_subsystem(void) { ptst_list = NULL; next_id = 0; WMB(); if ( pthread_key_create(&ptst_key, (void (*)(void *))ptst_destructor) ) { exit(1); } }
bsd-3-clause
GaloisInc/hacrypto
src/C/libssl/HEAD/src/crypto/ec/ec_pmeth.c
1
8188
/* $OpenBSD: ec_pmeth.c,v 1.5 2014/06/12 15:49:29 deraadt Exp $ */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2006. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include "evp_locl.h" /* EC pkey context structure */ typedef struct { /* Key and paramgen group */ EC_GROUP *gen_group; /* message digest */ const EVP_MD *md; } EC_PKEY_CTX; static int pkey_ec_init(EVP_PKEY_CTX * ctx) { EC_PKEY_CTX *dctx; dctx = malloc(sizeof(EC_PKEY_CTX)); if (!dctx) return 0; dctx->gen_group = NULL; dctx->md = NULL; ctx->data = dctx; return 1; } static int pkey_ec_copy(EVP_PKEY_CTX * dst, EVP_PKEY_CTX * src) { EC_PKEY_CTX *dctx, *sctx; if (!pkey_ec_init(dst)) return 0; sctx = src->data; dctx = dst->data; if (sctx->gen_group) { dctx->gen_group = EC_GROUP_dup(sctx->gen_group); if (!dctx->gen_group) return 0; } dctx->md = sctx->md; return 1; } static void pkey_ec_cleanup(EVP_PKEY_CTX * ctx) { EC_PKEY_CTX *dctx = ctx->data; if (dctx) { if (dctx->gen_group) EC_GROUP_free(dctx->gen_group); free(dctx); } } static int pkey_ec_sign(EVP_PKEY_CTX * ctx, unsigned char *sig, size_t * siglen, const unsigned char *tbs, size_t tbslen) { int ret, type; unsigned int sltmp; EC_PKEY_CTX *dctx = ctx->data; EC_KEY *ec = ctx->pkey->pkey.ec; if (!sig) { *siglen = ECDSA_size(ec); return 1; } else if (*siglen < (size_t) ECDSA_size(ec)) { ECerr(EC_F_PKEY_EC_SIGN, EC_R_BUFFER_TOO_SMALL); return 0; } if (dctx->md) type = EVP_MD_type(dctx->md); else type = NID_sha1; ret = ECDSA_sign(type, tbs, tbslen, sig, &sltmp, ec); if (ret <= 0) return ret; *siglen = (size_t) sltmp; return 1; } static int pkey_ec_verify(EVP_PKEY_CTX * ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen) { int ret, type; EC_PKEY_CTX *dctx = ctx->data; EC_KEY *ec = ctx->pkey->pkey.ec; if (dctx->md) type = EVP_MD_type(dctx->md); else type = NID_sha1; ret = ECDSA_verify(type, tbs, tbslen, sig, siglen, ec); return ret; } static int pkey_ec_derive(EVP_PKEY_CTX * ctx, unsigned char *key, size_t * keylen) { int ret; size_t outlen; const EC_POINT *pubkey = NULL; if (!ctx->pkey || !ctx->peerkey) { ECerr(EC_F_PKEY_EC_DERIVE, EC_R_KEYS_NOT_SET); return 0; } if (!key) { const EC_GROUP *group; group = EC_KEY_get0_group(ctx->pkey->pkey.ec); *keylen = (EC_GROUP_get_degree(group) + 7) / 8; return 1; } pubkey = EC_KEY_get0_public_key(ctx->peerkey->pkey.ec); /* * NB: unlike PKCS#3 DH, if *outlen is less than maximum size this is * not an error, the result is truncated. */ outlen = *keylen; ret = ECDH_compute_key(key, outlen, pubkey, ctx->pkey->pkey.ec, 0); if (ret < 0) return ret; *keylen = ret; return 1; } static int pkey_ec_ctrl(EVP_PKEY_CTX * ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = ctx->data; EC_GROUP *group; switch (type) { case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID: group = EC_GROUP_new_by_curve_name(p1); if (group == NULL) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_CURVE); return 0; } if (dctx->gen_group) EC_GROUP_free(dctx->gen_group); dctx->gen_group = group; return 1; case EVP_PKEY_CTRL_MD: if (EVP_MD_type((const EVP_MD *) p2) != NID_sha1 && EVP_MD_type((const EVP_MD *) p2) != NID_ecdsa_with_SHA1 && EVP_MD_type((const EVP_MD *) p2) != NID_sha224 && EVP_MD_type((const EVP_MD *) p2) != NID_sha256 && EVP_MD_type((const EVP_MD *) p2) != NID_sha384 && EVP_MD_type((const EVP_MD *) p2) != NID_sha512) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ case EVP_PKEY_CTRL_DIGESTINIT: case EVP_PKEY_CTRL_PKCS7_SIGN: case EVP_PKEY_CTRL_CMS_SIGN: return 1; default: return -2; } } static int pkey_ec_ctrl_str(EVP_PKEY_CTX * ctx, const char *type, const char *value) { if (!strcmp(type, "ec_paramgen_curve")) { int nid; nid = OBJ_sn2nid(value); if (nid == NID_undef) nid = OBJ_ln2nid(value); if (nid == NID_undef) { ECerr(EC_F_PKEY_EC_CTRL_STR, EC_R_INVALID_CURVE); return 0; } return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid); } return -2; } static int pkey_ec_paramgen(EVP_PKEY_CTX * ctx, EVP_PKEY * pkey) { EC_KEY *ec = NULL; EC_PKEY_CTX *dctx = ctx->data; int ret = 0; if (dctx->gen_group == NULL) { ECerr(EC_F_PKEY_EC_PARAMGEN, EC_R_NO_PARAMETERS_SET); return 0; } ec = EC_KEY_new(); if (!ec) return 0; ret = EC_KEY_set_group(ec, dctx->gen_group); if (ret) EVP_PKEY_assign_EC_KEY(pkey, ec); else EC_KEY_free(ec); return ret; } static int pkey_ec_keygen(EVP_PKEY_CTX * ctx, EVP_PKEY * pkey) { EC_KEY *ec = NULL; if (ctx->pkey == NULL) { ECerr(EC_F_PKEY_EC_KEYGEN, EC_R_NO_PARAMETERS_SET); return 0; } ec = EC_KEY_new(); if (!ec) return 0; EVP_PKEY_assign_EC_KEY(pkey, ec); /* Note: if error return, pkey is freed by parent routine */ if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return EC_KEY_generate_key(pkey->pkey.ec); } const EVP_PKEY_METHOD ec_pkey_meth = { .pkey_id = EVP_PKEY_EC, .init = pkey_ec_init, .copy = pkey_ec_copy, .cleanup = pkey_ec_cleanup, .paramgen = pkey_ec_paramgen, .keygen = pkey_ec_keygen, .sign = pkey_ec_sign, .verify = pkey_ec_verify, .derive = pkey_ec_derive, .ctrl = pkey_ec_ctrl, .ctrl_str = pkey_ec_ctrl_str };
bsd-3-clause
snowyu/libtorrent
src/string_util.cpp
1
7262
/* Copyright (c) 2012-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/string_util.hpp" #include "libtorrent/random.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/parse_url.hpp" #include "libtorrent/aux_/disable_warnings_push.hpp" #include <boost/tuple/tuple.hpp> #include <cstdlib> // for malloc #include <cstring> // for memmov/strcpy/strlen #include "libtorrent/aux_/disable_warnings_pop.hpp" namespace libtorrent { // lexical_cast's result depends on the locale. We need // a well defined result boost::array<char, 4 + std::numeric_limits<boost::int64_t>::digits10> to_string(boost::int64_t n) { boost::array<char, 4 + std::numeric_limits<boost::int64_t>::digits10> ret; char *p = &ret.back(); *p = '\0'; boost::uint64_t un = n; // TODO: warning C4146: unary minus operator applied to unsigned type, // result still unsigned if (n < 0) un = -un; do { *--p = '0' + un % 10; un /= 10; } while (un); if (n < 0) *--p = '-'; std::memmove(&ret[0], p, &ret.back() - p + 1); return ret; } bool is_alpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } bool is_print(char c) { return c >= 32 && c < 127; } bool is_space(char c) { static const char* ws = " \t\n\r\f\v"; return strchr(ws, c) != 0; } char to_lower(char c) { return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; } int split_string(char const** tags, int buf_size, char* in) { int ret = 0; char* i = in; for (;*i; ++i) { if (!is_print(*i) || is_space(*i)) { *i = 0; if (ret == buf_size) return ret; continue; } if (i == in || i[-1] == 0) { tags[ret++] = i; } } return ret; } bool string_begins_no_case(char const* s1, char const* s2) { while (*s1 != 0) { if (to_lower(*s1) != to_lower(*s2)) return false; ++s1; ++s2; } return true; } bool string_equal_no_case(char const* s1, char const* s2) { while (to_lower(*s1) == to_lower(*s2)) { if (*s1 == 0) return true; ++s1; ++s2; } return false; } // generate a url-safe random string void url_random(char* begin, char* end) { // http-accepted characters: // excluding ', since some buggy trackers don't support that static char const printable[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz-_.!~*()"; // the random number while (begin != end) *begin++ = printable[random() % (sizeof(printable)-1)]; } char* allocate_string_copy(char const* str) { if (str == 0) return 0; char* tmp = (char*)std::malloc(std::strlen(str) + 1); if (tmp == 0) return 0; std::strcpy(tmp, str); return tmp; } // 8-byte align pointer void* align_pointer(void* p) { int offset = uintptr_t(p) & 0x7; // if we're already aligned, don't do anything if (offset == 0) return p; // offset is how far passed the last aligned address // we are. We need to go forward to the next aligned // one. Since aligned addresses are 8 bytes apart, add // 8 - offset. return static_cast<char*>(p) + (8 - offset); } // this parses the string that's used as the liste_interfaces setting. // it is a comma-separated list of IP or device names with ports. For // example: "eth0:6881,eth1:6881" or "127.0.0.1:6881" void parse_comma_separated_string_port(std::string const& in , std::vector<std::pair<std::string, int> >& out) { out.clear(); std::string::size_type start = 0; std::string::size_type end = 0; while (start < in.size()) { // skip leading spaces while (start < in.size() && is_space(in[start])) ++start; end = in.find_first_of(',', start); if (end == std::string::npos) end = in.size(); std::string::size_type colon = in.find_last_of(':', end); if (colon != std::string::npos && colon > start) { int port = atoi(in.substr(colon + 1, end - colon - 1).c_str()); // skip trailing spaces std::string::size_type soft_end = colon; while (soft_end > start && is_space(in[soft_end-1])) --soft_end; // in case this is an IPv6 address, strip off the square brackets // to make it more easily parseable into an ip::address if (in[start] == '[') ++start; if (soft_end > start && in[soft_end-1] == ']') --soft_end; out.push_back(std::make_pair(in.substr(start, soft_end - start), port)); } start = end + 1; } } void parse_comma_separated_string(std::string const& in, std::vector<std::string>& out) { out.clear(); std::string::size_type start = 0; std::string::size_type end = 0; while (start < in.size()) { // skip leading spaces while (start < in.size() && is_space(in[start])) ++start; end = in.find_first_of(',', start); if (end == std::string::npos) end = in.size(); // skip trailing spaces std::string::size_type soft_end = end; while (soft_end > start && is_space(in[soft_end-1])) --soft_end; out.push_back(in.substr(start, soft_end - start)); start = end + 1; } } char* string_tokenize(char* last, char sep, char** next) { if (last == 0) return 0; if (last[0] == '"') { *next = strchr(last + 1, '"'); // consume the actual separator as well. if (*next != NULL) *next = strchr(*next, sep); } else { *next = strchr(last, sep); } if (*next == 0) return last; **next = 0; ++(*next); while (**next == sep && **next) ++(*next); return last; } #if TORRENT_USE_I2P bool is_i2p_url(std::string const& url) { using boost::tuples::ignore; std::string hostname; error_code ec; boost::tie(ignore, ignore, hostname, ignore, ignore) = parse_url_components(url, ec); char const* top_domain = strrchr(hostname.c_str(), '.'); return top_domain && strcmp(top_domain, ".i2p") == 0; } #endif }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE190_Integer_Overflow/s07/CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02.c
1
4750
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02.c Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-02.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: increment * GoodSink: Ensure there will not be an overflow before incrementing data * BadSink : Increment data, which can cause an overflow * Flow Variant: 02 Control flow: if(1) and if(0) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02_bad() { unsigned int data; data = 0; if(1) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(1) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; unsigned int result = data; printUnsignedLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second 1 to 0 */ static void goodB2G1() { unsigned int data; data = 0; if(1) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an overflow from occurring */ if (data < UINT_MAX) { ++data; unsigned int result = data; printUnsignedLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { unsigned int data; data = 0; if(1) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(1) { /* FIX: Add a check to prevent an overflow from occurring */ if (data < UINT_MAX) { ++data; unsigned int result = data; printUnsignedLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first 1 to 0 */ static void goodG2B1() { unsigned int data; data = 0; if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; } if(1) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; unsigned int result = data; printUnsignedLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { unsigned int data; data = 0; if(1) { /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; } if(1) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; unsigned int result = data; printUnsignedLine(result); } } } void CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__unsigned_int_fscanf_preinc_02_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
huard/scipy-work
scipy/sparse/linalg/dsolve/SuperLU/SRC/dgssv.c
2
8499
/* * -- SuperLU routine (version 3.0) -- * Univ. of California Berkeley, Xerox Palo Alto Research Center, * and Lawrence Berkeley National Lab. * October 15, 2003 * */ #include "dsp_defs.h" void dgssv(superlu_options_t *options, SuperMatrix *A, int *perm_c, int *perm_r, SuperMatrix *L, SuperMatrix *U, SuperMatrix *B, SuperLUStat_t *stat, int *info ) { /* * Purpose * ======= * * DGSSV solves the system of linear equations A*X=B, using the * LU factorization from DGSTRF. It performs the following steps: * * 1. If A is stored column-wise (A->Stype = SLU_NC): * * 1.1. Permute the columns of A, forming A*Pc, where Pc * is a permutation matrix. For more details of this step, * see sp_preorder.c. * * 1.2. Factor A as Pr*A*Pc=L*U with the permutation Pr determined * by Gaussian elimination with partial pivoting. * L is unit lower triangular with offdiagonal entries * bounded by 1 in magnitude, and U is upper triangular. * * 1.3. Solve the system of equations A*X=B using the factored * form of A. * * 2. If A is stored row-wise (A->Stype = SLU_NR), apply the * above algorithm to the transpose of A: * * 2.1. Permute columns of transpose(A) (rows of A), * forming transpose(A)*Pc, where Pc is a permutation matrix. * For more details of this step, see sp_preorder.c. * * 2.2. Factor A as Pr*transpose(A)*Pc=L*U with the permutation Pr * determined by Gaussian elimination with partial pivoting. * L is unit lower triangular with offdiagonal entries * bounded by 1 in magnitude, and U is upper triangular. * * 2.3. Solve the system of equations A*X=B using the factored * form of A. * * See supermatrix.h for the definition of 'SuperMatrix' structure. * * Arguments * ========= * * options (input) superlu_options_t* * The structure defines the input parameters to control * how the LU decomposition will be performed and how the * system will be solved. * * A (input) SuperMatrix* * Matrix A in A*X=B, of dimension (A->nrow, A->ncol). The number * of linear equations is A->nrow. Currently, the type of A can be: * Stype = SLU_NC or SLU_NR; Dtype = SLU_D; Mtype = SLU_GE. * In the future, more general A may be handled. * * perm_c (input/output) int* * If A->Stype = SLU_NC, column permutation vector of size A->ncol * which defines the permutation matrix Pc; perm_c[i] = j means * column i of A is in position j in A*Pc. * If A->Stype = SLU_NR, column permutation vector of size A->nrow * which describes permutation of columns of transpose(A) * (rows of A) as described above. * * If options->ColPerm = MY_PERMC or options->Fact = SamePattern or * options->Fact = SamePattern_SameRowPerm, it is an input argument. * On exit, perm_c may be overwritten by the product of the input * perm_c and a permutation that postorders the elimination tree * of Pc'*A'*A*Pc; perm_c is not changed if the elimination tree * is already in postorder. * Otherwise, it is an output argument. * * perm_r (input/output) int* * If A->Stype = SLU_NC, row permutation vector of size A->nrow, * which defines the permutation matrix Pr, and is determined * by partial pivoting. perm_r[i] = j means row i of A is in * position j in Pr*A. * If A->Stype = SLU_NR, permutation vector of size A->ncol, which * determines permutation of rows of transpose(A) * (columns of A) as described above. * * If options->RowPerm = MY_PERMR or * options->Fact = SamePattern_SameRowPerm, perm_r is an * input argument. * otherwise it is an output argument. * * L (output) SuperMatrix* * The factor L from the factorization * Pr*A*Pc=L*U (if A->Stype = SLU_NC) or * Pr*transpose(A)*Pc=L*U (if A->Stype = SLU_NR). * Uses compressed row subscripts storage for supernodes, i.e., * L has types: Stype = SLU_SC, Dtype = SLU_D, Mtype = SLU_TRLU. * * U (output) SuperMatrix* * The factor U from the factorization * Pr*A*Pc=L*U (if A->Stype = SLU_NC) or * Pr*transpose(A)*Pc=L*U (if A->Stype = SLU_NR). * Uses column-wise storage scheme, i.e., U has types: * Stype = SLU_NC, Dtype = SLU_D, Mtype = SLU_TRU. * * B (input/output) SuperMatrix* * B has types: Stype = SLU_DN, Dtype = SLU_D, Mtype = SLU_GE. * On entry, the right hand side matrix. * On exit, the solution matrix if info = 0; * * stat (output) SuperLUStat_t* * Record the statistics on runtime and floating-point operation count. * See util.h for the definition of 'SuperLUStat_t'. * * info (output) int* * = 0: successful exit * > 0: if info = i, and i is * <= A->ncol: U(i,i) is exactly zero. The factorization has * been completed, but the factor U is exactly singular, * so the solution could not be computed. * > A->ncol: number of bytes allocated when memory allocation * failure occurred, plus A->ncol. * */ DNformat *Bstore; SuperMatrix *AA;/* A in SLU_NC format used by the factorization routine.*/ SuperMatrix AC; /* Matrix postmultiplied by Pc */ int lwork = 0, *etree, i; /* Set default values for some parameters */ double drop_tol = 0.; int panel_size; /* panel size */ int relax; /* no of columns in a relaxed snodes */ int permc_spec; trans_t trans = NOTRANS; double *utime; double t; /* Temporary time */ /* Test the input parameters ... */ *info = 0; Bstore = B->Store; if ( options->Fact != DOFACT ) *info = -1; else if ( A->nrow != A->ncol || A->nrow < 0 || (A->Stype != SLU_NC && A->Stype != SLU_NR) || A->Dtype != SLU_D || A->Mtype != SLU_GE ) *info = -2; else if ( B->ncol < 0 || Bstore->lda < SUPERLU_MAX(0, A->nrow) || B->Stype != SLU_DN || B->Dtype != SLU_D || B->Mtype != SLU_GE ) *info = -7; if ( *info != 0 ) { i = -(*info); xerbla_("dgssv", &i); return; } utime = stat->utime; /* Convert A to SLU_NC format when necessary. */ if ( A->Stype == SLU_NR ) { NRformat *Astore = A->Store; AA = (SuperMatrix *) SUPERLU_MALLOC( sizeof(SuperMatrix) ); dCreate_CompCol_Matrix(AA, A->ncol, A->nrow, Astore->nnz, Astore->nzval, Astore->colind, Astore->rowptr, SLU_NC, A->Dtype, A->Mtype); trans = TRANS; } else { if ( A->Stype == SLU_NC ) AA = A; } t = SuperLU_timer_(); /* * Get column permutation vector perm_c[], according to permc_spec: * permc_spec = NATURAL: natural ordering * permc_spec = MMD_AT_PLUS_A: minimum degree on structure of A'+A * permc_spec = MMD_ATA: minimum degree on structure of A'*A * permc_spec = COLAMD: approximate minimum degree column ordering * permc_spec = MY_PERMC: the ordering already supplied in perm_c[] */ permc_spec = options->ColPerm; if ( permc_spec != MY_PERMC && options->Fact == DOFACT ) get_perm_c(permc_spec, AA, perm_c); utime[COLPERM] = SuperLU_timer_() - t; etree = intMalloc(A->ncol); t = SuperLU_timer_(); sp_preorder(options, AA, perm_c, etree, &AC); utime[ETREE] = SuperLU_timer_() - t; panel_size = sp_ienv(1); relax = sp_ienv(2); /*printf("Factor PA = LU ... relax %d\tw %d\tmaxsuper %d\trowblk %d\n", relax, panel_size, sp_ienv(3), sp_ienv(4));*/ t = SuperLU_timer_(); /* Compute the LU factorization of A. */ dgstrf(options, &AC, drop_tol, relax, panel_size, etree, NULL, lwork, perm_c, perm_r, L, U, stat, info); utime[FACT] = SuperLU_timer_() - t; t = SuperLU_timer_(); if ( *info == 0 ) { /* Solve the system A*X=B, overwriting B with X. */ dgstrs (trans, L, U, perm_c, perm_r, B, stat, info); } utime[SOLVE] = SuperLU_timer_() - t; SUPERLU_FREE (etree); Destroy_CompCol_Permuted(&AC); if ( A->Stype == SLU_NR ) { Destroy_SuperMatrix_Store(AA); SUPERLU_FREE(AA); } }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE319_Cleartext_Tx_Sensitive_Info/CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02.c
2
19516
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02.c Label Definition File: CWE319_Cleartext_Tx_Sensitive_Info__w32.label.xml Template File: sources-sinks-02.tmpl.c */ /* * @description * CWE: 319 Cleartext Transmission of Sensitive Information * BadSource: connect_socket Read the password using a connect socket (client side) * GoodSource: Use a hardcoded password (one that was not sent over the network) * Sinks: * GoodSink: Decrypt the password before using it in an authentication API call to show that it was transferred as ciphertext * BadSink : Use the password directly from the source in an authentication API call to show that it was transferred as plaintext * Flow Variant: 02 Control flow: if(1) and if(0) * * */ #include "std_testcase.h" #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #pragma comment(lib, "advapi32.lib") #define HASH_INPUT "ABCDEFG123456" /* INCIDENTAL: Hardcoded crypto */ #ifndef OMITBAD void CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02_bad() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(1) { { WSADATA wsaData; int wsaDataInit = 0; int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t passwordLen = wcslen(password); do { if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* POTENTIAL FLAW: Reading sensitive data from the network */ recvResult = recv(connectSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(wchar_t), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ password[passwordLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(password, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(password, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { closesocket(connectSocket); } if (wsaDataInit) { WSACleanup(); } } } if(1) { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Use the password in LogonUser() to establish that it is "sensitive" */ /* POTENTIAL FLAW: Using sensitive information that was possibly sent in plaintext over the network */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second 1 to 0 */ static void goodB2G1() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(1) { { WSADATA wsaData; int wsaDataInit = 0; int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t passwordLen = wcslen(password); do { if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* POTENTIAL FLAW: Reading sensitive data from the network */ recvResult = recv(connectSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(wchar_t), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ password[passwordLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(password, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(password, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { closesocket(connectSocket); } if (wsaDataInit) { WSACleanup(); } } } if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), password); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(password, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* FIX: Decrypt the password */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into password and NUL-terminate */ memcpy(password, payload, payloadBytes); password[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(1) { { WSADATA wsaData; int wsaDataInit = 0; int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t passwordLen = wcslen(password); do { if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* POTENTIAL FLAW: Reading sensitive data from the network */ recvResult = recv(connectSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(wchar_t), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ password[passwordLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(password, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(password, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { closesocket(connectSocket); } if (wsaDataInit) { WSACleanup(); } } } if(1) { { HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), password); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(password, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* FIX: Decrypt the password */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into password and NUL-terminate */ memcpy(password, payload, payloadBytes); password[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } } /* goodG2B1() - use goodsource and badsink by changing the first 1 to 0 */ static void goodG2B1() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a hardcoded password (it was not sent over the network) * INCIDENTAL FLAW: CWE-259 Hard Coded Password */ wcscpy(password, L"Password1234!"); } if(1) { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Use the password in LogonUser() to establish that it is "sensitive" */ /* POTENTIAL FLAW: Using sensitive information that was possibly sent in plaintext over the network */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(1) { /* FIX: Use a hardcoded password (it was not sent over the network) * INCIDENTAL FLAW: CWE-259 Hard Coded Password */ wcscpy(password, L"Password1234!"); } if(1) { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Use the password in LogonUser() to establish that it is "sensitive" */ /* POTENTIAL FLAW: Using sensitive information that was possibly sent in plaintext over the network */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } } void CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_02_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE415_Double_Free/s02/CWE415_Double_Free__new_delete_array_wchar_t_84_bad.cpp
2
1334
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_array_wchar_t_84_bad.cpp Label Definition File: CWE415_Double_Free__new_delete_array.label.xml Template File: sources-sinks-84_bad.tmpl.cpp */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE415_Double_Free__new_delete_array_wchar_t_84.h" namespace CWE415_Double_Free__new_delete_array_wchar_t_84 { CWE415_Double_Free__new_delete_array_wchar_t_84_bad::CWE415_Double_Free__new_delete_array_wchar_t_84_bad(wchar_t * dataCopy) { data = dataCopy; data = new wchar_t[100]; /* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */ delete [] data; } CWE415_Double_Free__new_delete_array_wchar_t_84_bad::~CWE415_Double_Free__new_delete_array_wchar_t_84_bad() { /* POTENTIAL FLAW: Possibly deleting memory twice */ delete [] data; } } #endif /* OMITBAD */
bsd-3-clause
chock-mostlyharmless/mostlyharmless
spirits_of_the_sea/i4k_OGL/src/_windows/main_rel.cpp
2
2131
//--------------------------------------------------------------------------// // iq / rgba . tiny codes . 2008 // //--------------------------------------------------------------------------// #define WIN32_LEAN_AND_MEAN #define WIN32_EXTRA_LEAN #include <windows.h> #include <mmsystem.h> #include "../intro.h" #include "../config.h" static const PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; #ifdef SETRESOLUTION #pragma data_seg(".screenSettings") static DEVMODE screenSettings = { {0}, #if _MSC_VER < 1400 0,0,148,0,0x001c0000,{0},0,0,0,0,0,0,0,0,0,{0},0,32,XRES,YRES,0,0, // Visual C++ 6.0 #else 0,0,156,0,0x001c0000,{0},0,0,0,0,0,{0},0,32,XRES,YRES,{0}, 0, // Visuatl Studio 2005 #endif #if(WINVER >= 0x0400) 0,0,0,0,0,0, #if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400) 0,0 #endif #endif }; #endif void entrypoint( void ) { // full screen #ifdef SETRESOLUTION if( ChangeDisplaySettings(&screenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) return; ShowCursor( 0 ); #endif // create window HWND hWnd = CreateWindow( "static",0,WS_POPUP|WS_VISIBLE|WS_MAXIMIZE,0,0,0,0,0,0,0,0); HDC hDC = GetDC(hWnd); // initalize opengl if( !SetPixelFormat(hDC,ChoosePixelFormat(hDC,&pfd),&pfd) ) return; HGLRC hRC = wglCreateContext(hDC); wglMakeCurrent(hDC,hRC); // init intro intro_init(); long t; long to = timeGetTime(); do { //ShowCursor(false); t = timeGetTime(); //if( !to ) to=t; t = t-to;//-150; intro_do( t ); //SwapBuffers ( hDC ); wglSwapLayerBuffers( hDC, WGL_SWAP_MAIN_PLANE ); }while ( !GetAsyncKeyState(VK_ESCAPE) ); sndPlaySound(0,0); ExitProcess(0); }
bsd-3-clause