repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE194_Unexpected_Sign_Extension/s01/CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34.c | 2 | 3583 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-34.tmpl.c
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Positive integer
* Sinks: memcpy
* BadSink : Copy strings using memcpy() with the length of data
* Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function)
*
* */
#include "std_testcase.h"
typedef union
{
short unionFirst;
short unionSecond;
} CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_unionType;
#ifndef OMITBAD
void CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_bad()
{
short data;
CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_unionType myUnion;
/* Initialize data */
data = 0;
/* FLAW: Use a value input from the console using fscanf() */
fscanf (stdin, "%hd", &data);
myUnion.unionFirst = data;
{
short data = myUnion.unionSecond;
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
memcpy(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
short data;
CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_unionType myUnion;
/* Initialize data */
data = 0;
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
myUnion.unionFirst = data;
{
short data = myUnion.unionSecond;
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
memcpy(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
}
void CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_good()
{
goodG2B();
}
#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()...");
CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE194_Unexpected_Sign_Extension__fscanf_memcpy_34_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
habanero-rice/hclib | test/performance-regression/full-apps/qmcpack/src/QMCDrivers/Experimental/EE/EEFactory.cpp | 2 | 1734 | //////////////////////////////////////////////////////////////////
// (c) Copyright 2003- by Jeongnim Kim
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Jeongnim Kim
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: jnkim@ncsa.uiuc.edu
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
#include "QMCDrivers/EE/EEFactory.h"
#include "QMCDrivers/EE/VMCRenyiOMP.h"
#include "QMCDrivers/EE/VMCMultiRenyiOMP.h"
#include "Message/OpenMP.h"
namespace qmcplusplus
{
QMCDriver* EEFactory::create(MCWalkerConfiguration& w, TrialWaveFunction& psi,
QMCHamiltonian& h, ParticleSetPool& ptclpool, HamiltonianPool& hpool, WaveFunctionPool& ppool)
{
int np=omp_get_max_threads();
//(SPACEWARP_MODE,MULTIPE_MODE,UPDATE_MODE)
QMCDriver* qmc=0;
if(VMCMode == 0 || VMCMode == 1) //(0,0,0) (0,0,1)
{
qmc = new VMCRenyiOMP(w,psi,h,hpool,ppool);
}
else
if(VMCMode == 2 || VMCMode == 3) //(0,1,0) (0,1,1)
{
qmc = new VMCMultiRenyiOMP(w,psi,h,hpool,ppool);
}
qmc->setUpdateMode(VMCMode&1);
return qmc;
}
}
/***************************************************************************
* $RCSfile: DMCFactory.cpp,v $ $Author: jnkim $
* $Revision: 1.3 $ $Date: 2006/04/05 00:49:59 $
* $Id: DMCFactory.cpp,v 1.3 2006/04/05 00:49:59 jnkim Exp $
***************************************************************************/
| bsd-3-clause |
Pballer/prayer | mod_fcgid-2.3.7/modules/fcgid/fcgid_filter.c | 3 | 3397 | /*
* 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 "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "fcgid_filter.h"
#include "fcgid_bucket.h"
#include "fcgid_conf.h"
apr_status_t fcgid_filter(ap_filter_t * f, apr_bucket_brigade * bb)
{
apr_status_t rv;
apr_bucket_brigade *tmp_brigade;
int save_size = 0;
conn_rec *c = f->c;
server_rec *s = f->r->server;
fcgid_server_conf *sconf = ap_get_module_config(s->module_config,
&fcgid_module);
tmp_brigade =
apr_brigade_create(f->r->pool, f->r->connection->bucket_alloc);
while (!APR_BRIGADE_EMPTY(bb)) {
apr_size_t readlen;
const char *buffer;
apr_bucket *e = APR_BRIGADE_FIRST(bb);
if (APR_BUCKET_IS_EOS(e))
break;
if (APR_BUCKET_IS_METADATA(e)) {
apr_bucket_delete(e);
continue;
}
/* Read the bucket now */
if ((rv = apr_bucket_read(e, &buffer, &readlen,
APR_BLOCK_READ)) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, rv, f->r,
"mod_fcgid: can't read data from fcgid handler");
return rv;
}
/* Move on to next bucket if it's fastcgi header bucket */
if (e->type == &ap_bucket_type_fcgid_header
|| (e->type == &apr_bucket_type_immortal && readlen == 0)) {
apr_bucket_delete(e);
continue;
}
save_size += readlen;
/* Cache it to tmp_brigade */
APR_BUCKET_REMOVE(e);
APR_BRIGADE_INSERT_TAIL(tmp_brigade, e);
/* I will pass tmp_brigade to next filter if I have got too much buckets */
if (save_size > sconf->output_buffersize) {
APR_BRIGADE_INSERT_TAIL(tmp_brigade,
apr_bucket_flush_create(f->r->
connection->
bucket_alloc));
if ((rv =
ap_pass_brigade(f->next, tmp_brigade)) != APR_SUCCESS)
return rv;
/* Is the client aborted? */
if (c && c->aborted)
return APR_SUCCESS;
save_size = 0;
}
}
/* Any thing left? */
if (!APR_BRIGADE_EMPTY(tmp_brigade)) {
if ((rv = ap_pass_brigade(f->next, tmp_brigade)) != APR_SUCCESS)
return rv;
}
/* This filter is done once it has served up its content */
ap_remove_output_filter(f);
return APR_SUCCESS;
}
| bsd-3-clause |
srekcah/infer | infer/tests/codetoanalyze/c/errors/null_dereference/null_pointer_dereference.c | 3 | 2400 | /*
* Copyright (c) 2015 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <stdlib.h>
struct Person {
int age;
int height;
int weight;
};
int simple_null_pointer() {
struct Person *max = 0;
return max->age;
}
struct Person *Person_create(int age, int height, int weight) {
struct Person *who = 0;
return who;
}
int get_age(struct Person *who) {
return who->age;
}
int null_pointer_interproc() {
struct Person *joe = Person_create(32, 64, 140);
return get_age(joe);
}
int negation_in_conditional() {
int *x = 0;
if (!x) return 0;
else return *x; // this never happens
}
int * foo() {
return 0;
}
void null_pointer_with_function_pointer() {
int * (*fp)();
fp = foo;
int *x = fp();
*x = 3;
}
void use_exit (struct Person *htbl) {
if (!htbl)
exit(0);
int x = htbl->age;
}
void basic_null_dereference() {
int *p = NULL;
*p = 42; // NULL dereference
}
void no_check_for_null_after_malloc() {
int *p;
p = (int*) malloc(sizeof(int));
*p = 42; // NULL dereference
free(p);
}
void no_check_for_null_after_realloc() {
int *p;
p = (int*) malloc(sizeof(int) * 5);
if (p) {
p[3] = 42;
}
int *q = (int*) realloc(p, sizeof(int) * 10);
if (!q)
free(p);
q[7] = 0; // NULL dereference
free(q);
}
void assign(int *p, int n) {
*p = n;
}
void potentially_null_pointer_passed_as_argument() {
int *p = NULL;
p = (int*) malloc(sizeof(int));
assign(p, 42); // NULL dereference
free(p);
}
void null_passed_as_argument() {
assign(NULL, 42); // NULL dereference
}
void allocated_pointer_passed_as_argument() {
int *p = NULL;
p = (int*) malloc(sizeof(int));
if (p) {
assign(p, 42);
free(p);
}
}
int* unsafe_allocate() {
int *p = NULL;
p = (int*) malloc(sizeof(int));
return p;
}
int* safe_allocate() {
int *p = NULL;
while (!p) {
p = (int*) malloc(sizeof(int));
}
return p;
}
void function_call_can_return_null_pointer() {
int *p = NULL;
p = unsafe_allocate();
assign(p, 42); // NULL dereference
free(p);
}
void function_call_returns_allocated_pointer() {
int *p = NULL;
p = safe_allocate();
assign(p, 42);
free(p);
}
| bsd-3-clause |
shaotuanchen/sunflower_exp | tools/source/newlib-1.9.0/newlib/libc/time/asctime.c | 3 | 1217 | /*
* asctime.c
* Original Author: G. Haley
*
* Converts the broken down time in the structure pointed to by tim_p into a
* string of the form
*
* Wed Jun 15 11:38:07 1988\n\0
*
* Returns a pointer to the string.
*/
/*
FUNCTION
<<asctime>>---format time as string
INDEX
asctime
INDEX
_asctime_r
ANSI_SYNOPSIS
#include <time.h>
char *asctime(const struct tm *<[clock]>);
char *asctime_r(const struct tm *<[clock]>, char *<[buf]>);
TRAD_SYNOPSIS
#include <time.h>
char *asctime(<[clock]>)
struct tm *<[clock]>;
char *asctime_r(<[clock]>)
struct tm *<[clock]>;
char *<[buf]>;
DESCRIPTION
Format the time value at <[clock]> into a string of the form
. Wed Jun 15 11:38:07 1988\n\0
The string is generated in a static buffer; each call to <<asctime>>
overwrites the string generated by previous calls.
RETURNS
A pointer to the string containing a formatted timestamp.
PORTABILITY
ANSI C requires <<asctime>>.
<<asctime>> requires no supporting OS subroutines.
*/
#include <time.h>
#include <_ansi.h>
#include <reent.h>
#ifndef _REENT_ONLY
char *
_DEFUN (asctime, (tim_p),
_CONST struct tm *tim_p)
{
char *buf = _REENT->_new._reent._asctime_buf;
return asctime_r (tim_p, buf);
}
#endif
| bsd-3-clause |
Multi2Sim/m2s-bench-parsec-3.0-src | facesim/TaskQ/lib/taskQDistCommon.c | 5 | 10496 | /*
* Implements dynamic task queues to provide load balancing
* Sanjeev Kumar --- December, 2004
*/
#include <time.h>
#include "config.h"
#ifdef ENABLE_PTHREADS
#include "alamere.h"
pthread_t _M4_threadsTable[MAX_THREADS];
int _M4_threadsTableAllocated[MAX_THREADS];
pthread_mutexattr_t _M4_normalMutexAttr;
#endif //ENABLE_PTHREADS
#include "taskQInternal.h"
#include "taskQList.h"
static volatile long numThreads, numTaskQs, threadsPerTaskQ, maxTasks;
static volatile int nextQ = 0; // Just a hint. Not protected by locks.
static volatile int parallelRegion = 0;
static volatile int noMoreTasks = 0;
#if defined( TASKQ_DIST_GRID)
#include "taskQDistGrid.h"
#elif defined( TASKQ_DIST_LIST)
#include "taskQDistList.h"
#elif defined( TASKQ_DIST_FIXED)
#include "taskQDistFixed.h"
#else
#error "Missing Definition"
#endif
typedef struct {
#ifdef ENABLE_PTHREADS
pthread_mutex_t lock;
#endif //ENABLE_PTHREADS
long statEnqueued, statLocal, *statStolen;
char padding1[CACHE_LINE_SIZE];
TaskQDetails q;
char padding2[CACHE_LINE_SIZE];
} TaskQ;
typedef struct {
#ifdef ENABLE_PTHREADS
pthread_mutex_t lock;
pthread_cond_t taskAvail;
pthread_cond_t tasksDone;
#endif //ENABLE_PTHREADS
volatile long threadCount;
} Sync;
TaskQ *taskQs;
Sync sync;
#define MAX_STEAL 8
static inline int calculateNumSteal( int available) {
int half = ( available == 1) ? 1 : available/2;
return ( half > MAX_STEAL) ? MAX_STEAL : half;
}
#if defined( TASKQ_DIST_GRID)
#include "taskQDistGrid.c"
#elif defined( TASKQ_DIST_LIST)
#include "taskQDistList.c"
#elif defined( TASKQ_DIST_FIXED)
#include "taskQDistFixed.c"
#else
#error "Missing Definition"
#endif
static void waitForTasks( void) {
TRACE;
#ifdef ENABLE_PTHREADS
pthread_mutex_lock(&(sync.lock));;
sync.threadCount++;
if ( sync.threadCount == numThreads)
pthread_cond_broadcast(&sync.tasksDone);;
pthread_cond_wait(&sync.taskAvail,&sync.lock); pthread_mutex_unlock(&sync.lock);;
#else
sync.threadCount++;
#endif //ENABLE_PTHREADS
TRACE;
}
static void signalTasks( void) {
TRACE;
if ( sync.threadCount == 0) return; // Unsafe
#ifdef ENABLE_PTHREADS
pthread_mutex_lock(&(sync.lock));;
sync.threadCount = 0;
pthread_cond_broadcast(&sync.taskAvail);;
pthread_cond_broadcast(&sync.tasksDone);;
pthread_mutex_unlock(&(sync.lock));;
#else
sync.threadCount = 0;
#endif //ENABLE_PTHREADS
TRACE;
}
static int waitForEnd( void) {
int done;
TRACE;
#ifdef ENABLE_PTHREADS
pthread_mutex_lock(&(sync.lock));;
sync.threadCount++;
if ( sync.threadCount != numThreads)
pthread_cond_wait(&sync.tasksDone,&sync.lock);;
done = (sync.threadCount == numThreads);
pthread_mutex_unlock(&(sync.lock));;
#else
sync.threadCount++;
done = (sync.threadCount == numThreads);
#endif //ENABLE_PTHREADS
TRACE;
return done;
}
static int doOwnTasks( long myThreadId, long myQ) {
void *task[NUM_FIELDS];
int executed = 0;
TRACE;
while ( getATaskFromHead( &taskQs[myQ], task)) {
( ( TaskQTask3)task[0])( myThreadId, task[1], task[2], task[3]);
executed = 1;
}
TRACE;
return executed;
}
static int stealTasks( long myThreadId, long myQ) {
int i, stolen = 0;
TRACE;
i = myQ + 1;
while ( 1 ) {
if ( i == numTaskQs) i = 0;
if ( i == myQ) break;
stolen = stealTasksSpecialized( &taskQs[myQ], &taskQs[i]);
if( stolen) {
IF_STATS( {
#ifdef ENABLE_PTHREADS
pthread_mutex_lock(&(taskQs[myQ].lock));;
taskQs[myQ].statStolen[i] += stolen;
pthread_mutex_unlock(&(taskQs[myQ].lock));;
#else
taskQs[myQ].statStolen[i] += stolen;
#endif //ENABLE_PTHREADS
});
break;
} else {
i++;
}
}
TRACE;
return stolen;
}
static void *taskQIdleLoop( void *arg) {
long index = ( long)arg;
long myQ = index / threadsPerTaskQ;
int i = 0;
int stolen;
while ( 1 ) {
waitForTasks();
if ( noMoreTasks) return 0;
doOwnTasks( index, myQ);
while ( 1) {
stolen = stealTasks( index, myQ);
if ( stolen)
doOwnTasks( index, myQ);
else
break;
}
i++;
}
}
void taskQInit( int numOfThreads, int maxNumOfTasks) {
int i;
#ifdef ENABLE_PTHREADS
ALAMERE_INIT(numOfThreads);
ALAMERE_AFTER_CHECKPOINT();
pthread_mutexattr_init( &_M4_normalMutexAttr);
pthread_mutexattr_settype( &_M4_normalMutexAttr, PTHREAD_MUTEX_NORMAL);
{
int _M4_i;
for ( _M4_i = 0; _M4_i < MAX_THREADS; _M4_i++) {
_M4_threadsTableAllocated[_M4_i] = 0;
}
}
#endif //ENABLE_PTHREADS
;
maxTasks = maxNumOfTasks;
numThreads = numOfThreads;
threadsPerTaskQ = taskQGetParam( TaskQThreadsPerQueue);
DEBUG_ASSERT( ( numThreads >= 1) && ( threadsPerTaskQ >= 1));
numTaskQs = (numOfThreads+threadsPerTaskQ-1)/threadsPerTaskQ;
/*
printf( "\n\n\t##### Running TaskQ version Distributed %-15s with %ld threads and %ld queues #####\n",
VERSION, numThreads, numTaskQs);
printf( "\t##### \t\t\t\t\t\t[ built on %s at %s ] #####\n\n", __DATE__, __TIME__);
printf( "\t\t TaskQ mutex address : %ld\n", ( long)&sync.lock);
printf( "\t\t TaskQ condition variable 1 address : %ld\n", ( long)&sync.taskAvail);
printf( "\t\t TaskQ condition variable 2 address : %ld\n", ( long)&sync.tasksDone);
printf( "\n\n");
*/
DEBUG_ANNOUNCE;
taskQs = ( TaskQ *)malloc( sizeof( TaskQ) * numTaskQs);
for ( i = 0; i < numTaskQs; i++) {
#ifdef ENABLE_PTHREADS
pthread_mutex_init(&(taskQs[i].lock), NULL);;
#endif //ENABLE_PTHREADS
taskQs[i].statStolen = ( long *)malloc( sizeof(long) * numTaskQs);
initTaskQDetails( &taskQs[i]);
}
taskQResetStats();
#ifdef ENABLE_PTHREADS
pthread_mutex_init(&(sync.lock), NULL);;
pthread_cond_init(&sync.taskAvail,NULL);;
pthread_cond_init(&sync.tasksDone,NULL);;
#endif //ENABLE_PTHREADS
sync.threadCount = 0;
#ifdef ENABLE_PTHREADS
for ( i = 1; i < numThreads; i++)
{
int _M4_i;
for ( _M4_i = 0; _M4_i < MAX_THREADS; _M4_i++) {
if ( _M4_threadsTableAllocated[_M4_i] == 0) break;
}
pthread_create(&_M4_threadsTable[_M4_i],NULL,(void *(*)(void *))taskQIdleLoop,(void *)( long)i);
_M4_threadsTableAllocated[_M4_i] = 1;
}
#endif //ENABLE_PTHREADS
;
waitForEnd();
}
static inline int pickQueue( int threadId) { // Needs work
if ( parallelRegion) return threadId/threadsPerTaskQ;
int q = nextQ;
int p = q+1;
nextQ = ( p >= numTaskQs) ? 0 : p;
DEBUG_ASSERT( q < numTaskQs);
return q;
}
void taskQEnqueueGrid( TaskQTask taskFunction, TaskQThreadId threadId, long numOfDimensions,
long dimensionSize[MAX_DIMENSION], long tileSize[MAX_DIMENSION]) {
taskQEnqueueGridSpecialized( ( TaskQTask3)taskFunction, threadId, numOfDimensions, tileSize);
enqueueGridHelper( assignTasks, ( TaskQTask3)taskFunction, numOfDimensions, numTaskQs, dimensionSize, tileSize);
if ( parallelRegion) signalTasks();
}
static inline void taskQEnqueueTaskHelper( int threadId, void *task[NUM_FIELDS]) {
TRACE;
int queueNo = pickQueue( threadId);
// if ( !parallelRegion) printf( "%30ld %20ld\n", ( long)task[1], ( long)queueNo);
taskQEnqueueTaskSpecialized( &taskQs[queueNo], task);
if ( parallelRegion) signalTasks();
}
void taskQEnqueueTask1( TaskQTask1 taskFunction, TaskQThreadId threadId, void *arg1) {
TRACE;
void *task[NUM_FIELDS];
copyArgs1( task, taskFunction, arg1);
taskQEnqueueTaskHelper( threadId, task);
}
void taskQEnqueueTask2( TaskQTask2 taskFunction, TaskQThreadId threadId, void *arg1, void *arg2) {
TRACE;
void *task[NUM_FIELDS];
copyArgs2( task, taskFunction, arg1, arg2);
taskQEnqueueTaskHelper( threadId, task);
}
void taskQEnqueueTask3( TaskQTask3 taskFunction, TaskQThreadId threadId, void *arg1, void *arg2, void *arg3) {
TRACE;
void *task[NUM_FIELDS];
copyArgs3( task, taskFunction, arg1, arg2, arg3);
taskQEnqueueTaskHelper( threadId, task);
}
void taskQWait( void) {
static int i = 0;
int done;
parallelRegion = 1;
signalTasks();
TRACE;
do {
doOwnTasks( 0, 0);
stealTasks( 0, 0);
doOwnTasks( 0, 0);
done = waitForEnd();
} while (!done);
parallelRegion = 0;
TRACE;
i++;
}
void taskQResetStats() {
IF_STATS( {
int i; int j;
for ( i = 0; i < numTaskQs; i++) {
taskQs[i].statEnqueued = 0;
taskQs[i].statLocal = 0;
for ( j = 0; j < numTaskQs; j++) {
taskQs[i].statStolen[j] = 0;
}
}
});
}
void taskQPrnStats() {
IF_STATS( {
long j; long i; long total1 = 0; long total2 = 0;
printf( "\n\n\t##### Cumulative statistics from Task Queues #####\n\n");
printf( "\t\t%-10s %-10s %-10s %-10s %-10s\n\n", "Queue", "Enqueued", "Local", "Stolen", "Executed");
for ( j = 0; j < numTaskQs; j++) {
long totalStolen = 0;
for ( i = 0; i < numTaskQs; i++) totalStolen += taskQs[j].statStolen[i];
printf( "\t\t%5ld %10ld %10ld %10ld %10ld\n", j, taskQs[j].statEnqueued, taskQs[j].statLocal-totalStolen, totalStolen, taskQs[j].statLocal);
total1 += taskQs[j].statEnqueued;
total2 += taskQs[j].statLocal;
}
printf( "\t\t%5s %10ld %10s %10s %10ld\n", "Total", total1, "", "", total2);
printf( "\n\n");
printf( "\tBreakdown of Task Stealing\n\n\t%10s", "");
for ( i = 0; i < numTaskQs; i++) { printf( "%8ld Q", i); }
printf( "\n\n");
for ( j = 0; j < numTaskQs; j++) {
printf( "\t%8ld T", j);
for ( i = 0; i < numTaskQs; i++) {
printf( "%10ld", taskQs[j].statStolen[i]);
}
printf( "\n");
}
printf( "\n\n");
});
}
void taskQEnd( void) {
noMoreTasks = 1;
signalTasks();
#ifdef ENABLE_PTHREADS
ALAMERE_END();;
#endif //ENABLE_PTHREADS
}
| bsd-3-clause |
zlqhem/crest-boost | benchmarks/vim-5.7/src/ctags/strlist.c | 7 | 3873 | /*****************************************************************************
* $Id: strlist.c,v 8.4 1999/09/29 02:20:25 darren Exp $
*
* Copyright (c) 1999, Darren Hiebert
*
* This source code is released for free distribution under the terms of the
* GNU General Public License.
*
* This module contains functions managing resizable string lists.
*****************************************************************************/
/*============================================================================
= Include files
============================================================================*/
#include "general.h"
#include <string.h>
#include "strlist.h"
#include "main.h"
#include "debug.h"
/*============================================================================
= Function definitions
============================================================================*/
extern stringList* stringListNew()
{
stringList* const result = (stringList*)eMalloc(sizeof(stringList));
result->max = 0;
result->count = 0;
result->list = NULL;
return result;
}
extern stringList* stringListNewFromArgv( argv )
const char* const* const argv;
{
stringList* const result = stringListNew();
const char *const *p;
Assert(argv != NULL);
for (p = argv ; *p != NULL ; ++p)
stringListAdd(result, vStringNewInit(*p));
return result;
}
extern void stringListAdd( current, string )
stringList *const current;
vString *string;
{
enum { incrementalIncrease = 10 };
Assert(current != NULL);
if (current->list == NULL)
{
Assert(current->max == 0);
current->count = 0;
current->max = incrementalIncrease;
current->list = (vString **)eMalloc((size_t)current->max *
sizeof(vString *));
}
else if (current->count == current->max)
{
current->max += incrementalIncrease;
current->list = (vString **)eRealloc(current->list,
(size_t)current->max * sizeof(vString *));
}
current->list[current->count++] = string;
}
extern unsigned int stringListCount( current )
stringList *const current;
{
Assert(current != NULL);
return current->count;
}
extern vString* stringListItem( current, indx )
stringList *const current;
const unsigned int indx;
{
Assert(current != NULL);
return current->list[indx];
}
extern void stringListClear( current )
stringList *const current;
{
unsigned int i;
Assert(current != NULL);
for (i = 0 ; i < current->count ; ++i)
{
vStringDelete(current->list[i]);
current->list[i] = NULL;
}
current->count = 0;
}
extern void stringListDelete( current )
stringList* const current;
{
if (current != NULL)
{
if (current->list != NULL)
{
stringListClear(current);
eFree(current->list);
current->list = NULL;
}
current->max = 0;
current->count = 0;
eFree(current);
}
}
extern boolean stringListHas( current, string)
stringList *const current;
const char *const string;
{
boolean result = FALSE;
unsigned int i;
Assert(current != NULL);
for (i = 0 ; ! result && i < current->count ; ++i)
{
if (strcmp(string, vStringValue(current->list[i])) == 0)
result = TRUE;
}
return result;
}
extern boolean stringListHasInsensitive( current, string)
stringList *const current;
const char *const string;
{
boolean result = FALSE;
unsigned int i;
Assert(current != NULL);
for (i = 0 ; ! result && i < current->count ; ++i)
{
if (strequiv(string, vStringValue(current->list[i])))
result = TRUE;
}
return result;
}
extern void stringListPrint( current )
stringList *const current;
{
unsigned int i;
Assert(current != NULL);
for (i = 0 ; i < current->count ; ++i)
printf("%s%s", (i > 0) ? ", " : "", vStringValue(current->list[i]));
}
| bsd-3-clause |
MisterTea/HyperNEAT | boost_1_57_0/libs/coroutine/example/cpp11/symmetric/simple.cpp | 8 | 1198 |
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cstdlib>
#include <iostream>
#include <boost/coroutine/all.hpp>
typedef boost::coroutines::symmetric_coroutine< void > coro_t;
int main( int argc, char * argv[])
{
coro_t::call_type * other1 = 0;
coro_t::call_type * other2 = 0;
coro_t::call_type coro1(
[&]( coro_t::yield_type & yield) {
std::cout << "foo1" << std::endl;
yield( * other2);
std::cout << "foo2" << std::endl;
yield( * other2);
std::cout << "foo3" << std::endl;
});
coro_t::call_type coro2(
[&]( coro_t::yield_type & yield) {
std::cout << "bar1" << std::endl;
yield( * other1);
std::cout << "bar2" << std::endl;
yield( * other1);
std::cout << "bar3" << std::endl;
});
other1 = & coro1;
other2 = & coro2;
coro1();
std::cout << "Done" << std::endl;
return EXIT_SUCCESS;
}
| bsd-3-clause |
maxhutch/magma | testing/lin/zebchvxx.f | 9 | 18236 | SUBROUTINE ZEBCHVXX( THRESH, PATH )
IMPLICIT NONE
* .. Scalar Arguments ..
DOUBLE PRECISION THRESH
CHARACTER*3 PATH
*
* Purpose
* ======
*
* ZEBCHVXX will run Z**SVXX on a series of Hilbert matrices and then
* compare the error bounds returned by Z**SVXX to see if the returned
* answer indeed falls within those bounds.
*
* Eight test ratios will be computed. The tests will pass if they are .LT.
* THRESH. There are two cases that are determined by 1 / (SQRT( N ) * EPS).
* If that value is .LE. to the component wise reciprocal condition number,
* it uses the guaranteed case, other wise it uses the unguaranteed case.
*
* Test ratios:
* Let Xc be X_computed and Xt be X_truth.
* The norm used is the infinity norm.
* Let A be the guaranteed case and B be the unguaranteed case.
*
* 1. Normwise guaranteed forward error bound.
* A: norm ( abs( Xc - Xt ) / norm ( Xt ) .LE. ERRBND( *, nwise_i, bnd_i ) and
* ERRBND( *, nwise_i, bnd_i ) .LE. MAX(SQRT(N),10) * EPS.
* If these conditions are met, the test ratio is set to be
* ERRBND( *, nwise_i, bnd_i ) / MAX(SQRT(N), 10). Otherwise it is 1/EPS.
* B: For this case, CGESVXX should just return 1. If it is less than
* one, treat it the same as in 1A. Otherwise it fails. (Set test
* ratio to ERRBND( *, nwise_i, bnd_i ) * THRESH?)
*
* 2. Componentwise guaranteed forward error bound.
* A: norm ( abs( Xc(j) - Xt(j) ) ) / norm (Xt(j)) .LE. ERRBND( *, cwise_i, bnd_i )
* for all j .AND. ERRBND( *, cwise_i, bnd_i ) .LE. MAX(SQRT(N), 10) * EPS.
* If these conditions are met, the test ratio is set to be
* ERRBND( *, cwise_i, bnd_i ) / MAX(SQRT(N), 10). Otherwise it is 1/EPS.
* B: Same as normwise test ratio.
*
* 3. Backwards error.
* A: The test ratio is set to BERR/EPS.
* B: Same test ratio.
*
* 4. Reciprocal condition number.
* A: A condition number is computed with Xt and compared with the one
* returned from CGESVXX. Let RCONDc be the RCOND returned by CGESVXX
* and RCONDt be the RCOND from the truth value. Test ratio is set to
* MAX(RCONDc/RCONDt, RCONDt/RCONDc).
* B: Test ratio is set to 1 / (EPS * RCONDc).
*
* 5. Reciprocal normwise condition number.
* A: The test ratio is set to
* MAX(ERRBND( *, nwise_i, cond_i ) / NCOND, NCOND / ERRBND( *, nwise_i, cond_i )).
* B: Test ratio is set to 1 / (EPS * ERRBND( *, nwise_i, cond_i )).
*
* 6. Reciprocal componentwise condition number.
* A: Test ratio is set to
* MAX(ERRBND( *, cwise_i, cond_i ) / CCOND, CCOND / ERRBND( *, cwise_i, cond_i )).
* B: Test ratio is set to 1 / (EPS * ERRBND( *, cwise_i, cond_i )).
*
* .. Parameters ..
* NMAX is determined by the largest number in the inverse of the hilbert
* matrix. Precision is exhausted when the largest entry in it is greater
* than 2 to the power of the number of bits in the fraction of the data
* type used plus one, which is 24 for single precision.
* NMAX should be 6 for single and 11 for double.
INTEGER NMAX, NPARAMS, NERRBND, NTESTS, KL, KU
PARAMETER (NMAX = 10, NPARAMS = 2, NERRBND = 3,
$ NTESTS = 6)
* .. Local Scalars ..
INTEGER N, NRHS, INFO, I ,J, k, NFAIL, LDA,
$ N_AUX_TESTS, LDAB, LDAFB
CHARACTER FACT, TRANS, UPLO, EQUED
CHARACTER*2 C2
CHARACTER(3) NGUAR, CGUAR
LOGICAL printed_guide
DOUBLE PRECISION NCOND, CCOND, M, NORMDIF, NORMT, RCOND,
$ RNORM, RINORM, SUMR, SUMRI, EPS,
$ BERR(NMAX), RPVGRW, ORCOND,
$ CWISE_ERR, NWISE_ERR, CWISE_BND, NWISE_BND,
$ CWISE_RCOND, NWISE_RCOND,
$ CONDTHRESH, ERRTHRESH
COMPLEX*16 ZDUM
* .. Local Arrays ..
DOUBLE PRECISION TSTRAT(NTESTS), RINV(NMAX), PARAMS(NPARAMS),
$ S(NMAX),R(NMAX),C(NMAX),RWORK(3*NMAX),
$ DIFF(NMAX, NMAX),
$ ERRBND_N(NMAX*3), ERRBND_C(NMAX*3)
INTEGER IPIV(NMAX)
COMPLEX*16 A(NMAX,NMAX),INVHILB(NMAX,NMAX),X(NMAX,NMAX),
$ WORK(NMAX*3*5), AF(NMAX, NMAX),B(NMAX, NMAX),
$ ACOPY(NMAX, NMAX),
$ AB( (NMAX-1)+(NMAX-1)+1, NMAX ),
$ ABCOPY( (NMAX-1)+(NMAX-1)+1, NMAX ),
$ AFB( 2*(NMAX-1)+(NMAX-1)+1, NMAX )
* .. External Functions ..
DOUBLE PRECISION DLAMCH
* .. External Subroutines ..
EXTERNAL ZLAHILB, ZGESVXX, ZPOSVXX, ZSYSVXX,
$ ZGBSVXX, ZLACPY, LSAMEN
LOGICAL LSAMEN
* .. Intrinsic Functions ..
INTRINSIC SQRT, MAX, ABS, DBLE, DIMAG
* .. Statement Functions ..
DOUBLE PRECISION CABS1
* .. Statement Function Definitions ..
CABS1( ZDUM ) = ABS( DBLE( ZDUM ) ) + ABS( DIMAG( ZDUM ) )
* .. Parameters ..
INTEGER NWISE_I, CWISE_I
PARAMETER (NWISE_I = 1, CWISE_I = 1)
INTEGER BND_I, COND_I
PARAMETER (BND_I = 2, COND_I = 3)
* Create the loop to test out the Hilbert matrices
FACT = 'E'
UPLO = 'U'
TRANS = 'N'
EQUED = 'N'
EPS = DLAMCH('Epsilon')
NFAIL = 0
N_AUX_TESTS = 0
LDA = NMAX
LDAB = (NMAX-1)+(NMAX-1)+1
LDAFB = 2*(NMAX-1)+(NMAX-1)+1
C2 = PATH( 2: 3 )
* Main loop to test the different Hilbert Matrices.
printed_guide = .false.
DO N = 1 , NMAX
PARAMS(1) = -1
PARAMS(2) = -1
KL = N-1
KU = N-1
NRHS = n
M = MAX(SQRT(DBLE(N)), 10.0D+0)
* Generate the Hilbert matrix, its inverse, and the
* right hand side, all scaled by the LCM(1,..,2N-1).
CALL ZLAHILB(N, N, A, LDA, INVHILB, LDA, B,
$ LDA, WORK, INFO, PATH)
* Copy A into ACOPY.
CALL ZLACPY('ALL', N, N, A, NMAX, ACOPY, NMAX)
* Store A in band format for GB tests
DO J = 1, N
DO I = 1, KL+KU+1
AB( I, J ) = (0.0D+0,0.0D+0)
END DO
END DO
DO J = 1, N
DO I = MAX( 1, J-KU ), MIN( N, J+KL )
AB( KU+1+I-J, J ) = A( I, J )
END DO
END DO
* Copy AB into ABCOPY.
DO J = 1, N
DO I = 1, KL+KU+1
ABCOPY( I, J ) = (0.0D+0,0.0D+0)
END DO
END DO
CALL ZLACPY('ALL', KL+KU+1, N, AB, LDAB, ABCOPY, LDAB)
* Call Z**SVXX with default PARAMS and N_ERR_BND = 3.
IF ( LSAMEN( 2, C2, 'SY' ) ) THEN
CALL ZSYSVXX(FACT, UPLO, N, NRHS, ACOPY, LDA, AF, LDA,
$ IPIV, EQUED, S, B, LDA, X, LDA, ORCOND,
$ RPVGRW, BERR, NERRBND, ERRBND_N, ERRBND_C, NPARAMS,
$ PARAMS, WORK, RWORK, INFO)
ELSE IF ( LSAMEN( 2, C2, 'PO' ) ) THEN
CALL ZPOSVXX(FACT, UPLO, N, NRHS, ACOPY, LDA, AF, LDA,
$ EQUED, S, B, LDA, X, LDA, ORCOND,
$ RPVGRW, BERR, NERRBND, ERRBND_N, ERRBND_C, NPARAMS,
$ PARAMS, WORK, RWORK, INFO)
ELSE IF ( LSAMEN( 2, C2, 'HE' ) ) THEN
CALL ZHESVXX(FACT, UPLO, N, NRHS, ACOPY, LDA, AF, LDA,
$ IPIV, EQUED, S, B, LDA, X, LDA, ORCOND,
$ RPVGRW, BERR, NERRBND, ERRBND_N, ERRBND_C, NPARAMS,
$ PARAMS, WORK, RWORK, INFO)
ELSE IF ( LSAMEN( 2, C2, 'GB' ) ) THEN
CALL ZGBSVXX(FACT, TRANS, N, KL, KU, NRHS, ABCOPY,
$ LDAB, AFB, LDAFB, IPIV, EQUED, R, C, B,
$ LDA, X, LDA, ORCOND, RPVGRW, BERR, NERRBND,
$ ERRBND_N, ERRBND_C, NPARAMS, PARAMS, WORK, RWORK,
$ INFO)
ELSE
CALL ZGESVXX(FACT, TRANS, N, NRHS, ACOPY, LDA, AF, LDA,
$ IPIV, EQUED, R, C, B, LDA, X, LDA, ORCOND,
$ RPVGRW, BERR, NERRBND, ERRBND_N, ERRBND_C, NPARAMS,
$ PARAMS, WORK, RWORK, INFO)
END IF
N_AUX_TESTS = N_AUX_TESTS + 1
IF (ORCOND .LT. EPS) THEN
! Either factorization failed or the matrix is flagged, and 1 <=
! INFO <= N+1. We don't decide based on rcond anymore.
! IF (INFO .EQ. 0 .OR. INFO .GT. N+1) THEN
! NFAIL = NFAIL + 1
! WRITE (*, FMT=8000) N, INFO, ORCOND, RCOND
! END IF
ELSE
! Either everything succeeded (INFO == 0) or some solution failed
! to converge (INFO > N+1).
IF (INFO .GT. 0 .AND. INFO .LE. N+1) THEN
NFAIL = NFAIL + 1
WRITE (*, FMT=8000) C2, N, INFO, ORCOND, RCOND
END IF
END IF
* Calculating the difference between Z**SVXX's X and the true X.
DO I = 1,N
DO J =1,NRHS
DIFF(I,J) = X(I,J) - INVHILB(I,J)
END DO
END DO
* Calculating the RCOND
RNORM = 0
RINORM = 0
IF ( LSAMEN( 2, C2, 'PO' ) .OR. LSAMEN( 2, C2, 'SY' ) .OR.
$ LSAMEN( 2, C2, 'HE' ) ) THEN
DO I = 1, N
SUMR = 0
SUMRI = 0
DO J = 1, N
SUMR = SUMR + S(I) * CABS1(A(I,J)) * S(J)
SUMRI = SUMRI + CABS1(INVHILB(I, J)) / (S(J) * S(I))
END DO
RNORM = MAX(RNORM,SUMR)
RINORM = MAX(RINORM,SUMRI)
END DO
ELSE IF ( LSAMEN( 2, C2, 'GE' ) .OR. LSAMEN( 2, C2, 'GB' ) )
$ THEN
DO I = 1, N
SUMR = 0
SUMRI = 0
DO J = 1, N
SUMR = SUMR + R(I) * CABS1(A(I,J)) * C(J)
SUMRI = SUMRI + CABS1(INVHILB(I, J)) / (R(J) * C(I))
END DO
RNORM = MAX(RNORM,SUMR)
RINORM = MAX(RINORM,SUMRI)
END DO
END IF
RNORM = RNORM / CABS1(A(1, 1))
RCOND = 1.0D+0/(RNORM * RINORM)
* Calculating the R for normwise rcond.
DO I = 1, N
RINV(I) = 0.0D+0
END DO
DO J = 1, N
DO I = 1, N
RINV(I) = RINV(I) + CABS1(A(I,J))
END DO
END DO
* Calculating the Normwise rcond.
RINORM = 0.0D+0
DO I = 1, N
SUMRI = 0.0D+0
DO J = 1, N
SUMRI = SUMRI + CABS1(INVHILB(I,J) * RINV(J))
END DO
RINORM = MAX(RINORM, SUMRI)
END DO
! invhilb is the inverse *unscaled* Hilbert matrix, so scale its norm
! by 1/A(1,1) to make the scaling match A (the scaled Hilbert matrix)
NCOND = CABS1(A(1,1)) / RINORM
CONDTHRESH = M * EPS
ERRTHRESH = M * EPS
DO K = 1, NRHS
NORMT = 0.0D+0
NORMDIF = 0.0D+0
CWISE_ERR = 0.0D+0
DO I = 1, N
NORMT = MAX(CABS1(INVHILB(I, K)), NORMT)
NORMDIF = MAX(CABS1(X(I,K) - INVHILB(I,K)), NORMDIF)
IF (INVHILB(I,K) .NE. 0.0D+0) THEN
CWISE_ERR = MAX(CABS1(X(I,K) - INVHILB(I,K))
$ /CABS1(INVHILB(I,K)), CWISE_ERR)
ELSE IF (X(I, K) .NE. 0.0D+0) THEN
CWISE_ERR = DLAMCH('OVERFLOW')
END IF
END DO
IF (NORMT .NE. 0.0D+0) THEN
NWISE_ERR = NORMDIF / NORMT
ELSE IF (NORMDIF .NE. 0.0D+0) THEN
NWISE_ERR = DLAMCH('OVERFLOW')
ELSE
NWISE_ERR = 0.0D+0
ENDIF
DO I = 1, N
RINV(I) = 0.0D+0
END DO
DO J = 1, N
DO I = 1, N
RINV(I) = RINV(I) + CABS1(A(I, J) * INVHILB(J, K))
END DO
END DO
RINORM = 0.0D+0
DO I = 1, N
SUMRI = 0.0D+0
DO J = 1, N
SUMRI = SUMRI
$ + CABS1(INVHILB(I, J) * RINV(J) / INVHILB(I, K))
END DO
RINORM = MAX(RINORM, SUMRI)
END DO
! invhilb is the inverse *unscaled* Hilbert matrix, so scale its norm
! by 1/A(1,1) to make the scaling match A (the scaled Hilbert matrix)
CCOND = CABS1(A(1,1))/RINORM
! Forward error bound tests
NWISE_BND = ERRBND_N(K + (BND_I-1)*NRHS)
CWISE_BND = ERRBND_C(K + (BND_I-1)*NRHS)
NWISE_RCOND = ERRBND_N(K + (COND_I-1)*NRHS)
CWISE_RCOND = ERRBND_C(K + (COND_I-1)*NRHS)
! write (*,*) 'nwise : ', n, k, ncond, nwise_rcond,
! $ condthresh, ncond.ge.condthresh
! write (*,*) 'nwise2: ', k, nwise_bnd, nwise_err, errthresh
IF (NCOND .GE. CONDTHRESH) THEN
NGUAR = 'YES'
IF (NWISE_BND .GT. ERRTHRESH) THEN
TSTRAT(1) = 1/(2.0D+0*EPS)
ELSE
IF (NWISE_BND .NE. 0.0D+0) THEN
TSTRAT(1) = NWISE_ERR / NWISE_BND
ELSE IF (NWISE_ERR .NE. 0.0D+0) THEN
TSTRAT(1) = 1/(16.0*EPS)
ELSE
TSTRAT(1) = 0.0D+0
END IF
IF (TSTRAT(1) .GT. 1.0D+0) THEN
TSTRAT(1) = 1/(4.0D+0*EPS)
END IF
END IF
ELSE
NGUAR = 'NO'
IF (NWISE_BND .LT. 1.0D+0) THEN
TSTRAT(1) = 1/(8.0D+0*EPS)
ELSE
TSTRAT(1) = 1.0D+0
END IF
END IF
! write (*,*) 'cwise : ', n, k, ccond, cwise_rcond,
! $ condthresh, ccond.ge.condthresh
! write (*,*) 'cwise2: ', k, cwise_bnd, cwise_err, errthresh
IF (CCOND .GE. CONDTHRESH) THEN
CGUAR = 'YES'
IF (CWISE_BND .GT. ERRTHRESH) THEN
TSTRAT(2) = 1/(2.0D+0*EPS)
ELSE
IF (CWISE_BND .NE. 0.0D+0) THEN
TSTRAT(2) = CWISE_ERR / CWISE_BND
ELSE IF (CWISE_ERR .NE. 0.0D+0) THEN
TSTRAT(2) = 1/(16.0D+0*EPS)
ELSE
TSTRAT(2) = 0.0D+0
END IF
IF (TSTRAT(2) .GT. 1.0D+0) TSTRAT(2) = 1/(4.0D+0*EPS)
END IF
ELSE
CGUAR = 'NO'
IF (CWISE_BND .LT. 1.0D+0) THEN
TSTRAT(2) = 1/(8.0D+0*EPS)
ELSE
TSTRAT(2) = 1.0D+0
END IF
END IF
! Backwards error test
TSTRAT(3) = BERR(K)/EPS
! Condition number tests
TSTRAT(4) = RCOND / ORCOND
IF (RCOND .GE. CONDTHRESH .AND. TSTRAT(4) .LT. 1.0D+0)
$ TSTRAT(4) = 1.0D+0 / TSTRAT(4)
TSTRAT(5) = NCOND / NWISE_RCOND
IF (NCOND .GE. CONDTHRESH .AND. TSTRAT(5) .LT. 1.0D+0)
$ TSTRAT(5) = 1.0D+0 / TSTRAT(5)
TSTRAT(6) = CCOND / NWISE_RCOND
IF (CCOND .GE. CONDTHRESH .AND. TSTRAT(6) .LT. 1.0D+0)
$ TSTRAT(6) = 1.0D+0 / TSTRAT(6)
DO I = 1, NTESTS
IF (TSTRAT(I) .GT. THRESH) THEN
IF (.NOT.PRINTED_GUIDE) THEN
WRITE(*,*)
WRITE( *, 9996) 1
WRITE( *, 9995) 2
WRITE( *, 9994) 3
WRITE( *, 9993) 4
WRITE( *, 9992) 5
WRITE( *, 9991) 6
WRITE( *, 9990) 7
WRITE( *, 9989) 8
WRITE(*,*)
PRINTED_GUIDE = .TRUE.
END IF
WRITE( *, 9999) C2, N, K, NGUAR, CGUAR, I, TSTRAT(I)
NFAIL = NFAIL + 1
END IF
END DO
END DO
c$$$ WRITE(*,*)
c$$$ WRITE(*,*) 'Normwise Error Bounds'
c$$$ WRITE(*,*) 'Guaranteed error bound: ',ERRBND(NRHS,nwise_i,bnd_i)
c$$$ WRITE(*,*) 'Reciprocal condition number: ',ERRBND(NRHS,nwise_i,cond_i)
c$$$ WRITE(*,*) 'Raw error estimate: ',ERRBND(NRHS,nwise_i,rawbnd_i)
c$$$ WRITE(*,*)
c$$$ WRITE(*,*) 'Componentwise Error Bounds'
c$$$ WRITE(*,*) 'Guaranteed error bound: ',ERRBND(NRHS,cwise_i,bnd_i)
c$$$ WRITE(*,*) 'Reciprocal condition number: ',ERRBND(NRHS,cwise_i,cond_i)
c$$$ WRITE(*,*) 'Raw error estimate: ',ERRBND(NRHS,cwise_i,rawbnd_i)
c$$$ print *, 'Info: ', info
c$$$ WRITE(*,*)
* WRITE(*,*) 'TSTRAT: ',TSTRAT
END DO
WRITE(*,*)
IF( NFAIL .GT. 0 ) THEN
WRITE(*,9998) C2, NFAIL, NTESTS*N+N_AUX_TESTS
ELSE
WRITE(*,9997) C2
END IF
9999 FORMAT( ' Z', A2, 'SVXX: N =', I2, ', RHS = ', I2,
$ ', NWISE GUAR. = ', A, ', CWISE GUAR. = ', A,
$ ' test(',I1,') =', G12.5 )
9998 FORMAT( ' Z', A2, 'SVXX: ', I6, ' out of ', I6,
$ ' tests failed to pass the threshold' )
9997 FORMAT( ' Z', A2, 'SVXX passed the tests of error bounds' )
* Test ratios.
9996 FORMAT( 3X, I2, ': Normwise guaranteed forward error', / 5X,
$ 'Guaranteed case: if norm ( abs( Xc - Xt )',
$ ' / norm ( Xt ) .LE. ERRBND( *, nwise_i, bnd_i ), then',
$ / 5X,
$ 'ERRBND( *, nwise_i, bnd_i ) .LE. MAX(SQRT(N), 10) * EPS')
9995 FORMAT( 3X, I2, ': Componentwise guaranteed forward error' )
9994 FORMAT( 3X, I2, ': Backwards error' )
9993 FORMAT( 3X, I2, ': Reciprocal condition number' )
9992 FORMAT( 3X, I2, ': Reciprocal normwise condition number' )
9991 FORMAT( 3X, I2, ': Raw normwise error estimate' )
9990 FORMAT( 3X, I2, ': Reciprocal componentwise condition number' )
9989 FORMAT( 3X, I2, ': Raw componentwise error estimate' )
8000 FORMAT( ' Z', A2, 'SVXX: N =', I2, ', INFO = ', I3,
$ ', ORCOND = ', G12.5, ', real RCOND = ', G12.5 )
END
| bsd-3-clause |
js0701/chromium-crosswalk | third_party/WebKit/Source/core/paint/PaintLayerStackingNodeIterator.cpp | 9 | 5852 | /*
* 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/paint/PaintLayerStackingNodeIterator.h"
// FIXME: We should build our primitive on top of
// PaintLayerStackingNode and remove this include.
#include "core/paint/PaintLayer.h"
#include "core/paint/PaintLayerStackingNode.h"
namespace blink {
PaintLayerStackingNodeIterator::PaintLayerStackingNodeIterator(const PaintLayerStackingNode& root, unsigned whichChildren)
: m_root(root)
, m_remainingChildren(whichChildren)
, m_index(0)
{
m_currentNormalFlowChild = root.layer()->firstChild();
}
PaintLayerStackingNode* PaintLayerStackingNodeIterator::next()
{
if (m_remainingChildren & NegativeZOrderChildren) {
Vector<PaintLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
if (negZOrderList && m_index < negZOrderList->size())
return negZOrderList->at(m_index++);
m_index = 0;
m_remainingChildren &= ~NegativeZOrderChildren;
}
if (m_remainingChildren & NormalFlowChildren) {
for (; m_currentNormalFlowChild; m_currentNormalFlowChild = m_currentNormalFlowChild->nextSibling()) {
if (!m_currentNormalFlowChild->stackingNode()->isTreatedAsOrStackingContext() && !m_currentNormalFlowChild->isReflection()) {
PaintLayer* normalFlowChild = m_currentNormalFlowChild;
m_currentNormalFlowChild = m_currentNormalFlowChild->nextSibling();
return normalFlowChild->stackingNode();
}
}
// We reset the iterator in case we reuse it.
m_currentNormalFlowChild = m_root.layer()->firstChild();
m_remainingChildren &= ~NormalFlowChildren;
}
if (m_remainingChildren & PositiveZOrderChildren) {
Vector<PaintLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
if (posZOrderList && m_index < posZOrderList->size())
return posZOrderList->at(m_index++);
m_index = 0;
m_remainingChildren &= ~PositiveZOrderChildren;
}
return 0;
}
PaintLayerStackingNode* PaintLayerStackingNodeReverseIterator::next()
{
if (m_remainingChildren & NegativeZOrderChildren) {
Vector<PaintLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
if (negZOrderList && m_index >= 0)
return negZOrderList->at(m_index--);
m_remainingChildren &= ~NegativeZOrderChildren;
setIndexToLastItem();
}
if (m_remainingChildren & NormalFlowChildren) {
for (; m_currentNormalFlowChild; m_currentNormalFlowChild = m_currentNormalFlowChild->previousSibling()) {
if (!m_currentNormalFlowChild->stackingNode()->isTreatedAsOrStackingContext() && !m_currentNormalFlowChild->isReflection()) {
PaintLayer* normalFlowChild = m_currentNormalFlowChild;
m_currentNormalFlowChild = m_currentNormalFlowChild->previousSibling();
return normalFlowChild->stackingNode();
}
}
m_remainingChildren &= ~NormalFlowChildren;
setIndexToLastItem();
}
if (m_remainingChildren & PositiveZOrderChildren) {
Vector<PaintLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
if (posZOrderList && m_index >= 0)
return posZOrderList->at(m_index--);
m_remainingChildren &= ~PositiveZOrderChildren;
setIndexToLastItem();
}
return 0;
}
void PaintLayerStackingNodeReverseIterator::setIndexToLastItem()
{
if (m_remainingChildren & NegativeZOrderChildren) {
Vector<PaintLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
if (negZOrderList) {
m_index = negZOrderList->size() - 1;
return;
}
m_remainingChildren &= ~NegativeZOrderChildren;
}
if (m_remainingChildren & NormalFlowChildren) {
m_currentNormalFlowChild = m_root.layer()->lastChild();
return;
}
if (m_remainingChildren & PositiveZOrderChildren) {
Vector<PaintLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
if (posZOrderList) {
m_index = posZOrderList->size() - 1;
return;
}
m_remainingChildren &= ~PositiveZOrderChildren;
}
// No more list to visit.
ASSERT(!m_remainingChildren);
m_index = -1;
}
} // namespace blink
| bsd-3-clause |
gnu3ra/SCC15HPCRepast | INSTALLATION/hdf5-1.8.13/tools/h5jam/tellub.c | 10 | 5025 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <stdio.h>
#ifdef H5_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "hdf5.h"
#include "H5private.h"
#include "h5tools.h"
#include "h5tools_utils.h"
/* Name of tool */
#define PROGRAMNAME "tellub"
/*
* Command-line options: The user can specify short or long-named
* parameters. The long-named ones can be partially spelled. When
* adding more, make sure that they don't clash with each other.
*/
static const char *s_opts = "h";
static struct long_options l_opts[] = {
{"help", no_arg, 'h'},
{"hel", no_arg, 'h'},
{NULL, 0, '\0'}
};
/*-------------------------------------------------------------------------
* Function: usage
*
* Purpose: Print the usage message
*
* Return: void
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
static void
usage (const char *prog)
{
fflush (stdout);
fprintf (stdout, "usage: %s h5_file\n", prog);
fprintf (stdout,
" Check that h5_fil is HDF5 file and print size of user block \n");
fprintf (stdout, " %s -h\n", prog);
fprintf (stdout, " Print a usage message and exit\n");
}
/*-------------------------------------------------------------------------
* Function: parse_command_line
*
* Purpose: Parse the command line for the h5dumper.
*
* Return: Success:
*
* Failure: Exits program with EXIT_FAILURE value.
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
static void
parse_command_line (int argc, const char *argv[])
{
int opt;
/* parse command line options */
while ((opt = get_option (argc, argv, s_opts, l_opts)) != EOF)
{
switch ((char) opt)
{
case 'h':
usage (h5tools_getprogname());
exit (EXIT_SUCCESS);
case '?':
default:
usage (h5tools_getprogname());
exit (EXIT_FAILURE);
}
}
/* check for file name to be processed */
if (argc <= opt_ind)
{
error_msg("missing file name\n");
usage (h5tools_getprogname());
exit (EXIT_FAILURE);
}
}
/*-------------------------------------------------------------------------
* Function: main
*
* Purpose: HDF5 user block unjammer
*
* Return: Success: 0
* Failure: 1
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
int
main (int argc, const char *argv[])
{
char *ifname;
void *edata;
H5E_auto2_t func;
hid_t ifile;
hsize_t usize;
htri_t testval;
herr_t status;
hid_t plist;
h5tools_setprogname(PROGRAMNAME);
h5tools_setstatus(EXIT_SUCCESS);
/* Initialize h5tools lib */
h5tools_init();
/* Disable error reporting */
H5Eget_auto2(H5E_DEFAULT, &func, &edata);
H5Eset_auto2(H5E_DEFAULT, NULL, NULL);
parse_command_line (argc, argv);
if (argc <= (opt_ind))
{
error_msg("missing file name\n");
usage (h5tools_getprogname());
return (EXIT_FAILURE);
}
ifname = HDstrdup (argv[opt_ind]);
testval = H5Fis_hdf5 (ifname);
if (testval <= 0)
{
error_msg("Input HDF5 file is not HDF \"%s\"\n", ifname);
return (EXIT_FAILURE);
}
ifile = H5Fopen (ifname, H5F_ACC_RDONLY, H5P_DEFAULT);
if (ifile < 0)
{
error_msg("Can't open input HDF5 file \"%s\"\n", ifname);
return (EXIT_FAILURE);
}
plist = H5Fget_create_plist (ifile);
if (plist < 0)
{
error_msg("Can't get file creation plist for file \"%s\"\n",
ifname);
return (EXIT_FAILURE);
}
status = H5Pget_userblock (plist, &usize);
if (status < 0)
{
error_msg("Can't get user block for file \"%s\"\n", ifname);
return (EXIT_FAILURE);
}
printf ("%ld\n", (long) usize);
H5Pclose (plist);
H5Fclose (ifile);
return (EXIT_SUCCESS);
}
| bsd-3-clause |
victorv/arrayfire | src/backend/opencl/assign.cpp | 11 | 2321 | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/dim4.hpp>
#include <Array.hpp>
#include <handle.hpp>
#include <assign.hpp>
#include <kernel/assign.hpp>
#include <err_opencl.hpp>
#include <memory.hpp>
using af::dim4;
namespace opencl
{
template<typename T>
void assign(Array<T>& out, const af_index_t idxrs[], const Array<T>& rhs)
{
kernel::AssignKernelParam_t p;
std::vector<af_seq> seqs(4, af_span);
// create seq vector to retrieve output
// dimensions, offsets & offsets
for (dim_t x=0; x<4; ++x) {
if (idxrs[x].isSeq) {
seqs[x] = idxrs[x].idx.seq;
}
}
// retrieve dimensions, strides and offsets
dim4 dDims = out.dims();
// retrieve dimensions & strides for array
// to which rhs is being copied to
dim4 dstOffs = toOffset(seqs, dDims);
dim4 dstStrds= toStride(seqs, dDims);
for (dim_t i=0; i<4; ++i) {
p.isSeq[i] = idxrs[i].isSeq;
p.offs[i] = dstOffs[i];
p.strds[i] = dstStrds[i];
}
Buffer* bPtrs[4];
std::vector< Array<uint> > idxArrs(4, createEmptyArray<uint>(dim4()));
// look through indexs to read af_array indexs
for (dim_t x=0; x<4; ++x) {
// set index pointers were applicable
if (!p.isSeq[x]) {
idxArrs[x] = castArray<uint>(idxrs[x].idx.arr);
bPtrs[x] = idxArrs[x].get();
}
else {
// alloc an 1-element buffer to avoid OpenCL from failing
bPtrs[x] = bufferAlloc(sizeof(uint));
}
}
kernel::assign<T>(out, rhs, p, bPtrs);
for (dim_t x=0; x<4; ++x) {
if (p.isSeq[x]) bufferFree(bPtrs[x]);
}
}
#define INSTANTIATE(T) \
template void assign<T>(Array<T>& out, const af_index_t idxrs[], const Array<T>& rhs);
INSTANTIATE(cdouble)
INSTANTIATE(double )
INSTANTIATE(cfloat )
INSTANTIATE(float )
INSTANTIATE(int )
INSTANTIATE(uint )
INSTANTIATE(intl )
INSTANTIATE(uintl )
INSTANTIATE(uchar )
INSTANTIATE(char )
INSTANTIATE(short )
INSTANTIATE(ushort )
}
| bsd-3-clause |
petchat/bosen | app/caffe/src/caffe/layers/hdf5_data_layer.cpp | 12 | 4106 | /*
TODO:
- load file in a separate thread ("prefetch")
- can be smarter about the memcpy call instead of doing it row-by-row
:: use util functions caffe_copy, and Blob->offset()
:: don't forget to update hdf5_daa_layer.cu accordingly
- add ability to shuffle filenames if flag is set
*/
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include "hdf5.h"
#include "hdf5_hl.h"
#include "stdint.h"
#include "caffe/layer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype>
HDF5DataLayer<Dtype>::~HDF5DataLayer<Dtype>() { }
// Load data and label from HDF5 filename into the class property blobs.
template <typename Dtype>
void HDF5DataLayer<Dtype>::LoadHDF5FileData(const char* filename) {
LOG(INFO) << "Loading HDF5 file" << filename;
hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
if (file_id < 0) {
LOG(ERROR) << "Failed opening HDF5 file" << filename;
return;
}
const int MIN_DATA_DIM = 2;
const int MAX_DATA_DIM = 4;
hdf5_load_nd_dataset(
file_id, "data", MIN_DATA_DIM, MAX_DATA_DIM, &data_blob_);
const int MIN_LABEL_DIM = 1;
const int MAX_LABEL_DIM = 2;
hdf5_load_nd_dataset(
file_id, "label", MIN_LABEL_DIM, MAX_LABEL_DIM, &label_blob_);
herr_t status = H5Fclose(file_id);
CHECK_GE(status, 0) << "Failed to close HDF5 file " << filename;
CHECK_EQ(data_blob_.num(), label_blob_.num());
LOG(INFO) << "Successully loaded " << data_blob_.num() << " rows";
}
template <typename Dtype>
void HDF5DataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top, const bool init_ps, int* num_tables,
map<string, vector<int> >* layer_name_to_blob_global_idx) {
// Read the source to parse the filenames.
const string& source = this->layer_param_.hdf5_data_param().source();
LOG(INFO) << "Loading filename from " << source;
hdf_filenames_.clear();
std::ifstream source_file(source.c_str());
if (source_file.is_open()) {
std::string line;
while (source_file >> line) {
hdf_filenames_.push_back(line);
}
}
source_file.close();
num_files_ = hdf_filenames_.size();
current_file_ = 0;
LOG(INFO) << "Number of files: " << num_files_;
// Load the first HDF5 file and initialize the line counter.
LoadHDF5FileData(hdf_filenames_[current_file_].c_str());
current_row_ = 0;
// Reshape blobs.
const int batch_size = this->layer_param_.hdf5_data_param().batch_size();
(*top)[0]->Reshape(batch_size, data_blob_.channels(),
data_blob_.height(), data_blob_.width());
(*top)[1]->Reshape(batch_size, label_blob_.channels(),
label_blob_.height(), label_blob_.width());
LOG(INFO) << "output data size: " << (*top)[0]->num() << ","
<< (*top)[0]->channels() << "," << (*top)[0]->height() << ","
<< (*top)[0]->width();
}
template <typename Dtype>
void HDF5DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const int batch_size = this->layer_param_.hdf5_data_param().batch_size();
const int data_count = (*top)[0]->count() / (*top)[0]->num();
const int label_data_count = (*top)[1]->count() / (*top)[1]->num();
for (int i = 0; i < batch_size; ++i, ++current_row_) {
if (current_row_ == data_blob_.num()) {
if (num_files_ > 1) {
current_file_ += 1;
if (current_file_ == num_files_) {
current_file_ = 0;
LOG(INFO) << "looping around to first file";
}
LoadHDF5FileData(hdf_filenames_[current_file_].c_str());
}
current_row_ = 0;
}
caffe_copy(data_count, &data_blob_.cpu_data()[current_row_ * data_count],
&(*top)[0]->mutable_cpu_data()[i * data_count]);
caffe_copy(label_data_count,
&label_blob_.cpu_data()[current_row_ * label_data_count],
&(*top)[1]->mutable_cpu_data()[i * label_data_count]);
}
}
#ifdef CPU_ONLY
STUB_GPU_FORWARD(HDF5DataLayer, Forward);
#endif
INSTANTIATE_CLASS(HDF5DataLayer);
} // namespace caffe
| bsd-3-clause |
vanish87/skia | src/views/win/skia_win.cpp | 12 | 3854 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <windows.h>
#include <tchar.h>
#include "SkTypes.h"
#include "SkApplication.h"
#include "SkOSWindow_Win.h"
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
// Returns the main window Win32 class name.
static const TCHAR* register_class(HINSTANCE hInstance) {
WNDCLASSEX wcex;
// The main window class name
static const TCHAR gSZWindowClass[] = _T("SkiaApp");
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = gSZWindowClass;
wcex.hIconSm = NULL;
RegisterClassEx(&wcex);
return gSZWindowClass;
}
static char* tchar_to_utf8(const TCHAR* str) {
#ifdef _UNICODE
int size = WideCharToMultiByte(CP_UTF8, 0, str, wcslen(str), NULL, 0, NULL, NULL);
char* str8 = (char*) sk_malloc_throw(size+1);
WideCharToMultiByte(CP_UTF8, 0, str, wcslen(str), str8, size, NULL, NULL);
str8[size] = '\0';
return str8;
#else
return _strdup(str);
#endif
}
// This file can work with GUI or CONSOLE subsystem types since we define _tWinMain and main().
static int main_common(HINSTANCE hInstance, int show, int argc, char**argv);
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine,
int nCmdShow) {
// convert from lpCmdLine to argc, argv.
char* argv[4096];
int argc = 0;
TCHAR exename[1024], *next;
int exenameLen = GetModuleFileName(NULL, exename, SK_ARRAY_COUNT(exename));
// we're ignoring the possibility that the exe name exceeds the exename buffer
(void) exenameLen;
argv[argc++] = tchar_to_utf8(exename);
TCHAR* arg = _tcstok_s(lpCmdLine, _T(" "), &next);
while (arg != NULL) {
argv[argc++] = tchar_to_utf8(arg);
arg = _tcstok_s(NULL, _T(" "), &next);
}
int result = main_common(hInstance, nCmdShow, argc, argv);
for (int i = 0; i < argc; ++i) {
sk_free(argv[i]);
}
return result;
}
int main(int argc, char**argv) {
return main_common(GetModuleHandle(NULL), SW_SHOW, argc, argv);
}
static int main_common(HINSTANCE hInstance, int show, int argc, char**argv) {
const TCHAR* windowClass = register_class(hInstance);
application_init();
SkOSWindow::WindowInit winInit;
winInit.fInstance = hInstance;
winInit.fClass = windowClass;
create_sk_window(&winInit, argc, argv);
SkOSWindow::ForAllWindows([show](void* hWnd, SkOSWindow**) {
ShowWindow((HWND)hWnd, show);
UpdateWindow((HWND)hWnd); }
);
MSG msg;
// Main message loop
while (GetMessage(&msg, NULL, 0, 0)) {
if (true) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
application_term();
return (int) msg.wParam;
}
extern SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_COMMAND:
return DefWindowProc(hWnd, message, wParam, lParam);
case WM_DESTROY:
PostQuitMessage(0);
break;
default: {
SkOSWindow* window = SkOSWindow::GetOSWindowForHWND(hWnd);
if (window && window->wndProc(hWnd, message, wParam, lParam)) {
return 0;
} else {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
}
return 0;
}
| bsd-3-clause |
ThanhVic/stm32plus | examples/timer_master_slave/system/f107_72_8/System.c | 524 | 34717 | /**
******************************************************************************
* @file system_stm32f10x.c
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
*
* 1. This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
* factors, AHB/APBx prescalers and Flash settings).
* This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f10x_xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* 2. After each device reset the HSI (8 MHz) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32f10x_xx.s" file, to
* configure the system clock before to branch to main program.
*
* 3. If the system clock source selected by user fails to startup, the SystemInit()
* function will do nothing and HSI still used as system clock source. User can
* add some code to deal with this issue inside the SetSysClock() function.
*
* 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depedning on
* the product used), refer to "HSE_VALUE" define in "stm32f10x.h" file.
* When HSE is used as system clock source, directly or through PLL, and you
* are using different crystal you have to adapt the HSE value to your own
* configuration.
*
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f10x_system
* @{
*/
/** @addtogroup STM32F10x_System_Private_Includes
* @{
*/
#include "config/stdperiph.h"
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Defines
* @{
*/
/*!< Uncomment the line corresponding to the desired System clock (SYSCLK)
frequency (after reset the HSI is used as SYSCLK source)
IMPORTANT NOTE:
==============
1. After each device reset the HSI is used as System clock source.
2. Please make sure that the selected System clock doesn't exceed your device's
maximum frequency.
3. If none of the define below is enabled, the HSI is used as System clock
source.
4. The System clock configuration functions provided within this file assume that:
- For Low, Medium and High density Value line devices an external 8MHz
crystal is used to drive the System clock.
- For Low, Medium and High density devices an external 8MHz crystal is
used to drive the System clock.
- For Connectivity line devices an external 25MHz crystal is used to drive
the System clock.
If you are using different crystal you have to adapt those functions accordingly.
*/
#if defined (STM32F10X_LD_VL) || (defined STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
/* #define SYSCLK_FREQ_HSE HSE_VALUE */
#define SYSCLK_FREQ_24MHz 24000000
#else
/* #define SYSCLK_FREQ_HSE HSE_VALUE */
/* #define SYSCLK_FREQ_24MHz 24000000 */
/* #define SYSCLK_FREQ_36MHz 36000000 */
/* #define SYSCLK_FREQ_48MHz 48000000 */
/* #define SYSCLK_FREQ_56MHz 56000000 */
#define SYSCLK_FREQ_72MHz 72000000
#endif
/*!< Uncomment the following line if you need to use external SRAM mounted
on STM3210E-EVAL board (STM32 High density and XL-density devices) or on
STM32100E-EVAL board (STM32 High-density value line devices) as data memory */
#if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL)
/* #define DATA_IN_ExtSRAM */
#endif
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Variables
* @{
*/
/*******************************************************************************
* Clock Definitions
*******************************************************************************/
#ifdef SYSCLK_FREQ_HSE
uint32_t SystemCoreClock = SYSCLK_FREQ_HSE; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_24MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_24MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_36MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_36MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_48MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_48MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_56MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_56MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_72MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_72MHz; /*!< System Clock Frequency (Core Clock) */
#else /*!< HSI Selected as System Clock source */
uint32_t SystemCoreClock = HSI_VALUE; /*!< System Clock Frequency (Core Clock) */
#endif
__I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_FunctionPrototypes
* @{
*/
static void SetSysClock(void);
#ifdef SYSCLK_FREQ_HSE
static void SetSysClockToHSE(void);
#elif defined SYSCLK_FREQ_24MHz
static void SetSysClockTo24(void);
#elif defined SYSCLK_FREQ_36MHz
static void SetSysClockTo36(void);
#elif defined SYSCLK_FREQ_48MHz
static void SetSysClockTo48(void);
#elif defined SYSCLK_FREQ_56MHz
static void SetSysClockTo56(void);
#elif defined SYSCLK_FREQ_72MHz
static void SetSysClockTo72(void);
#endif
#ifdef DATA_IN_ExtSRAM
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the Embedded Flash Interface, the PLL and update the
* SystemCoreClock variable.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
void SystemInit (void)
{
/* Reset the RCC clock configuration to the default reset state(for debug purpose) */
/* Set HSION bit */
RCC->CR |= (uint32_t)0x00000001;
/* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
#ifndef STM32F10X_CL
RCC->CFGR &= (uint32_t)0xF8FF0000;
#else
RCC->CFGR &= (uint32_t)0xF0FF0000;
#endif /* STM32F10X_CL */
/* Reset HSEON, CSSON and PLLON bits */
RCC->CR &= (uint32_t)0xFEF6FFFF;
/* Reset HSEBYP bit */
RCC->CR &= (uint32_t)0xFFFBFFFF;
/* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
RCC->CFGR &= (uint32_t)0xFF80FFFF;
#ifdef STM32F10X_CL
/* Reset PLL2ON and PLL3ON bits */
RCC->CR &= (uint32_t)0xEBFFFFFF;
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x00FF0000;
/* Reset CFGR2 register */
RCC->CFGR2 = 0x00000000;
#elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x009F0000;
/* Reset CFGR2 register */
RCC->CFGR2 = 0x00000000;
#else
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x009F0000;
#endif /* STM32F10X_CL */
#if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL)
#ifdef DATA_IN_ExtSRAM
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
#endif
/* Configure the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers */
/* Configure the Flash Latency cycles and enable prefetch buffer */
SetSysClock();
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
#endif
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz or 25 MHz, depedning on the product used), user has to ensure
* that HSE_VALUE is same as the real frequency of the crystal used.
* Otherwise, this function may have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
* @param None
* @retval None
*/
void SystemCoreClockUpdate (void)
{
uint32_t tmp = 0, pllmull = 0, pllsource = 0;
#ifdef STM32F10X_CL
uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0;
#endif /* STM32F10X_CL */
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
uint32_t prediv1factor = 0;
#endif /* STM32F10X_LD_VL or STM32F10X_MD_VL or STM32F10X_HD_VL */
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00: /* HSI used as system clock */
SystemCoreClock = HSI_VALUE;
break;
case 0x04: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case 0x08: /* PLL used as system clock */
/* Get PLL clock source and multiplication factor ----------------------*/
pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
#ifndef STM32F10X_CL
pllmull = ( pllmull >> 18) + 2;
if (pllsource == 0x00)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1) * pllmull;
}
else
{
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1;
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
#else
/* HSE selected as PLL clock entry */
if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET)
{/* HSE oscillator clock divided by 2 */
SystemCoreClock = (HSE_VALUE >> 1) * pllmull;
}
else
{
SystemCoreClock = HSE_VALUE * pllmull;
}
#endif
}
#else
pllmull = pllmull >> 18;
if (pllmull != 0x0D)
{
pllmull += 2;
}
else
{ /* PLL multiplication factor = PLL input clock * 6.5 */
pllmull = 13 / 2;
}
if (pllsource == 0x00)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1) * pllmull;
}
else
{/* PREDIV1 selected as PLL clock entry */
/* Get PREDIV1 clock source and division factor */
prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1;
if (prediv1source == 0)
{
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
}
else
{/* PLL2 clock selected as PREDIV1 clock entry */
/* Get PREDIV2 division factor and PLL2 multiplication factor */
prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1;
pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2;
SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
}
}
#endif /* STM32F10X_CL */
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK clock frequency ----------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
/**
* @brief Configures the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers.
* @param None
* @retval None
*/
static void SetSysClock(void)
{
#ifdef SYSCLK_FREQ_HSE
SetSysClockToHSE();
#elif defined SYSCLK_FREQ_24MHz
SetSysClockTo24();
#elif defined SYSCLK_FREQ_36MHz
SetSysClockTo36();
#elif defined SYSCLK_FREQ_48MHz
SetSysClockTo48();
#elif defined SYSCLK_FREQ_56MHz
SetSysClockTo56();
#elif defined SYSCLK_FREQ_72MHz
SetSysClockTo72();
#endif
/* If none of the define above is enabled, the HSI is used as System clock
source (default after reset) */
}
/**
* @brief Setup the external memory controller. Called in startup_stm32f10x.s
* before jump to __main
* @param None
* @retval None
*/
#ifdef DATA_IN_ExtSRAM
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f10x_xx.s/.c before jump to main.
* This function configures the external SRAM mounted on STM3210E-EVAL
* board (STM32 High density devices). This SRAM will be used as program
* data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
/*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
required, then adjust the Register Addresses */
/* Enable FSMC clock */
RCC->AHBENR = 0x00000114;
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
RCC->APB2ENR = 0x000001E0;
/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
/*---------------- SRAM Address lines configuration -------------------------*/
/*---------------- NOE and NWE configuration --------------------------------*/
/*---------------- NE3 configuration ----------------------------------------*/
/*---------------- NBL0, NBL1 configuration ---------------------------------*/
GPIOD->CRL = 0x44BB44BB;
GPIOD->CRH = 0xBBBBBBBB;
GPIOE->CRL = 0xB44444BB;
GPIOE->CRH = 0xBBBBBBBB;
GPIOF->CRL = 0x44BBBBBB;
GPIOF->CRH = 0xBBBB4444;
GPIOG->CRL = 0x44BBBBBB;
GPIOG->CRH = 0x44444B44;
/*---------------- FSMC Configuration ---------------------------------------*/
/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
FSMC_Bank1->BTCR[4] = 0x00001011;
FSMC_Bank1->BTCR[5] = 0x00000200;
}
#endif /* DATA_IN_ExtSRAM */
#ifdef SYSCLK_FREQ_HSE
/**
* @brief Selects HSE as System clock source and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockToHSE(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
#if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 0 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
#ifndef STM32F10X_CL
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
#else
if (HSE_VALUE <= 24000000)
{
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
}
else
{
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
}
#endif /* STM32F10X_CL */
#endif
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
/* Select HSE as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_HSE;
/* Wait till HSE is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x04)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_24MHz
/**
* @brief Sets System clock frequency to 24MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo24(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
#if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 0 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
#endif
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL configuration: PLLCLK = PREDIV1 * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL6);
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
#elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)
/* PLL configuration: = (HSE / 2) * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLXTPRE_PREDIV1_Div2 | RCC_CFGR_PLLMULL6);
#else
/* PLL configuration: = (HSE / 2) * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL6);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_36MHz
/**
* @brief Sets System clock frequency to 36MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo36(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 1 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL configuration: PLLCLK = PREDIV1 * 9 = 36 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL9);
/*!< PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
#else
/* PLL configuration: PLLCLK = (HSE / 2) * 9 = 36 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL9);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_48MHz
/**
* @brief Sets System clock frequency to 48MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo48(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 1 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 6 = 48 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL6);
#else
/* PLL configuration: PLLCLK = HSE * 6 = 48 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL6);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_56MHz
/**
* @brief Sets System clock frequency to 56MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo56(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 2 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 7 = 56 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL7);
#else
/* PLL configuration: PLLCLK = HSE * 7 = 56 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL7);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_72MHz
/**
* @brief Sets System clock frequency to 72MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo72(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 2 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 9 = 72 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL9);
#else
/* PLL configuration: PLLCLK = HSE * 9 = 72 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE |
RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL9);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| bsd-3-clause |
dylanede/blaze-lib | blazetest/src/mathtest/dmatdmatmult/DDbSDb.cpp | 13 | 4287 | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatmult/DDbSDb.cpp
// \brief Source file for the DDbSDb dense matrix/dense matrix multiplication math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DDbSDb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> > DDb;
typedef blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeB> > SDb;
// Creator type definitions
typedef blazetest::Creator<DDb> CDDb;
typedef blazetest::Creator<SDb> CSDb;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( i ), CSDb( i ) );
}
// Running tests with large matrices
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 15UL ), CSDb( 15UL ) );
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 37UL ), CSDb( 37UL ) );
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 63UL ), CSDb( 63UL ) );
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 16UL ), CSDb( 16UL ) );
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 32UL ), CSDb( 32UL ) );
RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 64UL ), CSDb( 64UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| bsd-3-clause |
hoangt/goblin-core | riscv/llvm/3.5/cfe-3.5.0.src/test/CodeGen/volatile-2.c | 17 | 1188 | // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s
void test0() {
// CHECK-LABEL: define void @test0()
// CHECK: [[F:%.*]] = alloca float
// CHECK-NEXT: [[REAL:%.*]] = load volatile float* getelementptr inbounds ({ float, float }* @test0_v, i32 0, i32 0), align 4
// CHECK-NEXT: load volatile float* getelementptr inbounds ({{.*}} @test0_v, i32 0, i32 1), align 4
// CHECK-NEXT: store float [[REAL]], float* [[F]], align 4
// CHECK-NEXT: ret void
extern volatile _Complex float test0_v;
float f = (float) test0_v;
}
void test1() {
// CHECK-LABEL: define void @test1()
// CHECK: [[REAL:%.*]] = load volatile float* getelementptr inbounds ({{.*}} @test1_v, i32 0, i32 0), align 4
// CHECK-NEXT: [[IMAG:%.*]] = load volatile float* getelementptr inbounds ({{.*}} @test1_v, i32 0, i32 1), align 4
// CHECK-NEXT: store volatile float [[REAL]], float* getelementptr inbounds ({{.*}} @test1_v, i32 0, i32 0), align 4
// CHECK-NEXT: store volatile float [[IMAG]], float* getelementptr inbounds ({{.*}} @test1_v, i32 0, i32 1), align 4
// CHECK-NEXT: ret void
extern volatile _Complex float test1_v;
test1_v = test1_v;
}
| bsd-3-clause |
guorendong/iridium-browser-ubuntu | third_party/mesa/src/src/egl/main/eglarray.c | 17 | 4805 | /**************************************************************************
*
* Copyright 2010 LunarG, 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, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 <stdlib.h>
#include <string.h>
#include "egllog.h"
#include "eglarray.h"
/**
* Grow the size of the array.
*/
static EGLBoolean
_eglGrowArray(_EGLArray *array)
{
EGLint new_size;
void **elems;
new_size = array->MaxSize;
while (new_size <= array->Size)
new_size *= 2;
elems = realloc(array->Elements, new_size * sizeof(array->Elements[0]));
if (!elems) {
_eglLog(_EGL_DEBUG, "failed to grow %s array to %d",
array->Name, new_size);
return EGL_FALSE;
}
array->Elements = elems;
array->MaxSize = new_size;
return EGL_TRUE;
}
/**
* Create an array.
*/
_EGLArray *
_eglCreateArray(const char *name, EGLint init_size)
{
_EGLArray *array;
array = calloc(1, sizeof(*array));
if (array) {
array->Name = name;
array->MaxSize = (init_size > 0) ? init_size : 1;
if (!_eglGrowArray(array)) {
free(array);
array = NULL;
}
}
return array;
}
/**
* Destroy an array, optionally free the data.
*/
void
_eglDestroyArray(_EGLArray *array, void (*free_cb)(void *))
{
if (free_cb) {
EGLint i;
for (i = 0; i < array->Size; i++)
free_cb(array->Elements[i]);
}
free(array->Elements);
free(array);
}
/**
* Append a element to an array.
*/
void
_eglAppendArray(_EGLArray *array, void *elem)
{
if (array->Size >= array->MaxSize && !_eglGrowArray(array))
return;
array->Elements[array->Size++] = elem;
}
/**
* Erase an element from an array.
*/
void
_eglEraseArray(_EGLArray *array, EGLint i, void (*free_cb)(void *))
{
if (free_cb)
free_cb(array->Elements[i]);
if (i < array->Size - 1) {
memmove(&array->Elements[i], &array->Elements[i + 1],
(array->Size - i - 1) * sizeof(array->Elements[0]));
}
array->Size--;
}
/**
* Find in an array for the given element.
*/
void *
_eglFindArray(_EGLArray *array, void *elem)
{
EGLint i;
if (!array)
return NULL;
for (i = 0; i < array->Size; i++)
if (array->Elements[i] == elem)
return elem;
return NULL;
}
/**
* Filter an array and return the number of filtered elements.
*/
EGLint
_eglFilterArray(_EGLArray *array, void **data, EGLint size,
_EGLArrayForEach filter, void *filter_data)
{
EGLint count = 0, i;
if (!array)
return 0;
if (filter) {
for (i = 0; i < array->Size; i++) {
if (filter(array->Elements[i], filter_data)) {
if (data && count < size)
data[count] = array->Elements[i];
count++;
}
if (data && count >= size)
break;
}
}
else {
if (data) {
count = (size < array->Size) ? size : array->Size;
memcpy(data, array->Elements, count * sizeof(array->Elements[0]));
}
else {
count = array->Size;
}
}
return count;
}
/**
* Flatten an array by converting array elements into another form and store
* them in a buffer.
*/
EGLint
_eglFlattenArray(_EGLArray *array, void *buffer, EGLint elem_size, EGLint size,
_EGLArrayForEach flatten)
{
EGLint i, count;
if (!array)
return 0;
count = array->Size;
if (buffer) {
/* do not exceed buffer size */
if (count > size)
count = size;
for (i = 0; i < count; i++)
flatten(array->Elements[i],
(void *) ((char *) buffer + elem_size * i));
}
return count;
}
| bsd-3-clause |
aashish24/VTK-old | ThirdParty/ftgl/src/FTFont.cpp | 17 | 5236 | #include "FTFace.h"
#include "FTFont.h"
#include "FTGlyphContainer.h"
#include "FTGlyph.h" // for FTBbox
#ifdef FTGL_DEBUG
#include "mmgr.h"
#endif
#ifdef FTGL_USE_NAMESPACE
namespace ftgl
{
#endif
FTFont::FTFont()
: numFaces(0),
glyphList(0),
numGlyphs(0),
preCache(true),
err(0)
{
pen.x = 0;
pen.y = 0;
}
FTFont::~FTFont()
{
Close();
}
bool FTFont::Open( const char* fontname, bool p)
{
preCache = p;
if( face.Open( fontname))
{
FT_Face* ftFace = face.Face();
numGlyphs = (*ftFace)->num_glyphs;
return true;
}
else
{
err = face.Error();
return false;
}
}
bool FTFont::Open( const unsigned char *pBufferBytes, size_t bufferSizeInBytes, bool p )
{
preCache = p;
if( face.Open( pBufferBytes, bufferSizeInBytes ))
{
FT_Face* ftFace = face.Face();
numGlyphs = (*ftFace)->num_glyphs;
return true;
}
else
{
err = face.Error();
return false;
}
}
bool FTFont::Attach( const char* filename)
{
return face.Attach( filename);
}
void FTFont::Close()
{
delete glyphList;
}
bool FTFont::FaceSize( const unsigned int size, const unsigned int res )
{
charSize = face.Size( size, res);
if( glyphList)
delete glyphList;
glyphList = new FTGlyphContainer( &face, numGlyphs, preCache);
if( preCache)
{
return MakeGlyphList() ? true : false;
}
return true;
}
bool FTFont::MakeGlyphList()
{
if( preCache)
{
for( unsigned int c = 0; c < numGlyphs; ++c)
{
glyphList->Add( MakeGlyph( c), c);
}
}
else
{
for( unsigned int c = 0; c < numGlyphs; ++c)
{
glyphList->Add( NULL, c);
}
}
return !err; // FIXME what err?
}
bool FTFont::CharMap( FT_Encoding encoding)
{
err = face.CharMap( encoding);
return !err;
}
int FTFont::Ascender() const
{
return charSize.Ascender();
}
int FTFont::Descender() const
{
return charSize.Descender();
}
void FTFont::BBox( const char* string,
float& llx, float& lly, float& llz, float& urx, float& ury, float& urz)
{
const unsigned char* c = (unsigned char*)string;
llx = lly = llz = urx = ury = urz = 0;
FTBBox bbox;
while( *c)
{
if( !glyphList->Glyph( static_cast<unsigned int>(*c)))
{
unsigned int g = face.CharIndex( static_cast<unsigned int>(*c));
glyphList->Add( MakeGlyph( g), g);
}
bbox = glyphList->BBox( *c);
// Lower extent
lly = lly < bbox.y1 ? lly: bbox.y1;
// Upper extent
ury = ury > bbox.y2 ? ury: bbox.y2;
// Depth
urz = urz < bbox.z2 ? urz: bbox.z2;
// Width
urx += glyphList->Advance( *c, *(c + 1));
++c;
}
//Final adjustments
llx = glyphList->BBox( *string).x1;
urx -= glyphList->Advance( *(c - 1), 0);
urx += bbox.x2;
}
void FTFont::BBox( const wchar_t* string,
float& llx, float& lly, float& llz, float& urx, float& ury, float& urz)
{
const wchar_t* c = string;
llx = lly = llz = urx = ury = urz = 0;
FTBBox bbox;
while( *c)
{
if( !glyphList->Glyph( static_cast<unsigned int>(*c)))
{
unsigned int g = face.CharIndex( static_cast<unsigned int>(*c));
glyphList->Add( MakeGlyph( g), g);
}
bbox = glyphList->BBox( *c);
// Lower extent
lly = lly < bbox.y1 ? lly: bbox.y1;
// Upper extent
ury = ury > bbox.y2 ? ury: bbox.y2;
// Depth
urz = urz < bbox.z2 ? urz: bbox.z2;
// Width
urx += glyphList->Advance( *c, *(c + 1));
++c;
}
//Final adjustments
llx = glyphList->BBox( *string).x1;
urx -= glyphList->Advance( *(c - 1), 0);
urx += bbox.x2;
}
float FTFont::Advance( const wchar_t* string)
{
const wchar_t* c = string;
float width = 0;
while( *c)
{
width += doAdvance( *c, *(c + 1));
++c;
}
return width;
}
float FTFont::Advance( const char* string)
{
const unsigned char* c = (unsigned char*)string;
float width = 0;
while( *c)
{
width += doAdvance( *c, *(c + 1));
++c;
}
return width;
}
float FTFont::doAdvance( const unsigned int chr, const unsigned int nextChr)
{
if( !glyphList->Glyph( chr))
{
unsigned int g = face.CharIndex( chr);
glyphList->Add( MakeGlyph( g), g);
}
return glyphList->Advance( chr, nextChr);
}
void FTFont::render( const char* string,
const FTGLRenderContext *context)
{
const unsigned char* c = (unsigned char*)string;
pen.x = 0; pen.y = 0;
while( *c)
{
doRender( *c, *(c + 1), context);
++c;
}
}
void FTFont::render( const wchar_t* string,
const FTGLRenderContext *context)
{
const wchar_t* c = string;
pen.x = 0; pen.y = 0;
while( *c)
{
doRender( *c, *(c + 1), context);
++c;
}
}
void FTFont::doRender( const unsigned int chr,
const unsigned int nextChr,
const FTGLRenderContext *context)
{
if( !glyphList->Glyph( chr))
{
unsigned int g = face.CharIndex( chr);
glyphList->Add( MakeGlyph( g), g);
}
FT_Vector kernAdvance = glyphList->render( chr, nextChr, pen, context);
pen.x += kernAdvance.x;
pen.y += kernAdvance.y;
}
#ifdef FTGL_USE_NAMESPACE
} // namespace ftgl
#endif
| bsd-3-clause |
WarrenWeckesser/scipy | scipy/integrate/odepack/lsoda.f | 18 | 78159 | subroutine lsoda (f, neq, y, t, tout, itol, rtol, atol, itask,
1 istate, iopt, rwork, lrw, iwork, liw, jac, jt)
external f, jac
integer neq, itol, itask, istate, iopt, lrw, iwork, liw, jt, isav
double precision y, t, tout, rtol, atol, rwork, rsav
dimension neq(1), y(1), rtol(1), atol(1), rwork(lrw), iwork(liw)
dimension rsav(240), isav(50)
c-----------------------------------------------------------------------
c this is the 24 feb 1997 version of
c lsoda.. livermore solver for ordinary differential equations, with
c automatic method switching for stiff and nonstiff problems.
c
c this version is in double precision.
c
c lsoda solves the initial value problem for stiff or nonstiff
c systems of first order ode-s,
c dy/dt = f(t,y) , or, in component form,
c dy(i)/dt = f(i) = f(i,t,y(1),y(2),...,y(neq)) (i = 1,...,neq).
c
c this a variant version of the lsode package.
c it switches automatically between stiff and nonstiff methods.
c this means that the user does not have to determine whether the
c problem is stiff or not, and the solver will automatically choose the
c appropriate method. it always starts with the nonstiff method.
c
c authors..
c linda r. petzold and alan c. hindmarsh,
c computing and mathematics research division, l-316
c lawrence livermore national laboratory
c livermore, ca 94550.
c
c references..
c 1. alan c. hindmarsh, odepack, a systematized collection of ode
c solvers, in scientific computing, r. s. stepleman et al. (eds.),
c north-holland, amsterdam, 1983, pp. 55-64.
c 2. linda r. petzold, automatic selection of methods for solving
c stiff and nonstiff systems of ordinary differential equations,
c siam j. sci. stat. comput. 4 (1983), pp. 136-148.
c-----------------------------------------------------------------------
c summary of usage.
c
c communication between the user and the lsoda package, for normal
c situations, is summarized here. this summary describes only a subset
c of the full set of options available. see the full description for
c details, including alternative treatment of the jacobian matrix,
c optional inputs and outputs, nonstandard options, and
c instructions for special situations. see also the example
c problem (with program and output) following this summary.
c
c a. first provide a subroutine of the form..
c subroutine f (neq, t, y, ydot)
c dimension y(neq), ydot(neq)
c which supplies the vector function f by loading ydot(i) with f(i).
c
c b. write a main program which calls subroutine lsoda once for
c each point at which answers are desired. this should also provide
c for possible use of logical unit 6 for output of error messages
c by lsoda. on the first call to lsoda, supply arguments as follows..
c f = name of subroutine for right-hand side vector f.
c this name must be declared external in calling program.
c neq = number of first order ode-s.
c y = array of initial values, of length neq.
c t = the initial value of the independent variable.
c tout = first point where output is desired (.ne. t).
c itol = 1 or 2 according as atol (below) is a scalar or array.
c rtol = relative tolerance parameter (scalar).
c atol = absolute tolerance parameter (scalar or array).
c the estimated local error in y(i) will be controlled so as
c to be less than
c ewt(i) = rtol*abs(y(i)) + atol if itol = 1, or
c ewt(i) = rtol*abs(y(i)) + atol(i) if itol = 2.
c thus the local error test passes if, in each component,
c either the absolute error is less than atol (or atol(i)),
c or the relative error is less than rtol.
c use rtol = 0.0 for pure absolute error control, and
c use atol = 0.0 (or atol(i) = 0.0) for pure relative error
c control. caution.. actual (global) errors may exceed these
c local tolerances, so choose them conservatively.
c itask = 1 for normal computation of output values of y at t = tout.
c istate = integer flag (input and output). set istate = 1.
c iopt = 0 to indicate no optional inputs used.
c rwork = real work array of length at least..
c 22 + neq * max(16, neq + 9).
c see also paragraph e below.
c lrw = declared length of rwork (in user-s dimension).
c iwork = integer work array of length at least 20 + neq.
c liw = declared length of iwork (in user-s dimension).
c jac = name of subroutine for jacobian matrix.
c use a dummy name. see also paragraph e below.
c jt = jacobian type indicator. set jt = 2.
c see also paragraph e below.
c note that the main program must declare arrays y, rwork, iwork,
c and possibly atol.
c
c c. the output from the first call (or any call) is..
c y = array of computed values of y(t) vector.
c t = corresponding value of independent variable (normally tout).
c istate = 2 if lsoda was successful, negative otherwise.
c -1 means excess work done on this call (perhaps wrong jt).
c -2 means excess accuracy requested (tolerances too small).
c -3 means illegal input detected (see printed message).
c -4 means repeated error test failures (check all inputs).
c -5 means repeated convergence failures (perhaps bad jacobian
c supplied or wrong choice of jt or tolerances).
c -6 means error weight became zero during problem. (solution
c component i vanished, and atol or atol(i) = 0.)
c -7 means work space insufficient to finish (see messages).
c
c d. to continue the integration after a successful return, simply
c reset tout and call lsoda again. no other parameters need be reset.
c
c e. note.. if and when lsoda regards the problem as stiff, and
c switches methods accordingly, it must make use of the neq by neq
c jacobian matrix, j = df/dy. for the sake of simplicity, the
c inputs to lsoda recommended in paragraph b above cause lsoda to
c treat j as a full matrix, and to approximate it internally by
c difference quotients. alternatively, j can be treated as a band
c matrix (with great potential reduction in the size of the rwork
c array). also, in either the full or banded case, the user can supply
c j in closed form, with a routine whose name is passed as the jac
c argument. these alternatives are described in the paragraphs on
c rwork, jac, and jt in the full description of the call sequence below.
c
c-----------------------------------------------------------------------
c example problem.
c
c the following is a simple example problem, with the coding
c needed for its solution by lsoda. the problem is from chemical
c kinetics, and consists of the following three rate equations..
c dy1/dt = -.04*y1 + 1.e4*y2*y3
c dy2/dt = .04*y1 - 1.e4*y2*y3 - 3.e7*y2**2
c dy3/dt = 3.e7*y2**2
c on the interval from t = 0.0 to t = 4.e10, with initial conditions
c y1 = 1.0, y2 = y3 = 0. the problem is stiff.
c
c the following coding solves this problem with lsoda,
c printing results at t = .4, 4., ..., 4.e10. it uses
c itol = 2 and atol much smaller for y2 than y1 or y3 because
c y2 has much smaller values.
c at the end of the run, statistical quantities of interest are
c printed (see optional outputs in the full description below).
c
c external fex
c double precision atol, rtol, rwork, t, tout, y
c dimension y(3), atol(3), rwork(70), iwork(23)
c neq = 3
c y(1) = 1.0d0
c y(2) = 0.0d0
c y(3) = 0.0d0
c t = 0.0d0
c tout = 0.4d0
c itol = 2
c rtol = 1.0d-4
c atol(1) = 1.0d-6
c atol(2) = 1.0d-10
c atol(3) = 1.0d-6
c itask = 1
c istate = 1
c iopt = 0
c lrw = 70
c liw = 23
c jt = 2
c do 40 iout = 1,12
c call lsoda(fex,neq,y,t,tout,itol,rtol,atol,itask,istate,
c 1 iopt,rwork,lrw,iwork,liw,jdum,jt)
c write(6,20)t,y(1),y(2),y(3)
c 20 format(' at t =',e12.4,' y =',3e14.6)
c if (istate .lt. 0) go to 80
c 40 tout = tout*10.0d0
c write(6,60)iwork(11),iwork(12),iwork(13),iwork(19),rwork(15)
c 60 format(/' no. steps =',i4,' no. f-s =',i4,' no. j-s =',i4/
c 1 ' method last used =',i2,' last switch was at t =',e12.4)
c stop
c 80 write(6,90)istate
c 90 format(///' error halt.. istate =',i3)
c stop
c end
c
c subroutine fex (neq, t, y, ydot)
c double precision t, y, ydot
c dimension y(3), ydot(3)
c ydot(1) = -.04d0*y(1) + 1.0d4*y(2)*y(3)
c ydot(3) = 3.0d7*y(2)*y(2)
c ydot(2) = -ydot(1) - ydot(3)
c return
c end
c
c the output of this program (on a cdc-7600 in single precision)
c is as follows..
c
c at t = 4.0000e-01 y = 9.851712e-01 3.386380e-05 1.479493e-02
c at t = 4.0000e+00 y = 9.055333e-01 2.240655e-05 9.444430e-02
c at t = 4.0000e+01 y = 7.158403e-01 9.186334e-06 2.841505e-01
c at t = 4.0000e+02 y = 4.505250e-01 3.222964e-06 5.494717e-01
c at t = 4.0000e+03 y = 1.831975e-01 8.941774e-07 8.168016e-01
c at t = 4.0000e+04 y = 3.898730e-02 1.621940e-07 9.610125e-01
c at t = 4.0000e+05 y = 4.936363e-03 1.984221e-08 9.950636e-01
c at t = 4.0000e+06 y = 5.161831e-04 2.065786e-09 9.994838e-01
c at t = 4.0000e+07 y = 5.179817e-05 2.072032e-10 9.999482e-01
c at t = 4.0000e+08 y = 5.283401e-06 2.113371e-11 9.999947e-01
c at t = 4.0000e+09 y = 4.659031e-07 1.863613e-12 9.999995e-01
c at t = 4.0000e+10 y = 1.404280e-08 5.617126e-14 1.000000e+00
c
c no. steps = 361 no. f-s = 693 no. j-s = 64
c method last used = 2 last switch was at t = 6.0092e-03
c-----------------------------------------------------------------------
c full description of user interface to lsoda.
c
c the user interface to lsoda consists of the following parts.
c
c i. the call sequence to subroutine lsoda, which is a driver
c routine for the solver. this includes descriptions of both
c the call sequence arguments and of user-supplied routines.
c following these descriptions is a description of
c optional inputs available through the call sequence, and then
c a description of optional outputs (in the work arrays).
c
c ii. descriptions of other routines in the lsoda package that may be
c (optionally) called by the user. these provide the ability to
c alter error message handling, save and restore the internal
c common, and obtain specified derivatives of the solution y(t).
c
c iii. descriptions of common blocks to be declared in overlay
c or similar environments, or to be saved when doing an interrupt
c of the problem and continued solution later.
c
c iv. description of a subroutine in the lsoda package,
c which the user may replace with his own version, if desired.
c this relates to the measurement of errors.
c
c-----------------------------------------------------------------------
c part i. call sequence.
c
c the call sequence parameters used for input only are
c f, neq, tout, itol, rtol, atol, itask, iopt, lrw, liw, jac, jt,
c and those used for both input and output are
c y, t, istate.
c the work arrays rwork and iwork are also used for conditional and
c optional inputs and optional outputs. (the term output here refers
c to the return from subroutine lsoda to the user-s calling program.)
c
c the legality of input parameters will be thoroughly checked on the
c initial call for the problem, but not checked thereafter unless a
c change in input parameters is flagged by istate = 3 on input.
c
c the descriptions of the call arguments are as follows.
c
c f = the name of the user-supplied subroutine defining the
c ode system. the system must be put in the first-order
c form dy/dt = f(t,y), where f is a vector-valued function
c of the scalar t and the vector y. subroutine f is to
c compute the function f. it is to have the form
c subroutine f (neq, t, y, ydot)
c dimension y(1), ydot(1)
c where neq, t, and y are input, and the array ydot = f(t,y)
c is output. y and ydot are arrays of length neq.
c (in the dimension statement above, 1 is a dummy
c dimension.. it can be replaced by any value.)
c subroutine f should not alter y(1),...,y(neq).
c f must be declared external in the calling program.
c
c subroutine f may access user-defined quantities in
c neq(2),... and/or in y(neq(1)+1),... if neq is an array
c (dimensioned in f) and/or y has length exceeding neq(1).
c see the descriptions of neq and y below.
c
c if quantities computed in the f routine are needed
c externally to lsoda, an extra call to f should be made
c for this purpose, for consistent and accurate results.
c if only the derivative dy/dt is needed, use intdy instead.
c
c neq = the size of the ode system (number of first order
c ordinary differential equations). used only for input.
c neq may be decreased, but not increased, during the problem.
c if neq is decreased (with istate = 3 on input), the
c remaining components of y should be left undisturbed, if
c these are to be accessed in f and/or jac.
c
c normally, neq is a scalar, and it is generally referred to
c as a scalar in this user interface description. however,
c neq may be an array, with neq(1) set to the system size.
c (the lsoda package accesses only neq(1).) in either case,
c this parameter is passed as the neq argument in all calls
c to f and jac. hence, if it is an array, locations
c neq(2),... may be used to store other integer data and pass
c it to f and/or jac. subroutines f and/or jac must include
c neq in a dimension statement in that case.
c
c y = a real array for the vector of dependent variables, of
c length neq or more. used for both input and output on the
c first call (istate = 1), and only for output on other calls.
c on the first call, y must contain the vector of initial
c values. on output, y contains the computed solution vector,
c evaluated at t. if desired, the y array may be used
c for other purposes between calls to the solver.
c
c this array is passed as the y argument in all calls to
c f and jac. hence its length may exceed neq, and locations
c y(neq+1),... may be used to store other real data and
c pass it to f and/or jac. (the lsoda package accesses only
c y(1),...,y(neq).)
c
c t = the independent variable. on input, t is used only on the
c first call, as the initial point of the integration.
c on output, after each call, t is the value at which a
c computed solution y is evaluated (usually the same as tout).
c on an error return, t is the farthest point reached.
c
c tout = the next value of t at which a computed solution is desired.
c used only for input.
c
c when starting the problem (istate = 1), tout may be equal
c to t for one call, then should .ne. t for the next call.
c for the initial t, an input value of tout .ne. t is used
c in order to determine the direction of the integration
c (i.e. the algebraic sign of the step sizes) and the rough
c scale of the problem. integration in either direction
c (forward or backward in t) is permitted.
c
c if itask = 2 or 5 (one-step modes), tout is ignored after
c the first call (i.e. the first call with tout .ne. t).
c otherwise, tout is required on every call.
c
c if itask = 1, 3, or 4, the values of tout need not be
c monotone, but a value of tout which backs up is limited
c to the current internal t interval, whose endpoints are
c tcur - hu and tcur (see optional outputs, below, for
c tcur and hu).
c
c itol = an indicator for the type of error control. see
c description below under atol. used only for input.
c
c rtol = a relative error tolerance parameter, either a scalar or
c an array of length neq. see description below under atol.
c input only.
c
c atol = an absolute error tolerance parameter, either a scalar or
c an array of length neq. input only.
c
c the input parameters itol, rtol, and atol determine
c the error control performed by the solver. the solver will
c control the vector e = (e(i)) of estimated local errors
c in y, according to an inequality of the form
c max-norm of ( e(i)/ewt(i) ) .le. 1,
c where ewt = (ewt(i)) is a vector of positive error weights.
c the values of rtol and atol should all be non-negative.
c the following table gives the types (scalar/array) of
c rtol and atol, and the corresponding form of ewt(i).
c
c itol rtol atol ewt(i)
c 1 scalar scalar rtol*abs(y(i)) + atol
c 2 scalar array rtol*abs(y(i)) + atol(i)
c 3 array scalar rtol(i)*abs(y(i)) + atol
c 4 array array rtol(i)*abs(y(i)) + atol(i)
c
c when either of these parameters is a scalar, it need not
c be dimensioned in the user-s calling program.
c
c if none of the above choices (with itol, rtol, and atol
c fixed throughout the problem) is suitable, more general
c error controls can be obtained by substituting a
c user-supplied routine for the setting of ewt.
c see part iv below.
c
c if global errors are to be estimated by making a repeated
c run on the same problem with smaller tolerances, then all
c components of rtol and atol (i.e. of ewt) should be scaled
c down uniformly.
c
c itask = an index specifying the task to be performed.
c input only. itask has the following values and meanings.
c 1 means normal computation of output values of y(t) at
c t = tout (by overshooting and interpolating).
c 2 means take one step only and return.
c 3 means stop at the first internal mesh point at or
c beyond t = tout and return.
c 4 means normal computation of output values of y(t) at
c t = tout but without overshooting t = tcrit.
c tcrit must be input as rwork(1). tcrit may be equal to
c or beyond tout, but not behind it in the direction of
c integration. this option is useful if the problem
c has a singularity at or beyond t = tcrit.
c 5 means take one step, without passing tcrit, and return.
c tcrit must be input as rwork(1).
c
c note.. if itask = 4 or 5 and the solver reaches tcrit
c (within roundoff), it will return t = tcrit (exactly) to
c indicate this (unless itask = 4 and tout comes before tcrit,
c in which case answers at t = tout are returned first).
c
c istate = an index used for input and output to specify the
c the state of the calculation.
c
c on input, the values of istate are as follows.
c 1 means this is the first call for the problem
c (initializations will be done). see note below.
c 2 means this is not the first call, and the calculation
c is to continue normally, with no change in any input
c parameters except possibly tout and itask.
c (if itol, rtol, and/or atol are changed between calls
c with istate = 2, the new values will be used but not
c tested for legality.)
c 3 means this is not the first call, and the
c calculation is to continue normally, but with
c a change in input parameters other than
c tout and itask. changes are allowed in
c neq, itol, rtol, atol, iopt, lrw, liw, jt, ml, mu,
c and any optional inputs except h0, mxordn, and mxords.
c (see iwork description for ml and mu.)
c note.. a preliminary call with tout = t is not counted
c as a first call here, as no initialization or checking of
c input is done. (such a call is sometimes useful for the
c purpose of outputting the initial conditions.)
c thus the first call for which tout .ne. t requires
c istate = 1 on input.
c
c on output, istate has the following values and meanings.
c 1 means nothing was done, as tout was equal to t with
c istate = 1 on input. (however, an internal counter was
c set to detect and prevent repeated calls of this type.)
c 2 means the integration was performed successfully.
c -1 means an excessive amount of work (more than mxstep
c steps) was done on this call, before completing the
c requested task, but the integration was otherwise
c successful as far as t. (mxstep is an optional input
c and is normally 500.) to continue, the user may
c simply reset istate to a value .gt. 1 and call again
c (the excess work step counter will be reset to 0).
c in addition, the user may increase mxstep to avoid
c this error return (see below on optional inputs).
c -2 means too much accuracy was requested for the precision
c of the machine being used. this was detected before
c completing the requested task, but the integration
c was successful as far as t. to continue, the tolerance
c parameters must be reset, and istate must be set
c to 3. the optional output tolsf may be used for this
c purpose. (note.. if this condition is detected before
c taking any steps, then an illegal input return
c (istate = -3) occurs instead.)
c -3 means illegal input was detected, before taking any
c integration steps. see written message for details.
c note.. if the solver detects an infinite loop of calls
c to the solver with illegal input, it will cause
c the run to stop.
c -4 means there were repeated error test failures on
c one attempted step, before completing the requested
c task, but the integration was successful as far as t.
c the problem may have a singularity, or the input
c may be inappropriate.
c -5 means there were repeated convergence test failures on
c one attempted step, before completing the requested
c task, but the integration was successful as far as t.
c this may be caused by an inaccurate jacobian matrix,
c if one is being used.
c -6 means ewt(i) became zero for some i during the
c integration. pure relative error control (atol(i)=0.0)
c was requested on a variable which has now vanished.
c the integration was successful as far as t.
c -7 means the length of rwork and/or iwork was too small to
c proceed, but the integration was successful as far as t.
c this happens when lsoda chooses to switch methods
c but lrw and/or liw is too small for the new method.
c
c note.. since the normal output value of istate is 2,
c it does not need to be reset for normal continuation.
c also, since a negative input value of istate will be
c regarded as illegal, a negative output value requires the
c user to change it, and possibly other inputs, before
c calling the solver again.
c
c iopt = an integer flag to specify whether or not any optional
c inputs are being used on this call. input only.
c the optional inputs are listed separately below.
c iopt = 0 means no optional inputs are being used.
c default values will be used in all cases.
c iopt = 1 means one or more optional inputs are being used.
c
c rwork = a real array (double precision) for work space, and (in the
c first 20 words) for conditional and optional inputs and
c optional outputs.
c as lsoda switches automatically between stiff and nonstiff
c methods, the required length of rwork can change during the
c problem. thus the rwork array passed to lsoda can either
c have a static (fixed) length large enough for both methods,
c or have a dynamic (changing) length altered by the calling
c program in response to output from lsoda.
c
c --- fixed length case ---
c if the rwork length is to be fixed, it should be at least
c max (lrn, lrs),
c where lrn and lrs are the rwork lengths required when the
c current method is nonstiff or stiff, respectively.
c
c the separate rwork length requirements lrn and lrs are
c as follows..
c if neq is constant and the maximum method orders have
c their default values, then
c lrn = 20 + 16*neq,
c lrs = 22 + 9*neq + neq**2 if jt = 1 or 2,
c lrs = 22 + 10*neq + (2*ml+mu)*neq if jt = 4 or 5.
c under any other conditions, lrn and lrs are given by..
c lrn = 20 + nyh*(mxordn+1) + 3*neq,
c lrs = 20 + nyh*(mxords+1) + 3*neq + lmat,
c where
c nyh = the initial value of neq,
c mxordn = 12, unless a smaller value is given as an
c optional input,
c mxords = 5, unless a smaller value is given as an
c optional input,
c lmat = length of matrix work space..
c lmat = neq**2 + 2 if jt = 1 or 2,
c lmat = (2*ml + mu + 1)*neq + 2 if jt = 4 or 5.
c
c --- dynamic length case ---
c if the length of rwork is to be dynamic, then it should
c be at least lrn or lrs, as defined above, depending on the
c current method. initially, it must be at least lrn (since
c lsoda starts with the nonstiff method). on any return
c from lsoda, the optional output mcur indicates the current
c method. if mcur differs from the value it had on the
c previous return, or if there has only been one call to
c lsoda and mcur is now 2, then lsoda has switched
c methods during the last call, and the length of rwork
c should be reset (to lrn if mcur = 1, or to lrs if
c mcur = 2). (an increase in the rwork length is required
c if lsoda returned istate = -7, but not otherwise.)
c after resetting the length, call lsoda with istate = 3
c to signal that change.
c
c lrw = the length of the array rwork, as declared by the user.
c (this will be checked by the solver.)
c
c iwork = an integer array for work space.
c as lsoda switches automatically between stiff and nonstiff
c methods, the required length of iwork can change during
c problem, between
c lis = 20 + neq and lin = 20,
c respectively. thus the iwork array passed to lsoda can
c either have a fixed length of at least 20 + neq, or have a
c dynamic length of at least lin or lis, depending on the
c current method. the comments on dynamic length under
c rwork above apply here. initially, this length need
c only be at least lin = 20.
c
c the first few words of iwork are used for conditional and
c optional inputs and optional outputs.
c
c the following 2 words in iwork are conditional inputs..
c iwork(1) = ml these are the lower and upper
c iwork(2) = mu half-bandwidths, respectively, of the
c banded jacobian, excluding the main diagonal.
c the band is defined by the matrix locations
c (i,j) with i-ml .le. j .le. i+mu. ml and mu
c must satisfy 0 .le. ml,mu .le. neq-1.
c these are required if jt is 4 or 5, and
c ignored otherwise. ml and mu may in fact be
c the band parameters for a matrix to which
c df/dy is only approximately equal.
c
c liw = the length of the array iwork, as declared by the user.
c (this will be checked by the solver.)
c
c note.. the base addresses of the work arrays must not be
c altered between calls to lsoda for the same problem.
c the contents of the work arrays must not be altered
c between calls, except possibly for the conditional and
c optional inputs, and except for the last 3*neq words of rwork.
c the latter space is used for internal scratch space, and so is
c available for use by the user outside lsoda between calls, if
c desired (but not for use by f or jac).
c
c jac = the name of the user-supplied routine to compute the
c jacobian matrix, df/dy, if jt = 1 or 4. the jac routine
c is optional, but if the problem is expected to be stiff much
c of the time, you are encouraged to supply jac, for the sake
c of efficiency. (alternatively, set jt = 2 or 5 to have
c lsoda compute df/dy internally by difference quotients.)
c if and when lsoda uses df/dy, if treats this neq by neq
c matrix either as full (jt = 1 or 2), or as banded (jt =
c 4 or 5) with half-bandwidths ml and mu (discussed under
c iwork above). in either case, if jt = 1 or 4, the jac
c routine must compute df/dy as a function of the scalar t
c and the vector y. it is to have the form
c subroutine jac (neq, t, y, ml, mu, pd, nrowpd)
c dimension y(1), pd(nrowpd,1)
c where neq, t, y, ml, mu, and nrowpd are input and the array
c pd is to be loaded with partial derivatives (elements of
c the jacobian matrix) on output. pd must be given a first
c dimension of nrowpd. t and y have the same meaning as in
c subroutine f. (in the dimension statement above, 1 is a
c dummy dimension.. it can be replaced by any value.)
c in the full matrix case (jt = 1), ml and mu are
c ignored, and the jacobian is to be loaded into pd in
c columnwise manner, with df(i)/dy(j) loaded into pd(i,j).
c in the band matrix case (jt = 4), the elements
c within the band are to be loaded into pd in columnwise
c manner, with diagonal lines of df/dy loaded into the rows
c of pd. thus df(i)/dy(j) is to be loaded into pd(i-j+mu+1,j).
c ml and mu are the half-bandwidth parameters (see iwork).
c the locations in pd in the two triangular areas which
c correspond to nonexistent matrix elements can be ignored
c or loaded arbitrarily, as they are overwritten by lsoda.
c jac need not provide df/dy exactly. a crude
c approximation (possibly with a smaller bandwidth) will do.
c in either case, pd is preset to zero by the solver,
c so that only the nonzero elements need be loaded by jac.
c each call to jac is preceded by a call to f with the same
c arguments neq, t, and y. thus to gain some efficiency,
c intermediate quantities shared by both calculations may be
c saved in a user common block by f and not recomputed by jac,
c if desired. also, jac may alter the y array, if desired.
c jac must be declared external in the calling program.
c subroutine jac may access user-defined quantities in
c neq(2),... and/or in y(neq(1)+1),... if neq is an array
c (dimensioned in jac) and/or y has length exceeding neq(1).
c see the descriptions of neq and y above.
c
c jt = jacobian type indicator. used only for input.
c jt specifies how the jacobian matrix df/dy will be
c treated, if and when lsoda requires this matrix.
c jt has the following values and meanings..
c 1 means a user-supplied full (neq by neq) jacobian.
c 2 means an internally generated (difference quotient) full
c jacobian (using neq extra calls to f per df/dy value).
c 4 means a user-supplied banded jacobian.
c 5 means an internally generated banded jacobian (using
c ml+mu+1 extra calls to f per df/dy evaluation).
c if jt = 1 or 4, the user must supply a subroutine jac
c (the name is arbitrary) as described above under jac.
c if jt = 2 or 5, a dummy argument can be used.
c-----------------------------------------------------------------------
c optional inputs.
c
c the following is a list of the optional inputs provided for in the
c call sequence. (see also part ii.) for each such input variable,
c this table lists its name as used in this documentation, its
c location in the call sequence, its meaning, and the default value.
c the use of any of these inputs requires iopt = 1, and in that
c case all of these inputs are examined. a value of zero for any
c of these optional inputs will cause the default value to be used.
c thus to use a subset of the optional inputs, simply preload
c locations 5 to 10 in rwork and iwork to 0.0 and 0 respectively, and
c then set those of interest to nonzero values.
c
c name location meaning and default value
c
c h0 rwork(5) the step size to be attempted on the first step.
c the default value is determined by the solver.
c
c hmax rwork(6) the maximum absolute step size allowed.
c the default value is infinite.
c
c hmin rwork(7) the minimum absolute step size allowed.
c the default value is 0. (this lower bound is not
c enforced on the final step before reaching tcrit
c when itask = 4 or 5.)
c
c ixpr iwork(5) flag to generate extra printing at method switches.
c ixpr = 0 means no extra printing (the default).
c ixpr = 1 means print data on each switch.
c t, h, and nst will be printed on the same logical
c unit as used for error messages.
c
c mxstep iwork(6) maximum number of (internally defined) steps
c allowed during one call to the solver.
c the default value is 500.
c
c mxhnil iwork(7) maximum number of messages printed (per problem)
c warning that t + h = t on a step (h = step size).
c this must be positive to result in a non-default
c value. the default value is 10.
c
c mxordn iwork(8) the maximum order to be allowed for the nonstiff
c (adams) method. the default value is 12.
c if mxordn exceeds the default value, it will
c be reduced to the default value.
c mxordn is held constant during the problem.
c
c mxords iwork(9) the maximum order to be allowed for the stiff
c (bdf) method. the default value is 5.
c if mxords exceeds the default value, it will
c be reduced to the default value.
c mxords is held constant during the problem.
c-----------------------------------------------------------------------
c optional outputs.
c
c as optional additional output from lsoda, the variables listed
c below are quantities related to the performance of lsoda
c which are available to the user. these are communicated by way of
c the work arrays, but also have internal mnemonic names as shown.
c except where stated otherwise, all of these outputs are defined
c on any successful return from lsoda, and on any return with
c istate = -1, -2, -4, -5, or -6. on an illegal input return
c (istate = -3), they will be unchanged from their existing values
c (if any), except possibly for tolsf, lenrw, and leniw.
c on any error return, outputs relevant to the error will be defined,
c as noted below.
c
c name location meaning
c
c hu rwork(11) the step size in t last used (successfully).
c
c hcur rwork(12) the step size to be attempted on the next step.
c
c tcur rwork(13) the current value of the independent variable
c which the solver has actually reached, i.e. the
c current internal mesh point in t. on output, tcur
c will always be at least as far as the argument
c t, but may be farther (if interpolation was done).
c
c tolsf rwork(14) a tolerance scale factor, greater than 1.0,
c computed when a request for too much accuracy was
c detected (istate = -3 if detected at the start of
c the problem, istate = -2 otherwise). if itol is
c left unaltered but rtol and atol are uniformly
c scaled up by a factor of tolsf for the next call,
c then the solver is deemed likely to succeed.
c (the user may also ignore tolsf and alter the
c tolerance parameters in any other way appropriate.)
c
c tsw rwork(15) the value of t at the time of the last method
c switch, if any.
c
c nst iwork(11) the number of steps taken for the problem so far.
c
c nfe iwork(12) the number of f evaluations for the problem so far.
c
c nje iwork(13) the number of jacobian evaluations (and of matrix
c lu decompositions) for the problem so far.
c
c nqu iwork(14) the method order last used (successfully).
c
c nqcur iwork(15) the order to be attempted on the next step.
c
c imxer iwork(16) the index of the component of largest magnitude in
c the weighted local error vector ( e(i)/ewt(i) ),
c on an error return with istate = -4 or -5.
c
c lenrw iwork(17) the length of rwork actually required, assuming
c that the length of rwork is to be fixed for the
c rest of the problem, and that switching may occur.
c this is defined on normal returns and on an illegal
c input return for insufficient storage.
c
c leniw iwork(18) the length of iwork actually required, assuming
c that the length of iwork is to be fixed for the
c rest of the problem, and that switching may occur.
c this is defined on normal returns and on an illegal
c input return for insufficient storage.
c
c mused iwork(19) the method indicator for the last successful step..
c 1 means adams (nonstiff), 2 means bdf (stiff).
c
c mcur iwork(20) the current method indicator..
c 1 means adams (nonstiff), 2 means bdf (stiff).
c this is the method to be attempted
c on the next step. thus it differs from mused
c only if a method switch has just been made.
c
c the following two arrays are segments of the rwork array which
c may also be of interest to the user as optional outputs.
c for each array, the table below gives its internal name,
c its base address in rwork, and its description.
c
c name base address description
c
c yh 21 the nordsieck history array, of size nyh by
c (nqcur + 1), where nyh is the initial value
c of neq. for j = 0,1,...,nqcur, column j+1
c of yh contains hcur**j/factorial(j) times
c the j-th derivative of the interpolating
c polynomial currently representing the solution,
c evaluated at t = tcur.
c
c acor lacor array of size neq used for the accumulated
c (from common corrections on each step, scaled on output
c as noted) to represent the estimated local error in y
c on the last step. this is the vector e in
c the description of the error control. it is
c defined only on a successful return from lsoda.
c the base address lacor is obtained by
c including in the user-s program the
c following 3 lines..
c double precision rls
c common /ls0001/ rls(218), ils(39)
c lacor = ils(5)
c
c-----------------------------------------------------------------------
c part ii. other routines callable.
c
c the following are optional calls which the user may make to
c gain additional capabilities in conjunction with lsoda.
c (the routines xsetun and xsetf are designed to conform to the
c slatec error handling package.)
c
c form of call function
c call xsetun(lun) set the logical unit number, lun, for
c output of messages from lsoda, if
c the default is not desired.
c the default value of lun is 6.
c
c call xsetf(mflag) set a flag to control the printing of
c messages by lsoda.
c mflag = 0 means do not print. (danger..
c this risks losing valuable information.)
c mflag = 1 means print (the default).
c
c either of the above calls may be made at
c any time and will take effect immediately.
c
c call srcma(rsav,isav,job) saves and restores the contents of
c the internal common blocks used by
c lsoda (see part iii below).
c rsav must be a real array of length 240
c or more, and isav must be an integer
c array of length 50 or more.
c job=1 means save common into rsav/isav.
c job=2 means restore common from rsav/isav.
c srcma is useful if one is
c interrupting a run and restarting
c later, or alternating between two or
c more problems solved with lsoda.
c
c call intdy(,,,,,) provide derivatives of y, of various
c (see below) orders, at a specified point t, if
c desired. it may be called only after
c a successful return from lsoda.
c
c the detailed instructions for using intdy are as follows.
c the form of the call is..
c
c call intdy (t, k, rwork(21), nyh, dky, iflag)
c
c the input parameters are..
c
c t = value of independent variable where answers are desired
c (normally the same as the t last returned by lsoda).
c for valid results, t must lie between tcur - hu and tcur.
c (see optional outputs for tcur and hu.)
c k = integer order of the derivative desired. k must satisfy
c 0 .le. k .le. nqcur, where nqcur is the current order
c (see optional outputs). the capability corresponding
c to k = 0, i.e. computing y(t), is already provided
c by lsoda directly. since nqcur .ge. 1, the first
c derivative dy/dt is always available with intdy.
c rwork(21) = the base address of the history array yh.
c nyh = column length of yh, equal to the initial value of neq.
c
c the output parameters are..
c
c dky = a real array of length neq containing the computed value
c of the k-th derivative of y(t).
c iflag = integer flag, returned as 0 if k and t were legal,
c -1 if k was illegal, and -2 if t was illegal.
c on an error return, a message is also written.
c-----------------------------------------------------------------------
c part iii. common blocks.
c
c if lsoda is to be used in an overlay situation, the user
c must declare, in the primary overlay, the variables in..
c (1) the call sequence to lsoda,
c (2) the three internal common blocks
c /ls0001/ of length 257 (218 double precision words
c followed by 39 integer words),
c /lsa001/ of length 31 (22 double precision words
c followed by 9 integer words),
c /eh0001/ of length 2 (integer words).
c
c if lsoda is used on a system in which the contents of internal
c common blocks are not preserved between calls, the user should
c declare the above common blocks in his main program to insure
c that their contents are preserved.
c
c if the solution of a given problem by lsoda is to be interrupted
c and then later continued, such as when restarting an interrupted run
c or alternating between two or more problems, the user should save,
c following the return from the last lsoda call prior to the
c interruption, the contents of the call sequence variables and the
c internal common blocks, and later restore these values before the
c next lsoda call for that problem. to save and restore the common
c blocks, use subroutine srcma (see part ii above).
c
c-----------------------------------------------------------------------
c part iv. optionally replaceable solver routines.
c
c below is a description of a routine in the lsoda package which
c relates to the measurement of errors, and can be
c replaced by a user-supplied version, if desired. however, since such
c a replacement may have a major impact on performance, it should be
c done only when absolutely necessary, and only with great caution.
c (note.. the means by which the package version of a routine is
c superseded by the user-s version may be system-dependent.)
c
c (a) ewset.
c the following subroutine is called just before each internal
c integration step, and sets the array of error weights, ewt, as
c described under itol/rtol/atol above..
c subroutine ewset (neq, itol, rtol, atol, ycur, ewt)
c where neq, itol, rtol, and atol are as in the lsoda call sequence,
c ycur contains the current dependent variable vector, and
c ewt is the array of weights set by ewset.
c
c if the user supplies this subroutine, it must return in ewt(i)
c (i = 1,...,neq) a positive quantity suitable for comparing errors
c in y(i) to. the ewt array returned by ewset is passed to the
c vmnorm routine, and also used by lsoda in the computation
c of the optional output imxer, and the increments for difference
c quotient jacobians.
c
c in the user-supplied version of ewset, it may be desirable to use
c the current values of derivatives of y. derivatives up to order nq
c are available from the history array yh, described above under
c optional outputs. in ewset, yh is identical to the ycur array,
c extended to nq + 1 columns with a column length of nyh and scale
c factors of h**j/factorial(j). on the first call for the problem,
c given by nst = 0, nq is 1 and h is temporarily set to 1.0.
c the quantities nq, nyh, h, and nst can be obtained by including
c in ewset the statements..
c double precision h, rls
c common /ls0001/ rls(218),ils(39)
c nq = ils(35)
c nyh = ils(14)
c nst = ils(36)
c h = rls(212)
c thus, for example, the current value of dy/dt can be obtained as
c ycur(nyh+i)/h (i=1,...,neq) (and the division by h is
c unnecessary when nst = 0).
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
c other routines in the lsoda package.
c
c in addition to subroutine lsoda, the lsoda package includes the
c following subroutines and function routines..
c intdy computes an interpolated value of the y vector at t = tout.
c stoda is the core integrator, which does one step of the
c integration and the associated error control.
c cfode sets all method coefficients and test constants.
c prja computes and preprocesses the jacobian matrix j = df/dy
c and the newton iteration matrix p = i - h*l0*j.
c solsy manages solution of linear system in chord iteration.
c ewset sets the error weight vector ewt before each step.
c vmnorm computes the weighted max-norm of a vector.
c fnorm computes the norm of a full matrix consistent with the
c weighted max-norm on vectors.
c bnorm computes the norm of a band matrix consistent with the
c weighted max-norm on vectors.
c srcma is a user-callable routine to save and restore
c the contents of the internal common blocks.
c dgetrf and dgetrs are routines from lapack for solving full
c systems of linear algebraic equations.
c dgbtrf and dgbtrs are routines from lapack for solving banded
c linear systems.
c daxpy, dscal, idamax, and ddot are basic linear algebra modules
c (blas) used by the above linpack routines.
c d1mach computes the unit roundoff in a machine-independent manner.
c xerrwv, xsetun, and xsetf handle the printing of all error
c messages and warnings. xerrwv is machine-dependent.
c note.. vmnorm, fnorm, bnorm, idamax, ddot, and d1mach are function
c routines. all the others are subroutines.
c
c the intrinsic and external routines used by lsoda are..
c dabs, dmax1, dmin1, dble, max0, min0, mod, dsign, dsqrt, and write.
c
c a block data subprogram is also included with the package,
c for loading some of the variables in internal common.
c
c-----------------------------------------------------------------------
c the following card is for optimized compilation on lll compilers.
clll. optimize
c-----------------------------------------------------------------------
external prja, solsy
integer illin, init, lyh, lewt, lacor, lsavf, lwm, liwm,
1 mxstep, mxhnil, nhnil, ntrep, nslast, nyh, iowns
integer icf, ierpj, iersl, jcur, jstart, kflag, l, meth, miter,
1 maxord, maxcor, msbp, mxncf, n, nq, nst, nfe, nje, nqu
integer insufr, insufi, ixpr, iowns2, jtyp, mused, mxordn, mxords
integer i, i1, i2, iflag, imxer, kgo, lf0,
1 leniw, lenrw, lenwm, ml, mord, mu, mxhnl0, mxstp0
integer len1, len1c, len1n, len1s, len2, leniwc,
1 lenrwc, lenrwn, lenrws
double precision rowns,
1 ccmax, el0, h, hmin, hmxi, hu, rc, tn, uround
double precision tsw, rowns2, pdnorm
double precision atoli, ayi, big, ewti, h0, hmax, hmx, rh, rtoli,
1 tcrit, tdist, tnext, tol, tolsf, tp, size, sum, w0,
2 d1mach, vmnorm
dimension mord(2)
logical ihit
c-----------------------------------------------------------------------
c the following two internal common blocks contain
c (a) variables which are local to any subroutine but whose values must
c be preserved between calls to the routine (own variables), and
c (b) variables which are communicated between subroutines.
c the structure of each block is as follows.. all real variables are
c listed first, followed by all integers. within each type, the
c variables are grouped with those local to subroutine lsoda first,
c then those local to subroutine stoda, and finally those used
c for communication. the block ls0001 is declared in subroutines
c lsoda, intdy, stoda, prja, and solsy. the block lsa001 is declared
c in subroutines lsoda, stoda, and prja. groups of variables are
c replaced by dummy arrays in the common declarations in routines
c where those variables are not used.
c-----------------------------------------------------------------------
common /ls0001/ rowns(209),
1 ccmax, el0, h, hmin, hmxi, hu, rc, tn, uround,
2 illin, init, lyh, lewt, lacor, lsavf, lwm, liwm,
3 mxstep, mxhnil, nhnil, ntrep, nslast, nyh, iowns(6),
4 icf, ierpj, iersl, jcur, jstart, kflag, l, meth, miter,
5 maxord, maxcor, msbp, mxncf, n, nq, nst, nfe, nje, nqu
common /lsa001/ tsw, rowns2(20), pdnorm,
1 insufr, insufi, ixpr, iowns2(2), jtyp, mused, mxordn, mxords
c
data mord(1),mord(2)/12,5/, mxstp0/500/, mxhnl0/10/
c-----------------------------------------------------------------------
c block a.
c this code block is executed on every call.
c it tests istate and itask for legality and branches appropriately.
c if istate .gt. 1 but the flag init shows that initialization has
c not yet been done, an error return occurs.
c if istate = 1 and tout = t, jump to block g and return immediately.
c-----------------------------------------------------------------------
if (istate .lt. 1 .or. istate .gt. 3) go to 601
if (itask .lt. 1 .or. itask .gt. 5) go to 602
if (istate .eq. 1) go to 10
if (init .eq. 0) go to 603
if (istate .eq. 2) go to 200
go to 20
10 init = 0
if (tout .eq. t) go to 430
20 ntrep = 0
c-----------------------------------------------------------------------
c block b.
c the next code block is executed for the initial call (istate = 1),
c or for a continuation call with parameter changes (istate = 3).
c it contains checking of all inputs and various initializations.
c
c first check legality of the non-optional inputs neq, itol, iopt,
c jt, ml, and mu.
c-----------------------------------------------------------------------
if (neq(1) .le. 0) go to 604
if (istate .eq. 1) go to 25
if (neq(1) .gt. n) go to 605
25 n = neq(1)
if (itol .lt. 1 .or. itol .gt. 4) go to 606
if (iopt .lt. 0 .or. iopt .gt. 1) go to 607
if (jt .eq. 3 .or. jt .lt. 1 .or. jt .gt. 5) go to 608
jtyp = jt
if (jt .le. 2) go to 30
ml = iwork(1)
mu = iwork(2)
if (ml .lt. 0 .or. ml .ge. n) go to 609
if (mu .lt. 0 .or. mu .ge. n) go to 610
30 continue
c next process and check the optional inputs. --------------------------
if (iopt .eq. 1) go to 40
ixpr = 0
mxstep = mxstp0
mxhnil = mxhnl0
hmxi = 0.0d0
hmin = 0.0d0
if (istate .ne. 1) go to 60
h0 = 0.0d0
mxordn = mord(1)
mxords = mord(2)
go to 60
40 ixpr = iwork(5)
if (ixpr .lt. 0 .or. ixpr .gt. 1) go to 611
mxstep = iwork(6)
if (mxstep .lt. 0) go to 612
if (mxstep .eq. 0) mxstep = mxstp0
mxhnil = iwork(7)
if (mxhnil .lt. 0) go to 613
if (mxhnil .eq. 0) mxhnil = mxhnl0
if (istate .ne. 1) go to 50
h0 = rwork(5)
mxordn = iwork(8)
if (mxordn .lt. 0) go to 628
if (mxordn .eq. 0) mxordn = 100
mxordn = min0(mxordn,mord(1))
mxords = iwork(9)
if (mxords .lt. 0) go to 629
if (mxords .eq. 0) mxords = 100
mxords = min0(mxords,mord(2))
if ((tout - t)*h0 .lt. 0.0d0) go to 614
50 hmax = rwork(6)
if (hmax .lt. 0.0d0) go to 615
hmxi = 0.0d0
if (hmax .gt. 0.0d0) hmxi = 1.0d0/hmax
hmin = rwork(7)
if (hmin .lt. 0.0d0) go to 616
c-----------------------------------------------------------------------
c set work array pointers and check lengths lrw and liw.
c if istate = 1, meth is initialized to 1 here to facilitate the
c checking of work space lengths.
c pointers to segments of rwork and iwork are named by prefixing l to
c the name of the segment. e.g., the segment yh starts at rwork(lyh).
c segments of rwork (in order) are denoted yh, wm, ewt, savf, acor.
c if the lengths provided are insufficient for the current method,
c an error return occurs. this is treated as illegal input on the
c first call, but as a problem interruption with istate = -7 on a
c continuation call. if the lengths are sufficient for the current
c method but not for both methods, a warning message is sent.
c-----------------------------------------------------------------------
60 if (istate .eq. 1) meth = 1
if (istate .eq. 1) nyh = n
lyh = 21
len1n = 20 + (mxordn + 1)*nyh
len1s = 20 + (mxords + 1)*nyh
lwm = len1s + 1
if (jt .le. 2) lenwm = n*n + 2
if (jt .ge. 4) lenwm = (2*ml + mu + 1)*n + 2
len1s = len1s + lenwm
len1c = len1n
if (meth .eq. 2) len1c = len1s
len1 = max0(len1n,len1s)
len2 = 3*n
lenrw = len1 + len2
lenrwn = len1n + len2
lenrws = len1s + len2
lenrwc = len1c + len2
iwork(17) = lenrw
liwm = 1
leniw = 20 + n
leniwc = 20
if (meth .eq. 2) leniwc = leniw
iwork(18) = leniw
if (istate .eq. 1 .and. lrw .lt. lenrwc) go to 617
if (istate .eq. 1 .and. liw .lt. leniwc) go to 618
if (istate .eq. 3 .and. lrw .lt. lenrwc) go to 550
if (istate .eq. 3 .and. liw .lt. leniwc) go to 555
lewt = len1 + 1
insufr = 0
if (lrw .ge. lenrw) go to 65
insufr = 2
lewt = len1c + 1
call xerrwv(
1 'lsoda-- warning.. rwork length is sufficient for now, but ',
1 60, 103, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' may not be later. integration will proceed anyway. ',
1 60, 103, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' length needed is lenrw = i1, while lrw = i2.',
1 50, 103, 0, 2, lenrw, lrw, 0, 0.0d0, 0.0d0)
65 lsavf = lewt + n
lacor = lsavf + n
insufi = 0
if (liw .ge. leniw) go to 70
insufi = 2
call xerrwv(
1 'lsoda-- warning.. iwork length is sufficient for now, but ',
1 60, 104, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' may not be later. integration will proceed anyway. ',
1 60, 104, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' length needed is leniw = i1, while liw = i2.',
1 50, 104, 0, 2, leniw, liw, 0, 0.0d0, 0.0d0)
70 continue
c check rtol and atol for legality. ------------------------------------
rtoli = rtol(1)
atoli = atol(1)
do 75 i = 1,n
if (itol .ge. 3) rtoli = rtol(i)
if (itol .eq. 2 .or. itol .eq. 4) atoli = atol(i)
if (rtoli .lt. 0.0d0) go to 619
if (atoli .lt. 0.0d0) go to 620
75 continue
if (istate .eq. 1) go to 100
c if istate = 3, set flag to signal parameter changes to stoda. --------
jstart = -1
if (n .eq. nyh) go to 200
c neq was reduced. zero part of yh to avoid undefined references. -----
i1 = lyh + l*nyh
i2 = lyh + (maxord + 1)*nyh - 1
if (i1 .gt. i2) go to 200
do 95 i = i1,i2
95 rwork(i) = 0.0d0
go to 200
c-----------------------------------------------------------------------
c block c.
c the next block is for the initial call only (istate = 1).
c it contains all remaining initializations, the initial call to f,
c and the calculation of the initial step size.
c the error weights in ewt are inverted after being loaded.
c-----------------------------------------------------------------------
100 uround = d1mach(4)
tn = t
tsw = t
maxord = mxordn
if (itask .ne. 4 .and. itask .ne. 5) go to 110
tcrit = rwork(1)
if ((tcrit - tout)*(tout - t) .lt. 0.0d0) go to 625
if (h0 .ne. 0.0d0 .and. (t + h0 - tcrit)*h0 .gt. 0.0d0)
1 h0 = tcrit - t
110 jstart = 0
nhnil = 0
nst = 0
nje = 0
nslast = 0
hu = 0.0d0
nqu = 0
mused = 0
miter = 0
ccmax = 0.3d0
maxcor = 3
msbp = 20
mxncf = 10
c initial call to f. (lf0 points to yh(*,2).) -------------------------
lf0 = lyh + nyh
call srcma(rsav, isav, 1)
call f (neq, t, y, rwork(lf0))
c SCIPY error check:
if (neq(1) .eq. -1) return
call srcma(rsav, isav, 2)
nfe = 1
c load the initial value vector in yh. ---------------------------------
do 115 i = 1,n
115 rwork(i+lyh-1) = y(i)
c load and invert the ewt array. (h is temporarily set to 1.0.) -------
nq = 1
h = 1.0d0
call ewset (n, itol, rtol, atol, rwork(lyh), rwork(lewt))
do 120 i = 1,n
if (rwork(i+lewt-1) .le. 0.0d0) go to 621
120 rwork(i+lewt-1) = 1.0d0/rwork(i+lewt-1)
c-----------------------------------------------------------------------
c the coding below computes the step size, h0, to be attempted on the
c first step, unless the user has supplied a value for this.
c first check that tout - t differs significantly from zero.
c a scalar tolerance quantity tol is computed, as max(rtol(i))
c if this is positive, or max(atol(i)/abs(y(i))) otherwise, adjusted
c so as to be between 100*uround and 1.0e-3.
c then the computed value h0 is given by..
c
c h0**(-2) = 1./(tol * w0**2) + tol * (norm(f))**2
c
c where w0 = max ( abs(t), abs(tout) ),
c f = the initial value of the vector f(t,y), and
c norm() = the weighted vector norm used throughout, given by
c the vmnorm function routine, and weighted by the
c tolerances initially loaded into the ewt array.
c the sign of h0 is inferred from the initial values of tout and t.
c abs(h0) is made .le. abs(tout-t) in any case.
c-----------------------------------------------------------------------
if (h0 .ne. 0.0d0) go to 180
tdist = dabs(tout - t)
w0 = dmax1(dabs(t),dabs(tout))
if (tdist .lt. 2.0d0*uround*w0) go to 622
tol = rtol(1)
if (itol .le. 2) go to 140
do 130 i = 1,n
130 tol = dmax1(tol,rtol(i))
140 if (tol .gt. 0.0d0) go to 160
atoli = atol(1)
do 150 i = 1,n
if (itol .eq. 2 .or. itol .eq. 4) atoli = atol(i)
ayi = dabs(y(i))
if (ayi .ne. 0.0d0) tol = dmax1(tol,atoli/ayi)
150 continue
160 tol = dmax1(tol,100.0d0*uround)
tol = dmin1(tol,0.001d0)
sum = vmnorm (n, rwork(lf0), rwork(lewt))
sum = 1.0d0/(tol*w0*w0) + tol*sum**2
h0 = 1.0d0/dsqrt(sum)
h0 = dmin1(h0,tdist)
h0 = dsign(h0,tout-t)
c adjust h0 if necessary to meet hmax bound. ---------------------------
180 rh = dabs(h0)*hmxi
if (rh .gt. 1.0d0) h0 = h0/rh
c load h with h0 and scale yh(*,2) by h0. ------------------------------
h = h0
do 190 i = 1,n
190 rwork(i+lf0-1) = h0*rwork(i+lf0-1)
go to 270
c-----------------------------------------------------------------------
c block d.
c the next code block is for continuation calls only (istate = 2 or 3)
c and is to check stop conditions before taking a step.
c-----------------------------------------------------------------------
200 nslast = nst
go to (210, 250, 220, 230, 240), itask
210 if ((tn - tout)*h .lt. 0.0d0) go to 250
call intdy (tout, 0, rwork(lyh), nyh, y, iflag)
if (iflag .ne. 0) go to 627
t = tout
go to 420
220 tp = tn - hu*(1.0d0 + 100.0d0*uround)
if ((tp - tout)*h .gt. 0.0d0) go to 623
if ((tn - tout)*h .lt. 0.0d0) go to 250
t = tn
go to 400
230 tcrit = rwork(1)
if ((tn - tcrit)*h .gt. 0.0d0) go to 624
if ((tcrit - tout)*h .lt. 0.0d0) go to 625
if ((tn - tout)*h .lt. 0.0d0) go to 245
call intdy (tout, 0, rwork(lyh), nyh, y, iflag)
if (iflag .ne. 0) go to 627
t = tout
go to 420
240 tcrit = rwork(1)
if ((tn - tcrit)*h .gt. 0.0d0) go to 624
245 hmx = dabs(tn) + dabs(h)
ihit = dabs(tn - tcrit) .le. 100.0d0*uround*hmx
if (ihit) t = tcrit
if (ihit) go to 400
tnext = tn + h*(1.0d0 + 4.0d0*uround)
if ((tnext - tcrit)*h .le. 0.0d0) go to 250
h = (tcrit - tn)*(1.0d0 - 4.0d0*uround)
if (istate .eq. 2 .and. jstart .ge. 0) jstart = -2
c-----------------------------------------------------------------------
c block e.
c the next block is normally executed for all calls and contains
c the call to the one-step core integrator stoda.
c
c this is a looping point for the integration steps.
c
c first check for too many steps being taken, update ewt (if not at
c start of problem), check for too much accuracy being requested, and
c check for h below the roundoff level in t.
c-----------------------------------------------------------------------
250 continue
if (meth .eq. mused) go to 255
if (insufr .eq. 1) go to 550
if (insufi .eq. 1) go to 555
255 if ((nst-nslast) .ge. mxstep) go to 500
call ewset (n, itol, rtol, atol, rwork(lyh), rwork(lewt))
do 260 i = 1,n
if (rwork(i+lewt-1) .le. 0.0d0) go to 510
260 rwork(i+lewt-1) = 1.0d0/rwork(i+lewt-1)
270 tolsf = uround*vmnorm (n, rwork(lyh), rwork(lewt))
if (tolsf .le. 0.01d0) go to 280
tolsf = tolsf*200.0d0
if (nst .eq. 0) go to 626
go to 520
280 if ((tn + h) .ne. tn) go to 290
nhnil = nhnil + 1
if (nhnil .gt. mxhnil) go to 290
call xerrwv('lsoda-- warning..internal t (=r1) and h (=r2) are',
1 50, 101, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' such that in the machine, t + h = t on the next step ',
1 60, 101, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' (h = step size). solver will continue anyway',
1 50, 101, 0, 0, 0, 0, 2, tn, h)
if (nhnil .lt. mxhnil) go to 290
call xerrwv('lsoda-- above warning has been issued i1 times. ',
1 50, 102, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' it will not be issued again for this problem',
1 50, 102, 0, 1, mxhnil, 0, 0, 0.0d0, 0.0d0)
290 continue
c-----------------------------------------------------------------------
c call stoda(neq,y,yh,nyh,yh,ewt,savf,acor,wm,iwm,f,jac,prja,solsy)
c-----------------------------------------------------------------------
call stoda (neq, y, rwork(lyh), nyh, rwork(lyh), rwork(lewt),
1 rwork(lsavf), rwork(lacor), rwork(lwm), iwork(liwm),
2 f, jac, prja, solsy)
c SCIPY error check:
if (neq(1) .eq. -1) return
kgo = 1 - kflag
go to (300, 530, 540), kgo
c-----------------------------------------------------------------------
c block f.
c the following block handles the case of a successful return from the
c core integrator (kflag = 0).
c if a method switch was just made, record tsw, reset maxord,
c set jstart to -1 to signal stoda to complete the switch,
c and do extra printing of data if ixpr = 1.
c then, in any case, check for stop conditions.
c-----------------------------------------------------------------------
300 init = 1
if (meth .eq. mused) go to 310
tsw = tn
maxord = mxordn
if (meth .eq. 2) maxord = mxords
if (meth .eq. 2) rwork(lwm) = dsqrt(uround)
insufr = min0(insufr,1)
insufi = min0(insufi,1)
jstart = -1
if (ixpr .eq. 0) go to 310
if (meth .eq. 2) call xerrwv(
1 'lsoda-- a switch to the bdf (stiff) method has occurred ',
1 60, 105, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
if (meth .eq. 1) call xerrwv(
1 'lsoda-- a switch to the adams (nonstiff) method has occurred',
1 60, 106, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' at t = r1, tentative step size h = r2, step nst = i1 ',
1 60, 107, 0, 1, nst, 0, 2, tn, h)
310 go to (320, 400, 330, 340, 350), itask
c itask = 1. if tout has been reached, interpolate. -------------------
320 if ((tn - tout)*h .lt. 0.0d0) go to 250
call intdy (tout, 0, rwork(lyh), nyh, y, iflag)
t = tout
go to 420
c itask = 3. jump to exit if tout was reached. ------------------------
330 if ((tn - tout)*h .ge. 0.0d0) go to 400
go to 250
c itask = 4. see if tout or tcrit was reached. adjust h if necessary.
340 if ((tn - tout)*h .lt. 0.0d0) go to 345
call intdy (tout, 0, rwork(lyh), nyh, y, iflag)
t = tout
go to 420
345 hmx = dabs(tn) + dabs(h)
ihit = dabs(tn - tcrit) .le. 100.0d0*uround*hmx
if (ihit) go to 400
tnext = tn + h*(1.0d0 + 4.0d0*uround)
if ((tnext - tcrit)*h .le. 0.0d0) go to 250
h = (tcrit - tn)*(1.0d0 - 4.0d0*uround)
if (jstart .ge. 0) jstart = -2
go to 250
c itask = 5. see if tcrit was reached and jump to exit. ---------------
350 hmx = dabs(tn) + dabs(h)
ihit = dabs(tn - tcrit) .le. 100.0d0*uround*hmx
c-----------------------------------------------------------------------
c block g.
c the following block handles all successful returns from lsoda.
c if itask .ne. 1, y is loaded from yh and t is set accordingly.
c istate is set to 2, the illegal input counter is zeroed, and the
c optional outputs are loaded into the work arrays before returning.
c if istate = 1 and tout = t, there is a return with no action taken,
c except that if this has happened repeatedly, the run is terminated.
c-----------------------------------------------------------------------
400 do 410 i = 1,n
410 y(i) = rwork(i+lyh-1)
t = tn
if (itask .ne. 4 .and. itask .ne. 5) go to 420
if (ihit) t = tcrit
420 istate = 2
illin = 0
rwork(11) = hu
rwork(12) = h
rwork(13) = tn
rwork(15) = tsw
iwork(11) = nst
iwork(12) = nfe
iwork(13) = nje
iwork(14) = nqu
iwork(15) = nq
iwork(19) = mused
iwork(20) = meth
return
c
430 ntrep = ntrep + 1
if (ntrep .lt. 5) return
call xerrwv(
1 'lsoda-- repeated calls with istate = 1 and tout = t (=r1) ',
1 60, 301, 0, 0, 0, 0, 1, t, 0.0d0)
go to 800
c-----------------------------------------------------------------------
c block h.
c the following block handles all unsuccessful returns other than
c those for illegal input. first the error message routine is called.
c if there was an error test or convergence test failure, imxer is set.
c then y is loaded from yh, t is set to tn, and the illegal input
c counter illin is set to 0. the optional outputs are loaded into
c the work arrays before returning.
c-----------------------------------------------------------------------
c the maximum number of steps was taken before reaching tout. ----------
c Error message removed, see gh-7888
500 istate = -1
go to 580
c ewt(i) .le. 0.0 for some i (not at start of problem). ----------------
510 ewti = rwork(lewt+i-1)
call xerrwv('lsoda-- at t (=r1), ewt(i1) has become r2 .le. 0.',
1 50, 202, 0, 1, i, 0, 2, tn, ewti)
istate = -6
go to 580
c too much accuracy requested for machine precision. -------------------
520 call xerrwv('lsoda-- at t (=r1), too much accuracy requested ',
1 50, 203, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' for precision of machine.. see tolsf (=r2) ',
1 50, 203, 0, 0, 0, 0, 2, tn, tolsf)
rwork(14) = tolsf
istate = -2
go to 580
c kflag = -1. error test failed repeatedly or with abs(h) = hmin. -----
530 call xerrwv('lsoda-- at t(=r1) and step size h(=r2), the error',
1 50, 204, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' test failed repeatedly or with abs(h) = hmin',
1 50, 204, 0, 0, 0, 0, 2, tn, h)
istate = -4
go to 560
c kflag = -2. convergence failed repeatedly or with abs(h) = hmin. ----
540 call xerrwv('lsoda-- at t (=r1) and step size h (=r2), the ',
1 50, 205, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' corrector convergence failed repeatedly ',
1 50, 205, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(' or with abs(h) = hmin ',
1 30, 205, 0, 0, 0, 0, 2, tn, h)
istate = -5
go to 560
c rwork length too small to proceed. -----------------------------------
550 call xerrwv('lsoda-- at current t(=r1), rwork length too small',
1 50, 206, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' to proceed. the integration was otherwise successful.',
1 60, 206, 0, 0, 0, 0, 1, tn, 0.0d0)
istate = -7
go to 580
c iwork length too small to proceed. -----------------------------------
555 call xerrwv('lsoda-- at current t(=r1), iwork length too small',
1 50, 207, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' to proceed. the integration was otherwise successful.',
1 60, 207, 0, 0, 0, 0, 1, tn, 0.0d0)
istate = -7
go to 580
c compute imxer if relevant. -------------------------------------------
560 big = 0.0d0
imxer = 1
do 570 i = 1,n
size = dabs(rwork(i+lacor-1)*rwork(i+lewt-1))
if (big .ge. size) go to 570
big = size
imxer = i
570 continue
iwork(16) = imxer
c set y vector, t, illin, and optional outputs. ------------------------
580 do 590 i = 1,n
590 y(i) = rwork(i+lyh-1)
t = tn
illin = 0
rwork(11) = hu
rwork(12) = h
rwork(13) = tn
rwork(15) = tsw
iwork(11) = nst
iwork(12) = nfe
iwork(13) = nje
iwork(14) = nqu
iwork(15) = nq
iwork(19) = mused
iwork(20) = meth
return
c-----------------------------------------------------------------------
c block i.
c the following block handles all error returns due to illegal input
c (istate = -3), as detected before calling the core integrator.
c first the error message routine is called. then if there have been
c 5 consecutive such returns just before this call to the solver,
c the run is halted.
c-----------------------------------------------------------------------
601 call xerrwv('lsoda-- istate (=i1) illegal ',
1 30, 1, 0, 1, istate, 0, 0, 0.0d0, 0.0d0)
go to 700
602 call xerrwv('lsoda-- itask (=i1) illegal ',
1 30, 2, 0, 1, itask, 0, 0, 0.0d0, 0.0d0)
go to 700
603 call xerrwv('lsoda-- istate .gt. 1 but lsoda not initialized ',
1 50, 3, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
go to 700
604 call xerrwv('lsoda-- neq (=i1) .lt. 1 ',
1 30, 4, 0, 1, neq(1), 0, 0, 0.0d0, 0.0d0)
go to 700
605 call xerrwv('lsoda-- istate = 3 and neq increased (i1 to i2) ',
1 50, 5, 0, 2, n, neq(1), 0, 0.0d0, 0.0d0)
go to 700
606 call xerrwv('lsoda-- itol (=i1) illegal ',
1 30, 6, 0, 1, itol, 0, 0, 0.0d0, 0.0d0)
go to 700
607 call xerrwv('lsoda-- iopt (=i1) illegal ',
1 30, 7, 0, 1, iopt, 0, 0, 0.0d0, 0.0d0)
go to 700
608 call xerrwv('lsoda-- jt (=i1) illegal ',
1 30, 8, 0, 1, jt, 0, 0, 0.0d0, 0.0d0)
go to 700
609 call xerrwv('lsoda-- ml (=i1) illegal.. .lt.0 or .ge.neq (=i2)',
1 50, 9, 0, 2, ml, neq(1), 0, 0.0d0, 0.0d0)
go to 700
610 call xerrwv('lsoda-- mu (=i1) illegal.. .lt.0 or .ge.neq (=i2)',
1 50, 10, 0, 2, mu, neq(1), 0, 0.0d0, 0.0d0)
go to 700
611 call xerrwv('lsoda-- ixpr (=i1) illegal ',
1 30, 11, 0, 1, ixpr, 0, 0, 0.0d0, 0.0d0)
go to 700
612 call xerrwv('lsoda-- mxstep (=i1) .lt. 0 ',
1 30, 12, 0, 1, mxstep, 0, 0, 0.0d0, 0.0d0)
go to 700
613 call xerrwv('lsoda-- mxhnil (=i1) .lt. 0 ',
1 30, 13, 0, 1, mxhnil, 0, 0, 0.0d0, 0.0d0)
go to 700
614 call xerrwv('lsoda-- tout (=r1) behind t (=r2) ',
1 40, 14, 0, 0, 0, 0, 2, tout, t)
call xerrwv(' integration direction is given by h0 (=r1) ',
1 50, 14, 0, 0, 0, 0, 1, h0, 0.0d0)
go to 700
615 call xerrwv('lsoda-- hmax (=r1) .lt. 0.0 ',
1 30, 15, 0, 0, 0, 0, 1, hmax, 0.0d0)
go to 700
616 call xerrwv('lsoda-- hmin (=r1) .lt. 0.0 ',
1 30, 16, 0, 0, 0, 0, 1, hmin, 0.0d0)
go to 700
617 call xerrwv(
1 'lsoda-- rwork length needed, lenrw (=i1), exceeds lrw (=i2)',
1 60, 17, 0, 2, lenrw, lrw, 0, 0.0d0, 0.0d0)
go to 700
618 call xerrwv(
1 'lsoda-- iwork length needed, leniw (=i1), exceeds liw (=i2)',
1 60, 18, 0, 2, leniw, liw, 0, 0.0d0, 0.0d0)
go to 700
619 call xerrwv('lsoda-- rtol(i1) is r1 .lt. 0.0 ',
1 40, 19, 0, 1, i, 0, 1, rtoli, 0.0d0)
go to 700
620 call xerrwv('lsoda-- atol(i1) is r1 .lt. 0.0 ',
1 40, 20, 0, 1, i, 0, 1, atoli, 0.0d0)
go to 700
621 ewti = rwork(lewt+i-1)
call xerrwv('lsoda-- ewt(i1) is r1 .le. 0.0 ',
1 40, 21, 0, 1, i, 0, 1, ewti, 0.0d0)
go to 700
622 call xerrwv(
1 'lsoda-- tout (=r1) too close to t(=r2) to start integration',
1 60, 22, 0, 0, 0, 0, 2, tout, t)
go to 700
623 call xerrwv(
1 'lsoda-- itask = i1 and tout (=r1) behind tcur - hu (= r2) ',
1 60, 23, 0, 1, itask, 0, 2, tout, tp)
go to 700
624 call xerrwv(
1 'lsoda-- itask = 4 or 5 and tcrit (=r1) behind tcur (=r2) ',
1 60, 24, 0, 0, 0, 0, 2, tcrit, tn)
go to 700
625 call xerrwv(
1 'lsoda-- itask = 4 or 5 and tcrit (=r1) behind tout (=r2) ',
1 60, 25, 0, 0, 0, 0, 2, tcrit, tout)
go to 700
626 call xerrwv('lsoda-- at start of problem, too much accuracy ',
1 50, 26, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
call xerrwv(
1 ' requested for precision of machine.. see tolsf (=r1) ',
1 60, 26, 0, 0, 0, 0, 1, tolsf, 0.0d0)
rwork(14) = tolsf
go to 700
627 call xerrwv('lsoda-- trouble from intdy. itask = i1, tout = r1',
1 50, 27, 0, 1, itask, 0, 1, tout, 0.0d0)
go to 700
628 call xerrwv('lsoda-- mxordn (=i1) .lt. 0 ',
1 30, 28, 0, 1, mxordn, 0, 0, 0.0d0, 0.0d0)
go to 700
629 call xerrwv('lsoda-- mxords (=i1) .lt. 0 ',
1 30, 29, 0, 1, mxords, 0, 0, 0.0d0, 0.0d0)
c
700 if (illin .eq. 5) go to 710
illin = illin + 1
istate = -3
return
710 call xerrwv('lsoda-- repeated occurrences of illegal input ',
1 50, 302, 0, 0, 0, 0, 0, 0.0d0, 0.0d0)
c
800 istate = -8
return
c----------------------- end of subroutine lsoda -----------------------
end
| bsd-3-clause |
CVML/OpenBLAS | lapack-netlib/lapacke/src/lapacke_zsyr_work.c | 18 | 3811 | /*****************************************************************************
Copyright (c) 2010, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
* Contents: Native middle-level C interface to LAPACK function zsyr
* Author: Intel Corporation
* Generated March, 2012
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_zsyr_work( int matrix_order, char uplo, lapack_int n,
lapack_complex_double alpha,
const lapack_complex_double* x,
lapack_int incx, lapack_complex_double* a,
lapack_int lda )
{
lapack_int info = 0;
if( matrix_order == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_zsyr( &uplo, &n, &alpha, x, &incx, a, &lda );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_order == LAPACK_ROW_MAJOR ) {
lapack_int lda_t = MAX(1,n);
lapack_complex_double* a_t = NULL;
/* Check leading dimension(s) */
if( lda < n ) {
info = -8;
LAPACKE_xerbla( "LAPACKE_zsyr_work", info );
return info;
}
/* Allocate memory for temporary array(s) */
a_t = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) * lda_t * MAX(1,n) );
if( a_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
/* Transpose input matrices */
LAPACKE_zsy_trans( matrix_order, uplo, n, a, lda, a_t, lda_t );
/* Call LAPACK function and adjust info */
LAPACK_zsyr( &uplo, &n, &alpha, x, &incx, a_t, &lda_t );
info = 0; /* LAPACK call is ok! */
/* Transpose output matrices */
LAPACKE_zsy_trans( LAPACK_COL_MAJOR, uplo, n, a_t, lda_t, a, lda );
/* Release memory and exit */
LAPACKE_free( a_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_zsyr_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_zsyr_work", info );
}
return info;
}
| bsd-3-clause |
unb-libraries/phantomjs | src/qt/src/corelib/animation/qvariantanimation.cpp | 19 | 24281 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qvariantanimation.h"
#include "qvariantanimation_p.h"
#include <QtCore/qrect.h>
#include <QtCore/qline.h>
#include <QtCore/qmutex.h>
#include <private/qmutexpool_p.h>
#ifndef QT_NO_ANIMATION
QT_BEGIN_NAMESPACE
/*!
\class QVariantAnimation
\ingroup animation
\brief The QVariantAnimation class provides an abstract base class for animations.
\since 4.6
This class is part of \l{The Animation Framework}. It serves as a
base class for property and item animations, with functions for
shared functionality.
QVariantAnimation cannot be used directly as it is an abstract
class; it has a pure virtual method called updateCurrentValue().
The class performs interpolation over
\l{QVariant}s, but leaves using the interpolated values to its
subclasses. Currently, Qt provides QPropertyAnimation, which
animates Qt \l{Qt's Property System}{properties}. See the
QPropertyAnimation class description if you wish to animate such
properties.
You can then set start and end values for the property by calling
setStartValue() and setEndValue(), and finally call start() to
start the animation. QVariantAnimation will interpolate the
property of the target object and emit valueChanged(). To react to
a change in the current value you have to reimplement the
updateCurrentValue() virtual function.
It is also possible to set values at specified steps situated
between the start and end value. The interpolation will then
touch these points at the specified steps. Note that the start and
end values are defined as the key values at 0.0 and 1.0.
There are two ways to affect how QVariantAnimation interpolates
the values. You can set an easing curve by calling
setEasingCurve(), and configure the duration by calling
setDuration(). You can change how the QVariants are interpolated
by creating a subclass of QVariantAnimation, and reimplementing
the virtual interpolated() function.
Subclassing QVariantAnimation can be an alternative if you have
\l{QVariant}s that you do not wish to declare as Qt properties.
Note, however, that you in most cases will be better off declaring
your QVariant as a property.
Not all QVariant types are supported. Below is a list of currently
supported QVariant types:
\list
\o \l{QMetaType::}{Int}
\o \l{QMetaType::}{Double}
\o \l{QMetaType::}{Float}
\o \l{QMetaType::}{QLine}
\o \l{QMetaType::}{QLineF}
\o \l{QMetaType::}{QPoint}
\o \l{QMetaType::}{QPointF}
\o \l{QMetaType::}{QSize}
\o \l{QMetaType::}{QSizeF}
\o \l{QMetaType::}{QRect}
\o \l{QMetaType::}{QRectF}
\o \l{QMetaType::}{QColor}
\endlist
If you need to interpolate other variant types, including custom
types, you have to implement interpolation for these yourself.
To do this, you can register an interpolator function for a given
type. This function takes 3 parameters: the start value, the end value
and the current progress.
Example:
\code
QVariant myColorInterpolator(const QColor &start, const QColor &end, qreal progress)
{
...
return QColor(...);
}
...
qRegisterAnimationInterpolator<QColor>(myColorInterpolator);
\endcode
Another option is to reimplement interpolated(), which returns
interpolation values for the value being interpolated.
\omit We need some snippets around here. \endomit
\sa QPropertyAnimation, QAbstractAnimation, {The Animation Framework}
*/
/*!
\fn void QVariantAnimation::valueChanged(const QVariant &value)
QVariantAnimation emits this signal whenever the current \a value changes.
\sa currentValue, startValue, endValue
*/
/*!
\fn void QVariantAnimation::updateCurrentValue(const QVariant &value) = 0;
This pure virtual function is called every time the animation's current
value changes. The \a value argument is the new current value.
\sa currentValue
*/
static bool animationValueLessThan(const QVariantAnimation::KeyValue &p1, const QVariantAnimation::KeyValue &p2)
{
return p1.first < p2.first;
}
static QVariant defaultInterpolator(const void *, const void *, qreal)
{
return QVariant();
}
template<> Q_INLINE_TEMPLATE QRect _q_interpolate(const QRect &f, const QRect &t, qreal progress)
{
QRect ret;
ret.setCoords(_q_interpolate(f.left(), t.left(), progress),
_q_interpolate(f.top(), t.top(), progress),
_q_interpolate(f.right(), t.right(), progress),
_q_interpolate(f.bottom(), t.bottom(), progress));
return ret;
}
template<> Q_INLINE_TEMPLATE QRectF _q_interpolate(const QRectF &f, const QRectF &t, qreal progress)
{
qreal x1, y1, w1, h1;
f.getRect(&x1, &y1, &w1, &h1);
qreal x2, y2, w2, h2;
t.getRect(&x2, &y2, &w2, &h2);
return QRectF(_q_interpolate(x1, x2, progress), _q_interpolate(y1, y2, progress),
_q_interpolate(w1, w2, progress), _q_interpolate(h1, h2, progress));
}
template<> Q_INLINE_TEMPLATE QLine _q_interpolate(const QLine &f, const QLine &t, qreal progress)
{
return QLine( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress));
}
template<> Q_INLINE_TEMPLATE QLineF _q_interpolate(const QLineF &f, const QLineF &t, qreal progress)
{
return QLineF( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress));
}
QVariantAnimationPrivate::QVariantAnimationPrivate() : duration(250), interpolator(&defaultInterpolator)
{ }
void QVariantAnimationPrivate::convertValues(int t)
{
//this ensures that all the keyValues are of type t
for (int i = 0; i < keyValues.count(); ++i) {
QVariantAnimation::KeyValue &pair = keyValues[i];
pair.second.convert(static_cast<QVariant::Type>(t));
}
//we also need update to the current interval if needed
currentInterval.start.second.convert(static_cast<QVariant::Type>(t));
currentInterval.end.second.convert(static_cast<QVariant::Type>(t));
//... and the interpolator
updateInterpolator();
}
void QVariantAnimationPrivate::updateInterpolator()
{
int type = currentInterval.start.second.userType();
if (type == currentInterval.end.second.userType())
interpolator = getInterpolator(type);
else
interpolator = 0;
//we make sure that the interpolator is always set to something
if (!interpolator)
interpolator = &defaultInterpolator;
}
/*!
\internal
The goal of this function is to update the currentInterval member. As a consequence, we also
need to update the currentValue.
Set \a force to true to always recalculate the interval.
*/
void QVariantAnimationPrivate::recalculateCurrentInterval(bool force/*=false*/)
{
// can't interpolate if we don't have at least 2 values
if ((keyValues.count() + (defaultStartEndValue.isValid() ? 1 : 0)) < 2)
return;
const qreal endProgress = (direction == QAbstractAnimation::Forward) ? qreal(1) : qreal(0);
const qreal progress = easing.valueForProgress(((duration == 0) ? endProgress : qreal(currentTime) / qreal(duration)));
//0 and 1 are still the boundaries
if (force || (currentInterval.start.first > 0 && progress < currentInterval.start.first)
|| (currentInterval.end.first < 1 && progress > currentInterval.end.first)) {
//let's update currentInterval
QVariantAnimation::KeyValues::const_iterator it = qLowerBound(keyValues.constBegin(),
keyValues.constEnd(),
qMakePair(progress, QVariant()),
animationValueLessThan);
if (it == keyValues.constBegin()) {
//the item pointed to by it is the start element in the range
if (it->first == 0 && keyValues.count() > 1) {
currentInterval.start = *it;
currentInterval.end = *(it+1);
} else {
currentInterval.start = qMakePair(qreal(0), defaultStartEndValue);
currentInterval.end = *it;
}
} else if (it == keyValues.constEnd()) {
--it; //position the iterator on the last item
if (it->first == 1 && keyValues.count() > 1) {
//we have an end value (item with progress = 1)
currentInterval.start = *(it-1);
currentInterval.end = *it;
} else {
//we use the default end value here
currentInterval.start = *it;
currentInterval.end = qMakePair(qreal(1), defaultStartEndValue);
}
} else {
currentInterval.start = *(it-1);
currentInterval.end = *it;
}
// update all the values of the currentInterval
updateInterpolator();
}
setCurrentValueForProgress(progress);
}
void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress)
{
Q_Q(QVariantAnimation);
const qreal startProgress = currentInterval.start.first;
const qreal endProgress = currentInterval.end.first;
const qreal localProgress = (progress - startProgress) / (endProgress - startProgress);
QVariant ret = q->interpolated(currentInterval.start.second,
currentInterval.end.second,
localProgress);
qSwap(currentValue, ret);
q->updateCurrentValue(currentValue);
static QBasicAtomicInt changedSignalIndex = Q_BASIC_ATOMIC_INITIALIZER(0);
if (!changedSignalIndex) {
//we keep the mask so that we emit valueChanged only when needed (for performance reasons)
changedSignalIndex.testAndSetRelaxed(0, signalIndex("valueChanged(QVariant)"));
}
if (isSignalConnected(changedSignalIndex) && currentValue != ret) {
//the value has changed
emit q->valueChanged(currentValue);
}
}
QVariant QVariantAnimationPrivate::valueAt(qreal step) const
{
QVariantAnimation::KeyValues::const_iterator result =
qBinaryFind(keyValues.begin(), keyValues.end(), qMakePair(step, QVariant()), animationValueLessThan);
if (result != keyValues.constEnd())
return result->second;
return QVariant();
}
void QVariantAnimationPrivate::setValueAt(qreal step, const QVariant &value)
{
if (step < qreal(0.0) || step > qreal(1.0)) {
qWarning("QVariantAnimation::setValueAt: invalid step = %f", step);
return;
}
QVariantAnimation::KeyValue pair(step, value);
QVariantAnimation::KeyValues::iterator result = qLowerBound(keyValues.begin(), keyValues.end(), pair, animationValueLessThan);
if (result == keyValues.end() || result->first != step) {
keyValues.insert(result, pair);
} else {
if (value.isValid())
result->second = value; // replaces the previous value
else
keyValues.erase(result); // removes the previous value
}
recalculateCurrentInterval(/*force=*/true);
}
void QVariantAnimationPrivate::setDefaultStartEndValue(const QVariant &value)
{
defaultStartEndValue = value;
recalculateCurrentInterval(/*force=*/true);
}
/*!
Construct a QVariantAnimation object. \a parent is passed to QAbstractAnimation's
constructor.
*/
QVariantAnimation::QVariantAnimation(QObject *parent) : QAbstractAnimation(*new QVariantAnimationPrivate, parent)
{
}
/*!
\internal
*/
QVariantAnimation::QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent) : QAbstractAnimation(dd, parent)
{
}
/*!
Destroys the animation.
*/
QVariantAnimation::~QVariantAnimation()
{
}
/*!
\property QVariantAnimation::easingCurve
\brief the easing curve of the animation
This property defines the easing curve of the animation. By
default, a linear easing curve is used, resulting in linear
interpolation. Other curves are provided, for instance,
QEasingCurve::InCirc, which provides a circular entry curve.
Another example is QEasingCurve::InOutElastic, which provides an
elastic effect on the values of the interpolated variant.
QVariantAnimation will use the QEasingCurve::valueForProgress() to
transform the "normalized progress" (currentTime / totalDuration)
of the animation into the effective progress actually
used by the animation. It is this effective progress that will be
the progress when interpolated() is called. Also, the steps in the
keyValues are referring to this effective progress.
The easing curve is used with the interpolator, the interpolated()
virtual function, the animation's duration, and iterationCount, to
control how the current value changes as the animation progresses.
*/
QEasingCurve QVariantAnimation::easingCurve() const
{
Q_D(const QVariantAnimation);
return d->easing;
}
void QVariantAnimation::setEasingCurve(const QEasingCurve &easing)
{
Q_D(QVariantAnimation);
d->easing = easing;
d->recalculateCurrentInterval();
}
typedef QVector<QVariantAnimation::Interpolator> QInterpolatorVector;
Q_GLOBAL_STATIC(QInterpolatorVector, registeredInterpolators)
/*!
\fn void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress))
\relates QVariantAnimation
\threadsafe
Registers a custom interpolator \a func for the template type \c{T}.
The interpolator has to be registered before the animation is constructed.
To unregister (and use the default interpolator) set \a func to 0.
*/
/*!
\internal
\typedef QVariantAnimation::Interpolator
This is a typedef for a pointer to a function with the following
signature:
\code
QVariant myInterpolator(const QVariant &from, const QVariant &to, qreal progress);
\endcode
*/
/*! \internal
* Registers a custom interpolator \a func for the specific \a interpolationType.
* The interpolator has to be registered before the animation is constructed.
* To unregister (and use the default interpolator) set \a func to 0.
*/
void QVariantAnimation::registerInterpolator(QVariantAnimation::Interpolator func, int interpolationType)
{
// will override any existing interpolators
QInterpolatorVector *interpolators = registeredInterpolators();
// When built on solaris with GCC, the destructors can be called
// in such an order that we get here with interpolators == NULL,
// to continue causes the app to crash on exit with a SEGV
if (interpolators) {
#ifndef QT_NO_THREAD
QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators));
#endif
if (int(interpolationType) >= interpolators->count())
interpolators->resize(int(interpolationType) + 1);
interpolators->replace(interpolationType, func);
}
}
template<typename T> static inline QVariantAnimation::Interpolator castToInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress))
{
return reinterpret_cast<QVariantAnimation::Interpolator>(func);
}
QVariantAnimation::Interpolator QVariantAnimationPrivate::getInterpolator(int interpolationType)
{
QInterpolatorVector *interpolators = registeredInterpolators();
#ifndef QT_NO_THREAD
QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators));
#endif
QVariantAnimation::Interpolator ret = 0;
if (interpolationType < interpolators->count()) {
ret = interpolators->at(interpolationType);
if (ret) return ret;
}
switch(interpolationType)
{
case QMetaType::Int:
return castToInterpolator(_q_interpolateVariant<int>);
case QMetaType::Double:
return castToInterpolator(_q_interpolateVariant<double>);
case QMetaType::Float:
return castToInterpolator(_q_interpolateVariant<float>);
case QMetaType::QLine:
return castToInterpolator(_q_interpolateVariant<QLine>);
case QMetaType::QLineF:
return castToInterpolator(_q_interpolateVariant<QLineF>);
case QMetaType::QPoint:
return castToInterpolator(_q_interpolateVariant<QPoint>);
case QMetaType::QPointF:
return castToInterpolator(_q_interpolateVariant<QPointF>);
case QMetaType::QSize:
return castToInterpolator(_q_interpolateVariant<QSize>);
case QMetaType::QSizeF:
return castToInterpolator(_q_interpolateVariant<QSizeF>);
case QMetaType::QRect:
return castToInterpolator(_q_interpolateVariant<QRect>);
case QMetaType::QRectF:
return castToInterpolator(_q_interpolateVariant<QRectF>);
default:
return 0; //this type is not handled
}
}
/*!
\property QVariantAnimation::duration
\brief the duration of the animation
This property describes the duration in milliseconds of the
animation. The default duration is 250 milliseconds.
\sa QAbstractAnimation::duration()
*/
int QVariantAnimation::duration() const
{
Q_D(const QVariantAnimation);
return d->duration;
}
void QVariantAnimation::setDuration(int msecs)
{
Q_D(QVariantAnimation);
if (msecs < 0) {
qWarning("QVariantAnimation::setDuration: cannot set a negative duration");
return;
}
if (d->duration == msecs)
return;
d->duration = msecs;
d->recalculateCurrentInterval();
}
/*!
\property QVariantAnimation::startValue
\brief the optional start value of the animation
This property describes the optional start value of the animation. If
omitted, or if a null QVariant is assigned as the start value, the
animation will use the current position of the end when the animation
is started.
\sa endValue
*/
QVariant QVariantAnimation::startValue() const
{
return keyValueAt(0);
}
void QVariantAnimation::setStartValue(const QVariant &value)
{
setKeyValueAt(0, value);
}
/*!
\property QVariantAnimation::endValue
\brief the end value of the animation
This property describes the end value of the animation.
\sa startValue
*/
QVariant QVariantAnimation::endValue() const
{
return keyValueAt(1);
}
void QVariantAnimation::setEndValue(const QVariant &value)
{
setKeyValueAt(1, value);
}
/*!
Returns the key frame value for the given \a step. The given \a step
must be in the range 0 to 1. If there is no KeyValue for \a step,
it returns an invalid QVariant.
\sa keyValues(), setKeyValueAt()
*/
QVariant QVariantAnimation::keyValueAt(qreal step) const
{
return d_func()->valueAt(step);
}
/*!
\typedef QVariantAnimation::KeyValue
This is a typedef for QPair<qreal, QVariant>.
*/
/*!
\typedef QVariantAnimation::KeyValues
This is a typedef for QVector<KeyValue>
*/
/*!
Creates a key frame at the given \a step with the given \a value.
The given \a step must be in the range 0 to 1.
\sa setKeyValues(), keyValueAt()
*/
void QVariantAnimation::setKeyValueAt(qreal step, const QVariant &value)
{
d_func()->setValueAt(step, value);
}
/*!
Returns the key frames of this animation.
\sa keyValueAt(), setKeyValues()
*/
QVariantAnimation::KeyValues QVariantAnimation::keyValues() const
{
return d_func()->keyValues;
}
/*!
Replaces the current set of key frames with the given \a keyValues.
the step of the key frames must be in the range 0 to 1.
\sa keyValues(), keyValueAt()
*/
void QVariantAnimation::setKeyValues(const KeyValues &keyValues)
{
Q_D(QVariantAnimation);
d->keyValues = keyValues;
qSort(d->keyValues.begin(), d->keyValues.end(), animationValueLessThan);
d->recalculateCurrentInterval(/*force=*/true);
}
/*!
\property QVariantAnimation::currentValue
\brief the current value of the animation.
This property describes the current value; an interpolated value
between the \l{startValue}{start value} and the \l{endValue}{end
value}, using the current time for progress. The value itself is
obtained from interpolated(), which is called repeatedly as the
animation is running.
QVariantAnimation calls the virtual updateCurrentValue() function
when the current value changes. This is particularly useful for
subclasses that need to track updates. For example,
QPropertyAnimation uses this function to animate Qt \l{Qt's
Property System}{properties}.
\sa startValue, endValue
*/
QVariant QVariantAnimation::currentValue() const
{
Q_D(const QVariantAnimation);
if (!d->currentValue.isValid())
const_cast<QVariantAnimationPrivate*>(d)->recalculateCurrentInterval();
return d->currentValue;
}
/*!
\reimp
*/
bool QVariantAnimation::event(QEvent *event)
{
return QAbstractAnimation::event(event);
}
/*!
\reimp
*/
void QVariantAnimation::updateState(QAbstractAnimation::State newState,
QAbstractAnimation::State oldState)
{
Q_UNUSED(oldState);
Q_UNUSED(newState);
}
/*!
This virtual function returns the linear interpolation between
variants \a from and \a to, at \a progress, usually a value
between 0 and 1. You can reimplement this function in a subclass
of QVariantAnimation to provide your own interpolation algorithm.
Note that in order for the interpolation to work with a
QEasingCurve that return a value smaller than 0 or larger than 1
(such as QEasingCurve::InBack) you should make sure that it can
extrapolate. If the semantic of the datatype does not allow
extrapolation this function should handle that gracefully.
You should call the QVariantAnimation implementation of this
function if you want your class to handle the types already
supported by Qt (see class QVariantAnimation description for a
list of supported types).
\sa QEasingCurve
*/
QVariant QVariantAnimation::interpolated(const QVariant &from, const QVariant &to, qreal progress) const
{
return d_func()->interpolator(from.constData(), to.constData(), progress);
}
/*!
\reimp
*/
void QVariantAnimation::updateCurrentTime(int)
{
d_func()->recalculateCurrentInterval();
}
QT_END_NAMESPACE
#include "moc_qvariantanimation.cpp"
#endif //QT_NO_ANIMATION
| bsd-3-clause |
tvandijck/premake-core | contrib/curl/lib/hostcheck.c | 20 | 4965 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(USE_OPENSSL) \
|| defined(USE_AXTLS) \
|| defined(USE_GSKIT) \
|| (defined(USE_SCHANNEL) && defined(_WIN32_WCE))
/* these backends use functions from this file */
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#include "hostcheck.h"
#include "strcase.h"
#include "inet_pton.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/*
* Match a hostname against a wildcard pattern.
* E.g.
* "foo.host.com" matches "*.host.com".
*
* We use the matching rule described in RFC6125, section 6.4.3.
* https://tools.ietf.org/html/rfc6125#section-6.4.3
*
* In addition: ignore trailing dots in the host names and wildcards, so that
* the names are used normalized. This is what the browsers do.
*
* Do not allow wildcard matching on IP numbers. There are apparently
* certificates being used with an IP address in the CN field, thus making no
* apparent distinction between a name and an IP. We need to detect the use of
* an IP address and not wildcard match on such names.
*
* NOTE: hostmatch() gets called with copied buffers so that it can modify the
* contents at will.
*/
static int hostmatch(char *hostname, char *pattern)
{
const char *pattern_label_end, *pattern_wildcard, *hostname_label_end;
int wildcard_enabled;
size_t prefixlen, suffixlen;
struct in_addr ignored;
#ifdef ENABLE_IPV6
struct sockaddr_in6 si6;
#endif
/* normalize pattern and hostname by stripping off trailing dots */
size_t len = strlen(hostname);
if(hostname[len-1]=='.')
hostname[len-1]=0;
len = strlen(pattern);
if(pattern[len-1]=='.')
pattern[len-1]=0;
pattern_wildcard = strchr(pattern, '*');
if(pattern_wildcard == NULL)
return strcasecompare(pattern, hostname) ?
CURL_HOST_MATCH : CURL_HOST_NOMATCH;
/* detect IP address as hostname and fail the match if so */
if(Curl_inet_pton(AF_INET, hostname, &ignored) > 0)
return CURL_HOST_NOMATCH;
#ifdef ENABLE_IPV6
else if(Curl_inet_pton(AF_INET6, hostname, &si6.sin6_addr) > 0)
return CURL_HOST_NOMATCH;
#endif
/* We require at least 2 dots in pattern to avoid too wide wildcard
match. */
wildcard_enabled = 1;
pattern_label_end = strchr(pattern, '.');
if(pattern_label_end == NULL || strchr(pattern_label_end+1, '.') == NULL ||
pattern_wildcard > pattern_label_end ||
strncasecompare(pattern, "xn--", 4)) {
wildcard_enabled = 0;
}
if(!wildcard_enabled)
return strcasecompare(pattern, hostname) ?
CURL_HOST_MATCH : CURL_HOST_NOMATCH;
hostname_label_end = strchr(hostname, '.');
if(hostname_label_end == NULL ||
!strcasecompare(pattern_label_end, hostname_label_end))
return CURL_HOST_NOMATCH;
/* The wildcard must match at least one character, so the left-most
label of the hostname is at least as large as the left-most label
of the pattern. */
if(hostname_label_end - hostname < pattern_label_end - pattern)
return CURL_HOST_NOMATCH;
prefixlen = pattern_wildcard - pattern;
suffixlen = pattern_label_end - (pattern_wildcard+1);
return strncasecompare(pattern, hostname, prefixlen) &&
strncasecompare(pattern_wildcard+1, hostname_label_end - suffixlen,
suffixlen) ?
CURL_HOST_MATCH : CURL_HOST_NOMATCH;
}
int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
{
char *matchp;
char *hostp;
int res = 0;
if(!match_pattern || !*match_pattern ||
!hostname || !*hostname) /* sanity check */
;
else {
matchp = strdup(match_pattern);
if(matchp) {
hostp = strdup(hostname);
if(hostp) {
if(hostmatch(hostp, matchp) == CURL_HOST_MATCH)
res= 1;
free(hostp);
}
free(matchp);
}
}
return res;
}
#endif /* OPENSSL, AXTLS, GSKIT or schannel+wince */
| bsd-3-clause |
AOSP-YU/platform_external_skia | gm/shadertext.cpp | 23 | 6640 | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
namespace skiagm {
static void makebm(SkBitmap* bm, int w, int h) {
bm->allocN32Pixels(w, h);
bm->eraseColor(SK_ColorTRANSPARENT);
SkCanvas canvas(*bm);
SkScalar s = SkIntToScalar(SkMin32(w, h));
SkPoint pts[] = { { 0, 0 }, { s, s } };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE };
SkScalar pos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
SkPaint paint;
paint.setDither(true);
paint.setShader(SkGradientShader::CreateLinear(pts, colors, pos,
SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode))->unref();
canvas.drawPaint(paint);
}
///////////////////////////////////////////////////////////////////////////////
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 5, gColors, NULL },
};
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX, data.fColors,
data.fPos, data.fCount, tm);
}
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount);
}
static SkShader* Make2Conical(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointConical(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm);
static const GradMaker gGradMakers[] = {
MakeLinear, MakeRadial, MakeSweep, Make2Conical
};
///////////////////////////////////////////////////////////////////////////////
class ShaderTextGM : public GM {
public:
ShaderTextGM() {
this->setBGColor(0xFFDDDDDD);
}
protected:
SkString onShortName() override {
return SkString("shadertext");
}
SkISize onISize() override { return SkISize::Make(1450, 500); }
void onDraw(SkCanvas* canvas) override {
const char text[] = "Shaded Text";
const int textLen = SK_ARRAY_COUNT(text) - 1;
const int pointSize = 36;
const int w = pointSize * textLen;
const int h = pointSize;
SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(w), SkIntToScalar(h) }
};
SkScalar textBase = SkIntToScalar(h/2);
SkShader::TileMode tileModes[] = {
SkShader::kClamp_TileMode,
SkShader::kRepeat_TileMode,
SkShader::kMirror_TileMode
};
static const int gradCount = SK_ARRAY_COUNT(gGradData) *
SK_ARRAY_COUNT(gGradMakers);
static const int bmpCount = SK_ARRAY_COUNT(tileModes) *
SK_ARRAY_COUNT(tileModes);
SkShader* shaders[gradCount + bmpCount];
int shdIdx = 0;
for (size_t d = 0; d < SK_ARRAY_COUNT(gGradData); ++d) {
for (size_t m = 0; m < SK_ARRAY_COUNT(gGradMakers); ++m) {
shaders[shdIdx++] = gGradMakers[m](pts,
gGradData[d],
SkShader::kClamp_TileMode);
}
}
SkBitmap bm;
makebm(&bm, w/16, h/4);
for (size_t tx = 0; tx < SK_ARRAY_COUNT(tileModes); ++tx) {
for (size_t ty = 0; ty < SK_ARRAY_COUNT(tileModes); ++ty) {
shaders[shdIdx++] = SkShader::CreateBitmapShader(bm, tileModes[tx], tileModes[ty]);
}
}
SkPaint paint;
paint.setDither(true);
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(SkIntToScalar(pointSize));
canvas->save();
canvas->translate(SkIntToScalar(20), SkIntToScalar(10));
SkPath path;
path.arcTo(SkRect::MakeXYWH(SkIntToScalar(-40), SkIntToScalar(15),
SkIntToScalar(300), SkIntToScalar(90)),
SkIntToScalar(225), SkIntToScalar(90),
false);
path.close();
static const int testsPerCol = 8;
static const int rowHeight = 60;
static const int colWidth = 300;
canvas->save();
for (int s = 0; s < static_cast<int>(SK_ARRAY_COUNT(shaders)); s++) {
canvas->save();
int i = 2*s;
canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth),
SkIntToScalar((i % testsPerCol) * rowHeight));
paint.setShader(shaders[s])->unref();
canvas->drawText(text, textLen, 0, textBase, paint);
canvas->restore();
canvas->save();
++i;
canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth),
SkIntToScalar((i % testsPerCol) * rowHeight));
canvas->drawTextOnPath(text, textLen, path, NULL, paint);
canvas->restore();
}
canvas->restore();
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new ShaderTextGM; }
static GMRegistry reg(MyFactory);
}
| bsd-3-clause |
AOKPSaber/android_external_skia | samplecode/SampleBigGradient.cpp | 25 | 1345 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
static SkShader* make_grad(SkScalar w, SkScalar h) {
SkColor colors[] = { 0xFF000000, 0xFF333333 };
SkPoint pts[] = { { 0, 0 }, { w, h } };
return SkGradientShader::CreateLinear(pts, colors, NULL, 2,
SkShader::kClamp_TileMode);
}
class BigGradientView : public SampleView {
public:
BigGradientView() {}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "BigGradient");
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual void onDrawContent(SkCanvas* canvas) {
SkRect r;
r.set(0, 0, this->width(), this->height());
SkPaint p;
p.setShader(make_grad(this->width(), this->height()))->unref();
canvas->drawRect(r, p);
}
private:
typedef SampleView INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new BigGradientView; }
static SkViewRegister reg(MyFactory);
| bsd-3-clause |
firebitsbr/golang-old | src/cmd/gc/const.c | 26 | 31421 | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <u.h>
#include <libc.h>
#include "go.h"
#define TUP(x,y) (((x)<<16)|(y))
/*c2go int TUP(int, int); */
static Val tocplx(Val);
static Val toflt(Val);
static Val tostr(Val);
static Val copyval(Val);
static void cmplxmpy(Mpcplx*, Mpcplx*);
static void cmplxdiv(Mpcplx*, Mpcplx*);
/*
* truncate float literal fv to 32-bit or 64-bit precision
* according to type; return truncated value.
*/
Mpflt*
truncfltlit(Mpflt *oldv, Type *t)
{
double d;
Mpflt *fv;
Val v;
if(t == T)
return oldv;
memset(&v, 0, sizeof v);
v.ctype = CTFLT;
v.u.fval = oldv;
overflow(v, t);
fv = mal(sizeof *fv);
*fv = *oldv;
// convert large precision literal floating
// into limited precision (float64 or float32)
switch(t->etype) {
case TFLOAT64:
d = mpgetflt(fv);
mpmovecflt(fv, d);
break;
case TFLOAT32:
d = mpgetflt32(fv);
mpmovecflt(fv, d);
break;
}
return fv;
}
/*
* convert n, if literal, to type t.
* implicit conversion.
*/
void
convlit(Node **np, Type *t)
{
convlit1(np, t, 0);
}
/*
* convert n, if literal, to type t.
* return a new node if necessary
* (if n is a named constant, can't edit n->type directly).
*/
void
convlit1(Node **np, Type *t, int explicit)
{
int ct, et;
Node *n, *nn;
n = *np;
if(n == N || t == T || n->type == T || isideal(t) || n->type == t)
return;
if(!explicit && !isideal(n->type))
return;
if(n->op == OLITERAL) {
nn = nod(OXXX, N, N);
*nn = *n;
n = nn;
*np = n;
}
switch(n->op) {
default:
if(n->type == idealbool) {
if(t->etype == TBOOL)
n->type = t;
else
n->type = types[TBOOL];
}
if(n->type->etype == TIDEAL) {
convlit(&n->left, t);
convlit(&n->right, t);
n->type = t;
}
return;
case OLITERAL:
// target is invalid type for a constant? leave alone.
if(!okforconst[t->etype] && n->type->etype != TNIL) {
defaultlit(&n, T);
*np = n;
return;
}
break;
case OLSH:
case ORSH:
convlit1(&n->left, t, explicit && isideal(n->left->type));
t = n->left->type;
if(t != T && t->etype == TIDEAL && n->val.ctype != CTINT)
n->val = toint(n->val);
if(t != T && !isint[t->etype]) {
yyerror("invalid operation: %N (shift of type %T)", n, t);
t = T;
}
n->type = t;
return;
case OCOMPLEX:
if(n->type->etype == TIDEAL) {
switch(t->etype) {
default:
// If trying to convert to non-complex type,
// leave as complex128 and let typechecker complain.
t = types[TCOMPLEX128];
//fallthrough
case TCOMPLEX128:
n->type = t;
convlit(&n->left, types[TFLOAT64]);
convlit(&n->right, types[TFLOAT64]);
break;
case TCOMPLEX64:
n->type = t;
convlit(&n->left, types[TFLOAT32]);
convlit(&n->right, types[TFLOAT32]);
break;
}
}
return;
}
// avoided repeated calculations, errors
if(eqtype(n->type, t))
return;
ct = consttype(n);
if(ct < 0)
goto bad;
et = t->etype;
if(et == TINTER) {
if(ct == CTNIL && n->type == types[TNIL]) {
n->type = t;
return;
}
defaultlit(np, T);
return;
}
switch(ct) {
default:
goto bad;
case CTNIL:
switch(et) {
default:
n->type = T;
goto bad;
case TSTRING:
// let normal conversion code handle it
return;
case TARRAY:
if(!isslice(t))
goto bad;
break;
case TPTR32:
case TPTR64:
case TINTER:
case TMAP:
case TCHAN:
case TFUNC:
case TUNSAFEPTR:
break;
case TUINTPTR:
// A nil literal may be converted to uintptr
// if it is an unsafe.Pointer
if(n->type->etype == TUNSAFEPTR) {
n->val.u.xval = mal(sizeof(*n->val.u.xval));
mpmovecfix(n->val.u.xval, 0);
n->val.ctype = CTINT;
} else
goto bad;
}
break;
case CTSTR:
case CTBOOL:
if(et != n->type->etype)
goto bad;
break;
case CTINT:
case CTRUNE:
case CTFLT:
case CTCPLX:
ct = n->val.ctype;
if(isint[et]) {
switch(ct) {
default:
goto bad;
case CTCPLX:
case CTFLT:
case CTRUNE:
n->val = toint(n->val);
// flowthrough
case CTINT:
overflow(n->val, t);
break;
}
} else
if(isfloat[et]) {
switch(ct) {
default:
goto bad;
case CTCPLX:
case CTINT:
case CTRUNE:
n->val = toflt(n->val);
// flowthrough
case CTFLT:
n->val.u.fval = truncfltlit(n->val.u.fval, t);
break;
}
} else
if(iscomplex[et]) {
switch(ct) {
default:
goto bad;
case CTFLT:
case CTINT:
case CTRUNE:
n->val = tocplx(n->val);
break;
case CTCPLX:
overflow(n->val, t);
break;
}
} else
if(et == TSTRING && (ct == CTINT || ct == CTRUNE) && explicit)
n->val = tostr(n->val);
else
goto bad;
break;
}
n->type = t;
return;
bad:
if(!n->diag) {
if(!t->broke)
yyerror("cannot convert %N to type %T", n, t);
n->diag = 1;
}
if(isideal(n->type)) {
defaultlit(&n, T);
*np = n;
}
return;
}
static Val
copyval(Val v)
{
Mpint *i;
Mpflt *f;
Mpcplx *c;
switch(v.ctype) {
case CTINT:
case CTRUNE:
i = mal(sizeof(*i));
mpmovefixfix(i, v.u.xval);
v.u.xval = i;
break;
case CTFLT:
f = mal(sizeof(*f));
mpmovefltflt(f, v.u.fval);
v.u.fval = f;
break;
case CTCPLX:
c = mal(sizeof(*c));
mpmovefltflt(&c->real, &v.u.cval->real);
mpmovefltflt(&c->imag, &v.u.cval->imag);
v.u.cval = c;
break;
}
return v;
}
static Val
tocplx(Val v)
{
Mpcplx *c;
switch(v.ctype) {
case CTINT:
case CTRUNE:
c = mal(sizeof(*c));
mpmovefixflt(&c->real, v.u.xval);
mpmovecflt(&c->imag, 0.0);
v.ctype = CTCPLX;
v.u.cval = c;
break;
case CTFLT:
c = mal(sizeof(*c));
mpmovefltflt(&c->real, v.u.fval);
mpmovecflt(&c->imag, 0.0);
v.ctype = CTCPLX;
v.u.cval = c;
break;
}
return v;
}
static Val
toflt(Val v)
{
Mpflt *f;
switch(v.ctype) {
case CTINT:
case CTRUNE:
f = mal(sizeof(*f));
mpmovefixflt(f, v.u.xval);
v.ctype = CTFLT;
v.u.fval = f;
break;
case CTCPLX:
f = mal(sizeof(*f));
mpmovefltflt(f, &v.u.cval->real);
if(mpcmpfltc(&v.u.cval->imag, 0) != 0)
yyerror("constant %#F%+#Fi truncated to real", &v.u.cval->real, &v.u.cval->imag);
v.ctype = CTFLT;
v.u.fval = f;
break;
}
return v;
}
Val
toint(Val v)
{
Mpint *i;
switch(v.ctype) {
case CTRUNE:
v.ctype = CTINT;
break;
case CTFLT:
i = mal(sizeof(*i));
if(mpmovefltfix(i, v.u.fval) < 0)
yyerror("constant %#F truncated to integer", v.u.fval);
v.ctype = CTINT;
v.u.xval = i;
break;
case CTCPLX:
i = mal(sizeof(*i));
if(mpmovefltfix(i, &v.u.cval->real) < 0)
yyerror("constant %#F%+#Fi truncated to integer", &v.u.cval->real, &v.u.cval->imag);
if(mpcmpfltc(&v.u.cval->imag, 0) != 0)
yyerror("constant %#F%+#Fi truncated to real", &v.u.cval->real, &v.u.cval->imag);
v.ctype = CTINT;
v.u.xval = i;
break;
}
return v;
}
int
doesoverflow(Val v, Type *t)
{
switch(v.ctype) {
case CTINT:
case CTRUNE:
if(!isint[t->etype])
fatal("overflow: %T integer constant", t);
if(mpcmpfixfix(v.u.xval, minintval[t->etype]) < 0 ||
mpcmpfixfix(v.u.xval, maxintval[t->etype]) > 0)
return 1;
break;
case CTFLT:
if(!isfloat[t->etype])
fatal("overflow: %T floating-point constant", t);
if(mpcmpfltflt(v.u.fval, minfltval[t->etype]) <= 0 ||
mpcmpfltflt(v.u.fval, maxfltval[t->etype]) >= 0)
return 1;
break;
case CTCPLX:
if(!iscomplex[t->etype])
fatal("overflow: %T complex constant", t);
if(mpcmpfltflt(&v.u.cval->real, minfltval[t->etype]) <= 0 ||
mpcmpfltflt(&v.u.cval->real, maxfltval[t->etype]) >= 0 ||
mpcmpfltflt(&v.u.cval->imag, minfltval[t->etype]) <= 0 ||
mpcmpfltflt(&v.u.cval->imag, maxfltval[t->etype]) >= 0)
return 1;
break;
}
return 0;
}
void
overflow(Val v, Type *t)
{
// v has already been converted
// to appropriate form for t.
if(t == T || t->etype == TIDEAL)
return;
if(!doesoverflow(v, t))
return;
switch(v.ctype) {
case CTINT:
case CTRUNE:
yyerror("constant %B overflows %T", v.u.xval, t);
break;
case CTFLT:
yyerror("constant %#F overflows %T", v.u.fval, t);
break;
case CTCPLX:
yyerror("constant %#F overflows %T", v.u.fval, t);
break;
}
}
static Val
tostr(Val v)
{
Rune rune;
int l;
Strlit *s;
switch(v.ctype) {
case CTINT:
case CTRUNE:
if(mpcmpfixfix(v.u.xval, minintval[TINT]) < 0 ||
mpcmpfixfix(v.u.xval, maxintval[TINT]) > 0)
yyerror("overflow in int -> string");
rune = mpgetfix(v.u.xval);
l = runelen(rune);
s = mal(sizeof(*s)+l);
s->len = l;
runetochar((char*)s->s, &rune);
memset(&v, 0, sizeof v);
v.ctype = CTSTR;
v.u.sval = s;
break;
case CTFLT:
yyerror("no float -> string");
case CTNIL:
memset(&v, 0, sizeof v);
v.ctype = CTSTR;
v.u.sval = mal(sizeof *s);
break;
}
return v;
}
int
consttype(Node *n)
{
if(n == N || n->op != OLITERAL)
return -1;
return n->val.ctype;
}
int
isconst(Node *n, int ct)
{
int t;
t = consttype(n);
// If the caller is asking for CTINT, allow CTRUNE too.
// Makes life easier for back ends.
return t == ct || (ct == CTINT && t == CTRUNE);
}
static Node*
saveorig(Node *n)
{
Node *n1;
if(n == n->orig) {
// duplicate node for n->orig.
n1 = nod(OLITERAL, N, N);
n->orig = n1;
*n1 = *n;
}
return n->orig;
}
/*
* if n is constant, rewrite as OLITERAL node.
*/
void
evconst(Node *n)
{
Node *nl, *nr, *norig;
int32 len;
Strlit *str;
int wl, wr, lno, et;
Val v, rv;
Mpint b;
NodeList *l1, *l2;
// pick off just the opcodes that can be
// constant evaluated.
switch(n->op) {
default:
return;
case OADD:
case OAND:
case OANDAND:
case OANDNOT:
case OARRAYBYTESTR:
case OCOM:
case ODIV:
case OEQ:
case OGE:
case OGT:
case OLE:
case OLSH:
case OLT:
case OMINUS:
case OMOD:
case OMUL:
case ONE:
case ONOT:
case OOR:
case OOROR:
case OPLUS:
case ORSH:
case OSUB:
case OXOR:
break;
case OCONV:
if(n->type == T)
return;
if(!okforconst[n->type->etype] && n->type->etype != TNIL)
return;
break;
case OADDSTR:
// merge adjacent constants in the argument list.
for(l1=n->list; l1 != nil; l1= l1->next) {
if(isconst(l1->n, CTSTR) && l1->next != nil && isconst(l1->next->n, CTSTR)) {
l2 = l1;
len = 0;
while(l2 != nil && isconst(l2->n, CTSTR)) {
nr = l2->n;
len += nr->val.u.sval->len;
l2 = l2->next;
}
// merge from l1 up to but not including l2
str = mal(sizeof(*str) + len);
str->len = len;
len = 0;
l2 = l1;
while(l2 != nil && isconst(l2->n, CTSTR)) {
nr = l2->n;
memmove(str->s+len, nr->val.u.sval->s, nr->val.u.sval->len);
len += nr->val.u.sval->len;
l2 = l2->next;
}
nl = nod(OXXX, N, N);
*nl = *l1->n;
nl->orig = nl;
nl->val.ctype = CTSTR;
nl->val.u.sval = str;
l1->n = nl;
l1->next = l2;
}
}
// fix list end pointer.
for(l2=n->list; l2 != nil; l2=l2->next)
n->list->end = l2;
// collapse single-constant list to single constant.
if(count(n->list) == 1 && isconst(n->list->n, CTSTR)) {
n->op = OLITERAL;
n->val = n->list->n->val;
}
return;
}
nl = n->left;
if(nl == N || nl->type == T)
return;
if(consttype(nl) < 0)
return;
wl = nl->type->etype;
if(isint[wl] || isfloat[wl] || iscomplex[wl])
wl = TIDEAL;
nr = n->right;
if(nr == N)
goto unary;
if(nr->type == T)
return;
if(consttype(nr) < 0)
return;
wr = nr->type->etype;
if(isint[wr] || isfloat[wr] || iscomplex[wr])
wr = TIDEAL;
// check for compatible general types (numeric, string, etc)
if(wl != wr)
goto illegal;
// check for compatible types.
switch(n->op) {
default:
// ideal const mixes with anything but otherwise must match.
if(nl->type->etype != TIDEAL) {
defaultlit(&nr, nl->type);
n->right = nr;
}
if(nr->type->etype != TIDEAL) {
defaultlit(&nl, nr->type);
n->left = nl;
}
if(nl->type->etype != nr->type->etype)
goto illegal;
break;
case OLSH:
case ORSH:
// right must be unsigned.
// left can be ideal.
defaultlit(&nr, types[TUINT]);
n->right = nr;
if(nr->type && (issigned[nr->type->etype] || !isint[nr->type->etype]))
goto illegal;
if(nl->val.ctype != CTRUNE)
nl->val = toint(nl->val);
nr->val = toint(nr->val);
break;
}
// copy numeric value to avoid modifying
// n->left, in case someone still refers to it (e.g. iota).
v = nl->val;
if(wl == TIDEAL)
v = copyval(v);
rv = nr->val;
// convert to common ideal
if(v.ctype == CTCPLX || rv.ctype == CTCPLX) {
v = tocplx(v);
rv = tocplx(rv);
}
if(v.ctype == CTFLT || rv.ctype == CTFLT) {
v = toflt(v);
rv = toflt(rv);
}
// Rune and int turns into rune.
if(v.ctype == CTRUNE && rv.ctype == CTINT)
rv.ctype = CTRUNE;
if(v.ctype == CTINT && rv.ctype == CTRUNE) {
if(n->op == OLSH || n->op == ORSH)
rv.ctype = CTINT;
else
v.ctype = CTRUNE;
}
if(v.ctype != rv.ctype) {
// Use of undefined name as constant?
if((v.ctype == 0 || rv.ctype == 0) && nerrors > 0)
return;
fatal("constant type mismatch %T(%d) %T(%d)", nl->type, v.ctype, nr->type, rv.ctype);
}
// run op
switch(TUP(n->op, v.ctype)) {
default:
illegal:
if(!n->diag) {
yyerror("illegal constant expression: %T %O %T",
nl->type, n->op, nr->type);
n->diag = 1;
}
return;
case TUP(OADD, CTINT):
case TUP(OADD, CTRUNE):
mpaddfixfix(v.u.xval, rv.u.xval, 0);
break;
case TUP(OSUB, CTINT):
case TUP(OSUB, CTRUNE):
mpsubfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OMUL, CTINT):
case TUP(OMUL, CTRUNE):
mpmulfixfix(v.u.xval, rv.u.xval);
break;
case TUP(ODIV, CTINT):
case TUP(ODIV, CTRUNE):
if(mpcmpfixc(rv.u.xval, 0) == 0) {
yyerror("division by zero");
mpmovecfix(v.u.xval, 1);
break;
}
mpdivfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OMOD, CTINT):
case TUP(OMOD, CTRUNE):
if(mpcmpfixc(rv.u.xval, 0) == 0) {
yyerror("division by zero");
mpmovecfix(v.u.xval, 1);
break;
}
mpmodfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OLSH, CTINT):
case TUP(OLSH, CTRUNE):
mplshfixfix(v.u.xval, rv.u.xval);
break;
case TUP(ORSH, CTINT):
case TUP(ORSH, CTRUNE):
mprshfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OOR, CTINT):
case TUP(OOR, CTRUNE):
mporfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OAND, CTINT):
case TUP(OAND, CTRUNE):
mpandfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OANDNOT, CTINT):
case TUP(OANDNOT, CTRUNE):
mpandnotfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OXOR, CTINT):
case TUP(OXOR, CTRUNE):
mpxorfixfix(v.u.xval, rv.u.xval);
break;
case TUP(OADD, CTFLT):
mpaddfltflt(v.u.fval, rv.u.fval);
break;
case TUP(OSUB, CTFLT):
mpsubfltflt(v.u.fval, rv.u.fval);
break;
case TUP(OMUL, CTFLT):
mpmulfltflt(v.u.fval, rv.u.fval);
break;
case TUP(ODIV, CTFLT):
if(mpcmpfltc(rv.u.fval, 0) == 0) {
yyerror("division by zero");
mpmovecflt(v.u.fval, 1.0);
break;
}
mpdivfltflt(v.u.fval, rv.u.fval);
break;
case TUP(OMOD, CTFLT):
// The default case above would print 'ideal % ideal',
// which is not quite an ideal error.
if(!n->diag) {
yyerror("illegal constant expression: floating-point %% operation");
n->diag = 1;
}
return;
case TUP(OADD, CTCPLX):
mpaddfltflt(&v.u.cval->real, &rv.u.cval->real);
mpaddfltflt(&v.u.cval->imag, &rv.u.cval->imag);
break;
case TUP(OSUB, CTCPLX):
mpsubfltflt(&v.u.cval->real, &rv.u.cval->real);
mpsubfltflt(&v.u.cval->imag, &rv.u.cval->imag);
break;
case TUP(OMUL, CTCPLX):
cmplxmpy(v.u.cval, rv.u.cval);
break;
case TUP(ODIV, CTCPLX):
if(mpcmpfltc(&rv.u.cval->real, 0) == 0 &&
mpcmpfltc(&rv.u.cval->imag, 0) == 0) {
yyerror("complex division by zero");
mpmovecflt(&rv.u.cval->real, 1.0);
mpmovecflt(&rv.u.cval->imag, 0.0);
break;
}
cmplxdiv(v.u.cval, rv.u.cval);
break;
case TUP(OEQ, CTNIL):
goto settrue;
case TUP(ONE, CTNIL):
goto setfalse;
case TUP(OEQ, CTINT):
case TUP(OEQ, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) == 0)
goto settrue;
goto setfalse;
case TUP(ONE, CTINT):
case TUP(ONE, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) != 0)
goto settrue;
goto setfalse;
case TUP(OLT, CTINT):
case TUP(OLT, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) < 0)
goto settrue;
goto setfalse;
case TUP(OLE, CTINT):
case TUP(OLE, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) <= 0)
goto settrue;
goto setfalse;
case TUP(OGE, CTINT):
case TUP(OGE, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) >= 0)
goto settrue;
goto setfalse;
case TUP(OGT, CTINT):
case TUP(OGT, CTRUNE):
if(mpcmpfixfix(v.u.xval, rv.u.xval) > 0)
goto settrue;
goto setfalse;
case TUP(OEQ, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) == 0)
goto settrue;
goto setfalse;
case TUP(ONE, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) != 0)
goto settrue;
goto setfalse;
case TUP(OLT, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) < 0)
goto settrue;
goto setfalse;
case TUP(OLE, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) <= 0)
goto settrue;
goto setfalse;
case TUP(OGE, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) >= 0)
goto settrue;
goto setfalse;
case TUP(OGT, CTFLT):
if(mpcmpfltflt(v.u.fval, rv.u.fval) > 0)
goto settrue;
goto setfalse;
case TUP(OEQ, CTCPLX):
if(mpcmpfltflt(&v.u.cval->real, &rv.u.cval->real) == 0 &&
mpcmpfltflt(&v.u.cval->imag, &rv.u.cval->imag) == 0)
goto settrue;
goto setfalse;
case TUP(ONE, CTCPLX):
if(mpcmpfltflt(&v.u.cval->real, &rv.u.cval->real) != 0 ||
mpcmpfltflt(&v.u.cval->imag, &rv.u.cval->imag) != 0)
goto settrue;
goto setfalse;
case TUP(OEQ, CTSTR):
if(cmpslit(nl, nr) == 0)
goto settrue;
goto setfalse;
case TUP(ONE, CTSTR):
if(cmpslit(nl, nr) != 0)
goto settrue;
goto setfalse;
case TUP(OLT, CTSTR):
if(cmpslit(nl, nr) < 0)
goto settrue;
goto setfalse;
case TUP(OLE, CTSTR):
if(cmpslit(nl, nr) <= 0)
goto settrue;
goto setfalse;
case TUP(OGE, CTSTR):
if(cmpslit(nl, nr) >= 0l)
goto settrue;
goto setfalse;
case TUP(OGT, CTSTR):
if(cmpslit(nl, nr) > 0)
goto settrue;
goto setfalse;
case TUP(OOROR, CTBOOL):
if(v.u.bval || rv.u.bval)
goto settrue;
goto setfalse;
case TUP(OANDAND, CTBOOL):
if(v.u.bval && rv.u.bval)
goto settrue;
goto setfalse;
case TUP(OEQ, CTBOOL):
if(v.u.bval == rv.u.bval)
goto settrue;
goto setfalse;
case TUP(ONE, CTBOOL):
if(v.u.bval != rv.u.bval)
goto settrue;
goto setfalse;
}
goto ret;
unary:
// copy numeric value to avoid modifying
// nl, in case someone still refers to it (e.g. iota).
v = nl->val;
if(wl == TIDEAL)
v = copyval(v);
switch(TUP(n->op, v.ctype)) {
default:
if(!n->diag) {
yyerror("illegal constant expression %O %T", n->op, nl->type);
n->diag = 1;
}
return;
case TUP(OCONV, CTNIL):
case TUP(OARRAYBYTESTR, CTNIL):
if(n->type->etype == TSTRING) {
v = tostr(v);
nl->type = n->type;
break;
}
// fall through
case TUP(OCONV, CTINT):
case TUP(OCONV, CTRUNE):
case TUP(OCONV, CTFLT):
case TUP(OCONV, CTSTR):
convlit1(&nl, n->type, 1);
v = nl->val;
break;
case TUP(OPLUS, CTINT):
case TUP(OPLUS, CTRUNE):
break;
case TUP(OMINUS, CTINT):
case TUP(OMINUS, CTRUNE):
mpnegfix(v.u.xval);
break;
case TUP(OCOM, CTINT):
case TUP(OCOM, CTRUNE):
et = Txxx;
if(nl->type != T)
et = nl->type->etype;
// calculate the mask in b
// result will be (a ^ mask)
switch(et) {
default:
// signed guys change sign
mpmovecfix(&b, -1);
break;
case TUINT8:
case TUINT16:
case TUINT32:
case TUINT64:
case TUINT:
case TUINTPTR:
// unsigned guys invert their bits
mpmovefixfix(&b, maxintval[et]);
break;
}
mpxorfixfix(v.u.xval, &b);
break;
case TUP(OPLUS, CTFLT):
break;
case TUP(OMINUS, CTFLT):
mpnegflt(v.u.fval);
break;
case TUP(OPLUS, CTCPLX):
break;
case TUP(OMINUS, CTCPLX):
mpnegflt(&v.u.cval->real);
mpnegflt(&v.u.cval->imag);
break;
case TUP(ONOT, CTBOOL):
if(!v.u.bval)
goto settrue;
goto setfalse;
}
ret:
norig = saveorig(n);
*n = *nl;
// restore value of n->orig.
n->orig = norig;
n->val = v;
// check range.
lno = setlineno(n);
overflow(v, n->type);
lineno = lno;
// truncate precision for non-ideal float.
if(v.ctype == CTFLT && n->type->etype != TIDEAL)
n->val.u.fval = truncfltlit(v.u.fval, n->type);
return;
settrue:
norig = saveorig(n);
*n = *nodbool(1);
n->orig = norig;
return;
setfalse:
norig = saveorig(n);
*n = *nodbool(0);
n->orig = norig;
return;
}
Node*
nodlit(Val v)
{
Node *n;
n = nod(OLITERAL, N, N);
n->val = v;
switch(v.ctype) {
default:
fatal("nodlit ctype %d", v.ctype);
case CTSTR:
n->type = idealstring;
break;
case CTBOOL:
n->type = idealbool;
break;
case CTINT:
case CTRUNE:
case CTFLT:
case CTCPLX:
n->type = types[TIDEAL];
break;
case CTNIL:
n->type = types[TNIL];
break;
}
return n;
}
Node*
nodcplxlit(Val r, Val i)
{
Node *n;
Mpcplx *c;
r = toflt(r);
i = toflt(i);
c = mal(sizeof(*c));
n = nod(OLITERAL, N, N);
n->type = types[TIDEAL];
n->val.u.cval = c;
n->val.ctype = CTCPLX;
if(r.ctype != CTFLT || i.ctype != CTFLT)
fatal("nodcplxlit ctype %d/%d", r.ctype, i.ctype);
mpmovefltflt(&c->real, r.u.fval);
mpmovefltflt(&c->imag, i.u.fval);
return n;
}
// idealkind returns a constant kind like consttype
// but for an arbitrary "ideal" (untyped constant) expression.
static int
idealkind(Node *n)
{
int k1, k2;
if(n == N || !isideal(n->type))
return CTxxx;
switch(n->op) {
default:
return CTxxx;
case OLITERAL:
return n->val.ctype;
case OADD:
case OAND:
case OANDNOT:
case OCOM:
case ODIV:
case OMINUS:
case OMOD:
case OMUL:
case OSUB:
case OXOR:
case OOR:
case OPLUS:
// numeric kinds.
k1 = idealkind(n->left);
k2 = idealkind(n->right);
if(k1 > k2)
return k1;
else
return k2;
case OREAL:
case OIMAG:
return CTFLT;
case OCOMPLEX:
return CTCPLX;
case OADDSTR:
return CTSTR;
case OANDAND:
case OEQ:
case OGE:
case OGT:
case OLE:
case OLT:
case ONE:
case ONOT:
case OOROR:
case OCMPSTR:
case OCMPIFACE:
return CTBOOL;
case OLSH:
case ORSH:
// shifts (beware!).
return idealkind(n->left);
}
}
void
defaultlit(Node **np, Type *t)
{
int lno;
int ctype;
Node *n, *nn;
Type *t1;
n = *np;
if(n == N || !isideal(n->type))
return;
if(n->op == OLITERAL) {
nn = nod(OXXX, N, N);
*nn = *n;
n = nn;
*np = n;
}
lno = setlineno(n);
ctype = idealkind(n);
switch(ctype) {
default:
if(t != T) {
convlit(np, t);
return;
}
if(n->val.ctype == CTNIL) {
lineno = lno;
if(!n->diag) {
yyerror("use of untyped nil");
n->diag = 1;
}
n->type = T;
break;
}
if(n->val.ctype == CTSTR) {
t1 = types[TSTRING];
convlit(np, t1);
break;
}
yyerror("defaultlit: unknown literal: %N", n);
break;
case CTxxx:
fatal("defaultlit: idealkind is CTxxx: %+N", n);
break;
case CTBOOL:
t1 = types[TBOOL];
if(t != T && t->etype == TBOOL)
t1 = t;
convlit(np, t1);
break;
case CTINT:
t1 = types[TINT];
goto num;
case CTRUNE:
t1 = runetype;
goto num;
case CTFLT:
t1 = types[TFLOAT64];
goto num;
case CTCPLX:
t1 = types[TCOMPLEX128];
goto num;
num:
if(t != T) {
if(isint[t->etype]) {
t1 = t;
n->val = toint(n->val);
}
else
if(isfloat[t->etype]) {
t1 = t;
n->val = toflt(n->val);
}
else
if(iscomplex[t->etype]) {
t1 = t;
n->val = tocplx(n->val);
}
}
overflow(n->val, t1);
convlit(np, t1);
break;
}
lineno = lno;
}
/*
* defaultlit on both nodes simultaneously;
* if they're both ideal going in they better
* get the same type going out.
* force means must assign concrete (non-ideal) type.
*/
void
defaultlit2(Node **lp, Node **rp, int force)
{
Node *l, *r;
int lkind, rkind;
l = *lp;
r = *rp;
if(l->type == T || r->type == T)
return;
if(!isideal(l->type)) {
convlit(rp, l->type);
return;
}
if(!isideal(r->type)) {
convlit(lp, r->type);
return;
}
if(!force)
return;
if(l->type->etype == TBOOL) {
convlit(lp, types[TBOOL]);
convlit(rp, types[TBOOL]);
}
lkind = idealkind(l);
rkind = idealkind(r);
if(lkind == CTCPLX || rkind == CTCPLX) {
convlit(lp, types[TCOMPLEX128]);
convlit(rp, types[TCOMPLEX128]);
return;
}
if(lkind == CTFLT || rkind == CTFLT) {
convlit(lp, types[TFLOAT64]);
convlit(rp, types[TFLOAT64]);
return;
}
if(lkind == CTRUNE || rkind == CTRUNE) {
convlit(lp, runetype);
convlit(rp, runetype);
return;
}
convlit(lp, types[TINT]);
convlit(rp, types[TINT]);
}
int
cmpslit(Node *l, Node *r)
{
int32 l1, l2, i, m;
uchar *s1, *s2;
l1 = l->val.u.sval->len;
l2 = r->val.u.sval->len;
s1 = (uchar*)l->val.u.sval->s;
s2 = (uchar*)r->val.u.sval->s;
m = l1;
if(l2 < m)
m = l2;
for(i=0; i<m; i++) {
if(s1[i] == s2[i])
continue;
if(s1[i] > s2[i])
return +1;
return -1;
}
if(l1 == l2)
return 0;
if(l1 > l2)
return +1;
return -1;
}
int
smallintconst(Node *n)
{
if(n->op == OLITERAL && isconst(n, CTINT) && n->type != T)
switch(simtype[n->type->etype]) {
case TINT8:
case TUINT8:
case TINT16:
case TUINT16:
case TINT32:
case TUINT32:
case TBOOL:
case TPTR32:
return 1;
case TIDEAL:
case TINT64:
case TUINT64:
case TPTR64:
if(mpcmpfixfix(n->val.u.xval, minintval[TINT32]) < 0
|| mpcmpfixfix(n->val.u.xval, maxintval[TINT32]) > 0)
break;
return 1;
}
return 0;
}
long
nonnegconst(Node *n)
{
if(n->op == OLITERAL && n->type != T)
switch(simtype[n->type->etype]) {
case TINT8:
case TUINT8:
case TINT16:
case TUINT16:
case TINT32:
case TUINT32:
case TINT64:
case TUINT64:
case TIDEAL:
// check negative and 2^31
if(mpcmpfixfix(n->val.u.xval, minintval[TUINT32]) < 0
|| mpcmpfixfix(n->val.u.xval, maxintval[TINT32]) > 0)
break;
return mpgetfix(n->val.u.xval);
}
return -1;
}
/*
* convert x to type et and back to int64
* for sign extension and truncation.
*/
static int64
iconv(int64 x, int et)
{
switch(et) {
case TINT8:
x = (int8)x;
break;
case TUINT8:
x = (uint8)x;
break;
case TINT16:
x = (int16)x;
break;
case TUINT16:
x = (uint64)x;
break;
case TINT32:
x = (int32)x;
break;
case TUINT32:
x = (uint32)x;
break;
case TINT64:
case TUINT64:
break;
}
return x;
}
/*
* convert constant val to type t; leave in con.
* for back end.
*/
void
convconst(Node *con, Type *t, Val *val)
{
int64 i;
int tt;
tt = simsimtype(t);
// copy the constant for conversion
nodconst(con, types[TINT8], 0);
con->type = t;
con->val = *val;
if(isint[tt]) {
con->val.ctype = CTINT;
con->val.u.xval = mal(sizeof *con->val.u.xval);
switch(val->ctype) {
default:
fatal("convconst ctype=%d %lT", val->ctype, t);
case CTINT:
case CTRUNE:
i = mpgetfix(val->u.xval);
break;
case CTBOOL:
i = val->u.bval;
break;
case CTNIL:
i = 0;
break;
}
i = iconv(i, tt);
mpmovecfix(con->val.u.xval, i);
return;
}
if(isfloat[tt]) {
con->val = toflt(con->val);
if(con->val.ctype != CTFLT)
fatal("convconst ctype=%d %T", con->val.ctype, t);
if(tt == TFLOAT32)
con->val.u.fval = truncfltlit(con->val.u.fval, t);
return;
}
if(iscomplex[tt]) {
con->val = tocplx(con->val);
if(tt == TCOMPLEX64) {
con->val.u.cval->real = *truncfltlit(&con->val.u.cval->real, types[TFLOAT32]);
con->val.u.cval->imag = *truncfltlit(&con->val.u.cval->imag, types[TFLOAT32]);
}
return;
}
fatal("convconst %lT constant", t);
}
// complex multiply v *= rv
// (a, b) * (c, d) = (a*c - b*d, b*c + a*d)
static void
cmplxmpy(Mpcplx *v, Mpcplx *rv)
{
Mpflt ac, bd, bc, ad;
mpmovefltflt(&ac, &v->real);
mpmulfltflt(&ac, &rv->real); // ac
mpmovefltflt(&bd, &v->imag);
mpmulfltflt(&bd, &rv->imag); // bd
mpmovefltflt(&bc, &v->imag);
mpmulfltflt(&bc, &rv->real); // bc
mpmovefltflt(&ad, &v->real);
mpmulfltflt(&ad, &rv->imag); // ad
mpmovefltflt(&v->real, &ac);
mpsubfltflt(&v->real, &bd); // ac-bd
mpmovefltflt(&v->imag, &bc);
mpaddfltflt(&v->imag, &ad); // bc+ad
}
// complex divide v /= rv
// (a, b) / (c, d) = ((a*c + b*d), (b*c - a*d))/(c*c + d*d)
static void
cmplxdiv(Mpcplx *v, Mpcplx *rv)
{
Mpflt ac, bd, bc, ad, cc_plus_dd;
mpmovefltflt(&cc_plus_dd, &rv->real);
mpmulfltflt(&cc_plus_dd, &rv->real); // cc
mpmovefltflt(&ac, &rv->imag);
mpmulfltflt(&ac, &rv->imag); // dd
mpaddfltflt(&cc_plus_dd, &ac); // cc+dd
mpmovefltflt(&ac, &v->real);
mpmulfltflt(&ac, &rv->real); // ac
mpmovefltflt(&bd, &v->imag);
mpmulfltflt(&bd, &rv->imag); // bd
mpmovefltflt(&bc, &v->imag);
mpmulfltflt(&bc, &rv->real); // bc
mpmovefltflt(&ad, &v->real);
mpmulfltflt(&ad, &rv->imag); // ad
mpmovefltflt(&v->real, &ac);
mpaddfltflt(&v->real, &bd); // ac+bd
mpdivfltflt(&v->real, &cc_plus_dd); // (ac+bd)/(cc+dd)
mpmovefltflt(&v->imag, &bc);
mpsubfltflt(&v->imag, &ad); // bc-ad
mpdivfltflt(&v->imag, &cc_plus_dd); // (bc+ad)/(cc+dd)
}
static int hascallchan(Node*);
// Is n a Go language constant (as opposed to a compile-time constant)?
// Expressions derived from nil, like string([]byte(nil)), while they
// may be known at compile time, are not Go language constants.
// Only called for expressions known to evaluated to compile-time
// constants.
int
isgoconst(Node *n)
{
Node *l;
Type *t;
if(n->orig != N)
n = n->orig;
switch(n->op) {
case OADD:
case OADDSTR:
case OAND:
case OANDAND:
case OANDNOT:
case OCOM:
case ODIV:
case OEQ:
case OGE:
case OGT:
case OLE:
case OLSH:
case OLT:
case OMINUS:
case OMOD:
case OMUL:
case ONE:
case ONOT:
case OOR:
case OOROR:
case OPLUS:
case ORSH:
case OSUB:
case OXOR:
case OIOTA:
case OCOMPLEX:
case OREAL:
case OIMAG:
if(isgoconst(n->left) && (n->right == N || isgoconst(n->right)))
return 1;
break;
case OCONV:
if(okforconst[n->type->etype] && isgoconst(n->left))
return 1;
break;
case OLEN:
case OCAP:
l = n->left;
if(isgoconst(l))
return 1;
// Special case: len/cap is constant when applied to array or
// pointer to array when the expression does not contain
// function calls or channel receive operations.
t = l->type;
if(t != T && isptr[t->etype])
t = t->type;
if(isfixedarray(t) && !hascallchan(l))
return 1;
break;
case OLITERAL:
if(n->val.ctype != CTNIL)
return 1;
break;
case ONAME:
l = n->sym->def;
if(l && l->op == OLITERAL && n->val.ctype != CTNIL)
return 1;
break;
case ONONAME:
if(n->sym->def != N && n->sym->def->op == OIOTA)
return 1;
break;
case OCALL:
// Only constant calls are unsafe.Alignof, Offsetof, and Sizeof.
l = n->left;
while(l->op == OPAREN)
l = l->left;
if(l->op != ONAME || l->sym->pkg != unsafepkg)
break;
if(strcmp(l->sym->name, "Alignof") == 0 ||
strcmp(l->sym->name, "Offsetof") == 0 ||
strcmp(l->sym->name, "Sizeof") == 0)
return 1;
break;
}
//dump("nonconst", n);
return 0;
}
static int
hascallchan(Node *n)
{
NodeList *l;
if(n == N)
return 0;
switch(n->op) {
case OAPPEND:
case OCALL:
case OCALLFUNC:
case OCALLINTER:
case OCALLMETH:
case OCAP:
case OCLOSE:
case OCOMPLEX:
case OCOPY:
case ODELETE:
case OIMAG:
case OLEN:
case OMAKE:
case ONEW:
case OPANIC:
case OPRINT:
case OPRINTN:
case OREAL:
case ORECOVER:
case ORECV:
return 1;
}
if(hascallchan(n->left) ||
hascallchan(n->right))
return 1;
for(l=n->list; l; l=l->next)
if(hascallchan(l->n))
return 1;
for(l=n->rlist; l; l=l->next)
if(hascallchan(l->n))
return 1;
return 0;
}
| bsd-3-clause |
OPM/eigen3 | blas/chpr.f | 28 | 6849 | SUBROUTINE CHPR(UPLO,N,ALPHA,X,INCX,AP)
* .. Scalar Arguments ..
REAL ALPHA
INTEGER INCX,N
CHARACTER UPLO
* ..
* .. Array Arguments ..
COMPLEX AP(*),X(*)
* ..
*
* Purpose
* =======
*
* CHPR performs the hermitian rank 1 operation
*
* A := alpha*x*conjg( x' ) + A,
*
* where alpha is a real scalar, x is an n element vector and A is an
* n by n hermitian matrix, supplied in packed form.
*
* Arguments
* ==========
*
* UPLO - CHARACTER*1.
* On entry, UPLO specifies whether the upper or lower
* triangular part of the matrix A is supplied in the packed
* array AP as follows:
*
* UPLO = 'U' or 'u' The upper triangular part of A is
* supplied in AP.
*
* UPLO = 'L' or 'l' The lower triangular part of A is
* supplied in AP.
*
* Unchanged on exit.
*
* N - INTEGER.
* On entry, N specifies the order of the matrix A.
* N must be at least zero.
* Unchanged on exit.
*
* ALPHA - REAL .
* On entry, ALPHA specifies the scalar alpha.
* Unchanged on exit.
*
* X - COMPLEX array of dimension at least
* ( 1 + ( n - 1 )*abs( INCX ) ).
* Before entry, the incremented array X must contain the n
* element vector x.
* Unchanged on exit.
*
* INCX - INTEGER.
* On entry, INCX specifies the increment for the elements of
* X. INCX must not be zero.
* Unchanged on exit.
*
* AP - COMPLEX array of DIMENSION at least
* ( ( n*( n + 1 ) )/2 ).
* Before entry with UPLO = 'U' or 'u', the array AP must
* contain the upper triangular part of the hermitian matrix
* packed sequentially, column by column, so that AP( 1 )
* contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 1, 2 )
* and a( 2, 2 ) respectively, and so on. On exit, the array
* AP is overwritten by the upper triangular part of the
* updated matrix.
* Before entry with UPLO = 'L' or 'l', the array AP must
* contain the lower triangular part of the hermitian matrix
* packed sequentially, column by column, so that AP( 1 )
* contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 )
* and a( 3, 1 ) respectively, and so on. On exit, the array
* AP is overwritten by the lower triangular part of the
* updated matrix.
* Note that the imaginary parts of the diagonal elements need
* not be set, they are assumed to be zero, and on exit they
* are set to zero.
*
* Further Details
* ===============
*
* Level 2 Blas routine.
*
* -- Written on 22-October-1986.
* Jack Dongarra, Argonne National Lab.
* Jeremy Du Croz, Nag Central Office.
* Sven Hammarling, Nag Central Office.
* Richard Hanson, Sandia National Labs.
*
* =====================================================================
*
* .. Parameters ..
COMPLEX ZERO
PARAMETER (ZERO= (0.0E+0,0.0E+0))
* ..
* .. Local Scalars ..
COMPLEX TEMP
INTEGER I,INFO,IX,J,JX,K,KK,KX
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC CONJG,REAL
* ..
*
* Test the input parameters.
*
INFO = 0
IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN
INFO = 1
ELSE IF (N.LT.0) THEN
INFO = 2
ELSE IF (INCX.EQ.0) THEN
INFO = 5
END IF
IF (INFO.NE.0) THEN
CALL XERBLA('CHPR ',INFO)
RETURN
END IF
*
* Quick return if possible.
*
IF ((N.EQ.0) .OR. (ALPHA.EQ.REAL(ZERO))) RETURN
*
* Set the start point in X if the increment is not unity.
*
IF (INCX.LE.0) THEN
KX = 1 - (N-1)*INCX
ELSE IF (INCX.NE.1) THEN
KX = 1
END IF
*
* Start the operations. In this version the elements of the array AP
* are accessed sequentially with one pass through AP.
*
KK = 1
IF (LSAME(UPLO,'U')) THEN
*
* Form A when upper triangle is stored in AP.
*
IF (INCX.EQ.1) THEN
DO 20 J = 1,N
IF (X(J).NE.ZERO) THEN
TEMP = ALPHA*CONJG(X(J))
K = KK
DO 10 I = 1,J - 1
AP(K) = AP(K) + X(I)*TEMP
K = K + 1
10 CONTINUE
AP(KK+J-1) = REAL(AP(KK+J-1)) + REAL(X(J)*TEMP)
ELSE
AP(KK+J-1) = REAL(AP(KK+J-1))
END IF
KK = KK + J
20 CONTINUE
ELSE
JX = KX
DO 40 J = 1,N
IF (X(JX).NE.ZERO) THEN
TEMP = ALPHA*CONJG(X(JX))
IX = KX
DO 30 K = KK,KK + J - 2
AP(K) = AP(K) + X(IX)*TEMP
IX = IX + INCX
30 CONTINUE
AP(KK+J-1) = REAL(AP(KK+J-1)) + REAL(X(JX)*TEMP)
ELSE
AP(KK+J-1) = REAL(AP(KK+J-1))
END IF
JX = JX + INCX
KK = KK + J
40 CONTINUE
END IF
ELSE
*
* Form A when lower triangle is stored in AP.
*
IF (INCX.EQ.1) THEN
DO 60 J = 1,N
IF (X(J).NE.ZERO) THEN
TEMP = ALPHA*CONJG(X(J))
AP(KK) = REAL(AP(KK)) + REAL(TEMP*X(J))
K = KK + 1
DO 50 I = J + 1,N
AP(K) = AP(K) + X(I)*TEMP
K = K + 1
50 CONTINUE
ELSE
AP(KK) = REAL(AP(KK))
END IF
KK = KK + N - J + 1
60 CONTINUE
ELSE
JX = KX
DO 80 J = 1,N
IF (X(JX).NE.ZERO) THEN
TEMP = ALPHA*CONJG(X(JX))
AP(KK) = REAL(AP(KK)) + REAL(TEMP*X(JX))
IX = JX
DO 70 K = KK + 1,KK + N - J
IX = IX + INCX
AP(K) = AP(K) + X(IX)*TEMP
70 CONTINUE
ELSE
AP(KK) = REAL(AP(KK))
END IF
JX = JX + INCX
KK = KK + N - J + 1
80 CONTINUE
END IF
END IF
*
RETURN
*
* End of CHPR .
*
END
| bsd-3-clause |
UPenn-RoboCup/OpenBLAS | lapack-netlib/SRC/dstevd.f | 29 | 9120 | *> \brief <b> DSTEVD computes the eigenvalues and, optionally, the left and/or right eigenvectors for OTHER matrices</b>
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download DSTEVD + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dstevd.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dstevd.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dstevd.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE DSTEVD( JOBZ, N, D, E, Z, LDZ, WORK, LWORK, IWORK,
* LIWORK, INFO )
*
* .. Scalar Arguments ..
* CHARACTER JOBZ
* INTEGER INFO, LDZ, LIWORK, LWORK, N
* ..
* .. Array Arguments ..
* INTEGER IWORK( * )
* DOUBLE PRECISION D( * ), E( * ), WORK( * ), Z( LDZ, * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> DSTEVD computes all eigenvalues and, optionally, eigenvectors of a
*> real symmetric tridiagonal matrix. If eigenvectors are desired, it
*> uses a divide and conquer algorithm.
*>
*> The divide and conquer algorithm makes very mild assumptions about
*> floating point arithmetic. It will work on machines with a guard
*> digit in add/subtract, or on those binary machines without guard
*> digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or
*> Cray-2. It could conceivably fail on hexadecimal or decimal machines
*> without guard digits, but we know of none.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] JOBZ
*> \verbatim
*> JOBZ is CHARACTER*1
*> = 'N': Compute eigenvalues only;
*> = 'V': Compute eigenvalues and eigenvectors.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The order of the matrix. N >= 0.
*> \endverbatim
*>
*> \param[in,out] D
*> \verbatim
*> D is DOUBLE PRECISION array, dimension (N)
*> On entry, the n diagonal elements of the tridiagonal matrix
*> A.
*> On exit, if INFO = 0, the eigenvalues in ascending order.
*> \endverbatim
*>
*> \param[in,out] E
*> \verbatim
*> E is DOUBLE PRECISION array, dimension (N-1)
*> On entry, the (n-1) subdiagonal elements of the tridiagonal
*> matrix A, stored in elements 1 to N-1 of E.
*> On exit, the contents of E are destroyed.
*> \endverbatim
*>
*> \param[out] Z
*> \verbatim
*> Z is DOUBLE PRECISION array, dimension (LDZ, N)
*> If JOBZ = 'V', then if INFO = 0, Z contains the orthonormal
*> eigenvectors of the matrix A, with the i-th column of Z
*> holding the eigenvector associated with D(i).
*> If JOBZ = 'N', then Z is not referenced.
*> \endverbatim
*>
*> \param[in] LDZ
*> \verbatim
*> LDZ is INTEGER
*> The leading dimension of the array Z. LDZ >= 1, and if
*> JOBZ = 'V', LDZ >= max(1,N).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is DOUBLE PRECISION array,
*> dimension (LWORK)
*> On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
*> \endverbatim
*>
*> \param[in] LWORK
*> \verbatim
*> LWORK is INTEGER
*> The dimension of the array WORK.
*> If JOBZ = 'N' or N <= 1 then LWORK must be at least 1.
*> If JOBZ = 'V' and N > 1 then LWORK must be at least
*> ( 1 + 4*N + N**2 ).
*>
*> If LWORK = -1, then a workspace query is assumed; the routine
*> only calculates the optimal sizes of the WORK and IWORK
*> arrays, returns these values as the first entries of the WORK
*> and IWORK arrays, and no error message related to LWORK or
*> LIWORK is issued by XERBLA.
*> \endverbatim
*>
*> \param[out] IWORK
*> \verbatim
*> IWORK is INTEGER array, dimension (MAX(1,LIWORK))
*> On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK.
*> \endverbatim
*>
*> \param[in] LIWORK
*> \verbatim
*> LIWORK is INTEGER
*> The dimension of the array IWORK.
*> If JOBZ = 'N' or N <= 1 then LIWORK must be at least 1.
*> If JOBZ = 'V' and N > 1 then LIWORK must be at least 3+5*N.
*>
*> If LIWORK = -1, then a workspace query is assumed; the
*> routine only calculates the optimal sizes of the WORK and
*> IWORK arrays, returns these values as the first entries of
*> the WORK and IWORK arrays, and no error message related to
*> LWORK or LIWORK is issued by XERBLA.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value
*> > 0: if INFO = i, the algorithm failed to converge; i
*> off-diagonal elements of E did not converge to zero.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup doubleOTHEReigen
*
* =====================================================================
SUBROUTINE DSTEVD( JOBZ, N, D, E, Z, LDZ, WORK, LWORK, IWORK,
$ LIWORK, INFO )
*
* -- LAPACK driver routine (version 3.4.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2011
*
* .. Scalar Arguments ..
CHARACTER JOBZ
INTEGER INFO, LDZ, LIWORK, LWORK, N
* ..
* .. Array Arguments ..
INTEGER IWORK( * )
DOUBLE PRECISION D( * ), E( * ), WORK( * ), Z( LDZ, * )
* ..
*
* =====================================================================
*
* .. Parameters ..
DOUBLE PRECISION ZERO, ONE
PARAMETER ( ZERO = 0.0D0, ONE = 1.0D0 )
* ..
* .. Local Scalars ..
LOGICAL LQUERY, WANTZ
INTEGER ISCALE, LIWMIN, LWMIN
DOUBLE PRECISION BIGNUM, EPS, RMAX, RMIN, SAFMIN, SIGMA, SMLNUM,
$ TNRM
* ..
* .. External Functions ..
LOGICAL LSAME
DOUBLE PRECISION DLAMCH, DLANST
EXTERNAL LSAME, DLAMCH, DLANST
* ..
* .. External Subroutines ..
EXTERNAL DSCAL, DSTEDC, DSTERF, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC SQRT
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
WANTZ = LSAME( JOBZ, 'V' )
LQUERY = ( LWORK.EQ.-1 .OR. LIWORK.EQ.-1 )
*
INFO = 0
LIWMIN = 1
LWMIN = 1
IF( N.GT.1 .AND. WANTZ ) THEN
LWMIN = 1 + 4*N + N**2
LIWMIN = 3 + 5*N
END IF
*
IF( .NOT.( WANTZ .OR. LSAME( JOBZ, 'N' ) ) ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( LDZ.LT.1 .OR. ( WANTZ .AND. LDZ.LT.N ) ) THEN
INFO = -6
END IF
*
IF( INFO.EQ.0 ) THEN
WORK( 1 ) = LWMIN
IWORK( 1 ) = LIWMIN
*
IF( LWORK.LT.LWMIN .AND. .NOT.LQUERY ) THEN
INFO = -8
ELSE IF( LIWORK.LT.LIWMIN .AND. .NOT.LQUERY ) THEN
INFO = -10
END IF
END IF
*
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'DSTEVD', -INFO )
RETURN
ELSE IF( LQUERY ) THEN
RETURN
END IF
*
* Quick return if possible
*
IF( N.EQ.0 )
$ RETURN
*
IF( N.EQ.1 ) THEN
IF( WANTZ )
$ Z( 1, 1 ) = ONE
RETURN
END IF
*
* Get machine constants.
*
SAFMIN = DLAMCH( 'Safe minimum' )
EPS = DLAMCH( 'Precision' )
SMLNUM = SAFMIN / EPS
BIGNUM = ONE / SMLNUM
RMIN = SQRT( SMLNUM )
RMAX = SQRT( BIGNUM )
*
* Scale matrix to allowable range, if necessary.
*
ISCALE = 0
TNRM = DLANST( 'M', N, D, E )
IF( TNRM.GT.ZERO .AND. TNRM.LT.RMIN ) THEN
ISCALE = 1
SIGMA = RMIN / TNRM
ELSE IF( TNRM.GT.RMAX ) THEN
ISCALE = 1
SIGMA = RMAX / TNRM
END IF
IF( ISCALE.EQ.1 ) THEN
CALL DSCAL( N, SIGMA, D, 1 )
CALL DSCAL( N-1, SIGMA, E( 1 ), 1 )
END IF
*
* For eigenvalues only, call DSTERF. For eigenvalues and
* eigenvectors, call DSTEDC.
*
IF( .NOT.WANTZ ) THEN
CALL DSTERF( N, D, E, INFO )
ELSE
CALL DSTEDC( 'I', N, D, E, Z, LDZ, WORK, LWORK, IWORK, LIWORK,
$ INFO )
END IF
*
* If matrix was scaled, then rescale eigenvalues appropriately.
*
IF( ISCALE.EQ.1 )
$ CALL DSCAL( N, ONE / SIGMA, D, 1 )
*
WORK( 1 ) = LWMIN
IWORK( 1 ) = LIWMIN
*
RETURN
*
* End of DSTEVD
*
END
| bsd-3-clause |
tkelman/OpenBLAS | lapack-netlib/TESTING/EIG/ssbt21.f | 32 | 7790 | *> \brief \b SSBT21
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
* Definition:
* ===========
*
* SUBROUTINE SSBT21( UPLO, N, KA, KS, A, LDA, D, E, U, LDU, WORK,
* RESULT )
*
* .. Scalar Arguments ..
* CHARACTER UPLO
* INTEGER KA, KS, LDA, LDU, N
* ..
* .. Array Arguments ..
* REAL A( LDA, * ), D( * ), E( * ), RESULT( 2 ),
* $ U( LDU, * ), WORK( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> SSBT21 generally checks a decomposition of the form
*>
*> A = U S U'
*>
*> where ' means transpose, A is symmetric banded, U is
*> orthogonal, and S is diagonal (if KS=0) or symmetric
*> tridiagonal (if KS=1).
*>
*> Specifically:
*>
*> RESULT(1) = | A - U S U' | / ( |A| n ulp ) *andC> RESULT(2) = | I - UU' | / ( n ulp )
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] UPLO
*> \verbatim
*> UPLO is CHARACTER
*> If UPLO='U', the upper triangle of A and V will be used and
*> the (strictly) lower triangle will not be referenced.
*> If UPLO='L', the lower triangle of A and V will be used and
*> the (strictly) upper triangle will not be referenced.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The size of the matrix. If it is zero, SSBT21 does nothing.
*> It must be at least zero.
*> \endverbatim
*>
*> \param[in] KA
*> \verbatim
*> KA is INTEGER
*> The bandwidth of the matrix A. It must be at least zero. If
*> it is larger than N-1, then max( 0, N-1 ) will be used.
*> \endverbatim
*>
*> \param[in] KS
*> \verbatim
*> KS is INTEGER
*> The bandwidth of the matrix S. It may only be zero or one.
*> If zero, then S is diagonal, and E is not referenced. If
*> one, then S is symmetric tri-diagonal.
*> \endverbatim
*>
*> \param[in] A
*> \verbatim
*> A is REAL array, dimension (LDA, N)
*> The original (unfactored) matrix. It is assumed to be
*> symmetric, and only the upper (UPLO='U') or only the lower
*> (UPLO='L') will be referenced.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> The leading dimension of A. It must be at least 1
*> and at least min( KA, N-1 ).
*> \endverbatim
*>
*> \param[in] D
*> \verbatim
*> D is REAL array, dimension (N)
*> The diagonal of the (symmetric tri-) diagonal matrix S.
*> \endverbatim
*>
*> \param[in] E
*> \verbatim
*> E is REAL array, dimension (N-1)
*> The off-diagonal of the (symmetric tri-) diagonal matrix S.
*> E(1) is the (1,2) and (2,1) element, E(2) is the (2,3) and
*> (3,2) element, etc.
*> Not referenced if KS=0.
*> \endverbatim
*>
*> \param[in] U
*> \verbatim
*> U is REAL array, dimension (LDU, N)
*> The orthogonal matrix in the decomposition, expressed as a
*> dense matrix (i.e., not as a product of Householder
*> transformations, Givens transformations, etc.)
*> \endverbatim
*>
*> \param[in] LDU
*> \verbatim
*> LDU is INTEGER
*> The leading dimension of U. LDU must be at least N and
*> at least 1.
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is REAL array, dimension (N**2+N)
*> \endverbatim
*>
*> \param[out] RESULT
*> \verbatim
*> RESULT is REAL array, dimension (2)
*> The values computed by the two tests described above. The
*> values are currently limited to 1/ulp, to avoid overflow.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup single_eig
*
* =====================================================================
SUBROUTINE SSBT21( UPLO, N, KA, KS, A, LDA, D, E, U, LDU, WORK,
$ RESULT )
*
* -- LAPACK test routine (version 3.4.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2011
*
* .. Scalar Arguments ..
CHARACTER UPLO
INTEGER KA, KS, LDA, LDU, N
* ..
* .. Array Arguments ..
REAL A( LDA, * ), D( * ), E( * ), RESULT( 2 ),
$ U( LDU, * ), WORK( * )
* ..
*
* =====================================================================
*
* .. Parameters ..
REAL ZERO, ONE
PARAMETER ( ZERO = 0.0E0, ONE = 1.0E0 )
* ..
* .. Local Scalars ..
LOGICAL LOWER
CHARACTER CUPLO
INTEGER IKA, J, JC, JR, LW
REAL ANORM, ULP, UNFL, WNORM
* ..
* .. External Functions ..
LOGICAL LSAME
REAL SLAMCH, SLANGE, SLANSB, SLANSP
EXTERNAL LSAME, SLAMCH, SLANGE, SLANSB, SLANSP
* ..
* .. External Subroutines ..
EXTERNAL SGEMM, SSPR, SSPR2
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX, MIN, REAL
* ..
* .. Executable Statements ..
*
* Constants
*
RESULT( 1 ) = ZERO
RESULT( 2 ) = ZERO
IF( N.LE.0 )
$ RETURN
*
IKA = MAX( 0, MIN( N-1, KA ) )
LW = ( N*( N+1 ) ) / 2
*
IF( LSAME( UPLO, 'U' ) ) THEN
LOWER = .FALSE.
CUPLO = 'U'
ELSE
LOWER = .TRUE.
CUPLO = 'L'
END IF
*
UNFL = SLAMCH( 'Safe minimum' )
ULP = SLAMCH( 'Epsilon' )*SLAMCH( 'Base' )
*
* Some Error Checks
*
* Do Test 1
*
* Norm of A:
*
ANORM = MAX( SLANSB( '1', CUPLO, N, IKA, A, LDA, WORK ), UNFL )
*
* Compute error matrix: Error = A - U S U'
*
* Copy A from SB to SP storage format.
*
J = 0
DO 50 JC = 1, N
IF( LOWER ) THEN
DO 10 JR = 1, MIN( IKA+1, N+1-JC )
J = J + 1
WORK( J ) = A( JR, JC )
10 CONTINUE
DO 20 JR = IKA + 2, N + 1 - JC
J = J + 1
WORK( J ) = ZERO
20 CONTINUE
ELSE
DO 30 JR = IKA + 2, JC
J = J + 1
WORK( J ) = ZERO
30 CONTINUE
DO 40 JR = MIN( IKA, JC-1 ), 0, -1
J = J + 1
WORK( J ) = A( IKA+1-JR, JC )
40 CONTINUE
END IF
50 CONTINUE
*
DO 60 J = 1, N
CALL SSPR( CUPLO, N, -D( J ), U( 1, J ), 1, WORK )
60 CONTINUE
*
IF( N.GT.1 .AND. KS.EQ.1 ) THEN
DO 70 J = 1, N - 1
CALL SSPR2( CUPLO, N, -E( J ), U( 1, J ), 1, U( 1, J+1 ), 1,
$ WORK )
70 CONTINUE
END IF
WNORM = SLANSP( '1', CUPLO, N, WORK, WORK( LW+1 ) )
*
IF( ANORM.GT.WNORM ) THEN
RESULT( 1 ) = ( WNORM / ANORM ) / ( N*ULP )
ELSE
IF( ANORM.LT.ONE ) THEN
RESULT( 1 ) = ( MIN( WNORM, N*ANORM ) / ANORM ) / ( N*ULP )
ELSE
RESULT( 1 ) = MIN( WNORM / ANORM, REAL( N ) ) / ( N*ULP )
END IF
END IF
*
* Do Test 2
*
* Compute UU' - I
*
CALL SGEMM( 'N', 'C', N, N, N, ONE, U, LDU, U, LDU, ZERO, WORK,
$ N )
*
DO 80 J = 1, N
WORK( ( N+1 )*( J-1 )+1 ) = WORK( ( N+1 )*( J-1 )+1 ) - ONE
80 CONTINUE
*
RESULT( 2 ) = MIN( SLANGE( '1', N, N, WORK, N, WORK( N**2+1 ) ),
$ REAL( N ) ) / ( N*ULP )
*
RETURN
*
* End of SSBT21
*
END
| bsd-3-clause |
endlessm/chromium-browser | third_party/llvm/clang/test/Index/print-mangled-name.cpp | 37 | 1107 | // REQUIRES: x86-registered-target
// RUN: c-index-test -write-pch %t_linux.ast -target i686-pc-linux-gnu %s
// RUN: c-index-test -test-print-mangle %t_linux.ast | FileCheck %s --check-prefix=ITANIUM
// RUN: c-index-test -write-pch %t_macho.ast -target x86_64-apple-darwin %s
// RUN: c-index-test -test-print-mangle %t_macho.ast | FileCheck %s --check-prefix=MACHO
// RUN: c-index-test -write-pch %t_msft.ast -target i686-pc-win32 %s
// RUN: c-index-test -test-print-mangle %t_msft.ast | FileCheck %s --check-prefix=MICROSOFT
int foo(int, int);
// ITANIUM: mangled=_Z3fooii
// MACHO: mangled=__Z3fooii
// MICROSOFT: mangled=?foo@@YAHHH
int foo(float, int);
// ITANIUM: mangled=_Z3foofi
// MACHO: mangled=__Z3foofi
// MICROSOFT: mangled=?foo@@YAHMH
struct S {
int x, y;
};
// ITANIUM: StructDecl{{.*}}mangled=]
// MACHO: StructDecl{{.*}}mangled=]
// MICROSOFT: StructDecl{{.*}}mangled=]
int foo(S, S&);
// ITANIUM: mangled=_Z3foo1SRS_
// MACHO: mangled=__Z3foo1SRS_
// MICROSOFT: mangled=?foo@@YAHUS
extern "C" int foo(int);
// ITANIUM: mangled=foo
// MACHO: mangled=_foo
// MICROSOFT: mangled=_foo
| bsd-3-clause |
pizzathief/scipy | scipy/optimize/minpack/dpmpar.f | 38 | 5806 | recursive
*double precision function dpmpar(i)
integer i
c **********
c
c Function dpmpar
c
c This function provides double precision machine parameters
c when the appropriate set of data statements is activated (by
c removing the c from column 1) and all other data statements are
c rendered inactive. Most of the parameter values were obtained
c from the corresponding Bell Laboratories Port Library function.
c
c The function statement is
c
c double precision function dpmpar(i)
c
c where
c
c i is an integer input variable set to 1, 2, or 3 which
c selects the desired machine parameter. If the machine has
c t base b digits and its smallest and largest exponents are
c emin and emax, respectively, then these parameters are
c
c dpmpar(1) = b**(1 - t), the machine precision,
c
c dpmpar(2) = b**(emin - 1), the smallest magnitude,
c
c dpmpar(3) = b**emax*(1 - b**(-t)), the largest magnitude.
c
c Argonne National Laboratory. MINPACK Project. November 1996.
c Burton S. Garbow, Kenneth E. Hillstrom, Jorge J. More'
c
c **********
integer mcheps(4)
integer minmag(4)
integer maxmag(4)
double precision dmach(3)
equivalence (dmach(1),mcheps(1))
equivalence (dmach(2),minmag(1))
equivalence (dmach(3),maxmag(1))
c
c Machine constants for the IBM 360/370 series,
c the Amdahl 470/V6, the ICL 2900, the Itel AS/6,
c the Xerox Sigma 5/7/9 and the Sel systems 85/86.
c
c data mcheps(1),mcheps(2) / z34100000, z00000000 /
c data minmag(1),minmag(2) / z00100000, z00000000 /
c data maxmag(1),maxmag(2) / z7fffffff, zffffffff /
c
c Machine constants for the Honeywell 600/6000 series.
c
c data mcheps(1),mcheps(2) / o606400000000, o000000000000 /
c data minmag(1),minmag(2) / o402400000000, o000000000000 /
c data maxmag(1),maxmag(2) / o376777777777, o777777777777 /
c
c Machine constants for the CDC 6000/7000 series.
c
c data mcheps(1) / 15614000000000000000b /
c data mcheps(2) / 15010000000000000000b /
c
c data minmag(1) / 00604000000000000000b /
c data minmag(2) / 00000000000000000000b /
c
c data maxmag(1) / 37767777777777777777b /
c data maxmag(2) / 37167777777777777777b /
c
c Machine constants for the PDP-10 (KA processor).
c
c data mcheps(1),mcheps(2) / "114400000000, "000000000000 /
c data minmag(1),minmag(2) / "033400000000, "000000000000 /
c data maxmag(1),maxmag(2) / "377777777777, "344777777777 /
c
c Machine constants for the PDP-10 (KI processor).
c
c data mcheps(1),mcheps(2) / "104400000000, "000000000000 /
c data minmag(1),minmag(2) / "000400000000, "000000000000 /
c data maxmag(1),maxmag(2) / "377777777777, "377777777777 /
c
c Machine constants for the PDP-11.
c
c data mcheps(1),mcheps(2) / 9472, 0 /
c data mcheps(3),mcheps(4) / 0, 0 /
c
c data minmag(1),minmag(2) / 128, 0 /
c data minmag(3),minmag(4) / 0, 0 /
c
c data maxmag(1),maxmag(2) / 32767, -1 /
c data maxmag(3),maxmag(4) / -1, -1 /
c
c Machine constants for the Burroughs 6700/7700 systems.
c
c data mcheps(1) / o1451000000000000 /
c data mcheps(2) / o0000000000000000 /
c
c data minmag(1) / o1771000000000000 /
c data minmag(2) / o7770000000000000 /
c
c data maxmag(1) / o0777777777777777 /
c data maxmag(2) / o7777777777777777 /
c
c Machine constants for the Burroughs 5700 system.
c
c data mcheps(1) / o1451000000000000 /
c data mcheps(2) / o0000000000000000 /
c
c data minmag(1) / o1771000000000000 /
c data minmag(2) / o0000000000000000 /
c
c data maxmag(1) / o0777777777777777 /
c data maxmag(2) / o0007777777777777 /
c
c Machine constants for the Burroughs 1700 system.
c
c data mcheps(1) / zcc6800000 /
c data mcheps(2) / z000000000 /
c
c data minmag(1) / zc00800000 /
c data minmag(2) / z000000000 /
c
c data maxmag(1) / zdffffffff /
c data maxmag(2) / zfffffffff /
c
c Machine constants for the Univac 1100 series.
c
c data mcheps(1),mcheps(2) / o170640000000, o000000000000 /
c data minmag(1),minmag(2) / o000040000000, o000000000000 /
c data maxmag(1),maxmag(2) / o377777777777, o777777777777 /
c
c Machine constants for the Data General Eclipse S/200.
c
c Note - it may be appropriate to include the following card -
c static dmach(3)
c
c data minmag/20k,3*0/,maxmag/77777k,3*177777k/
c data mcheps/32020k,3*0/
c
c Machine constants for the Harris 220.
c
c data mcheps(1),mcheps(2) / '20000000, '00000334 /
c data minmag(1),minmag(2) / '20000000, '00000201 /
c data maxmag(1),maxmag(2) / '37777777, '37777577 /
c
c Machine constants for the Cray-1.
c
c data mcheps(1) / 0376424000000000000000b /
c data mcheps(2) / 0000000000000000000000b /
c
c data minmag(1) / 0200034000000000000000b /
c data minmag(2) / 0000000000000000000000b /
c
c data maxmag(1) / 0577777777777777777777b /
c data maxmag(2) / 0000007777777777777776b /
c
c Machine constants for the Prime 400.
c
c data mcheps(1),mcheps(2) / :10000000000, :00000000123 /
c data minmag(1),minmag(2) / :10000000000, :00000100000 /
c data maxmag(1),maxmag(2) / :17777777777, :37777677776 /
c
c Machine constants for the VAX-11.
c
c data mcheps(1),mcheps(2) / 9472, 0 /
c data minmag(1),minmag(2) / 128, 0 /
c data maxmag(1),maxmag(2) / -32769, -1 /
c
c Machine constants for IEEE machines.
c
data dmach(1) /2.22044604926d-16/
data dmach(2) /2.22507385852d-308/
data dmach(3) /1.79769313485d+308/
c
dpmpar = dmach(i)
return
c
c Last card of function dpmpar.
c
end
| bsd-3-clause |
ut-osa/laminar | linux-2.6.22.6/net/rxrpc/ar-call.c | 61 | 21718 | /* RxRPC individual remote procedure call handling
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.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/module.h>
#include <linux/circ_buf.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include "ar-internal.h"
const char *rxrpc_call_states[] = {
[RXRPC_CALL_CLIENT_SEND_REQUEST] = "ClSndReq",
[RXRPC_CALL_CLIENT_AWAIT_REPLY] = "ClAwtRpl",
[RXRPC_CALL_CLIENT_RECV_REPLY] = "ClRcvRpl",
[RXRPC_CALL_CLIENT_FINAL_ACK] = "ClFnlACK",
[RXRPC_CALL_SERVER_SECURING] = "SvSecure",
[RXRPC_CALL_SERVER_ACCEPTING] = "SvAccept",
[RXRPC_CALL_SERVER_RECV_REQUEST] = "SvRcvReq",
[RXRPC_CALL_SERVER_ACK_REQUEST] = "SvAckReq",
[RXRPC_CALL_SERVER_SEND_REPLY] = "SvSndRpl",
[RXRPC_CALL_SERVER_AWAIT_ACK] = "SvAwtACK",
[RXRPC_CALL_COMPLETE] = "Complete",
[RXRPC_CALL_SERVER_BUSY] = "SvBusy ",
[RXRPC_CALL_REMOTELY_ABORTED] = "RmtAbort",
[RXRPC_CALL_LOCALLY_ABORTED] = "LocAbort",
[RXRPC_CALL_NETWORK_ERROR] = "NetError",
[RXRPC_CALL_DEAD] = "Dead ",
};
struct kmem_cache *rxrpc_call_jar;
LIST_HEAD(rxrpc_calls);
DEFINE_RWLOCK(rxrpc_call_lock);
static unsigned rxrpc_call_max_lifetime = 60;
static unsigned rxrpc_dead_call_timeout = 2;
static void rxrpc_destroy_call(struct work_struct *work);
static void rxrpc_call_life_expired(unsigned long _call);
static void rxrpc_dead_call_expired(unsigned long _call);
static void rxrpc_ack_time_expired(unsigned long _call);
static void rxrpc_resend_time_expired(unsigned long _call);
/*
* allocate a new call
*/
static struct rxrpc_call *rxrpc_alloc_call(gfp_t gfp)
{
struct rxrpc_call *call;
call = kmem_cache_zalloc(rxrpc_call_jar, gfp);
if (!call)
return NULL;
call->acks_winsz = 16;
call->acks_window = kmalloc(call->acks_winsz * sizeof(unsigned long),
gfp);
if (!call->acks_window) {
kmem_cache_free(rxrpc_call_jar, call);
return NULL;
}
setup_timer(&call->lifetimer, &rxrpc_call_life_expired,
(unsigned long) call);
setup_timer(&call->deadspan, &rxrpc_dead_call_expired,
(unsigned long) call);
setup_timer(&call->ack_timer, &rxrpc_ack_time_expired,
(unsigned long) call);
setup_timer(&call->resend_timer, &rxrpc_resend_time_expired,
(unsigned long) call);
INIT_WORK(&call->destroyer, &rxrpc_destroy_call);
INIT_WORK(&call->processor, &rxrpc_process_call);
INIT_LIST_HEAD(&call->accept_link);
skb_queue_head_init(&call->rx_queue);
skb_queue_head_init(&call->rx_oos_queue);
init_waitqueue_head(&call->tx_waitq);
spin_lock_init(&call->lock);
rwlock_init(&call->state_lock);
atomic_set(&call->usage, 1);
call->debug_id = atomic_inc_return(&rxrpc_debug_id);
call->state = RXRPC_CALL_CLIENT_SEND_REQUEST;
memset(&call->sock_node, 0xed, sizeof(call->sock_node));
call->rx_data_expect = 1;
call->rx_data_eaten = 0;
call->rx_first_oos = 0;
call->ackr_win_top = call->rx_data_eaten + 1 + RXRPC_MAXACKS;
call->creation_jif = jiffies;
return call;
}
/*
* allocate a new client call and attempt to to get a connection slot for it
*/
static struct rxrpc_call *rxrpc_alloc_client_call(
struct rxrpc_sock *rx,
struct rxrpc_transport *trans,
struct rxrpc_conn_bundle *bundle,
gfp_t gfp)
{
struct rxrpc_call *call;
int ret;
_enter("");
ASSERT(rx != NULL);
ASSERT(trans != NULL);
ASSERT(bundle != NULL);
call = rxrpc_alloc_call(gfp);
if (!call)
return ERR_PTR(-ENOMEM);
sock_hold(&rx->sk);
call->socket = rx;
call->rx_data_post = 1;
ret = rxrpc_connect_call(rx, trans, bundle, call, gfp);
if (ret < 0) {
kmem_cache_free(rxrpc_call_jar, call);
return ERR_PTR(ret);
}
spin_lock(&call->conn->trans->peer->lock);
list_add(&call->error_link, &call->conn->trans->peer->error_targets);
spin_unlock(&call->conn->trans->peer->lock);
call->lifetimer.expires = jiffies + rxrpc_call_max_lifetime * HZ;
add_timer(&call->lifetimer);
_leave(" = %p", call);
return call;
}
/*
* set up a call for the given data
* - called in process context with IRQs enabled
*/
struct rxrpc_call *rxrpc_get_client_call(struct rxrpc_sock *rx,
struct rxrpc_transport *trans,
struct rxrpc_conn_bundle *bundle,
unsigned long user_call_ID,
int create,
gfp_t gfp)
{
struct rxrpc_call *call, *candidate;
struct rb_node *p, *parent, **pp;
_enter("%p,%d,%d,%lx,%d",
rx, trans ? trans->debug_id : -1, bundle ? bundle->debug_id : -1,
user_call_ID, create);
/* search the extant calls first for one that matches the specified
* user ID */
read_lock(&rx->call_lock);
p = rx->calls.rb_node;
while (p) {
call = rb_entry(p, struct rxrpc_call, sock_node);
if (user_call_ID < call->user_call_ID)
p = p->rb_left;
else if (user_call_ID > call->user_call_ID)
p = p->rb_right;
else
goto found_extant_call;
}
read_unlock(&rx->call_lock);
if (!create || !trans)
return ERR_PTR(-EBADSLT);
/* not yet present - create a candidate for a new record and then
* redo the search */
candidate = rxrpc_alloc_client_call(rx, trans, bundle, gfp);
if (IS_ERR(candidate)) {
_leave(" = %ld", PTR_ERR(candidate));
return candidate;
}
candidate->user_call_ID = user_call_ID;
__set_bit(RXRPC_CALL_HAS_USERID, &candidate->flags);
write_lock(&rx->call_lock);
pp = &rx->calls.rb_node;
parent = NULL;
while (*pp) {
parent = *pp;
call = rb_entry(parent, struct rxrpc_call, sock_node);
if (user_call_ID < call->user_call_ID)
pp = &(*pp)->rb_left;
else if (user_call_ID > call->user_call_ID)
pp = &(*pp)->rb_right;
else
goto found_extant_second;
}
/* second search also failed; add the new call */
call = candidate;
candidate = NULL;
rxrpc_get_call(call);
rb_link_node(&call->sock_node, parent, pp);
rb_insert_color(&call->sock_node, &rx->calls);
write_unlock(&rx->call_lock);
write_lock_bh(&rxrpc_call_lock);
list_add_tail(&call->link, &rxrpc_calls);
write_unlock_bh(&rxrpc_call_lock);
_net("CALL new %d on CONN %d", call->debug_id, call->conn->debug_id);
_leave(" = %p [new]", call);
return call;
/* we found the call in the list immediately */
found_extant_call:
rxrpc_get_call(call);
read_unlock(&rx->call_lock);
_leave(" = %p [extant %d]", call, atomic_read(&call->usage));
return call;
/* we found the call on the second time through the list */
found_extant_second:
rxrpc_get_call(call);
write_unlock(&rx->call_lock);
rxrpc_put_call(candidate);
_leave(" = %p [second %d]", call, atomic_read(&call->usage));
return call;
}
/*
* set up an incoming call
* - called in process context with IRQs enabled
*/
struct rxrpc_call *rxrpc_incoming_call(struct rxrpc_sock *rx,
struct rxrpc_connection *conn,
struct rxrpc_header *hdr,
gfp_t gfp)
{
struct rxrpc_call *call, *candidate;
struct rb_node **p, *parent;
__be32 call_id;
_enter(",%d,,%x", conn->debug_id, gfp);
ASSERT(rx != NULL);
candidate = rxrpc_alloc_call(gfp);
if (!candidate)
return ERR_PTR(-EBUSY);
candidate->socket = rx;
candidate->conn = conn;
candidate->cid = hdr->cid;
candidate->call_id = hdr->callNumber;
candidate->channel = ntohl(hdr->cid) & RXRPC_CHANNELMASK;
candidate->rx_data_post = 0;
candidate->state = RXRPC_CALL_SERVER_ACCEPTING;
if (conn->security_ix > 0)
candidate->state = RXRPC_CALL_SERVER_SECURING;
write_lock_bh(&conn->lock);
/* set the channel for this call */
call = conn->channels[candidate->channel];
_debug("channel[%u] is %p", candidate->channel, call);
if (call && call->call_id == hdr->callNumber) {
/* already set; must've been a duplicate packet */
_debug("extant call [%d]", call->state);
ASSERTCMP(call->conn, ==, conn);
read_lock(&call->state_lock);
switch (call->state) {
case RXRPC_CALL_LOCALLY_ABORTED:
if (!test_and_set_bit(RXRPC_CALL_ABORT, &call->events))
rxrpc_queue_call(call);
case RXRPC_CALL_REMOTELY_ABORTED:
read_unlock(&call->state_lock);
goto aborted_call;
default:
rxrpc_get_call(call);
read_unlock(&call->state_lock);
goto extant_call;
}
}
if (call) {
/* it seems the channel is still in use from the previous call
* - ditch the old binding if its call is now complete */
_debug("CALL: %u { %s }",
call->debug_id, rxrpc_call_states[call->state]);
if (call->state >= RXRPC_CALL_COMPLETE) {
conn->channels[call->channel] = NULL;
} else {
write_unlock_bh(&conn->lock);
kmem_cache_free(rxrpc_call_jar, candidate);
_leave(" = -EBUSY");
return ERR_PTR(-EBUSY);
}
}
/* check the call number isn't duplicate */
_debug("check dup");
call_id = hdr->callNumber;
p = &conn->calls.rb_node;
parent = NULL;
while (*p) {
parent = *p;
call = rb_entry(parent, struct rxrpc_call, conn_node);
if (call_id < call->call_id)
p = &(*p)->rb_left;
else if (call_id > call->call_id)
p = &(*p)->rb_right;
else
goto old_call;
}
/* make the call available */
_debug("new call");
call = candidate;
candidate = NULL;
rb_link_node(&call->conn_node, parent, p);
rb_insert_color(&call->conn_node, &conn->calls);
conn->channels[call->channel] = call;
sock_hold(&rx->sk);
atomic_inc(&conn->usage);
write_unlock_bh(&conn->lock);
spin_lock(&conn->trans->peer->lock);
list_add(&call->error_link, &conn->trans->peer->error_targets);
spin_unlock(&conn->trans->peer->lock);
write_lock_bh(&rxrpc_call_lock);
list_add_tail(&call->link, &rxrpc_calls);
write_unlock_bh(&rxrpc_call_lock);
_net("CALL incoming %d on CONN %d", call->debug_id, call->conn->debug_id);
call->lifetimer.expires = jiffies + rxrpc_call_max_lifetime * HZ;
add_timer(&call->lifetimer);
_leave(" = %p {%d} [new]", call, call->debug_id);
return call;
extant_call:
write_unlock_bh(&conn->lock);
kmem_cache_free(rxrpc_call_jar, candidate);
_leave(" = %p {%d} [extant]", call, call ? call->debug_id : -1);
return call;
aborted_call:
write_unlock_bh(&conn->lock);
kmem_cache_free(rxrpc_call_jar, candidate);
_leave(" = -ECONNABORTED");
return ERR_PTR(-ECONNABORTED);
old_call:
write_unlock_bh(&conn->lock);
kmem_cache_free(rxrpc_call_jar, candidate);
_leave(" = -ECONNRESET [old]");
return ERR_PTR(-ECONNRESET);
}
/*
* find an extant server call
* - called in process context with IRQs enabled
*/
struct rxrpc_call *rxrpc_find_server_call(struct rxrpc_sock *rx,
unsigned long user_call_ID)
{
struct rxrpc_call *call;
struct rb_node *p;
_enter("%p,%lx", rx, user_call_ID);
/* search the extant calls for one that matches the specified user
* ID */
read_lock(&rx->call_lock);
p = rx->calls.rb_node;
while (p) {
call = rb_entry(p, struct rxrpc_call, sock_node);
if (user_call_ID < call->user_call_ID)
p = p->rb_left;
else if (user_call_ID > call->user_call_ID)
p = p->rb_right;
else
goto found_extant_call;
}
read_unlock(&rx->call_lock);
_leave(" = NULL");
return NULL;
/* we found the call in the list immediately */
found_extant_call:
rxrpc_get_call(call);
read_unlock(&rx->call_lock);
_leave(" = %p [%d]", call, atomic_read(&call->usage));
return call;
}
/*
* detach a call from a socket and set up for release
*/
void rxrpc_release_call(struct rxrpc_call *call)
{
struct rxrpc_connection *conn = call->conn;
struct rxrpc_sock *rx = call->socket;
_enter("{%d,%d,%d,%d}",
call->debug_id, atomic_read(&call->usage),
atomic_read(&call->ackr_not_idle),
call->rx_first_oos);
spin_lock_bh(&call->lock);
if (test_and_set_bit(RXRPC_CALL_RELEASED, &call->flags))
BUG();
spin_unlock_bh(&call->lock);
/* dissociate from the socket
* - the socket's ref on the call is passed to the death timer
*/
_debug("RELEASE CALL %p (%d CONN %p)", call, call->debug_id, conn);
write_lock_bh(&rx->call_lock);
if (!list_empty(&call->accept_link)) {
_debug("unlinking once-pending call %p { e=%lx f=%lx }",
call, call->events, call->flags);
ASSERT(!test_bit(RXRPC_CALL_HAS_USERID, &call->flags));
list_del_init(&call->accept_link);
sk_acceptq_removed(&rx->sk);
} else if (test_bit(RXRPC_CALL_HAS_USERID, &call->flags)) {
rb_erase(&call->sock_node, &rx->calls);
memset(&call->sock_node, 0xdd, sizeof(call->sock_node));
clear_bit(RXRPC_CALL_HAS_USERID, &call->flags);
}
write_unlock_bh(&rx->call_lock);
/* free up the channel for reuse */
spin_lock(&conn->trans->client_lock);
write_lock_bh(&conn->lock);
write_lock(&call->state_lock);
if (conn->channels[call->channel] == call)
conn->channels[call->channel] = NULL;
if (conn->out_clientflag && conn->bundle) {
conn->avail_calls++;
switch (conn->avail_calls) {
case 1:
list_move_tail(&conn->bundle_link,
&conn->bundle->avail_conns);
case 2 ... RXRPC_MAXCALLS - 1:
ASSERT(conn->channels[0] == NULL ||
conn->channels[1] == NULL ||
conn->channels[2] == NULL ||
conn->channels[3] == NULL);
break;
case RXRPC_MAXCALLS:
list_move_tail(&conn->bundle_link,
&conn->bundle->unused_conns);
ASSERT(conn->channels[0] == NULL &&
conn->channels[1] == NULL &&
conn->channels[2] == NULL &&
conn->channels[3] == NULL);
break;
default:
printk(KERN_ERR "RxRPC: conn->avail_calls=%d\n",
conn->avail_calls);
BUG();
}
}
spin_unlock(&conn->trans->client_lock);
if (call->state < RXRPC_CALL_COMPLETE &&
call->state != RXRPC_CALL_CLIENT_FINAL_ACK) {
_debug("+++ ABORTING STATE %d +++\n", call->state);
call->state = RXRPC_CALL_LOCALLY_ABORTED;
call->abort_code = RX_CALL_DEAD;
set_bit(RXRPC_CALL_ABORT, &call->events);
rxrpc_queue_call(call);
}
write_unlock(&call->state_lock);
write_unlock_bh(&conn->lock);
/* clean up the Rx queue */
if (!skb_queue_empty(&call->rx_queue) ||
!skb_queue_empty(&call->rx_oos_queue)) {
struct rxrpc_skb_priv *sp;
struct sk_buff *skb;
_debug("purge Rx queues");
spin_lock_bh(&call->lock);
while ((skb = skb_dequeue(&call->rx_queue)) ||
(skb = skb_dequeue(&call->rx_oos_queue))) {
sp = rxrpc_skb(skb);
if (sp->call) {
ASSERTCMP(sp->call, ==, call);
rxrpc_put_call(call);
sp->call = NULL;
}
skb->destructor = NULL;
spin_unlock_bh(&call->lock);
_debug("- zap %s %%%u #%u",
rxrpc_pkts[sp->hdr.type],
ntohl(sp->hdr.serial),
ntohl(sp->hdr.seq));
rxrpc_free_skb(skb);
spin_lock_bh(&call->lock);
}
spin_unlock_bh(&call->lock);
ASSERTCMP(call->state, !=, RXRPC_CALL_COMPLETE);
}
del_timer_sync(&call->resend_timer);
del_timer_sync(&call->ack_timer);
del_timer_sync(&call->lifetimer);
call->deadspan.expires = jiffies + rxrpc_dead_call_timeout * HZ;
add_timer(&call->deadspan);
_leave("");
}
/*
* handle a dead call being ready for reaping
*/
static void rxrpc_dead_call_expired(unsigned long _call)
{
struct rxrpc_call *call = (struct rxrpc_call *) _call;
_enter("{%d}", call->debug_id);
write_lock_bh(&call->state_lock);
call->state = RXRPC_CALL_DEAD;
write_unlock_bh(&call->state_lock);
rxrpc_put_call(call);
}
/*
* mark a call as to be released, aborting it if it's still in progress
* - called with softirqs disabled
*/
static void rxrpc_mark_call_released(struct rxrpc_call *call)
{
bool sched;
write_lock(&call->state_lock);
if (call->state < RXRPC_CALL_DEAD) {
sched = false;
if (call->state < RXRPC_CALL_COMPLETE) {
_debug("abort call %p", call);
call->state = RXRPC_CALL_LOCALLY_ABORTED;
call->abort_code = RX_CALL_DEAD;
if (!test_and_set_bit(RXRPC_CALL_ABORT, &call->events))
sched = true;
}
if (!test_and_set_bit(RXRPC_CALL_RELEASE, &call->events))
sched = true;
if (sched)
rxrpc_queue_call(call);
}
write_unlock(&call->state_lock);
}
/*
* release all the calls associated with a socket
*/
void rxrpc_release_calls_on_socket(struct rxrpc_sock *rx)
{
struct rxrpc_call *call;
struct rb_node *p;
_enter("%p", rx);
read_lock_bh(&rx->call_lock);
/* mark all the calls as no longer wanting incoming packets */
for (p = rb_first(&rx->calls); p; p = rb_next(p)) {
call = rb_entry(p, struct rxrpc_call, sock_node);
rxrpc_mark_call_released(call);
}
/* kill the not-yet-accepted incoming calls */
list_for_each_entry(call, &rx->secureq, accept_link) {
rxrpc_mark_call_released(call);
}
list_for_each_entry(call, &rx->acceptq, accept_link) {
rxrpc_mark_call_released(call);
}
read_unlock_bh(&rx->call_lock);
_leave("");
}
/*
* release a call
*/
void __rxrpc_put_call(struct rxrpc_call *call)
{
ASSERT(call != NULL);
_enter("%p{u=%d}", call, atomic_read(&call->usage));
ASSERTCMP(atomic_read(&call->usage), >, 0);
if (atomic_dec_and_test(&call->usage)) {
_debug("call %d dead", call->debug_id);
ASSERTCMP(call->state, ==, RXRPC_CALL_DEAD);
rxrpc_queue_work(&call->destroyer);
}
_leave("");
}
/*
* clean up a call
*/
static void rxrpc_cleanup_call(struct rxrpc_call *call)
{
_net("DESTROY CALL %d", call->debug_id);
ASSERT(call->socket);
memset(&call->sock_node, 0xcd, sizeof(call->sock_node));
del_timer_sync(&call->lifetimer);
del_timer_sync(&call->deadspan);
del_timer_sync(&call->ack_timer);
del_timer_sync(&call->resend_timer);
ASSERT(test_bit(RXRPC_CALL_RELEASED, &call->flags));
ASSERTCMP(call->events, ==, 0);
if (work_pending(&call->processor)) {
_debug("defer destroy");
rxrpc_queue_work(&call->destroyer);
return;
}
if (call->conn) {
spin_lock(&call->conn->trans->peer->lock);
list_del(&call->error_link);
spin_unlock(&call->conn->trans->peer->lock);
write_lock_bh(&call->conn->lock);
rb_erase(&call->conn_node, &call->conn->calls);
write_unlock_bh(&call->conn->lock);
rxrpc_put_connection(call->conn);
}
if (call->acks_window) {
_debug("kill Tx window %d",
CIRC_CNT(call->acks_head, call->acks_tail,
call->acks_winsz));
smp_mb();
while (CIRC_CNT(call->acks_head, call->acks_tail,
call->acks_winsz) > 0) {
struct rxrpc_skb_priv *sp;
unsigned long _skb;
_skb = call->acks_window[call->acks_tail] & ~1;
sp = rxrpc_skb((struct sk_buff *) _skb);
_debug("+++ clear Tx %u", ntohl(sp->hdr.seq));
rxrpc_free_skb((struct sk_buff *) _skb);
call->acks_tail =
(call->acks_tail + 1) & (call->acks_winsz - 1);
}
kfree(call->acks_window);
}
rxrpc_free_skb(call->tx_pending);
rxrpc_purge_queue(&call->rx_queue);
ASSERT(skb_queue_empty(&call->rx_oos_queue));
sock_put(&call->socket->sk);
kmem_cache_free(rxrpc_call_jar, call);
}
/*
* destroy a call
*/
static void rxrpc_destroy_call(struct work_struct *work)
{
struct rxrpc_call *call =
container_of(work, struct rxrpc_call, destroyer);
_enter("%p{%d,%d,%p}",
call, atomic_read(&call->usage), call->channel, call->conn);
ASSERTCMP(call->state, ==, RXRPC_CALL_DEAD);
write_lock_bh(&rxrpc_call_lock);
list_del_init(&call->link);
write_unlock_bh(&rxrpc_call_lock);
rxrpc_cleanup_call(call);
_leave("");
}
/*
* preemptively destroy all the call records from a transport endpoint rather
* than waiting for them to time out
*/
void __exit rxrpc_destroy_all_calls(void)
{
struct rxrpc_call *call;
_enter("");
write_lock_bh(&rxrpc_call_lock);
while (!list_empty(&rxrpc_calls)) {
call = list_entry(rxrpc_calls.next, struct rxrpc_call, link);
_debug("Zapping call %p", call);
list_del_init(&call->link);
switch (atomic_read(&call->usage)) {
case 0:
ASSERTCMP(call->state, ==, RXRPC_CALL_DEAD);
break;
case 1:
if (del_timer_sync(&call->deadspan) != 0 &&
call->state != RXRPC_CALL_DEAD)
rxrpc_dead_call_expired((unsigned long) call);
if (call->state != RXRPC_CALL_DEAD)
break;
default:
printk(KERN_ERR "RXRPC:"
" Call %p still in use (%d,%d,%s,%lx,%lx)!\n",
call, atomic_read(&call->usage),
atomic_read(&call->ackr_not_idle),
rxrpc_call_states[call->state],
call->flags, call->events);
if (!skb_queue_empty(&call->rx_queue))
printk(KERN_ERR"RXRPC: Rx queue occupied\n");
if (!skb_queue_empty(&call->rx_oos_queue))
printk(KERN_ERR"RXRPC: OOS queue occupied\n");
break;
}
write_unlock_bh(&rxrpc_call_lock);
cond_resched();
write_lock_bh(&rxrpc_call_lock);
}
write_unlock_bh(&rxrpc_call_lock);
_leave("");
}
/*
* handle call lifetime being exceeded
*/
static void rxrpc_call_life_expired(unsigned long _call)
{
struct rxrpc_call *call = (struct rxrpc_call *) _call;
if (call->state >= RXRPC_CALL_COMPLETE)
return;
_enter("{%d}", call->debug_id);
read_lock_bh(&call->state_lock);
if (call->state < RXRPC_CALL_COMPLETE) {
set_bit(RXRPC_CALL_LIFE_TIMER, &call->events);
rxrpc_queue_call(call);
}
read_unlock_bh(&call->state_lock);
}
/*
* handle resend timer expiry
*/
static void rxrpc_resend_time_expired(unsigned long _call)
{
struct rxrpc_call *call = (struct rxrpc_call *) _call;
_enter("{%d}", call->debug_id);
if (call->state >= RXRPC_CALL_COMPLETE)
return;
read_lock_bh(&call->state_lock);
clear_bit(RXRPC_CALL_RUN_RTIMER, &call->flags);
if (call->state < RXRPC_CALL_COMPLETE &&
!test_and_set_bit(RXRPC_CALL_RESEND_TIMER, &call->events))
rxrpc_queue_call(call);
read_unlock_bh(&call->state_lock);
}
/*
* handle ACK timer expiry
*/
static void rxrpc_ack_time_expired(unsigned long _call)
{
struct rxrpc_call *call = (struct rxrpc_call *) _call;
_enter("{%d}", call->debug_id);
if (call->state >= RXRPC_CALL_COMPLETE)
return;
read_lock_bh(&call->state_lock);
if (call->state < RXRPC_CALL_COMPLETE &&
!test_and_set_bit(RXRPC_CALL_ACK, &call->events))
rxrpc_queue_call(call);
read_unlock_bh(&call->state_lock);
}
| bsd-3-clause |
attilahorvath/phantomjs | src/qt/qtbase/src/3rdparty/freetype/src/truetype/ttdriver.c | 323 | 17743 | /***************************************************************************/
/* */
/* ttdriver.c */
/* */
/* TrueType font driver implementation (body). */
/* */
/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 */
/* 2010 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>
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_SFNT_H
#include FT_SERVICE_XFREE86_NAME_H
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
#include FT_MULTIPLE_MASTERS_H
#include FT_SERVICE_MULTIPLE_MASTERS_H
#endif
#include FT_SERVICE_TRUETYPE_ENGINE_H
#include FT_SERVICE_TRUETYPE_GLYF_H
#include "ttdriver.h"
#include "ttgload.h"
#include "ttpload.h"
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
#include "ttgxvar.h"
#endif
#include "tterrors.h"
#include "ttpic.h"
/*************************************************************************/
/* */
/* 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_ttdriver
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** ****/
/**** F A C E S ****/
/**** ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
#undef PAIR_TAG
#define PAIR_TAG( left, right ) ( ( (FT_ULong)left << 16 ) | \
(FT_ULong)right )
/*************************************************************************/
/* */
/* <Function> */
/* tt_get_kerning */
/* */
/* <Description> */
/* A driver method used to return the kerning vector between two */
/* glyphs of the same face. */
/* */
/* <Input> */
/* face :: A handle to the source face object. */
/* */
/* left_glyph :: The index of the left glyph in the kern pair. */
/* */
/* right_glyph :: The index of the right glyph in the kern pair. */
/* */
/* <Output> */
/* kerning :: The kerning vector. This is in font units for */
/* scalable formats, and in pixels for fixed-sizes */
/* formats. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
/* <Note> */
/* Only horizontal layouts (left-to-right & right-to-left) are */
/* supported by this function. Other layouts, or more sophisticated */
/* kernings, are out of scope of this method (the basic driver */
/* interface is meant to be simple). */
/* */
/* They can be implemented by format-specific interfaces. */
/* */
static FT_Error
tt_get_kerning( FT_Face ttface, /* TT_Face */
FT_UInt left_glyph,
FT_UInt right_glyph,
FT_Vector* kerning )
{
TT_Face face = (TT_Face)ttface;
SFNT_Service sfnt = (SFNT_Service)face->sfnt;
kerning->x = 0;
kerning->y = 0;
if ( sfnt )
kerning->x = sfnt->get_kerning( face, left_glyph, right_glyph );
return 0;
}
#undef PAIR_TAG
static FT_Error
tt_get_advances( FT_Face ttface,
FT_UInt start,
FT_UInt count,
FT_Int32 flags,
FT_Fixed *advances )
{
FT_UInt nn;
TT_Face face = (TT_Face) ttface;
FT_Bool check = FT_BOOL(
!( flags & FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH ) );
/* XXX: TODO: check for sbits */
if ( flags & FT_LOAD_VERTICAL_LAYOUT )
{
for ( nn = 0; nn < count; nn++ )
{
FT_Short tsb;
FT_UShort ah;
TT_Get_VMetrics( face, start + nn, check, &tsb, &ah );
advances[nn] = ah;
}
}
else
{
for ( nn = 0; nn < count; nn++ )
{
FT_Short lsb;
FT_UShort aw;
TT_Get_HMetrics( face, start + nn, check, &lsb, &aw );
advances[nn] = aw;
}
}
return TT_Err_Ok;
}
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** ****/
/**** S I Z E S ****/
/**** ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
#ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS
static FT_Error
tt_size_select( FT_Size size,
FT_ULong strike_index )
{
TT_Face ttface = (TT_Face)size->face;
TT_Size ttsize = (TT_Size)size;
FT_Error error = TT_Err_Ok;
ttsize->strike_index = strike_index;
if ( FT_IS_SCALABLE( size->face ) )
{
/* use the scaled metrics, even when tt_size_reset fails */
FT_Select_Metrics( size->face, strike_index );
tt_size_reset( ttsize );
}
else
{
SFNT_Service sfnt = (SFNT_Service) ttface->sfnt;
FT_Size_Metrics* metrics = &size->metrics;
error = sfnt->load_strike_metrics( ttface, strike_index, metrics );
if ( error )
ttsize->strike_index = 0xFFFFFFFFUL;
}
return error;
}
#endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */
static FT_Error
tt_size_request( FT_Size size,
FT_Size_Request req )
{
TT_Size ttsize = (TT_Size)size;
FT_Error error = TT_Err_Ok;
#ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS
if ( FT_HAS_FIXED_SIZES( size->face ) )
{
TT_Face ttface = (TT_Face)size->face;
SFNT_Service sfnt = (SFNT_Service) ttface->sfnt;
FT_ULong strike_index;
error = sfnt->set_sbit_strike( ttface, req, &strike_index );
if ( error )
ttsize->strike_index = 0xFFFFFFFFUL;
else
return tt_size_select( size, strike_index );
}
#endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */
FT_Request_Metrics( size->face, req );
if ( FT_IS_SCALABLE( size->face ) )
error = tt_size_reset( ttsize );
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* Load_Glyph */
/* */
/* <Description> */
/* A driver method used to load a glyph within a given glyph slot. */
/* */
/* <Input> */
/* slot :: A handle to the target slot object where the glyph */
/* will be loaded. */
/* */
/* size :: A handle to the source face size at which the glyph */
/* must be scaled, loaded, etc. */
/* */
/* glyph_index :: The index of the glyph in the font file. */
/* */
/* load_flags :: A flag indicating what to load for this glyph. The */
/* FT_LOAD_XXX constants can be used to control the */
/* glyph loading process (e.g., whether the outline */
/* should be scaled, whether to load bitmaps or not, */
/* whether to hint the outline, etc). */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
static FT_Error
Load_Glyph( FT_GlyphSlot ttslot, /* TT_GlyphSlot */
FT_Size ttsize, /* TT_Size */
FT_UInt glyph_index,
FT_Int32 load_flags )
{
TT_GlyphSlot slot = (TT_GlyphSlot)ttslot;
TT_Size size = (TT_Size)ttsize;
FT_Face face = ttslot->face;
FT_Error error;
if ( !slot )
return TT_Err_Invalid_Slot_Handle;
if ( !size )
return TT_Err_Invalid_Size_Handle;
if ( !face )
return TT_Err_Invalid_Argument;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( glyph_index >= (FT_UInt)face->num_glyphs &&
!face->internal->incremental_interface )
#else
if ( glyph_index >= (FT_UInt)face->num_glyphs )
#endif
return TT_Err_Invalid_Argument;
if ( load_flags & FT_LOAD_NO_HINTING )
{
/* both FT_LOAD_NO_HINTING and FT_LOAD_NO_AUTOHINT */
/* are necessary to disable hinting for tricky fonts */
if ( FT_IS_TRICKY( face ) )
load_flags &= ~FT_LOAD_NO_HINTING;
if ( load_flags & FT_LOAD_NO_AUTOHINT )
load_flags |= FT_LOAD_NO_HINTING;
}
if ( load_flags & ( FT_LOAD_NO_RECURSE | FT_LOAD_NO_SCALE ) )
{
load_flags |= FT_LOAD_NO_BITMAP | FT_LOAD_NO_SCALE;
if ( !FT_IS_TRICKY( face ) )
load_flags |= FT_LOAD_NO_HINTING;
}
/* now load the glyph outline if necessary */
error = TT_Load_Glyph( size, slot, glyph_index, load_flags );
/* force drop-out mode to 2 - irrelevant now */
/* slot->outline.dropout_mode = 2; */
return error;
}
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** ****/
/**** D R I V E R I N T E R F A C E ****/
/**** ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
FT_DEFINE_SERVICE_MULTIMASTERSREC(tt_service_gx_multi_masters,
(FT_Get_MM_Func) NULL,
(FT_Set_MM_Design_Func) NULL,
(FT_Set_MM_Blend_Func) TT_Set_MM_Blend,
(FT_Get_MM_Var_Func) TT_Get_MM_Var,
(FT_Set_Var_Design_Func)TT_Set_Var_Design
)
#endif
static const FT_Service_TrueTypeEngineRec tt_service_truetype_engine =
{
#ifdef TT_USE_BYTECODE_INTERPRETER
#ifdef TT_CONFIG_OPTION_UNPATENTED_HINTING
FT_TRUETYPE_ENGINE_TYPE_UNPATENTED
#else
FT_TRUETYPE_ENGINE_TYPE_PATENTED
#endif
#else /* !TT_USE_BYTECODE_INTERPRETER */
FT_TRUETYPE_ENGINE_TYPE_NONE
#endif /* TT_USE_BYTECODE_INTERPRETER */
};
FT_DEFINE_SERVICE_TTGLYFREC(tt_service_truetype_glyf,
(TT_Glyf_GetLocationFunc)tt_face_get_location
)
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
FT_DEFINE_SERVICEDESCREC4(tt_services,
FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_TRUETYPE,
FT_SERVICE_ID_MULTI_MASTERS, &FT_TT_SERVICE_GX_MULTI_MASTERS_GET,
FT_SERVICE_ID_TRUETYPE_ENGINE, &tt_service_truetype_engine,
FT_SERVICE_ID_TT_GLYF, &FT_TT_SERVICE_TRUETYPE_GLYF_GET
)
#else
FT_DEFINE_SERVICEDESCREC3(tt_services,
FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_TRUETYPE,
FT_SERVICE_ID_TRUETYPE_ENGINE, &tt_service_truetype_engine,
FT_SERVICE_ID_TT_GLYF, &FT_TT_SERVICE_TRUETYPE_GLYF_GET
)
#endif
FT_CALLBACK_DEF( FT_Module_Interface )
tt_get_interface( FT_Module driver, /* TT_Driver */
const char* tt_interface )
{
FT_Module_Interface result;
FT_Module sfntd;
SFNT_Service sfnt;
result = ft_service_list_lookup( FT_TT_SERVICES_GET, tt_interface );
if ( result != NULL )
return result;
if ( !driver )
return NULL;
/* only return the default interface from the SFNT module */
sfntd = FT_Get_Module( driver->library, "sfnt" );
if ( sfntd )
{
sfnt = (SFNT_Service)( sfntd->clazz->module_interface );
if ( sfnt )
return sfnt->get_interface( driver, tt_interface );
}
return 0;
}
/* The FT_DriverInterface structure is defined in ftdriver.h. */
#ifdef TT_USE_BYTECODE_INTERPRETER
#define TT_HINTER_FLAG FT_MODULE_DRIVER_HAS_HINTER
#else
#define TT_HINTER_FLAG 0
#endif
#ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS
#define TT_SIZE_SELECT tt_size_select
#else
#define TT_SIZE_SELECT 0
#endif
FT_DEFINE_DRIVER(tt_driver_class,
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_SCALABLE |
TT_HINTER_FLAG,
sizeof ( TT_DriverRec ),
"truetype", /* driver name */
0x10000L, /* driver version == 1.0 */
0x20000L, /* driver requires FreeType 2.0 or above */
(void*)0, /* driver specific interface */
tt_driver_init,
tt_driver_done,
tt_get_interface,
sizeof ( TT_FaceRec ),
sizeof ( TT_SizeRec ),
sizeof ( FT_GlyphSlotRec ),
tt_face_init,
tt_face_done,
tt_size_init,
tt_size_done,
tt_slot_init,
0, /* FT_Slot_DoneFunc */
ft_stub_set_char_sizes, /* FT_CONFIG_OPTION_OLD_INTERNALS */
ft_stub_set_pixel_sizes, /* FT_CONFIG_OPTION_OLD_INTERNALS */
Load_Glyph,
tt_get_kerning,
0, /* FT_Face_AttachFunc */
tt_get_advances,
tt_size_request,
TT_SIZE_SELECT
)
/* END */
| bsd-3-clause |
Hybrid-Rom/external_skia | src/utils/SkPDFRasterizer.cpp | 76 | 2221 |
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifdef SK_BUILD_FOR_WIN32
#pragma warning(push)
#pragma warning(disable : 4530)
#endif
#include "SkPDFRasterizer.h"
#include "SkColorPriv.h"
#ifdef SK_BUILD_NATIVE_PDF_RENDERER
#include "SkPdfRenderer.h"
#endif // SK_BUILD_NATIVE_PDF_RENDERER
#ifdef SK_BUILD_POPPLER
#include <poppler-document.h>
#include <poppler-image.h>
#include <poppler-page.h>
#include <poppler-page-renderer.h>
#endif // SK_BUILD_POPPLER
#ifdef SK_BUILD_POPPLER
bool SkPopplerRasterizePDF(SkStream* pdf, SkBitmap* output) {
size_t size = pdf->getLength();
SkAutoFree buffer(sk_malloc_throw(size));
pdf->read(buffer.get(), size);
SkAutoTDelete<poppler::document> doc(
poppler::document::load_from_raw_data((const char*)buffer.get(), size));
if (!doc.get() || doc->is_locked()) {
return false;
}
SkAutoTDelete<poppler::page> page(doc->create_page(0));
poppler::page_renderer renderer;
poppler::image image = renderer.render_page(page.get());
if (!image.is_valid() || image.format() != poppler::image::format_argb32) {
return false;
}
int width = image.width(), height = image.height();
size_t rowSize = image.bytes_per_row();
char *imgData = image.data();
SkBitmap bitmap;
if (!bitmap.allocPixels(SkImageInfo::MakeN32Premul(width, height))) {
return false;
}
bitmap.eraseColor(SK_ColorWHITE);
SkPMColor* bitmapPixels = (SkPMColor*)bitmap.getPixels();
// do pixel-by-pixel copy to deal with RGBA ordering conversions
for (int y = 0; y < height; y++) {
char *rowData = imgData;
for (int x = 0; x < width; x++) {
uint8_t a = rowData[3];
uint8_t r = rowData[2];
uint8_t g = rowData[1];
uint8_t b = rowData[0];
*bitmapPixels = SkPreMultiplyARGB(a, r, g, b);
bitmapPixels++;
rowData += 4;
}
imgData += rowSize;
}
output->swap(bitmap);
return true;
}
#endif // SK_BUILD_POPPLER
#ifdef SK_BUILD_NATIVE_PDF_RENDERER
bool SkNativeRasterizePDF(SkStream* pdf, SkBitmap* output) {
return SkPDFNativeRenderToBitmap(pdf, output);
}
#endif // SK_BUILD_NATIVE_PDF_RENDERER
| bsd-3-clause |
huangguiyang/minix-v3.1.0 | lib/zlib-1.2.3/trees.c | 1874 | 44027 | /* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2005 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored in a compressed form which is itself
* a Huffman encoding of the lengths of all the code strings (in
* ascending order by source values). The actual code strings are
* reconstructed from the lengths in the inflate process, as described
* in the deflate specification.
*
* REFERENCES
*
* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
*
* Storer, James A.
* Data Compression: Methods and Theory, pp. 49-50.
* Computer Science Press, 1988. ISBN 0-7167-8156-5.
*
* Sedgewick, R.
* Algorithms, p290.
* Addison-Wesley, 1983. ISBN 0-201-06672-6.
*/
/* @(#) $Id$ */
/* #define GEN_TREES_H */
#include "deflate.h"
#ifdef DEBUG
# include <ctype.h>
#endif
/* ===========================================================================
* Constants
*/
#define MAX_BL_BITS 7
/* Bit length codes must not exceed MAX_BL_BITS bits */
#define END_BLOCK 256
/* end of block literal code */
#define REP_3_6 16
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
#define REPZ_3_10 17
/* repeat a zero length 3-10 times (3 bits of repeat count) */
#define REPZ_11_138 18
/* repeat a zero length 11-138 times (7 bits of repeat count) */
local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
= {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
local const int extra_dbits[D_CODES] /* extra bits for each distance code */
= {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
local const uch bl_order[BL_CODES]
= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
#define Buf_size (8 * 2*sizeof(char))
/* Number of bits used within bi_buf. (bi_buf might be implemented on
* more than 16 bits on some systems.)
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
#if defined(GEN_TREES_H) || !defined(STDC)
/* non ANSI compilers may not accept trees.h */
local ct_data static_ltree[L_CODES+2];
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
local ct_data static_dtree[D_CODES];
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
uch _dist_code[DIST_CODE_LEN];
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
uch _length_code[MAX_MATCH-MIN_MATCH+1];
/* length code for each normalized match length (0 == MIN_MATCH) */
local int base_length[LENGTH_CODES];
/* First normalized length for each code (0 = MIN_MATCH) */
local int base_dist[D_CODES];
/* First normalized distance for each code (0 = distance of 1) */
#else
# include "trees.h"
#endif /* GEN_TREES_H */
struct static_tree_desc_s {
const ct_data *static_tree; /* static tree or NULL */
const intf *extra_bits; /* extra bits for each code or NULL */
int extra_base; /* base index for extra_bits */
int elems; /* max number of elements in the tree */
int max_length; /* max bit length for the codes */
};
local static_tree_desc static_l_desc =
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
local static_tree_desc static_d_desc =
{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
local static_tree_desc static_bl_desc =
{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
/* ===========================================================================
* Local (static) routines in this file.
*/
local void tr_static_init OF((void));
local void init_block OF((deflate_state *s));
local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
local void build_tree OF((deflate_state *s, tree_desc *desc));
local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
local int build_bl_tree OF((deflate_state *s));
local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
int blcodes));
local void compress_block OF((deflate_state *s, ct_data *ltree,
ct_data *dtree));
local void set_data_type OF((deflate_state *s));
local unsigned bi_reverse OF((unsigned value, int length));
local void bi_windup OF((deflate_state *s));
local void bi_flush OF((deflate_state *s));
local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
int header));
#ifdef GEN_TREES_H
local void gen_trees_header OF((void));
#endif
#ifndef DEBUG
# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
/* Send a code of the given tree. c and tree must not have side effects */
#else /* DEBUG */
# define send_code(s, c, tree) \
{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
send_bits(s, tree[c].Code, tree[c].Len); }
#endif
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
#define put_short(s, w) { \
put_byte(s, (uch)((w) & 0xff)); \
put_byte(s, (uch)((ush)(w) >> 8)); \
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
#ifdef DEBUG
local void send_bits OF((deflate_state *s, int value, int length));
local void send_bits(s, value, length)
deflate_state *s;
int value; /* value to send */
int length; /* number of bits */
{
Tracevv((stderr," l %2d v %4x ", length, value));
Assert(length > 0 && length <= 15, "invalid length");
s->bits_sent += (ulg)length;
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if (s->bi_valid > (int)Buf_size - length) {
s->bi_buf |= (value << s->bi_valid);
put_short(s, s->bi_buf);
s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
s->bi_valid += length - Buf_size;
} else {
s->bi_buf |= value << s->bi_valid;
s->bi_valid += length;
}
}
#else /* !DEBUG */
#define send_bits(s, value, length) \
{ int len = length;\
if (s->bi_valid > (int)Buf_size - len) {\
int val = value;\
s->bi_buf |= (val << s->bi_valid);\
put_short(s, s->bi_buf);\
s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
s->bi_valid += len - Buf_size;\
} else {\
s->bi_buf |= (value) << s->bi_valid;\
s->bi_valid += len;\
}\
}
#endif /* DEBUG */
/* the arguments must not have side effects */
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
local void tr_static_init()
{
#if defined(GEN_TREES_H) || !defined(STDC)
static int static_init_done = 0;
int n; /* iterates over tree elements */
int bits; /* bit counter */
int length; /* length value */
int code; /* code value */
int dist; /* distance index */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = (uch)code;
}
}
Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = (uch)code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
n = 0;
while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n].Len = 5;
static_dtree[n].Code = bi_reverse((unsigned)n, 5);
}
static_init_done = 1;
# ifdef GEN_TREES_H
gen_trees_header();
# endif
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
}
/* ===========================================================================
* Genererate the file trees.h describing the static trees.
*/
#ifdef GEN_TREES_H
# ifndef DEBUG
# include <stdio.h>
# endif
# define SEPARATOR(i, last, width) \
((i) == (last)? "\n};\n\n" : \
((i) % (width) == (width)-1 ? ",\n" : ", "))
void gen_trees_header()
{
FILE *header = fopen("trees.h", "w");
int i;
Assert (header != NULL, "Can't open trees.h");
fprintf(header,
"/* header created automatically with -DGEN_TREES_H */\n\n");
fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
for (i = 0; i < L_CODES+2; i++) {
fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
}
fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
}
fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
for (i = 0; i < DIST_CODE_LEN; i++) {
fprintf(header, "%2u%s", _dist_code[i],
SEPARATOR(i, DIST_CODE_LEN-1, 20));
}
fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
fprintf(header, "%2u%s", _length_code[i],
SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
}
fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
for (i = 0; i < LENGTH_CODES; i++) {
fprintf(header, "%1u%s", base_length[i],
SEPARATOR(i, LENGTH_CODES-1, 20));
}
fprintf(header, "local const int base_dist[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "%5u%s", base_dist[i],
SEPARATOR(i, D_CODES-1, 10));
}
fclose(header);
}
#endif /* GEN_TREES_H */
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
void _tr_init(s)
deflate_state *s;
{
tr_static_init();
s->l_desc.dyn_tree = s->dyn_ltree;
s->l_desc.stat_desc = &static_l_desc;
s->d_desc.dyn_tree = s->dyn_dtree;
s->d_desc.stat_desc = &static_d_desc;
s->bl_desc.dyn_tree = s->bl_tree;
s->bl_desc.stat_desc = &static_bl_desc;
s->bi_buf = 0;
s->bi_valid = 0;
s->last_eob_len = 8; /* enough lookahead for inflate */
#ifdef DEBUG
s->compressed_len = 0L;
s->bits_sent = 0L;
#endif
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Initialize a new block.
*/
local void init_block(s)
deflate_state *s;
{
int n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
s->dyn_ltree[END_BLOCK].Freq = 1;
s->opt_len = s->static_len = 0L;
s->last_lit = s->matches = 0;
}
#define SMALLEST 1
/* Index within the heap array of least frequent node in the Huffman tree */
/* ===========================================================================
* Remove the smallest element from the heap and recreate the heap with
* one less element. Updates heap and heap_len.
*/
#define pqremove(s, tree, top) \
{\
top = s->heap[SMALLEST]; \
s->heap[SMALLEST] = s->heap[s->heap_len--]; \
pqdownheap(s, tree, SMALLEST); \
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
#define smaller(tree, n, m, depth) \
(tree[n].Freq < tree[m].Freq || \
(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
local void pqdownheap(s, tree, k)
deflate_state *s;
ct_data *tree; /* the tree to restore */
int k; /* node to move down */
{
int v = s->heap[k];
int j = k << 1; /* left son of k */
while (j <= s->heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s->heap_len &&
smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s->heap[j], s->depth)) break;
/* Exchange v with the smallest son */
s->heap[k] = s->heap[j]; k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s->heap[k] = v;
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
local void gen_bitlen(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
int max_code = desc->max_code;
const ct_data *stree = desc->stat_desc->static_tree;
const intf *extra = desc->stat_desc->extra_bits;
int base = desc->stat_desc->extra_base;
int max_length = desc->stat_desc->max_length;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
ush f; /* frequency */
int overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
n = s->heap[h];
bits = tree[tree[n].Dad].Len + 1;
if (bits > max_length) bits = max_length, overflow++;
tree[n].Len = (ush)bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) continue; /* not a leaf node */
s->bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n].Freq;
s->opt_len += (ulg)f * (bits + xbits);
if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
}
if (overflow == 0) return;
Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s->bl_count[bits] == 0) bits--;
s->bl_count[bits]--; /* move one leaf down the tree */
s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
s->bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits != 0; bits--) {
n = s->bl_count[bits];
while (n != 0) {
m = s->heap[--h];
if (m > max_code) continue;
if ((unsigned) tree[m].Len != (unsigned) bits) {
Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s->opt_len += ((long)bits - (long)tree[m].Len)
*(long)tree[m].Freq;
tree[m].Len = (ush)bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
local void gen_codes (tree, max_code, bl_count)
ct_data *tree; /* the tree to decorate */
int max_code; /* largest code with non zero frequency */
ushf *bl_count; /* number of codes at each bit length */
{
ush next_code[MAX_BITS+1]; /* next code value for each bit length */
ush code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
"inconsistent bit counts");
Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n].Len;
if (len == 0) continue;
/* Now reverse the bits */
tree[n].Code = bi_reverse(next_code[len]++, len);
Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
local void build_tree(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
const ct_data *stree = desc->stat_desc->static_tree;
int elems = desc->stat_desc->elems;
int n, m; /* iterate over heap elements */
int max_code = -1; /* largest code with non zero frequency */
int node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s->heap_len = 0, s->heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n].Freq != 0) {
s->heap[++(s->heap_len)] = max_code = n;
s->depth[n] = 0;
} else {
tree[n].Len = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s->heap_len < 2) {
node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
tree[node].Freq = 1;
s->depth[node] = 0;
s->opt_len--; if (stree) s->static_len -= stree[node].Len;
/* node is 0 or 1 so it does not have extra bits */
}
desc->max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
pqremove(s, tree, n); /* n = node of least frequency */
m = s->heap[SMALLEST]; /* m = node of next least frequency */
s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
s->heap[--(s->heap_max)] = m;
/* Create a new node father of n and m */
tree[node].Freq = tree[n].Freq + tree[m].Freq;
s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
s->depth[n] : s->depth[m]) + 1);
tree[n].Dad = tree[m].Dad = (ush)node;
#ifdef DUMP_BL_TREE
if (tree == s->bl_tree) {
fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
}
#endif
/* and insert the new node in the heap */
s->heap[SMALLEST] = node++;
pqdownheap(s, tree, SMALLEST);
} while (s->heap_len >= 2);
s->heap[--(s->heap_max)] = s->heap[SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, (tree_desc *)desc);
/* The field len is now set, we can generate the bit codes */
gen_codes ((ct_data *)tree, max_code, s->bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
local void scan_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
if (nextlen == 0) max_count = 138, min_count = 3;
tree[max_code+1].Len = (ush)0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
s->bl_tree[curlen].Freq += count;
} else if (curlen != 0) {
if (curlen != prevlen) s->bl_tree[curlen].Freq++;
s->bl_tree[REP_3_6].Freq++;
} else if (count <= 10) {
s->bl_tree[REPZ_3_10].Freq++;
} else {
s->bl_tree[REPZ_11_138].Freq++;
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
local void send_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen == 0) max_count = 138, min_count = 3;
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(s, curlen, s->bl_tree); count--;
}
Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
local int build_bl_tree(s)
deflate_state *s;
{
int max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, (tree_desc *)(&(s->bl_desc)));
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
s->opt_len += 3*(max_blindex+1) + 5+5+4;
Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
local void send_all_trees(s, lcodes, dcodes, blcodes)
deflate_state *s;
int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
int rank; /* index in bl_order */
Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
"too many codes");
Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
}
Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Send a stored block
*/
void _tr_stored_block(s, buf, stored_len, eof)
deflate_state *s;
charf *buf; /* input block */
ulg stored_len; /* length of input block */
int eof; /* true if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
#ifdef DEBUG
s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
s->compressed_len += (stored_len + 4) << 3;
#endif
copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
* The current inflate code requires 9 bits of lookahead. If the
* last two codes for the previous block (real code plus EOB) were coded
* on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
* the last real code. In this case we send two empty static blocks instead
* of one. (There are no problems if the previous block is stored or fixed.)
* To simplify the code, we assume the worst case of last real code encoded
* on one bit only.
*/
void _tr_align(s)
deflate_state *s;
{
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
#endif
bi_flush(s);
/* Of the 10 bits for the empty block, we have already sent
* (10 - bi_valid) bits. The lookahead for the last real code (before
* the EOB of the previous block) was thus at least one plus the length
* of the EOB plus what we have just sent of the empty static block.
*/
if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L;
#endif
bi_flush(s);
}
s->last_eob_len = 7;
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
void _tr_flush_block(s, buf, stored_len, eof)
deflate_state *s;
charf *buf; /* input block, or NULL if too old */
ulg stored_len; /* length of input block */
int eof; /* true if this is the last block for a file */
{
ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
int max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) {
/* Check if the file is binary or text */
if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
set_data_type(s);
/* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc)));
Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
build_tree(s, (tree_desc *)(&(s->d_desc)));
Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s->opt_len+3+7)>>3;
static_lenb = (s->static_len+3+7)>>3;
Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
s->last_lit));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
} else {
Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
#ifdef FORCE_STORED
if (buf != (char*)0) { /* force stored block */
#else
if (stored_len+4 <= opt_lenb && buf != (char*)0) {
/* 4: two words for the lengths */
#endif
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, eof);
#ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */
#else
} else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
#endif
send_bits(s, (STATIC_TREES<<1)+eof, 3);
compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->static_len;
#endif
} else {
send_bits(s, (DYN_TREES<<1)+eof, 3);
send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
max_blindex+1);
compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->opt_len;
#endif
}
Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (eof) {
bi_windup(s);
#ifdef DEBUG
s->compressed_len += 7; /* align on byte boundary */
#endif
}
Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
s->compressed_len-7*eof));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
int _tr_tally (s, dist, lc)
deflate_state *s;
unsigned dist; /* distance of matched string */
unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
s->d_buf[s->last_lit] = (ush)dist;
s->l_buf[s->last_lit++] = (uch)lc;
if (dist == 0) {
/* lc is the unmatched char */
s->dyn_ltree[lc].Freq++;
} else {
s->matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
Assert((ush)dist < (ush)MAX_DIST(s) &&
(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
s->dyn_dtree[d_code(dist)].Freq++;
}
#ifdef TRUNCATE_BLOCK
/* Try to guess if it is profitable to stop the current block here */
if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
/* Compute an upper bound for the compressed length */
ulg out_length = (ulg)s->last_lit*8L;
ulg in_length = (ulg)((long)s->strstart - s->block_start);
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += (ulg)s->dyn_dtree[dcode].Freq *
(5L+extra_dbits[dcode]);
}
out_length >>= 3;
Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
s->last_lit, in_length, out_length,
100L - out_length*100L/in_length));
if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
}
#endif
return (s->last_lit == s->lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
local void compress_block(s, ltree, dtree)
deflate_state *s;
ct_data *ltree; /* literal tree */
ct_data *dtree; /* distance tree */
{
unsigned dist; /* distance of matched string */
int lc; /* match length or unmatched char (if dist == 0) */
unsigned lx = 0; /* running index in l_buf */
unsigned code; /* the code to send */
int extra; /* number of extra bits to send */
if (s->last_lit != 0) do {
dist = s->d_buf[lx];
lc = s->l_buf[lx++];
if (dist == 0) {
send_code(s, lc, ltree); /* send a literal byte */
Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra != 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra != 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
"pendingBuf overflow");
} while (lx < s->last_lit);
send_code(s, END_BLOCK, ltree);
s->last_eob_len = ltree[END_BLOCK].Len;
}
/* ===========================================================================
* Set the data type to BINARY or TEXT, using a crude approximation:
* set it to Z_TEXT if all symbols are either printable characters (33 to 255)
* or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
* IN assertion: the fields Freq of dyn_ltree are set.
*/
local void set_data_type(s)
deflate_state *s;
{
int n;
for (n = 0; n < 9; n++)
if (s->dyn_ltree[n].Freq != 0)
break;
if (n == 9)
for (n = 14; n < 32; n++)
if (s->dyn_ltree[n].Freq != 0)
break;
s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
local unsigned bi_reverse(code, len)
unsigned code; /* the value to invert */
int len; /* its bit length */
{
register unsigned res = 0;
do {
res |= code & 1;
code >>= 1, res <<= 1;
} while (--len > 0);
return res >> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
local void bi_flush(s)
deflate_state *s;
{
if (s->bi_valid == 16) {
put_short(s, s->bi_buf);
s->bi_buf = 0;
s->bi_valid = 0;
} else if (s->bi_valid >= 8) {
put_byte(s, (Byte)s->bi_buf);
s->bi_buf >>= 8;
s->bi_valid -= 8;
}
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
local void bi_windup(s)
deflate_state *s;
{
if (s->bi_valid > 8) {
put_short(s, s->bi_buf);
} else if (s->bi_valid > 0) {
put_byte(s, (Byte)s->bi_buf);
}
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->bits_sent = (s->bits_sent+7) & ~7;
#endif
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
local void copy_block(s, buf, len, header)
deflate_state *s;
charf *buf; /* the input data */
unsigned len; /* its length */
int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
s->last_eob_len = 8; /* enough lookahead for inflate */
if (header) {
put_short(s, (ush)len);
put_short(s, (ush)~len);
#ifdef DEBUG
s->bits_sent += 2*16;
#endif
}
#ifdef DEBUG
s->bits_sent += (ulg)len<<3;
#endif
while (len--) {
put_byte(s, *buf++);
}
}
| bsd-3-clause |
avinashkunuje/phantomjs | src/qt/qtbase/src/corelib/codecs/qeucjpcodec.cpp | 84 | 8288 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
// Most of the code here was originally written by Serika Kurusugawa
// a.k.a. Junji Takagi, and is included in Qt with the author's permission,
// and the grateful thanks of the Qt team.
/*! \class QEucJpCodec
\inmodule QtCore
\reentrant
\internal
*/
/*
* Copyright (C) 1999 Serika Kurusugawa, 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "qeucjpcodec_p.h"
QT_BEGIN_NAMESPACE
#ifndef QT_NO_BIG_CODECS
static const uchar Ss2 = 0x8e; // Single Shift 2
static const uchar Ss3 = 0x8f; // Single Shift 3
#define IsKana(c) (((c) >= 0xa1) && ((c) <= 0xdf))
#define IsEucChar(c) (((c) >= 0xa1) && ((c) <= 0xfe))
#define QValidChar(u) ((u) ? QChar((ushort)(u)) : QChar(QChar::ReplacementCharacter))
/*!
Constructs a QEucJpCodec.
*/
QEucJpCodec::QEucJpCodec() : conv(QJpUnicodeConv::newConverter(QJpUnicodeConv::Default))
{
}
/*!
Destroys the codec.
*/
QEucJpCodec::~QEucJpCodec()
{
delete (QJpUnicodeConv*)conv;
conv = 0;
}
QByteArray QEucJpCodec::convertFromUnicode(const QChar *uc, int len, ConverterState *state) const
{
char replacement = '?';
if (state) {
if (state->flags & ConvertInvalidToNull)
replacement = 0;
}
int invalid = 0;
int rlen = 3*len + 1;
QByteArray rstr;
rstr.resize(rlen);
uchar* cursor = (uchar*)rstr.data();
for (int i = 0; i < len; i++) {
QChar ch = uc[i];
uint j;
if (ch.unicode() < 0x80) {
// ASCII
*cursor++ = ch.cell();
} else if ((j = conv->unicodeToJisx0201(ch.row(), ch.cell())) != 0) {
if (j < 0x80) {
// JIS X 0201 Latin ?
*cursor++ = j;
} else {
// JIS X 0201 Kana
*cursor++ = Ss2;
*cursor++ = j;
}
} else if ((j = conv->unicodeToJisx0208(ch.row(), ch.cell())) != 0) {
// JIS X 0208
*cursor++ = (j >> 8) | 0x80;
*cursor++ = (j & 0xff) | 0x80;
} else if ((j = conv->unicodeToJisx0212(ch.row(), ch.cell())) != 0) {
// JIS X 0212
*cursor++ = Ss3;
*cursor++ = (j >> 8) | 0x80;
*cursor++ = (j & 0xff) | 0x80;
} else {
// Error
*cursor++ = replacement;
++invalid;
}
}
rstr.resize(cursor - (uchar*)rstr.constData());
if (state) {
state->invalidChars += invalid;
}
return rstr;
}
QString QEucJpCodec::convertToUnicode(const char* chars, int len, ConverterState *state) const
{
uchar buf[2] = {0, 0};
int nbuf = 0;
QChar replacement = QChar::ReplacementCharacter;
if (state) {
if (state->flags & ConvertInvalidToNull)
replacement = QChar::Null;
nbuf = state->remainingChars;
buf[0] = state->state_data[0];
buf[1] = state->state_data[1];
}
int invalid = 0;
QString result;
for (int i=0; i<len; i++) {
uchar ch = chars[i];
switch (nbuf) {
case 0:
if (ch < 0x80) {
// ASCII
result += QLatin1Char(ch);
} else if (ch == Ss2 || ch == Ss3) {
// JIS X 0201 Kana or JIS X 0212
buf[0] = ch;
nbuf = 1;
} else if (IsEucChar(ch)) {
// JIS X 0208
buf[0] = ch;
nbuf = 1;
} else {
// Invalid
result += replacement;
++invalid;
}
break;
case 1:
if (buf[0] == Ss2) {
// JIS X 0201 Kana
if (IsKana(ch)) {
uint u = conv->jisx0201ToUnicode(ch);
result += QValidChar(u);
} else {
result += replacement;
++invalid;
}
nbuf = 0;
} else if (buf[0] == Ss3) {
// JIS X 0212-1990
if (IsEucChar(ch)) {
buf[1] = ch;
nbuf = 2;
} else {
// Error
result += replacement;
++invalid;
nbuf = 0;
}
} else {
// JIS X 0208-1990
if (IsEucChar(ch)) {
uint u = conv->jisx0208ToUnicode(buf[0] & 0x7f, ch & 0x7f);
result += QValidChar(u);
} else {
// Error
result += replacement;
++invalid;
}
nbuf = 0;
}
break;
case 2:
// JIS X 0212
if (IsEucChar(ch)) {
uint u = conv->jisx0212ToUnicode(buf[1] & 0x7f, ch & 0x7f);
result += QValidChar(u);
} else {
result += replacement;
++invalid;
}
nbuf = 0;
}
}
if (state) {
state->remainingChars = nbuf;
state->state_data[0] = buf[0];
state->state_data[1] = buf[1];
state->invalidChars += invalid;
}
return result;
}
int QEucJpCodec::_mibEnum()
{
return 18;
}
QByteArray QEucJpCodec::_name()
{
return "EUC-JP";
}
#endif // QT_NO_BIG_CODECS
QT_END_NAMESPACE
| bsd-3-clause |
TeamEOS/external_chromium_org_third_party_skia | experimental/PdfViewer/pdfparser/native/SkPdfNativeDoc.cpp | 87 | 21238 | /*
* 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 "SkPdfNativeDoc.h"
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "SkPdfMapper_autogen.h"
#include "SkPdfNativeObject.h"
#include "SkPdfNativeTokenizer.h"
#include "SkPdfReporter.h"
#include "SkStream.h"
// TODO(edisonn): for some reason on mac these files are found here, but are found from headers
//#include "SkPdfFileTrailerDictionary_autogen.h"
//#include "SkPdfCatalogDictionary_autogen.h"
//#include "SkPdfPageObjectDictionary_autogen.h"
//#include "SkPdfPageTreeNodeDictionary_autogen.h"
#include "SkPdfHeaders_autogen.h"
static long getFileSize(const char* filename)
{
struct stat stat_buf;
int rc = stat(filename, &stat_buf);
return rc == 0 ? (long)stat_buf.st_size : -1;
}
static const unsigned char* lineHome(const unsigned char* start, const unsigned char* current) {
while (current > start && !isPdfEOL(*(current - 1))) {
current--;
}
return current;
}
static const unsigned char* previousLineHome(const unsigned char* start,
const unsigned char* current) {
if (current > start && isPdfEOL(*(current - 1))) {
current--;
}
// allows CR+LF, LF+CR but not two CR+CR or LF+LF
if (current > start && isPdfEOL(*(current - 1)) && *current != *(current - 1)) {
current--;
}
while (current > start && !isPdfEOL(*(current - 1))) {
current--;
}
return current;
}
static const unsigned char* ignoreLine(const unsigned char* current, const unsigned char* end) {
while (current < end && !isPdfEOL(*current)) {
current++;
}
current++;
if (current < end && isPdfEOL(*current) && *current != *(current - 1)) {
current++;
}
return current;
}
SkPdfNativeDoc* gDoc = NULL;
SkPdfNativeDoc::SkPdfNativeDoc(SkStream* stream)
: fAllocator(new SkPdfAllocator())
, fFileContent(NULL)
, fContentLength(0)
, fRootCatalogRef(NULL)
, fRootCatalog(NULL) {
size_t size = stream->getLength();
void* ptr = sk_malloc_throw(size);
stream->read(ptr, size);
init(ptr, size);
}
SkPdfNativeDoc::SkPdfNativeDoc(const char* path)
: fAllocator(new SkPdfAllocator())
, fFileContent(NULL)
, fContentLength(0)
, fRootCatalogRef(NULL)
, fRootCatalog(NULL) {
gDoc = this;
FILE* file = fopen(path, "r");
// TODO(edisonn): put this in a function that can return NULL
if (file) {
size_t size = getFileSize(path);
void* content = sk_malloc_throw(size);
bool ok = (0 != fread(content, size, 1, file));
fclose(file);
if (!ok) {
sk_free(content);
SkPdfReport(kFatalError_SkPdfIssueSeverity, kReadStreamError_SkPdfIssue,
"could not read file", NULL, NULL);
// TODO(edisonn): not nice to return like this from constructor, create a static
// function that can report NULL for failures.
return; // Doc will have 0 pages
}
init(content, size);
}
}
void SkPdfNativeDoc::init(const void* bytes, size_t length) {
fFileContent = (const unsigned char*)bytes;
fContentLength = length;
const unsigned char* eofLine = lineHome(fFileContent, fFileContent + fContentLength - 1);
const unsigned char* xrefByteOffsetLine = previousLineHome(fFileContent, eofLine);
const unsigned char* xrefstartKeywordLine = previousLineHome(fFileContent, xrefByteOffsetLine);
if (strcmp((char*)xrefstartKeywordLine, "startxref") != 0) {
SkPdfReport(kWarning_SkPdfIssueSeverity, kMissingToken_SkPdfIssue,
"Could not find startxref", NULL, NULL);
}
long xrefByteOffset = atol((const char*)xrefByteOffsetLine);
bool storeCatalog = true;
while (xrefByteOffset >= 0) {
const unsigned char* trailerStart = this->readCrossReferenceSection(fFileContent + xrefByteOffset,
xrefstartKeywordLine);
xrefByteOffset = -1;
if (trailerStart < xrefstartKeywordLine) {
this->readTrailer(trailerStart, xrefstartKeywordLine, storeCatalog, &xrefByteOffset, false);
storeCatalog = false;
}
}
// TODO(edisonn): warn/error expect fObjects[fRefCatalogId].fGeneration == fRefCatalogGeneration
// TODO(edisonn): security, verify that SkPdfCatalogDictionary is indeed using mapper
if (fRootCatalogRef) {
fRootCatalog = (SkPdfCatalogDictionary*)resolveReference(fRootCatalogRef);
if (fRootCatalog != NULL && fRootCatalog->isDictionary() && fRootCatalog->valid()) {
SkPdfPageTreeNodeDictionary* tree = fRootCatalog->Pages(this);
if (tree && tree->isDictionary() && tree->valid()) {
fillPages(tree);
}
}
}
if (pages() == 0) {
// TODO(edisonn): probably it would be better to return NULL and make a clean document.
loadWithoutXRef();
}
// TODO(edisonn): corrupted pdf, read it from beginning and rebuild
// (xref, trailer, or just read all objects)
}
void SkPdfNativeDoc::loadWithoutXRef() {
const unsigned char* current = fFileContent;
const unsigned char* end = fFileContent + fContentLength;
// TODO(edisonn): read pdf version
current = ignoreLine(current, end);
current = skipPdfWhiteSpaces(current, end);
while (current < end) {
SkPdfNativeObject token;
current = nextObject(current, end, &token, NULL, NULL);
if (token.isInteger()) {
int id = (int)token.intValue();
token.reset();
current = nextObject(current, end, &token, NULL, NULL);
// TODO(edisonn): generation ignored for now (used in pdfs with updates)
// int generation = (int)token.intValue();
token.reset();
current = nextObject(current, end, &token, NULL, NULL);
// TODO(edisonn): keywork must be "obj". Add ability to report error instead ignoring.
if (!token.isKeyword("obj")) {
SkPdfReport(kWarning_SkPdfIssueSeverity, kMissingToken_SkPdfIssue,
"Could not find obj", NULL, NULL);
continue;
}
while (fObjects.count() < id + 1) {
reset(fObjects.append());
}
fObjects[id].fOffset = current - fFileContent;
SkPdfNativeObject* obj = fAllocator->allocObject();
current = nextObject(current, end, obj, fAllocator, this);
fObjects[id].fResolvedReference = obj;
fObjects[id].fObj = obj;
fObjects[id].fIsReferenceResolved = true;
} else if (token.isKeyword("trailer")) {
long dummy;
current = readTrailer(current, end, true, &dummy, true);
} else if (token.isKeyword("startxref")) {
token.reset();
current = nextObject(current, end, &token, NULL, NULL); // ignore startxref
}
current = skipPdfWhiteSpaces(current, end);
}
// TODO(edisonn): quick hack, detect root catalog. When we implement linearized support we
// might not need it.
if (!fRootCatalogRef) {
for (unsigned int i = 0 ; i < objects(); i++) {
SkPdfNativeObject* obj = object(i);
SkPdfNativeObject* root = (obj && obj->isDictionary()) ? obj->get("Root") : NULL;
if (root && root->isReference()) {
fRootCatalogRef = root;
}
}
}
if (fRootCatalogRef) {
fRootCatalog = (SkPdfCatalogDictionary*)resolveReference(fRootCatalogRef);
if (fRootCatalog != NULL && fRootCatalog->isDictionary() && fRootCatalog->valid()) {
SkPdfPageTreeNodeDictionary* tree = fRootCatalog->Pages(this);
if (tree && tree->isDictionary() && tree->valid()) {
fillPages(tree);
}
}
}
}
SkPdfNativeDoc::~SkPdfNativeDoc() {
sk_free((void*)fFileContent);
delete fAllocator;
}
const unsigned char* SkPdfNativeDoc::readCrossReferenceSection(const unsigned char* xrefStart,
const unsigned char* trailerEnd) {
SkPdfNativeObject xref;
const unsigned char* current = nextObject(xrefStart, trailerEnd, &xref, NULL, NULL);
if (!xref.isKeyword("xref")) {
SkPdfReport(kWarning_SkPdfIssueSeverity, kMissingToken_SkPdfIssue, "Could not find sref",
NULL, NULL);
return trailerEnd;
}
SkPdfNativeObject token;
while (current < trailerEnd) {
token.reset();
const unsigned char* previous = current;
current = nextObject(current, trailerEnd, &token, NULL, NULL);
if (!token.isInteger()) {
SkPdfReport(kInfo_SkPdfIssueSeverity, kNoIssue_SkPdfIssue,
"Done readCrossReferenceSection", NULL, NULL);
return previous;
}
int startId = (int)token.intValue();
token.reset();
current = nextObject(current, trailerEnd, &token, NULL, NULL);
if (!token.isInteger()) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity, "readCrossReferenceSection",
&token, SkPdfNativeObject::kInteger_PdfObjectType, NULL);
return current;
}
int entries = (int)token.intValue();
for (int i = 0; i < entries; i++) {
token.reset();
current = nextObject(current, trailerEnd, &token, NULL, NULL);
if (!token.isInteger()) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readCrossReferenceSection",
&token, SkPdfNativeObject::kInteger_PdfObjectType, NULL);
return current;
}
int offset = (int)token.intValue();
token.reset();
current = nextObject(current, trailerEnd, &token, NULL, NULL);
if (!token.isInteger()) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readCrossReferenceSection",
&token, SkPdfNativeObject::kInteger_PdfObjectType, NULL);
return current;
}
int generation = (int)token.intValue();
token.reset();
current = nextObject(current, trailerEnd, &token, NULL, NULL);
if (!token.isKeyword() || token.lenstr() != 1 ||
(*token.c_str() != 'f' && *token.c_str() != 'n')) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readCrossReferenceSection: f or n expected",
&token, SkPdfNativeObject::kKeyword_PdfObjectType, NULL);
return current;
}
this->addCrossSectionInfo(startId + i, generation, offset, *token.c_str() == 'f');
}
}
SkPdfReport(kInfo_SkPdfIssueSeverity, kNoIssue_SkPdfIssue,
"Unexpected end of readCrossReferenceSection", NULL, NULL);
return current;
}
const unsigned char* SkPdfNativeDoc::readTrailer(const unsigned char* trailerStart,
const unsigned char* trailerEnd,
bool storeCatalog, long* prev, bool skipKeyword) {
*prev = -1;
const unsigned char* current = trailerStart;
if (!skipKeyword) {
SkPdfNativeObject trailerKeyword;
// Use null allocator, and let it just fail if memory, it should not crash.
current = nextObject(current, trailerEnd, &trailerKeyword, NULL, NULL);
if (!trailerKeyword.isKeyword() || strlen("trailer") != trailerKeyword.lenstr() ||
strncmp(trailerKeyword.c_str(), "trailer", strlen("trailer")) != 0) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readTrailer: trailer keyword expected",
&trailerKeyword,
SkPdfNativeObject::kKeyword_PdfObjectType, NULL);
return current;
}
}
SkPdfNativeObject token;
current = nextObject(current, trailerEnd, &token, fAllocator, NULL);
if (!token.isDictionary()) {
return current;
}
SkPdfFileTrailerDictionary* trailer = (SkPdfFileTrailerDictionary*)&token;
if (!trailer->valid()) {
return current;
}
if (storeCatalog) {
SkPdfNativeObject* ref = trailer->Root(NULL);
if (ref == NULL || !ref->isReference()) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readTrailer: unexpected root reference",
ref, SkPdfNativeObject::kReference_PdfObjectType, NULL);
return current;
}
fRootCatalogRef = ref;
}
if (trailer->has_Prev()) {
*prev = (long)trailer->Prev(NULL);
}
return current;
}
void SkPdfNativeDoc::addCrossSectionInfo(int id, int generation, int offset, bool isFreed) {
// TODO(edisonn): security here, verify id
while (fObjects.count() < id + 1) {
this->reset(fObjects.append());
}
fObjects[id].fOffset = offset;
fObjects[id].fObj = NULL;
fObjects[id].fResolvedReference = NULL;
fObjects[id].fIsReferenceResolved = false;
}
SkPdfNativeObject* SkPdfNativeDoc::readObject(int id/*, int expectedGeneration*/) {
long startOffset = fObjects[id].fOffset;
//long endOffset = fObjects[id].fOffsetEnd;
// TODO(edisonn): use hinted endOffset
const unsigned char* current = fFileContent + startOffset;
const unsigned char* end = fFileContent + fContentLength;
SkPdfNativeTokenizer tokenizer(current, (int) (end - current), fAllocator, this);
SkPdfNativeObject idObj;
SkPdfNativeObject generationObj;
SkPdfNativeObject objKeyword;
SkPdfNativeObject* dict = fAllocator->allocObject();
current = nextObject(current, end, &idObj, NULL, NULL);
if (current >= end) {
SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kReadStreamError_SkPdfIssue, "reading id",
NULL, NULL);
return NULL;
}
current = nextObject(current, end, &generationObj, NULL, NULL);
if (current >= end) {
SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kReadStreamError_SkPdfIssue,
"reading generation", NULL, NULL);
return NULL;
}
current = nextObject(current, end, &objKeyword, NULL, NULL);
if (current >= end) {
SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kReadStreamError_SkPdfIssue,
"reading keyword obj", NULL, NULL);
return NULL;
}
if (!idObj.isInteger() || id != idObj.intValue()) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity, "readObject: unexpected id",
&idObj, SkPdfNativeObject::kInteger_PdfObjectType, NULL);
}
// TODO(edisonn): verify that the generation is the right one
if (!generationObj.isInteger() /* || generation != generationObj.intValue()*/) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readObject: unexpected generation",
&generationObj, SkPdfNativeObject::kInteger_PdfObjectType, NULL);
}
if (!objKeyword.isKeyword() || strcmp(objKeyword.c_str(), "obj") != 0) {
SkPdfReportUnexpectedType(kIgnoreError_SkPdfIssueSeverity,
"readObject: unexpected obj keyword",
&objKeyword, SkPdfNativeObject::kKeyword_PdfObjectType, NULL);
}
current = nextObject(current, end, dict, fAllocator, this);
// TODO(edisonn): report warning/error - verify that the last token is endobj
return dict;
}
void SkPdfNativeDoc::fillPages(SkPdfPageTreeNodeDictionary* tree) {
SkPdfArray* kids = tree->Kids(this);
if (kids == NULL) {
*fPages.append() = (SkPdfPageObjectDictionary*)tree;
return;
}
int cnt = (int) kids->size();
for (int i = 0; i < cnt; i++) {
SkPdfNativeObject* obj = resolveReference(kids->objAtAIndex(i));
if (fMapper->mapPageObjectDictionary(obj) != kPageObjectDictionary_SkPdfNativeObjectType) {
*fPages.append() = (SkPdfPageObjectDictionary*)obj;
} else {
// TODO(edisonn): verify that it is a page tree indeed
fillPages((SkPdfPageTreeNodeDictionary*)obj);
}
}
}
int SkPdfNativeDoc::pages() const {
return fPages.count();
}
SkPdfPageObjectDictionary* SkPdfNativeDoc::page(int page) {
SkASSERT(page >= 0 && page < fPages.count());
return fPages[page];
}
SkPdfResourceDictionary* SkPdfNativeDoc::pageResources(int page) {
SkASSERT(page >= 0 && page < fPages.count());
return fPages[page]->Resources(this);
}
// TODO(edisonn): Partial implemented.
// Move the logics directly in the code generator for inheritable and default values?
SkRect SkPdfNativeDoc::MediaBox(int page) {
SkPdfPageObjectDictionary* current = fPages[page];
while (!current->has_MediaBox() && current->has_Parent()) {
current = (SkPdfPageObjectDictionary*)current->Parent(this);
}
if (current) {
return current->MediaBox(this);
}
return SkRect::MakeEmpty();
}
size_t SkPdfNativeDoc::objects() const {
return fObjects.count();
}
SkPdfNativeObject* SkPdfNativeDoc::object(int i) {
SkASSERT(!(i < 0 || i > fObjects.count()));
if (i < 0 || i > fObjects.count()) {
return NULL;
}
if (fObjects[i].fObj == NULL) {
fObjects[i].fObj = readObject(i);
// TODO(edisonn): For perf, when we read the cross reference sections, we should take
// advantage of the boundaries of known objects, to minimize the risk of just parsing a bad
// stream, and fail quickly, in case we default to sequential stream read.
}
return fObjects[i].fObj;
}
const SkPdfMapper* SkPdfNativeDoc::mapper() const {
return fMapper;
}
SkPdfReal* SkPdfNativeDoc::createReal(double value) const {
SkPdfNativeObject* obj = fAllocator->allocObject();
SkPdfNativeObject::makeReal(value, obj);
TRACK_OBJECT_SRC(obj);
return (SkPdfReal*)obj;
}
SkPdfInteger* SkPdfNativeDoc::createInteger(int value) const {
SkPdfNativeObject* obj = fAllocator->allocObject();
SkPdfNativeObject::makeInteger(value, obj);
TRACK_OBJECT_SRC(obj);
return (SkPdfInteger*)obj;
}
SkPdfString* SkPdfNativeDoc::createString(const unsigned char* sz, size_t len) const {
SkPdfNativeObject* obj = fAllocator->allocObject();
SkPdfNativeObject::makeString(sz, len, obj);
TRACK_OBJECT_SRC(obj);
return (SkPdfString*)obj;
}
SkPdfAllocator* SkPdfNativeDoc::allocator() const {
return fAllocator;
}
SkPdfNativeObject* SkPdfNativeDoc::resolveReference(SkPdfNativeObject* ref) {
if (ref && ref->isReference()) {
int id = ref->referenceId();
// TODO(edisonn): generation/updates not supported now
//int gen = ref->referenceGeneration();
// TODO(edisonn): verify id and gen expected
if (id < 0 || id >= fObjects.count()) {
SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kReadStreamError_SkPdfIssue,
"resolve reference id out of bounds", NULL, NULL);
return NULL;
}
if (fObjects[id].fIsReferenceResolved) {
SkPdfReportIf(!fObjects[id].fResolvedReference, kIgnoreError_SkPdfIssueSeverity,
kBadReference_SkPdfIssue, "ref is NULL", NULL, NULL);
return fObjects[id].fResolvedReference;
}
// TODO(edisonn): there are pdfs in the crashing suite that cause a stack overflow
// here unless we check for resolved reference on next line.
// Determine if the pdf is corrupted, or we have a bug here.
// Avoids recursive calls
fObjects[id].fIsReferenceResolved = true;
if (fObjects[id].fObj == NULL) {
fObjects[id].fObj = readObject(id);
}
if (fObjects[id].fObj != NULL && fObjects[id].fResolvedReference == NULL) {
if (!fObjects[id].fObj->isReference()) {
fObjects[id].fResolvedReference = fObjects[id].fObj;
} else {
fObjects[id].fResolvedReference = resolveReference(fObjects[id].fObj);
}
}
return fObjects[id].fResolvedReference;
}
return (SkPdfNativeObject*)ref;
}
size_t SkPdfNativeDoc::bytesUsed() const {
return fAllocator->bytesUsed() +
fContentLength +
fObjects.count() * sizeof(PublicObjectEntry) +
fPages.count() * sizeof(SkPdfPageObjectDictionary*) +
sizeof(*this);
}
| bsd-3-clause |
apanda/phantomjs-intercept | src/qt/qtbase/src/corelib/doc/snippets/code/src_corelib_kernel_qcoreapplication.cpp | 105 | 3666 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
//! [0]
QMouseEvent event(QEvent::MouseButtonPress, pos, 0, 0, 0);
QApplication::sendEvent(mainWindow, &event);
//! [0]
//! [1]
QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, SIGNAL(clicked()), &app, SLOT(quit()));
//! [1]
//! [2]
foreach (const QString &path, app.libraryPaths())
do_something(path);
//! [2]
//! [3]
// Called once QCoreApplication exists
static void preRoutineMyDebugTool()
{
MyDebugTool* tool = new MyDebugTool(QCoreApplication::instance());
QCoreApplication::instance()->installEventFilter(tool);
}
Q_COREAPP_STARTUP_FUNCTION(preRoutineMyDebugTool)
//! [3]
//! [4]
static int *global_ptr = 0;
static void cleanup_ptr()
{
delete [] global_ptr;
global_ptr = 0;
}
void init_ptr()
{
global_ptr = new int[100]; // allocate data
qAddPostRoutine(cleanup_ptr); // delete later
}
//! [4]
//! [5]
class MyPrivateInitStuff : public QObject
{
public:
static MyPrivateInitStuff *initStuff(QObject *parent)
{
if (!p)
p = new MyPrivateInitStuff(parent);
return p;
}
~MyPrivateInitStuff()
{
// cleanup goes here
}
private:
MyPrivateInitStuff(QObject *parent)
: QObject(parent)
{
// initialization goes here
}
MyPrivateInitStuff *p;
};
//! [5]
//! [6]
static inline QString tr(const char *sourceText,
const char *comment = 0);
static inline QString trUtf8(const char *sourceText,
const char *comment = 0);
//! [6]
//! [7]
class MyMfcView : public CView
{
Q_DECLARE_TR_FUNCTIONS(MyMfcView)
public:
MyMfcView();
...
};
//! [7]
| bsd-3-clause |
likaiwalkman/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/graphics/ImageBuffer.cpp | 109 | 4744 | /*
* Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ImageBuffer.h"
#include "IntRect.h"
#include <wtf/MathExtras.h>
namespace WebCore {
#if !USE(CG)
void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
{
DEFINE_STATIC_LOCAL(Vector<int>, deviceRgbLUT, ());
DEFINE_STATIC_LOCAL(Vector<int>, linearRgbLUT, ());
if (srcColorSpace == dstColorSpace)
return;
// only sRGB <-> linearRGB are supported at the moment
if ((srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
|| (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB))
return;
if (dstColorSpace == ColorSpaceLinearRGB) {
if (linearRgbLUT.isEmpty()) {
for (unsigned i = 0; i < 256; i++) {
float color = i / 255.0f;
color = (color <= 0.04045f ? color / 12.92f : pow((color + 0.055f) / 1.055f, 2.4f));
color = std::max(0.0f, color);
color = std::min(1.0f, color);
linearRgbLUT.append(static_cast<int>(round(color * 255)));
}
}
platformTransformColorSpace(linearRgbLUT);
} else if (dstColorSpace == ColorSpaceDeviceRGB) {
if (deviceRgbLUT.isEmpty()) {
for (unsigned i = 0; i < 256; i++) {
float color = i / 255.0f;
color = (powf(color, 1.0f / 2.4f) * 1.055f) - 0.055f;
color = std::max(0.0f, color);
color = std::min(1.0f, color);
deviceRgbLUT.append(static_cast<int>(round(color * 255)));
}
}
platformTransformColorSpace(deviceRgbLUT);
}
}
#endif // USE(CG)
inline void ImageBuffer::genericConvertToLuminanceMask()
{
IntRect luminanceRect(IntPoint(), internalSize());
RefPtr<Uint8ClampedArray> srcPixelArray = getUnmultipliedImageData(luminanceRect);
unsigned pixelArrayLength = srcPixelArray->length();
for (unsigned pixelOffset = 0; pixelOffset < pixelArrayLength; pixelOffset += 4) {
unsigned char a = srcPixelArray->item(pixelOffset + 3);
if (!a)
continue;
unsigned char r = srcPixelArray->item(pixelOffset);
unsigned char g = srcPixelArray->item(pixelOffset + 1);
unsigned char b = srcPixelArray->item(pixelOffset + 2);
double luma = (r * 0.2125 + g * 0.7154 + b * 0.0721) * ((double)a / 255.0);
srcPixelArray->set(pixelOffset + 3, luma);
}
putByteArray(Unmultiplied, srcPixelArray.get(), luminanceRect.size(), luminanceRect, IntPoint());
}
void ImageBuffer::convertToLuminanceMask()
{
// Add platform specific functions with platformConvertToLuminanceMask here later.
genericConvertToLuminanceMask();
}
#if USE(ACCELERATED_COMPOSITING) && !USE(CAIRO) && !PLATFORM(BLACKBERRY)
PlatformLayer* ImageBuffer::platformLayer() const
{
return 0;
}
#endif
bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D&, Platform3DObject, GC3Denum, bool, bool)
{
return false;
}
PassOwnPtr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const IntSize& size, float resolutionScale, ColorSpace colorSpace, const GraphicsContext* context, bool)
{
return create(size, resolutionScale, colorSpace, context->isAcceleratedContext() ? Accelerated : Unaccelerated);
}
}
| bsd-3-clause |
wuxianghou/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/IDBBindingUtilities.cpp | 115 | 12039 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
* Copyright (C) 2012 Michael Pruett <michael@68k.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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(INDEXED_DATABASE)
#include "IDBBindingUtilities.h"
#include "DOMRequestState.h"
#include "IDBKey.h"
#include "IDBKeyPath.h"
#include "IDBTracing.h"
#include "SharedBuffer.h"
#include <runtime/DateInstance.h>
#include <runtime/ObjectConstructor.h>
using namespace JSC;
namespace WebCore {
static bool get(ExecState* exec, JSValue object, const String& keyPathElement, JSValue& result)
{
if (object.isString() && keyPathElement == "length") {
result = jsNumber(object.toString(exec)->length());
return true;
}
if (!object.isObject())
return false;
Identifier identifier(&exec->vm(), keyPathElement.utf8().data());
if (!asObject(object)->hasProperty(exec, identifier))
return false;
result = asObject(object)->get(exec, identifier);
return true;
}
static bool canSet(JSValue object, const String& keyPathElement)
{
UNUSED_PARAM(keyPathElement);
return object.isObject();
}
static bool set(ExecState* exec, JSValue& object, const String& keyPathElement, JSValue jsValue)
{
if (!canSet(object, keyPathElement))
return false;
Identifier identifier(&exec->vm(), keyPathElement.utf8().data());
asObject(object)->putDirect(exec->vm(), identifier, jsValue);
return true;
}
static JSValue idbKeyToJSValue(ExecState* exec, JSDOMGlobalObject* globalObject, IDBKey* key)
{
if (!key) {
// This should be undefined, not null.
// Spec: http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBKeyRange
return jsUndefined();
}
switch (key->type()) {
case IDBKey::ArrayType:
{
const IDBKey::KeyArray& inArray = key->array();
size_t size = inArray.size();
JSArray* outArray = constructEmptyArray(exec, 0, globalObject, size);
for (size_t i = 0; i < size; ++i) {
IDBKey* arrayKey = inArray.at(i).get();
outArray->putDirectIndex(exec, i, idbKeyToJSValue(exec, globalObject, arrayKey));
}
return JSValue(outArray);
}
case IDBKey::StringType:
return jsStringWithCache(exec, key->string());
case IDBKey::DateType:
return jsDateOrNull(exec, key->date());
case IDBKey::NumberType:
return jsNumber(key->number());
case IDBKey::MinType:
case IDBKey::InvalidType:
ASSERT_NOT_REACHED();
return jsUndefined();
}
ASSERT_NOT_REACHED();
return jsUndefined();
}
static const size_t maximumDepth = 2000;
static PassRefPtr<IDBKey> createIDBKeyFromValue(ExecState* exec, JSValue value, Vector<JSArray*>& stack)
{
if (value.isNumber() && !std::isnan(value.toNumber(exec)))
return IDBKey::createNumber(value.toNumber(exec));
if (value.isString())
return IDBKey::createString(value.toString(exec)->value(exec));
if (value.inherits(&DateInstance::s_info) && !std::isnan(valueToDate(exec, value)))
return IDBKey::createDate(valueToDate(exec, value));
if (value.isObject()) {
JSObject* object = asObject(value);
if (isJSArray(object) || object->inherits(&JSArray::s_info)) {
JSArray* array = asArray(object);
size_t length = array->length();
if (stack.contains(array))
return 0;
if (stack.size() >= maximumDepth)
return 0;
stack.append(array);
IDBKey::KeyArray subkeys;
for (size_t i = 0; i < length; i++) {
JSValue item = array->getIndex(exec, i);
RefPtr<IDBKey> subkey = createIDBKeyFromValue(exec, item, stack);
if (!subkey)
subkeys.append(IDBKey::createInvalid());
else
subkeys.append(subkey);
}
stack.removeLast();
return IDBKey::createArray(subkeys);
}
}
return 0;
}
PassRefPtr<IDBKey> createIDBKeyFromValue(ExecState* exec, JSValue value)
{
Vector<JSArray*> stack;
RefPtr<IDBKey> key = createIDBKeyFromValue(exec, value, stack);
if (key)
return key;
return IDBKey::createInvalid();
}
IDBKeyPath idbKeyPathFromValue(ExecState* exec, JSValue keyPathValue)
{
IDBKeyPath keyPath;
if (isJSArray(keyPathValue))
keyPath = IDBKeyPath(toNativeArray<String>(exec, keyPathValue));
else
keyPath = IDBKeyPath(keyPathValue.toString(exec)->value(exec));
return keyPath;
}
static JSValue getNthValueOnKeyPath(ExecState* exec, JSValue rootValue, const Vector<String>& keyPathElements, size_t index)
{
JSValue currentValue(rootValue);
ASSERT(index <= keyPathElements.size());
for (size_t i = 0; i < index; i++) {
JSValue parentValue(currentValue);
if (!get(exec, parentValue, keyPathElements[i], currentValue))
return jsUndefined();
}
return currentValue;
}
static PassRefPtr<IDBKey> createIDBKeyFromScriptValueAndKeyPath(ExecState* exec, const ScriptValue& value, const String& keyPath)
{
Vector<String> keyPathElements;
IDBKeyPathParseError error;
IDBParseKeyPath(keyPath, keyPathElements, error);
ASSERT(error == IDBKeyPathParseErrorNone);
JSValue jsValue = value.jsValue();
jsValue = getNthValueOnKeyPath(exec, jsValue, keyPathElements, keyPathElements.size());
if (jsValue.isUndefined())
return 0;
return createIDBKeyFromValue(exec, jsValue);
}
static JSValue ensureNthValueOnKeyPath(ExecState* exec, JSValue rootValue, const Vector<String>& keyPathElements, size_t index)
{
JSValue currentValue(rootValue);
ASSERT(index <= keyPathElements.size());
for (size_t i = 0; i < index; i++) {
JSValue parentValue(currentValue);
const String& keyPathElement = keyPathElements[i];
if (!get(exec, parentValue, keyPathElement, currentValue)) {
JSObject* object = constructEmptyObject(exec);
if (!set(exec, parentValue, keyPathElement, JSValue(object)))
return jsUndefined();
currentValue = JSValue(object);
}
}
return currentValue;
}
static bool canInjectNthValueOnKeyPath(ExecState* exec, JSValue rootValue, const Vector<String>& keyPathElements, size_t index)
{
if (!rootValue.isObject())
return false;
JSValue currentValue(rootValue);
ASSERT(index <= keyPathElements.size());
for (size_t i = 0; i < index; ++i) {
JSValue parentValue(currentValue);
const String& keyPathElement = keyPathElements[i];
if (!get(exec, parentValue, keyPathElement, currentValue))
return canSet(parentValue, keyPathElement);
}
return true;
}
bool injectIDBKeyIntoScriptValue(DOMRequestState* requestState, PassRefPtr<IDBKey> key, ScriptValue& value, const IDBKeyPath& keyPath)
{
IDB_TRACE("injectIDBKeyIntoScriptValue");
ASSERT(keyPath.type() == IDBKeyPath::StringType);
Vector<String> keyPathElements;
IDBKeyPathParseError error;
IDBParseKeyPath(keyPath.string(), keyPathElements, error);
ASSERT(error == IDBKeyPathParseErrorNone);
if (keyPathElements.isEmpty())
return false;
ExecState* exec = requestState->exec();
JSValue parent = ensureNthValueOnKeyPath(exec, value.jsValue(), keyPathElements, keyPathElements.size() - 1);
if (parent.isUndefined())
return false;
if (!set(exec, parent, keyPathElements.last(), idbKeyToJSValue(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), key.get())))
return false;
return true;
}
PassRefPtr<IDBKey> createIDBKeyFromScriptValueAndKeyPath(DOMRequestState* requestState, const ScriptValue& value, const IDBKeyPath& keyPath)
{
IDB_TRACE("createIDBKeyFromScriptValueAndKeyPath");
ASSERT(!keyPath.isNull());
ExecState* exec = requestState->exec();
if (keyPath.type() == IDBKeyPath::ArrayType) {
IDBKey::KeyArray result;
const Vector<String>& array = keyPath.array();
for (size_t i = 0; i < array.size(); i++) {
RefPtr<IDBKey> key = createIDBKeyFromScriptValueAndKeyPath(exec, value, array[i]);
if (!key)
return 0;
result.append(key);
}
return IDBKey::createArray(result);
}
ASSERT(keyPath.type() == IDBKeyPath::StringType);
return createIDBKeyFromScriptValueAndKeyPath(exec, value, keyPath.string());
}
bool canInjectIDBKeyIntoScriptValue(DOMRequestState* requestState, const ScriptValue& scriptValue, const IDBKeyPath& keyPath)
{
IDB_TRACE("canInjectIDBKeyIntoScriptValue");
ASSERT(keyPath.type() == IDBKeyPath::StringType);
Vector<String> keyPathElements;
IDBKeyPathParseError error;
IDBParseKeyPath(keyPath.string(), keyPathElements, error);
ASSERT(error == IDBKeyPathParseErrorNone);
if (!keyPathElements.size())
return false;
JSC::ExecState* exec = requestState->exec();
return canInjectNthValueOnKeyPath(exec, scriptValue.jsValue(), keyPathElements, keyPathElements.size() - 1);
}
ScriptValue deserializeIDBValue(DOMRequestState* requestState, PassRefPtr<SerializedScriptValue> prpValue)
{
ExecState* exec = requestState->exec();
RefPtr<SerializedScriptValue> serializedValue = prpValue;
if (serializedValue)
return ScriptValue::deserialize(exec, serializedValue.get(), NonThrowing);
return ScriptValue(exec->vm(), jsNull());
}
ScriptValue deserializeIDBValueBuffer(DOMRequestState* requestState, PassRefPtr<SharedBuffer> prpBuffer)
{
ExecState* exec = requestState->exec();
RefPtr<SharedBuffer> buffer = prpBuffer;
if (buffer) {
// FIXME: The extra copy here can be eliminated by allowing SerializedScriptValue to take a raw const char* or const uint8_t*.
Vector<uint8_t> value;
value.append(buffer->data(), buffer->size());
RefPtr<SerializedScriptValue> serializedValue = SerializedScriptValue::createFromWireBytes(value);
return ScriptValue::deserialize(exec, serializedValue.get(), NonThrowing);
}
return ScriptValue(exec->vm(), jsNull());
}
ScriptValue idbKeyToScriptValue(DOMRequestState* requestState, PassRefPtr<IDBKey> key)
{
ExecState* exec = requestState->exec();
return ScriptValue(exec->vm(), idbKeyToJSValue(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), key.get()));
}
PassRefPtr<IDBKey> scriptValueToIDBKey(DOMRequestState* requestState, const ScriptValue& scriptValue)
{
ExecState* exec = requestState->exec();
return createIDBKeyFromValue(exec, scriptValue.jsValue());
}
} // namespace WebCore
#endif // ENABLE(INDEXED_DATABASE)
| bsd-3-clause |
toanalien/phantomjs | src/qt/qtwebkit/Source/WebCore/inspector/InspectorDebuggerAgent.cpp | 116 | 31986 | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
#include "InspectorDebuggerAgent.h"
#include "CachedResource.h"
#include "ContentSearchUtils.h"
#include "InjectedScript.h"
#include "InjectedScriptManager.h"
#include "InspectorFrontend.h"
#include "InspectorPageAgent.h"
#include "InspectorState.h"
#include "InspectorValues.h"
#include "InstrumentingAgents.h"
#include "RegularExpression.h"
#include "ScriptDebugServer.h"
#include "ScriptObject.h"
#include <wtf/text/WTFString.h>
using WebCore::TypeBuilder::Array;
using WebCore::TypeBuilder::Debugger::FunctionDetails;
using WebCore::TypeBuilder::Debugger::ScriptId;
using WebCore::TypeBuilder::Runtime::RemoteObject;
namespace WebCore {
namespace DebuggerAgentState {
static const char debuggerEnabled[] = "debuggerEnabled";
static const char javaScriptBreakpoints[] = "javaScriptBreakopints";
static const char pauseOnExceptionsState[] = "pauseOnExceptionsState";
};
const char* InspectorDebuggerAgent::backtraceObjectGroup = "backtrace";
InspectorDebuggerAgent::InspectorDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
: InspectorBaseAgent<InspectorDebuggerAgent>("Debugger", instrumentingAgents, inspectorState)
, m_injectedScriptManager(injectedScriptManager)
, m_frontend(0)
, m_pausedScriptState(0)
, m_javaScriptPauseScheduled(false)
, m_listener(0)
{
// FIXME: make breakReason optional so that there was no need to init it with "other".
clearBreakDetails();
m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
}
InspectorDebuggerAgent::~InspectorDebuggerAgent()
{
ASSERT(!m_instrumentingAgents->inspectorDebuggerAgent());
}
void InspectorDebuggerAgent::enable()
{
m_instrumentingAgents->setInspectorDebuggerAgent(this);
// FIXME(WK44513): breakpoints activated flag should be synchronized between all front-ends
scriptDebugServer().setBreakpointsActivated(true);
startListeningScriptDebugServer();
if (m_listener)
m_listener->debuggerWasEnabled();
}
void InspectorDebuggerAgent::disable()
{
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, InspectorObject::create());
m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
m_instrumentingAgents->setInspectorDebuggerAgent(0);
stopListeningScriptDebugServer();
scriptDebugServer().clearBreakpoints();
scriptDebugServer().clearCompiledScripts();
scriptDebugServer().continueProgram();
clear();
if (m_listener)
m_listener->debuggerWasDisabled();
}
bool InspectorDebuggerAgent::enabled()
{
return m_state->getBoolean(DebuggerAgentState::debuggerEnabled);
}
void InspectorDebuggerAgent::causesRecompilation(ErrorString*, bool* result)
{
*result = scriptDebugServer().causesRecompilation();
}
void InspectorDebuggerAgent::canSetScriptSource(ErrorString*, bool* result)
{
*result = scriptDebugServer().canSetScriptSource();
}
void InspectorDebuggerAgent::supportsSeparateScriptCompilationAndExecution(ErrorString*, bool* result)
{
*result = scriptDebugServer().supportsSeparateScriptCompilationAndExecution();
}
void InspectorDebuggerAgent::enable(ErrorString*)
{
if (enabled())
return;
enable();
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, true);
ASSERT(m_frontend);
}
void InspectorDebuggerAgent::disable(ErrorString*)
{
if (!enabled())
return;
disable();
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
}
void InspectorDebuggerAgent::restore()
{
if (enabled()) {
m_frontend->globalObjectCleared();
enable();
long pauseState = m_state->getLong(DebuggerAgentState::pauseOnExceptionsState);
String error;
setPauseOnExceptionsImpl(&error, pauseState);
}
}
void InspectorDebuggerAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->debugger();
}
void InspectorDebuggerAgent::clearFrontend()
{
m_frontend = 0;
if (!enabled())
return;
disable();
// FIXME: due to m_state->mute() hack in InspectorController, debuggerEnabled is actually set to false only
// in InspectorState, but not in cookie. That's why after navigation debuggerEnabled will be true,
// but after front-end re-open it will still be false.
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
}
void InspectorDebuggerAgent::setBreakpointsActive(ErrorString*, bool active)
{
if (active)
scriptDebugServer().activateBreakpoints();
else
scriptDebugServer().deactivateBreakpoints();
}
bool InspectorDebuggerAgent::isPaused()
{
return scriptDebugServer().isPaused();
}
bool InspectorDebuggerAgent::runningNestedMessageLoop()
{
return scriptDebugServer().runningNestedMessageLoop();
}
void InspectorDebuggerAgent::addMessageToConsole(MessageSource source, MessageType type)
{
if (scriptDebugServer().pauseOnExceptionsState() != ScriptDebugServer::DontPauseOnExceptions && source == ConsoleAPIMessageSource && type == AssertMessageType)
breakProgram(InspectorFrontend::Debugger::Reason::Assert, 0);
}
static PassRefPtr<InspectorObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, bool isRegex)
{
RefPtr<InspectorObject> breakpointObject = InspectorObject::create();
breakpointObject->setString("url", url);
breakpointObject->setNumber("lineNumber", lineNumber);
breakpointObject->setNumber("columnNumber", columnNumber);
breakpointObject->setString("condition", condition);
breakpointObject->setBoolean("isRegex", isRegex);
return breakpointObject;
}
static bool matches(const String& url, const String& pattern, bool isRegex)
{
if (isRegex) {
RegularExpression regex(pattern, TextCaseSensitive);
return regex.match(url) != -1;
}
return url == pattern;
}
void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations)
{
locations = Array<TypeBuilder::Debugger::Location>::create();
if (!optionalURL == !optionalURLRegex) {
*errorString = "Either url or urlRegex must be specified.";
return;
}
String url = optionalURL ? *optionalURL : *optionalURLRegex;
int columnNumber = optionalColumnNumber ? *optionalColumnNumber : 0;
String condition = optionalCondition ? *optionalCondition : "";
bool isRegex = optionalURLRegex;
String breakpointId = (isRegex ? "/" + url + "/" : url) + ':' + String::number(lineNumber) + ':' + String::number(columnNumber);
RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
if (breakpointsCookie->find(breakpointId) != breakpointsCookie->end()) {
*errorString = "Breakpoint at specified location already exists.";
return;
}
breakpointsCookie->setObject(breakpointId, buildObjectForBreakpointCookie(url, lineNumber, columnNumber, condition, isRegex));
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, breakpointsCookie);
ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition);
for (ScriptsMap::iterator it = m_scripts.begin(); it != m_scripts.end(); ++it) {
if (!matches(it->value.url, url, isRegex))
continue;
RefPtr<TypeBuilder::Debugger::Location> location = resolveBreakpoint(breakpointId, it->key, breakpoint);
if (location)
locations->addItem(location);
}
*outBreakpointId = breakpointId;
}
static bool parseLocation(ErrorString* errorString, RefPtr<InspectorObject> location, String* scriptId, int* lineNumber, int* columnNumber)
{
if (!location->getString("scriptId", scriptId) || !location->getNumber("lineNumber", lineNumber)) {
// FIXME: replace with input validation.
*errorString = "scriptId and lineNumber are required.";
return false;
}
*columnNumber = 0;
location->getNumber("columnNumber", columnNumber);
return true;
}
void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<InspectorObject>& location, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
{
String scriptId;
int lineNumber;
int columnNumber;
if (!parseLocation(errorString, location, &scriptId, &lineNumber, &columnNumber))
return;
String condition = optionalCondition ? *optionalCondition : emptyString();
String breakpointId = scriptId + ':' + String::number(lineNumber) + ':' + String::number(columnNumber);
if (m_breakpointIdToDebugServerBreakpointIds.find(breakpointId) != m_breakpointIdToDebugServerBreakpointIds.end()) {
*errorString = "Breakpoint at specified location already exists.";
return;
}
ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition);
actualLocation = resolveBreakpoint(breakpointId, scriptId, breakpoint);
if (actualLocation)
*outBreakpointId = breakpointId;
else
*errorString = "Could not resolve breakpoint";
}
void InspectorDebuggerAgent::removeBreakpoint(ErrorString*, const String& breakpointId)
{
RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
breakpointsCookie->remove(breakpointId);
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, breakpointsCookie);
BreakpointIdToDebugServerBreakpointIdsMap::iterator debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.find(breakpointId);
if (debugServerBreakpointIdsIterator == m_breakpointIdToDebugServerBreakpointIds.end())
return;
for (size_t i = 0; i < debugServerBreakpointIdsIterator->value.size(); ++i)
scriptDebugServer().removeBreakpoint(debugServerBreakpointIdsIterator->value[i]);
m_breakpointIdToDebugServerBreakpointIds.remove(debugServerBreakpointIdsIterator);
}
void InspectorDebuggerAgent::continueToLocation(ErrorString* errorString, const RefPtr<InspectorObject>& location)
{
if (!m_continueToLocationBreakpointId.isEmpty()) {
scriptDebugServer().removeBreakpoint(m_continueToLocationBreakpointId);
m_continueToLocationBreakpointId = "";
}
String scriptId;
int lineNumber;
int columnNumber;
if (!parseLocation(errorString, location, &scriptId, &lineNumber, &columnNumber))
return;
ScriptBreakpoint breakpoint(lineNumber, columnNumber, "");
m_continueToLocationBreakpointId = scriptDebugServer().setBreakpoint(scriptId, breakpoint, &lineNumber, &columnNumber);
resume(errorString);
}
PassRefPtr<TypeBuilder::Debugger::Location> InspectorDebuggerAgent::resolveBreakpoint(const String& breakpointId, const String& scriptId, const ScriptBreakpoint& breakpoint)
{
ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
if (scriptIterator == m_scripts.end())
return 0;
Script& script = scriptIterator->value;
if (breakpoint.lineNumber < script.startLine || script.endLine < breakpoint.lineNumber)
return 0;
int actualLineNumber;
int actualColumnNumber;
String debugServerBreakpointId = scriptDebugServer().setBreakpoint(scriptId, breakpoint, &actualLineNumber, &actualColumnNumber);
if (debugServerBreakpointId.isEmpty())
return 0;
BreakpointIdToDebugServerBreakpointIdsMap::iterator debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.find(breakpointId);
if (debugServerBreakpointIdsIterator == m_breakpointIdToDebugServerBreakpointIds.end())
debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.set(breakpointId, Vector<String>()).iterator;
debugServerBreakpointIdsIterator->value.append(debugServerBreakpointId);
RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
.setScriptId(scriptId)
.setLineNumber(actualLineNumber);
location->setColumnNumber(actualColumnNumber);
return location;
}
static PassRefPtr<InspectorObject> scriptToInspectorObject(ScriptObject scriptObject)
{
if (scriptObject.hasNoValue())
return 0;
RefPtr<InspectorValue> value = scriptObject.toInspectorValue(scriptObject.scriptState());
if (!value)
return 0;
return value->asObject();
}
void InspectorDebuggerAgent::searchInContent(ErrorString* error, const String& scriptId, const String& query, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Array<WebCore::TypeBuilder::Page::SearchMatch> >& results)
{
bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
ScriptsMap::iterator it = m_scripts.find(scriptId);
if (it != m_scripts.end())
results = ContentSearchUtils::searchInTextByLines(it->value.source, query, caseSensitive, isRegex);
else
*error = "No script for id: " + scriptId;
}
void InspectorDebuggerAgent::setScriptSource(ErrorString* error, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result)
{
bool previewOnly = preview && *preview;
ScriptObject resultObject;
if (!scriptDebugServer().setScriptSource(scriptId, newContent, previewOnly, error, &m_currentCallStack, &resultObject))
return;
newCallFrames = currentCallFrames();
RefPtr<InspectorObject> object = scriptToInspectorObject(resultObject);
if (object)
result = object;
}
void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result)
{
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(callFrameId);
if (injectedScript.hasNoValue()) {
*errorString = "Inspected frame has gone";
return;
}
injectedScript.restartFrame(errorString, m_currentCallStack, callFrameId, &result);
scriptDebugServer().updateCallStack(&m_currentCallStack);
newCallFrames = currentCallFrames();
}
void InspectorDebuggerAgent::getScriptSource(ErrorString* error, const String& scriptId, String* scriptSource)
{
ScriptsMap::iterator it = m_scripts.find(scriptId);
if (it != m_scripts.end())
*scriptSource = it->value.source;
else
*error = "No script for id: " + scriptId;
}
void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>& details)
{
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(functionId);
if (injectedScript.hasNoValue()) {
*errorString = "Function object id is obsolete";
return;
}
injectedScript.getFunctionDetails(errorString, functionId, &details);
}
void InspectorDebuggerAgent::schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data)
{
if (m_javaScriptPauseScheduled)
return;
m_breakReason = breakReason;
m_breakAuxData = data;
scriptDebugServer().setPauseOnNextStatement(true);
}
void InspectorDebuggerAgent::cancelPauseOnNextStatement()
{
if (m_javaScriptPauseScheduled)
return;
clearBreakDetails();
scriptDebugServer().setPauseOnNextStatement(false);
}
void InspectorDebuggerAgent::pause(ErrorString*)
{
if (m_javaScriptPauseScheduled)
return;
clearBreakDetails();
scriptDebugServer().setPauseOnNextStatement(true);
m_javaScriptPauseScheduled = true;
}
void InspectorDebuggerAgent::resume(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
scriptDebugServer().continueProgram();
}
void InspectorDebuggerAgent::stepOver(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
scriptDebugServer().stepOverStatement();
}
void InspectorDebuggerAgent::stepInto(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
scriptDebugServer().stepIntoStatement();
m_listener->stepInto();
}
void InspectorDebuggerAgent::stepOut(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
scriptDebugServer().stepOutOfFunction();
}
void InspectorDebuggerAgent::setPauseOnExceptions(ErrorString* errorString, const String& stringPauseState)
{
ScriptDebugServer::PauseOnExceptionsState pauseState;
if (stringPauseState == "none")
pauseState = ScriptDebugServer::DontPauseOnExceptions;
else if (stringPauseState == "all")
pauseState = ScriptDebugServer::PauseOnAllExceptions;
else if (stringPauseState == "uncaught")
pauseState = ScriptDebugServer::PauseOnUncaughtExceptions;
else {
*errorString = "Unknown pause on exceptions mode: " + stringPauseState;
return;
}
setPauseOnExceptionsImpl(errorString, pauseState);
}
void InspectorDebuggerAgent::setPauseOnExceptionsImpl(ErrorString* errorString, int pauseState)
{
scriptDebugServer().setPauseOnExceptionsState(static_cast<ScriptDebugServer::PauseOnExceptionsState>(pauseState));
if (scriptDebugServer().pauseOnExceptionsState() != pauseState)
*errorString = "Internal error. Could not change pause on exceptions state";
else
m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, pauseState);
}
void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
{
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(callFrameId);
if (injectedScript.hasNoValue()) {
*errorString = "Inspected frame has gone";
return;
}
ScriptDebugServer::PauseOnExceptionsState previousPauseOnExceptionsState = scriptDebugServer().pauseOnExceptionsState();
if (doNotPauseOnExceptionsAndMuteConsole ? *doNotPauseOnExceptionsAndMuteConsole : false) {
if (previousPauseOnExceptionsState != ScriptDebugServer::DontPauseOnExceptions)
scriptDebugServer().setPauseOnExceptionsState(ScriptDebugServer::DontPauseOnExceptions);
muteConsole();
}
injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack, callFrameId, expression, objectGroup ? *objectGroup : "", includeCommandLineAPI ? *includeCommandLineAPI : false, returnByValue ? *returnByValue : false, generatePreview ? *generatePreview : false, &result, wasThrown);
if (doNotPauseOnExceptionsAndMuteConsole ? *doNotPauseOnExceptionsAndMuteConsole : false) {
unmuteConsole();
if (scriptDebugServer().pauseOnExceptionsState() != previousPauseOnExceptionsState)
scriptDebugServer().setPauseOnExceptionsState(previousPauseOnExceptionsState);
}
}
void InspectorDebuggerAgent::compileScript(ErrorString* errorString, const String& expression, const String& sourceURL, TypeBuilder::OptOutput<ScriptId>* scriptId, TypeBuilder::OptOutput<String>* syntaxErrorMessage)
{
InjectedScript injectedScript = injectedScriptForEval(errorString, 0);
if (injectedScript.hasNoValue()) {
*errorString = "Inspected frame has gone";
return;
}
String scriptIdValue;
String exceptionMessage;
scriptDebugServer().compileScript(injectedScript.scriptState(), expression, sourceURL, &scriptIdValue, &exceptionMessage);
if (!scriptIdValue && !exceptionMessage) {
*errorString = "Script compilation failed";
return;
}
*syntaxErrorMessage = exceptionMessage;
*scriptId = scriptIdValue;
}
void InspectorDebuggerAgent::runScript(ErrorString* errorString, const ScriptId& scriptId, const int* executionContextId, const String* const objectGroup, const bool* const doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
{
InjectedScript injectedScript = injectedScriptForEval(errorString, executionContextId);
if (injectedScript.hasNoValue()) {
*errorString = "Inspected frame has gone";
return;
}
ScriptDebugServer::PauseOnExceptionsState previousPauseOnExceptionsState = scriptDebugServer().pauseOnExceptionsState();
if (doNotPauseOnExceptionsAndMuteConsole && *doNotPauseOnExceptionsAndMuteConsole) {
if (previousPauseOnExceptionsState != ScriptDebugServer::DontPauseOnExceptions)
scriptDebugServer().setPauseOnExceptionsState(ScriptDebugServer::DontPauseOnExceptions);
muteConsole();
}
ScriptValue value;
bool wasThrownValue;
String exceptionMessage;
scriptDebugServer().runScript(injectedScript.scriptState(), scriptId, &value, &wasThrownValue, &exceptionMessage);
*wasThrown = wasThrownValue;
if (value.hasNoValue()) {
*errorString = "Script execution failed";
return;
}
result = injectedScript.wrapObject(value, objectGroup ? *objectGroup : "");
if (wasThrownValue)
result->setDescription(exceptionMessage);
if (doNotPauseOnExceptionsAndMuteConsole && *doNotPauseOnExceptionsAndMuteConsole) {
unmuteConsole();
if (scriptDebugServer().pauseOnExceptionsState() != previousPauseOnExceptionsState)
scriptDebugServer().setPauseOnExceptionsState(previousPauseOnExceptionsState);
}
}
void InspectorDebuggerAgent::setOverlayMessage(ErrorString*, const String*)
{
}
void InspectorDebuggerAgent::setVariableValue(ErrorString* errorString, int scopeNumber, const String& variableName, const RefPtr<InspectorObject>& newValue, const String* callFrameId, const String* functionObjectId)
{
InjectedScript injectedScript;
if (callFrameId) {
injectedScript = m_injectedScriptManager->injectedScriptForObjectId(*callFrameId);
if (injectedScript.hasNoValue()) {
*errorString = "Inspected frame has gone";
return;
}
} else if (functionObjectId) {
injectedScript = m_injectedScriptManager->injectedScriptForObjectId(*functionObjectId);
if (injectedScript.hasNoValue()) {
*errorString = "Function object id cannot be resolved";
return;
}
} else {
*errorString = "Either call frame or function object must be specified";
return;
}
String newValueString = newValue->toJSONString();
injectedScript.setVariableValue(errorString, m_currentCallStack, callFrameId, functionObjectId, scopeNumber, variableName, newValueString);
}
void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText)
{
if (scriptDebugServer().pauseOnExceptionsState() != ScriptDebugServer::DontPauseOnExceptions) {
RefPtr<InspectorObject> directive = InspectorObject::create();
directive->setString("directiveText", directiveText);
breakProgram(InspectorFrontend::Debugger::Reason::CSPViolation, directive.release());
}
}
PassRefPtr<Array<TypeBuilder::Debugger::CallFrame> > InspectorDebuggerAgent::currentCallFrames()
{
if (!m_pausedScriptState)
return Array<TypeBuilder::Debugger::CallFrame>::create();
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState);
if (injectedScript.hasNoValue()) {
ASSERT_NOT_REACHED();
return Array<TypeBuilder::Debugger::CallFrame>::create();
}
return injectedScript.wrapCallFrames(m_currentCallStack);
}
String InspectorDebuggerAgent::sourceMapURLForScript(const Script& script)
{
DEFINE_STATIC_LOCAL(String, sourceMapHTTPHeader, (ASCIILiteral("SourceMap")));
DEFINE_STATIC_LOCAL(String, sourceMapHTTPHeaderDeprecated, (ASCIILiteral("X-SourceMap")));
if (!script.url.isEmpty()) {
if (InspectorPageAgent* pageAgent = m_instrumentingAgents->inspectorPageAgent()) {
CachedResource* resource = pageAgent->cachedResource(pageAgent->mainFrame(), KURL(ParsedURLString, script.url));
if (resource) {
String sourceMapHeader = resource->response().httpHeaderField(sourceMapHTTPHeader);
if (!sourceMapHeader.isEmpty())
return sourceMapHeader;
sourceMapHeader = resource->response().httpHeaderField(sourceMapHTTPHeaderDeprecated);
if (!sourceMapHeader.isEmpty())
return sourceMapHeader;
}
}
}
return ContentSearchUtils::findScriptSourceMapURL(script.source);
}
// JavaScriptDebugListener functions
void InspectorDebuggerAgent::didParseSource(const String& scriptId, const Script& script)
{
// Don't send script content to the front end until it's really needed.
const bool* isContentScript = script.isContentScript ? &script.isContentScript : 0;
String sourceMapURL = sourceMapURLForScript(script);
String* sourceMapURLParam = sourceMapURL.isNull() ? 0 : &sourceMapURL;
String sourceURL;
if (!script.startLine && !script.startColumn)
sourceURL = ContentSearchUtils::findScriptSourceURL(script.source);
bool hasSourceURL = !sourceURL.isEmpty();
String scriptURL = hasSourceURL ? sourceURL : script.url;
bool* hasSourceURLParam = hasSourceURL ? &hasSourceURL : 0;
m_frontend->scriptParsed(scriptId, scriptURL, script.startLine, script.startColumn, script.endLine, script.endColumn, isContentScript, sourceMapURLParam, hasSourceURLParam);
m_scripts.set(scriptId, script);
if (scriptURL.isEmpty())
return;
RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
for (InspectorObject::iterator it = breakpointsCookie->begin(); it != breakpointsCookie->end(); ++it) {
RefPtr<InspectorObject> breakpointObject = it->value->asObject();
bool isRegex;
breakpointObject->getBoolean("isRegex", &isRegex);
String url;
breakpointObject->getString("url", &url);
if (!matches(scriptURL, url, isRegex))
continue;
ScriptBreakpoint breakpoint;
breakpointObject->getNumber("lineNumber", &breakpoint.lineNumber);
breakpointObject->getNumber("columnNumber", &breakpoint.columnNumber);
breakpointObject->getString("condition", &breakpoint.condition);
RefPtr<TypeBuilder::Debugger::Location> location = resolveBreakpoint(it->key, scriptId, breakpoint);
if (location)
m_frontend->breakpointResolved(it->key, location);
}
}
void InspectorDebuggerAgent::failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage)
{
m_frontend->scriptFailedToParse(url, data, firstLine, errorLine, errorMessage);
}
void InspectorDebuggerAgent::didPause(ScriptState* scriptState, const ScriptValue& callFrames, const ScriptValue& exception)
{
ASSERT(scriptState && !m_pausedScriptState);
m_pausedScriptState = scriptState;
m_currentCallStack = callFrames;
if (!exception.hasNoValue()) {
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(scriptState);
if (!injectedScript.hasNoValue()) {
m_breakReason = InspectorFrontend::Debugger::Reason::Exception;
m_breakAuxData = injectedScript.wrapObject(exception, "backtrace")->openAccessors();
// m_breakAuxData might be null after this.
}
}
m_frontend->paused(currentCallFrames(), m_breakReason, m_breakAuxData);
m_javaScriptPauseScheduled = false;
if (!m_continueToLocationBreakpointId.isEmpty()) {
scriptDebugServer().removeBreakpoint(m_continueToLocationBreakpointId);
m_continueToLocationBreakpointId = "";
}
if (m_listener)
m_listener->didPause();
}
void InspectorDebuggerAgent::didContinue()
{
m_pausedScriptState = 0;
m_currentCallStack = ScriptValue();
clearBreakDetails();
m_frontend->resumed();
}
void InspectorDebuggerAgent::breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data)
{
m_breakReason = breakReason;
m_breakAuxData = data;
scriptDebugServer().breakProgram();
}
void InspectorDebuggerAgent::clear()
{
m_pausedScriptState = 0;
m_currentCallStack = ScriptValue();
m_scripts.clear();
m_breakpointIdToDebugServerBreakpointIds.clear();
m_continueToLocationBreakpointId = String();
clearBreakDetails();
m_javaScriptPauseScheduled = false;
ErrorString error;
setOverlayMessage(&error, 0);
}
bool InspectorDebuggerAgent::assertPaused(ErrorString* errorString)
{
if (!m_pausedScriptState) {
*errorString = "Can only perform operation while paused.";
return false;
}
return true;
}
void InspectorDebuggerAgent::clearBreakDetails()
{
m_breakReason = InspectorFrontend::Debugger::Reason::Other;
m_breakAuxData = 0;
}
void InspectorDebuggerAgent::reset()
{
m_scripts.clear();
m_breakpointIdToDebugServerBreakpointIds.clear();
if (m_frontend)
m_frontend->globalObjectCleared();
}
} // namespace WebCore
#endif // ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
| bsd-3-clause |
ixiom/phantomjs | src/qt/qtwebkit/Source/WebCore/html/shadow/ProgressShadowElement.cpp | 116 | 3381 | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(PROGRESS_ELEMENT)
#include "ProgressShadowElement.h"
#include "HTMLNames.h"
#include "HTMLProgressElement.h"
#include "RenderProgress.h"
namespace WebCore {
using namespace HTMLNames;
ProgressShadowElement::ProgressShadowElement(Document* document)
: HTMLDivElement(HTMLNames::divTag, document)
{
}
HTMLProgressElement* ProgressShadowElement::progressElement() const
{
return toHTMLProgressElement(shadowHost());
}
bool ProgressShadowElement::rendererIsNeeded(const NodeRenderingContext& context)
{
RenderObject* progressRenderer = progressElement()->renderer();
return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(context);
}
ProgressInnerElement::ProgressInnerElement(Document* document)
: ProgressShadowElement(document)
{
DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
setPseudo(pseudoId);
}
PassRefPtr<ProgressInnerElement> ProgressInnerElement::create(Document* document)
{
return adoptRef(new ProgressInnerElement(document));
}
RenderObject* ProgressInnerElement::createRenderer(RenderArena* arena, RenderStyle*)
{
return new (arena) RenderProgress(this);
}
bool ProgressInnerElement::rendererIsNeeded(const NodeRenderingContext& context)
{
if (progressElement()->hasAuthorShadowRoot())
return HTMLDivElement::rendererIsNeeded(context);
RenderObject* progressRenderer = progressElement()->renderer();
return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(context);
}
void ProgressValueElement::setWidthPercentage(double width)
{
setInlineStyleProperty(CSSPropertyWidth, width, CSSPrimitiveValue::CSS_PERCENTAGE);
}
}
#endif
| bsd-3-clause |
sharma1nitish/phantomjs | src/qt/qtwebkit/Source/WebCore/editing/atk/FrameSelectionAtk.cpp | 117 | 3771 | /*
* Copyright (C) 2009 Igalia S.L.
*
* 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 "FrameSelection.h"
#if HAVE(ACCESSIBILITY)
#include "AXObjectCache.h"
#include "Document.h"
#include "Frame.h"
#include "WebKitAccessibleWrapperAtk.h"
#if PLATFORM(EFL)
#include <glib.h>
#else
#include <gtk/gtk.h>
#endif
#include <wtf/RefPtr.h>
namespace WebCore {
static void emitTextSelectionChange(AccessibilityObject* object, VisibleSelection selection, int offset)
{
AtkObject* axObject = object->wrapper();
if (!axObject || !ATK_IS_TEXT(axObject))
return;
g_signal_emit_by_name(axObject, "text-caret-moved", offset);
if (selection.isRange())
g_signal_emit_by_name(axObject, "text-selection-changed");
}
static void maybeEmitTextFocusChange(PassRefPtr<AccessibilityObject> prpObject)
{
// This static variable is needed to keep track of the old object
// as per previous calls to this function, in order to properly
// decide whether to emit some signals or not.
DEFINE_STATIC_LOCAL(RefPtr<AccessibilityObject>, oldObject, ());
RefPtr<AccessibilityObject> object = prpObject;
// Ensure the oldObject belongs to the same document that the
// current object so further comparisons make sense. Otherwise,
// just reset oldObject to 0 so it won't be taken into account in
// the immediately following call to this function.
if (object && oldObject && oldObject->document() != object->document())
oldObject = 0;
AtkObject* axObject = object ? object->wrapper() : 0;
AtkObject* oldAxObject = oldObject ? oldObject->wrapper() : 0;
if (axObject != oldAxObject) {
if (oldAxObject && ATK_IS_TEXT(oldAxObject)) {
g_signal_emit_by_name(oldAxObject, "focus-event", false);
g_signal_emit_by_name(oldAxObject, "state-change", "focused", false);
}
if (axObject && ATK_IS_TEXT(axObject)) {
g_signal_emit_by_name(axObject, "focus-event", true);
g_signal_emit_by_name(axObject, "state-change", "focused", true);
}
}
// Update pointer to last focused object.
oldObject = object;
}
void FrameSelection::notifyAccessibilityForSelectionChange()
{
if (!AXObjectCache::accessibilityEnabled())
return;
if (!m_selection.start().isNotNull() || !m_selection.end().isNotNull())
return;
RenderObject* focusedNode = m_selection.end().containerNode()->renderer();
AXObjectCache* cache = m_frame->document()->existingAXObjectCache();
if (!cache)
return;
AccessibilityObject* accessibilityObject = cache->getOrCreate(focusedNode);
if (!accessibilityObject)
return;
int offset;
RefPtr<AccessibilityObject> object = objectFocusedAndCaretOffsetUnignored(accessibilityObject, offset);
if (!object)
return;
emitTextSelectionChange(object.get(), m_selection, offset);
maybeEmitTextFocusChange(object.release());
}
} // namespace WebCore
#endif // HAVE(ACCESSIBILITY)
| bsd-3-clause |
bprodoehl/phantomjs | src/qt/qtwebkit/Tools/WebKitTestRunner/PixelDumpSupport.cpp | 126 | 4086 | /*
* Copyright (C) 2009 Apple, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PixelDumpSupport.h"
#include "CyclicRedundancyCheck.h"
#include <cstdio>
static void appendIntToVector(unsigned number, Vector<unsigned char>& vector)
{
size_t offset = vector.size();
vector.grow(offset + 4);
vector[offset] = ((number >> 24) & 0xff);
vector[offset + 1] = ((number >> 16) & 0xff);
vector[offset + 2] = ((number >> 8) & 0xff);
vector[offset + 3] = (number & 0xff);
}
static void convertChecksumToPNGComment(const char* checksum, Vector<unsigned char>& bytesToAdd)
{
// Chunks of PNG files are <length>, <type>, <data>, <crc>.
static const char textCommentPrefix[] = "\x00\x00\x00\x29tEXtchecksum\x00";
static const size_t prefixLength = sizeof(textCommentPrefix) - 1; // The -1 is for the null at the end of the char[].
static const size_t checksumLength = 32;
bytesToAdd.append(textCommentPrefix, prefixLength);
bytesToAdd.append(checksum, checksumLength);
Vector<unsigned char> dataToCrc;
dataToCrc.append(textCommentPrefix + 4, prefixLength - 4); // Don't include the chunk length in the crc.
dataToCrc.append(checksum, checksumLength);
unsigned crc32 = computeCrc(dataToCrc);
appendIntToVector(crc32, bytesToAdd);
}
static size_t offsetAfterIHDRChunk(const unsigned char* data, const size_t dataLength)
{
const int pngHeaderLength = 8;
const int pngIHDRChunkLength = 25; // chunk length + "IHDR" + 13 bytes of data + checksum
return pngHeaderLength + pngIHDRChunkLength;
}
void printPNG(const unsigned char* data, const size_t dataLength, const char* checksum)
{
Vector<unsigned char> bytesToAdd;
convertChecksumToPNGComment(checksum, bytesToAdd);
printf("Content-Type: %s\n", "image/png");
printf("Content-Length: %lu\n", static_cast<unsigned long>(dataLength + bytesToAdd.size()));
size_t insertOffset = offsetAfterIHDRChunk(data, dataLength);
fwrite(data, 1, insertOffset, stdout);
fwrite(bytesToAdd.data(), 1, bytesToAdd.size(), stdout);
const size_t bytesToWriteInOneChunk = 1 << 15;
data += insertOffset;
size_t dataRemainingToWrite = dataLength - insertOffset;
while (dataRemainingToWrite) {
size_t bytesToWriteInThisChunk = std::min(dataRemainingToWrite, bytesToWriteInOneChunk);
size_t bytesWritten = fwrite(data, 1, bytesToWriteInThisChunk, stdout);
if (bytesWritten != bytesToWriteInThisChunk)
break;
dataRemainingToWrite -= bytesWritten;
data += bytesWritten;
}
}
| bsd-3-clause |
bukalov/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/JSEntryCustom.cpp | 127 | 2220 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(FILE_SYSTEM)
#include "JSEntry.h"
#include "Entry.h"
#include "JSDOMBinding.h"
#include "JSDirectoryEntry.h"
#include "JSFileEntry.h"
#include <wtf/Assertions.h>
using namespace JSC;
namespace WebCore {
JSValue toJS(ExecState* exec, JSDOMGlobalObject* globalObject, Entry* entry)
{
if (!entry)
return jsNull();
if (entry->isFile())
return wrap<JSFileEntry>(exec, globalObject, static_cast<FileEntry*>(entry));
ASSERT(entry->isDirectory());
return wrap<JSDirectoryEntry>(exec, globalObject, static_cast<DirectoryEntry*>(entry));
}
} // namespace WebCore
#endif // ENABLE(FILE_SYSTEM)
| bsd-3-clause |
eceglov/phantomjs | src/qt/qtwebkit/Source/WebCore/svg/SVGAnimatedIntegerOptionalInteger.cpp | 127 | 5079 | /*
* Copyright (C) Research In Motion Limited 2012. 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"
#if ENABLE(SVG)
#include "SVGAnimatedIntegerOptionalInteger.h"
#include "SVGAnimateElement.h"
#include "SVGAnimatedInteger.h"
#include "SVGParserUtilities.h"
namespace WebCore {
SVGAnimatedIntegerOptionalIntegerAnimator::SVGAnimatedIntegerOptionalIntegerAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
: SVGAnimatedTypeAnimator(AnimatedIntegerOptionalInteger, animationElement, contextElement)
{
}
PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerOptionalIntegerAnimator::constructFromString(const String& string)
{
OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createIntegerOptionalInteger(new pair<int, int>);
pair<int, int>& animatedInteger = animtedType->integerOptionalInteger();
float firstNumber = 0;
float secondNumber = 0;
if (!parseNumberOptionalNumber(string, firstNumber, secondNumber)) {
animatedInteger.first = 0;
animatedInteger.second = 0;
} else {
animatedInteger.first = static_cast<int>(roundf(firstNumber));
animatedInteger.second = static_cast<int>(roundf(secondNumber));
}
return animtedType.release();
}
PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerOptionalIntegerAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
{
return SVGAnimatedType::createIntegerOptionalInteger(constructFromBaseValues<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes));
}
void SVGAnimatedIntegerOptionalIntegerAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
{
stopAnimValAnimationForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
}
void SVGAnimatedIntegerOptionalIntegerAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
{
resetFromBaseValues<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes, type, &SVGAnimatedType::integerOptionalInteger);
}
void SVGAnimatedIntegerOptionalIntegerAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
{
animValWillChangeForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
}
void SVGAnimatedIntegerOptionalIntegerAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
{
animValDidChangeForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
}
void SVGAnimatedIntegerOptionalIntegerAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
{
ASSERT(from->type() == AnimatedIntegerOptionalInteger);
ASSERT(from->type() == to->type());
const pair<int, int>& fromIntegerPair = from->integerOptionalInteger();
pair<int, int>& toIntegerPair = to->integerOptionalInteger();
toIntegerPair.first += fromIntegerPair.first;
toIntegerPair.second += fromIntegerPair.second;
}
void SVGAnimatedIntegerOptionalIntegerAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
{
ASSERT(m_animationElement);
ASSERT(m_contextElement);
const pair<int, int>& fromIntegerPair = m_animationElement->animationMode() == ToAnimation ? animated->integerOptionalInteger() : from->integerOptionalInteger();
const pair<int, int>& toIntegerPair = to->integerOptionalInteger();
const pair<int, int>& toAtEndOfDurationIntegerPair = toAtEndOfDuration->integerOptionalInteger();
pair<int, int>& animatedIntegerPair = animated->integerOptionalInteger();
SVGAnimatedIntegerAnimator::calculateAnimatedInteger(m_animationElement, percentage, repeatCount, fromIntegerPair.first, toIntegerPair.first, toAtEndOfDurationIntegerPair.first, animatedIntegerPair.first);
SVGAnimatedIntegerAnimator::calculateAnimatedInteger(m_animationElement, percentage, repeatCount, fromIntegerPair.second, toIntegerPair.second, toAtEndOfDurationIntegerPair.second, animatedIntegerPair.second);
}
float SVGAnimatedIntegerOptionalIntegerAnimator::calculateDistance(const String&, const String&)
{
// FIXME: Distance calculation is not possible for SVGIntegerOptionalInteger right now. We need the distance for every single value.
return -1;
}
}
#endif // ENABLE(SVG)
| bsd-3-clause |
grevutiu-gabriel/phantomjs | src/qt/qtwebkit/Source/WebKit/win/DefaultDownloadDelegate.cpp | 140 | 8426 | /*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitDLL.h"
#include "DefaultDownloadDelegate.h"
#include "MarshallingHelpers.h"
#include "WebKit.h"
#include "WebKitLogging.h"
#include "WebMutableURLRequest.h"
#include <WebCore/COMPtr.h>
#include <wtf/text/CString.h>
#include <shlobj.h>
#include <wchar.h>
#include <WebCore/BString.h>
using namespace WebCore;
// DefaultDownloadDelegate ----------------------------------------------------------------
DefaultDownloadDelegate::DefaultDownloadDelegate()
: m_refCount(0)
{
gClassCount++;
gClassNameCount.add("DefaultDownloadDelegate");
}
DefaultDownloadDelegate::~DefaultDownloadDelegate()
{
gClassCount--;
gClassNameCount.remove("DefaultDownloadDelegate");
HashSet<IWebDownload*>::iterator i = m_downloads.begin();
for (;i != m_downloads.end(); ++i)
(*i)->Release();
}
DefaultDownloadDelegate* DefaultDownloadDelegate::sharedInstance()
{
static COMPtr<DefaultDownloadDelegate> shared;
if (!shared)
shared.adoptRef(DefaultDownloadDelegate::createInstance());
return shared.get();
}
DefaultDownloadDelegate* DefaultDownloadDelegate::createInstance()
{
DefaultDownloadDelegate* instance = new DefaultDownloadDelegate();
instance->AddRef();
return instance;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IUnknown*>(this);
else if (IsEqualGUID(riid, IID_IWebDownloadDelegate))
*ppvObject = static_cast<IWebDownloadDelegate*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE DefaultDownloadDelegate::AddRef()
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE DefaultDownloadDelegate::Release()
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::decideDestinationWithSuggestedFilename(IWebDownload *download, BSTR filename)
{
LOG(Download, "DefaultDownloadDelegate %p - decideDestinationWithSuggestedFilename %s", download, String(filename, SysStringLen(filename)).ascii().data());
WCHAR pathChars[MAX_PATH];
if (FAILED(SHGetFolderPath(0, CSIDL_DESKTOPDIRECTORY | CSIDL_FLAG_CREATE, 0, 0, pathChars))) {
if (FAILED(download->setDestination(filename, true))) {
LOG_ERROR("Failed to set destination on file");
return E_FAIL;
}
return S_OK;
}
size_t fullLength = wcslen(pathChars) + SysStringLen(filename) + 2;
BSTR full = SysAllocStringLen(0, (UINT)fullLength);
if (!full)
return E_OUTOFMEMORY;
wcscpy_s(full, fullLength, pathChars);
wcscat_s(full, fullLength, L"\\");
wcscat_s(full, fullLength, filename);
BString fullPath;
fullPath.adoptBSTR(full);
#ifndef NDEBUG
String debug((BSTR)fullPath, SysStringLen(BSTR(fullPath)));
LOG(Download, "Setting path to %s", debug.ascii().data());
#endif
if (FAILED(download->setDestination(fullPath, true))) {
LOG_ERROR("Failed to set destination on file");
return E_FAIL;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didCancelAuthenticationChallenge(IWebDownload* download, IWebURLAuthenticationChallenge* challenge)
{
LOG(Download, "DefaultDownloadDelegate %p - didCancelAuthenticationChallenge %p", download, challenge);
download = 0;
challenge = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didCreateDestination(IWebDownload* download, BSTR destination)
{
LOG(Download, "DefaultDownloadDelegate %p - didCreateDestination %s", download, String(destination, SysStringLen(destination)).ascii().data());
download = 0;
destination = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didReceiveAuthenticationChallenge(IWebDownload* download, IWebURLAuthenticationChallenge* challenge)
{
LOG(Download, "DefaultDownloadDelegate %p - didReceiveAuthenticationChallenge %p", download, challenge);
download = 0;
challenge = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didReceiveDataOfLength(IWebDownload* download, unsigned length)
{
LOG(Download, "DefaultDownloadDelegate %p - didReceiveDataOfLength %i", download, length);
download = 0;
length = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didReceiveResponse(IWebDownload* download, IWebURLResponse* response)
{
LOG(Download, "DefaultDownloadDelegate %p - didReceiveResponse %p", download, response);
download = 0;
response = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::shouldDecodeSourceDataOfMIMEType(IWebDownload* download, BSTR encodingType, BOOL* shouldDecode)
{
LOG(Download, "DefaultDownloadDelegate %p - shouldDecodeSourceDataOfMIMEType %s", download, String(encodingType, SysStringLen(encodingType)).ascii().data());
download = 0;
encodingType = 0;
*shouldDecode = false;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::willResumeWithResponse(IWebDownload* download, IWebURLResponse* response, long long fromByte)
{
LOG(Download, "DefaultDownloadDelegate %p - willResumeWithResponse %p, %q", download, response, fromByte);
download = 0;
response = 0;
fromByte = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::willSendRequest(IWebDownload* download, IWebMutableURLRequest* request,
IWebURLResponse* redirectResponse, IWebMutableURLRequest** finalRequest)
{
LOG(Download, "DefaultDownloadDelegate %p - willSendRequest %p %p", download, request, redirectResponse);
download = 0;
redirectResponse = 0;
*finalRequest = request;
(*finalRequest)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didBegin(IWebDownload* download)
{
LOG(Download, "DefaultDownloadDelegate %p - didBegin", download);
registerDownload(download);
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didFinish(IWebDownload* download)
{
LOG(Download, "DefaultDownloadDelegate %p - didFinish", download);
unregisterDownload(download);
return S_OK;
}
HRESULT STDMETHODCALLTYPE DefaultDownloadDelegate::didFailWithError(IWebDownload* download, IWebError* error)
{
LOG(Download, "DefaultDownloadDelegate %p - didFailWithError %p", download, error);
unregisterDownload(download);
error = 0;
return S_OK;
}
void DefaultDownloadDelegate::registerDownload(IWebDownload* download)
{
if (m_downloads.contains(download))
return;
download->AddRef();
m_downloads.add(download);
}
void DefaultDownloadDelegate::unregisterDownload(IWebDownload* download)
{
if (m_downloads.contains(download)) {
download->Release();
m_downloads.remove(download);
}
}
| bsd-3-clause |
trankmichael/scipy | scipy/special/cdflib/gaminv.f | 151 | 10511 | SUBROUTINE gaminv(a,x,x0,p,q,ierr)
C ----------------------------------------------------------------------
C INVERSE INCOMPLETE GAMMA RATIO FUNCTION
C
C GIVEN POSITIVE A, AND NONEGATIVE P AND Q WHERE P + Q = 1.
C THEN X IS COMPUTED WHERE P(A,X) = P AND Q(A,X) = Q. SCHRODER
C ITERATION IS EMPLOYED. THE ROUTINE ATTEMPTS TO COMPUTE X
C TO 10 SIGNIFICANT DIGITS IF THIS IS POSSIBLE FOR THE
C PARTICULAR COMPUTER ARITHMETIC BEING USED.
C
C ------------
C
C X IS A VARIABLE. IF P = 0 THEN X IS ASSIGNED THE VALUE 0,
C AND IF Q = 0 THEN X IS SET TO THE LARGEST FLOATING POINT
C NUMBER AVAILABLE. OTHERWISE, GAMINV ATTEMPTS TO OBTAIN
C A SOLUTION FOR P(A,X) = P AND Q(A,X) = Q. IF THE ROUTINE
C IS SUCCESSFUL THEN THE SOLUTION IS STORED IN X.
C
C X0 IS AN OPTIONAL INITIAL APPROXIMATION FOR X. IF THE USER
C DOES NOT WISH TO SUPPLY AN INITIAL APPROXIMATION, THEN SET
C X0 .LE. 0.
C
C IERR IS A VARIABLE THAT REPORTS THE STATUS OF THE RESULTS.
C WHEN THE ROUTINE TERMINATES, IERR HAS ONE OF THE FOLLOWING
C VALUES ...
C
C IERR = 0 THE SOLUTION WAS OBTAINED. ITERATION WAS
C NOT USED.
C IERR.GT.0 THE SOLUTION WAS OBTAINED. IERR ITERATIONS
C WERE PERFORMED.
C IERR = -2 (INPUT ERROR) A .LE. 0
C IERR = -3 NO SOLUTION WAS OBTAINED. THE RATIO Q/A
C IS TOO LARGE.
C IERR = -4 (INPUT ERROR) P + Q .NE. 1
C IERR = -6 20 ITERATIONS WERE PERFORMED. THE MOST
C RECENT VALUE OBTAINED FOR X IS GIVEN.
C THIS CANNOT OCCUR IF X0 .LE. 0.
C IERR = -7 ITERATION FAILED. NO VALUE IS GIVEN FOR X.
C THIS MAY OCCUR WHEN X IS APPROXIMATELY 0.
C IERR = -8 A VALUE FOR X HAS BEEN OBTAINED, BUT THE
C ROUTINE IS NOT CERTAIN OF ITS ACCURACY.
C ITERATION CANNOT BE PERFORMED IN THIS
C CASE. IF X0 .LE. 0, THIS CAN OCCUR ONLY
C WHEN P OR Q IS APPROXIMATELY 0. IF X0 IS
C POSITIVE THEN THIS CAN OCCUR WHEN A IS
C EXCEEDINGLY CLOSE TO X AND A IS EXTREMELY
C LARGE (SAY A .GE. 1.E20).
C ----------------------------------------------------------------------
C WRITTEN BY ALFRED H. MORRIS, JR.
C NAVAL SURFACE WEAPONS CENTER
C DAHLGREN, VIRGINIA
C -------------------
C .. Scalar Arguments ..
DOUBLE PRECISION a,p,q,x,x0
INTEGER ierr
C ..
C .. Local Scalars ..
DOUBLE PRECISION a0,a1,a2,a3,am1,amax,ap1,ap2,ap3,apn,b,b1,b2,b3,
+ b4,c,c1,c2,c3,c4,c5,d,e,e2,eps,g,h,ln10,pn,qg,qn,
+ r,rta,s,s2,sum,t,tol,u,w,xmax,xmin,xn,y,z
INTEGER iop
C ..
C .. Local Arrays ..
DOUBLE PRECISION amin(2),bmin(2),dmin(2),emin(2),eps0(2)
C ..
C .. External Functions ..
DOUBLE PRECISION alnrel,gamln,gamln1,gamma,rcomp,spmpar
EXTERNAL alnrel,gamln,gamln1,gamma,rcomp,spmpar
C ..
C .. External Subroutines ..
EXTERNAL gratio
C ..
C .. Intrinsic Functions ..
INTRINSIC abs,dble,dlog,dmax1,exp,sqrt
C ..
C .. Data statements ..
C -------------------
C LN10 = LN(10)
C C = EULER CONSTANT
C -------------------
C -------------------
C -------------------
C -------------------
DATA ln10/2.302585D0/
DATA c/.577215664901533D0/
DATA a0/3.31125922108741D0/,a1/11.6616720288968D0/,
+ a2/4.28342155967104D0/,a3/.213623493715853D0/
DATA b1/6.61053765625462D0/,b2/6.40691597760039D0/,
+ b3/1.27364489782223D0/,b4/.036117081018842D0/
DATA eps0(1)/1.D-10/,eps0(2)/1.D-08/
DATA amin(1)/500.0D0/,amin(2)/100.0D0/
DATA bmin(1)/1.D-28/,bmin(2)/1.D-13/
DATA dmin(1)/1.D-06/,dmin(2)/1.D-04/
DATA emin(1)/2.D-03/,emin(2)/6.D-03/
DATA tol/1.D-5/
C ..
C .. Executable Statements ..
C -------------------
C ****** E, XMIN, AND XMAX ARE MACHINE DEPENDENT CONSTANTS.
C E IS THE SMALLEST NUMBER FOR WHICH 1.0 + E .GT. 1.0.
C XMIN IS THE SMALLEST POSITIVE NUMBER AND XMAX IS THE
C LARGEST POSITIVE NUMBER.
C
e = spmpar(1)
xmin = spmpar(2)
xmax = spmpar(3)
C -------------------
x = 0.0D0
IF (a.LE.0.0D0) GO TO 300
t = dble(p) + dble(q) - 1.D0
IF (abs(t).GT.e) GO TO 320
C
ierr = 0
IF (p.EQ.0.0D0) RETURN
IF (q.EQ.0.0D0) GO TO 270
IF (a.EQ.1.0D0) GO TO 280
C
e2 = 2.0D0*e
amax = 0.4D-10/ (e*e)
iop = 1
IF (e.GT.1.D-10) iop = 2
eps = eps0(iop)
xn = x0
IF (x0.GT.0.0D0) GO TO 160
C
C SELECTION OF THE INITIAL APPROXIMATION XN OF X
C WHEN A .LT. 1
C
IF (a.GT.1.0D0) GO TO 80
g = gamma(a+1.0D0)
qg = q*g
IF (qg.EQ.0.0D0) GO TO 360
b = qg/a
IF (qg.GT.0.6D0*a) GO TO 40
IF (a.GE.0.30D0 .OR. b.LT.0.35D0) GO TO 10
t = exp(- (b+c))
u = t*exp(t)
xn = t*exp(u)
GO TO 160
C
10 IF (b.GE.0.45D0) GO TO 40
IF (b.EQ.0.0D0) GO TO 360
y = -dlog(b)
s = 0.5D0 + (0.5D0-a)
z = dlog(y)
t = y - s*z
IF (b.LT.0.15D0) GO TO 20
xn = y - s*dlog(t) - dlog(1.0D0+s/ (t+1.0D0))
GO TO 220
20 IF (b.LE.0.01D0) GO TO 30
u = ((t+2.0D0* (3.0D0-a))*t+ (2.0D0-a)* (3.0D0-a))/
+ ((t+ (5.0D0-a))*t+2.0D0)
xn = y - s*dlog(t) - dlog(u)
GO TO 220
30 c1 = -s*z
c2 = -s* (1.0D0+c1)
c3 = s* ((0.5D0*c1+ (2.0D0-a))*c1+ (2.5D0-1.5D0*a))
c4 = -s* (((c1/3.0D0+ (2.5D0-1.5D0*a))*c1+ ((a-6.0D0)*a+7.0D0))*
+ c1+ ((11.0D0*a-46)*a+47.0D0)/6.0D0)
c5 = -s* ((((-c1/4.0D0+ (11.0D0*a-17.0D0)/6.0D0)*c1+ ((-3.0D0*a+
+ 13.0D0)*a-13.0D0))*c1+0.5D0* (((2.0D0*a-25.0D0)*a+72.0D0)*a-
+ 61.0D0))*c1+ (((25.0D0*a-195.0D0)*a+477.0D0)*a-379.0D0)/
+ 12.0D0)
xn = ((((c5/y+c4)/y+c3)/y+c2)/y+c1) + y
IF (a.GT.1.0D0) GO TO 220
IF (b.GT.bmin(iop)) GO TO 220
x = xn
RETURN
C
40 IF (b*q.GT.1.D-8) GO TO 50
xn = exp(- (q/a+c))
GO TO 70
50 IF (p.LE.0.9D0) GO TO 60
xn = exp((alnrel(-q)+gamln1(a))/a)
GO TO 70
60 xn = exp(dlog(p*g)/a)
70 IF (xn.EQ.0.0D0) GO TO 310
t = 0.5D0 + (0.5D0-xn/ (a+1.0D0))
xn = xn/t
GO TO 160
C
C SELECTION OF THE INITIAL APPROXIMATION XN OF X
C WHEN A .GT. 1
C
80 IF (q.LE.0.5D0) GO TO 90
w = dlog(p)
GO TO 100
90 w = dlog(q)
100 t = sqrt(-2.0D0*w)
s = t - (((a3*t+a2)*t+a1)*t+a0)/ ((((b4*t+b3)*t+b2)*t+b1)*t+1.0D0)
IF (q.GT.0.5D0) s = -s
C
rta = sqrt(a)
s2 = s*s
xn = a + s*rta + (s2-1.0D0)/3.0D0 + s* (s2-7.0D0)/ (36.0D0*rta) -
+ ((3.0D0*s2+7.0D0)*s2-16.0D0)/ (810.0D0*a) +
+ s* ((9.0D0*s2+256.0D0)*s2-433.0D0)/ (38880.0D0*a*rta)
xn = dmax1(xn,0.0D0)
IF (a.LT.amin(iop)) GO TO 110
x = xn
d = 0.5D0 + (0.5D0-x/a)
IF (abs(d).LE.dmin(iop)) RETURN
C
110 IF (p.LE.0.5D0) GO TO 130
IF (xn.LT.3.0D0*a) GO TO 220
y = - (w+gamln(a))
d = dmax1(2.0D0,a* (a-1.0D0))
IF (y.LT.ln10*d) GO TO 120
s = 1.0D0 - a
z = dlog(y)
GO TO 30
120 t = a - 1.0D0
xn = y + t*dlog(xn) - alnrel(-t/ (xn+1.0D0))
xn = y + t*dlog(xn) - alnrel(-t/ (xn+1.0D0))
GO TO 220
C
130 ap1 = a + 1.0D0
IF (xn.GT.0.70D0*ap1) GO TO 170
w = w + gamln(ap1)
IF (xn.GT.0.15D0*ap1) GO TO 140
ap2 = a + 2.0D0
ap3 = a + 3.0D0
x = exp((w+x)/a)
x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+x/ap2)))/a)
x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+x/ap2)))/a)
x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+ (x/ap2)* (1.0D0+
+ x/ap3))))/a)
xn = x
IF (xn.GT.1.D-2*ap1) GO TO 140
IF (xn.LE.emin(iop)*ap1) RETURN
GO TO 170
C
140 apn = ap1
t = xn/apn
sum = 1.0D0 + t
150 apn = apn + 1.0D0
t = t* (xn/apn)
sum = sum + t
IF (t.GT.1.D-4) GO TO 150
t = w - dlog(sum)
xn = exp((xn+t)/a)
xn = xn* (1.0D0- (a*dlog(xn)-xn-t)/ (a-xn))
GO TO 170
C
C SCHRODER ITERATION USING P
C
160 IF (p.GT.0.5D0) GO TO 220
170 IF (p.LE.1.D10*xmin) GO TO 350
am1 = (a-0.5D0) - 0.5D0
180 IF (a.LE.amax) GO TO 190
d = 0.5D0 + (0.5D0-xn/a)
IF (abs(d).LE.e2) GO TO 350
C
190 IF (ierr.GE.20) GO TO 330
ierr = ierr + 1
CALL gratio(a,xn,pn,qn,0)
IF (pn.EQ.0.0D0 .OR. qn.EQ.0.0D0) GO TO 350
r = rcomp(a,xn)
IF (r.EQ.0.0D0) GO TO 350
t = (pn-p)/r
w = 0.5D0* (am1-xn)
IF (abs(t).LE.0.1D0 .AND. abs(w*t).LE.0.1D0) GO TO 200
x = xn* (1.0D0-t)
IF (x.LE.0.0D0) GO TO 340
d = abs(t)
GO TO 210
C
200 h = t* (1.0D0+w*t)
x = xn* (1.0D0-h)
IF (x.LE.0.0D0) GO TO 340
IF (abs(w).GE.1.0D0 .AND. abs(w)*t*t.LE.eps) RETURN
d = abs(h)
210 xn = x
IF (d.GT.tol) GO TO 180
IF (d.LE.eps) RETURN
IF (abs(p-pn).LE.tol*p) RETURN
GO TO 180
C
C SCHRODER ITERATION USING Q
C
220 IF (q.LE.1.D10*xmin) GO TO 350
am1 = (a-0.5D0) - 0.5D0
230 IF (a.LE.amax) GO TO 240
d = 0.5D0 + (0.5D0-xn/a)
IF (abs(d).LE.e2) GO TO 350
C
240 IF (ierr.GE.20) GO TO 330
ierr = ierr + 1
CALL gratio(a,xn,pn,qn,0)
IF (pn.EQ.0.0D0 .OR. qn.EQ.0.0D0) GO TO 350
r = rcomp(a,xn)
IF (r.EQ.0.0D0) GO TO 350
t = (q-qn)/r
w = 0.5D0* (am1-xn)
IF (abs(t).LE.0.1D0 .AND. abs(w*t).LE.0.1D0) GO TO 250
x = xn* (1.0D0-t)
IF (x.LE.0.0D0) GO TO 340
d = abs(t)
GO TO 260
C
250 h = t* (1.0D0+w*t)
x = xn* (1.0D0-h)
IF (x.LE.0.0D0) GO TO 340
IF (abs(w).GE.1.0D0 .AND. abs(w)*t*t.LE.eps) RETURN
d = abs(h)
260 xn = x
IF (d.GT.tol) GO TO 230
IF (d.LE.eps) RETURN
IF (abs(q-qn).LE.tol*q) RETURN
GO TO 230
C
C SPECIAL CASES
C
270 x = xmax
RETURN
C
280 IF (q.LT.0.9D0) GO TO 290
x = -alnrel(-p)
RETURN
290 x = -dlog(q)
RETURN
C
C ERROR RETURN
C
300 ierr = -2
RETURN
C
310 ierr = -3
RETURN
C
320 ierr = -4
RETURN
C
330 ierr = -6
RETURN
C
340 ierr = -7
RETURN
C
350 x = xn
ierr = -8
RETURN
C
360 x = xmax
ierr = -8
RETURN
END
| bsd-3-clause |
kyle-emmerich/blueshift-engine | Dependencies/bullet/include/BulletCollision/CollisionShapes/btConeShape.cpp | 411 | 4137 | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btConeShape.h"
btConeShape::btConeShape (btScalar radius,btScalar height): btConvexInternalShape (),
m_radius (radius),
m_height(height)
{
m_shapeType = CONE_SHAPE_PROXYTYPE;
setConeUpIndex(1);
btVector3 halfExtents;
m_sinAngle = (m_radius / btSqrt(m_radius * m_radius + m_height * m_height));
}
btConeShapeZ::btConeShapeZ (btScalar radius,btScalar height):
btConeShape(radius,height)
{
setConeUpIndex(2);
}
btConeShapeX::btConeShapeX (btScalar radius,btScalar height):
btConeShape(radius,height)
{
setConeUpIndex(0);
}
///choose upAxis index
void btConeShape::setConeUpIndex(int upIndex)
{
switch (upIndex)
{
case 0:
m_coneIndices[0] = 1;
m_coneIndices[1] = 0;
m_coneIndices[2] = 2;
break;
case 1:
m_coneIndices[0] = 0;
m_coneIndices[1] = 1;
m_coneIndices[2] = 2;
break;
case 2:
m_coneIndices[0] = 0;
m_coneIndices[1] = 2;
m_coneIndices[2] = 1;
break;
default:
btAssert(0);
};
m_implicitShapeDimensions[m_coneIndices[0]] = m_radius;
m_implicitShapeDimensions[m_coneIndices[1]] = m_height;
m_implicitShapeDimensions[m_coneIndices[2]] = m_radius;
}
btVector3 btConeShape::coneLocalSupport(const btVector3& v) const
{
btScalar halfHeight = m_height * btScalar(0.5);
if (v[m_coneIndices[1]] > v.length() * m_sinAngle)
{
btVector3 tmp;
tmp[m_coneIndices[0]] = btScalar(0.);
tmp[m_coneIndices[1]] = halfHeight;
tmp[m_coneIndices[2]] = btScalar(0.);
return tmp;
}
else {
btScalar s = btSqrt(v[m_coneIndices[0]] * v[m_coneIndices[0]] + v[m_coneIndices[2]] * v[m_coneIndices[2]]);
if (s > SIMD_EPSILON) {
btScalar d = m_radius / s;
btVector3 tmp;
tmp[m_coneIndices[0]] = v[m_coneIndices[0]] * d;
tmp[m_coneIndices[1]] = -halfHeight;
tmp[m_coneIndices[2]] = v[m_coneIndices[2]] * d;
return tmp;
}
else {
btVector3 tmp;
tmp[m_coneIndices[0]] = btScalar(0.);
tmp[m_coneIndices[1]] = -halfHeight;
tmp[m_coneIndices[2]] = btScalar(0.);
return tmp;
}
}
}
btVector3 btConeShape::localGetSupportingVertexWithoutMargin(const btVector3& vec) const
{
return coneLocalSupport(vec);
}
void btConeShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int i=0;i<numVectors;i++)
{
const btVector3& vec = vectors[i];
supportVerticesOut[i] = coneLocalSupport(vec);
}
}
btVector3 btConeShape::localGetSupportingVertex(const btVector3& vec) const
{
btVector3 supVertex = coneLocalSupport(vec);
if ( getMargin()!=btScalar(0.) )
{
btVector3 vecnorm = vec;
if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON))
{
vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.));
}
vecnorm.normalize();
supVertex+= getMargin() * vecnorm;
}
return supVertex;
}
void btConeShape::setLocalScaling(const btVector3& scaling)
{
int axis = m_coneIndices[1];
int r1 = m_coneIndices[0];
int r2 = m_coneIndices[2];
m_height *= scaling[axis] / m_localScaling[axis];
m_radius *= (scaling[r1] / m_localScaling[r1] + scaling[r2] / m_localScaling[r2]) / 2;
m_sinAngle = (m_radius / btSqrt(m_radius * m_radius + m_height * m_height));
btConvexInternalShape::setLocalScaling(scaling);
} | bsd-3-clause |
PurityROM/platform_external_skia | src/animator/SkPathParts.cpp | 206 | 5287 |
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPathParts.h"
#include "SkAnimateMaker.h"
#include "SkDrawMatrix.h"
#include "SkDrawRectangle.h"
#include "SkDrawPath.h"
SkPathPart::SkPathPart() : fPath(NULL) {
}
void SkPathPart::dirty() {
fPath->dirty();
}
SkDisplayable* SkPathPart::getParent() const {
return fPath;
}
bool SkPathPart::setParent(SkDisplayable* parent) {
SkASSERT(parent != NULL);
if (parent->isPath() == false)
return true;
fPath = (SkDrawPath*) parent;
return false;
}
// MoveTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkMoveTo::fInfo[] = {
SK_MEMBER(x, Float),
SK_MEMBER(y, Float)
};
#endif
DEFINE_GET_MEMBER(SkMoveTo);
SkMoveTo::SkMoveTo() : x(0), y(0) {
}
bool SkMoveTo::add() {
fPath->fPath.moveTo(x, y);
return false;
}
// RMoveTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkRMoveTo::fInfo[] = {
SK_MEMBER_INHERITED
};
#endif
DEFINE_GET_MEMBER(SkRMoveTo);
bool SkRMoveTo::add() {
fPath->fPath.rMoveTo(x, y);
return false;
}
// LineTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkLineTo::fInfo[] = {
SK_MEMBER(x, Float),
SK_MEMBER(y, Float)
};
#endif
DEFINE_GET_MEMBER(SkLineTo);
SkLineTo::SkLineTo() : x(0), y(0) {
}
bool SkLineTo::add() {
fPath->fPath.lineTo(x, y);
return false;
}
// RLineTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkRLineTo::fInfo[] = {
SK_MEMBER_INHERITED
};
#endif
DEFINE_GET_MEMBER(SkRLineTo);
bool SkRLineTo::add() {
fPath->fPath.rLineTo(x, y);
return false;
}
// QuadTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkQuadTo::fInfo[] = {
SK_MEMBER(x1, Float),
SK_MEMBER(x2, Float),
SK_MEMBER(y1, Float),
SK_MEMBER(y2, Float)
};
#endif
DEFINE_GET_MEMBER(SkQuadTo);
SkQuadTo::SkQuadTo() : x1(0), y1(0), x2(0), y2(0) {
}
bool SkQuadTo::add() {
fPath->fPath.quadTo(x1, y1, x2, y2);
return false;
}
// RQuadTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkRQuadTo::fInfo[] = {
SK_MEMBER_INHERITED
};
#endif
DEFINE_GET_MEMBER(SkRQuadTo);
bool SkRQuadTo::add() {
fPath->fPath.rQuadTo(x1, y1, x2, y2);
return false;
}
// CubicTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkCubicTo::fInfo[] = {
SK_MEMBER(x1, Float),
SK_MEMBER(x2, Float),
SK_MEMBER(x3, Float),
SK_MEMBER(y1, Float),
SK_MEMBER(y2, Float),
SK_MEMBER(y3, Float)
};
#endif
DEFINE_GET_MEMBER(SkCubicTo);
SkCubicTo::SkCubicTo() : x1(0), y1(0), x2(0), y2(0), x3(0), y3(0) {
}
bool SkCubicTo::add() {
fPath->fPath.cubicTo(x1, y1, x2, y2, x3, y3);
return false;
}
// RCubicTo
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkRCubicTo::fInfo[] = {
SK_MEMBER_INHERITED
};
#endif
DEFINE_GET_MEMBER(SkRCubicTo);
bool SkRCubicTo::add() {
fPath->fPath.rCubicTo(x1, y1, x2, y2, x3, y3);
return false;
}
// SkClose
bool SkClose::add() {
fPath->fPath.close();
return false;
}
// SkAddGeom
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddGeom::fInfo[] = {
SK_MEMBER(direction, PathDirection)
};
#endif
DEFINE_GET_MEMBER(SkAddGeom);
SkAddGeom::SkAddGeom() : direction(SkPath::kCCW_Direction) {
}
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddRect::fInfo[] = {
SK_MEMBER_INHERITED,
SK_MEMBER_ALIAS(bottom, fRect.fBottom, Float),
SK_MEMBER_ALIAS(left, fRect.fLeft, Float),
SK_MEMBER_ALIAS(right, fRect.fRight, Float),
SK_MEMBER_ALIAS(top, fRect.fTop, Float)
};
#endif
DEFINE_GET_MEMBER(SkAddRect);
SkAddRect::SkAddRect() {
fRect.setEmpty();
}
bool SkAddRect::add() {
fPath->fPath.addRect(fRect, (SkPath::Direction) direction);
return false;
}
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddOval::fInfo[] = {
SK_MEMBER_INHERITED
};
#endif
DEFINE_GET_MEMBER(SkAddOval);
bool SkAddOval::add() {
fPath->fPath.addOval(fRect, (SkPath::Direction) direction);
return false;
}
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddCircle::fInfo[] = {
SK_MEMBER_INHERITED,
SK_MEMBER(radius, Float),
SK_MEMBER(x, Float),
SK_MEMBER(y, Float)
};
#endif
DEFINE_GET_MEMBER(SkAddCircle);
SkAddCircle::SkAddCircle() : radius(0), x(0), y(0) {
}
bool SkAddCircle::add() {
fPath->fPath.addCircle(x, y, radius, (SkPath::Direction) direction);
return false;
}
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddRoundRect::fInfo[] = {
SK_MEMBER_INHERITED,
SK_MEMBER(rx, Float),
SK_MEMBER(ry, Float)
};
#endif
DEFINE_GET_MEMBER(SkAddRoundRect);
SkAddRoundRect::SkAddRoundRect() : rx(0), ry(0) {
}
bool SkAddRoundRect::add() {
fPath->fPath.addRoundRect(fRect, rx, ry, (SkPath::Direction) direction);
return false;
}
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkAddPath::fInfo[] = {
SK_MEMBER(matrix, Matrix),
SK_MEMBER(path, Path)
};
#endif
DEFINE_GET_MEMBER(SkAddPath);
SkAddPath::SkAddPath() : matrix(NULL), path(NULL) {
}
bool SkAddPath::add() {
SkASSERT (path != NULL);
if (matrix)
fPath->fPath.addPath(path->fPath, matrix->getMatrix());
else
fPath->fPath.addPath(path->fPath);
return false;
}
| bsd-3-clause |
eriknstr/ThinkPad-FreeBSD-setup | FreeBSD/sys/dev/ppc/ppc_acpi.c | 4 | 3328 | /*-
* Copyright (c) 2006 Marcel Moolenaar
* 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$");
#include "opt_isa.h"
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <machine/bus.h>
#include <isa/isareg.h>
#include <isa/isavar.h>
#include <dev/ppbus/ppbconf.h>
#include <dev/ppbus/ppb_msq.h>
#include <dev/ppc/ppcvar.h>
#include <dev/ppc/ppcreg.h>
#include "ppbus_if.h"
static int ppc_acpi_probe(device_t dev);
int ppc_isa_attach(device_t dev);
int ppc_isa_write(device_t, char *, int, int);
static device_method_t ppc_acpi_methods[] = {
/* device interface */
DEVMETHOD(device_probe, ppc_acpi_probe),
#ifdef DEV_ISA
DEVMETHOD(device_attach, ppc_isa_attach),
#else
DEVMETHOD(device_attach, ppc_attach),
#endif
DEVMETHOD(device_detach, ppc_detach),
/* bus interface */
DEVMETHOD(bus_read_ivar, ppc_read_ivar),
DEVMETHOD(bus_write_ivar, ppc_write_ivar),
DEVMETHOD(bus_alloc_resource, ppc_alloc_resource),
DEVMETHOD(bus_release_resource, ppc_release_resource),
/* ppbus interface */
DEVMETHOD(ppbus_io, ppc_io),
DEVMETHOD(ppbus_exec_microseq, ppc_exec_microseq),
DEVMETHOD(ppbus_reset_epp, ppc_reset_epp),
DEVMETHOD(ppbus_setmode, ppc_setmode),
DEVMETHOD(ppbus_ecp_sync, ppc_ecp_sync),
DEVMETHOD(ppbus_read, ppc_read),
#ifdef DEV_ISA
DEVMETHOD(ppbus_write, ppc_isa_write),
#else
DEVMETHOD(ppbus_write, ppc_write),
#endif
{ 0, 0 }
};
static driver_t ppc_acpi_driver = {
ppc_driver_name,
ppc_acpi_methods,
sizeof(struct ppc_data),
};
static struct isa_pnp_id lpc_ids[] = {
{ 0x0004d041, "Standard parallel printer port" }, /* PNP0400 */
{ 0x0104d041, "ECP parallel printer port" }, /* PNP0401 */
{ 0 }
};
static int
ppc_acpi_probe(device_t dev)
{
device_t parent;
int error;
parent = device_get_parent(dev);
error = ISA_PNP_PROBE(parent, dev, lpc_ids);
if (error)
return (ENXIO);
device_set_desc(dev, "Parallel port");
return (ppc_probe(dev, 0));
}
DRIVER_MODULE(ppc, acpi, ppc_acpi_driver, ppc_devclass, 0, 0);
| isc |
andrewssobral/bgslibrary | src/algorithms/LBP_MRF/MEImage.cpp | 1 | 50479 | #include <opencv2/opencv.hpp>
// opencv legacy includes
#include <opencv2/imgproc/types_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include "MEImage.hpp"
#include "MEDefs.hpp"
#if CV_MAJOR_VERSION >= 2 && CV_MAJOR_VERSION <= 3 && CV_MINOR_VERSION <= 4 && CV_VERSION_REVISION <= 7
//using namespace bgslibrary::algorithms::lbp_mrf;
#define ME_CAST_TO_IPLIMAGE(image_ptr) ((IplImage*)image_ptr)
#define ME_RELEASE_IPLIMAGE(image_ptr) \
cvReleaseImage((IplImage**)&image_ptr); \
image_ptr = NULL;
namespace bgslibrary
{
namespace algorithms
{
namespace lbp_mrf
{
// RGB to YUV transform
const float RGBtoYUVMatrix[3][3] =
{ { 0.299, 0.587, 0.114 },
{ -0.147, -0.289, 0.436 },
{ 0.615, -0.515, -0.100 } };
// RGB to YIQ transform
const float RGBtoYIQMatrix[3][3] =
{ { 0.299, 0.587, 0.114 },
{ 0.596, -0.274, -0.322 },
{ 0.212, -0.523, 0.311 } };
MEImage::MEImage(int width, int height, int layers) : cvImg(NULL)
{
_Init(width, height, layers);
}
MEImage::MEImage(const MEImage& other) : cvImg(NULL)
{
_Copy(other);
}
MEImage::~MEImage()
{
if (ME_CAST_TO_IPLIMAGE(cvImg))
{
ME_RELEASE_IPLIMAGE(cvImg);
}
}
void MEImage::Clear()
{
cvSetZero(ME_CAST_TO_IPLIMAGE(cvImg));
}
void MEImage::GetLayer(MEImage& new_layer, int layer_number) const
{
int LayerNumber = layer_number;
if ((new_layer.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width) ||
(new_layer.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height) ||
(new_layer.GetLayers() != 1))
{
new_layer.Realloc(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height, 1);
}
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels < LayerNumber)
{
printf("The given layer number is too large (%d > %d)\n",
LayerNumber, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
LayerNumber = ME_CAST_TO_IPLIMAGE(cvImg)->nChannels;
}
if (LayerNumber <= 0)
{
printf("The given layer number is too small (%d <= 0)\n", LayerNumber);
LayerNumber = 1;
}
cvSetImageCOI(ME_CAST_TO_IPLIMAGE(cvImg), LayerNumber);
cvCopy(ME_CAST_TO_IPLIMAGE(cvImg), (IplImage*)new_layer.GetIplImage(), NULL);
cvSetImageCOI(ME_CAST_TO_IPLIMAGE(cvImg), 0);
}
void MEImage::SetLayer(MEImage& layer, int layer_number)
{
int LayerNumber = layer_number;
if (layer.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
layer.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height)
{
printf("The dimensions of the layer and "
"destination image is different (%dx%d <> %dx%d)\n",
layer.GetWidth(), layer.GetHeight(), ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height);
return;
}
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels < LayerNumber)
{
printf("The given layer number is too large (%d > %d)\n",
LayerNumber, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
LayerNumber = ME_CAST_TO_IPLIMAGE(cvImg)->nChannels;
}
if (LayerNumber <= 0)
{
printf("The given layer number is too small (%d <= 0)\n", LayerNumber);
LayerNumber = 1;
}
if (layer.GetLayers() != 1)
{
printf("The layer image has not one color channel (1 != %d)\n",
layer.GetLayers());
return;
}
cvSetImageCOI(ME_CAST_TO_IPLIMAGE(cvImg), LayerNumber);
cvCopy((IplImage*)layer.GetIplImage(), ME_CAST_TO_IPLIMAGE(cvImg), NULL);
cvSetImageCOI(ME_CAST_TO_IPLIMAGE(cvImg), 0);
}
void MEImage::CopyImageData(unsigned char* data)
{
memcpy(ME_CAST_TO_IPLIMAGE(cvImg)->imageData, data, ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
}
void* MEImage::GetIplImage() const
{
return (void*)ME_CAST_TO_IPLIMAGE(cvImg);
}
void MEImage::SetIplImage(void* image)
{
if (ME_CAST_TO_IPLIMAGE(cvImg))
{
ME_RELEASE_IPLIMAGE(cvImg);
}
cvImg = cvCloneImage((IplImage*)image);
// Correct the origin of the image
if (ME_CAST_TO_IPLIMAGE(cvImg)->origin == 1)
{
MirrorVertical();
ME_CAST_TO_IPLIMAGE(cvImg)->origin = 0;
}
}
bool MEImage::operator==(const MEImage& image)
{
return Equal(image);
}
bool MEImage::operator!=(const MEImage& image)
{
return !operator==(image);
}
MEImage& MEImage::operator=(const MEImage& other_image)
{
if (&other_image == this)
return *this;
_Copy(other_image);
return *this;
}
int MEImage::GetWidth() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? ME_CAST_TO_IPLIMAGE(cvImg)->width : 0;
}
int MEImage::GetRowWidth() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? ME_CAST_TO_IPLIMAGE(cvImg)->widthStep : 0;
}
int MEImage::GetHeight() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? ME_CAST_TO_IPLIMAGE(cvImg)->height : 0;
}
int MEImage::GetLayers() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? ME_CAST_TO_IPLIMAGE(cvImg)->nChannels : 0;
}
int MEImage::GetPixelDataNumber() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? GetWidth()*GetHeight()*GetLayers() : 0;
}
unsigned char* MEImage::GetImageData() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData : NULL;
}
void MEImage::SetData(unsigned char* image_data, int width, int height, int channels)
{
_Init(width, height, channels);
for (int y = height - 1; y >= 0; --y)
{
int Start = GetRowWidth()*y;
int Start2 = width*channels*y;
memcpy(&ME_CAST_TO_IPLIMAGE(cvImg)->imageData[Start], &image_data[Start2], width*channels);
}
}
float MEImage::GetRatio() const
{
return ME_CAST_TO_IPLIMAGE(cvImg) ? (float)ME_CAST_TO_IPLIMAGE(cvImg)->height / (float)ME_CAST_TO_IPLIMAGE(cvImg)->width : 0.0;
}
void MEImage::Realloc(int width, int height)
{
Realloc(width, height, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
}
void MEImage::Realloc(int width, int height, int layers)
{
_Init(width, height, layers);
}
void MEImage::Resize(int new_width, int new_height)
{
if (new_height < 1)
{
printf("Invalid new height: %d < 1\n", new_height);
return;
}
if (new_width < 1)
{
printf("Invalid new width: %d < 1\n", new_width);
return;
}
IplImage* TempImg = cvCreateImage(cvSize(new_width, new_height), 8, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvResize(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_INTER_NN);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::ResizeScaleX(int new_width)
{
if (new_width < 1)
{
printf("Invalid new width: %d < 1\n", new_width);
return;
}
Resize(new_width, (int)((float)new_width*GetRatio()));
}
void MEImage::ResizeScaleY(int new_height)
{
if (new_height < 1)
{
printf("Invalid new height: %d < 1\n", new_height);
return;
}
Resize((int)((float)new_height * 1 / GetRatio()), new_height);
}
void MEImage::MirrorHorizontal()
{
cvFlip(ME_CAST_TO_IPLIMAGE(cvImg), NULL, 1);
}
void MEImage::MirrorVertical()
{
cvFlip(ME_CAST_TO_IPLIMAGE(cvImg), NULL, 0);
}
void MEImage::Crop(int x1, int y1, int x2, int y2)
{
int NewX1 = x1;
int NewY1 = y1;
int NewX2 = x2;
int NewY2 = y2;
NewX1 = (NewX1 < 0) ? 0 : NewX1;
NewX1 = (NewX1 > ME_CAST_TO_IPLIMAGE(cvImg)->width) ? ME_CAST_TO_IPLIMAGE(cvImg)->width : NewX1;
NewY1 = (NewY1 < 0) ? 0 : NewY1;
NewY1 = (NewY1 > ME_CAST_TO_IPLIMAGE(cvImg)->height) ? ME_CAST_TO_IPLIMAGE(cvImg)->height : NewY1;
NewX2 = (NewX2 < 0) ? 0 : NewX2;
NewX2 = (NewX2 > ME_CAST_TO_IPLIMAGE(cvImg)->width) ? ME_CAST_TO_IPLIMAGE(cvImg)->width : NewX2;
NewY2 = (NewY2 < 0) ? 0 : NewY2;
NewY2 = (NewY2 > ME_CAST_TO_IPLIMAGE(cvImg)->height) ? ME_CAST_TO_IPLIMAGE(cvImg)->height : NewY2;
if ((NewX2 - NewX1) <= 0)
{
printf("Invalid new width: %d <= 0\n", NewX2 - NewX1);
return;
}
if ((NewY2 - NewY1) <= 0)
{
printf("Invalid new height: %d <= 0\n", NewY2 - NewY1);
return;
}
IplImage* TempImg = cvCreateImage(cvSize(NewX2 - NewX1, NewY2 - NewY1), 8, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvSetImageROI(ME_CAST_TO_IPLIMAGE(cvImg), cvRect(NewX1, NewY1, NewX2 - NewX1, NewY2 - NewY1));
cvCopy(ME_CAST_TO_IPLIMAGE(cvImg), TempImg);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::CopyImageInside(int x, int y, MEImage& source_image)
{
int NewX = x;
int NewY = y;
int PasteLengthX = source_image.GetWidth();
int PasteLengthY = source_image.GetHeight();
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != source_image.GetLayers())
{
if (source_image.GetLayers() == 1 && ME_CAST_TO_IPLIMAGE(cvImg)->nChannels == 3)
{
source_image.ConvertGrayscaleToRGB();
}
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels == 1 && source_image.GetLayers() == 3)
{
source_image.ConvertToGrayscale(g_OpenCV);
}
}
if (NewX < 0)
NewX = 0;
if (NewX > ME_CAST_TO_IPLIMAGE(cvImg)->width)
NewX = ME_CAST_TO_IPLIMAGE(cvImg)->width;
if (NewY < 0)
NewY = 0;
if (NewY > ME_CAST_TO_IPLIMAGE(cvImg)->height)
NewY = ME_CAST_TO_IPLIMAGE(cvImg)->height;
if (NewX + PasteLengthX > ME_CAST_TO_IPLIMAGE(cvImg)->width)
PasteLengthX = ME_CAST_TO_IPLIMAGE(cvImg)->width - NewX;
if (NewY + PasteLengthY > ME_CAST_TO_IPLIMAGE(cvImg)->height)
PasteLengthY = ME_CAST_TO_IPLIMAGE(cvImg)->height - NewY;
if (PasteLengthX != source_image.GetWidth() ||
PasteLengthY != source_image.GetHeight())
{
source_image.Resize(PasteLengthX, PasteLengthY);
}
cvSetImageROI(ME_CAST_TO_IPLIMAGE(cvImg), cvRect(NewX, NewY, PasteLengthX, PasteLengthY));
cvCopy((IplImage*)source_image.GetIplImage(), ME_CAST_TO_IPLIMAGE(cvImg));
cvResetImageROI(ME_CAST_TO_IPLIMAGE(cvImg));
}
void MEImage::Erode(int iterations)
{
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height),
8, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvErode(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, NULL, iterations);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::Dilate(int iterations)
{
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height),
8, ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvDilate(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, NULL, iterations);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::Smooth()
{
SmoothAdvanced(s_Median, 3);
}
void MEImage::SmoothAdvanced(SmoothType filtermode, int filtersize)
{
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
switch (filtermode)
{
case s_Blur:
cvSmooth(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_BLUR, filtersize, filtersize, 0);
break;
case s_Median:
cvSmooth(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_MEDIAN, filtersize, 0, 0);
break;
case s_Gaussian:
cvSmooth(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_GAUSSIAN, filtersize, filtersize, 0);
break;
default:
cvSmooth(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_MEDIAN, filtersize, 0, 0);
break;
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::Canny()
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels > 1)
{
ConvertToGrayscale(g_OpenCV);
}
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCanny(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, 800, 1100, 5);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::Laplace()
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != 1)
{
ConvertToGrayscale(g_OpenCV);
}
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height),
IPL_DEPTH_16S, 1);
cvLaplace(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, 3);
cvConvertScale(TempImg, ME_CAST_TO_IPLIMAGE(cvImg), 1, 0);
ME_RELEASE_IPLIMAGE(cvImg);
}
void MEImage::Quantize(int levels)
{
if (levels <= 0)
{
printf("Level number is too small (%d <= 0)\n", levels);
return;
}
if (levels > 256)
{
printf("Level number is too large (%d > 256)\n", levels);
return;
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; i >= 0; --i)
{
ImageData[i] = ImageData[i] / (256 / levels)*(256 / levels);
}
}
void MEImage::Threshold(int threshold_limit)
{
if (threshold_limit < 0)
{
printf("Threshold number is too small (%d <= 0)\n", threshold_limit);
return;
}
if (threshold_limit > 255)
{
printf("Threshold number is too large (%d > 255)\n", threshold_limit);
return;
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; i >= 0; --i)
{
if (ImageData[i] < threshold_limit)
{
ImageData[i] = 0;
}
}
}
void MEImage::AdaptiveThreshold()
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != 1)
{
ConvertToGrayscale(g_OpenCV);
}
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvAdaptiveThreshold(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, 25,
CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, 7, -7);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::ThresholdByMask(MEImage& mask_image)
{
if (mask_image.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
mask_image.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height)
{
printf("Image properties are different\n");
return;
}
if (mask_image.GetLayers() != 3 && ME_CAST_TO_IPLIMAGE(cvImg)->nChannels == 3)
{
mask_image.ConvertGrayscaleToRGB();
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* MaskImageData = mask_image.GetImageData();
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; i >= 0; --i)
{
if (MaskImageData[i] == 0)
{
ImageData[i] = 0;
}
}
}
void MEImage::ColorSpace(ColorSpaceConvertType mode)
{
IplImage* TempImg = NULL;
unsigned char* ImageData = NULL;
int WidthStep = 0;
int RowStart = 0;
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels == 1)
{
printf("No sense to convert: source image is greyscale\n");
ConvertGrayscaleToRGB();
}
switch (mode)
{
case csc_RGBtoXYZCIED65:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2XYZ);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_XYZCIED65toRGB:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_XYZ2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_RGBtoHSV:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2HSV);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_HSVtoRGB:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width,
ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_HSV2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_RGBtoHLS:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2HLS);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_HLStoRGB:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_HLS2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_RGBtoCIELab:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2Lab);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_CIELabtoRGB:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_Lab2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_RGBtoCIELuv:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2Luv);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_CIELuvtoRGB:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_Luv2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case csc_RGBtoYUV:
ComputeColorSpace(csc_RGBtoYUV);
break;
case csc_RGBtoYIQ:
ComputeColorSpace(csc_RGBtoYIQ);
break;
case csc_RGBtorgI:
ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = (ME_CAST_TO_IPLIMAGE(cvImg)->width - 1) * 3; x >= 0; x -= 3)
{
int r = 0;
int g = 0;
int I = 0;
I = (int)ImageData[RowStart + x] + (int)ImageData[RowStart + x + 1] + (int)ImageData[RowStart + x + 2];
r = (int)((float)ImageData[RowStart + x] / I * 255);
g = (int)((float)ImageData[RowStart + x + 1] / I * 255);
ImageData[RowStart + x] = (unsigned char)r;
ImageData[RowStart + x + 1] = (unsigned char)g;
ImageData[RowStart + x + 2] = (unsigned char)(I / 3);
}
RowStart += WidthStep;
}
break;
default:
break;
}
}
void MEImage::ConvertToGrayscale(GrayscaleType grayscale_mode)
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels == 1)
{
printf("Image is already grayscale\n");
return;
}
IplImage* TempImg = NULL;
unsigned char* ImgData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* ImageData = NULL;
switch (grayscale_mode)
{
case g_Average:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8, 1);
ImageData = (unsigned char*)TempImg->imageData;
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*ME_CAST_TO_IPLIMAGE(cvImg)->height - 3; i >= 0; i -= 3)
{
ImageData[i / 3] = (ImgData[i] + ImgData[i + 1] + ImgData[i + 2]) / 3;
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
case g_OpenCV:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8, 1);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_RGB2GRAY);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
default:
break;
}
}
void MEImage::ConvertGrayscaleToRGB()
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != 1)
{
return;
}
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8, 3);
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), TempImg, CV_GRAY2RGB);
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::ConvertBGRToRGB()
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != 3)
{
return;
}
cvCvtColor(ME_CAST_TO_IPLIMAGE(cvImg), ME_CAST_TO_IPLIMAGE(cvImg), CV_RGB2BGR);
}
void MEImage::LBP(LBPType mode)
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels > 1)
{
ConvertToGrayscale(g_OpenCV);
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8, 1);
unsigned char* TempImgData = (unsigned char*)TempImg->imageData;
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int WidthStep_2 = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep * 2;
cvSetZero(TempImg);
switch (mode)
{
case lbp_Normal:
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*(ME_CAST_TO_IPLIMAGE(cvImg)->height - 2) - 1; i >= ME_CAST_TO_IPLIMAGE(cvImg)->widthStep + 1; --i)
{
TempImgData[i] =
(ImageData[i] <= ImageData[i - ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1]) +
((ImageData[i] <= ImageData[i - ME_CAST_TO_IPLIMAGE(cvImg)->widthStep]) * 2) +
((ImageData[i] <= ImageData[i - ME_CAST_TO_IPLIMAGE(cvImg)->widthStep + 1]) * 4) +
((ImageData[i] <= ImageData[i - 1]) * 8) +
((ImageData[i] <= ImageData[i + 1]) * 16) +
((ImageData[i] <= ImageData[i + ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1]) * 32) +
((ImageData[i] <= ImageData[i + ME_CAST_TO_IPLIMAGE(cvImg)->widthStep]) * 64) +
((ImageData[i] <= ImageData[i + ME_CAST_TO_IPLIMAGE(cvImg)->widthStep + 1]) * 128);
}
break;
case lbp_Special:
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*(ME_CAST_TO_IPLIMAGE(cvImg)->height - 3) - 2; i >= ME_CAST_TO_IPLIMAGE(cvImg)->widthStep * 2 + 2; --i)
{
int CenterPixel = (ImageData[i + 1] + ImageData[i - 1] +
ImageData[i - WidthStep] + ImageData[i + WidthStep]) / 4;
TempImgData[i] = ((CenterPixel <= (ImageData[i - (WidthStep_2)-2] +
ImageData[i - (WidthStep_2)-1] +
ImageData[i - WidthStep - 2] +
ImageData[i - WidthStep - 1]) / 4)) +
((CenterPixel <= (ImageData[i - WidthStep] +
ImageData[i - (WidthStep_2)]) / 2) * 2) +
((CenterPixel <= ((ImageData[i - (WidthStep_2)+2] +
ImageData[i - (WidthStep_2)+1] +
ImageData[i - WidthStep + 2] +
ImageData[i - WidthStep + 1]) / 4)) * 4) +
((CenterPixel <= (ImageData[i - 1] +
ImageData[i - 2]) / 2) * 8) +
((CenterPixel <= (ImageData[i + 1] +
ImageData[i + 2]) / 2) * 16) +
((CenterPixel <= ((ImageData[i + (WidthStep_2)-2] +
ImageData[i + (WidthStep_2)-1] +
ImageData[i + WidthStep - 2] +
ImageData[i + WidthStep - 1]) / 4)) * 32) +
((CenterPixel <= (ImageData[i + WidthStep] +
ImageData[i - WidthStep_2]) / 2) * 64) +
((CenterPixel <= ((ImageData[i + (WidthStep_2)+2] +
ImageData[i + (WidthStep_2)+1] +
ImageData[i + WidthStep + 2] +
ImageData[i + WidthStep + 1]) / 4)) * 128);
}
break;
default:
break;
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
void MEImage::Binarize(int threshold)
{
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1; i >= 0; --i)
{
if (ImageData[i] >= threshold)
{
ImageData[i] = 255;
}
else {
ImageData[i] = 0;
}
}
}
void MEImage::Subtract(MEImage& source, SubtractModeType mode)
{
if (source.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
source.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height ||
source.GetLayers() != ME_CAST_TO_IPLIMAGE(cvImg)->nChannels)
{
printf("Image properties are different.\n");
return;
}
unsigned char* ImageData = NULL;
unsigned char* DstData = NULL;
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
switch (mode)
{
case sub_Normal:
ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
DstData = source.GetImageData();
RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
ImageData[RowStart + x] =
ImageData[RowStart + x] - DstData[RowStart + x] < 0 ? 0 :
ImageData[RowStart + x] - DstData[RowStart + x];
}
RowStart += WidthStep;
}
break;
case sub_Absolut:
ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
DstData = source.GetImageData();
RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
ImageData[RowStart + x] = ImageData[RowStart + x] -
DstData[RowStart + x] < 0 ? -ImageData[RowStart + x] +
DstData[RowStart + x] : ImageData[RowStart + x] - DstData[RowStart + x];
}
RowStart += WidthStep;
}
break;
default:
break;
}
}
void MEImage::Multiple(MEImage& source, MultiplicationType mode)
{
if (source.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
source.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height ||
source.GetLayers() != ME_CAST_TO_IPLIMAGE(cvImg)->nChannels)
{
printf("Image properties are different.\n");
return;
}
float Result = 0.0;
IplImage* TempImg = NULL;
unsigned char* ImageData = NULL;
unsigned char* ImageData2 = NULL;
unsigned char* ImageData3 = NULL;
unsigned char* DstData = NULL;
switch (mode)
{
case m_Normal:
Result = 0;
ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
DstData = source.GetImageData();
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1; i >= 0; --i)
{
if ((ImageData[i] >= 128) && (DstData[i] >= 128))
{
Result = (float)ImageData[i] / 128 * (float)DstData[i] / 128;
if (Result >= 1)
{
ImageData[i] = 255;
}
else {
ImageData[i] = 0;
}
}
else {
ImageData[i] = 0;
}
}
break;
case m_Neighbourhood:
TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
ImageData2 = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
DstData = source.GetImageData();
ImageData3 = (unsigned char*)TempImg->imageData;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width - 1; x >= 0; --x)
for (int l = ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; l >= 0; --l)
{
if (((DstData[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels +
x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] == 255) ||
(ImageData2[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels +
x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] == 255)) &&
(NeighbourhoodCounter(x - 2, y - 2, n_5x5) > 3) &&
(source.NeighbourhoodCounter(x - 2, y - 2, n_5x5) > 3))
{
ImageData3[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels +
x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] = 255;
}
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
break;
default:
break;
}
}
void MEImage::Addition(MEImage& source, AdditionType mode)
{
if (source.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
source.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height ||
source.GetLayers() != ME_CAST_TO_IPLIMAGE(cvImg)->nChannels)
{
printf("Image properties are different.\n");
return;
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* DstData = source.GetImageData();
switch (mode)
{
case a_Average:
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1; i >= 0; --i)
{
ImageData[i] = (ImageData[i] + DstData[i]) / 2;
}
break;
case a_Union:
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep - 1; i >= 0; --i)
{
if (DstData[i] > ImageData[i])
{
ImageData[i] = DstData[i];
}
}
break;
default:
break;
}
}
void MEImage::EliminateSinglePixels()
{
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* DstData = (unsigned char*)TempImg->imageData;
int sum = 0;
int xy = 0;
int ywidth = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width - 1; x >= 0; --x)
{
xy = y*ywidth + x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels;
for (int l = ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; l >= 0; --l)
{
if ((ImageData[xy + l] > 0) && (x > 0) && (y > 0) && (x < ME_CAST_TO_IPLIMAGE(cvImg)->width - 1) && (y < ME_CAST_TO_IPLIMAGE(cvImg)->height - 1))
{
sum = (ImageData[xy - ywidth - ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0) +
(ImageData[xy - ywidth + l] > 0) +
(ImageData[xy - ywidth + ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0) +
(ImageData[xy - ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0) +
(ImageData[xy + ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0) +
(ImageData[xy + ywidth - ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0) +
(ImageData[xy + ywidth + l] > 0) +
(ImageData[xy + ywidth + ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l] > 0);
if (sum > 3)
{
DstData[xy + l] = 255;
}
else {
DstData[xy + l] = 0;
}
}
else {
DstData[xy + l] = 0;
}
}
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
float MEImage::DifferenceAreas(MEImage& reference, int difference) const
{
if (reference.GetWidth() != GetWidth() ||
reference.GetHeight() != GetHeight() ||
reference.GetLayers() != GetLayers())
{
printf("Image dimensions or channels are different\n");
return -1.0;
}
float PixelDiff = 0.0;
int Pixels = 0;
unsigned char* OrigImgData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* RefImgData = reference.GetImageData();
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
if (abs(OrigImgData[RowStart + x] - RefImgData[RowStart + x]) > difference)
Pixels++;
}
RowStart += WidthStep;
}
PixelDiff = (float)Pixels / (ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep) * 100;
return PixelDiff;
}
int MEImage::AverageDifference(MEImage& reference) const
{
if (reference.GetWidth() != GetWidth() ||
reference.GetHeight() != GetHeight() ||
reference.GetLayers() != GetLayers())
{
printf("Image dimensions or channels are different\n");
return -1;
}
int Difference = 0;
unsigned char* OrigImgData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* RefImgData = reference.GetImageData();
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
Difference += abs(OrigImgData[RowStart + x] - RefImgData[RowStart + x]);
}
RowStart += WidthStep;
}
Difference = Difference / (ME_CAST_TO_IPLIMAGE(cvImg)->height*ME_CAST_TO_IPLIMAGE(cvImg)->widthStep);
return Difference;
}
void MEImage::Minimum(MEImage& image)
{
if (image.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
image.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height ||
image.GetLayers() != ME_CAST_TO_IPLIMAGE(cvImg)->nChannels)
{
printf("Image properties are different\n");
return;
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* SecData = image.GetImageData();
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
ImageData[RowStart + x] = ImageData[RowStart + x] > SecData[RowStart + x] ?
SecData[RowStart + x] : ImageData[RowStart + x];
}
RowStart += WidthStep;
}
}
float MEImage::AverageBrightnessLevel() const
{
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
int BrightnessLevel = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
BrightnessLevel += (int)ImageData[RowStart + x];
}
RowStart += WidthStep;
}
return BrightnessLevel / (GetWidth()*GetHeight()*GetLayers());
}
bool MEImage::Equal(const MEImage& reference) const
{
return Equal(reference, 1);
}
bool MEImage::Equal(const MEImage& reference, int maxabsdiff) const
{
bool Ret = true;
if (reference.GetWidth() != ME_CAST_TO_IPLIMAGE(cvImg)->width ||
reference.GetHeight() != ME_CAST_TO_IPLIMAGE(cvImg)->height ||
reference.GetLayers() != ME_CAST_TO_IPLIMAGE(cvImg)->nChannels)
{
printf("Image properties are different\n");
return false;
}
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* RefData = reference.GetImageData();
int WidthStep = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep;
int RowStart = 0;
for (int y = ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; y >= 0; --y)
{
for (int x = ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels - 1; x >= 0; --x)
{
if (abs(ImageData[RowStart + x] - RefData[RowStart + x]) >= maxabsdiff)
{
Ret = false;
return Ret;
}
}
RowStart += WidthStep;
}
return Ret;
}
unsigned char MEImage::GrayscalePixel(int x, int y) const
{
int NewX = x;
int NewY = y;
NewX = NewX < 0 ? 0 : NewX;
NewX = NewX > ME_CAST_TO_IPLIMAGE(cvImg)->width - 1 ? ME_CAST_TO_IPLIMAGE(cvImg)->width - 1 : NewX;
NewY = NewY < 0 ? 0 : NewY;
NewY = NewY > ME_CAST_TO_IPLIMAGE(cvImg)->height - 1 ? ME_CAST_TO_IPLIMAGE(cvImg)->height - 1 : NewY;
float Sum = 0;
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
for (int l = 0; l < ME_CAST_TO_IPLIMAGE(cvImg)->nChannels; l++)
{
Sum = Sum + (int)ImageData[NewY*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + NewX*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + l];
}
Sum = Sum / ME_CAST_TO_IPLIMAGE(cvImg)->nChannels;
return (unsigned char)(Sum);
}
int MEImage::NeighbourhoodCounter(int startx, int starty,
NeighbourhoodType neighbourhood) const
{
int IterX = 0;
int IterY = 0;
int Counter = 0;
// Determine the iteration numbers
switch (neighbourhood)
{
case n_2x2:
IterX = 2;
IterY = 2;
break;
case n_3x3:
IterX = 3;
IterY = 3;
break;
case n_3x2:
IterX = 2;
IterY = 3;
break;
case n_5x5:
IterX = 5;
IterY = 5;
break;
case n_7x7:
IterX = 7;
IterY = 7;
break;
default:
IterX = 3;
IterY = 3;
break;
}
int NewStartX = startx;
int NewStartY = starty;
NewStartX = startx < 0 ? 0 : startx;
NewStartX = startx >= ME_CAST_TO_IPLIMAGE(cvImg)->width - IterX ? ME_CAST_TO_IPLIMAGE(cvImg)->width - IterX - 1 : startx;
NewStartY = starty < 0 ? 0 : starty;
NewStartY = starty >= ME_CAST_TO_IPLIMAGE(cvImg)->height - IterY ? ME_CAST_TO_IPLIMAGE(cvImg)->height - IterY - 1 : starty;
int Value = 0;
unsigned char* ImageData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
for (int x = NewStartX; x < NewStartX + IterX; x++)
for (int y = NewStartY; y < NewStartY + IterY; y++)
{
Value = ((int)ImageData[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels] +
(int)ImageData[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + 1] +
(int)ImageData[y*ME_CAST_TO_IPLIMAGE(cvImg)->width*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + x*ME_CAST_TO_IPLIMAGE(cvImg)->nChannels + 2]) / 3;
if (Value == 255)
{
Counter++;
}
}
return Counter;
}
void MEImage::GradientVector(bool smooth, int x, int y, int mask_size, int& result_x, int& result_y)
{
int Results[8];
int DiagonalMaskSize = (int)((float)mask_size / sqrtf(2));
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels > 1)
{
ConvertToGrayscale(g_OpenCV);
}
if (smooth)
{
SmoothAdvanced(s_Gaussian, mask_size * 3 - (mask_size * 3 - 1) % 2);
}
Results[0] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x, y - mask_size);
Results[1] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x + DiagonalMaskSize, y - DiagonalMaskSize);
Results[2] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x + mask_size, y);
Results[3] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x + DiagonalMaskSize, y + DiagonalMaskSize);
Results[4] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x, y + mask_size);
Results[5] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x - DiagonalMaskSize, y + DiagonalMaskSize);
Results[6] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x - mask_size, y);
Results[7] = (int)GrayscalePixel(x, y) - (int)GrayscalePixel(x + DiagonalMaskSize, y - DiagonalMaskSize);
result_x = (DiagonalMaskSize*Results[1] + mask_size*Results[2] +
DiagonalMaskSize*Results[3] - DiagonalMaskSize*Results[5] -
mask_size*Results[6] + DiagonalMaskSize*Results[7]) / 256;
result_y = (-mask_size*Results[0] - DiagonalMaskSize*Results[1] +
DiagonalMaskSize*Results[3] + mask_size*Results[4] +
DiagonalMaskSize*Results[5] - DiagonalMaskSize*Results[7]) / 256;
}
void MEImage::GradientVisualize(int vector_x, int vector_y)
{
if (vector_x <= 0)
{
printf("vectorx: wrong parameter (%d <= 0)\n", vector_x);
return;
}
if (vector_y <= 0)
{
printf("vectory: wrong parameter (%d <= 0)\n", vector_y);
return;
}
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels > 1)
{
ConvertToGrayscale(g_OpenCV);
}
int masksize = (ME_CAST_TO_IPLIMAGE(cvImg)->width < ME_CAST_TO_IPLIMAGE(cvImg)->height) ?
ME_CAST_TO_IPLIMAGE(cvImg)->width / (vector_x + 1) :
ME_CAST_TO_IPLIMAGE(cvImg)->height / (vector_y + 1);
SmoothAdvanced(s_Gaussian, masksize * 2 - 1);
for (int i = 1; i < vector_x; i++)
for (int i1 = 1; i1 < vector_y; i1++)
{
int Resultx = 0, Resulty = 0;
int x = (int)(((float)ME_CAST_TO_IPLIMAGE(cvImg)->width*i / (vector_x)));
int y = (int)(((float)ME_CAST_TO_IPLIMAGE(cvImg)->height*i1 / (vector_y)));
GradientVector(false, x, y, (int)(0.707*masksize), Resultx, Resulty);
CvPoint Point1;
CvPoint Point2;
Point1.x = x - Resultx / 2;
Point1.y = y - Resulty / 2;
Point2.x = x + Resultx / 2;
Point2.y = y + Resulty / 2;
cvLine(ME_CAST_TO_IPLIMAGE(cvImg), Point1, Point2, CV_RGB(255, 255, 255), 1, 8);
}
}
bool MEImage::_Copy(const MEImage& other_image)
{
if (&other_image == this)
return true;
if (ME_CAST_TO_IPLIMAGE(cvImg))
{
ME_RELEASE_IPLIMAGE(cvImg);
}
cvImg = cvCloneImage((IplImage*)other_image.GetIplImage());
return true;
}
void MEImage::_Init(int width, int height, int layers)
{
if (width < 1)
{
printf("Given width for the new image is too small (%d <= 0)\n", width);
return;
}
if (height < 1)
{
printf("Given height for the new image is (%d <= 0)\n", height);
return;
}
if ((layers != 1) && (layers != 3))
{
printf("Only one or three (%d != 1 or 3) layer allowed\n", layers);
return;
}
if (ME_CAST_TO_IPLIMAGE(cvImg))
{
ME_RELEASE_IPLIMAGE(cvImg);
}
cvImg = cvCreateImage(cvSize(width, height), 8, layers);
}
void MEImage::ComputeColorSpace(ColorSpaceConvertType mode)
{
if (ME_CAST_TO_IPLIMAGE(cvImg)->nChannels != 3)
{
printf("Image has to have three color channels (%d != 3)\n", ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
return;
}
IplImage* TempImg = cvCreateImage(cvSize(ME_CAST_TO_IPLIMAGE(cvImg)->width, ME_CAST_TO_IPLIMAGE(cvImg)->height), 8,
ME_CAST_TO_IPLIMAGE(cvImg)->nChannels);
for (int i = 0; i < 3; i++)
for (int i1 = 0; i1 < 3; i1++)
{
if (mode == csc_RGBtoYUV)
TransformMatrix[i][i1] = RGBtoYUVMatrix[i][i1];
if (mode == csc_RGBtoYIQ)
TransformMatrix[i][i1] = RGBtoYIQMatrix[i][i1];
}
float x = 0.0;
float y = 0.0;
float z = 0.0;
float xmin = 0.0;
float xmax = 0.0;
float ymin = 0.0;
float ymax = 0.0;
float zmin = 0.0;
float zmax = 0.0;
if (mode == csc_RGBtoYUV)
{
xmin = 0.0;
xmax = 255.0;
ymin = -111.18;
ymax = 111.18;
zmin = -156.825;
zmax = 156.825;
}
if (mode == csc_RGBtoYIQ)
{
xmin = 0.0;
xmax = 255.0;
ymin = -151.98;
ymax = 151.98;
zmin = -133.365;
zmax = 133.365;
}
unsigned char* SrcData = (unsigned char*)ME_CAST_TO_IPLIMAGE(cvImg)->imageData;
unsigned char* DstData = (unsigned char*)TempImg->imageData;
for (int i = ME_CAST_TO_IPLIMAGE(cvImg)->widthStep*ME_CAST_TO_IPLIMAGE(cvImg)->height - 1; i >= 0; i -= 3)
{
x = (float)SrcData[i] * TransformMatrix[0][0] +
(float)SrcData[i + 1] * TransformMatrix[0][1] +
(float)SrcData[i + 2] * TransformMatrix[0][2];
y = (float)SrcData[i] * TransformMatrix[1][0] +
(float)SrcData[i + 1] * TransformMatrix[1][1] +
(float)SrcData[i + 2] * TransformMatrix[1][2];
z = (float)SrcData[i] * TransformMatrix[2][0] +
(float)SrcData[i + 1] * TransformMatrix[2][1] +
(float)SrcData[i + 2] * TransformMatrix[2][2];
x = xmax - xmin != 0.0 ? 255.0 : (x - xmin) / (xmax - xmin)*255.0;
y = ymax - ymin != 0.0 ? 255.0 : (y - xmin) / (ymax - ymin)*255.0;
z = zmax - zmin != 0.0 ? 255.0 : (z - xmin) / (zmax - zmin)*255.0;
DstData[i] = (unsigned char)MEBound(0, (int)x, 255);
DstData[i + 1] = (unsigned char)MEBound(0, (int)y, 255);
DstData[i + 2] = (unsigned char)MEBound(0, (int)z, 255);
}
ME_RELEASE_IPLIMAGE(cvImg);
cvImg = TempImg;
}
}
}
}
#endif
| mit |
mishless/smart-mirror | SmartMirror/neural_network/perceptron_layer.cpp | 1 | 54985 | /****************************************************************************************************************/
/* */
/* OpenNN: Open Neural Networks Library */
/* www.opennn.cimne.com */
/* */
/* P E R C E P T R O N L A Y E R C L A S S */
/* */
/* Roberto Lopez */
/* International Center for Numerical Methods in Engineering (CIMNE) */
/* Technical University of Catalonia (UPC) */
/* Barcelona, Spain */
/* E-mail: rlopez@cimne.upc.edu */
/* */
/****************************************************************************************************************/
// System includes
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
// OpenNN includes
#include "perceptron_layer.h"
namespace OpenNN
{
// DEFAULT CONSTRUCTOR
/// Default constructor.
/// It creates a empty layer object, with no perceptrons.
/// This constructor also initializes the rest of class members to their default values.
PerceptronLayer::PerceptronLayer(void)
{
set();
}
// ARCHITECTURE CONSTRUCTOR
/// Layer architecture constructor.
/// It creates a layer object with given numbers of inputs and perceptrons.
/// The parameters are initialized at random.
/// This constructor also initializes the rest of class members to their default values.
/// @param new_inputs_number Number of inputs in the layer.
/// @param new_perceptrons_number Number of perceptrons in the layer.
PerceptronLayer::PerceptronLayer(const unsigned int& new_inputs_number, const unsigned int& new_perceptrons_number)
{
set(new_inputs_number, new_perceptrons_number);
}
// COPY CONSTRUCTOR
/// Copy constructor.
/// It creates a copy of an existing perceptron layer object.
/// @param other_perceptron_layer Perceptron layer object to be copied.
PerceptronLayer::PerceptronLayer(const PerceptronLayer& other_perceptron_layer)
{
set(other_perceptron_layer);
}
// DESTRUCTOR
/// Destructor.
/// This destructor does not delete any pointer.
PerceptronLayer::~PerceptronLayer(void)
{
}
// ASSIGNMENT OPERATOR
/// Assignment operator.
/// It assigns to this object the members of an existing perceptron layer object.
/// @param other_perceptron_layer Perceptron layer object to be assigned.
PerceptronLayer& PerceptronLayer::operator = (const PerceptronLayer& other_perceptron_layer)
{
if(this != &other_perceptron_layer)
{
perceptrons = other_perceptron_layer.perceptrons;
display = other_perceptron_layer.display;
}
return(*this);
}
// EQUAL TO OPERATOR
// bool operator == (const PerceptronLayer&) const method
/// Equal to operator.
/// It compares this object with another object of the same class.
/// It returns true if the members of the two objects have the same values, and false otherwise.
/// @ param other_perceptron_layer Perceptron layer to be compared with.
bool PerceptronLayer::operator == (const PerceptronLayer& other_perceptron_layer) const
{
if(perceptrons == other_perceptron_layer.perceptrons
&& display == other_perceptron_layer.display)
{
return(true);
}
else
{
return(false);
}
}
// METHODS
// bool is_empty(void) const method
/// This method returns true if the size of the layer is zero, and false otherwise.
bool PerceptronLayer::is_empty(void) const
{
if(perceptrons.empty())
{
return(true);
}
else
{
return(false);
}
}
// const Vector<Perceptron>& get_perceptrons(void) const method
/// This method returns a constant reference to the vector of perceptrons defining the layer.
const Vector<Perceptron>& PerceptronLayer::get_perceptrons(void) const
{
return(perceptrons);
}
// unsigned int count_inputs_number(void) const
/// This method returns the number of inputs to the layer.
unsigned int PerceptronLayer::count_inputs_number(void) const
{
if(is_empty())
{
return(0);
}
else
{
return(perceptrons[0].count_inputs_number());
}
}
// const unsigned int& count_perceptrons_number(void) const
/// This method returns a reference to the size of the perceptrons vector.
unsigned int PerceptronLayer::count_perceptrons_number(void) const
{
const unsigned int& perceptrons_number = perceptrons.size();
return(perceptrons_number);
}
// const Perceptron& get_perceptron(const unsigned int&) const method
/// This method returns a reference to a given element in the perceptrons vector.
/// @param index Index of perceptron element.
const Perceptron& PerceptronLayer::get_perceptron(const unsigned int& index) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int perceptrons_number = count_perceptrons_number();
if(index >= perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "const Perceptron& get_perceptron(const unsigned int&) const method.\n"
<< "Index of perceptron must be less than layer size.\n";
throw std::logic_error(buffer.str());
}
#endif
return(perceptrons[index]);
}
// unsigned int count_parameters_number(void) const method
/// This method returns the number of parameters (biases and synaptic weights) of the layer.
unsigned int PerceptronLayer::count_parameters_number(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
unsigned int parameters_number = 0;
for(unsigned int i = 0; i < perceptrons_number; i++)
{
parameters_number += perceptrons[i].count_parameters_number();
}
return(parameters_number);
}
// Vector<unsigned int> count_cumulative_parameters_number(void) const method
/// This method returns a vector of size the number of neurons in the layer,
/// where each element is equal to the total number of parameters in the current and all the previous neurons.
Vector<unsigned int> PerceptronLayer::count_cumulative_parameters_number(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
Vector<unsigned int> cumulative_parameters_number(perceptrons_number);
if(perceptrons_number > 0)
{
cumulative_parameters_number[0] = perceptrons[0].count_parameters_number();
for(unsigned int i = 1; i < perceptrons_number; i++)
{
cumulative_parameters_number[i] = cumulative_parameters_number[i-1] + perceptrons[i].count_parameters_number();
}
}
return(cumulative_parameters_number);
}
// Vector<double> arrange_biases(void) const method
/// This method returns the biases from all the perceptrons in the layer.
/// The format is a vector of real values.
/// The size of this vector is the number of neurons in the layer.
Vector<double> PerceptronLayer::arrange_biases(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
Vector<double> biases(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
biases[i] = perceptrons[i].get_bias();
}
return(biases);
}
// Matrix<double> arrange_synaptic_weights(void) const method
/// This method returns the synaptic weights from the perceptrons.
/// The format is a matrix of real values.
/// The number of rows is the number of neurons in the layer.
/// The number of columns is the number of inputs to the layer.
Matrix<double> PerceptronLayer::arrange_synaptic_weights(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
const unsigned int inputs_number = count_inputs_number();
Matrix<double> synaptic_weights(perceptrons_number, inputs_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
for(unsigned int j = 0; j < inputs_number; j++)
{
synaptic_weights[i][j] = perceptrons[i].get_synaptic_weight(j);
}
}
return(synaptic_weights);
}
// Vector<double> arrange_parameters(void) const method
/// This method returns a single vector with all the layer parameters.
/// The format is a vector of real values.
/// The size is the number of parameters in the layer.
Vector<double> PerceptronLayer::arrange_parameters(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
if(perceptrons_number == 0)
{
Vector<double> parameters;
return(parameters);
}
else
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
const unsigned int perceptron_parameters_number = perceptrons[0].count_parameters_number();
Vector<double> perceptron_parameters(perceptron_parameters_number);
unsigned int position = 0;
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptron_parameters = perceptrons[i].arrange_parameters();
parameters.tuck_in(position, perceptron_parameters);
position += perceptron_parameters_number;
}
return(parameters);
}
}
// const Perceptron::ActivationFunction& get_activation_function(void) const method
/// This method returns the activation function of the layer.
/// The activation function of a layer is the activation function of all perceptrons in it.
const Perceptron::ActivationFunction& PerceptronLayer::get_activation_function(void) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
if(perceptrons_number > 0)
{
return(perceptrons[0].get_activation_function());
}
else
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Perceptron::ActivationFunction& get_activation_function(void) method.\n"
<< "PerceptronLayer is empty.\n";
throw std::logic_error(buffer.str());
}
}
// std::string write_activation_function_name(void) const method
/// This method returns a string with the name of the layer activation function.
/// This can be: Logistic, HyperbolicTangent, Threshold, SymmetricThreshold or Linear.
std::string PerceptronLayer::write_activation_function_name(void) const
{
const Perceptron::ActivationFunction activation_function = get_activation_function();
switch(activation_function)
{
case Perceptron::Logistic:
{
return("Logistic");
}
break;
case Perceptron::HyperbolicTangent:
{
return("HyperbolicTangent");
}
break;
case Perceptron::Threshold:
{
return("Threshold");
}
break;
case Perceptron::SymmetricThreshold:
{
return("SymmetricThreshold");
}
break;
case Perceptron::Linear:
{
return("Linear");
}
break;
default:
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "std::string write_activation_function_name(void) const method.\n"
<< "Unknown layer activation function.\n";
throw std::logic_error(buffer.str());
}
break;
}
}
// const bool& get_display(void) const method
/// This method returns true if messages from this class are to be displayed on the screen,
/// or false if messages from this class are not to be displayed on the screen.
const bool& PerceptronLayer::get_display(void) const
{
return(display);
}
// void set(void) method
/// This method sets an empty layer, wihtout any perceptron.
/// It also sets the rest of members to their default values.
void PerceptronLayer::set(void)
{
perceptrons.set();
set_default();
}
// void set(const Vector<Perceptron>&) method
/// This method sets a new layer from a given vector of perceptrons.
/// The rest of members of this class are given their defaul values.
void PerceptronLayer::set(const Vector<Perceptron>& new_perceptrons)
{
perceptrons = new_perceptrons;
set_default();
}
// void set(const unsigned int&, const unsigned int&) method
/// This method sets new numbers of inputs and perceptrons in the layer.
/// It also sets the rest of members to their default values.
/// @param new_inputs_number Number of inputs.
/// @param new_perceptrons_number Number of perceptron neurons.
void PerceptronLayer::set(const unsigned int& new_inputs_number, const unsigned int& new_perceptrons_number)
{
perceptrons.set(new_perceptrons_number);
for(unsigned int i = 0; i < new_perceptrons_number; i++)
{
perceptrons[i].set_inputs_number(new_inputs_number);
}
set_default();
}
// void set(const PerceptronLayer&) method
/// This method sets the members of this perceptron layer object with those from other perceptron layer object.
/// @param other_perceptron_layer PerceptronLayer object to be copied.
void PerceptronLayer::set(const PerceptronLayer& other_perceptron_layer)
{
perceptrons = other_perceptron_layer.perceptrons;
display = other_perceptron_layer.display;
}
// void set_perceptrons(const Vector<Perceptron>&) method
/// This method sets a new vector of percpetrons in the layer.
/// @param new_perceptrons Perceptrons vector.
void PerceptronLayer::set_perceptrons(const Vector<Perceptron>& new_perceptrons)
{
perceptrons = new_perceptrons;
}
// void set_perceptron(const unsigned int&, const Perceptron&) method
/// This method sets a single perceptron in the layer.
/// @param i Index of perceptron.
/// @param new_perceptron Perceptron neuron to be set.
void PerceptronLayer::set_perceptron(const unsigned int& i, const Perceptron& new_perceptron)
{
perceptrons[i] = new_perceptron;
}
// void set_default(void) method
/// This method sets those members not related to the vector of perceptrons to their default value.
/// <ul>
/// <li> Display: True.
/// </ul>
void PerceptronLayer::set_default(void)
{
display = true;
}
// void set_inputs_number(const unsigned int&) method
/// This method sets a new number of inputs in the layer.
/// The new synaptic weights are initialized at random.
/// @param new_inputs_number Number of layer inputs.
void PerceptronLayer::set_inputs_number(const unsigned int& new_inputs_number)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].set_inputs_number(new_inputs_number);
}
}
// void set_perceptrons_number(const unsigned int&) method
/// This method sets a new number perceptrons in the layer.
/// All the parameters are also initialized at random.
/// @param new_perceptrons_number New number of neurons in the layer.
void PerceptronLayer::set_perceptrons_number(const unsigned int& new_perceptrons_number)
{
const unsigned int perceptrons_number = count_perceptrons_number();
const unsigned int inputs_number = count_inputs_number();
if(perceptrons_number > 0)
{
const Perceptron::ActivationFunction& activation_function = get_activation_function();
perceptrons.set(new_perceptrons_number);
set_activation_function(activation_function);
}
else
{
perceptrons.set(new_perceptrons_number);
}
set_inputs_number(inputs_number);
}
// void set_biases(const Vector<double>&) method
/// This method sets the biases of all perceptrons in the layer from a single vector.
/// @param new_biases New set of biases in the layer.
void PerceptronLayer::set_biases(const Vector<double>& new_biases)
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int new_biases_size = new_biases.size();
if(new_biases_size != perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "void set_biases(const Vector<double>&) method.\n"
<< "Size must be equal to number of perceptrons.\n";
throw std::logic_error(buffer.str());
}
#endif
// Set layer biases
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].set_bias(new_biases[i]);
}
}
// void set_synaptic_weights(const Matrix<double>&) method
/// This method sets the synaptic weights of this perceptron layer from a single matrix.
/// The format is a matrix of real numbers.
/// The number of rows is the number of neurons in the corresponding layer.
/// The number of columns is the number of inputs to the corresponding layer.
/// @param new_synaptic_weights New set of synaptic weights in that layer.
void PerceptronLayer::set_synaptic_weights(const Matrix<double>& new_synaptic_weights)
{
const unsigned int inputs_number = count_inputs_number();
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int rows_number = new_synaptic_weights.get_rows_number();
const unsigned int columns_number = new_synaptic_weights.get_columns_number();
std::ostringstream buffer;
if(rows_number != perceptrons_number)
{
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "void set_synaptic_weights(const Matrix<double>&) method.\n"
<< "Number of rows must be equal to size of layer.\n";
throw std::logic_error(buffer.str());
}
else if(columns_number != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "void set_synaptic_weights(const Matrix<double>&) method.\n"
<< "Number of columns must be equal to number of inputs.\n";
throw std::logic_error(buffer.str());
}
#endif
for(unsigned int i = 0; i < perceptrons_number; i++)
{
for(unsigned int j = 0; j < inputs_number; j++)
{
perceptrons[i].set_synaptic_weight(j, new_synaptic_weights[i][j]);
}
}
}
// void set_parameters(const Vector<double>&) method
/// This method sets the parameters of this layer.
/// @param new_parameters Parameters vector for that layer.
void PerceptronLayer::set_parameters(const Vector<double>& new_parameters)
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int parameters_number = count_parameters_number();
const unsigned int new_parameters_size = new_parameters.size();
if(new_parameters_size != parameters_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "void set_parameters(const Vector<double>&) method.\n"
<< "Size of new parameters vector must be equal to number of parameters.\n";
throw std::logic_error(buffer.str());
}
#endif
if(perceptrons_number != 0)
{
const unsigned int perceptron_parameters_number = perceptrons[0].count_parameters_number();
Vector<double> perceptron_parameters(perceptron_parameters_number);
unsigned int position = 0;
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptron_parameters = new_parameters.take_out(position, perceptron_parameters_number);
perceptrons[i].set_parameters(perceptron_parameters);
position += perceptron_parameters_number;
}
}
}
// void set_activation_function(const Perceptron::ActivationFunction&) method
/// This class sets a new activation (or transfer) function in a single layer.
/// @param new_activation_function Activation function for the layer with the previous index.
void PerceptronLayer::set_activation_function(const Perceptron::ActivationFunction& new_activation_function)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].set_activation_function(new_activation_function);
}
}
// void set_activation_function(const std::string&) method
/// This method sets a new activation (or transfer) function in a single layer.
/// The second argument is a string containing the name of the function ("Logistic", "HyperbolicTangent", "Threshold", etc).
/// @param new_activation_function Activation function for that layer.
void PerceptronLayer::set_activation_function(const std::string& new_activation_function)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].set_activation_function(new_activation_function);
}
}
// void set_display(const bool&) method
/// This method sets a new display value.
/// If it is set to true messages from this class are to be displayed on the screen;
/// if it is set to false messages from this class are not to be displayed on the screen.
/// @param new_display Display value.
void PerceptronLayer::set_display(const bool& new_display)
{
display = new_display;
}
// void grow_input(void) method
/// This method makes the perceptron layer to have one more input.
void PerceptronLayer::grow_input(void)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].grow_input();
}
}
// void grow_perceptron(void) method
/// This method makes the perceptron layer to have one more perceptron.
void PerceptronLayer::grow_perceptron(void)
{
const unsigned int inputs_number = count_inputs_number();
Perceptron perceptron(inputs_number);
perceptron.initialize_parameters(0.0);
perceptrons.push_back(perceptron);
}
// void prune_input(const unsigned int&) method
/// This method removes a given input from the layer of perceptrons.
/// @param index Index of input to be pruned.
void PerceptronLayer::prune_input(const unsigned int& index)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].prune_input(index);
}
}
// void prune_perceptron(const unsigned int&) method
/// This method removes a given perceptron from the layer.
/// @param index Index of perceptron to be pruned.
void PerceptronLayer::prune_perceptron(const unsigned int& index)
{
perceptrons.erase(perceptrons.begin() + index-1);
}
// void initialize_random(void) method
/// This method initializes the perceptron layer with a random number of inputs and a randon number of perceptrons.
/// That can be useful for testing purposes.
void PerceptronLayer::initialize_random(void)
{
const unsigned int inputs_number = rand()%10 + 1;
const unsigned int perceptrons_number = rand()%10 + 1;
set(inputs_number, perceptrons_number);
set_display(true);
}
// void initialize_biases(const double&) method
/// This method initializes the biases of all the perceptrons in the layer of perceptrons with a given value.
/// @param value Biases initialization value.
void PerceptronLayer::initialize_biases(const double& value)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].initialize_bias(value);
}
}
// void initialize_synaptic_weights(const double&) const method
/// This method initializes the synaptic weights of all the perceptrons in the layer of perceptrons perceptron with a given value.
/// @param value Synaptic weights initialization value.
void PerceptronLayer::initialize_synaptic_weights(const double& value)
{
const unsigned int perceptrons_number = count_perceptrons_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
perceptrons[i].initialize_synaptic_weights(value);
}
}
// void initialize_parameters(const double&) method
/// This method initializes all the biases and synaptic weights in the neural newtork with a given value.
/// @param value Parameters initialization value.
void PerceptronLayer::initialize_parameters(const double& value)
{
const unsigned int parameters_number = count_parameters_number();
const Vector<double> parameters(parameters_number, value);
set_parameters(parameters);
}
// void initialize_parameters_uniform(void) method
/// This method initializes all the biases and synaptic weights in the neural newtork at random with values comprised
/// between -1 and +1.
void PerceptronLayer::initialize_parameters_uniform(void)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_uniform();
set_parameters(parameters);
}
// void initialize_parameters_uniform(const double&, const double&) method
/// This method initializes all the biases and synaptic weights in the layer of perceptrons at random with values
/// comprised between a minimum and a maximum values.
/// @param minimum Minimum initialization value.
/// @param maximum Maximum initialization value.
void PerceptronLayer::initialize_parameters_uniform(const double& minimum, const double& maximum)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_uniform(minimum, maximum);
set_parameters(parameters);
}
// void initialize_parameters_uniform(const Vector<double>&, const Vector<double>&) method
/// This method initializes all the biases and synaptic weights in the layer of perceptrons at random, with values
/// comprised between different minimum and maximum numbers for each parameter.
/// @param minimum Vector of minimum initialization values.
/// @param maximum Vector of maximum initialization values.
void PerceptronLayer::initialize_parameters_uniform(const Vector<double>& minimum, const Vector<double>& maximum)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_uniform(minimum, maximum);
set_parameters(parameters);
}
// void initialize_parameters_uniform(const Vector< Vector<double> >&) method
/// This method initializes all the biases and synaptic weights in the layer of perceptrons at random, with values
/// comprised between a different minimum and maximum numbers for each parameter.
/// All minimum are maximum initialization values must be given from a vector of two real vectors.
/// The first element must contain the minimum inizizalization value for each parameter.
/// The second element must contain the maximum inizizalization value for each parameter.
/// @param minimum_maximum Vector of minimum and maximum initialization values.
void PerceptronLayer::initialize_parameters_uniform(const Vector< Vector<double> >& minimum_maximum)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_uniform(minimum_maximum[0], minimum_maximum[1]);
set_parameters(parameters);
}
// void initialize_parameters_normal(void) method
/// This method initializes all the biases and synaptic weights in the newtork with random values chosen from a
/// normal distribution with mean 0 and standard deviation 1.
void PerceptronLayer::initialize_parameters_normal(void)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_normal();
set_parameters(parameters);
}
// void initialize_parameters_normal(const double&, const double&) method
/// This method initializes all the biases and synaptic weights in the layer of perceptrons with random random values
/// chosen from a normal distribution with a given mean and a given standard deviation.
/// @param mean Mean of normal distribution.
/// @param standard_deviation Standard deviation of normal distribution.
void PerceptronLayer::initialize_parameters_normal(const double& mean, const double& standard_deviation)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_normal(mean, standard_deviation);
set_parameters(parameters);
}
// void initialize_parameters_normal(const Vector<double>&, const Vector<double>&) method
/// This method initializes all the biases an synaptic weights in the layer of perceptrons with random values chosen
/// from normal distributions with different mean and standard deviation for each parameter.
/// @param mean Vector of mean values.
/// @param standard_deviation Vector of standard deviation values.
void PerceptronLayer::initialize_parameters_normal(const Vector<double>& mean, const Vector<double>& standard_deviation)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_normal(mean, standard_deviation);
set_parameters(parameters);
}
// void initialize_parameters_normal(const Vector< Vector<double> >&) method
/// This method initializes all the biases and synaptic weights in the layer of perceptrons with random values chosen
/// from normal distributions with different mean and standard deviation for each parameter.
/// All mean and standard deviation values are given from a vector of two real vectors.
/// The first element must contain the mean value for each parameter.
/// The second element must contain the standard deviation value for each parameter.
/// @param mean_standard_deviation Vector of mean and standard deviation values.
void PerceptronLayer::initialize_parameters_normal(const Vector< Vector<double> >& mean_standard_deviation)
{
const unsigned int parameters_number = count_parameters_number();
Vector<double> parameters(parameters_number);
parameters.initialize_normal(mean_standard_deviation[0], mean_standard_deviation[1]);
set_parameters(parameters);
}
// double calculate_parameters_norm(void) const method
/// This method calculates the norm of a layer parameters vector.
double PerceptronLayer::calculate_parameters_norm(void) const
{
return(arrange_parameters().calculate_norm());
}
// Vector<double> calculate_combination(const Vector<double>&) const method
/// This method returns the combination to every perceptron in the layer as a function of the inputs to that layer.
/// @param inputs Input to the layer with the previous index.
Vector<double> PerceptronLayer::calculate_combination(const Vector<double>& inputs) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_size = inputs.size();
const unsigned int inputs_number = count_inputs_number();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_combination(const Vector<double>&) const method.\n"
<< "Size of inputs to layer must be equal to number of layer inputs.\n";
throw std::logic_error(buffer.str());
}
#endif
const unsigned int perceptrons_number = count_perceptrons_number();
// Calculate combination to layer
Vector<double> combination(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
combination[i] = perceptrons[i].calculate_combination(inputs);
}
return(combination);
}
// Matrix<double> calculate_combination_Jacobian(const Vector<double>&) const method
/// This method returns the partial derivatives of the combination of a layer with respect to the inputs.
/// All that partial derivatives are arranged in the so called Jacobian matrix of the layer combination function.
Matrix<double> PerceptronLayer::calculate_combination_Jacobian(const Vector<double>&) const
{
return(arrange_synaptic_weights());
}
// Vector< Matrix<double> > calculate_combination_Hessian_form(const unsigned int&, const Vector<double>&) const method
/// This method returns the second partial derivatives of the combination of a layer with respect to the inputs of that layer.
/// All that partial derivatives are arranged in the so called Hessian form, represented as a vector of matrices, of the layer combination function.
Vector< Matrix<double> > PerceptronLayer::calculate_combination_Hessian_form(const Vector<double>&) const
{
const unsigned int inputs_number = count_inputs_number();
const unsigned int perceptrons_number = count_perceptrons_number();
Vector< Matrix<double> > combination_Hessian_form(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
combination_Hessian_form[i].set(inputs_number, inputs_number, 0.0);
}
return(combination_Hessian_form);
}
// Vector<double> calculate_combination_parameters(const Vector<double>&, const Vector<double>&) const method
/// This method returns which would be the combination of a layer as a function of the inputs and for a set of parameters.
/// @param inputs Vector of inputs to that layer.
/// @param parameters Vector of parameters in the layer.
Vector<double> PerceptronLayer::calculate_combination_parameters(const Vector<double>& inputs, const Vector<double>& parameters) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_size = inputs.size();
const unsigned int inputs_number = count_inputs_number();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_combination_parameters(i, const Vector<double>&, const Vector<double>&) const method.\n"
<< "Size of layer inputs (" << inputs_size << ") must be equal to number of layer inputs (" << inputs_number << ").\n";
throw std::logic_error(buffer.str());
}
const unsigned int parameters_size = parameters.size();
const unsigned int parameters_number = count_parameters_number();
if(parameters_size != parameters_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_combination_parameters(const Vector<double>&, const Vector<double>&) const method.\n"
<< "Size of layer parameters (" << parameters_size << ") must be equal to number of lasyer parameters (" << parameters_number << ").\n";
throw std::logic_error(buffer.str());
}
#endif
PerceptronLayer copy(*this);
copy.set_parameters(parameters);
return(copy.calculate_combination(inputs));
}
// Matrix<double> calculate_combination_parameters_Jacobian(const Vector<double>&) const method
/// This method returns the partial derivatives of the combination of a layer with respect to the parameters in that layer, for a given set of inputs.
/// All that partial derivatives are arranged in the so called Jacobian matrix of the layer combination function.
/// @param inputs Vector of inputs to that layer.
Matrix<double> PerceptronLayer::calculate_combination_parameters_Jacobian(const Vector<double>& inputs, const Vector<double>&) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
const unsigned int parameters_number = count_parameters_number();
const unsigned int inputs_number = count_inputs_number();
Matrix<double> combination_parameters_Jacobian(perceptrons_number, parameters_number, 0.0);
unsigned int column_index;
for(unsigned int i = 0; i < perceptrons_number; i++)
{
// Bias derivative
column_index = (1 + inputs_number)*i;
combination_parameters_Jacobian[i][column_index] = 1.0;
// Synaptic weight derivatives
for(unsigned int j = 0; j < inputs_number; j++)
{
column_index = 1 + (1 + inputs_number)*i + j;
combination_parameters_Jacobian[i][column_index] = inputs[j];
}
}
return(combination_parameters_Jacobian);
}
// Vector< Matrix<double> > calculate_combination_parameters_Hessian_form(const Vector<double>&) const method
/// This method returns the second partial derivatives of the combination of a layer with respect to the parameters in that layer, for a given set of inputs.
/// All that partial derivatives are arranged in the so called Hessian form, represented as a vector of matrices, of the layer combination function.
/// @todo
Vector< Matrix<double> > PerceptronLayer::calculate_combination_parameters_Hessian_form(const Vector<double>&, const Vector<double>&) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
Vector< Matrix<double> > combination_parameters_Hessian_form(perceptrons_number);
const unsigned int parameters_number = count_parameters_number();
for(unsigned int i = 0; i < perceptrons_number; i++)
{
combination_parameters_Hessian_form[i].set(parameters_number, parameters_number, 0.0);
}
return(combination_parameters_Hessian_form);
}
// Vector<double> calculate_activation(const Vector<double>&) const method
/// This method returns the outputs from every perceptron in a layer as a function of their combination.
/// @param combination Combination to every neuron in the layer with the previous index.
Vector<double> PerceptronLayer::calculate_activation(const Vector<double>& combination) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int combination_size = combination.size();
if(combination_size != perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_activation(const Vector<double>&) const method.\n"
<< "Combination size must be equal to number of neurons.\n";
throw std::logic_error(buffer.str());
}
#endif
// Calculate activation from layer
Vector<double> activation(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
activation[i] = perceptrons[i].calculate_activation(combination[i]);
}
return(activation);
}
// Vector<double> calculate_activation_derivative(const Vector<double>&) const method
/// This method returns the activation derivative from every perceptron in a layer as a function of their combination.
/// @param combination Combination to every neuron in the layer with the previous index.
Vector<double> PerceptronLayer::calculate_activation_derivative(const Vector<double>& combination) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int combination_size = combination.size();
if(combination_size != perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_activation_derivative(const Vector<double>&) const method.\n"
<< "Size of combination must be equal to number of neurons.\n";
throw std::logic_error(buffer.str());
}
#endif
// Calculate activation derivative from layer
Vector<double> activation_derivative(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
activation_derivative[i] = perceptrons[i].calculate_activation_derivative(combination[i]);
}
return(activation_derivative);
}
// Vector<double> calculate_activation_second_derivative(const Vector<double>&) const method
/// This method returns the activation second derivative from every perceptron as a function of their combination.
/// @param combination Combination to every perceptron in the layer.
Vector<double> PerceptronLayer::calculate_activation_second_derivative(const Vector<double>& combination) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int combination_size = combination.size();
if(combination_size != perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_activation_second_derivative(const Vector<double>&) const method.\n"
<< "Size of combination must be equal to number of neurons.\n";
throw std::logic_error(buffer.str());
}
#endif
// Calculate activation second derivative from layer
Vector<double> activation_second_derivative(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
activation_second_derivative[i] = perceptrons[i].calculate_activation_second_derivative(combination[i]);
}
return(activation_second_derivative);
}
// Matrix<double> arrange_activation_Jacobian(const Vector<double>&) const method
/// This method arranges a "Jacobian" matrix from a vector of derivatives.
/// @param activation_derivative Vector of activation function derivatives.
Matrix<double> PerceptronLayer::arrange_activation_Jacobian(const Vector<double>& activation_derivative) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
Matrix<double> activation_Jacobian(perceptrons_number, perceptrons_number, 0.0);
activation_Jacobian.set_diagonal(activation_derivative);
return(activation_Jacobian);
}
// Vector< Matrix<double> > calculate_activation_Hessian_form(const Vector<double>&) const method
/// This method arranges a "Hessian form" vector of matrices from a vector of second derivatives.
/// @param activation_second_derivative Vector of activation function second derivatives.
Vector< Matrix<double> > PerceptronLayer::arrange_activation_Hessian_form(const Vector<double>& activation_second_derivative) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
Vector< Matrix<double> > activation_Hessian_form(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
activation_Hessian_form[i].set(perceptrons_number, perceptrons_number, 0.0);
activation_Hessian_form[i][i][i] = activation_second_derivative[i];
}
return(activation_Hessian_form);
}
// Vector<double> calculate_outputs(const Vector<double>&) const method
/// This method returns the outputs from every perceptron in a layer as a function of their inputs.
/// @param inputs Input vector to the layer with the previous index.
Vector<double> PerceptronLayer::calculate_outputs(const Vector<double>& inputs) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_size = inputs.size();
const unsigned int inputs_number = count_inputs_number();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_outputs(const Vector<double>&) const method.\n"
<< "Size of inputs must be equal to number of inputs to layer.\n";
throw std::logic_error(buffer.str());
}
#endif
return(calculate_activation(calculate_combination(inputs)));
}
// Matrix<double> calculate_Jacobian(const Vector<double>&) const method
/// This method returns the Jacobian matrix of a layer for a given inputs to that layer.
/// This is composed by the derivatives of the layer outputs with respect to their inputs.
/// The number of rows is the number of neurons in the layer.
/// The number of columns is the number of inputs to that layer.
/// @param inputs Input to layer.
Matrix<double> PerceptronLayer::calculate_Jacobian(const Vector<double>& inputs) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_number = count_inputs_number();
const unsigned int inputs_size = inputs.size();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Matrix<double> calculate_Jacobian(const Vector<double>&) const method.\n"
<< "Size of inputs must be equal to number of inputs to layer.\n";
throw std::logic_error(buffer.str());
}
#endif
const Vector<double> combinations = calculate_combination(inputs);
const Vector<double> activation_derivative = calculate_activation_derivative(combinations);
// const Vector<double> activation_Jacobian = arrange_Jacobian(activation_derivative);
// @todo
const Matrix<double> synaptic_weights = arrange_synaptic_weights();
return(activation_derivative*synaptic_weights);
}
// Vector< Matrix<double> > calculate_Hessian_form(const Vector<double>&) const method
/// This method returns the second partial derivatives of the outputs from a layer with respect to the inputs to that layer.
/// @param inputs Vector of inputs to that layer.
Vector< Matrix<double> > PerceptronLayer::calculate_Hessian_form(const Vector<double>& inputs) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
const Matrix<double> synaptic_weights = arrange_synaptic_weights();
const Vector<double> combination = calculate_combination(inputs);
const Vector<double> activation_second_derivative = calculate_activation_second_derivative(combination);
Vector< Matrix<double> > activation_Hessian_form(perceptrons_number);
Vector< Matrix<double> > Hessian_form(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
activation_Hessian_form[i].set(perceptrons_number, perceptrons_number, 0.0);
activation_Hessian_form[i][i][i] = activation_second_derivative[i];
Hessian_form[i] = synaptic_weights.calculate_transpose().dot(activation_Hessian_form[i]).dot(synaptic_weights);
}
return(Hessian_form);
}
// Vector<double> calculate_parameters_output(const Vector<double>&, const Vector<double>&) const method
/// This method returns which would be the outputs from a layer for a given inputs to that layer and a set of parameters in that layer.
/// @param inputs Vector of inputs to that layer.
/// @param parameters Vector of parameters in that layer.
Vector<double> PerceptronLayer::calculate_parameters_output(const Vector<double>& inputs, const Vector<double>& parameters) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_size = inputs.size();
const unsigned int inputs_number = count_inputs_number();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_parameters_output(const Vector<double>&, const Vector<double>&) const method.\n"
<< "Size of layer inputs (" << inputs_size << ") must be equal to number of layer inputs (" << inputs_number << ").\n";
throw std::logic_error(buffer.str());
}
const unsigned int parameters_size = parameters.size();
const unsigned int parameters_number = count_parameters_number();
if(parameters_size != parameters_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector<double> calculate_parameters_output(const Vector<double>&, const Vector<double>&) const method.\n"
<< "Size of parameters (" << parameters_size << ") must be equal to number of parameters (" << parameters_number << ").\n";
throw std::logic_error(buffer.str());
}
#endif
PerceptronLayer copy(*this);
copy.set_parameters(parameters);
return(copy.calculate_outputs(inputs));
}
// Matrix<double> calculate_parameters_Jacobian(const unsigned int&, const Vector<double>&) const method
/// This method returns the parameters Jacobian for a given set of inputs.
/// This is composed by the derivatives of the layer outputs with respect to the layer parameters.
/// The number of rows is the number of neurons in the layer.
/// The number of columns is the number of parameters in that layer.
/// @param inputs Set of inputs to the layer.
/// @param parameters Set of layer parameters.
Matrix<double> PerceptronLayer::calculate_parameters_Jacobian(const Vector<double>& inputs, const Vector<double>& parameters) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_number = count_inputs_number();
const unsigned int inputs_size = inputs.size();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Matrix<double> calculate_parameters_Jacobian(const Vector<double>&) const method.\n"
<< "Size of inputs must be equal to number of inputs.\n";
throw std::logic_error(buffer.str());
}
#endif
const Vector<double> combination_parameters = calculate_combination_parameters(inputs, parameters);
const Matrix<double> combination_parameters_Jacobian = calculate_combination_parameters_Jacobian(inputs, parameters);
const Vector<double> activation_derivative = calculate_activation_derivative(combination_parameters);
const Matrix<double> activation_Jacobian = arrange_activation_Jacobian(activation_derivative);
return(activation_Jacobian.dot(combination_parameters_Jacobian));
}
// Vector< Matrix<double> > calculate_parameters_Hessian_form(const Vector<double>&) const method
/// This method returns the second partial derivatives of the outputs from a layer with respect to the parameters in that layer, for a given inputs to that layer.
/// This quantity is the Hessian form of the layer outputs function, and it is represented as a vector of matrices.
/// @param inputs Set of layer inputs.
/// @param parameters Set of layer parameters.
Vector< Matrix<double> > PerceptronLayer::calculate_parameters_Hessian_form(const Vector<double>& inputs, const Vector<double>& parameters) const
{
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_number = count_inputs_number();
const unsigned int inputs_size = inputs.size();
if(inputs_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "Vector< Matrix<double> > calculate_parameters_Hessian_form(const unsigned int&, const Vector<double>&) const method.\n"
<< "Size must be equal to number of inputs of layer.\n";
throw std::logic_error(buffer.str());
}
#endif
const unsigned int perceptrons_number = count_perceptrons_number();
const Vector<double> combination = calculate_combination(inputs);
const Matrix<double> combination_parameters_Jacobian = calculate_combination_parameters_Jacobian(inputs, parameters);
const Vector<double> activation_second_derivative = calculate_activation_second_derivative(combination);
const Vector< Matrix<double> > activation_Hessian_form = arrange_activation_Hessian_form(activation_second_derivative);
// Calculate parameters Hessian form
Vector< Matrix<double> > parameters_Hessian_form(perceptrons_number);
for(unsigned int i = 0; i < perceptrons_number; i++)
{
parameters_Hessian_form[i] = combination_parameters_Jacobian.calculate_transpose().dot(activation_Hessian_form[i]).dot(combination_parameters_Jacobian);
}
return(parameters_Hessian_form);
}
// std::string write_expression(const Vector<std::string>&, const Vector<std::string>&) const method
/// This method returns a string with the expression of the inputs-outputs relationship of the layer.
/// @param inputs_name Vector of strings with the name of the layer inputs.
/// @param outputs_name Vector of strings with the name of the layer outputs.
std::string PerceptronLayer::write_expression(const Vector<std::string>& inputs_name, const Vector<std::string>& outputs_name) const
{
const unsigned int perceptrons_number = count_perceptrons_number();
// Control sentence (if debug)
#ifdef _DEBUG
const unsigned int inputs_number = count_inputs_number();
const unsigned int inputs_name_size = inputs_name.size();
if(inputs_name_size != inputs_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "std::string write_expression(const Vector<std::string>&, const Vector<std::string>&) const method.\n"
<< "Size of inputs name must be equal to number of layer inputs.\n";
throw std::logic_error(buffer.str());
}
const unsigned int outputs_name_size = outputs_name.size();
if(outputs_name_size != perceptrons_number)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: PerceptronLayer class.\n"
<< "std::string write_expression(const Vector<std::string>&, const Vector<std::string>&) const method.\n"
<< "Size of outputs name must be equal to number of perceptrons.\n";
throw std::logic_error(buffer.str());
}
#endif
std::ostringstream buffer;
for(unsigned int i = 0; i < perceptrons_number; i++)
{
buffer << perceptrons[i].write_expression(inputs_name, outputs_name[i]);
}
return(buffer.str());
}
}
// OpenNN: Open Neural Networks Library.
// Copyright (C) 2005-2012 Roberto Lopez
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
| mit |
skylersaleh/ArgonEngine | mac/SDL2/thread/pthread/SDL_systhread.c | 1 | 5985 | //Generated by the Argon Build System
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL2/SDL_config.h"
#include <pthread.h>
#if HAVE_PTHREAD_NP_H
#include <pthread_np.h>
#endif
#include <signal.h>
#ifdef __LINUX__
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif /* __LINUX__ */
#if defined(__LINUX__) || defined(__MACOSX__) || defined(__IPHONEOS__)
#include <dlfcn.h>
#ifndef RTLD_DEFAULT
#define RTLD_DEFAULT NULL
#endif
#endif
#include "SDL2/SDL_platform.h"
#include "SDL2/SDL_thread.h"
#include "SDL2/thread/SDL_thread_c.h"
#include "SDL2/thread/SDL_systhread.h"
#ifdef __ANDROID__
#include "SDL2/core/android/SDL_android.h"
#endif
#include "SDL2/SDL_assert.h"
/* List of signals to mask in the subthreads */
static const int sig_list[] = {
SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH,
SIGVTALRM, SIGPROF, 0
};
static void *
RunThread(void *data)
{
#ifdef __ANDROID__
Android_JNI_SetupThread();
#endif
SDL_RunThread(data);
return NULL;
}
#if defined(__MACOSX__) || defined(__IPHONEOS__)
static SDL_bool checked_setname = SDL_FALSE;
static int (*ppthread_setname_np)(const char*) = NULL;
#elif defined(__LINUX__)
static SDL_bool checked_setname = SDL_FALSE;
static int (*ppthread_setname_np)(pthread_t, const char*) = NULL;
#endif
int
SDL_SYS_CreateThread(SDL_Thread * thread, void *args)
{
pthread_attr_t type;
/* do this here before any threads exist, so there's no race condition. */
#if defined(__MACOSX__) || defined(__IPHONEOS__) || defined(__LINUX__)
if (!checked_setname) {
void *fn = dlsym(RTLD_DEFAULT, "pthread_setname_np");
#if defined(__MACOSX__) || defined(__IPHONEOS__)
ppthread_setname_np = (int(*)(const char*)) fn;
#elif defined(__LINUX__)
ppthread_setname_np = (int(*)(pthread_t, const char*)) fn;
#endif
checked_setname = SDL_TRUE;
}
#endif
/* Set the thread attributes */
if (pthread_attr_init(&type) != 0) {
return SDL_SetError("Couldn't initialize pthread attributes");
}
pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
/* Create the thread and go! */
if (pthread_create(&thread->handle, &type, RunThread, args) != 0) {
return SDL_SetError("Not enough resources to create thread");
}
return 0;
}
void
SDL_SYS_SetupThread(const char *name)
{
int i;
sigset_t mask;
if (name != NULL) {
#if defined(__MACOSX__) || defined(__IPHONEOS__) || defined(__LINUX__)
SDL_assert(checked_setname);
if (ppthread_setname_np != NULL) {
#if defined(__MACOSX__) || defined(__IPHONEOS__)
ppthread_setname_np(name);
#elif defined(__LINUX__)
ppthread_setname_np(pthread_self(), name);
#endif
}
#elif HAVE_PTHREAD_SETNAME_NP
pthread_setname_np(pthread_self(), name);
#elif HAVE_PTHREAD_SET_NAME_NP
pthread_set_name_np(pthread_self(), name);
#endif
}
/* Mask asynchronous signals for this thread */
sigemptyset(&mask);
for (i = 0; sig_list[i]; ++i) {
sigaddset(&mask, sig_list[i]);
}
pthread_sigmask(SIG_BLOCK, &mask, 0);
#ifdef PTHREAD_CANCEL_ASYNCHRONOUS
/* Allow ourselves to be asynchronously cancelled */
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
}
#endif
}
SDL_threadID
SDL_ThreadID(void)
{
return ((SDL_threadID) pthread_self());
}
int
SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority)
{
#ifdef __LINUX__
int value;
if (priority == SDL_THREAD_PRIORITY_LOW) {
value = 19;
} else if (priority == SDL_THREAD_PRIORITY_HIGH) {
value = -20;
} else {
value = 0;
}
if (setpriority(PRIO_PROCESS, syscall(SYS_gettid), value) < 0) {
/* Note that this fails if you're trying to set high priority
and you don't have root permission. BUT DON'T RUN AS ROOT!
*/
return SDL_SetError("setpriority() failed");
}
return 0;
#else
struct sched_param sched;
int policy;
pthread_t thread = pthread_self();
if (pthread_getschedparam(thread, &policy, &sched) < 0) {
return SDL_SetError("pthread_getschedparam() failed");
}
if (priority == SDL_THREAD_PRIORITY_LOW) {
sched.sched_priority = sched_get_priority_min(policy);
} else if (priority == SDL_THREAD_PRIORITY_HIGH) {
sched.sched_priority = sched_get_priority_max(policy);
} else {
int min_priority = sched_get_priority_min(policy);
int max_priority = sched_get_priority_max(policy);
sched.sched_priority = (min_priority + (max_priority - min_priority) / 2);
}
if (pthread_setschedparam(thread, policy, &sched) < 0) {
return SDL_SetError("pthread_setschedparam() failed");
}
return 0;
#endif /* linux */
}
void
SDL_SYS_WaitThread(SDL_Thread * thread)
{
pthread_join(thread->handle, 0);
}
/* vi: set ts=4 sw=4 expandtab: */
| mit |
smogpill/core | src/imgui/backends/imgui_impl_opengl3.cpp | 1 | 35469 | #include "imgui/pch.h"
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
// 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
// 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
// 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
// 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
// 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x)
// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader.
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "../imgui.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// GL includes
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <GLES2/gl2.h>
#elif defined(IMGUI_IMPL_OPENGL_ES3)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES3/gl.h> // Use GL ES 3
#else
#include <GLES3/gl3.h> // Use GL ES 3
#endif
#else
// About Desktop OpenGL function loaders:
// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
#include <GL/gl3w.h> // Needs to be initialized with gl3wInit() in user's code
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
#include <GL/glew.h> // Needs to be initialized with glewInit() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
#include <glad/glad.h> // Needs to be initialized with gladLoadGL() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
#include <glad/gl.h> // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/Binding.h> // Needs to be initialized with glbinding::Binding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/glbinding.h>// Needs to be initialized with glbinding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#else
#include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
#endif
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
#endif
// Desktop GL 3.3+ has glBindSampler()
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
#endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif
// Desktop GL use extension detection
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
#endif
// OpenGL Data
static GLuint g_GlVersion = 0; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings.
static GLuint g_FontTexture = 0;
static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location
static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location
static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
static bool g_HasClipOrigin = false;
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
// Query for GL version (e.g. 320 for GL 3.2)
#if !defined(IMGUI_IMPL_OPENGL_ES2)
GLint major = 0;
GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major == 0 && minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
const char* gl_version = (const char*)glGetString(GL_VERSION);
sscanf(gl_version, "%d.%d", &major, &minor);
}
g_GlVersion = (GLuint)(major * 100 + minor * 10);
#else
g_GlVersion = 200; // GLES 2
#endif
// Setup backend capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_opengl3";
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate shaders.
// Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
#if defined(IMGUI_IMPL_OPENGL_ES2)
if (glsl_version == NULL)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
if (glsl_version == NULL)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
if (glsl_version == NULL)
glsl_version = "#version 150";
#else
if (glsl_version == NULL)
glsl_version = "#version 130";
#endif
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
strcpy(g_GlslVersionString, glsl_version);
strcat(g_GlslVersionString, "\n");
// Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected.
// The code actually never uses the 'gl_loader' variable! It is only here so you can read it!
// If auto-detection fails or doesn't select the same GL loader file as used by your application,
// you are likely to get a crash below.
// You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
const char* gl_loader = "Unknown";
IM_UNUSED(gl_loader);
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
gl_loader = "GL3W";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
gl_loader = "GLEW";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
gl_loader = "GLAD";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
gl_loader = "GLAD2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
gl_loader = "glbinding2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
gl_loader = "glbinding3";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
gl_loader = "custom";
#else
gl_loader = "none";
#endif
// Make an arbitrary GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code.
// Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture);
// Detect extensions we support
g_HasClipOrigin = (g_GlVersion >= 450);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
GLint num_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
for (GLint i = 0; i < num_extensions; i++)
{
const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
if (strcmp(extension, "GL_ARB_clip_control") == 0)
g_HasClipOrigin = true;
}
#endif
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
void ImGui_ImplOpenGL3_NewFrame()
{
if (!g_ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (g_GlVersion >= 310)
glDisable(GL_PRIMITIVE_RESTART);
#endif
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
#if defined(GL_CLIP_ORIGIN)
bool clip_origin_lower_left = true;
if (g_HasClipOrigin)
{
GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
}
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
#if defined(GL_CLIP_ORIGIN)
if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
#endif
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (g_GlVersion >= 330)
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
#endif
(void)vertex_array_object;
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glEnableVertexAttribArray(g_AttribLocationVtxPos);
glEnableVertexAttribArray(g_AttribLocationVtxUV);
glEnableVertexAttribArray(g_AttribLocationVtxColor);
glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
}
// OpenGL3 Render function.
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
// This is in order to be able to run within an OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
GLuint last_sampler; if (g_GlVersion >= 330) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
#endif
GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef GL_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
GLboolean last_enable_primitive_restart = (g_GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
#endif
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
GLuint vertex_array_object = 0;
#ifndef IMGUI_IMPL_OPENGL_ES2
glGenVertexArrays(1, &vertex_array_object);
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
{
// Apply scissor/clipping rectangle
glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
// Bind texture, Draw
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID());
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset);
else
#endif
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)));
}
}
}
}
// Destroy the temporary VAO
#ifndef IMGUI_IMPL_OPENGL_ES2
glDeleteVertexArrays(1, &vertex_array_object);
#endif
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (g_GlVersion >= 330)
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (g_GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
#endif
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
#endif
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->SetTexID((ImTextureID)(intptr_t)g_FontTexture);
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
if (g_FontTexture)
{
ImGuiIO& io = ImGui::GetIO();
glDeleteTextures(1, &g_FontTexture);
io.Fonts->SetTexID(0);
g_FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(g_GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision mediump float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = NULL;
const GLchar* fragment_shader = NULL;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader };
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
glCompileShader(g_VertHandle);
CheckShader(g_VertHandle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader };
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
glCompileShader(g_FragHandle);
CheckShader(g_FragHandle, "fragment shader");
g_ShaderHandle = glCreateProgram();
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
CheckProgram(g_ShaderHandle, "shader program");
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
if (g_VboHandle) { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; }
if (g_ElementsHandle) { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; }
if (g_ShaderHandle && g_VertHandle) { glDetachShader(g_ShaderHandle, g_VertHandle); }
if (g_ShaderHandle && g_FragHandle) { glDetachShader(g_ShaderHandle, g_FragHandle); }
if (g_VertHandle) { glDeleteShader(g_VertHandle); g_VertHandle = 0; }
if (g_FragHandle) { glDeleteShader(g_FragHandle); g_FragHandle = 0; }
if (g_ShaderHandle) { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; }
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
| mit |
npettiaux/orthanc-viewer | Code/Controller/SubInterface.cpp | 1 | 2749 | /**
* Copyright (c) 2013-2014 Quentin Smetz <qsmetz@gmail.com>, Sebastien
* Jodogne <s.jodogne@gmail.com>
*
* 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.
**/
//!
//! \file SubInterface.cpp
//! \brief The SubInterface.cpp file contains the definition of non-inline
//! methods of the SubInterface class.
//!
//! \author Quentin Smetz
//!
#include "SubInterface.h"
using namespace std;
using namespace customwidget;
// Constructor
SubInterface::SubInterface() : Widget()
{
m_viewer = 0;
// Create the interface
m_gridLayout = new QGridLayout();
setLayout(m_gridLayout);
}
// Destructor
SubInterface::~SubInterface()
{}
// The 'setViewer' method
void SubInterface::setViewer(Viewer* viewer)
{
m_viewer = viewer;
// Create the central layout
QHBoxLayout* centralLayout = new QHBoxLayout();
centralLayout->addWidget(m_viewer);
m_gridLayout->addLayout(centralLayout, 1, 1); // Permits to add components in subclasses
// To check event from the viewer
m_viewer->installEventFilter(this);
}
// The 'eventFilter' method
bool SubInterface::eventFilter(QObject* object, QEvent* event)
{
// If the event is from the viewer
if(object == m_viewer)
{
// Simulate a double click if the viewer was double clicked
if(event->type() == QEvent::MouseButtonDblClick)
mouseDoubleClickEvent(static_cast<QMouseEvent*>(event));
}
return Widget::eventFilter(object, event);
}
// The 'mouseDoubleClickEvent' method
void SubInterface::mouseDoubleClickEvent(QMouseEvent* event)
{
// Emits a signal which indicates the SubInterface was double clicked
emit doubleClicked(this);
event->accept(); // Stop the event
}
| mit |
coder-bot/ftc5602-code | 2011-2012 Bowled Over!/bowlingservos.c | 1 | 5019 | #pragma config(Hubs, S1, HTMotor, HTServo, HTMotor, none)
#pragma config(Sensor, S1, , sensorI2CMuxController)
#pragma config(Motor, mtr_S1_C1_1, motorD, tmotorNone, openLoop)
#pragma config(Motor, mtr_S1_C1_2, motorE, tmotorNone, openLoop)
#pragma config(Motor, mtr_S1_C3_1, motorF, tmotorNormal, openLoop)
#pragma config(Motor, mtr_S1_C3_2, motorG, tmotorNormal, openLoop)
#pragma config(Servo, srvo_S1_C2_1, leftservo, tServoContinuousRotation)
#pragma config(Servo, srvo_S1_C2_2, rightservo, tServoContinuousRotation)
#pragma config(Servo, srvo_S1_C2_3, servo3, tServoNone)
#pragma config(Servo, srvo_S1_C2_4, servo4, tServoNone)
#pragma config(Servo, srvo_S1_C2_5, servo5, tServoNone)
#pragma config(Servo, srvo_S1_C2_6, servo6, tServoNone)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tele-Operation Mode Code Template
//
// This file contains a template for simplified creation of an tele-op program for an FTC
// competition.
//
// You need to customize two functions with code unique to your specific robot.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
#include "JoystickDriver.c" //Include file to "handle" the Bluetooth messages.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// initializeRobot
//
// Prior to the start of tele-op mode, you may want to perform some initialization on your robot
// and the variables within your program.
//
// In most cases, you may not have to add any code to this function and it will remain "empty".
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
void initializeRobot()
{
// Place code here to sinitialize servos to starting positions.
// Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize.
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Main Task
//
// The following is the main code for the tele-op robot operation. Customize as appropriate for
// your specific robot.
//
// Game controller / joystick information is sent periodically (about every 50 milliseconds) from
// the FMS (Field Management System) to the robot. Most tele-op programs will follow the following
// logic:
// 1. Loop forever repeating the following actions:
// 2. Get the latest game controller / joystick settings that have been received from the PC.
// 3. Perform appropriate actions based on the joystick + buttons settings. This is usually a
// simple action:
// * Joystick values are usually directly translated into power levels for a motor or
// position of a servo.
// * Buttons are usually used to start/stop a motor or cause a servo to move to a specific
// position.
// 4. Repeat the loop.
//
// Your program needs to continuously loop because you need to continuously respond to changes in
// the game controller settings.
//
// At the end of the tele-op period, the FMS will autonmatically abort (stop) execution of the program.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
task main()
{
initializeRobot();
waitForStart(); // wait for start of tele-op phase
while (true)
{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//// ////
//// Add your robot specific tele-op code here. ////
//// ////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
#if 0
servo[leftservo] = 127;
servo[rightservo] = 127;
wait1Msec(1000);
servo[leftservo] = 0;
servo[rightservo] = 255;
wait1Msec(1000);
servo[leftservo] = 127;
servo[rightservo] = 127;
wait1Msec(1000);
servo[leftservo] = 255;
servo[rightservo] = 0;
wait1Msec(1000);
#endif
#if 1
if(joystick.joy1_y2 > 20)
{
servo[leftservo] = 255;
servo[rightservo] = 0;
}
else if (joystick.joy1_y2 < -20)
{
servo[leftservo] = 0;
servo[rightservo] = 255;
}
else
{
servo[leftservo] = 127;
servo[rightservo] = 127;
}
//wait1Msec( 100 );
#endif
// Look in the ROBOTC samples folder for programs that may be similar to what you want to perform.
// You may be able to find "snippets" of code that are similar to the functions that you want to
// perform.
}
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__malloc_free_int64_t_84_goodB2G.cpp | 1 | 1376 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__malloc_free_int64_t_84_goodB2G.cpp
Label Definition File: CWE415_Double_Free__malloc_free.label.xml
Template File: sources-sinks-84_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 415 Double Free
* BadSource: Allocate data using malloc() and Deallocate data using free()
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: do nothing
* BadSink : Deallocate data using free()
* 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 OMITGOOD
#include "std_testcase.h"
#include "CWE415_Double_Free__malloc_free_int64_t_84.h"
namespace CWE415_Double_Free__malloc_free_int64_t_84
{
CWE415_Double_Free__malloc_free_int64_t_84_goodB2G::CWE415_Double_Free__malloc_free_int64_t_84_goodB2G(int64_t * dataCopy)
{
data = dataCopy;
data = (int64_t *)malloc(100*sizeof(int64_t));
/* POTENTIAL FLAW: Free data in the source - the bad sink frees data as well */
free(data);
}
CWE415_Double_Free__malloc_free_int64_t_84_goodB2G::~CWE415_Double_Free__malloc_free_int64_t_84_goodB2G()
{
/* do nothing */
/* FIX: Don't attempt to free the memory */
; /* empty statement needed for some flow variants */
}
}
#endif /* OMITGOOD */
| mit |
century-arcade/src | c64/vice-2.4/src/arch/unix/gui/uifliplist.c | 1 | 13280 | /*
* uifliplist.c
*
* Written by
* pottendo <pottendo@gmx.net>
* Andreas Boose <viceteam@t-online.de>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "vice.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "attach.h"
#include "fliplist.h"
#include "lib.h"
#include "log.h"
#include "resources.h"
#include "uiapi.h"
#include "uifliplist.h"
#include "uidrive.h"
#include "uilib.h"
#include "uimenu.h"
#include "util.h"
#include "vsync.h"
struct cb_data_t {
int unit;
long data; /* should be enough for a pointer */
};
typedef enum {
CBD_NEXT, CBD_PREV, CBD_ADD, CBD_REMOVE
} cbd_enum_t;
extern char last_attached_images[NUM_DRIVES][256];
extern ui_drive_enable_t enabled_drives;
extern UI_CALLBACK(attach_disk);
extern UI_CALLBACK(detach_disk);
static UI_CALLBACK(attach_from_fliplist3)
{
fliplist_attach_head(8, vice_ptr_to_int(UI_MENU_CB_PARAM));
}
static UI_CALLBACK(add2fliplist)
{
fliplist_add_image(8);
uifliplist_update_menus(8, 8);
}
static UI_CALLBACK(remove_from_fliplist)
{
fliplist_remove(8, NULL);
uifliplist_update_menus(8, 8);
}
static char *load_save_fliplist_last_dir = NULL;
static UI_CALLBACK(load_save_fliplist)
{
char *filename, *title;
int what = vice_ptr_to_int(UI_MENU_CB_PARAM);
ui_button_t button;
uilib_file_filter_enum_t filter[] = { UILIB_FILTER_FLIPLIST, UILIB_FILTER_ALL };
vsync_suspend_speed_eval();
title = util_concat(what ? _("Load ") : _("Save"), _("Flip list file"), NULL);
filename = ui_select_file(title, NULL, 0, load_save_fliplist_last_dir, filter, sizeof(filter) / sizeof(*filter), &button, 1, NULL, what ? UI_FC_LOAD : UI_FC_SAVE);
lib_free(title);
switch (button) {
case UI_BUTTON_OK:
if (what) {
if (fliplist_load_list((unsigned int)-1, filename, 0) == 0) {
ui_message(_("Successfully read `%s'."), filename);
} else {
ui_error(_("Error reading `%s'."), filename);
}
} else {
if (fliplist_save_list((unsigned int)-1, filename) == 0) {
ui_message(_("Successfully wrote `%s'"), filename);
} else {
ui_error(_("Error writing `%s'."), filename);
}
}
lib_free(load_save_fliplist_last_dir);
util_fname_split(filename, &load_save_fliplist_last_dir, NULL);
break;
default:
break;
}
}
ui_menu_entry_t fliplist_submenu[] = {
{ N_("Add current image (Unit 8)"), UI_MENU_TYPE_NORMAL,
(ui_callback_t)add2fliplist, (ui_callback_data_t)0, NULL,
KEYSYM_i, UI_HOTMOD_META },
{ N_("Remove current image (Unit 8)"), UI_MENU_TYPE_NORMAL,
(ui_callback_t)remove_from_fliplist, (ui_callback_data_t)0, NULL,
KEYSYM_k, UI_HOTMOD_META },
{ N_("Attach next image (Unit 8)"), UI_MENU_TYPE_NORMAL,
(ui_callback_t)attach_from_fliplist3, (ui_callback_data_t)1, NULL,
KEYSYM_n, UI_HOTMOD_META },
{ N_("Attach previous image (Unit 8)"), UI_MENU_TYPE_NORMAL,
(ui_callback_t)attach_from_fliplist3, (ui_callback_data_t)0, NULL,
KEYSYM_N, UI_HOTMOD_META | UI_HOTMOD_SHIFT },
{ N_("Load flip list file"), UI_MENU_TYPE_DOTS,
(ui_callback_t)load_save_fliplist, (ui_callback_data_t)1, NULL },
{ N_("Save flip list file"), UI_MENU_TYPE_DOTS,
(ui_callback_t)load_save_fliplist, (ui_callback_data_t)0, NULL },
{ NULL }
};
static UI_CALLBACK(attach_from_fliplist2)
{
file_system_attach_disk(fliplist_get_unit((void *)UI_MENU_CB_PARAM), fliplist_get_image((void *)UI_MENU_CB_PARAM));
}
static UI_CALLBACK(remove_from_fliplist2)
{
fliplist_remove(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit, (char *)((struct cb_data_t *)UI_MENU_CB_PARAM)->data);
uifliplist_update_menus(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit, ((struct cb_data_t *)UI_MENU_CB_PARAM)->unit);
}
static UI_CALLBACK(add2fliplist2)
{
fliplist_set_current(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit, (char *)((struct cb_data_t *)UI_MENU_CB_PARAM)->data);
fliplist_add_image(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit);
uifliplist_update_menus(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit, ((struct cb_data_t *)UI_MENU_CB_PARAM)->unit);
}
static UI_CALLBACK(attach_from_fliplist)
{
fliplist_attach_head(((struct cb_data_t *)UI_MENU_CB_PARAM)->unit, (int)((struct cb_data_t *)UI_MENU_CB_PARAM)->data);
}
UI_MENU_DEFINE_TOGGLE(AttachDevice8Readonly)
UI_MENU_DEFINE_TOGGLE(AttachDevice9Readonly)
UI_MENU_DEFINE_TOGGLE(AttachDevice10Readonly)
UI_MENU_DEFINE_TOGGLE(AttachDevice11Readonly)
#define FLIPLIST_MENU_LIMIT 256
void uifliplist_update_menus(int from_unit, int to_unit)
{
/* Yick, allocate dynamically */
static ui_menu_entry_t flipmenu[NUM_DRIVES][FLIPLIST_MENU_LIMIT];
static struct cb_data_t cb_data[NUM_DRIVES][sizeof(cbd_enum_t)];
char *image = NULL, *t0 = NULL, *t1 = NULL, *t2 = NULL, *t3 = NULL;
char *t4 = NULL, *t5 = NULL, *dir;
void *fl_iterator;
int i, drive, true_emu, fliplist_start = 0;
ui_callback_t callback = NULL;
resources_get_int("DriveTrueEmulation", &true_emu);
for (drive = from_unit - 8; (drive <= to_unit - 8) && (drive < NUM_DRIVES); drive++) {
i = 0;
t0 = t1 = t2 = t3 = t4 = t5 = NULL;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
t0 = lib_msprintf(_("Attach #%d"), drive + 8);
flipmenu[drive][i].string = t0;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)attach_disk;
flipmenu[drive][i].callback_data = (ui_callback_data_t)(long)(drive + 8);
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
t5 = lib_msprintf(_("Detach #%d"), drive + 8);
flipmenu[drive][i].string = t5;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)detach_disk;
flipmenu[drive][i].callback_data = (ui_callback_data_t)(long)(drive + 8);
i++;
/* drivesettings */
memcpy(&flipmenu[drive][i], (const char *)ui_drive_options_submenu, sizeof(ui_menu_entry_t));
i++;
/* Write protext UI controll */
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
flipmenu[drive][i].string = _("Read-only");
flipmenu[drive][i].type = UI_MENU_TYPE_TICK;
switch (drive) {
case 0:
callback = (ui_callback_t)toggle_AttachDevice8Readonly;
break;
case 1:
callback = (ui_callback_t)toggle_AttachDevice9Readonly;
break;
case 2:
callback = (ui_callback_t)toggle_AttachDevice10Readonly;
break;
case 3:
callback = (ui_callback_t)toggle_AttachDevice11Readonly;
break;
}
flipmenu[drive][i].callback = callback;
i++;
fliplist_start = i; /* if we take the goto don't free anything */
/* don't update menu deeply when drive has not been enabled
or nothing has been attached */
if (true_emu) {
if (!((1 << drive) & enabled_drives)) {
goto update_menu;
}
} else {
if (strcmp(last_attached_images[drive], "") == 0) {
goto update_menu;
}
}
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
flipmenu[drive][i].string = "--";
flipmenu[drive][i].type = UI_MENU_TYPE_SEPARATOR;
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
util_fname_split(fliplist_get_next(drive + 8), &dir, &image);
if (image) {
t1 = util_concat(_("Next: "), image, NULL);
} else {
t1 = util_concat(_("Next: "), "<", _("empty"), ">", NULL);
}
flipmenu[drive][i].string = t1;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)attach_from_fliplist;
cb_data[drive][CBD_NEXT].unit = drive + 8;
cb_data[drive][CBD_NEXT].data = 1;
flipmenu[drive][i].callback_data = (ui_callback_data_t)&(cb_data[drive][CBD_NEXT]);
lib_free(dir);
dir = NULL;
lib_free(image);
image = NULL;
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
util_fname_split(fliplist_get_prev(drive + 8), &dir, &image);
if (image) {
t2 = util_concat(_("Previous: "), image, NULL);
} else {
t2 = util_concat(_("Previous: "), "<", _("empty"), ">", NULL);
}
flipmenu[drive][i].string = t2;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)attach_from_fliplist;
cb_data[drive][CBD_PREV].unit = drive + 8;
cb_data[drive][CBD_PREV].data = 0;
flipmenu[drive][i].callback_data = (ui_callback_data_t)&(cb_data[drive][CBD_PREV]);
lib_free(dir);
dir = NULL;
lib_free(image);
image = NULL;
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
util_fname_split(last_attached_images[drive], &dir, &image);
t3 = util_concat(_("Add: "), image, NULL);
flipmenu[drive][i].string = t3;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)add2fliplist2;
cb_data[drive][CBD_ADD].unit = drive + 8;
cb_data[drive][CBD_ADD].data = (long) last_attached_images[drive];
flipmenu[drive][i].callback_data = (ui_callback_data_t)&(cb_data[drive][CBD_ADD]);
lib_free(dir);
dir = NULL;
lib_free(image);
image = NULL;
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
util_fname_split(last_attached_images[drive], &dir, &image);
t4 = util_concat(_("Remove: "), image, NULL);
flipmenu[drive][i].string = t4;
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)remove_from_fliplist2;
cb_data[drive][CBD_REMOVE].unit = drive + 8;
cb_data[drive][CBD_REMOVE].data = (long) last_attached_images[drive];
flipmenu[drive][i].callback_data = (ui_callback_data_t)&(cb_data[drive][CBD_REMOVE]);
lib_free(dir);
dir = NULL;
lib_free(image);
image = NULL;
i++;
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
flipmenu[drive][i].string = "--";
flipmenu[drive][i].type = UI_MENU_TYPE_SEPARATOR;
i++;
/* Now collect current fliplist */
fl_iterator = fliplist_init_iterate(drive + 8);
fliplist_start = i;
while (fl_iterator) {
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
util_fname_split(fliplist_get_image(fl_iterator), &dir, &image);
flipmenu[drive][i].string = util_concat(NO_TRANS, image, NULL);
flipmenu[drive][i].type = UI_MENU_TYPE_NORMAL;
flipmenu[drive][i].callback = (ui_callback_t)attach_from_fliplist2;
flipmenu[drive][i].callback_data = (ui_callback_data_t)fl_iterator;
fl_iterator = fliplist_next_iterate(drive + 8);
lib_free(dir);
dir = NULL;
lib_free(image);
image = NULL;
i++;
if (i >= (FLIPLIST_MENU_LIMIT - 1)) {
/* the end delimitor must fit */
log_warning(LOG_DEFAULT, "Number of fliplist menu entries exceeded. Cutting after %d entries.", i);
break;
}
}
update_menu:
/* make sure the menu is well terminated */
memset(&(flipmenu[drive][i]), 0, sizeof(ui_menu_entry_t));
ui_destroy_drive_menu(drive);
ui_set_drive_menu(drive, flipmenu[drive]);
lib_free(t0);
lib_free(t1);
lib_free(t2);
lib_free(t3);
lib_free(t4);
lib_free(t5);
while (fliplist_start < i) {
lib_free(flipmenu[drive][fliplist_start].string);
flipmenu[drive][fliplist_start].string = NULL;
fliplist_start++;
}
}
/* Update the checkmarks */
ui_menu_update_all();
}
void uifliplist_shutdown(void)
{
lib_free(load_save_fliplist_last_dir);
}
| mit |
sarielsaz/sarielsaz | src/pubkey.cpp | 1 | 9188 | // Copyright (c) 2009-2016 The Sarielsaz Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pubkey.h"
#include <secp256k1.h>
#include <secp256k1_recovery.h>
namespace
{
/* Global secp256k1_context object used for verification. */
secp256k1_context* secp256k1_context_verify = nullptr;
} // namespace
/** This function is taken from the libsecp256k1 distribution and implements
* DER parsing for ECDSA signatures, while supporting an arbitrary subset of
* format violations.
*
* Supported violations include negative integers, excessive padding, garbage
* at the end, and overly long length descriptors. This is safe to use in
* Sarielsaz because since the activation of BIP66, signatures are verified to be
* strict DER before being passed to this module, and we know it supports all
* violations present in the blockchain before that point.
*/
static int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
size_t rpos, rlen, spos, slen;
size_t pos = 0;
size_t lenbyte;
unsigned char tmpsig[64] = {0};
int overflow = 0;
/* Hack to initialize sig with a correctly-parsed but invalid signature. */
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
/* Sequence tag byte */
if (pos == inputlen || input[pos] != 0x30) {
return 0;
}
pos++;
/* Sequence length bytes */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
pos += lenbyte;
}
/* Integer tag byte for R */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for R */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
rlen = 0;
while (lenbyte > 0) {
rlen = (rlen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
rlen = lenbyte;
}
if (rlen > inputlen - pos) {
return 0;
}
rpos = pos;
pos += rlen;
/* Integer tag byte for S */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for S */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
slen = 0;
while (lenbyte > 0) {
slen = (slen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
slen = lenbyte;
}
if (slen > inputlen - pos) {
return 0;
}
spos = pos;
/* Ignore leading zeroes in R */
while (rlen > 0 && input[rpos] == 0) {
rlen--;
rpos++;
}
/* Copy R value */
if (rlen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
}
/* Ignore leading zeroes in S */
while (slen > 0 && input[spos] == 0) {
slen--;
spos++;
}
/* Copy S value */
if (slen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 64 - slen, input + spos, slen);
}
if (!overflow) {
overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
if (overflow) {
/* Overwrite the result again with a correctly-parsed but invalid
signature if parsing failed. */
memset(tmpsig, 0, 64);
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
return 1;
}
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_signature sig;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) {
return false;
}
/* libsecp256k1's ECDSA verification requires lower-S signatures, which have
* not historically been enforced in Sarielsaz, so normalize them first. */
secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, &sig, &sig);
return secp256k1_ecdsa_verify(secp256k1_context_verify, &sig, hash.begin(), &pubkey);
}
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.size() != 65)
return false;
int recid = (vchSig[0] - 27) & 3;
bool fComp = ((vchSig[0] - 27) & 4) != 0;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_verify, &sig, &vchSig[1], recid)) {
return false;
}
if (!secp256k1_ecdsa_recover(secp256k1_context_verify, &pubkey, &sig, hash.begin())) {
return false;
}
unsigned char pub[65];
size_t publen = 65;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size());
}
bool CPubKey::Decompress() {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
unsigned char pub[65];
size_t publen = 65;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(begin() + 33 == end());
unsigned char out[64];
BIP32Hash(cc, nChild, *begin(), begin()+1, out);
memcpy(ccChild.begin(), out+32, 32);
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey, out)) {
return false;
}
unsigned char pub[33];
size_t publen = 33;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED);
pubkeyChild.Set(pub, pub + publen);
return true;
}
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, chaincode.begin(), 32);
assert(pubkey.size() == 33);
memcpy(code+41, pubkey.begin(), 33);
}
void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(chaincode.begin(), code+9, 32);
pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = _nChild;
return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode);
}
/* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) {
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) {
return false;
}
return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, nullptr, &sig));
}
/* static */ int ECCVerifyHandle::refcount = 0;
ECCVerifyHandle::ECCVerifyHandle()
{
if (refcount == 0) {
assert(secp256k1_context_verify == nullptr);
secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
assert(secp256k1_context_verify != nullptr);
}
refcount++;
}
ECCVerifyHandle::~ECCVerifyHandle()
{
refcount--;
if (refcount == 0) {
assert(secp256k1_context_verify != nullptr);
secp256k1_context_destroy(secp256k1_context_verify);
secp256k1_context_verify = nullptr;
}
}
| mit |
reuben/freshplayerplugin | src/config_libpdf_backend.c | 2 | 2292 | /*
* Copyright © 2013-2015 Rinat Ibragimov
*
* This file is part of FreshPlayerPlugin.
*
* 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 "config.h"
#include <stdlib.h>
static
const char *
plugin_path_list[] = {
"/opt/google/chrome", // Chrome
"/opt/google/chrome-beta", // Chrome beta
"/opt/google/chrome-unstable", // Chrome unstable
"/usr/lib64/chromium", // Chromium (Slackware)
"/usr/lib/chromium", // Chromium (Slackware)
NULL
};
const char **
fpp_config_get_plugin_path_list(void)
{
return plugin_path_list;
}
const char *
fpp_config_get_default_plugin_version(void)
{
return "1.0.0.0";
}
const char *
fpp_config_get_plugin_name(void)
{
return "libpdf.so renderer backend";
}
const char *
fpp_config_get_default_plugin_descr(void)
{
return "libpdf.so renderer backend";
}
const char *
fpp_config_get_plugin_mime_type(void)
{
return "application/x-freshwrapper-libpdf-so::libpdf renderer";
}
char *
fpp_config_get_plugin_path(void)
{
return NULL;
}
const char *
fpp_config_get_plugin_file_name(void)
{
return "libpdf.so";
}
uintptr_t
fpp_config_plugin_has_manifest(void)
{
return 0;
}
void
fpp_config_detect_plugin_specific_quirks(void)
{
}
| mit |
EliteProgrammersClub/ublab_bot | src/cmds.c | 2 | 88844 | /*
* cmds.c -- handles:
* commands from a user via dcc
* (split in 2, this portion contains no-irc commands)
*
* $Id: cmds.c,v 1.129 2011/02/13 14:19:33 simple Exp $
*/
/*
* Copyright (C) 1997 Robey Pointer
* Copyright (C) 1999 - 2011 Eggheads Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "main.h"
#include "tandem.h"
#include "modules.h"
#include <ctype.h>
extern struct chanset_t *chanset;
extern struct dcc_t *dcc;
extern struct userrec *userlist;
extern tcl_timer_t *timer, *utimer;
extern int dcc_total, remote_boots, backgrd, make_userfile, do_restart,
conmask, require_p, must_be_owner, strict_host;
extern unsigned long otraffic_irc, otraffic_irc_today, itraffic_irc,
itraffic_irc_today, otraffic_bn, otraffic_bn_today,
itraffic_bn, itraffic_bn_today, otraffic_dcc,
otraffic_dcc_today, itraffic_dcc, itraffic_dcc_today,
otraffic_trans, otraffic_trans_today, itraffic_trans,
itraffic_trans_today, otraffic_unknown,
otraffic_unknown_today, itraffic_unknown,
itraffic_unknown_today;
extern Tcl_Interp *interp;
extern char botnetnick[], origbotname[], ver[], network[], owner[], quit_msg[];
extern time_t now, online_since;
extern module_entry *module_list;
static char *btos(unsigned long);
/* Add hostmask to a bot's record if possible.
*/
static int add_bot_hostmask(int idx, char *nick)
{
struct chanset_t *chan;
for (chan = chanset; chan; chan = chan->next)
if (channel_active(chan)) {
memberlist *m = ismember(chan, nick);
if (m) {
char s[UHOSTLEN];
struct userrec *u;
egg_snprintf(s, sizeof s, "%s!%s", m->nick, m->userhost);
u = get_user_by_host(s);
if (u) {
dprintf(idx, "(Can't add hostmask for %s because it matches %s)\n",
nick, u->handle);
return 0;
}
if (strchr("~^+=-", m->userhost[0]))
egg_snprintf(s, sizeof s, "*!%s%s", strict_host ? "?" : "",
m->userhost + 1);
else
egg_snprintf(s, sizeof s, "*!%s", m->userhost);
dprintf(idx, "(Added hostmask for %s from %s)\n", nick, chan->dname);
addhost_by_handle(nick, s);
return 1;
}
}
return 0;
}
static void tell_who(struct userrec *u, int idx, int chan)
{
int i, k, ok = 0, atr = u ? u->flags : 0;
int nicklen;
char format[81];
char s[1024]; /* temp fix - 1.4 has a better one */
if (!chan)
dprintf(idx, "%s (* = owner, + = master, %% = botmaster, @ = op, "
"^ = halfop)\n", BOT_PARTYMEMBS);
else {
simple_sprintf(s, "assoc %d", chan);
if ((Tcl_Eval(interp, s) != TCL_OK) || tcl_resultempty())
dprintf(idx, "%s %s%d: (* = owner, + = master, %% = botmaster, @ = op, "
"^ = halfop)\n", BOT_PEOPLEONCHAN, (chan < GLOBAL_CHANS) ? "" :
"*", chan % GLOBAL_CHANS);
else
dprintf(idx, "%s '%s' (%s%d): (* = owner, + = master, %% = botmaster, @ = op, "
"^ = halfop)\n", BOT_PEOPLEONCHAN, tcl_resultstring(),
(chan < GLOBAL_CHANS) ? "" : "*", chan % GLOBAL_CHANS);
}
/* calculate max nicklen */
nicklen = 0;
for (i = 0; i < dcc_total; i++) {
if (strlen(dcc[i].nick) > nicklen)
nicklen = strlen(dcc[i].nick);
}
if (nicklen < 9)
nicklen = 9;
for (i = 0; i < dcc_total; i++)
if (dcc[i].type == &DCC_CHAT)
if (dcc[i].u.chat->channel == chan) {
if (atr & USER_OWNER) {
egg_snprintf(format, sizeof format, " [%%.2lu] %%c%%-%us %%s",
nicklen);
sprintf(s, format, dcc[i].sock,
(geticon(i) == '-' ? ' ' : geticon(i)), dcc[i].nick,
dcc[i].host);
} else {
egg_snprintf(format, sizeof format, " %%c%%-%us %%s", nicklen);
sprintf(s, format,
(geticon(i) == '-' ? ' ' : geticon(i)),
dcc[i].nick, dcc[i].host);
}
if (atr & USER_MASTER) {
if (dcc[i].u.chat->con_flags)
sprintf(&s[strlen(s)], " (con:%s)",
masktype(dcc[i].u.chat->con_flags));
}
if (now - dcc[i].timeval > 300) {
unsigned long days, hrs, mins;
days = (now - dcc[i].timeval) / 86400;
hrs = ((now - dcc[i].timeval) - (days * 86400)) / 3600;
mins = ((now - dcc[i].timeval) - (hrs * 3600)) / 60;
if (days > 0)
sprintf(&s[strlen(s)], " (idle %lud%luh)", days, hrs);
else if (hrs > 0)
sprintf(&s[strlen(s)], " (idle %luh%lum)", hrs, mins);
else
sprintf(&s[strlen(s)], " (idle %lum)", mins);
}
dprintf(idx, "%s\n", s);
if (dcc[i].u.chat->away != NULL)
dprintf(idx, " AWAY: %s\n", dcc[i].u.chat->away);
}
for (i = 0; i < dcc_total; i++)
if (dcc[i].type == &DCC_BOT) {
if (!ok) {
ok = 1;
dprintf(idx, "Bots connected:\n");
}
egg_strftime(s, 14, "%d %b %H:%M", localtime(&dcc[i].timeval));
if (atr & USER_OWNER) {
egg_snprintf(format, sizeof format,
" [%%.2lu] %%s%%c%%-%us (%%s) %%s\n", nicklen);
dprintf(idx, format, dcc[i].sock,
dcc[i].status & STAT_CALLED ? "<-" : "->",
dcc[i].status & STAT_SHARE ? '+' : ' ', dcc[i].nick, s,
dcc[i].u.bot->version);
} else {
egg_snprintf(format, sizeof format, " %%s%%c%%-%us (%%s) %%s\n",
nicklen);
dprintf(idx, format, dcc[i].status & STAT_CALLED ? "<-" : "->",
dcc[i].status & STAT_SHARE ? '+' : ' ', dcc[i].nick, s,
dcc[i].u.bot->version);
}
}
ok = 0;
for (i = 0; i < dcc_total; i++) {
if ((dcc[i].type == &DCC_CHAT) && (dcc[i].u.chat->channel != chan)) {
if (!ok) {
ok = 1;
dprintf(idx, "Other people on the bot:\n");
}
if (atr & USER_OWNER) {
egg_snprintf(format, sizeof format, " [%%.2lu] %%c%%-%us ", nicklen);
sprintf(s, format, dcc[i].sock,
(geticon(i) == '-' ? ' ' : geticon(i)), dcc[i].nick);
} else {
egg_snprintf(format, sizeof format, " %%c%%-%us ", nicklen);
sprintf(s, format, (geticon(i) == '-' ? ' ' : geticon(i)), dcc[i].nick);
}
if (atr & USER_MASTER) {
if (dcc[i].u.chat->channel < 0)
strcat(s, "(-OFF-) ");
else if (!dcc[i].u.chat->channel)
strcat(s, "(party) ");
else
sprintf(&s[strlen(s)], "(%5d) ", dcc[i].u.chat->channel);
}
strcat(s, dcc[i].host);
if (atr & USER_MASTER) {
if (dcc[i].u.chat->con_flags)
sprintf(&s[strlen(s)], " (con:%s)",
masktype(dcc[i].u.chat->con_flags));
}
if (now - dcc[i].timeval > 300) {
k = (now - dcc[i].timeval) / 60;
if (k < 60)
sprintf(&s[strlen(s)], " (idle %dm)", k);
else
sprintf(&s[strlen(s)], " (idle %dh%dm)", k / 60, k % 60);
}
dprintf(idx, "%s\n", s);
if (dcc[i].u.chat->away != NULL)
dprintf(idx, " AWAY: %s\n", dcc[i].u.chat->away);
}
if ((atr & USER_MASTER) && (dcc[i].type->flags & DCT_SHOWWHO) &&
(dcc[i].type != &DCC_CHAT)) {
if (!ok) {
ok = 1;
dprintf(idx, "Other people on the bot:\n");
}
if (atr & USER_OWNER) {
egg_snprintf(format, sizeof format, " [%%.2lu] %%c%%-%us (files) %%s",
nicklen);
sprintf(s, format,
dcc[i].sock, dcc[i].status & STAT_CHAT ? '+' : ' ',
dcc[i].nick, dcc[i].host);
} else {
egg_snprintf(format, sizeof format, " %%c%%-%us (files) %%s", nicklen);
sprintf(s, format,
dcc[i].status & STAT_CHAT ? '+' : ' ',
dcc[i].nick, dcc[i].host);
}
dprintf(idx, "%s\n", s);
}
}
}
static void cmd_botinfo(struct userrec *u, int idx, char *par)
{
char s[512], s2[32];
struct chanset_t *chan;
time_t now2;
int hr, min;
now2 = now - online_since;
s2[0] = 0;
if (now2 > 86400) {
int days = now2 / 86400;
/* Days */
sprintf(s2, "%d day", days);
if (days >= 2)
strcat(s2, "s");
strcat(s2, ", ");
now2 -= days * 86400;
}
hr = (time_t) ((int) now2 / 3600);
now2 -= (hr * 3600);
min = (time_t) ((int) now2 / 60);
sprintf(&s2[strlen(s2)], "%02d:%02d", (int) hr, (int) min);
putlog(LOG_CMDS, "*", "#%s# botinfo", dcc[idx].nick);
simple_sprintf(s, "%d:%s@%s", dcc[idx].sock, dcc[idx].nick, botnetnick);
botnet_send_infoq(-1, s);
s[0] = 0;
if (module_find("server", 0, 0)) {
for (chan = chanset; chan; chan = chan->next) {
if (!channel_secret(chan)) {
if ((strlen(s) + strlen(chan->dname) + strlen(network)
+ strlen(botnetnick) + strlen(ver) + 1) >= 490) {
strcat(s, "++ ");
break; /* yeesh! */
}
strcat(s, chan->dname);
strcat(s, ", ");
}
}
if (s[0]) {
s[strlen(s) - 2] = 0;
dprintf(idx, "*** [%s] %s <%s> (%s) [UP %s]\n", botnetnick,
ver, network, s, s2);
} else
dprintf(idx, "*** [%s] %s <%s> (%s) [UP %s]\n", botnetnick,
ver, network, BOT_NOCHANNELS, s2);
} else
dprintf(idx, "*** [%s] %s <NO_IRC> [UP %s]\n", botnetnick, ver, s2);
}
static void cmd_whom(struct userrec *u, int idx, char *par)
{
if (par[0] == '*') {
putlog(LOG_CMDS, "*", "#%s# whom %s", dcc[idx].nick, par);
answer_local_whom(idx, -1);
return;
} else if (dcc[idx].u.chat->channel < 0) {
dprintf(idx, "You have chat turned off.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# whom %s", dcc[idx].nick, par);
if (!par[0]) {
answer_local_whom(idx, dcc[idx].u.chat->channel);
} else {
int chan = -1;
if ((par[0] < '0') || (par[0] > '9')) {
Tcl_SetVar(interp, "_chan", par, 0);
if ((Tcl_VarEval(interp, "assoc ", "$_chan", NULL) == TCL_OK) &&
!tcl_resultempty()) {
chan = tcl_resultint();
}
if (chan <= 0) {
dprintf(idx, "No such channel exists.\n");
return;
}
} else
chan = atoi(par);
if ((chan < 0) || (chan >= GLOBAL_CHANS)) {
dprintf(idx, "Channel number out of range: must be between 0 and %d."
"\n", GLOBAL_CHANS);
return;
}
answer_local_whom(idx, chan);
}
}
static void cmd_me(struct userrec *u, int idx, char *par)
{
int i;
if (dcc[idx].u.chat->channel < 0) {
dprintf(idx, "You have chat turned off.\n");
return;
}
if (!par[0]) {
dprintf(idx, "Usage: me <action>\n");
return;
}
if (dcc[idx].u.chat->away != NULL)
not_away(idx);
for (i = 0; i < dcc_total; i++)
if ((dcc[i].type->flags & DCT_CHAT) &&
(dcc[i].u.chat->channel == dcc[idx].u.chat->channel) &&
((i != idx) || (dcc[i].status & STAT_ECHO)))
dprintf(i, "* %s %s\n", dcc[idx].nick, par);
botnet_send_act(idx, botnetnick, dcc[idx].nick,
dcc[idx].u.chat->channel, par);
check_tcl_act(dcc[idx].nick, dcc[idx].u.chat->channel, par);
}
static void cmd_motd(struct userrec *u, int idx, char *par)
{
int i;
if (par[0]) {
putlog(LOG_CMDS, "*", "#%s# motd %s", dcc[idx].nick, par);
if (!egg_strcasecmp(par, botnetnick))
show_motd(idx);
else {
i = nextbot(par);
if (i < 0)
dprintf(idx, "That bot isn't connected.\n");
else {
char x[40];
simple_sprintf(x, "%s%d:%s@%s",
(u->flags & USER_HIGHLITE) ?
((dcc[idx].status & STAT_TELNET) ? "#" : "!") : "",
dcc[idx].sock, dcc[idx].nick, botnetnick);
botnet_send_motd(i, x, par);
}
}
} else {
putlog(LOG_CMDS, "*", "#%s# motd", dcc[idx].nick);
show_motd(idx);
}
}
static void cmd_away(struct userrec *u, int idx, char *par)
{
if (strlen(par) > 60)
par[60] = 0;
set_away(idx, par);
}
static void cmd_back(struct userrec *u, int idx, char *par)
{
not_away(idx);
}
static void cmd_newpass(struct userrec *u, int idx, char *par)
{
char *new;
if (!par[0]) {
dprintf(idx, "Usage: newpass <newpassword>\n");
return;
}
new = newsplit(&par);
if (strlen(new) > 16)
new[16] = 0;
if (strlen(new) < 6) {
dprintf(idx, "Please use at least 6 characters.\n");
return;
}
set_user(&USERENTRY_PASS, u, new);
putlog(LOG_CMDS, "*", "#%s# newpass...", dcc[idx].nick);
dprintf(idx, "Changed password to '%s'.\n", new);
}
static void cmd_bots(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# bots", dcc[idx].nick);
tell_bots(idx);
}
static void cmd_bottree(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# bottree", dcc[idx].nick);
tell_bottree(idx, 0);
}
static void cmd_vbottree(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# vbottree", dcc[idx].nick);
tell_bottree(idx, 1);
}
static void cmd_rehelp(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# rehelp", dcc[idx].nick);
dprintf(idx, "Reload help cache...\n");
reload_help_data();
}
static void cmd_help(struct userrec *u, int idx, char *par)
{
struct flag_record fr = { FR_GLOBAL | FR_CHAN, 0, 0, 0, 0, 0 };
get_user_flagrec(u, &fr, dcc[idx].u.chat->con_chan);
if (par[0]) {
putlog(LOG_CMDS, "*", "#%s# help %s", dcc[idx].nick, par);
if (!strcmp(par, "all"))
tellallhelp(idx, "all", &fr);
else if (strchr(par, '*') || strchr(par, '?')) {
char *p = par;
/* Check if the search pattern only consists of '*' and/or '?'
* If it does, show help for "all" instead of listing all help
* entries.
*/
for (p = par; *p && ((*p == '*') || (*p == '?')); p++);
if (*p)
tellwildhelp(idx, par, &fr);
else
tellallhelp(idx, "all", &fr);
} else
tellhelp(idx, par, &fr, 0);
} else {
putlog(LOG_CMDS, "*", "#%s# help", dcc[idx].nick);
if (glob_op(fr) || glob_botmast(fr) || chan_op(fr))
tellhelp(idx, "help", &fr, 0);
else
tellhelp(idx, "partyline", &fr, 0);
}
}
static void cmd_addlog(struct userrec *u, int idx, char *par)
{
if (!par[0]) {
dprintf(idx, "Usage: addlog <message>\n");
return;
}
dprintf(idx, "Placed entry in the log file.\n");
putlog(LOG_MISC, "*", "%s: %s", dcc[idx].nick, par);
}
static void cmd_who(struct userrec *u, int idx, char *par)
{
int i;
if (par[0]) {
if (dcc[idx].u.chat->channel < 0) {
dprintf(idx, "You have chat turned off.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# who %s", dcc[idx].nick, par);
if (!egg_strcasecmp(par, botnetnick))
tell_who(u, idx, dcc[idx].u.chat->channel);
else {
i = nextbot(par);
if (i < 0) {
dprintf(idx, "That bot isn't connected.\n");
} else if (dcc[idx].u.chat->channel >= GLOBAL_CHANS)
dprintf(idx, "You are on a local channel.\n");
else {
char s[40];
simple_sprintf(s, "%d:%s@%s", dcc[idx].sock, dcc[idx].nick, botnetnick);
botnet_send_who(i, s, par, dcc[idx].u.chat->channel);
}
}
} else {
putlog(LOG_CMDS, "*", "#%s# who", dcc[idx].nick);
if (dcc[idx].u.chat->channel < 0)
tell_who(u, idx, 0);
else
tell_who(u, idx, dcc[idx].u.chat->channel);
}
}
static void cmd_whois(struct userrec *u, int idx, char *par)
{
if (!par[0]) {
dprintf(idx, "Usage: whois <handle>\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# whois %s", dcc[idx].nick, par);
tell_user_ident(idx, par, u ? (u->flags & USER_MASTER) : 0);
}
static void cmd_match(struct userrec *u, int idx, char *par)
{
int start = 1, limit = 20;
char *s, *s1, *chname;
if (!par[0]) {
dprintf(idx, "Usage: match <nick/host> [[skip] count]\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# match %s", dcc[idx].nick, par);
s = newsplit(&par);
if (strchr(CHANMETA, par[0]) != NULL)
chname = newsplit(&par);
else
chname = "";
if (atoi(par) > 0) {
s1 = newsplit(&par);
if (atoi(par) > 0) {
start = atoi(s1);
limit = atoi(par);
} else
limit = atoi(s1);
}
tell_users_match(idx, s, start, limit, u ? (u->flags & USER_MASTER) : 0,
chname);
}
static void cmd_uptime(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# uptime", dcc[idx].nick);
tell_verbose_uptime(idx);
}
static void cmd_status(struct userrec *u, int idx, char *par)
{
int atr = u ? u->flags : 0;
if (!egg_strcasecmp(par, "all")) {
if (!(atr & USER_MASTER)) {
dprintf(idx, "You do not have Bot Master privileges.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# status all", dcc[idx].nick);
tell_verbose_status(idx);
tell_mem_status_dcc(idx);
dprintf(idx, "\n");
tell_settings(idx);
do_module_report(idx, 1, NULL);
} else {
putlog(LOG_CMDS, "*", "#%s# status", dcc[idx].nick);
tell_verbose_status(idx);
tell_mem_status_dcc(idx);
do_module_report(idx, 0, NULL);
}
}
static void cmd_dccstat(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# dccstat", dcc[idx].nick);
tell_dcc(idx);
}
static void cmd_boot(struct userrec *u, int idx, char *par)
{
int i, files = 0, ok = 0;
char *who;
struct userrec *u2;
if (!par[0]) {
dprintf(idx, "Usage: boot nick[@bot]\n");
return;
}
who = newsplit(&par);
if (strchr(who, '@') != NULL) {
char whonick[HANDLEN + 1];
splitcn(whonick, who, '@', HANDLEN + 1);
if (!egg_strcasecmp(who, botnetnick)) {
cmd_boot(u, idx, whonick);
return;
}
if (remote_boots > 0) {
i = nextbot(who);
if (i < 0) {
dprintf(idx, "No such bot connected.\n");
return;
}
botnet_send_reject(i, dcc[idx].nick, botnetnick, whonick,
who, par[0] ? par : dcc[idx].nick);
putlog(LOG_BOTS, "*", "#%s# boot %s@%s (%s)", dcc[idx].nick, whonick,
who, par[0] ? par : dcc[idx].nick);
} else
dprintf(idx, "Remote boots are disabled here.\n");
return;
}
for (i = 0; i < dcc_total; i++)
if (!egg_strcasecmp(dcc[i].nick, who) && !ok &&
(dcc[i].type->flags & DCT_CANBOOT)) {
u2 = get_user_by_handle(userlist, dcc[i].nick);
if (u2 && (u2->flags & USER_OWNER) &&
egg_strcasecmp(dcc[idx].nick, who)) {
dprintf(idx, "You can't boot a bot owner.\n");
return;
}
if (u2 && (u2->flags & USER_MASTER) && !(u && (u->flags & USER_MASTER))) {
dprintf(idx, "You can't boot a bot master.\n");
return;
}
files = (dcc[i].type->flags & DCT_FILES);
if (files)
dprintf(idx, "Booted %s from the file area.\n", dcc[i].nick);
else
dprintf(idx, "Booted %s from the party line.\n", dcc[i].nick);
putlog(LOG_CMDS, "*", "#%s# boot %s %s", dcc[idx].nick, who, par);
do_boot(i, dcc[idx].nick, par);
ok = 1;
}
if (!ok)
dprintf(idx, "Who? No such person on the party line.\n");
}
static void cmd_console(struct userrec *u, int idx, char *par)
{
char *nick, s[2], s1[512];
int dest = 0, i, ok = 0, pls;
struct flag_record fr = { FR_GLOBAL | FR_CHAN, 0, 0, 0, 0, 0 };
module_entry *me;
if (!par[0]) {
dprintf(idx, "Your console is %s: %s (%s).\n",
dcc[idx].u.chat->con_chan,
masktype(dcc[idx].u.chat->con_flags),
maskname(dcc[idx].u.chat->con_flags));
return;
}
get_user_flagrec(u, &fr, dcc[idx].u.chat->con_chan);
strcpy(s1, par);
nick = newsplit(&par);
/* Don't remove '+' as someone couldn't have '+' in CHANMETA cause
* he doesn't use IRCnet ++rtc.
*/
if (nick[0] && !strchr(CHANMETA "+-*", nick[0]) && glob_master(fr)) {
for (i = 0; i < dcc_total; i++)
if (!egg_strcasecmp(nick, dcc[i].nick) &&
(dcc[i].type == &DCC_CHAT) && (!ok)) {
ok = 1;
dest = i;
}
if (!ok) {
dprintf(idx, "No such user on the party line!\n");
return;
}
nick[0] = 0;
} else
dest = idx;
if (!nick[0])
nick = newsplit(&par);
/* Consider modeless channels, starting with '+' */
if ((nick[0] == '+' && findchan_by_dname(nick)) ||
(nick[0] != '+' && strchr(CHANMETA "*", nick[0]))) {
if (strcmp(nick, "*") && !findchan_by_dname(nick)) {
dprintf(idx, "Invalid console channel: %s.\n", nick);
return;
}
get_user_flagrec(u, &fr, nick);
if (!chan_op(fr) && !(glob_op(fr) && !chan_deop(fr))) {
dprintf(idx, "You don't have op or master access to channel %s.\n",
nick);
return;
}
strncpyz(dcc[dest].u.chat->con_chan, nick, 81);
nick[0] = 0;
if (dest != idx)
get_user_flagrec(dcc[dest].user, &fr, dcc[dest].u.chat->con_chan);
}
if (!nick[0])
nick = newsplit(&par);
pls = 1;
if (nick[0]) {
if ((nick[0] != '+') && (nick[0] != '-'))
dcc[dest].u.chat->con_flags = 0;
for (; *nick; nick++) {
if (*nick == '+')
pls = 1;
else if (*nick == '-')
pls = 0;
else {
s[0] = *nick;
s[1] = 0;
if (pls)
dcc[dest].u.chat->con_flags |= logmodes(s);
else
dcc[dest].u.chat->con_flags &= ~logmodes(s);
}
}
}
dcc[dest].u.chat->con_flags = check_conflags(&fr,
dcc[dest].u.chat->con_flags);
putlog(LOG_CMDS, "*", "#%s# console %s", dcc[idx].nick, s1);
if (dest == idx) {
dprintf(idx, "Set your console to %s: %s (%s).\n",
dcc[idx].u.chat->con_chan,
masktype(dcc[idx].u.chat->con_flags),
maskname(dcc[idx].u.chat->con_flags));
} else {
dprintf(idx, "Set console of %s to %s: %s (%s).\n", dcc[dest].nick,
dcc[dest].u.chat->con_chan,
masktype(dcc[dest].u.chat->con_flags),
maskname(dcc[dest].u.chat->con_flags));
dprintf(dest, "%s set your console to %s: %s (%s).\n", dcc[idx].nick,
dcc[dest].u.chat->con_chan,
masktype(dcc[dest].u.chat->con_flags),
maskname(dcc[dest].u.chat->con_flags));
}
/* New style autosave -- drummer,07/25/1999 */
if ((me = module_find("console", 1, 1))) {
Function *func = me->funcs;
(func[CONSOLE_DOSTORE]) (dest);
}
}
static void cmd_pls_bot(struct userrec *u, int idx, char *par)
{
char *handle, *addr, *p, *q, *host;
struct userrec *u1;
struct bot_addr *bi;
if (!par[0]) {
dprintf(idx, "Usage: +bot <handle> [address[:telnet-port[/relay-port]]] "
"[host]\n");
return;
}
handle = newsplit(&par);
addr = newsplit(&par);
host = newsplit(&par);
if (strlen(handle) > HANDLEN)
handle[HANDLEN] = 0;
if (get_user_by_handle(userlist, handle)) {
dprintf(idx, "Someone already exists by that name.\n");
return;
}
if (strchr(BADHANDCHARS, handle[0]) != NULL) {
dprintf(idx, "You can't start a botnick with '%c'.\n", handle[0]);
return;
}
if (strlen(addr) > 60)
addr[60] = 0;
putlog(LOG_CMDS, "*", "#%s# +bot %s%s%s%s%s", dcc[idx].nick, handle,
addr[0] ? " " : "", addr, host[0] ? " " : "", host);
userlist = adduser(userlist, handle, "none", "-", USER_BOT);
u1 = get_user_by_handle(userlist, handle);
bi = user_malloc(sizeof(struct bot_addr));
q = strchr(addr, ':');
if (!q) {
bi->address = user_malloc(strlen(addr) + 1);
strcpy(bi->address, addr);
bi->telnet_port = 3333;
bi->relay_port = 3333;
} else {
bi->address = user_malloc(q - addr + 1);
strncpy(bi->address, addr, q - addr);
bi->address[q - addr] = 0;
p = q + 1;
bi->telnet_port = atoi(p);
q = strchr(p, '/');
if (!q) {
bi->relay_port = bi->telnet_port;
} else {
bi->relay_port = atoi(q + 1);
}
}
set_user(&USERENTRY_BOTADDR, u1, bi);
if (addr[0]) {
dprintf(idx, "Added bot '%s' with address '%s' and %s%s%s.\n", handle,
addr, host[0] ? "hostmask '" : "no hostmask", host[0] ? host : "",
host[0] ? "'" : "");
} else{
dprintf(idx, "Added bot '%s' with no address and %s%s%s.\n", handle,
host[0] ? "hostmask '" : "no hostmask", host[0] ? host : "",
host[0] ? "'" : "");
}
if (host[0]) {
addhost_by_handle(handle, host);
} else if (!add_bot_hostmask(idx, handle)) {
dprintf(idx, "You'll want to add a hostmask if this bot will ever be on "
"any channels that I'm on.\n");
}
}
static void cmd_chhandle(struct userrec *u, int idx, char *par)
{
char hand[HANDLEN + 1], newhand[HANDLEN + 1];
int i, atr = u ? u->flags : 0, atr2;
struct userrec *u2;
strncpyz(hand, newsplit(&par), sizeof hand);
strncpyz(newhand, newsplit(&par), sizeof newhand);
if (!hand[0] || !newhand[0]) {
dprintf(idx, "Usage: chhandle <oldhandle> <newhandle>\n");
return;
}
for (i = 0; i < strlen(newhand); i++)
if (((unsigned char) newhand[i] <= 32) || (newhand[i] == '@'))
newhand[i] = '?';
if (strchr(BADHANDCHARS, newhand[0]) != NULL)
dprintf(idx, "Bizarre quantum forces prevent nicknames from starting with "
"'%c'.\n", newhand[0]);
else if (get_user_by_handle(userlist, newhand) &&
egg_strcasecmp(hand, newhand))
dprintf(idx, "Somebody is already using %s.\n", newhand);
else {
u2 = get_user_by_handle(userlist, hand);
atr2 = u2 ? u2->flags : 0;
if ((atr & USER_BOTMAST) && !(atr & USER_MASTER) && !(atr2 & USER_BOT))
dprintf(idx, "You can't change handles for non-bots.\n");
else if ((bot_flags(u2) & BOT_SHARE) && !(atr & USER_OWNER))
dprintf(idx, "You can't change share bot's nick.\n");
else if ((atr2 & USER_OWNER) && !(atr & USER_OWNER) &&
egg_strcasecmp(dcc[idx].nick, hand))
dprintf(idx, "You can't change a bot owner's handle.\n");
else if (isowner(hand) && egg_strcasecmp(dcc[idx].nick, hand))
dprintf(idx, "You can't change a permanent bot owner's handle.\n");
else if (!egg_strcasecmp(newhand, botnetnick) && (!(atr2 & USER_BOT) ||
nextbot(hand) != -1))
dprintf(idx, "Hey! That's MY name!\n");
else if (change_handle(u2, newhand)) {
putlog(LOG_CMDS, "*", "#%s# chhandle %s %s", dcc[idx].nick,
hand, newhand);
dprintf(idx, "Changed.\n");
} else
dprintf(idx, "Failed.\n");
}
}
static void cmd_handle(struct userrec *u, int idx, char *par)
{
char oldhandle[HANDLEN + 1], newhandle[HANDLEN + 1];
int i;
strncpyz(newhandle, newsplit(&par), sizeof newhandle);
if (!newhandle[0]) {
dprintf(idx, "Usage: handle <new-handle>\n");
return;
}
for (i = 0; i < strlen(newhandle); i++)
if (((unsigned char) newhandle[i] <= 32) || (newhandle[i] == '@'))
newhandle[i] = '?';
if (strchr(BADHANDCHARS, newhandle[0]) != NULL)
dprintf(idx,
"Bizarre quantum forces prevent handle from starting with '%c'.\n",
newhandle[0]);
else if (get_user_by_handle(userlist, newhandle) &&
egg_strcasecmp(dcc[idx].nick, newhandle))
dprintf(idx, "Somebody is already using %s.\n", newhandle);
else if (!egg_strcasecmp(newhandle, botnetnick))
dprintf(idx, "Hey! That's MY name!\n");
else {
strncpyz(oldhandle, dcc[idx].nick, sizeof oldhandle);
if (change_handle(u, newhandle)) {
putlog(LOG_CMDS, "*", "#%s# handle %s", oldhandle, newhandle);
dprintf(idx, "Okay, changed.\n");
} else
dprintf(idx, "Failed.\n");
}
}
static void cmd_chpass(struct userrec *u, int idx, char *par)
{
char *handle, *new;
int atr = u ? u->flags : 0, l;
if (!par[0])
dprintf(idx, "Usage: chpass <handle> [password]\n");
else {
handle = newsplit(&par);
u = get_user_by_handle(userlist, handle);
if (!u)
dprintf(idx, "No such user.\n");
else if ((atr & USER_BOTMAST) && !(atr & USER_MASTER) &&
!(u->flags & USER_BOT))
dprintf(idx, "You can't change passwords for non-bots.\n");
else if ((bot_flags(u) & BOT_SHARE) && !(atr & USER_OWNER))
dprintf(idx, "You can't change a share bot's password.\n");
else if ((u->flags & USER_OWNER) && !(atr & USER_OWNER) &&
egg_strcasecmp(handle, dcc[idx].nick))
dprintf(idx, "You can't change a bot owner's password.\n");
else if (isowner(handle) && egg_strcasecmp(dcc[idx].nick, handle))
dprintf(idx, "You can't change a permanent bot owner's password.\n");
else if (!par[0]) {
putlog(LOG_CMDS, "*", "#%s# chpass %s [nothing]", dcc[idx].nick, handle);
set_user(&USERENTRY_PASS, u, NULL);
dprintf(idx, "Removed password.\n");
} else {
l = strlen(new = newsplit(&par));
if (l > 16)
new[16] = 0;
if (l < 6)
dprintf(idx, "Please use at least 6 characters.\n");
else {
set_user(&USERENTRY_PASS, u, new);
putlog(LOG_CMDS, "*", "#%s# chpass %s [something]", dcc[idx].nick,
handle);
dprintf(idx, "Changed password.\n");
}
}
}
}
static void cmd_chaddr(struct userrec *u, int idx, char *par)
{
int telnet_port = 3333, relay_port = 3333;
char *handle, *addr, *p, *q;
struct bot_addr *bi;
struct userrec *u1;
handle = newsplit(&par);
if (!par[0]) {
dprintf(idx, "Usage: chaddr <botname> "
"<address[:telnet-port[/relay-port]]>\n");
return;
}
addr = newsplit(&par);
if (strlen(addr) > UHOSTMAX)
addr[UHOSTMAX] = 0;
u1 = get_user_by_handle(userlist, handle);
if (!u1 || !(u1->flags & USER_BOT)) {
dprintf(idx, "This command is only useful for tandem bots.\n");
return;
}
if ((bot_flags(u1) & BOT_SHARE) && (!u || !(u->flags & USER_OWNER))) {
dprintf(idx, "You can't change a share bot's address.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# chaddr %s %s", dcc[idx].nick, handle, addr);
dprintf(idx, "Changed bot's address.\n");
bi = (struct bot_addr *) get_user(&USERENTRY_BOTADDR, u1);
if (bi) {
telnet_port = bi->telnet_port;
relay_port = bi->relay_port;
}
bi = user_malloc(sizeof(struct bot_addr));
q = strchr(addr, ':');
if (!q) {
bi->address = user_malloc(strlen(addr) + 1);
strcpy(bi->address, addr);
bi->telnet_port = telnet_port;
bi->relay_port = relay_port;
} else {
bi->address = user_malloc(q - addr + 1);
strncpyz(bi->address, addr, q - addr + 1);
p = q + 1;
bi->telnet_port = atoi(p);
q = strchr(p, '/');
if (!q) {
bi->relay_port = bi->telnet_port;
} else {
bi->relay_port = atoi(q + 1);
}
}
set_user(&USERENTRY_BOTADDR, u1, bi);
}
static void cmd_comment(struct userrec *u, int idx, char *par)
{
char *handle;
struct userrec *u1;
handle = newsplit(&par);
if (!par[0]) {
dprintf(idx, "Usage: comment <handle> <newcomment>\n");
return;
}
u1 = get_user_by_handle(userlist, handle);
if (!u1) {
dprintf(idx, "No such user!\n");
return;
}
if ((u1->flags & USER_OWNER) && !(u && (u->flags & USER_OWNER)) &&
egg_strcasecmp(handle, dcc[idx].nick)) {
dprintf(idx, "You can't change comment on a bot owner.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# comment %s %s", dcc[idx].nick, handle, par);
if (!egg_strcasecmp(par, "none")) {
dprintf(idx, "Okay, comment blanked.\n");
set_user(&USERENTRY_COMMENT, u1, NULL);
return;
}
dprintf(idx, "Changed comment.\n");
set_user(&USERENTRY_COMMENT, u1, par);
}
static void cmd_restart(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# restart", dcc[idx].nick);
if (!backgrd) {
dprintf(idx, "You cannot .restart a bot when running -n (due to Tcl).\n");
return;
}
dprintf(idx, "Restarting.\n");
if (make_userfile) {
putlog(LOG_MISC, "*", "Uh, guess you don't need to create a new userfile.");
make_userfile = 0;
}
write_userfile(-1);
putlog(LOG_MISC, "*", "Restarting ...");
wipe_timers(interp, &utimer);
wipe_timers(interp, &timer);
do_restart = idx;
}
static void cmd_rehash(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# rehash", dcc[idx].nick);
dprintf(idx, "Rehashing.\n");
if (make_userfile) {
putlog(LOG_MISC, "*", "Uh, guess you don't need to create a new userfile.");
make_userfile = 0;
}
write_userfile(-1);
putlog(LOG_MISC, "*", "Rehashing ...");
do_restart = -2;
}
static void cmd_reload(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# reload", dcc[idx].nick);
dprintf(idx, "Reloading user file...\n");
reload();
}
void cmd_die(struct userrec *u, int idx, char *par)
{
char s1[1024], s2[1024];
putlog(LOG_CMDS, "*", "#%s# die %s", dcc[idx].nick, par);
if (par[0]) {
egg_snprintf(s1, sizeof s1, "BOT SHUTDOWN (%s: %s)", dcc[idx].nick, par);
egg_snprintf(s2, sizeof s2, "DIE BY %s!%s (%s)", dcc[idx].nick,
dcc[idx].host, par);
strncpyz(quit_msg, par, 1024);
} else {
egg_snprintf(s1, sizeof s1, "BOT SHUTDOWN (Authorized by %s)",
dcc[idx].nick);
egg_snprintf(s2, sizeof s2, "DIE BY %s!%s (request)", dcc[idx].nick,
dcc[idx].host);
strncpyz(quit_msg, dcc[idx].nick, 1024);
}
kill_bot(s1, s2);
}
static void cmd_debug(struct userrec *u, int idx, char *par)
{
if (!egg_strcasecmp(par, "help")) {
putlog(LOG_CMDS, "*", "#%s# debug help", dcc[idx].nick);
debug_help(idx);
} else {
putlog(LOG_CMDS, "*", "#%s# debug", dcc[idx].nick);
debug_mem_to_dcc(idx);
}
}
static void cmd_simul(struct userrec *u, int idx, char *par)
{
char *nick;
int i, ok = 0;
nick = newsplit(&par);
if (!par[0]) {
dprintf(idx, "Usage: simul <hand> <text>\n");
return;
}
if (isowner(nick)) {
dprintf(idx, "Unable to '.simul' permanent owners.\n");
return;
}
for (i = 0; i < dcc_total; i++)
if (!egg_strcasecmp(nick, dcc[i].nick) && !ok &&
(dcc[i].type->flags & DCT_SIMUL)) {
putlog(LOG_CMDS, "*", "#%s# simul %s %s", dcc[idx].nick, nick, par);
if (dcc[i].type && dcc[i].type->activity) {
dcc[i].type->activity(i, par, strlen(par));
ok = 1;
}
}
if (!ok)
dprintf(idx, "No such user on the party line.\n");
}
static void cmd_link(struct userrec *u, int idx, char *par)
{
char *s;
int i;
if (!par[0]) {
dprintf(idx, "Usage: link [some-bot] <new-bot>\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# link %s", dcc[idx].nick, par);
s = newsplit(&par);
if (!par[0] || !egg_strcasecmp(par, botnetnick))
botlink(dcc[idx].nick, idx, s);
else {
char x[40];
i = nextbot(s);
if (i < 0) {
dprintf(idx, "No such bot online.\n");
return;
}
simple_sprintf(x, "%d:%s@%s", dcc[idx].sock, dcc[idx].nick, botnetnick);
botnet_send_link(i, x, s, par);
}
}
static void cmd_unlink(struct userrec *u, int idx, char *par)
{
int i;
char *bot;
if (!par[0]) {
dprintf(idx, "Usage: unlink <bot> [reason]\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# unlink %s", dcc[idx].nick, par);
bot = newsplit(&par);
i = nextbot(bot);
if (i < 0) {
botunlink(idx, bot, par, dcc[idx].nick);
return;
}
/* If we're directly connected to that bot, just do it
* (is nike gunna sue?)
*/
if (!egg_strcasecmp(dcc[i].nick, bot))
botunlink(idx, bot, par, dcc[i].nick);
else {
char x[40];
simple_sprintf(x, "%d:%s@%s", dcc[idx].sock, dcc[idx].nick, botnetnick);
botnet_send_unlink(i, x, lastbot(bot), bot, par);
}
}
static void cmd_relay(struct userrec *u, int idx, char *par)
{
if (!par[0]) {
dprintf(idx, "Usage: relay <bot>\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# relay %s", dcc[idx].nick, par);
tandem_relay(idx, par, 0);
}
static void cmd_save(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# save", dcc[idx].nick);
dprintf(idx, "Saving user file...\n");
write_userfile(-1);
}
static void cmd_backup(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# backup", dcc[idx].nick);
dprintf(idx, "Backing up the channel & user files...\n");
call_hook(HOOK_BACKUP);
}
static void cmd_trace(struct userrec *u, int idx, char *par)
{
int i;
char x[NOTENAMELEN + 11], y[11];
if (!par[0]) {
dprintf(idx, "Usage: trace <botname>\n");
return;
}
if (!egg_strcasecmp(par, botnetnick)) {
dprintf(idx, "That's me! Hiya! :)\n");
return;
}
i = nextbot(par);
if (i < 0) {
dprintf(idx, "Unreachable bot.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# trace %s", dcc[idx].nick, par);
simple_sprintf(x, "%d:%s@%s", dcc[idx].sock, dcc[idx].nick, botnetnick);
simple_sprintf(y, ":%d", now);
botnet_send_trace(i, x, par, y);
}
static void cmd_binds(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# binds %s", dcc[idx].nick, par);
tell_binds(idx, par);
}
static void cmd_banner(struct userrec *u, int idx, char *par)
{
char s[1024];
int i;
if (!par[0]) {
dprintf(idx, "Usage: banner <message>\n");
return;
}
simple_sprintf(s, "\007### Botwide: [%s] %s\n", dcc[idx].nick, par);
for (i = 0; i < dcc_total; i++)
if (dcc[i].type->flags & DCT_MASTER)
dprintf(i, "%s", s);
}
/* After messing with someone's user flags, make sure the dcc-chat flags
* are set correctly.
*/
int check_dcc_attrs(struct userrec *u, int oatr)
{
int i, stat;
struct flag_record fr = { FR_GLOBAL | FR_CHAN, 0, 0, 0, 0, 0 };
if (!u)
return 0;
/* Make sure default owners are +n */
if (isowner(u->handle)) {
u->flags = sanity_check(u->flags | USER_OWNER);
}
for (i = 0; i < dcc_total; i++) {
if ((dcc[i].type->flags & DCT_MASTER) &&
(!egg_strcasecmp(u->handle, dcc[i].nick))) {
stat = dcc[i].status;
if ((dcc[i].type == &DCC_CHAT) &&
((u->flags & (USER_OP | USER_MASTER | USER_OWNER | USER_BOTMAST)) !=
(oatr & (USER_OP | USER_MASTER | USER_OWNER | USER_BOTMAST)))) {
botnet_send_join_idx(i, -1);
}
if ((oatr & USER_MASTER) && !(u->flags & USER_MASTER)) {
dprintf(i, "*** POOF! ***\n");
dprintf(i, "You are no longer a master on this bot.\n");
}
if (!(oatr & USER_MASTER) && (u->flags & USER_MASTER)) {
dcc[i].u.chat->con_flags |= conmask;
dprintf(i, "*** POOF! ***\n");
dprintf(i, "You are now a master on this bot.\n");
}
if (!(oatr & USER_BOTMAST) && (u->flags & USER_BOTMAST)) {
dprintf(i, "### POOF! ###\n");
dprintf(i, "You are now a botnet master on this bot.\n");
}
if ((oatr & USER_BOTMAST) && !(u->flags & USER_BOTMAST)) {
dprintf(i, "### POOF! ###\n");
dprintf(i, "You are no longer a botnet master on this bot.\n");
}
if (!(oatr & USER_OWNER) && (u->flags & USER_OWNER)) {
dprintf(i, "@@@ POOF! @@@\n");
dprintf(i, "You are now an OWNER of this bot.\n");
}
if ((oatr & USER_OWNER) && !(u->flags & USER_OWNER)) {
dprintf(i, "@@@ POOF! @@@\n");
dprintf(i, "You are no longer an owner of this bot.\n");
}
get_user_flagrec(u, &fr, dcc[i].u.chat->con_chan);
dcc[i].u.chat->con_flags = check_conflags(&fr,
dcc[i].u.chat->con_flags);
if ((stat & STAT_PARTY) && (u->flags & USER_OP))
stat &= ~STAT_PARTY;
if (!(stat & STAT_PARTY) && !(u->flags & USER_OP) &&
!(u->flags & USER_MASTER))
stat |= STAT_PARTY;
if ((stat & STAT_CHAT) && !(u->flags & USER_PARTY) &&
!(u->flags & USER_MASTER) && (!(u->flags & USER_OP) || require_p))
stat &= ~STAT_CHAT;
if ((dcc[i].type->flags & DCT_FILES) && !(stat & STAT_CHAT) &&
((u->flags & USER_MASTER) || (u->flags & USER_PARTY) ||
((u->flags & USER_OP) && !require_p)))
stat |= STAT_CHAT;
dcc[i].status = stat;
/* Check if they no longer have access to wherever they are.
*
* NOTE: DON'T kick someone off the party line just cuz they lost +p
* (pinvite script removes +p after 5 mins automatically)
*/
if ((dcc[i].type->flags & DCT_FILES) && !(u->flags & USER_XFER) &&
!(u->flags & USER_MASTER)) {
dprintf(i, "-+- POOF! -+-\n");
dprintf(i, "You no longer have file area access.\n\n");
putlog(LOG_MISC, "*", "DCC user [%s]%s removed from file system",
dcc[i].nick, dcc[i].host);
if (dcc[i].status & STAT_CHAT) {
struct chat_info *ci;
ci = dcc[i].u.file->chat;
nfree(dcc[i].u.file);
dcc[i].u.chat = ci;
dcc[i].status &= (~STAT_CHAT);
dcc[i].type = &DCC_CHAT;
if (dcc[i].u.chat->channel >= 0) {
chanout_but(-1, dcc[i].u.chat->channel,
"*** %s has returned.\n", dcc[i].nick);
if (dcc[i].u.chat->channel < GLOBAL_CHANS)
botnet_send_join_idx(i, -1);
}
} else {
killsock(dcc[i].sock);
lostdcc(i);
}
}
}
if (dcc[i].type == &DCC_BOT && !egg_strcasecmp(u->handle, dcc[i].nick)) {
if ((dcc[i].status & STAT_LEAF) && !(bot_flags(u) & BOT_LEAF))
dcc[i].status &= ~(STAT_LEAF | STAT_WARNED);
if (!(dcc[i].status & STAT_LEAF) && (bot_flags(u) & BOT_LEAF))
dcc[i].status |= STAT_LEAF;
}
}
return u->flags;
}
int check_dcc_chanattrs(struct userrec *u, char *chname, int chflags,
int ochatr)
{
int i, found = 0;
struct flag_record fr = { FR_CHAN, 0, 0, 0, 0, 0 };
struct chanset_t *chan;
if (!u)
return 0;
for (i = 0; i < dcc_total; i++) {
if ((dcc[i].type->flags & DCT_MASTER) &&
!egg_strcasecmp(u->handle, dcc[i].nick)) {
if ((dcc[i].type == &DCC_CHAT) &&
((chflags & (USER_OP | USER_MASTER | USER_OWNER)) !=
(ochatr & (USER_OP | USER_MASTER | USER_OWNER))))
botnet_send_join_idx(i, -1);
if ((ochatr & USER_MASTER) && !(chflags & USER_MASTER)) {
dprintf(i, "*** POOF! ***\n");
dprintf(i, "You are no longer a master on %s.\n", chname);
}
if (!(ochatr & USER_MASTER) && (chflags & USER_MASTER)) {
dcc[i].u.chat->con_flags |= conmask;
dprintf(i, "*** POOF! ***\n");
dprintf(i, "You are now a master on %s.\n", chname);
}
if (!(ochatr & USER_OWNER) && (chflags & USER_OWNER)) {
dprintf(i, "@@@ POOF! @@@\n");
dprintf(i, "You are now an OWNER of %s.\n", chname);
}
if ((ochatr & USER_OWNER) && !(chflags & USER_OWNER)) {
dprintf(i, "@@@ POOF! @@@\n");
dprintf(i, "You are no longer an owner of %s.\n", chname);
}
if (((ochatr & (USER_OP | USER_MASTER | USER_OWNER)) &&
(!(chflags & (USER_OP | USER_MASTER | USER_OWNER)))) ||
((chflags & (USER_OP | USER_MASTER | USER_OWNER)) &&
(!(ochatr & (USER_OP | USER_MASTER | USER_OWNER))))) {
for (chan = chanset; chan && !found; chan = chan->next) {
get_user_flagrec(u, &fr, chan->dname);
if (fr.chan & (USER_OP | USER_MASTER | USER_OWNER))
found = 1;
}
if (!chan)
chan = chanset;
if (chan)
strcpy(dcc[i].u.chat->con_chan, chan->dname);
else
strcpy(dcc[i].u.chat->con_chan, "*");
}
fr.match = (FR_CHAN | FR_GLOBAL);
get_user_flagrec(u, &fr, dcc[i].u.chat->con_chan);
dcc[i].u.chat->con_flags = check_conflags(&fr,
dcc[i].u.chat->con_flags);
}
}
return chflags;
}
static void cmd_chattr(struct userrec *u, int idx, char *par)
{
char *hand, *arg = NULL, *tmpchg = NULL, *chg = NULL, work[1024];
struct chanset_t *chan = NULL;
struct userrec *u2;
struct flag_record pls = { 0, 0, 0, 0, 0, 0 },
mns = { 0, 0, 0, 0, 0, 0 },
user = { 0, 0, 0, 0, 0, 0 };
module_entry *me;
int fl = -1, of = 0, ocf = 0;
if (!par[0]) {
dprintf(idx, "Usage: chattr <handle> [changes] [channel]\n");
return;
}
hand = newsplit(&par);
u2 = get_user_by_handle(userlist, hand);
if (!u2) {
dprintf(idx, "No such user!\n");
return;
}
/* Parse args */
if (par[0]) {
arg = newsplit(&par);
if (par[0]) {
/* .chattr <handle> <changes> <channel> */
chg = arg;
arg = newsplit(&par);
chan = findchan_by_dname(arg);
} else {
chan = findchan_by_dname(arg);
/* Consider modeless channels, starting with '+' */
if (!(arg[0] == '+' && chan) &&
!(arg[0] != '+' && strchr(CHANMETA, arg[0]))) {
/* .chattr <handle> <changes> */
chg = arg;
chan = NULL; /* uh, !strchr (CHANMETA, channel[0]) && channel found?? */
arg = NULL;
}
/* .chattr <handle> <channel>: nothing to do... */
}
}
/* arg: pointer to channel name, NULL if none specified
* chan: pointer to channel structure, NULL if none found or none specified
* chg: pointer to changes, NULL if none specified
*/
Assert(!(!arg && chan));
if (arg && !chan) {
dprintf(idx, "No channel record for %s.\n", arg);
return;
}
if (chg) {
if (!arg && strpbrk(chg, "&|")) {
/* .chattr <handle> *[&|]*: use console channel if found... */
if (!strcmp((arg = dcc[idx].u.chat->con_chan), "*"))
arg = NULL;
else
chan = findchan_by_dname(arg);
if (arg && !chan) {
dprintf(idx, "Invalid console channel %s.\n", arg);
return;
}
} else if (arg && !strpbrk(chg, "&|")) {
tmpchg = nmalloc(strlen(chg) + 2);
strcpy(tmpchg, "|");
strcat(tmpchg, chg);
chg = tmpchg;
}
}
par = arg;
user.match = FR_GLOBAL;
if (chan)
user.match |= FR_CHAN;
get_user_flagrec(u, &user, chan ? chan->dname : 0);
if (!chan && !glob_botmast(user)) {
dprintf(idx, "You do not have Bot Master privileges.\n");
if (tmpchg)
nfree(tmpchg);
return;
}
if (chan && !glob_master(user) && !chan_master(user)) {
dprintf(idx, "You do not have channel master privileges for channel %s.\n",
par);
if (tmpchg)
nfree(tmpchg);
return;
}
user.match &= fl;
if (chg) {
pls.match = user.match;
break_down_flags(chg, &pls, &mns);
/* No-one can change these flags on-the-fly */
pls.global &=~(USER_BOT);
mns.global &=~(USER_BOT);
if (chan) {
pls.chan &= ~(BOT_SHARE);
mns.chan &= ~(BOT_SHARE);
}
if (!glob_owner(user)) {
pls.global &=~(USER_OWNER | USER_MASTER | USER_BOTMAST | USER_UNSHARED);
mns.global &=~(USER_OWNER | USER_MASTER | USER_BOTMAST | USER_UNSHARED);
if (chan) {
pls.chan &= ~USER_OWNER;
mns.chan &= ~USER_OWNER;
}
if (!glob_master(user)) {
pls.global &=USER_PARTY | USER_XFER;
mns.global &=USER_PARTY | USER_XFER;
if (!glob_botmast(user)) {
pls.global = 0;
mns.global = 0;
}
}
}
if (chan && !chan_owner(user) && !glob_owner(user)) {
pls.chan &= ~USER_MASTER;
mns.chan &= ~USER_MASTER;
if (!chan_master(user) && !glob_master(user)) {
pls.chan = 0;
mns.chan = 0;
}
}
get_user_flagrec(u2, &user, par);
if (user.match & FR_GLOBAL) {
of = user.global;
user.global = sanity_check((user.global |pls.global) &~mns.global);
user.udef_global = (user.udef_global | pls.udef_global)
& ~mns.udef_global;
}
if (chan) {
ocf = user.chan;
user.chan = chan_sanity_check((user.chan | pls.chan) & ~mns.chan,
user.global);
user.udef_chan = (user.udef_chan | pls.udef_chan) & ~mns.udef_chan;
}
set_user_flagrec(u2, &user, par);
}
if (chan)
putlog(LOG_CMDS, "*", "#%s# (%s) chattr %s %s",
dcc[idx].nick, chan ? chan->dname : "*", hand, chg ? chg : "");
else
putlog(LOG_CMDS, "*", "#%s# chattr %s %s", dcc[idx].nick, hand,
chg ? chg : "");
/* Get current flags and display them */
if (user.match & FR_GLOBAL) {
user.match = FR_GLOBAL;
if (chg)
check_dcc_attrs(u2, of);
get_user_flagrec(u2, &user, NULL);
build_flags(work, &user, NULL);
if (work[0] != '-')
dprintf(idx, "Global flags for %s are now +%s.\n", hand, work);
else
dprintf(idx, "No global flags for %s.\n", hand);
}
if (chan) {
user.match = FR_CHAN;
get_user_flagrec(u2, &user, par);
user.chan &= ~BOT_SHARE;
if (chg)
check_dcc_chanattrs(u2, chan->dname, user.chan, ocf);
build_flags(work, &user, NULL);
if (work[0] != '-')
dprintf(idx, "Channel flags for %s on %s are now +%s.\n", hand,
chan->dname, work);
else
dprintf(idx, "No flags for %s on %s.\n", hand, chan->dname);
}
if (chg && (me = module_find("irc", 0, 0))) {
Function *func = me->funcs;
(func[IRC_CHECK_THIS_USER]) (hand, 0, NULL);
}
if (tmpchg)
nfree(tmpchg);
}
static void cmd_botattr(struct userrec *u, int idx, char *par)
{
char *hand, *chg = NULL, *arg = NULL, *tmpchg = NULL, work[1024];
struct chanset_t *chan = NULL;
struct userrec *u2;
struct flag_record pls = { 0, 0, 0, 0, 0, 0 },
mns = { 0, 0, 0, 0, 0, 0 },
user = { 0, 0, 0, 0, 0, 0 };
int idx2;
if (!par[0]) {
dprintf(idx, "Usage: botattr <handle> [changes] [channel]\n");
return;
}
hand = newsplit(&par);
u2 = get_user_by_handle(userlist, hand);
if (!u2 || !(u2->flags & USER_BOT)) {
dprintf(idx, "No such bot!\n");
return;
}
for (idx2 = 0; idx2 < dcc_total; idx2++)
if (dcc[idx2].type != &DCC_RELAY && dcc[idx2].type != &DCC_FORK_BOT &&
!egg_strcasecmp(dcc[idx2].nick, hand))
break;
if (idx2 != dcc_total) {
dprintf(idx,
"You may not change the attributes of a directly linked bot.\n");
return;
}
/* Parse args */
if (par[0]) {
arg = newsplit(&par);
if (par[0]) {
/* .botattr <handle> <changes> <channel> */
chg = arg;
arg = newsplit(&par);
chan = findchan_by_dname(arg);
} else {
chan = findchan_by_dname(arg);
/* Consider modeless channels, starting with '+' */
if (!(arg[0] == '+' && chan) &&
!(arg[0] != '+' && strchr(CHANMETA, arg[0]))) {
/* .botattr <handle> <changes> */
chg = arg;
chan = NULL; /* uh, !strchr (CHANMETA, channel[0]) && channel found?? */
arg = NULL;
}
/* .botattr <handle> <channel>: nothing to do... */
}
}
/* arg: pointer to channel name, NULL if none specified
* chan: pointer to channel structure, NULL if none found or none specified
* chg: pointer to changes, NULL if none specified
*/
Assert(!(!arg && chan));
if (arg && !chan) {
dprintf(idx, "No channel record for %s.\n", arg);
return;
}
if (chg) {
if (!arg && strpbrk(chg, "&|")) {
/* botattr <handle> *[&|]*: use console channel if found... */
if (!strcmp((arg = dcc[idx].u.chat->con_chan), "*"))
arg = NULL;
else
chan = findchan_by_dname(arg);
if (arg && !chan) {
dprintf(idx, "Invalid console channel %s.\n", arg);
return;
}
} else if (arg && !strpbrk(chg, "&|")) {
tmpchg = nmalloc(strlen(chg) + 2);
strcpy(tmpchg, "|");
strcat(tmpchg, chg);
chg = tmpchg;
}
}
par = arg;
user.match = FR_GLOBAL;
get_user_flagrec(u, &user, chan ? chan->dname : 0);
if (!glob_botmast(user)) {
dprintf(idx, "You do not have Bot Master privileges.\n");
if (tmpchg)
nfree(tmpchg);
return;
}
if (chg) {
user.match = FR_BOT | (chan ? FR_CHAN : 0);
pls.match = user.match;
break_down_flags(chg, &pls, &mns);
/* No-one can change these flags on-the-fly */
pls.global &=~BOT_BOT;
mns.global &=~BOT_BOT;
if (chan && glob_owner(user)) {
pls.chan &= BOT_SHARE;
mns.chan &= BOT_SHARE;
} else {
pls.chan = 0;
mns.chan = 0;
}
if (!glob_owner(user)) {
pls.bot &= ~(BOT_SHARE | BOT_GLOBAL);
mns.bot &= ~(BOT_SHARE | BOT_GLOBAL);
}
user.match = FR_BOT | (chan ? FR_CHAN : 0);
get_user_flagrec(u2, &user, par);
user.bot = (user.bot | pls.bot) & ~mns.bot;
if ((user.bot & BOT_SHARE) == BOT_SHARE)
user.bot &= ~BOT_SHARE;
if (chan)
user.chan = (user.chan | pls.chan) & ~mns.chan;
set_user_flagrec(u2, &user, par);
}
if (chan)
putlog(LOG_CMDS, "*", "#%s# (%s) botattr %s %s",
dcc[idx].nick, chan->dname, hand, chg ? chg : "");
else
putlog(LOG_CMDS, "*", "#%s# botattr %s %s", dcc[idx].nick, hand,
chg ? chg : "");
/* get current flags and display them */
if (!chan || pls.bot || mns.bot) {
user.match = FR_BOT;
get_user_flagrec(u2, &user, NULL);
build_flags(work, &user, NULL);
if (work[0] != '-')
dprintf(idx, "Bot flags for %s are now +%s.\n", hand, work);
else
dprintf(idx, "There are no bot flags for %s.\n", hand);
}
if (chan) {
user.match = FR_CHAN;
get_user_flagrec(u2, &user, par);
user.chan &= BOT_SHARE;
user.udef_chan = 0; /* udef chan flags are user only */
build_flags(work, &user, NULL);
if (work[0] != '-')
dprintf(idx, "Bot flags for %s on %s are now +%s.\n", hand,
chan->dname, work);
else
dprintf(idx, "There are no bot flags for %s on %s.\n", hand, chan->dname);
}
if (tmpchg)
nfree(tmpchg);
}
static void cmd_chat(struct userrec *u, int idx, char *par)
{
char *arg;
int newchan, oldchan;
module_entry *me;
arg = newsplit(&par);
if (!egg_strcasecmp(arg, "off")) {
/* Turn chat off */
if (dcc[idx].u.chat->channel < 0) {
dprintf(idx, "You weren't in chat anyway!\n");
return;
} else {
dprintf(idx, "Leaving chat mode...\n");
check_tcl_chpt(botnetnick, dcc[idx].nick, dcc[idx].sock,
dcc[idx].u.chat->channel);
chanout_but(-1, dcc[idx].u.chat->channel,
"*** %s left the party line.\n", dcc[idx].nick);
if (dcc[idx].u.chat->channel < GLOBAL_CHANS)
botnet_send_part_idx(idx, "");
}
dcc[idx].u.chat->channel = -1;
} else {
if (arg[0] == '*') {
if (((arg[1] < '0') || (arg[1] > '9'))) {
if (!arg[1])
newchan = 0;
else {
Tcl_SetVar(interp, "_chan", arg, 0);
if ((Tcl_VarEval(interp, "assoc ", "$_chan", NULL) == TCL_OK) &&
!tcl_resultempty())
newchan = tcl_resultint();
else
newchan = -1;
}
if (newchan < 0) {
dprintf(idx, "No channel exists by that name.\n");
return;
}
} else
newchan = GLOBAL_CHANS + atoi(arg + 1);
if (newchan < GLOBAL_CHANS || newchan > 199999) {
dprintf(idx, "Channel number out of range: local channels must be "
"*0-*99999.\n");
return;
}
} else {
if (((arg[0] < '0') || (arg[0] > '9')) && (arg[0])) {
if (!egg_strcasecmp(arg, "on"))
newchan = 0;
else {
Tcl_SetVar(interp, "_chan", arg, 0);
if ((Tcl_VarEval(interp, "assoc ", "$_chan", NULL) == TCL_OK) &&
!tcl_resultempty())
newchan = tcl_resultint();
else
newchan = -1;
}
if (newchan < 0) {
dprintf(idx, "No channel exists by that name.\n");
return;
}
} else
newchan = atoi(arg);
if ((newchan < 0) || (newchan >= GLOBAL_CHANS)) {
dprintf(idx, "Channel number out of range: must be between 0 and %d."
"\n", GLOBAL_CHANS);
return;
}
}
/* If coming back from being off the party line, make sure they're
* not away.
*/
if ((dcc[idx].u.chat->channel < 0) && (dcc[idx].u.chat->away != NULL))
not_away(idx);
if (dcc[idx].u.chat->channel == newchan) {
if (!newchan) {
dprintf(idx, "You're already on the party line!\n");
return;
} else {
dprintf(idx, "You're already on channel %s%d!\n",
(newchan < GLOBAL_CHANS) ? "" : "*", newchan % GLOBAL_CHANS);
return;
}
} else {
oldchan = dcc[idx].u.chat->channel;
if (oldchan >= 0)
check_tcl_chpt(botnetnick, dcc[idx].nick, dcc[idx].sock, oldchan);
if (!oldchan)
chanout_but(-1, 0, "*** %s left the party line.\n", dcc[idx].nick);
else if (oldchan > 0)
chanout_but(-1, oldchan, "*** %s left the channel.\n", dcc[idx].nick);
dcc[idx].u.chat->channel = newchan;
if (!newchan) {
dprintf(idx, "Entering the party line...\n");
chanout_but(-1, 0, "*** %s joined the party line.\n", dcc[idx].nick);
} else {
dprintf(idx, "Joining channel '%s'...\n", arg);
chanout_but(-1, newchan, "*** %s joined the channel.\n", dcc[idx].nick);
}
check_tcl_chjn(botnetnick, dcc[idx].nick, newchan, geticon(idx),
dcc[idx].sock, dcc[idx].host);
if (newchan < GLOBAL_CHANS)
botnet_send_join_idx(idx, oldchan);
else if (oldchan < GLOBAL_CHANS)
botnet_send_part_idx(idx, "");
}
}
/* New style autosave here too -- rtc, 09/28/1999 */
if ((me = module_find("console", 1, 1))) {
Function *func = me->funcs;
(func[CONSOLE_DOSTORE]) (idx);
}
}
static void cmd_echo(struct userrec *u, int idx, char *par)
{
module_entry *me;
if (!par[0]) {
dprintf(idx, "Echo is currently %s.\n", dcc[idx].status & STAT_ECHO ?
"on" : "off");
return;
}
if (!egg_strcasecmp(par, "on")) {
dprintf(idx, "Echo turned on.\n");
dcc[idx].status |= STAT_ECHO;
} else if (!egg_strcasecmp(par, "off")) {
dprintf(idx, "Echo turned off.\n");
dcc[idx].status &= ~STAT_ECHO;
} else {
dprintf(idx, "Usage: echo <on/off>\n");
return;
}
/* New style autosave here too -- rtc, 09/28/1999 */
if ((me = module_find("console", 1, 1))) {
Function *func = me->funcs;
(func[CONSOLE_DOSTORE]) (idx);
}
}
int stripmodes(char *s)
{
int res = 0;
for (; *s; s++)
switch (tolower((unsigned) *s)) {
case 'b':
res |= STRIP_BOLD;
break;
case 'c':
res |= STRIP_COLOR;
break;
case 'r':
res |= STRIP_REV;
break;
case 'u':
res |= STRIP_UNDER;
break;
case 'a':
res |= STRIP_ANSI;
break;
case 'g':
res |= STRIP_BELLS;
break;
case '*':
res |= STRIP_ALL;
break;
}
return res;
}
char *stripmasktype(int x)
{
static char s[20];
char *p = s;
if (x & STRIP_BOLD)
*p++ = 'b';
if (x & STRIP_COLOR)
*p++ = 'c';
if (x & STRIP_REV)
*p++ = 'r';
if (x & STRIP_UNDER)
*p++ = 'u';
if (x & STRIP_ANSI)
*p++ = 'a';
if (x & STRIP_BELLS)
*p++ = 'g';
if (p == s)
*p++ = '-';
*p = 0;
return s;
}
static char *stripmaskname(int x)
{
static char s[161];
int i = 0;
s[i] = 0;
if (x & STRIP_BOLD)
i += my_strcpy(s + i, "bold, ");
if (x & STRIP_COLOR)
i += my_strcpy(s + i, "color, ");
if (x & STRIP_REV)
i += my_strcpy(s + i, "reverse, ");
if (x & STRIP_UNDER)
i += my_strcpy(s + i, "underline, ");
if (x & STRIP_ANSI)
i += my_strcpy(s + i, "ansi, ");
if (x & STRIP_BELLS)
i += my_strcpy(s + i, "bells, ");
if (!i)
strcpy(s, "none");
else
s[i - 2] = 0;
return s;
}
static void cmd_strip(struct userrec *u, int idx, char *par)
{
char *nick, *changes, *c, s[2];
int dest = 0, i, pls, md, ok = 0;
module_entry *me;
if (!par[0]) {
dprintf(idx, "Your current strip settings are: %s (%s).\n",
stripmasktype(dcc[idx].u.chat->strip_flags),
stripmaskname(dcc[idx].u.chat->strip_flags));
return;
}
nick = newsplit(&par);
if ((nick[0] != '+') && (nick[0] != '-') && u && (u->flags & USER_MASTER)) {
for (i = 0; i < dcc_total; i++)
if (!egg_strcasecmp(nick, dcc[i].nick) && dcc[i].type == &DCC_CHAT && !ok) {
ok = 1;
dest = i;
}
if (!ok) {
dprintf(idx, "No such user on the party line!\n");
return;
}
changes = par;
} else {
changes = nick;
nick = "";
dest = idx;
}
c = changes;
if ((c[0] != '+') && (c[0] != '-'))
dcc[dest].u.chat->strip_flags = 0;
s[1] = 0;
for (pls = 1; *c; c++) {
switch (*c) {
case '+':
pls = 1;
break;
case '-':
pls = 0;
break;
default:
s[0] = *c;
md = stripmodes(s);
if (pls == 1)
dcc[dest].u.chat->strip_flags |= md;
else
dcc[dest].u.chat->strip_flags &= ~md;
}
}
if (nick[0])
putlog(LOG_CMDS, "*", "#%s# strip %s %s", dcc[idx].nick, nick, changes);
else
putlog(LOG_CMDS, "*", "#%s# strip %s", dcc[idx].nick, changes);
if (dest == idx) {
dprintf(idx, "Your strip settings are: %s (%s).\n",
stripmasktype(dcc[idx].u.chat->strip_flags),
stripmaskname(dcc[idx].u.chat->strip_flags));
} else {
dprintf(idx, "Strip setting for %s: %s (%s).\n", dcc[dest].nick,
stripmasktype(dcc[dest].u.chat->strip_flags),
stripmaskname(dcc[dest].u.chat->strip_flags));
dprintf(dest, "%s set your strip settings to: %s (%s).\n", dcc[idx].nick,
stripmasktype(dcc[dest].u.chat->strip_flags),
stripmaskname(dcc[dest].u.chat->strip_flags));
}
/* Set highlight flag here so user is able to control stripping of
* bold also as intended -- dw 27/12/1999
*/
if (dcc[dest].u.chat->strip_flags & STRIP_BOLD && u->flags & USER_HIGHLITE) {
u->flags &= ~USER_HIGHLITE;
} else if (!(dcc[dest].u.chat->strip_flags & STRIP_BOLD) &&
!(u->flags & USER_HIGHLITE)) {
u->flags |= USER_HIGHLITE;
}
/* New style autosave here too -- rtc, 09/28/1999 */
if ((me = module_find("console", 1, 1))) {
Function *func = me->funcs;
(func[CONSOLE_DOSTORE]) (dest);
}
}
static void cmd_su(struct userrec *u, int idx, char *par)
{
int atr = u ? u->flags : 0;
struct flag_record fr = { FR_ANYWH | FR_CHAN | FR_GLOBAL, 0, 0, 0, 0, 0 };
u = get_user_by_handle(userlist, par);
if (!par[0])
dprintf(idx, "Usage: su <user>\n");
else if (!u)
dprintf(idx, "No such user.\n");
else if (u->flags & USER_BOT)
dprintf(idx, "You can't su to a bot... then again, why would you wanna?\n");
else if (dcc[idx].u.chat->su_nick)
dprintf(idx, "You cannot currently double .su; try .su'ing directly.\n");
else {
get_user_flagrec(u, &fr, NULL);
if ((!glob_party(fr) && (require_p || !(glob_op(fr) || chan_op(fr)))) &&
!(atr & USER_BOTMAST))
dprintf(idx, "No party line access permitted for %s.\n", par);
else {
correct_handle(par);
putlog(LOG_CMDS, "*", "#%s# su %s", dcc[idx].nick, par);
if (!(atr & USER_OWNER) || ((u->flags & USER_OWNER) && (isowner(par)) &&
!(isowner(dcc[idx].nick)))) {
/* This check is only important for non-owners */
if (u_pass_match(u, "-")) {
dprintf(idx, "No password set for user. You may not .su to them.\n");
return;
}
if (dcc[idx].u.chat->channel < GLOBAL_CHANS)
botnet_send_part_idx(idx, "");
chanout_but(-1, dcc[idx].u.chat->channel,
"*** %s left the party line.\n", dcc[idx].nick);
/* Store the old nick in the away section, for weenies who can't get
* their password right ;)
*/
if (dcc[idx].u.chat->away != NULL)
nfree(dcc[idx].u.chat->away);
dcc[idx].u.chat->away = get_data_ptr(strlen(dcc[idx].nick) + 1);
strcpy(dcc[idx].u.chat->away, dcc[idx].nick);
dcc[idx].u.chat->su_nick = get_data_ptr(strlen(dcc[idx].nick) + 1);
strcpy(dcc[idx].u.chat->su_nick, dcc[idx].nick);
dcc[idx].user = u;
strcpy(dcc[idx].nick, par);
/* Display password prompt and turn off echo (send IAC WILL ECHO). */
dprintf(idx, "Enter password for %s%s\n", par,
(dcc[idx].status & STAT_TELNET) ? TLN_IAC_C TLN_WILL_C
TLN_ECHO_C : "");
dcc[idx].type = &DCC_CHAT_PASS;
} else if (atr & USER_OWNER) {
if (dcc[idx].u.chat->channel < GLOBAL_CHANS)
botnet_send_part_idx(idx, "");
chanout_but(-1, dcc[idx].u.chat->channel,
"*** %s left the party line.\n", dcc[idx].nick);
dprintf(idx, "Setting your username to %s.\n", par);
if (atr & USER_MASTER)
dcc[idx].u.chat->con_flags = conmask;
dcc[idx].u.chat->su_nick = get_data_ptr(strlen(dcc[idx].nick) + 1);
strcpy(dcc[idx].u.chat->su_nick, dcc[idx].nick);
dcc[idx].user = u;
strcpy(dcc[idx].nick, par);
dcc_chatter(idx);
}
}
}
}
static void cmd_fixcodes(struct userrec *u, int idx, char *par)
{
if (dcc[idx].status & STAT_TELNET) {
dcc[idx].status |= STAT_ECHO;
dcc[idx].status &= ~STAT_TELNET;
dprintf(idx, "Turned off telnet codes.\n");
putlog(LOG_CMDS, "*", "#%s# fixcodes (telnet off)", dcc[idx].nick);
} else {
dcc[idx].status |= STAT_TELNET;
dcc[idx].status &= ~STAT_ECHO;
dprintf(idx, "Turned on telnet codes.\n");
putlog(LOG_CMDS, "*", "#%s# fixcodes (telnet on)", dcc[idx].nick);
}
}
static void cmd_page(struct userrec *u, int idx, char *par)
{
int a;
module_entry *me;
if (!par[0]) {
if (dcc[idx].status & STAT_PAGE) {
dprintf(idx, "Currently paging outputs to %d lines.\n",
dcc[idx].u.chat->max_line);
} else
dprintf(idx, "You don't have paging on.\n");
return;
}
a = atoi(par);
if ((!a && !par[0]) || !egg_strcasecmp(par, "off")) {
dcc[idx].status &= ~STAT_PAGE;
dcc[idx].u.chat->max_line = 0x7ffffff; /* flush_lines needs this */
while (dcc[idx].u.chat->buffer)
flush_lines(idx, dcc[idx].u.chat);
dprintf(idx, "Paging turned off.\n");
putlog(LOG_CMDS, "*", "#%s# page off", dcc[idx].nick);
} else if (a > 0) {
dprintf(idx, "Paging turned on, stopping every %d line%s.\n", a,
(a != 1) ? "s" : "");
dcc[idx].status |= STAT_PAGE;
dcc[idx].u.chat->max_line = a;
dcc[idx].u.chat->line_count = 0;
dcc[idx].u.chat->current_lines = 0;
putlog(LOG_CMDS, "*", "#%s# page %d", dcc[idx].nick, a);
} else {
dprintf(idx, "Usage: page <off or #>\n");
return;
}
/* New style autosave here too -- rtc, 09/28/1999 */
if ((me = module_find("console", 1, 1))) {
Function *func = me->funcs;
(func[CONSOLE_DOSTORE]) (idx);
}
}
/* Evaluate a Tcl command, send output to a dcc user.
*/
static void cmd_tcl(struct userrec *u, int idx, char *msg)
{
int code;
char *result;
#ifdef USE_TCL_ENCODING
Tcl_DString dstr;
#endif
if (!(isowner(dcc[idx].nick)) && (must_be_owner)) {
dprintf(idx, MISC_NOSUCHCMD);
return;
}
debug1("tcl: evaluate (.tcl): %s", msg);
code = Tcl_GlobalEval(interp, msg);
#ifdef USE_TCL_ENCODING
/* properly convert string to system encoding. */
Tcl_DStringInit(&dstr);
Tcl_UtfToExternalDString(NULL, tcl_resultstring(), -1, &dstr);
result = Tcl_DStringValue(&dstr);
#else
/* use old pre-Tcl 8.1 way. */
result = tcl_resultstring();
#endif
if (code == TCL_OK)
dumplots(idx, "Tcl: ", result);
else
dumplots(idx, "Tcl error: ", result);
#ifdef USE_TCL_ENCODING
Tcl_DStringFree(&dstr);
#endif
}
/* Perform a 'set' command
*/
static void cmd_set(struct userrec *u, int idx, char *msg)
{
int code;
char s[512], *result;
#ifdef USE_TCL_ENCODING
Tcl_DString dstr;
#endif
if (!(isowner(dcc[idx].nick)) && (must_be_owner)) {
dprintf(idx, MISC_NOSUCHCMD);
return;
}
putlog(LOG_CMDS, "*", "#%s# set %s", dcc[idx].nick, msg);
strcpy(s, "set ");
if (!msg[0]) {
strcpy(s, "info globals");
Tcl_Eval(interp, s);
dumplots(idx, "Global vars: ", tcl_resultstring());
return;
}
strcpy(s + 4, msg);
code = Tcl_Eval(interp, s);
#ifdef USE_TCL_ENCODING
/* properly convert string to system encoding. */
Tcl_DStringInit(&dstr);
Tcl_UtfToExternalDString(NULL, tcl_resultstring(), -1, &dstr);
result = Tcl_DStringValue(&dstr);
#else
/* use old pre-Tcl 8.1 way. */
result = tcl_resultstring();
#endif
if (code == TCL_OK) {
if (!strchr(msg, ' '))
dumplots(idx, "Currently: ", result);
else
dprintf(idx, "Ok, set.\n");
} else
dprintf(idx, "Error: %s\n", result);
#ifdef USE_TCL_ENCODING
Tcl_DStringFree(&dstr);
#endif
}
static void cmd_module(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# module %s", dcc[idx].nick, par);
do_module_report(idx, 2, par[0] ? par : NULL);
}
static void cmd_loadmod(struct userrec *u, int idx, char *par)
{
const char *p;
if (!(isowner(dcc[idx].nick)) && (must_be_owner)) {
dprintf(idx, MISC_NOSUCHCMD);
return;
}
if (!par[0]) {
dprintf(idx, "%s: loadmod <module>\n", MISC_USAGE);
} else {
p = module_load(par);
if (p)
dprintf(idx, "%s: %s %s\n", par, MOD_LOADERROR, p);
else {
putlog(LOG_CMDS, "*", "#%s# loadmod %s", dcc[idx].nick, par);
dprintf(idx, MOD_LOADED, par);
dprintf(idx, "\n");
}
}
}
static void cmd_unloadmod(struct userrec *u, int idx, char *par)
{
char *p;
if (!(isowner(dcc[idx].nick)) && (must_be_owner)) {
dprintf(idx, MISC_NOSUCHCMD);
return;
}
if (!par[0])
dprintf(idx, "%s: unloadmod <module>\n", MISC_USAGE);
else {
p = module_unload(par, dcc[idx].nick);
if (p)
dprintf(idx, "%s %s: %s\n", MOD_UNLOADERROR, par, p);
else {
putlog(LOG_CMDS, "*", "#%s# unloadmod %s", dcc[idx].nick, par);
dprintf(idx, "%s %s\n", MOD_UNLOADED, par);
}
}
}
static void cmd_pls_ignore(struct userrec *u, int idx, char *par)
{
char *who, s[UHOSTLEN];
unsigned long int expire_time = 0;
if (!par[0]) {
dprintf(idx, "Usage: +ignore <hostmask> [%%<XdXhXm>] [comment]\n");
return;
}
who = newsplit(&par);
if (par[0] == '%') {
char *p, *p_expire;
unsigned long int expire_foo;
p = newsplit(&par);
p_expire = p + 1;
while (*(++p) != 0) {
switch (tolower((unsigned) *p)) {
case 'd':
*p = 0;
expire_foo = strtol(p_expire, NULL, 10);
if (expire_foo > 365)
expire_foo = 365;
expire_time += 86400 * expire_foo;
p_expire = p + 1;
break;
case 'h':
*p = 0;
expire_foo = strtol(p_expire, NULL, 10);
if (expire_foo > 8760)
expire_foo = 8760;
expire_time += 3600 * expire_foo;
p_expire = p + 1;
break;
case 'm':
*p = 0;
expire_foo = strtol(p_expire, NULL, 10);
if (expire_foo > 525600)
expire_foo = 525600;
expire_time += 60 * expire_foo;
p_expire = p + 1;
}
}
}
if (!par[0])
par = "requested";
else if (strlen(par) > 65)
par[65] = 0;
if (strlen(who) > UHOSTMAX - 4)
who[UHOSTMAX - 4] = 0;
/* Fix missing ! or @ BEFORE continuing */
if (!strchr(who, '!')) {
if (!strchr(who, '@'))
simple_sprintf(s, "%s!*@*", who);
else
simple_sprintf(s, "*!%s", who);
} else if (!strchr(who, '@'))
simple_sprintf(s, "%s@*", who);
else
strcpy(s, who);
if (match_ignore(s))
dprintf(idx, "That already matches an existing ignore.\n");
else {
dprintf(idx, "Now ignoring: %s (%s)\n", s, par);
addignore(s, dcc[idx].nick, par, expire_time ? now + expire_time : 0L);
putlog(LOG_CMDS, "*", "#%s# +ignore %s %s", dcc[idx].nick, s, par);
}
}
static void cmd_mns_ignore(struct userrec *u, int idx, char *par)
{
char buf[UHOSTLEN];
if (!par[0]) {
dprintf(idx, "Usage: -ignore <hostmask | ignore #>\n");
return;
}
strncpyz(buf, par, sizeof buf);
if (delignore(buf)) {
putlog(LOG_CMDS, "*", "#%s# -ignore %s", dcc[idx].nick, buf);
dprintf(idx, "No longer ignoring: %s\n", buf);
} else
dprintf(idx, "That ignore cannot be found.\n");
}
static void cmd_ignores(struct userrec *u, int idx, char *par)
{
putlog(LOG_CMDS, "*", "#%s# ignores %s", dcc[idx].nick, par);
tell_ignores(idx, par);
}
static void cmd_pls_user(struct userrec *u, int idx, char *par)
{
char *handle, *host;
if (!par[0]) {
dprintf(idx, "Usage: +user <handle> [hostmask]\n");
return;
}
handle = newsplit(&par);
host = newsplit(&par);
if (strlen(handle) > HANDLEN)
handle[HANDLEN] = 0;
if (get_user_by_handle(userlist, handle))
dprintf(idx, "Someone already exists by that name.\n");
else if (strchr(BADNICKCHARS, handle[0]) != NULL)
dprintf(idx, "You can't start a nick with '%c'.\n", handle[0]);
else if (!egg_strcasecmp(handle, botnetnick))
dprintf(idx, "Hey! That's MY name!\n");
else {
putlog(LOG_CMDS, "*", "#%s# +user %s %s", dcc[idx].nick, handle, host);
userlist = adduser(userlist, handle, host, "-", 0);
dprintf(idx, "Added %s (%s) with no password and no flags.\n", handle,
host[0] ? host : "no host");
}
}
static void cmd_mns_user(struct userrec *u, int idx, char *par)
{
int idx2;
char *handle;
struct userrec *u2;
module_entry *me;
if (!par[0]) {
dprintf(idx, "Usage: -user <hand>\n");
return;
}
handle = newsplit(&par);
u2 = get_user_by_handle(userlist, handle);
if (!u2 || !u) {
dprintf(idx, "No such user!\n");
return;
}
if (isowner(u2->handle)) {
dprintf(idx, "You can't remove a permanent bot owner!\n");
return;
}
if ((u2->flags & USER_OWNER) && !(u->flags & USER_OWNER)) {
dprintf(idx, "You can't remove a bot owner!\n");
return;
}
if (u2->flags & USER_BOT) {
if ((bot_flags(u2) & BOT_SHARE) && !(u->flags & USER_OWNER)) {
dprintf(idx, "You can't remove share bots.\n");
return;
}
for (idx2 = 0; idx2 < dcc_total; idx2++)
if (dcc[idx2].type != &DCC_RELAY && dcc[idx2].type != &DCC_FORK_BOT &&
!egg_strcasecmp(dcc[idx2].nick, handle))
break;
if (idx2 != dcc_total) {
dprintf(idx, "You can't remove a directly linked bot.\n");
return;
}
}
if ((u->flags & USER_BOTMAST) && !(u->flags & USER_MASTER) &&
!(u2->flags & USER_BOT)) {
dprintf(idx, "You can't remove users who aren't bots!\n");
return;
}
if ((me = module_find("irc", 0, 0))) {
Function *func = me->funcs;
(func[IRC_CHECK_THIS_USER]) (handle, 1, NULL);
}
if (deluser(handle)) {
putlog(LOG_CMDS, "*", "#%s# -user %s", dcc[idx].nick, handle);
dprintf(idx, "Deleted %s.\n", handle);
} else
dprintf(idx, "Failed.\n");
}
static void cmd_pls_host(struct userrec *u, int idx, char *par)
{
char *handle, *host;
struct userrec *u2;
struct list_type *q;
struct flag_record fr2 = { FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0, 0, 0 },
fr = { FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0, 0, 0 };
module_entry *me;
if (!par[0]) {
dprintf(idx, "Usage: +host [handle] <newhostmask>\n");
return;
}
handle = newsplit(&par);
if (par[0]) {
host = newsplit(&par);
u2 = get_user_by_handle(userlist, handle);
} else {
host = handle;
handle = dcc[idx].nick;
u2 = u;
}
if (!u2 || !u) {
dprintf(idx, "No such user.\n");
return;
}
get_user_flagrec(u, &fr, NULL);
if (egg_strcasecmp(handle, dcc[idx].nick)) {
get_user_flagrec(u2, &fr2, NULL);
if (!glob_master(fr) && !glob_bot(fr2) && !chan_master(fr)) {
dprintf(idx, "You can't add hostmasks to non-bots.\n");
return;
}
if (!glob_owner(fr) && glob_bot(fr2) && (bot_flags(u2) & BOT_SHARE)) {
dprintf(idx, "You can't add hostmasks to share bots.\n");
return;
}
if ((glob_owner(fr2) || glob_master(fr2)) && !glob_owner(fr)) {
dprintf(idx, "You can't add hostmasks to a bot owner/master.\n");
return;
}
if ((chan_owner(fr2) || chan_master(fr2)) && !glob_master(fr) &&
!glob_owner(fr) && !chan_owner(fr)) {
dprintf(idx, "You can't add hostmasks to a channel owner/master.\n");
return;
}
if (!glob_botmast(fr) && !glob_master(fr) && !chan_master(fr)) {
dprintf(idx, "Permission denied.\n");
return;
}
}
if (!glob_botmast(fr) && !chan_master(fr) && get_user_by_host(host)) {
dprintf(idx, "You cannot add a host matching another user!\n");
return;
}
for (q = get_user(&USERENTRY_HOSTS, u); q; q = q->next)
if (!egg_strcasecmp(q->extra, host)) {
dprintf(idx, "That hostmask is already there.\n");
return;
}
putlog(LOG_CMDS, "*", "#%s# +host %s %s", dcc[idx].nick, handle, host);
addhost_by_handle(handle, host);
dprintf(idx, "Added '%s' to %s.\n", host, handle);
if ((me = module_find("irc", 0, 0))) {
Function *func = me->funcs;
(func[IRC_CHECK_THIS_USER]) (handle, 0, NULL);
}
}
static void cmd_mns_host(struct userrec *u, int idx, char *par)
{
char *handle, *host;
struct userrec *u2;
struct flag_record fr2 = { FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0, 0, 0 },
fr = { FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0, 0, 0 };
module_entry *me;
if (!par[0]) {
dprintf(idx, "Usage: -host [handle] <hostmask>\n");
return;
}
handle = newsplit(&par);
if (par[0]) {
host = newsplit(&par);
u2 = get_user_by_handle(userlist, handle);
} else {
host = handle;
handle = dcc[idx].nick;
u2 = u;
}
if (!u2 || !u) {
dprintf(idx, "No such user.\n");
return;
}
get_user_flagrec(u, &fr, NULL);
get_user_flagrec(u2, &fr2, NULL);
/* check to see if user is +d or +k and don't let them remove hosts */
if (((glob_deop(fr) || glob_kick(fr)) && !glob_master(fr)) ||
((chan_deop(fr) || chan_kick(fr)) && !chan_master(fr))) {
dprintf(idx, "You can't remove hostmasks while having the +d or +k "
"flag.\n");
return;
}
if (egg_strcasecmp(handle, dcc[idx].nick)) {
if (!glob_master(fr) && !glob_bot(fr2) && !chan_master(fr)) {
dprintf(idx, "You can't remove hostmasks from non-bots.\n");
return;
}
if (glob_bot(fr2) && (bot_flags(u2) & BOT_SHARE) && !glob_owner(fr)) {
dprintf(idx, "You can't remove hostmasks from a share bot.\n");
return;
}
if ((glob_owner(fr2) || glob_master(fr2)) && !glob_owner(fr)) {
dprintf(idx, "You can't remove hostmasks from a bot owner/master.\n");
return;
}
if ((chan_owner(fr2) || chan_master(fr2)) && !glob_master(fr) &&
!glob_owner(fr) && !chan_owner(fr)) {
dprintf(idx, "You can't remove hostmasks from a channel owner/master.\n");
return;
}
if (!glob_botmast(fr) && !glob_master(fr) && !chan_master(fr)) {
dprintf(idx, "Permission denied.\n");
return;
}
}
if (delhost_by_handle(handle, host)) {
putlog(LOG_CMDS, "*", "#%s# -host %s %s", dcc[idx].nick, handle, host);
dprintf(idx, "Removed '%s' from %s.\n", host, handle);
if ((me = module_find("irc", 0, 0))) {
Function *func = me->funcs;
(func[IRC_CHECK_THIS_USER]) (handle, 2, host);
}
} else
dprintf(idx, "Failed.\n");
}
static void cmd_modules(struct userrec *u, int idx, char *par)
{
int ptr;
char *bot;
module_entry *me;
putlog(LOG_CMDS, "*", "#%s# modules %s", dcc[idx].nick, par);
if (!par[0]) {
dprintf(idx, "Modules loaded:\n");
for (me = module_list; me; me = me->next)
dprintf(idx, " Module: %s (v%d.%d)\n", me->name, me->major, me->minor);
dprintf(idx, "End of modules list.\n");
} else {
bot = newsplit(&par);
if ((ptr = nextbot(bot)) >= 0)
dprintf(ptr, "v %s %s %d:%s\n", botnetnick, bot, dcc[idx].sock,
dcc[idx].nick);
else
dprintf(idx, "No such bot online.\n");
}
}
static void cmd_traffic(struct userrec *u, int idx, char *par)
{
unsigned long itmp, itmp2;
dprintf(idx, "Traffic since last restart\n");
dprintf(idx, "==========================\n");
if (otraffic_irc > 0 || itraffic_irc > 0 || otraffic_irc_today > 0 ||
itraffic_irc_today > 0) {
dprintf(idx, "IRC:\n");
dprintf(idx, " out: %s", btos(otraffic_irc + otraffic_irc_today));
dprintf(idx, " (%s today)\n", btos(otraffic_irc_today));
dprintf(idx, " in: %s", btos(itraffic_irc + itraffic_irc_today));
dprintf(idx, " (%s today)\n", btos(itraffic_irc_today));
}
if (otraffic_bn > 0 || itraffic_bn > 0 || otraffic_bn_today > 0 ||
itraffic_bn_today > 0) {
dprintf(idx, "Botnet:\n");
dprintf(idx, " out: %s", btos(otraffic_bn + otraffic_bn_today));
dprintf(idx, " (%s today)\n", btos(otraffic_bn_today));
dprintf(idx, " in: %s", btos(itraffic_bn + itraffic_bn_today));
dprintf(idx, " (%s today)\n", btos(itraffic_bn_today));
}
if (otraffic_dcc > 0 || itraffic_dcc > 0 || otraffic_dcc_today > 0 ||
itraffic_dcc_today > 0) {
dprintf(idx, "Partyline:\n");
itmp = otraffic_dcc + otraffic_dcc_today;
itmp2 = otraffic_dcc_today;
dprintf(idx, " out: %s", btos(itmp));
dprintf(idx, " (%s today)\n", btos(itmp2));
dprintf(idx, " in: %s", btos(itraffic_dcc + itraffic_dcc_today));
dprintf(idx, " (%s today)\n", btos(itraffic_dcc_today));
}
if (otraffic_trans > 0 || itraffic_trans > 0 || otraffic_trans_today > 0 ||
itraffic_trans_today > 0) {
dprintf(idx, "Transfer.mod:\n");
dprintf(idx, " out: %s", btos(otraffic_trans + otraffic_trans_today));
dprintf(idx, " (%s today)\n", btos(otraffic_trans_today));
dprintf(idx, " in: %s", btos(itraffic_trans + itraffic_trans_today));
dprintf(idx, " (%s today)\n", btos(itraffic_trans_today));
}
if (otraffic_unknown > 0 || otraffic_unknown_today > 0) {
dprintf(idx, "Misc:\n");
dprintf(idx, " out: %s", btos(otraffic_unknown + otraffic_unknown_today));
dprintf(idx, " (%s today)\n", btos(otraffic_unknown_today));
dprintf(idx, " in: %s", btos(itraffic_unknown + itraffic_unknown_today));
dprintf(idx, " (%s today)\n", btos(itraffic_unknown_today));
}
dprintf(idx, "---\n");
dprintf(idx, "Total:\n");
itmp = otraffic_irc + otraffic_bn + otraffic_dcc + otraffic_trans +
otraffic_unknown + otraffic_irc_today + otraffic_bn_today +
otraffic_dcc_today + otraffic_trans_today + otraffic_unknown_today;
itmp2 = otraffic_irc_today + otraffic_bn_today + otraffic_dcc_today +
otraffic_trans_today + otraffic_unknown_today;
dprintf(idx, " out: %s", btos(itmp));
dprintf(idx, " (%s today)\n", btos(itmp2));
dprintf(idx, " in: %s", btos(itraffic_irc + itraffic_bn + itraffic_dcc +
itraffic_trans + itraffic_unknown + itraffic_irc_today +
itraffic_bn_today + itraffic_dcc_today + itraffic_trans_today +
itraffic_unknown_today));
dprintf(idx, " (%s today)\n", btos(itraffic_irc_today + itraffic_bn_today +
itraffic_dcc_today + itraffic_trans_today + itraffic_unknown_today));
putlog(LOG_CMDS, "*", "#%s# traffic", dcc[idx].nick);
}
static char traffictxt[20];
static char *btos(unsigned long bytes)
{
char unit[10];
float xbytes;
sprintf(unit, "Bytes");
xbytes = bytes;
if (xbytes > 1024.0) {
sprintf(unit, "KBytes");
xbytes = xbytes / 1024.0;
}
if (xbytes > 1024.0) {
sprintf(unit, "MBytes");
xbytes = xbytes / 1024.0;
}
if (xbytes > 1024.0) {
sprintf(unit, "GBytes");
xbytes = xbytes / 1024.0;
}
if (xbytes > 1024.0) {
sprintf(unit, "TBytes");
xbytes = xbytes / 1024.0;
}
if (bytes > 1024)
sprintf(traffictxt, "%.2f %s", xbytes, unit);
else
sprintf(traffictxt, "%lu Bytes", bytes);
return traffictxt;
}
static void cmd_whoami(struct userrec *u, int idx, char *par)
{
dprintf(idx, "You are %s@%s.\n", dcc[idx].nick, botnetnick);
putlog(LOG_CMDS, "*", "#%s# whoami", dcc[idx].nick);
}
/* DCC CHAT COMMANDS
*/
/* Function call should be:
* static void cmd_whatever(struct userrec *u, int idx, char *par);
* As with msg commands, function is responsible for any logging.
*/
cmd_t C_dcc[] = {
{"+bot", "t", (IntFunc) cmd_pls_bot, NULL},
{"+host", "t|m", (IntFunc) cmd_pls_host, NULL},
{"+ignore", "m", (IntFunc) cmd_pls_ignore, NULL},
{"+user", "m", (IntFunc) cmd_pls_user, NULL},
{"-bot", "t", (IntFunc) cmd_mns_user, NULL},
{"-host", "", (IntFunc) cmd_mns_host, NULL},
{"-ignore", "m", (IntFunc) cmd_mns_ignore, NULL},
{"-user", "m", (IntFunc) cmd_mns_user, NULL},
{"addlog", "to|o", (IntFunc) cmd_addlog, NULL},
{"away", "", (IntFunc) cmd_away, NULL},
{"back", "", (IntFunc) cmd_back, NULL},
{"backup", "m|m", (IntFunc) cmd_backup, NULL},
{"banner", "t", (IntFunc) cmd_banner, NULL},
{"binds", "m", (IntFunc) cmd_binds, NULL},
{"boot", "t", (IntFunc) cmd_boot, NULL},
{"botattr", "t", (IntFunc) cmd_botattr, NULL},
{"botinfo", "", (IntFunc) cmd_botinfo, NULL},
{"bots", "", (IntFunc) cmd_bots, NULL},
{"bottree", "", (IntFunc) cmd_bottree, NULL},
{"chaddr", "t", (IntFunc) cmd_chaddr, NULL},
{"chat", "", (IntFunc) cmd_chat, NULL},
{"chattr", "m|m", (IntFunc) cmd_chattr, NULL},
{"chhandle", "t", (IntFunc) cmd_chhandle, NULL},
{"chnick", "t", (IntFunc) cmd_chhandle, NULL},
{"chpass", "t", (IntFunc) cmd_chpass, NULL},
{"comment", "m", (IntFunc) cmd_comment, NULL},
{"console", "to|o", (IntFunc) cmd_console, NULL},
{"dccstat", "t", (IntFunc) cmd_dccstat, NULL},
{"debug", "m", (IntFunc) cmd_debug, NULL},
{"die", "n", (IntFunc) cmd_die, NULL},
{"echo", "", (IntFunc) cmd_echo, NULL},
{"fixcodes", "", (IntFunc) cmd_fixcodes, NULL},
{"help", "", (IntFunc) cmd_help, NULL},
{"ignores", "m", (IntFunc) cmd_ignores, NULL},
{"link", "t", (IntFunc) cmd_link, NULL},
{"loadmod", "n", (IntFunc) cmd_loadmod, NULL},
{"match", "to|o", (IntFunc) cmd_match, NULL},
{"me", "", (IntFunc) cmd_me, NULL},
{"module", "m", (IntFunc) cmd_module, NULL},
{"modules", "n", (IntFunc) cmd_modules, NULL},
{"motd", "", (IntFunc) cmd_motd, NULL},
{"newpass", "", (IntFunc) cmd_newpass, NULL},
{"handle", "", (IntFunc) cmd_handle, NULL},
{"nick", "", (IntFunc) cmd_handle, NULL},
{"page", "", (IntFunc) cmd_page, NULL},
{"quit", "", (IntFunc) CMD_LEAVE, NULL},
{"rehash", "m", (IntFunc) cmd_rehash, NULL},
{"rehelp", "n", (IntFunc) cmd_rehelp, NULL},
{"relay", "o", (IntFunc) cmd_relay, NULL},
{"reload", "m|m", (IntFunc) cmd_reload, NULL},
{"restart", "m", (IntFunc) cmd_restart, NULL},
{"save", "m|m", (IntFunc) cmd_save, NULL},
{"set", "n", (IntFunc) cmd_set, NULL},
{"simul", "n", (IntFunc) cmd_simul, NULL},
{"status", "m|m", (IntFunc) cmd_status, NULL},
{"strip", "", (IntFunc) cmd_strip, NULL},
{"su", "", (IntFunc) cmd_su, NULL},
{"tcl", "n", (IntFunc) cmd_tcl, NULL},
{"trace", "t", (IntFunc) cmd_trace, NULL},
{"unlink", "t", (IntFunc) cmd_unlink, NULL},
{"unloadmod", "n", (IntFunc) cmd_unloadmod, NULL},
{"uptime", "m|m", (IntFunc) cmd_uptime, NULL},
{"vbottree", "", (IntFunc) cmd_vbottree, NULL},
{"who", "", (IntFunc) cmd_who, NULL},
{"whois", "to|o", (IntFunc) cmd_whois, NULL},
{"whom", "", (IntFunc) cmd_whom, NULL},
{"traffic", "m|m", (IntFunc) cmd_traffic, NULL},
{"whoami", "", (IntFunc) cmd_whoami, NULL},
{NULL, NULL, NULL, NULL}
};
| mit |
nonconforme/AtomicGameEngine | Attic/AtomicEditorReference/Source/Build/BuildBase.cpp | 2 | 2749 | // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// Please see LICENSE.md in repository root for license information
// https://github.com/AtomicGameEngine/AtomicGameEngine
#include "AtomicEditor.h"
#include <Atomic/IO/Log.h>
#include <Atomic/IO/FileSystem.h>
#include "BuildBase.h"
#include "ResourcePackager.h"
namespace AtomicEditor
{
BuildBase::BuildBase(Context * context) : Object(context), containsMDL_(false)
{
if (UseResourcePackager())
resourcePackager_ = new ResourcePackager(context, this);
BuildLog("Build Started");
}
BuildBase::~BuildBase()
{
for (unsigned i = 0; i < resourceEntries_.Size(); i++)
{
delete resourceEntries_[i];
}
}
void BuildBase::BuildLog(const String& message)
{
buildLog_.Push(message);
}
void BuildBase::BuildWarn(const String& warning)
{
buildWarnings_.Push(warning);
}
void BuildBase::BuildError(const String& error)
{
buildErrors_.Push(error);
}
void BuildBase::ScanResourceDirectory(const String& resourceDir)
{
Vector<String> fileNames;
FileSystem* fileSystem = GetSubsystem<FileSystem>();
fileSystem->ScanDir(fileNames, resourceDir, "*.*", SCAN_FILES, true);
for (unsigned i = 0; i < fileNames.Size(); i++)
{
const String& filename = fileNames[i];
for (unsigned j = 0; j < resourceEntries_.Size(); j++)
{
const BuildResourceEntry* entry = resourceEntries_[j];
if (entry->packagePath_ == filename)
{
BuildWarn(ToString("Resource Path: %s already exists", filename.CString()));
continue;
}
}
BuildResourceEntry* newEntry = new BuildResourceEntry;
// BEGIN LICENSE MANAGEMENT
if (GetExtension(filename) == ".mdl")
{
containsMDL_ = true;
}
// END LICENSE MANAGEMENT
newEntry->absolutePath_ = resourceDir + filename;
newEntry->packagePath_ = filename;
newEntry->resourceDir_ = resourceDir;
resourceEntries_.Push(newEntry);
}
}
void BuildBase::BuildResourceEntries()
{
for (unsigned i = 0; i < resourceDirs_.Size(); i++)
{
ScanResourceDirectory(resourceDirs_[i]);
}
if (resourcePackager_.NotNull())
{
for (unsigned i = 0; i < resourceEntries_.Size(); i++)
{
BuildResourceEntry* entry = resourceEntries_[i];
resourcePackager_->AddResourceEntry(entry);
}
}
}
void BuildBase::GenerateResourcePackage(const String& resourcePackagePath)
{
resourcePackager_->GeneratePackage(resourcePackagePath);
}
void BuildBase::AddResourceDir(const String& dir)
{
assert(!resourceDirs_.Contains(dir));
resourceDirs_.Push(dir);
}
}
| mit |
chinesebear/rtt-examples | examples/07/application.c | 2 | 19148 | /*
* File : application.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2006-2012, RT-Thread Develop Team
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rt-thread.org/license/LICENSE
*
* Change Logs:
* Date Author Notes
* 2010-06-25 Bernard first version
* 2011-08-08 lgnq modified for Loongson LS1B
* 2015-07-06 chinesebear modified for Loongson LS1C
* 2017-07-26 chinesebear NB-IOT communication
*/
#include <rtthread.h>
#include <components.h>
#include "uart.h"
#include "gpio.h"
#define AT_DEBUG 0
#define SEND_TO_NBIOT 0
#define RECV_FROM_NBIOT 1
#define atCmdGapTime 100 //tick
#define atUart3RxTimeOut 400 //tick
#define atNbiotCreateSocket_type "DGRAM"
#define atNbiotCreateSocket_protocol "17"
#define atNbiotCreateSocket_listen_port "5683"
#define atNbiotCreateSocket_receive_control "1"
#define atNbiotSendMessage_ip "118.190.93.84"
#define atNbiotSendMessage_port "2317"
#define atNbiotTxBufferSize 256
#define atNbiotRxBufferSize 512
#define AT_OK 0
#define AT_FAIL (-1)
#define AT_RESPNOSE_OK AT_OK
#define AT_RESPNOSE_ERROR AT_FAIL
enum AT_NBIOT_UDP_STATE{
AT_AUTO_CONN_CFG,
AT_CREATE_SOCKET,
AT_SEND_MSG,
AT_RECV_MSG,
AT_READ_MSG,
AT_CLOSE_SOCKET,
AT_IDLE
};
enum AT_NBIOT_CoAP_STATE{
AT_QUERY_IEMI,
AT_CFG_CDP_SERVER,
AT_QUERY_CDP_SERVER,
AT_ENABLE_SEND_INDICATE,
AT_ENABLE_NEW_INDICATE,
AT_SEND_CoAP_MSG,
AT_QUERY_RECV,
AT_GET_MSG,
AT_QUERY_RECV2
};
typedef struct socket_message{
int socketid;
int msglen;
}socket_msg;
int atstate = AT_AUTO_CONN_CFG;
int link_NBIOT = SEND_TO_NBIOT;
int socketID;
rt_uint8_t pt_rx_buffer[atNbiotRxBufferSize];
rt_uint8_t pt_tx_buffer[atNbiotTxBufferSize];
int pt_tx_size = 0;
int pt_rx_size = 0;
socket_msg smsg;
static const rt_uint16_t crctab16[] =
{
0X0000, 0X1189, 0X2312, 0X329B, 0X4624, 0X57AD, 0X6536, 0X74BF,
0X8C48, 0X9DC1, 0XAF5A, 0XBED3, 0XCA6C, 0XDBE5, 0XE97E, 0XF8F7,
0X1081, 0X0108, 0X3393, 0X221A, 0X56A5, 0X472C, 0X75B7, 0X643E,
0X9CC9, 0X8D40, 0XBFDB, 0XAE52, 0XDAED, 0XCB64, 0XF9FF, 0XE876,
0X2102, 0X308B, 0X0210, 0X1399, 0X6726, 0X76AF, 0X4434, 0X55BD,
0XAD4A, 0XBCC3, 0X8E58, 0X9FD1, 0XEB6E, 0XFAE7, 0XC87C, 0XD9F5,
0X3183, 0X200A, 0X1291, 0X0318, 0X77A7, 0X662E, 0X54B5, 0X453C,
0XBDCB, 0XAC42, 0X9ED9, 0X8F50, 0XFBEF, 0XEA66, 0XD8FD, 0XC974,
0X4204, 0X538D, 0X6116, 0X709F, 0X0420, 0X15A9, 0X2732, 0X36BB,
0XCE4C, 0XDFC5, 0XED5E, 0XFCD7, 0X8868, 0X99E1, 0XAB7A, 0XBAF3,
0X5285, 0X430C, 0X7197, 0X601E, 0X14A1, 0X0528, 0X37B3, 0X263A,
0XDECD, 0XCF44, 0XFDDF, 0XEC56, 0X98E9, 0X8960, 0XBBFB, 0XAA72,
0X6306, 0X728F, 0X4014, 0X519D, 0X2522, 0X34AB, 0X0630, 0X17B9,
0XEF4E, 0XFEC7, 0XCC5C, 0XDDD5, 0XA96A, 0XB8E3, 0X8A78, 0X9BF1,
0X7387, 0X620E, 0X5095, 0X411C, 0X35A3, 0X242A, 0X16B1, 0X0738,
0XFFCF, 0XEE46, 0XDCDD, 0XCD54, 0XB9EB, 0XA862, 0X9AF9, 0X8B70,
0X8408, 0X9581, 0XA71A, 0XB693, 0XC22C, 0XD3A5, 0XE13E, 0XF0B7,
0X0840, 0X19C9, 0X2B52, 0X3ADB, 0X4E64, 0X5FED, 0X6D76, 0X7CFF,
0X9489, 0X8500, 0XB79B, 0XA612, 0XD2AD, 0XC324, 0XF1BF, 0XE036,
0X18C1, 0X0948, 0X3BD3, 0X2A5A, 0X5EE5, 0X4F6C, 0X7DF7, 0X6C7E,
0XA50A, 0XB483, 0X8618, 0X9791, 0XE32E, 0XF2A7, 0XC03C, 0XD1B5,
0X2942, 0X38CB, 0X0A50, 0X1BD9, 0X6F66, 0X7EEF, 0X4C74, 0X5DFD,
0XB58B, 0XA402, 0X9699, 0X8710, 0XF3AF, 0XE226, 0XD0BD, 0XC134,
0X39C3, 0X284A, 0X1AD1, 0X0B58, 0X7FE7, 0X6E6E, 0X5CF5, 0X4D7C,
0XC60C, 0XD785, 0XE51E, 0XF497, 0X8028, 0X91A1, 0XA33A, 0XB2B3,
0X4A44, 0X5BCD, 0X6956, 0X78DF, 0X0C60, 0X1DE9, 0X2F72, 0X3EFB,
0XD68D, 0XC704, 0XF59F, 0XE416, 0X90A9, 0X8120, 0XB3BB, 0XA232,
0X5AC5, 0X4B4C, 0X79D7, 0X685E, 0X1CE1, 0X0D68, 0X3FF3, 0X2E7A,
0XE70E, 0XF687, 0XC41C, 0XD595, 0XA12A, 0XB0A3, 0X8238, 0X93B1,
0X6B46, 0X7ACF, 0X4854, 0X59DD, 0X2D62, 0X3CEB, 0X0E70, 0X1FF9,
0XF78F, 0XE606, 0XD49D, 0XC514, 0XB1AB, 0XA022, 0X92B9, 0X8330,
0X7BC7, 0X6A4E, 0X58D5, 0X495C, 0X3DE3, 0X2C6A, 0X1EF1, 0X0F78,
};
extern rt_device_t uart_dev[];
static void DumpData(const rt_uint8_t *pcStr,rt_uint8_t *pucBuf,rt_uint32_t usLen)
{
rt_uint32_t i;
rt_uint8_t acTmp[17];
rt_uint8_t *p;
rt_uint8_t *pucAddr = pucBuf;
if(usLen == 0)
{
return;
}
if(pcStr)
{
rt_kprintf("%s: length = %d [0x%X]\r\n", pcStr, usLen, usLen);
}
p = acTmp;
rt_kprintf("%p ", pucAddr);
for(i=0;i<usLen;i++)
{
rt_kprintf("%02X ",pucBuf[i]);
if((pucBuf[i]>=0x20) && (pucBuf[i]<0x7F))
{
*p++ = pucBuf[i];
}
else
{
*p++ = '.';
}
if((i+1)%16==0)
{
*p++ = 0;//string end
rt_kprintf(" | %s", acTmp);
p = acTmp;
rt_kprintf("\r\n");
if((i+1) < usLen)
{
pucAddr += 16;
rt_kprintf("%p ", pucAddr);
}
}
else if((i+1)%8==0)
{
rt_kprintf("- ");
}
}
if(usLen%16!=0)
{
for(i=usLen%16;i<16;i++)
{
rt_kprintf(" ");
if(((i+1)%8==0) && ((i+1)%16!=0))
{
rt_kprintf("- ");
}
}
*p++ = 0;//string end
rt_kprintf(" | %s", acTmp);
rt_kprintf("\r\n");
}
}
static int AtStr2Hex(const char* src, unsigned char* dest)
{
int srcLen,destLen;
unsigned char val;
unsigned char tmp;
int i =0;
//rt_kprintf("Entering AtStr2Hex()\r\n");
if(src == NULL || dest == NULL)
{
return -1;
}
srcLen = strlen(src);
//rt_kprintf("srcLen = %d\r\n",srcLen);
if(srcLen < 1)
{
return -2;
}
if(srcLen%2)
destLen = srcLen/2 + 1;
else
destLen = srcLen/2;
rt_memset(dest,0x00,destLen); //clr dest buf
//rt_kprintf("AtStr2Hex()--1\r\n");
for(i=0;i < srcLen;i++)
{
tmp = *(src+ i);
if(tmp >= '0' && tmp <= '9')
{
val = tmp -'0';
}
else if(tmp >= 'A' && tmp <= 'F')
{
val = tmp -'A' + 10;
}
else
return -3;
if(i%2 == 0)//high half byte
{
*(dest+ i/2) |= (val<<4);
}
else // low half byte
{
*(dest+ i/2) |= val;
}
//rt_kprintf("dest(%d) = 0x%02X\r\n",i/2,*(dest+ i/2));
}
return 0;
}
static rt_uint16_t AtGetCrc16(const rt_uint8_t* pData, int nLength)
{
rt_uint16_t fcs = 0xffff;
while(nLength>0){
fcs = (fcs >> 8) ^ crctab16[(fcs ^ *pData) & 0xff];
nLength--;
pData++;
}
return ~fcs;
}
static int AtStrCompare(const void * recvBuf,const int recvSize,const void* cmpStr)
{
int i,iRet =0;
int cmpStrSize;
cmpStrSize = strlen(cmpStr);
#if AT_DEBUG
{
DumpData("StrCompare",(rt_uint8_t *)recvBuf,recvSize);
DumpData("StrCmpwith",(rt_uint8_t *)cmpStr,cmpStrSize);
}
#endif
for(i = 0; i< recvSize;i++)
{
if(rt_memcmp(recvBuf+i,cmpStr,cmpStrSize)==0)
{
iRet= 1;
break;
}
}
return iRet;
}
static int AtCheckRecvData(const void * recvBuf,const int recvSize)
{
if( AtStrCompare(recvBuf,recvSize,"OK"))
return AT_RESPNOSE_OK;
else
return AT_RESPNOSE_ERROR;
}
static int AtGetSocketId(const void * recvBuf,const int recvSize)
{
int i;
rt_uint8_t ch;
int socketid = AT_FAIL;
if(AtCheckRecvData(recvBuf,recvSize) == AT_RESPNOSE_OK)
{
for(i=0;i<recvSize;i++)
{
ch = *(rt_uint8_t*)(recvBuf+i);
if('0' <= ch && ch <= '9')
{
socketid = socketid*10 + (ch-'0');
}
}
rt_kprintf("socket ID = %d!\r\n",socketid);
return socketid;
}
else
{
rt_kprintf("reponse msg is NOK!\r\n");
return AT_FAIL;
}
}
rt_size_t AtUart3Read(rt_device_t dev,void *buffer,rt_size_t size)
{
int rx_size = 0,rx_size1 =0;
int i=0,j=0,flag = 0;
unsigned char * tmp;
tmp = (unsigned char*)buffer;
while(i < atUart3RxTimeOut)
{
// check string with key words "ERROR" & "OK"
if(AtStrCompare(buffer,rx_size,"ERROR")|| AtStrCompare(buffer,rx_size,"OK"))
{
break;
}
rt_thread_delay(2);
rx_size1 = rt_device_read(dev,0,buffer+rx_size,size-rx_size);
rx_size += rx_size1;//update rx_size value
if(rx_size)break;
i++;
}
DumpData("Uart3Rx",buffer,rx_size);
return rx_size;
}
static rt_size_t AtUart3ReadTimeOut(rt_device_t dev,void *buffer,rt_size_t size,int TimeOutMs)
{
int rx_size = 0,rx_size1 =0;
int i=0,j=0,flag = 0;
int flagLoop=1;
int ticktimeout=0;
unsigned char * tmp;
tmp = (unsigned char*)buffer;
if(TimeOutMs == -1)
{
while(1)
{
// check string with key words "ERROR" & "OK"
if(AtStrCompare(buffer,rx_size,"ERROR")|| AtStrCompare(buffer,rx_size,"OK"))
{
break;
}
rt_thread_delay(2);
rx_size1 = rt_device_read(dev,0,buffer+rx_size,size-rx_size);
rx_size += rx_size1;//update rx_size value
}
}
else
{
ticktimeout = TimeOutMs / 20;
while(i < ticktimeout)
{
// check string with key words "ERROR" & "OK"
if(AtStrCompare(buffer,rx_size,"ERROR")|| AtStrCompare(buffer,rx_size,"OK"))
{
break;
}
rt_thread_delay(2);
rx_size1 = rt_device_read(dev,0,buffer+rx_size,size-rx_size);
rx_size += rx_size1;//update rx_size value
i++;
}
}
DumpData("AtUart3Rx",buffer,rx_size);
return rx_size;
}
static void nbiot_atcmd_NCONFIG(rt_device_t newdev)
{
char* ATcmd;
int rx_size,iRet,infopos;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
switch(link_NBIOT)
{
case SEND_TO_NBIOT:
rt_kprintf("[AT_AUTO_CONN_CFG] enter\r\n");
ATcmd = "AT+NCONFIG=AUTOCONNECT,TRUE\n";
DumpData("ATcmd",ATcmd,strlen(ATcmd));
rt_device_write(newdev,0,ATcmd,strlen(ATcmd));
link_NBIOT = RECV_FROM_NBIOT;
break;
case RECV_FROM_NBIOT:
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,-1);
iRet = AtCheckRecvData(rx_buffer,rx_size);
if(iRet == AT_RESPNOSE_OK)
{
atstate = AT_CREATE_SOCKET;
link_NBIOT = SEND_TO_NBIOT;
rt_kprintf("[AT_AUTO_CONN_CFG] OK\r\n");
rt_thread_delay(atCmdGapTime);
}
else
{
rt_kprintf("[AT_AUTO_CONN_CFG](error)\r\n");
}
rt_kprintf("[AT_AUTO_CONN_CFG] exit\r\n");
break;
default:
rt_kprintf("[AT_AUTO_CONN_CFG] link_NBIOT err state\r\n");
break;
}
}
static void nbiot_atcmd_NSOCR(rt_device_t newdev)
{
/*
Create a socket
AT+NSOCR= DGRAM,17,5683,1
*/
char* ATcmd;
int rx_size,iRet,infopos;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
switch(link_NBIOT)
{
case SEND_TO_NBIOT:
rt_kprintf("[AT_CREATE_SOCKET] enter\r\n");
rt_sprintf(tx_buffer,"AT+NSOCR=%s,%s,%s,%s\n",
atNbiotCreateSocket_type,atNbiotCreateSocket_protocol,
atNbiotCreateSocket_listen_port,atNbiotCreateSocket_receive_control);
DumpData("ATcmd",tx_buffer,strlen(tx_buffer));
rt_device_write(newdev,0,tx_buffer,strlen(tx_buffer));
link_NBIOT = RECV_FROM_NBIOT;
break;
case RECV_FROM_NBIOT:
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,-1);
iRet = AtCheckRecvData(rx_buffer,rx_size);
if(iRet == AT_RESPNOSE_OK)
{
atstate = SEND_TO_NBIOT;
link_NBIOT = SEND_TO_NBIOT;
socketID = AtGetSocketId(rx_buffer,rx_size);
rt_kprintf("[AT_CREATE_SOCKET] OK\r\n");
rt_thread_delay(atCmdGapTime);
}
else
{
rt_kprintf("[AT_CREATE_SOCKET](error)\r\n");
}
rt_kprintf("[AT_CREATE_SOCKET] exit\r\n");
break;
default:
rt_kprintf("[AT_CREATE_SOCKET] link_NBIOT err state\r\n");
break;
}
}
static void nbiot_atcmd_NSOST(rt_device_t newdev)
{
/*
Send a message
AT+NSOST=0,192.53.100.53,5683,25,400241C7B17401724D0265703D323031363038323331363438
<socket> Socket number returned by AT+NSOCR
<remote_addr> IPv4 A dot notation IP address
<remote_port> A number in the range 0-65535. This is the remote port on which messages will be received
<length> Decimal length of data to be sent
<data> Data received in hex string format, or quoted string format
*/
char* ATcmd;
int rx_size,iRet,infopos;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
switch(link_NBIOT)
{
case SEND_TO_NBIOT:
rt_kprintf("[AT_SEND_MSG] enter\r\n");
rt_sprintf(tx_buffer,"AT+NSOST=%d,%s,%s,%d,%s\n",
socketID,atNbiotSendMessage_ip,
atNbiotSendMessage_port,10,"hello NB!!!!!!");
DumpData("ATcmd",tx_buffer,strlen(tx_buffer));
rt_device_write(newdev,0,tx_buffer,strlen(tx_buffer));
link_NBIOT = RECV_FROM_NBIOT;
break;
case RECV_FROM_NBIOT:
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,-1);
iRet = AtCheckRecvData(rx_buffer,rx_size);
if(iRet == AT_RESPNOSE_OK)
{
atstate = AT_RECV_MSG;
link_NBIOT = SEND_TO_NBIOT;
rt_kprintf("[AT_SEND_MSG] OK\r\n");
rt_thread_delay(atCmdGapTime);
}
else
{
rt_kprintf("[AT_SEND_MSG](error)\r\n");
}
rt_kprintf("[AT_SEND_MSG] exit\r\n");
break;
default:
rt_kprintf("[AT_SEND_MSG] link_NBIOT err state\r\n");
break;
}
}
static void nbiot_atcmd_NSONMI(rt_device_t newdev)
{
/*
Receive the message
+NSONMI:0,4
*/
int rx_size,i,startpos =0,socketid=0,slen=0;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_uint8_t ch;
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
rt_kprintf("[AT_RECV_MSG] enter\r\n");
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,1000);
if(rx_size)
{
for(i=0;i<rx_size;i++)
{
if(rt_memcmp((rx_buffer+i),"+NSONMI:",8)==0)
{
startpos = i+8;
break;
}
}
if(startpos == 0 )return ;
for(i=startpos;i<rx_size;i++)
{
ch= *(rx_buffer + i);
if('0' <= ch && ch <= '9')
{
socketid = socketid*10+(ch -'0');
}
if(ch == ',')
{
startpos = i+1;
break;
}
}
for(i=startpos;i<rx_size;i++)
{
ch= *(rx_buffer + i);
if('0' <= ch && ch <= '9')
{
slen = slen*10+(ch -'0');
}
}
rt_kprintf("socket ID = %d,message len = !\r\n",socketid,slen);
smsg.socketid = socketid;
smsg.msglen = slen;
atstate = AT_READ_MSG;
link_NBIOT = SEND_TO_NBIOT;
}
rt_kprintf("[AT_RECV_MSG] exit\r\n");
}
static void nbiot_atcmd_NSORF(rt_device_t newdev)
{
/*
Read the messages
AT+NSORF=0,4
*/
char* ATcmd;
int rx_size,iRet,infopos;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
switch(link_NBIOT)
{
case SEND_TO_NBIOT:
rt_kprintf("[AT_READ_MSG] enter\r\n");
rt_sprintf(tx_buffer,"AT+NSORF=%d,%d\n",smsg.socketid,smsg.msglen);
DumpData("ATcmd",tx_buffer,strlen(tx_buffer));
rt_device_write(newdev,0,tx_buffer,strlen(tx_buffer));
link_NBIOT = RECV_FROM_NBIOT;
break;
case RECV_FROM_NBIOT:
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,-1);
iRet = AtCheckRecvData(rx_buffer,rx_size);
if(iRet == AT_RESPNOSE_OK)
{
atstate = AT_RECV_MSG;
link_NBIOT = RECV_FROM_NBIOT;
/*
<socket>,<ip_addr>,<port>,<length>,<data>,<remaining_length>
*/
rt_kprintf("[AT_READ_MSG] OK\r\n");
rt_thread_delay(atCmdGapTime);
}
else
{
rt_kprintf("[AT_READ_MSG](error)\r\n");
}
rt_kprintf("[AT_READ_MSG] exit\r\n");
break;
default:
rt_kprintf("[AT_READ_MSG] link_NBIOT err state\r\n");
break;
}
}
static void nbiot_atcmd_NSOCL(rt_device_t newdev)
{
/*
Close the socket
AT+NSOCL=0
*/
char* ATcmd;
int rx_size,iRet,infopos;
rt_uint8_t rx_buffer[atNbiotRxBufferSize];
rt_uint8_t tx_buffer[atNbiotTxBufferSize];
rt_memset(rx_buffer,0x00,atNbiotRxBufferSize);
rt_memset(tx_buffer,0x00,atNbiotTxBufferSize);
switch(link_NBIOT)
{
case SEND_TO_NBIOT:
rt_kprintf("[AT_CLOSE_SOCKET] enter\r\n");
rt_sprintf(tx_buffer,"AT+NSOCL=%d\n",socketID);
DumpData("ATcmd",tx_buffer,strlen(tx_buffer));
rt_device_write(newdev,0,tx_buffer,strlen(tx_buffer));
link_NBIOT = RECV_FROM_NBIOT;
break;
case RECV_FROM_NBIOT:
rx_size = AtUart3ReadTimeOut(newdev,rx_buffer,256,-1);
iRet = AtCheckRecvData(rx_buffer,rx_size);
if(iRet == AT_RESPNOSE_OK)
{
atstate = AT_IDLE;
link_NBIOT = RECV_FROM_NBIOT;
rt_kprintf("[AT_CLOSE_SOCKET] OK\r\n");
rt_thread_delay(atCmdGapTime);
}
else
{
rt_kprintf("[AT_CLOSE_SOCKET](error)\r\n");
}
rt_kprintf("[AT_CLOSE_SOCKET] exit\r\n");
break;
default:
rt_kprintf("[AT_CLOSE_SOCKET] link_NBIOT err state\r\n");
break;
}
}
void rt_init_thread_entry(void *parameter)
{
/* initialization RT-Thread Components */
rt_components_init();
}
void rt_run_example_thread_entry(void *parameter)
{
rt_uint8_t rx_buffer[256];
rt_uint8_t tx_buffer[256];
rt_device_t newdev;
rt_err_t iRet;
rt_uint32_t rx_size,tx_size;
rt_kprintf("uart1 thread start...\r\n");
newdev = rt_device_find("uart1");
if(newdev == NULL)
{
rt_kprintf("find no uart1\r\n");
return ;
}
iRet = rt_device_open(newdev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
if(iRet)
{
rt_kprintf("open uart1 failure\r\n");
return ;
}
//rt_pad_show();
for(;;)
{
rt_thread_delay(100);
}
rt_kprintf("never get here...\r\n");
}
void rt_run_example2_thread_entry(void *parameter)
{
rt_device_t newdev;
rt_uint32_t rx_size,tx_size;
char* ATcmd,PtData;
rt_uint8_t rx_buffer[256];
rt_uint8_t tx_buffer[256];
int pos,iRet;
rt_kprintf("uart3 thread start...\r\n");
newdev = rt_device_find("uart3");
if(newdev == NULL)
{
rt_kprintf("find no uart3\r\n");
return ;
}
iRet = rt_device_open(newdev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
if(iRet)
{
rt_kprintf("open uart3 failure\r\n");
return ;
}
//rt_pad_show();
for(;;)
{
rt_memset(rx_buffer,0,256);
rt_memset(tx_buffer,0,256);
switch(atstate)
{
case AT_AUTO_CONN_CFG:
nbiot_atcmd_NCONFIG(newdev);
break;
case AT_CREATE_SOCKET:
nbiot_atcmd_NSOCR(newdev);
break;
case AT_SEND_MSG:
nbiot_atcmd_NSOST(newdev);
break;
case AT_RECV_MSG:
nbiot_atcmd_NSONMI(newdev);
break;
case AT_READ_MSG:
nbiot_atcmd_NSORF(newdev);
break;
case AT_CLOSE_SOCKET:
nbiot_atcmd_NSOCL(newdev);
break;
case AT_IDLE:
rt_thread_delay(100);
break;
default:
rt_thread_delay(100);
break;
}
rt_thread_delay(1);
}
rt_kprintf("never get here...\r\n");
}
int rt_application_init(void)
{
rt_thread_t tid,tid1,tid2,tid3;
rt_thread_t sid;
/* create initialization thread */
tid = rt_thread_create("init",
rt_init_thread_entry, RT_NULL,
4096, RT_THREAD_PRIORITY_MAX/3, 20);
if (tid != RT_NULL)
rt_thread_startup(tid);
else
return -1;
/*create example thread*/
tid1 = rt_thread_create("example",
rt_run_example_thread_entry, RT_NULL,
4096, 16, 20);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
else
return -1;
/*create example2 thread*/
tid2 = rt_thread_create("example2",
rt_run_example2_thread_entry, RT_NULL,
4096, 17, 20);
if (tid2 != RT_NULL)
rt_thread_startup(tid2);
else
return -1;
return 0;
}
| mit |
netmask/rembox | ext/termbox/termbox_wrap.c | 2 | 94648 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGRUBY
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* -----------------------------------------------------------------------------
* swigrun.swg
*
* This file contains generic C API SWIG runtime support for pointer
* type checking.
* ----------------------------------------------------------------------------- */
/* This should only be incremented when either the layout of swig_type_info changes,
or for whatever reason, the runtime changes incompatibly */
#define SWIG_RUNTIME_VERSION "4"
/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
#ifdef SWIG_TYPE_TABLE
# define SWIG_QUOTE_STRING(x) #x
# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
#else
# define SWIG_TYPE_TABLE_NAME
#endif
/*
You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
creating a static or dynamic library from the SWIG runtime code.
In 99.9% of the cases, SWIG just needs to declare them as 'static'.
But only do this if strictly necessary, ie, if you have problems
with your compiler or suchlike.
*/
#ifndef SWIGRUNTIME
# define SWIGRUNTIME SWIGINTERN
#endif
#ifndef SWIGRUNTIMEINLINE
# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
#endif
/* Generic buffer size */
#ifndef SWIG_BUFFER_SIZE
# define SWIG_BUFFER_SIZE 1024
#endif
/* Flags for pointer conversions */
#define SWIG_POINTER_DISOWN 0x1
#define SWIG_CAST_NEW_MEMORY 0x2
/* Flags for new pointer objects */
#define SWIG_POINTER_OWN 0x1
/*
Flags/methods for returning states.
The SWIG conversion methods, as ConvertPtr, return an integer
that tells if the conversion was successful or not. And if not,
an error code can be returned (see swigerrors.swg for the codes).
Use the following macros/flags to set or process the returning
states.
In old versions of SWIG, code such as the following was usually written:
if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
// success code
} else {
//fail code
}
Now you can be more explicit:
int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
if (SWIG_IsOK(res)) {
// success code
} else {
// fail code
}
which is the same really, but now you can also do
Type *ptr;
int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
if (SWIG_IsOK(res)) {
// success code
if (SWIG_IsNewObj(res) {
...
delete *ptr;
} else {
...
}
} else {
// fail code
}
I.e., now SWIG_ConvertPtr can return new objects and you can
identify the case and take care of the deallocation. Of course that
also requires SWIG_ConvertPtr to return new result values, such as
int SWIG_ConvertPtr(obj, ptr,...) {
if (<obj is ok>) {
if (<need new object>) {
*ptr = <ptr to new allocated object>;
return SWIG_NEWOBJ;
} else {
*ptr = <ptr to old object>;
return SWIG_OLDOBJ;
}
} else {
return SWIG_BADOBJ;
}
}
Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
SWIG errors code.
Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
allows to return the 'cast rank', for example, if you have this
int food(double)
int fooi(int);
and you call
food(1) // cast rank '1' (1 -> 1.0)
fooi(1) // cast rank '0'
just use the SWIG_AddCast()/SWIG_CheckState()
*/
#define SWIG_OK (0)
#define SWIG_ERROR (-1)
#define SWIG_IsOK(r) (r >= 0)
#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError)
/* The CastRankLimit says how many bits are used for the cast rank */
#define SWIG_CASTRANKLIMIT (1 << 8)
/* The NewMask denotes the object was created (using new/malloc) */
#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1)
/* The TmpMask is for in/out typemaps that use temporal objects */
#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1)
/* Simple returning values */
#define SWIG_BADOBJ (SWIG_ERROR)
#define SWIG_OLDOBJ (SWIG_OK)
#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK)
#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK)
/* Check, add and del mask methods */
#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
/* Cast-Rank Mode */
#if defined(SWIG_CASTRANK_MODE)
# ifndef SWIG_TypeRank
# define SWIG_TypeRank unsigned long
# endif
# ifndef SWIG_MAXCASTRANK /* Default cast allowed */
# define SWIG_MAXCASTRANK (2)
# endif
# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1)
# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK)
SWIGINTERNINLINE int SWIG_AddCast(int r) {
return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
}
SWIGINTERNINLINE int SWIG_CheckState(int r) {
return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0;
}
#else /* no cast-rank mode */
# define SWIG_AddCast(r) (r)
# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
#endif
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*swig_converter_func)(void *, int *);
typedef struct swig_type_info *(*swig_dycast_func)(void **);
/* Structure to store information on one type */
typedef struct swig_type_info {
const char *name; /* mangled name of this type */
const char *str; /* human readable name of this type */
swig_dycast_func dcast; /* dynamic cast function down a hierarchy */
struct swig_cast_info *cast; /* linked list of types that can cast into this type */
void *clientdata; /* language specific type data */
int owndata; /* flag if the structure owns the clientdata */
} swig_type_info;
/* Structure to store a type and conversion function used for casting */
typedef struct swig_cast_info {
swig_type_info *type; /* pointer to type that is equivalent to this type */
swig_converter_func converter; /* function to cast the void pointers */
struct swig_cast_info *next; /* pointer to next cast in linked list */
struct swig_cast_info *prev; /* pointer to the previous cast */
} swig_cast_info;
/* Structure used to store module information
* Each module generates one structure like this, and the runtime collects
* all of these structures and stores them in a circularly linked list.*/
typedef struct swig_module_info {
swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */
size_t size; /* Number of types in this module */
struct swig_module_info *next; /* Pointer to next element in circularly linked list */
swig_type_info **type_initial; /* Array of initially generated type structures */
swig_cast_info **cast_initial; /* Array of initially generated casting structures */
void *clientdata; /* Language specific module data */
} swig_module_info;
/*
Compare two type names skipping the space characters, therefore
"char*" == "char *" and "Class<int>" == "Class<int >", etc.
Return 0 when the two name types are equivalent, as in
strncmp, but skipping ' '.
*/
SWIGRUNTIME int
SWIG_TypeNameComp(const char *f1, const char *l1,
const char *f2, const char *l2) {
for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
while ((*f1 == ' ') && (f1 != l1)) ++f1;
while ((*f2 == ' ') && (f2 != l2)) ++f2;
if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
}
return (int)((l1 - f1) - (l2 - f2));
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
Return 0 if equal, -1 if nb < tb, 1 if nb > tb
*/
SWIGRUNTIME int
SWIG_TypeCmp(const char *nb, const char *tb) {
int equiv = 1;
const char* te = tb + strlen(tb);
const char* ne = nb;
while (equiv != 0 && *ne) {
for (nb = ne; *ne; ++ne) {
if (*ne == '|') break;
}
equiv = SWIG_TypeNameComp(nb, ne, tb, te);
if (*ne) ++ne;
}
return equiv;
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
Return 0 if not equal, 1 if equal
*/
SWIGRUNTIME int
SWIG_TypeEquiv(const char *nb, const char *tb) {
return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0;
}
/*
Check the typename
*/
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheck(const char *c, swig_type_info *ty) {
if (ty) {
swig_cast_info *iter = ty->cast;
while (iter) {
if (strcmp(iter->type->name, c) == 0) {
if (iter == ty->cast)
return iter;
/* Move iter to the top of the linked list */
iter->prev->next = iter->next;
if (iter->next)
iter->next->prev = iter->prev;
iter->next = ty->cast;
iter->prev = 0;
if (ty->cast) ty->cast->prev = iter;
ty->cast = iter;
return iter;
}
iter = iter->next;
}
}
return 0;
}
/*
Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison
*/
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) {
if (ty) {
swig_cast_info *iter = ty->cast;
while (iter) {
if (iter->type == from) {
if (iter == ty->cast)
return iter;
/* Move iter to the top of the linked list */
iter->prev->next = iter->next;
if (iter->next)
iter->next->prev = iter->prev;
iter->next = ty->cast;
iter->prev = 0;
if (ty->cast) ty->cast->prev = iter;
ty->cast = iter;
return iter;
}
iter = iter->next;
}
}
return 0;
}
/*
Cast a pointer up an inheritance hierarchy
*/
SWIGRUNTIMEINLINE void *
SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
}
/*
Dynamic pointer casting. Down an inheritance hierarchy
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
swig_type_info *lastty = ty;
if (!ty || !ty->dcast) return ty;
while (ty && (ty->dcast)) {
ty = (*ty->dcast)(ptr);
if (ty) lastty = ty;
}
return lastty;
}
/*
Return the name associated with this type
*/
SWIGRUNTIMEINLINE const char *
SWIG_TypeName(const swig_type_info *ty) {
return ty->name;
}
/*
Return the pretty name associated with this type,
that is an unmangled type name in a form presentable to the user.
*/
SWIGRUNTIME const char *
SWIG_TypePrettyName(const swig_type_info *type) {
/* The "str" field contains the equivalent pretty names of the
type, separated by vertical-bar characters. We choose
to print the last name, as it is often (?) the most
specific. */
if (!type) return NULL;
if (type->str != NULL) {
const char *last_name = type->str;
const char *s;
for (s = type->str; *s; s++)
if (*s == '|') last_name = s+1;
return last_name;
}
else
return type->name;
}
/*
Set the clientdata field for a type
*/
SWIGRUNTIME void
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
swig_cast_info *cast = ti->cast;
/* if (ti->clientdata == clientdata) return; */
ti->clientdata = clientdata;
while (cast) {
if (!cast->converter) {
swig_type_info *tc = cast->type;
if (!tc->clientdata) {
SWIG_TypeClientData(tc, clientdata);
}
}
cast = cast->next;
}
}
SWIGRUNTIME void
SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
SWIG_TypeClientData(ti, clientdata);
ti->owndata = 1;
}
/*
Search for a swig_type_info structure only by mangled name
Search is a O(log #types)
We start searching at module start, and finish searching when start == end.
Note: if start == end at the beginning of the function, we go all the way around
the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_MangledTypeQueryModule(swig_module_info *start,
swig_module_info *end,
const char *name) {
swig_module_info *iter = start;
do {
if (iter->size) {
register size_t l = 0;
register size_t r = iter->size - 1;
do {
/* since l+r >= 0, we can (>> 1) instead (/ 2) */
register size_t i = (l + r) >> 1;
const char *iname = iter->types[i]->name;
if (iname) {
register int compare = strcmp(name, iname);
if (compare == 0) {
return iter->types[i];
} else if (compare < 0) {
if (i) {
r = i - 1;
} else {
break;
}
} else if (compare > 0) {
l = i + 1;
}
} else {
break; /* should never happen */
}
} while (l <= r);
}
iter = iter->next;
} while (iter != end);
return 0;
}
/*
Search for a swig_type_info structure for either a mangled name or a human readable name.
It first searches the mangled names of the types, which is a O(log #types)
If a type is not found it then searches the human readable names, which is O(#types).
We start searching at module start, and finish searching when start == end.
Note: if start == end at the beginning of the function, we go all the way around
the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeQueryModule(swig_module_info *start,
swig_module_info *end,
const char *name) {
/* STEP 1: Search the name field using binary search */
swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
if (ret) {
return ret;
} else {
/* STEP 2: If the type hasn't been found, do a complete search
of the str field (the human readable name) */
swig_module_info *iter = start;
do {
register size_t i = 0;
for (; i < iter->size; ++i) {
if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
return iter->types[i];
}
iter = iter->next;
} while (iter != end);
}
/* neither found a match */
return 0;
}
/*
Pack binary data into a string
*/
SWIGRUNTIME char *
SWIG_PackData(char *c, void *ptr, size_t sz) {
static const char hex[17] = "0123456789abcdef";
register const unsigned char *u = (unsigned char *) ptr;
register const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
register unsigned char uu = *u;
*(c++) = hex[(uu & 0xf0) >> 4];
*(c++) = hex[uu & 0xf];
}
return c;
}
/*
Unpack binary data from a string
*/
SWIGRUNTIME const char *
SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
register unsigned char *u = (unsigned char *) ptr;
register const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
register char d = *(c++);
register unsigned char uu;
if ((d >= '0') && (d <= '9'))
uu = ((d - '0') << 4);
else if ((d >= 'a') && (d <= 'f'))
uu = ((d - ('a'-10)) << 4);
else
return (char *) 0;
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu |= (d - '0');
else if ((d >= 'a') && (d <= 'f'))
uu |= (d - ('a'-10));
else
return (char *) 0;
*u = uu;
}
return c;
}
/*
Pack 'void *' into a string buffer.
*/
SWIGRUNTIME char *
SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
char *r = buff;
if ((2*sizeof(void *) + 2) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,&ptr,sizeof(void *));
if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
strcpy(r,name);
return buff;
}
SWIGRUNTIME const char *
SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
*ptr = (void *) 0;
return name;
} else {
return 0;
}
}
return SWIG_UnpackData(++c,ptr,sizeof(void *));
}
SWIGRUNTIME char *
SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
char *r = buff;
size_t lname = (name ? strlen(name) : 0);
if ((2*sz + 2 + lname) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,ptr,sz);
if (lname) {
strncpy(r,name,lname+1);
} else {
*r = 0;
}
return buff;
}
SWIGRUNTIME const char *
SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
memset(ptr,0,sz);
return name;
} else {
return 0;
}
}
return SWIG_UnpackData(++c,ptr,sz);
}
#ifdef __cplusplus
}
#endif
/* Errors in SWIG */
#define SWIG_UnknownError -1
#define SWIG_IOError -2
#define SWIG_RuntimeError -3
#define SWIG_IndexError -4
#define SWIG_TypeError -5
#define SWIG_DivisionByZero -6
#define SWIG_OverflowError -7
#define SWIG_SyntaxError -8
#define SWIG_ValueError -9
#define SWIG_SystemError -10
#define SWIG_AttributeError -11
#define SWIG_MemoryError -12
#define SWIG_NullReferenceError -13
#include <ruby.h>
/* Ruby 1.9.1 has a "memoisation optimisation" when compiling with GCC which
* breaks using rb_intern as an lvalue, as SWIG does. We work around this
* issue for now by disabling this.
* https://sourceforge.net/tracker/?func=detail&aid=2859614&group_id=1645&atid=101645
*/
#ifdef rb_intern
# undef rb_intern
#endif
/* Remove global macros defined in Ruby's win32.h */
#ifdef write
# undef write
#endif
#ifdef read
# undef read
#endif
#ifdef bind
# undef bind
#endif
#ifdef close
# undef close
#endif
#ifdef connect
# undef connect
#endif
/* Ruby 1.7 defines NUM2LL(), LL2NUM() and ULL2NUM() macros */
#ifndef NUM2LL
#define NUM2LL(x) NUM2LONG((x))
#endif
#ifndef LL2NUM
#define LL2NUM(x) INT2NUM((long) (x))
#endif
#ifndef ULL2NUM
#define ULL2NUM(x) UINT2NUM((unsigned long) (x))
#endif
/* Ruby 1.7 doesn't (yet) define NUM2ULL() */
#ifndef NUM2ULL
#ifdef HAVE_LONG_LONG
#define NUM2ULL(x) rb_num2ull((x))
#else
#define NUM2ULL(x) NUM2ULONG(x)
#endif
#endif
/* RSTRING_LEN, etc are new in Ruby 1.9, but ->ptr and ->len no longer work */
/* Define these for older versions so we can just write code the new way */
#ifndef RSTRING_LEN
# define RSTRING_LEN(x) RSTRING(x)->len
#endif
#ifndef RSTRING_PTR
# define RSTRING_PTR(x) RSTRING(x)->ptr
#endif
#ifndef RSTRING_END
# define RSTRING_END(x) (RSTRING_PTR(x) + RSTRING_LEN(x))
#endif
#ifndef RARRAY_LEN
# define RARRAY_LEN(x) RARRAY(x)->len
#endif
#ifndef RARRAY_PTR
# define RARRAY_PTR(x) RARRAY(x)->ptr
#endif
#ifndef RFLOAT_VALUE
# define RFLOAT_VALUE(x) RFLOAT(x)->value
#endif
#ifndef DOUBLE2NUM
# define DOUBLE2NUM(x) rb_float_new(x)
#endif
#ifndef RHASH_TBL
# define RHASH_TBL(x) (RHASH(x)->tbl)
#endif
#ifndef RHASH_ITER_LEV
# define RHASH_ITER_LEV(x) (RHASH(x)->iter_lev)
#endif
#ifndef RHASH_IFNONE
# define RHASH_IFNONE(x) (RHASH(x)->ifnone)
#endif
#ifndef RHASH_SIZE
# define RHASH_SIZE(x) (RHASH(x)->tbl->num_entries)
#endif
#ifndef RHASH_EMPTY_P
# define RHASH_EMPTY_P(x) (RHASH_SIZE(x) == 0)
#endif
#ifndef RSTRUCT_LEN
# define RSTRUCT_LEN(x) RSTRUCT(x)->len
#endif
#ifndef RSTRUCT_PTR
# define RSTRUCT_PTR(x) RSTRUCT(x)->ptr
#endif
/*
* Need to be very careful about how these macros are defined, especially
* when compiling C++ code or C code with an ANSI C compiler.
*
* VALUEFUNC(f) is a macro used to typecast a C function that implements
* a Ruby method so that it can be passed as an argument to API functions
* like rb_define_method() and rb_define_singleton_method().
*
* VOIDFUNC(f) is a macro used to typecast a C function that implements
* either the "mark" or "free" stuff for a Ruby Data object, so that it
* can be passed as an argument to API functions like Data_Wrap_Struct()
* and Data_Make_Struct().
*/
#ifdef __cplusplus
# ifndef RUBY_METHOD_FUNC /* These definitions should work for Ruby 1.4.6 */
# define PROTECTFUNC(f) ((VALUE (*)()) f)
# define VALUEFUNC(f) ((VALUE (*)()) f)
# define VOIDFUNC(f) ((void (*)()) f)
# else
# ifndef ANYARGS /* These definitions should work for Ruby 1.6 */
# define PROTECTFUNC(f) ((VALUE (*)()) f)
# define VALUEFUNC(f) ((VALUE (*)()) f)
# define VOIDFUNC(f) ((RUBY_DATA_FUNC) f)
# else /* These definitions should work for Ruby 1.7+ */
# define PROTECTFUNC(f) ((VALUE (*)(VALUE)) f)
# define VALUEFUNC(f) ((VALUE (*)(ANYARGS)) f)
# define VOIDFUNC(f) ((RUBY_DATA_FUNC) f)
# endif
# endif
#else
# define VALUEFUNC(f) (f)
# define VOIDFUNC(f) (f)
#endif
/* Don't use for expressions have side effect */
#ifndef RB_STRING_VALUE
#define RB_STRING_VALUE(s) (TYPE(s) == T_STRING ? (s) : (*(volatile VALUE *)&(s) = rb_str_to_str(s)))
#endif
#ifndef StringValue
#define StringValue(s) RB_STRING_VALUE(s)
#endif
#ifndef StringValuePtr
#define StringValuePtr(s) RSTRING_PTR(RB_STRING_VALUE(s))
#endif
#ifndef StringValueLen
#define StringValueLen(s) RSTRING_LEN(RB_STRING_VALUE(s))
#endif
#ifndef SafeStringValue
#define SafeStringValue(v) do {\
StringValue(v);\
rb_check_safe_str(v);\
} while (0)
#endif
#ifndef HAVE_RB_DEFINE_ALLOC_FUNC
#define rb_define_alloc_func(klass, func) rb_define_singleton_method((klass), "new", VALUEFUNC((func)), -1)
#define rb_undef_alloc_func(klass) rb_undef_method(CLASS_OF((klass)), "new")
#endif
static VALUE _mSWIG = Qnil;
/* -----------------------------------------------------------------------------
* error manipulation
* ----------------------------------------------------------------------------- */
/* Define some additional error types */
#define SWIG_ObjectPreviouslyDeletedError -100
/* Define custom exceptions for errors that do not map to existing Ruby
exceptions. Note this only works for C++ since a global cannot be
initialized by a function in C. For C, fallback to rb_eRuntimeError.*/
SWIGINTERN VALUE
getNullReferenceError(void) {
static int init = 0;
static VALUE rb_eNullReferenceError ;
if (!init) {
init = 1;
rb_eNullReferenceError = rb_define_class("NullReferenceError", rb_eRuntimeError);
}
return rb_eNullReferenceError;
}
SWIGINTERN VALUE
getObjectPreviouslyDeletedError(void) {
static int init = 0;
static VALUE rb_eObjectPreviouslyDeleted ;
if (!init) {
init = 1;
rb_eObjectPreviouslyDeleted = rb_define_class("ObjectPreviouslyDeleted", rb_eRuntimeError);
}
return rb_eObjectPreviouslyDeleted;
}
SWIGINTERN VALUE
SWIG_Ruby_ErrorType(int SWIG_code) {
VALUE type;
switch (SWIG_code) {
case SWIG_MemoryError:
type = rb_eNoMemError;
break;
case SWIG_IOError:
type = rb_eIOError;
break;
case SWIG_RuntimeError:
type = rb_eRuntimeError;
break;
case SWIG_IndexError:
type = rb_eIndexError;
break;
case SWIG_TypeError:
type = rb_eTypeError;
break;
case SWIG_DivisionByZero:
type = rb_eZeroDivError;
break;
case SWIG_OverflowError:
type = rb_eRangeError;
break;
case SWIG_SyntaxError:
type = rb_eSyntaxError;
break;
case SWIG_ValueError:
type = rb_eArgError;
break;
case SWIG_SystemError:
type = rb_eFatal;
break;
case SWIG_AttributeError:
type = rb_eRuntimeError;
break;
case SWIG_NullReferenceError:
type = getNullReferenceError();
break;
case SWIG_ObjectPreviouslyDeletedError:
type = getObjectPreviouslyDeletedError();
break;
case SWIG_UnknownError:
type = rb_eRuntimeError;
break;
default:
type = rb_eRuntimeError;
}
return type;
}
/* This function is called when a user inputs a wrong argument to
a method.
*/
SWIGINTERN
const char* Ruby_Format_TypeError( const char* msg,
const char* type,
const char* name,
const int argn,
VALUE input )
{
char buf[128];
VALUE str;
VALUE asStr;
if ( msg && *msg )
{
str = rb_str_new2(msg);
}
else
{
str = rb_str_new(NULL, 0);
}
str = rb_str_cat2( str, "Expected argument " );
sprintf( buf, "%d of type ", argn-1 );
str = rb_str_cat2( str, buf );
str = rb_str_cat2( str, type );
str = rb_str_cat2( str, ", but got " );
str = rb_str_cat2( str, rb_obj_classname(input) );
str = rb_str_cat2( str, " " );
asStr = rb_inspect(input);
if ( RSTRING_LEN(asStr) > 30 )
{
str = rb_str_cat( str, StringValuePtr(asStr), 30 );
str = rb_str_cat2( str, "..." );
}
else
{
str = rb_str_append( str, asStr );
}
if ( name )
{
str = rb_str_cat2( str, "\n\tin SWIG method '" );
str = rb_str_cat2( str, name );
str = rb_str_cat2( str, "'" );
}
return StringValuePtr( str );
}
/* This function is called when an overloaded method fails */
SWIGINTERN
void Ruby_Format_OverloadedError(
const int argc,
const int maxargs,
const char* method,
const char* prototypes
)
{
const char* msg = "Wrong # of arguments";
if ( argc <= maxargs ) msg = "Wrong arguments";
rb_raise(rb_eArgError,"%s for overloaded method '%s'.\n"
"Possible C/C++ prototypes are:\n%s",
msg, method, prototypes);
}
/* -----------------------------------------------------------------------------
* rubytracking.swg
*
* This file contains support for tracking mappings from
* Ruby objects to C++ objects. This functionality is needed
* to implement mark functions for Ruby's mark and sweep
* garbage collector.
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#endif
/* Ruby 1.8 actually assumes the first case. */
#if SIZEOF_VOIDP == SIZEOF_LONG
# define SWIG2NUM(v) LONG2NUM((unsigned long)v)
# define NUM2SWIG(x) (unsigned long)NUM2LONG(x)
#elif SIZEOF_VOIDP == SIZEOF_LONG_LONG
# define SWIG2NUM(v) LL2NUM((unsigned long long)v)
# define NUM2SWIG(x) (unsigned long long)NUM2LL(x)
#else
# error sizeof(void*) is not the same as long or long long
#endif
/* Global Ruby hash table to store Trackings from C/C++
structs to Ruby Objects.
*/
static VALUE swig_ruby_trackings = Qnil;
/* Global variable that stores a reference to the ruby
hash table delete function. */
static ID swig_ruby_hash_delete;
/* Setup a Ruby hash table to store Trackings */
SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) {
/* Create a ruby hash table to store Trackings from C++
objects to Ruby objects. */
/* Try to see if some other .so has already created a
tracking hash table, which we keep hidden in an instance var
in the SWIG module.
This is done to allow multiple DSOs to share the same
tracking table.
*/
ID trackings_id = rb_intern( "@__trackings__" );
VALUE verbose = rb_gv_get("VERBOSE");
rb_gv_set("VERBOSE", Qfalse);
swig_ruby_trackings = rb_ivar_get( _mSWIG, trackings_id );
rb_gv_set("VERBOSE", verbose);
/* No, it hasn't. Create one ourselves */
if ( swig_ruby_trackings == Qnil )
{
swig_ruby_trackings = rb_hash_new();
rb_ivar_set( _mSWIG, trackings_id, swig_ruby_trackings );
}
/* Now store a reference to the hash table delete function
so that we only have to look it up once.*/
swig_ruby_hash_delete = rb_intern("delete");
}
/* Get a Ruby number to reference a pointer */
SWIGRUNTIME VALUE SWIG_RubyPtrToReference(void* ptr) {
/* We cast the pointer to an unsigned long
and then store a reference to it using
a Ruby number object. */
/* Convert the pointer to a Ruby number */
return SWIG2NUM(ptr);
}
/* Get a Ruby number to reference an object */
SWIGRUNTIME VALUE SWIG_RubyObjectToReference(VALUE object) {
/* We cast the object to an unsigned long
and then store a reference to it using
a Ruby number object. */
/* Convert the Object to a Ruby number */
return SWIG2NUM(object);
}
/* Get a Ruby object from a previously stored reference */
SWIGRUNTIME VALUE SWIG_RubyReferenceToObject(VALUE reference) {
/* The provided Ruby number object is a reference
to the Ruby object we want.*/
/* Convert the Ruby number to a Ruby object */
return NUM2SWIG(reference);
}
/* Add a Tracking from a C/C++ struct to a Ruby object */
SWIGRUNTIME void SWIG_RubyAddTracking(void* ptr, VALUE object) {
/* In a Ruby hash table we store the pointer and
the associated Ruby object. The trick here is
that we cannot store the Ruby object directly - if
we do then it cannot be garbage collected. So
instead we typecast it as a unsigned long and
convert it to a Ruby number object.*/
/* Get a reference to the pointer as a Ruby number */
VALUE key = SWIG_RubyPtrToReference(ptr);
/* Get a reference to the Ruby object as a Ruby number */
VALUE value = SWIG_RubyObjectToReference(object);
/* Store the mapping to the global hash table. */
rb_hash_aset(swig_ruby_trackings, key, value);
}
/* Get the Ruby object that owns the specified C/C++ struct */
SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) {
/* Get a reference to the pointer as a Ruby number */
VALUE key = SWIG_RubyPtrToReference(ptr);
/* Now lookup the value stored in the global hash table */
VALUE value = rb_hash_aref(swig_ruby_trackings, key);
if (value == Qnil) {
/* No object exists - return nil. */
return Qnil;
}
else {
/* Convert this value to Ruby object */
return SWIG_RubyReferenceToObject(value);
}
}
/* Remove a Tracking from a C/C++ struct to a Ruby object. It
is very important to remove objects once they are destroyed
since the same memory address may be reused later to create
a new object. */
SWIGRUNTIME void SWIG_RubyRemoveTracking(void* ptr) {
/* Get a reference to the pointer as a Ruby number */
VALUE key = SWIG_RubyPtrToReference(ptr);
/* Delete the object from the hash table by calling Ruby's
do this we need to call the Hash.delete method.*/
rb_funcall(swig_ruby_trackings, swig_ruby_hash_delete, 1, key);
}
/* This is a helper method that unlinks a Ruby object from its
underlying C++ object. This is needed if the lifetime of the
Ruby object is longer than the C++ object */
SWIGRUNTIME void SWIG_RubyUnlinkObjects(void* ptr) {
VALUE object = SWIG_RubyInstanceFor(ptr);
if (object != Qnil) {
DATA_PTR(object) = 0;
}
}
#ifdef __cplusplus
}
#endif
/* -----------------------------------------------------------------------------
* Ruby API portion that goes into the runtime
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#endif
SWIGINTERN VALUE
SWIG_Ruby_AppendOutput(VALUE target, VALUE o) {
if (NIL_P(target)) {
target = o;
} else {
if (TYPE(target) != T_ARRAY) {
VALUE o2 = target;
target = rb_ary_new();
rb_ary_push(target, o2);
}
rb_ary_push(target, o);
}
return target;
}
/* For ruby1.8.4 and earlier. */
#ifndef RUBY_INIT_STACK
RUBY_EXTERN void Init_stack(VALUE* addr);
# define RUBY_INIT_STACK \
VALUE variable_in_this_stack_frame; \
Init_stack(&variable_in_this_stack_frame);
#endif
#ifdef __cplusplus
}
#endif
/* -----------------------------------------------------------------------------
* rubyrun.swg
*
* This file contains the runtime support for Ruby modules
* and includes code for managing global variables and pointer
* type checking.
* ----------------------------------------------------------------------------- */
/* For backward compatibility only */
#define SWIG_POINTER_EXCEPTION 0
/* for raw pointers */
#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, own)
#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Ruby_NewPointerObj(ptr, type, flags)
#define SWIG_AcquirePtr(ptr, own) SWIG_Ruby_AcquirePtr(ptr, own)
#define swig_owntype ruby_owntype
/* for raw packed data */
#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty, flags)
#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type)
/* for class or struct pointers */
#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags)
#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags)
/* for C or C++ function pointers */
#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_ConvertPtr(obj, pptr, type, 0)
#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_NewPointerObj(ptr, type, 0)
/* for C++ member pointers, ie, member methods */
#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty)
#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type)
/* Runtime API */
#define SWIG_GetModule(clientdata) SWIG_Ruby_GetModule(clientdata)
#define SWIG_SetModule(clientdata, pointer) SWIG_Ruby_SetModule(pointer)
/* Error manipulation */
#define SWIG_ErrorType(code) SWIG_Ruby_ErrorType(code)
#define SWIG_Error(code, msg) rb_raise(SWIG_Ruby_ErrorType(code), "%s", msg)
#define SWIG_fail goto fail
/* Ruby-specific SWIG API */
#define SWIG_InitRuntime() SWIG_Ruby_InitRuntime()
#define SWIG_define_class(ty) SWIG_Ruby_define_class(ty)
#define SWIG_NewClassInstance(value, ty) SWIG_Ruby_NewClassInstance(value, ty)
#define SWIG_MangleStr(value) SWIG_Ruby_MangleStr(value)
#define SWIG_CheckConvert(value, ty) SWIG_Ruby_CheckConvert(value, ty)
#include "assert.h"
/* -----------------------------------------------------------------------------
* pointers/data manipulation
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
VALUE klass;
VALUE mImpl;
void (*mark)(void *);
void (*destroy)(void *);
int trackObjects;
} swig_class;
/* Global pointer used to keep some internal SWIG stuff */
static VALUE _cSWIG_Pointer = Qnil;
static VALUE swig_runtime_data_type_pointer = Qnil;
/* Global IDs used to keep some internal SWIG stuff */
static ID swig_arity_id = 0;
static ID swig_call_id = 0;
/*
If your swig extension is to be run within an embedded ruby and has
director callbacks, you should set -DRUBY_EMBEDDED during compilation.
This will reset ruby's stack frame on each entry point from the main
program the first time a virtual director function is invoked (in a
non-recursive way).
If this is not done, you run the risk of Ruby trashing the stack.
*/
#ifdef RUBY_EMBEDDED
# define SWIG_INIT_STACK \
if ( !swig_virtual_calls ) { RUBY_INIT_STACK } \
++swig_virtual_calls;
# define SWIG_RELEASE_STACK --swig_virtual_calls;
# define Ruby_DirectorTypeMismatchException(x) \
rb_raise( rb_eTypeError, "%s", x ); return c_result;
static unsigned int swig_virtual_calls = 0;
#else /* normal non-embedded extension */
# define SWIG_INIT_STACK
# define SWIG_RELEASE_STACK
# define Ruby_DirectorTypeMismatchException(x) \
throw Swig::DirectorTypeMismatchException( x );
#endif /* RUBY_EMBEDDED */
SWIGRUNTIME VALUE
getExceptionClass(void) {
static int init = 0;
static VALUE rubyExceptionClass ;
if (!init) {
init = 1;
rubyExceptionClass = rb_const_get(_mSWIG, rb_intern("Exception"));
}
return rubyExceptionClass;
}
/* This code checks to see if the Ruby object being raised as part
of an exception inherits from the Ruby class Exception. If so,
the object is simply returned. If not, then a new Ruby exception
object is created and that will be returned to Ruby.*/
SWIGRUNTIME VALUE
SWIG_Ruby_ExceptionType(swig_type_info *desc, VALUE obj) {
VALUE exceptionClass = getExceptionClass();
if (rb_obj_is_kind_of(obj, exceptionClass)) {
return obj;
} else {
return rb_exc_new3(rb_eRuntimeError, rb_obj_as_string(obj));
}
}
/* Initialize Ruby runtime support */
SWIGRUNTIME void
SWIG_Ruby_InitRuntime(void)
{
if (_mSWIG == Qnil) {
_mSWIG = rb_define_module("SWIG");
swig_call_id = rb_intern("call");
swig_arity_id = rb_intern("arity");
}
}
/* Define Ruby class for C type */
SWIGRUNTIME void
SWIG_Ruby_define_class(swig_type_info *type)
{
VALUE klass;
char *klass_name = (char *) malloc(4 + strlen(type->name) + 1);
sprintf(klass_name, "TYPE%s", type->name);
if (NIL_P(_cSWIG_Pointer)) {
_cSWIG_Pointer = rb_define_class_under(_mSWIG, "Pointer", rb_cObject);
rb_undef_method(CLASS_OF(_cSWIG_Pointer), "new");
}
klass = rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer);
free((void *) klass_name);
}
/* Create a new pointer object */
SWIGRUNTIME VALUE
SWIG_Ruby_NewPointerObj(void *ptr, swig_type_info *type, int flags)
{
int own = flags & SWIG_POINTER_OWN;
int track;
char *klass_name;
swig_class *sklass;
VALUE klass;
VALUE obj;
if (!ptr)
return Qnil;
if (type->clientdata) {
sklass = (swig_class *) type->clientdata;
/* Are we tracking this class and have we already returned this Ruby object? */
track = sklass->trackObjects;
if (track) {
obj = SWIG_RubyInstanceFor(ptr);
/* Check the object's type and make sure it has the correct type.
It might not in cases where methods do things like
downcast methods. */
if (obj != Qnil) {
VALUE value = rb_iv_get(obj, "@__swigtype__");
const char* type_name = RSTRING_PTR(value);
if (strcmp(type->name, type_name) == 0) {
return obj;
}
}
}
/* Create a new Ruby object */
obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark),
( own ? VOIDFUNC(sklass->destroy) :
(track ? VOIDFUNC(SWIG_RubyRemoveTracking) : 0 )
), ptr);
/* If tracking is on for this class then track this object. */
if (track) {
SWIG_RubyAddTracking(ptr, obj);
}
} else {
klass_name = (char *) malloc(4 + strlen(type->name) + 1);
sprintf(klass_name, "TYPE%s", type->name);
klass = rb_const_get(_mSWIG, rb_intern(klass_name));
free((void *) klass_name);
obj = Data_Wrap_Struct(klass, 0, 0, ptr);
}
rb_iv_set(obj, "@__swigtype__", rb_str_new2(type->name));
return obj;
}
/* Create a new class instance (always owned) */
SWIGRUNTIME VALUE
SWIG_Ruby_NewClassInstance(VALUE klass, swig_type_info *type)
{
VALUE obj;
swig_class *sklass = (swig_class *) type->clientdata;
obj = Data_Wrap_Struct(klass, VOIDFUNC(sklass->mark), VOIDFUNC(sklass->destroy), 0);
rb_iv_set(obj, "@__swigtype__", rb_str_new2(type->name));
return obj;
}
/* Get type mangle from class name */
SWIGRUNTIMEINLINE char *
SWIG_Ruby_MangleStr(VALUE obj)
{
VALUE stype = rb_iv_get(obj, "@__swigtype__");
return StringValuePtr(stype);
}
/* Acquire a pointer value */
typedef void (*ruby_owntype)(void*);
SWIGRUNTIME ruby_owntype
SWIG_Ruby_AcquirePtr(VALUE obj, ruby_owntype own) {
if (obj) {
ruby_owntype oldown = RDATA(obj)->dfree;
RDATA(obj)->dfree = own;
return oldown;
} else {
return 0;
}
}
/* Convert a pointer value */
SWIGRUNTIME int
SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, ruby_owntype *own)
{
char *c;
swig_cast_info *tc;
void *vptr = 0;
/* Grab the pointer */
if (NIL_P(obj)) {
*ptr = 0;
return SWIG_OK;
} else {
if (TYPE(obj) != T_DATA) {
return SWIG_ERROR;
}
Data_Get_Struct(obj, void, vptr);
}
if (own) *own = RDATA(obj)->dfree;
/* Check to see if the input object is giving up ownership
of the underlying C struct or C++ object. If so then we
need to reset the destructor since the Ruby object no
longer owns the underlying C++ object.*/
if (flags & SWIG_POINTER_DISOWN) {
/* Is tracking on for this class? */
int track = 0;
if (ty && ty->clientdata) {
swig_class *sklass = (swig_class *) ty->clientdata;
track = sklass->trackObjects;
}
if (track) {
/* We are tracking objects for this class. Thus we change the destructor
* to SWIG_RubyRemoveTracking. This allows us to
* remove the mapping from the C++ to Ruby object
* when the Ruby object is garbage collected. If we don't
* do this, then it is possible we will return a reference
* to a Ruby object that no longer exists thereby crashing Ruby. */
RDATA(obj)->dfree = SWIG_RubyRemoveTracking;
} else {
RDATA(obj)->dfree = 0;
}
}
/* Do type-checking if type info was provided */
if (ty) {
if (ty->clientdata) {
if (rb_obj_is_kind_of(obj, ((swig_class *) (ty->clientdata))->klass)) {
if (vptr == 0) {
/* The object has already been deleted */
return SWIG_ObjectPreviouslyDeletedError;
}
*ptr = vptr;
return SWIG_OK;
}
}
if ((c = SWIG_MangleStr(obj)) == NULL) {
return SWIG_ERROR;
}
tc = SWIG_TypeCheck(c, ty);
if (!tc) {
return SWIG_ERROR;
} else {
int newmemory = 0;
*ptr = SWIG_TypeCast(tc, vptr, &newmemory);
assert(!newmemory); /* newmemory handling not yet implemented */
}
} else {
*ptr = vptr;
}
return SWIG_OK;
}
/* Check convert */
SWIGRUNTIMEINLINE int
SWIG_Ruby_CheckConvert(VALUE obj, swig_type_info *ty)
{
char *c = SWIG_MangleStr(obj);
if (!c) return 0;
return SWIG_TypeCheck(c,ty) != 0;
}
SWIGRUNTIME VALUE
SWIG_Ruby_NewPackedObj(void *ptr, int sz, swig_type_info *type) {
char result[1024];
char *r = result;
if ((2*sz + 1 + strlen(type->name)) > 1000) return 0;
*(r++) = '_';
r = SWIG_PackData(r, ptr, sz);
strcpy(r, type->name);
return rb_str_new2(result);
}
/* Convert a packed value value */
SWIGRUNTIME int
SWIG_Ruby_ConvertPacked(VALUE obj, void *ptr, int sz, swig_type_info *ty) {
swig_cast_info *tc;
const char *c;
if (TYPE(obj) != T_STRING) goto type_error;
c = StringValuePtr(obj);
/* Pointer values must start with leading underscore */
if (*c != '_') goto type_error;
c++;
c = SWIG_UnpackData(c, ptr, sz);
if (ty) {
tc = SWIG_TypeCheck(c, ty);
if (!tc) goto type_error;
}
return SWIG_OK;
type_error:
return SWIG_ERROR;
}
SWIGRUNTIME swig_module_info *
SWIG_Ruby_GetModule(void *SWIGUNUSEDPARM(clientdata))
{
VALUE pointer;
swig_module_info *ret = 0;
VALUE verbose = rb_gv_get("VERBOSE");
/* temporarily disable warnings, since the pointer check causes warnings with 'ruby -w' */
rb_gv_set("VERBOSE", Qfalse);
/* first check if pointer already created */
pointer = rb_gv_get("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
if (pointer != Qnil) {
Data_Get_Struct(pointer, swig_module_info, ret);
}
/* reinstate warnings */
rb_gv_set("VERBOSE", verbose);
return ret;
}
SWIGRUNTIME void
SWIG_Ruby_SetModule(swig_module_info *pointer)
{
/* register a new class */
VALUE cl = rb_define_class("swig_runtime_data", rb_cObject);
/* create and store the structure pointer to a global variable */
swig_runtime_data_type_pointer = Data_Wrap_Struct(cl, 0, 0, pointer);
rb_define_readonly_variable("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, &swig_runtime_data_type_pointer);
}
/* This function can be used to check whether a proc or method or similarly
callable function has been passed. Usually used in a %typecheck, like:
%typecheck(c_callback_t, precedence=SWIG_TYPECHECK_POINTER) {
$result = SWIG_Ruby_isCallable( $input );
}
*/
SWIGINTERN
int SWIG_Ruby_isCallable( VALUE proc )
{
if ( rb_respond_to( proc, swig_call_id ) )
return 1;
return 0;
}
/* This function can be used to check the arity (number of arguments)
a proc or method can take. Usually used in a %typecheck.
Valid arities will be that equal to minimal or those < 0
which indicate a variable number of parameters at the end.
*/
SWIGINTERN
int SWIG_Ruby_arity( VALUE proc, int minimal )
{
if ( rb_respond_to( proc, swig_arity_id ) )
{
VALUE num = rb_funcall( proc, swig_arity_id, 0 );
int arity = NUM2INT(num);
if ( arity < 0 && (arity+1) < -minimal ) return 1;
if ( arity == minimal ) return 1;
return 1;
}
return 0;
}
#ifdef __cplusplus
}
#endif
#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0)
#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else
/* -------- TYPES TABLE (BEGIN) -------- */
#define SWIGTYPE_p_char swig_types[0]
#define SWIGTYPE_p_tb_cell swig_types[1]
#define SWIGTYPE_p_tb_event swig_types[2]
#define SWIGTYPE_p_uint32_t swig_types[3]
static swig_type_info *swig_types[5];
static swig_module_info swig_module = {swig_types, 4, 0, 0, 0, 0};
#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
/* -------- TYPES TABLE (END) -------- */
#define SWIG_init Init_termbox
#define SWIG_name "Termbox"
static VALUE mTermbox;
#define SWIG_RUBY_THREAD_BEGIN_BLOCK
#define SWIG_RUBY_THREAD_END_BLOCK
#define SWIGVERSION 0x020011
#define SWIG_VERSION SWIGVERSION
#define SWIG_as_voidptr(a) (void *)((const void *)(a))
#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a))
#include "termbox.h"
#include <limits.h>
#if !defined(SWIG_NO_LLONG_MAX)
# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)
# define LLONG_MAX __LONG_LONG_MAX__
# define LLONG_MIN (-LLONG_MAX - 1LL)
# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
# endif
#endif
#define SWIG_From_long LONG2NUM
SWIGINTERNINLINE VALUE
SWIG_From_int (int value)
{
return SWIG_From_long (value);
}
SWIGINTERN VALUE
SWIG_ruby_failed(void)
{
return Qnil;
}
/*@SWIG:/usr/local/Cellar/swig/2.0.11/share/swig/2.0.11/ruby/rubyprimtypes.swg,19,%ruby_aux_method@*/
SWIGINTERN VALUE SWIG_AUX_NUM2ULONG(VALUE *args)
{
VALUE obj = args[0];
VALUE type = TYPE(obj);
unsigned long *res = (unsigned long *)(args[1]);
*res = type == T_FIXNUM ? NUM2ULONG(obj) : rb_big2ulong(obj);
return obj;
}
/*@SWIG@*/
SWIGINTERN int
SWIG_AsVal_unsigned_SS_long (VALUE obj, unsigned long *val)
{
VALUE type = TYPE(obj);
if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
unsigned long v;
VALUE a[2];
a[0] = obj;
a[1] = (VALUE)(&v);
if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2ULONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
if (val) *val = v;
return SWIG_OK;
}
}
return SWIG_TypeError;
}
SWIGINTERN int
SWIG_AsVal_unsigned_SS_int (VALUE obj, unsigned int *val)
{
unsigned long v;
int res = SWIG_AsVal_unsigned_SS_long (obj, &v);
if (SWIG_IsOK(res)) {
if ((v > UINT_MAX)) {
return SWIG_OverflowError;
} else {
if (val) *val = (unsigned int)(v);
}
}
return res;
}
SWIGINTERNINLINE VALUE
SWIG_From_unsigned_SS_long (unsigned long value)
{
return ULONG2NUM(value);
}
SWIGINTERNINLINE VALUE
SWIG_From_unsigned_SS_int (unsigned int value)
{
return SWIG_From_unsigned_SS_long (value);
}
/*@SWIG:/usr/local/Cellar/swig/2.0.11/share/swig/2.0.11/ruby/rubyprimtypes.swg,19,%ruby_aux_method@*/
SWIGINTERN VALUE SWIG_AUX_NUM2LONG(VALUE *args)
{
VALUE obj = args[0];
VALUE type = TYPE(obj);
long *res = (long *)(args[1]);
*res = type == T_FIXNUM ? NUM2LONG(obj) : rb_big2long(obj);
return obj;
}
/*@SWIG@*/
SWIGINTERN int
SWIG_AsVal_long (VALUE obj, long* val)
{
VALUE type = TYPE(obj);
if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
long v;
VALUE a[2];
a[0] = obj;
a[1] = (VALUE)(&v);
if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2LONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
if (val) *val = v;
return SWIG_OK;
}
}
return SWIG_TypeError;
}
SWIGINTERN int
SWIG_AsVal_int (VALUE obj, int *val)
{
long v;
int res = SWIG_AsVal_long (obj, &v);
if (SWIG_IsOK(res)) {
if ((v < INT_MIN || v > INT_MAX)) {
return SWIG_OverflowError;
} else {
if (val) *val = (int)(v);
}
}
return res;
}
SWIGINTERN swig_type_info*
SWIG_pchar_descriptor(void)
{
static int init = 0;
static swig_type_info* info = 0;
if (!init) {
info = SWIG_TypeQuery("_p_char");
init = 1;
}
return info;
}
SWIGINTERN int
SWIG_AsCharPtrAndSize(VALUE obj, char** cptr, size_t* psize, int *alloc)
{
if (TYPE(obj) == T_STRING) {
char *cstr = StringValuePtr(obj);
size_t size = RSTRING_LEN(obj) + 1;
if (cptr) {
if (alloc) {
if (*alloc == SWIG_NEWOBJ) {
*cptr = (char *)memcpy((char *)malloc((size)*sizeof(char)), cstr, sizeof(char)*(size));
} else {
*cptr = cstr;
*alloc = SWIG_OLDOBJ;
}
}
}
if (psize) *psize = size;
return SWIG_OK;
} else {
swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
if (pchar_descriptor) {
void* vptr = 0;
if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
if (cptr) *cptr = (char *)vptr;
if (psize) *psize = vptr ? (strlen((char*)vptr) + 1) : 0;
if (alloc) *alloc = SWIG_OLDOBJ;
return SWIG_OK;
}
}
}
return SWIG_TypeError;
}
SWIGINTERN int
SWIG_AsCharArray(VALUE obj, char *val, size_t size)
{
char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ;
int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc);
if (SWIG_IsOK(res)) {
if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize;
if (csize <= size) {
if (val) {
if (csize) memcpy(val, cptr, csize*sizeof(char));
if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char));
}
if (alloc == SWIG_NEWOBJ) {
free((char*)cptr);
res = SWIG_DelNewMask(res);
}
return res;
}
if (alloc == SWIG_NEWOBJ) free((char*)cptr);
}
return SWIG_TypeError;
}
SWIGINTERN int
SWIG_AsVal_char (VALUE obj, char *val)
{
int res = SWIG_AsCharArray(obj, val, 1);
if (!SWIG_IsOK(res)) {
long v;
res = SWIG_AddCast(SWIG_AsVal_long (obj, &v));
if (SWIG_IsOK(res)) {
if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) {
if (val) *val = (char)(v);
} else {
res = SWIG_OverflowError;
}
}
}
return res;
}
static swig_class SwigClassTb_cell;
SWIGINTERN VALUE
_wrap_tb_cell_ch_set(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
uint32_t arg2 ;
void *argp1 = 0 ;
int res1 = 0 ;
unsigned int val2 ;
int ecode2 = 0 ;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","ch", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
ecode2 = SWIG_AsVal_unsigned_SS_int(argv[0], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "uint32_t","ch", 2, argv[0] ));
}
arg2 = (uint32_t)(val2);
if (arg1) (arg1)->ch = arg2;
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_cell_ch_get(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
uint32_t result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","ch", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
result = ((arg1)->ch);
vresult = SWIG_From_unsigned_SS_int((unsigned int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_cell_fg_set(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
uint16_t arg2 ;
void *argp1 = 0 ;
int res1 = 0 ;
unsigned int val2 ;
int ecode2 = 0 ;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","fg", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
ecode2 = SWIG_AsVal_unsigned_SS_int(argv[0], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "uint16_t","fg", 2, argv[0] ));
}
arg2 = (uint16_t)(val2);
if (arg1) (arg1)->fg = arg2;
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_cell_fg_get(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
uint16_t result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","fg", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
result = ((arg1)->fg);
vresult = SWIG_From_unsigned_SS_int((unsigned int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_cell_bg_set(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
uint16_t arg2 ;
void *argp1 = 0 ;
int res1 = 0 ;
unsigned int val2 ;
int ecode2 = 0 ;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","bg", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
ecode2 = SWIG_AsVal_unsigned_SS_int(argv[0], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "uint16_t","bg", 2, argv[0] ));
}
arg2 = (uint16_t)(val2);
if (arg1) (arg1)->bg = arg2;
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_cell_bg_get(int argc, VALUE *argv, VALUE self) {
struct tb_cell *arg1 = (struct tb_cell *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
uint16_t result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_cell *","bg", 1, self ));
}
arg1 = (struct tb_cell *)(argp1);
result = ((arg1)->bg);
vresult = SWIG_From_unsigned_SS_int((unsigned int)(result));
return vresult;
fail:
return Qnil;
}
#ifdef HAVE_RB_DEFINE_ALLOC_FUNC
SWIGINTERN VALUE
_wrap_tb_cell_allocate(VALUE self) {
#else
SWIGINTERN VALUE
_wrap_tb_cell_allocate(int argc, VALUE *argv, VALUE self) {
#endif
VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE_p_tb_cell);
#ifndef HAVE_RB_DEFINE_ALLOC_FUNC
rb_obj_call_init(vresult, argc, argv);
#endif
return vresult;
}
SWIGINTERN VALUE
_wrap_new_tb_cell(int argc, VALUE *argv, VALUE self) {
struct tb_cell *result = 0 ;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
result = (struct tb_cell *)calloc(1, sizeof(struct tb_cell));
DATA_PTR(self) = result;
return self;
fail:
return Qnil;
}
SWIGINTERN void
free_tb_cell(struct tb_cell *arg1) {
free((char *) arg1);
}
SWIGINTERN VALUE
_wrap_tb_init(int argc, VALUE *argv, VALUE self) {
int result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
result = (int)tb_init();
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_shutdown(int argc, VALUE *argv, VALUE self) {
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
tb_shutdown();
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_width(int argc, VALUE *argv, VALUE self) {
int result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
result = (int)tb_width();
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_height(int argc, VALUE *argv, VALUE self) {
int result;
VALUE vresult = Qnil;
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
result = (int)tb_height();
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_clear(int argc, VALUE *argv, VALUE self) {
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
tb_clear();
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_set_clear_attributes(int argc, VALUE *argv, VALUE self) {
uint16_t arg1 ;
uint16_t arg2 ;
unsigned int val1 ;
int ecode1 = 0 ;
unsigned int val2 ;
int ecode2 = 0 ;
if ((argc < 2) || (argc > 2)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_unsigned_SS_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "uint16_t","tb_set_clear_attributes", 1, argv[0] ));
}
arg1 = (uint16_t)(val1);
ecode2 = SWIG_AsVal_unsigned_SS_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "uint16_t","tb_set_clear_attributes", 2, argv[1] ));
}
arg2 = (uint16_t)(val2);
tb_set_clear_attributes(arg1,arg2);
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_present(int argc, VALUE *argv, VALUE self) {
if ((argc < 0) || (argc > 0)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail;
}
tb_present();
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_set_cursor(int argc, VALUE *argv, VALUE self) {
int arg1 ;
int arg2 ;
int val1 ;
int ecode1 = 0 ;
int val2 ;
int ecode2 = 0 ;
if ((argc < 2) || (argc > 2)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "int","tb_set_cursor", 1, argv[0] ));
}
arg1 = (int)(val1);
ecode2 = SWIG_AsVal_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "int","tb_set_cursor", 2, argv[1] ));
}
arg2 = (int)(val2);
tb_set_cursor(arg1,arg2);
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_put_cell(int argc, VALUE *argv, VALUE self) {
int arg1 ;
int arg2 ;
struct tb_cell *arg3 = (struct tb_cell *) 0 ;
int val1 ;
int ecode1 = 0 ;
int val2 ;
int ecode2 = 0 ;
void *argp3 = 0 ;
int res3 = 0 ;
if ((argc < 3) || (argc > 3)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 3)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "int","tb_put_cell", 1, argv[0] ));
}
arg1 = (int)(val1);
ecode2 = SWIG_AsVal_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "int","tb_put_cell", 2, argv[1] ));
}
arg2 = (int)(val2);
res3 = SWIG_ConvertPtr(argv[2], &argp3,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res3)) {
SWIG_exception_fail(SWIG_ArgError(res3), Ruby_Format_TypeError( "", "struct tb_cell const *","tb_put_cell", 3, argv[2] ));
}
arg3 = (struct tb_cell *)(argp3);
tb_put_cell(arg1,arg2,(struct tb_cell const *)arg3);
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_change_cell(int argc, VALUE *argv, VALUE self) {
int arg1 ;
int arg2 ;
uint32_t arg3 ;
uint16_t arg4 ;
uint16_t arg5 ;
int val1 ;
int ecode1 = 0 ;
int val2 ;
int ecode2 = 0 ;
unsigned int val3 ;
int ecode3 = 0 ;
unsigned int val4 ;
int ecode4 = 0 ;
unsigned int val5 ;
int ecode5 = 0 ;
if ((argc < 5) || (argc > 5)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 5)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "int","tb_change_cell", 1, argv[0] ));
}
arg1 = (int)(val1);
ecode2 = SWIG_AsVal_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "int","tb_change_cell", 2, argv[1] ));
}
arg2 = (int)(val2);
ecode3 = SWIG_AsVal_unsigned_SS_int(argv[2], &val3);
if (!SWIG_IsOK(ecode3)) {
SWIG_exception_fail(SWIG_ArgError(ecode3), Ruby_Format_TypeError( "", "uint32_t","tb_change_cell", 3, argv[2] ));
}
arg3 = (uint32_t)(val3);
ecode4 = SWIG_AsVal_unsigned_SS_int(argv[3], &val4);
if (!SWIG_IsOK(ecode4)) {
SWIG_exception_fail(SWIG_ArgError(ecode4), Ruby_Format_TypeError( "", "uint16_t","tb_change_cell", 4, argv[3] ));
}
arg4 = (uint16_t)(val4);
ecode5 = SWIG_AsVal_unsigned_SS_int(argv[4], &val5);
if (!SWIG_IsOK(ecode5)) {
SWIG_exception_fail(SWIG_ArgError(ecode5), Ruby_Format_TypeError( "", "uint16_t","tb_change_cell", 5, argv[4] ));
}
arg5 = (uint16_t)(val5);
tb_change_cell(arg1,arg2,arg3,arg4,arg5);
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_blit(int argc, VALUE *argv, VALUE self) {
int arg1 ;
int arg2 ;
int arg3 ;
int arg4 ;
struct tb_cell *arg5 = (struct tb_cell *) 0 ;
int val1 ;
int ecode1 = 0 ;
int val2 ;
int ecode2 = 0 ;
int val3 ;
int ecode3 = 0 ;
int val4 ;
int ecode4 = 0 ;
void *argp5 = 0 ;
int res5 = 0 ;
if ((argc < 5) || (argc > 5)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 5)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "int","tb_blit", 1, argv[0] ));
}
arg1 = (int)(val1);
ecode2 = SWIG_AsVal_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "int","tb_blit", 2, argv[1] ));
}
arg2 = (int)(val2);
ecode3 = SWIG_AsVal_int(argv[2], &val3);
if (!SWIG_IsOK(ecode3)) {
SWIG_exception_fail(SWIG_ArgError(ecode3), Ruby_Format_TypeError( "", "int","tb_blit", 3, argv[2] ));
}
arg3 = (int)(val3);
ecode4 = SWIG_AsVal_int(argv[3], &val4);
if (!SWIG_IsOK(ecode4)) {
SWIG_exception_fail(SWIG_ArgError(ecode4), Ruby_Format_TypeError( "", "int","tb_blit", 4, argv[3] ));
}
arg4 = (int)(val4);
res5 = SWIG_ConvertPtr(argv[4], &argp5,SWIGTYPE_p_tb_cell, 0 | 0 );
if (!SWIG_IsOK(res5)) {
SWIG_exception_fail(SWIG_ArgError(res5), Ruby_Format_TypeError( "", "struct tb_cell const *","tb_blit", 5, argv[4] ));
}
arg5 = (struct tb_cell *)(argp5);
tb_blit(arg1,arg2,arg3,arg4,(struct tb_cell const *)arg5);
return Qnil;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_select_input_mode(int argc, VALUE *argv, VALUE self) {
int arg1 ;
int val1 ;
int ecode1 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_int(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "int","tb_select_input_mode", 1, argv[0] ));
}
arg1 = (int)(val1);
result = (int)tb_select_input_mode(arg1);
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_peek_event(int argc, VALUE *argv, VALUE self) {
struct tb_event *arg1 = (struct tb_event *) 0 ;
int arg2 ;
void *argp1 = 0 ;
int res1 = 0 ;
int val2 ;
int ecode2 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 2) || (argc > 2)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_tb_event, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_event *","tb_peek_event", 1, argv[0] ));
}
arg1 = (struct tb_event *)(argp1);
ecode2 = SWIG_AsVal_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "int","tb_peek_event", 2, argv[1] ));
}
arg2 = (int)(val2);
result = (int)tb_peek_event(arg1,arg2);
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_poll_event(int argc, VALUE *argv, VALUE self) {
struct tb_event *arg1 = (struct tb_event *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_tb_event, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "struct tb_event *","tb_poll_event", 1, argv[0] ));
}
arg1 = (struct tb_event *)(argp1);
result = (int)tb_poll_event(arg1);
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_utf8_char_length(int argc, VALUE *argv, VALUE self) {
char arg1 ;
char val1 ;
int ecode1 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 1) || (argc > 1)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail;
}
ecode1 = SWIG_AsVal_char(argv[0], &val1);
if (!SWIG_IsOK(ecode1)) {
SWIG_exception_fail(SWIG_ArgError(ecode1), Ruby_Format_TypeError( "", "char","tb_utf8_char_length", 1, argv[0] ));
}
arg1 = (char)(val1);
result = (int)tb_utf8_char_length(arg1);
vresult = SWIG_From_int((int)(result));
return vresult;
fail:
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_utf8_char_to_unicode(int argc, VALUE *argv, VALUE self) {
uint32_t *arg1 = (uint32_t *) 0 ;
char *arg2 = (char *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
int res2 ;
char *buf2 = 0 ;
int alloc2 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 2) || (argc > 2)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail;
}
res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_uint32_t, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "uint32_t *","tb_utf8_char_to_unicode", 1, argv[0] ));
}
arg1 = (uint32_t *)(argp1);
res2 = SWIG_AsCharPtrAndSize(argv[1], &buf2, NULL, &alloc2);
if (!SWIG_IsOK(res2)) {
SWIG_exception_fail(SWIG_ArgError(res2), Ruby_Format_TypeError( "", "char const *","tb_utf8_char_to_unicode", 2, argv[1] ));
}
arg2 = (char *)(buf2);
result = (int)tb_utf8_char_to_unicode(arg1,(char const *)arg2);
vresult = SWIG_From_int((int)(result));
if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
return vresult;
fail:
if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
return Qnil;
}
SWIGINTERN VALUE
_wrap_tb_utf8_unicode_to_char(int argc, VALUE *argv, VALUE self) {
char *arg1 = (char *) 0 ;
uint32_t arg2 ;
int res1 ;
char *buf1 = 0 ;
int alloc1 = 0 ;
unsigned int val2 ;
int ecode2 = 0 ;
int result;
VALUE vresult = Qnil;
if ((argc < 2) || (argc > 2)) {
rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail;
}
res1 = SWIG_AsCharPtrAndSize(argv[0], &buf1, NULL, &alloc1);
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), Ruby_Format_TypeError( "", "char *","tb_utf8_unicode_to_char", 1, argv[0] ));
}
arg1 = (char *)(buf1);
ecode2 = SWIG_AsVal_unsigned_SS_int(argv[1], &val2);
if (!SWIG_IsOK(ecode2)) {
SWIG_exception_fail(SWIG_ArgError(ecode2), Ruby_Format_TypeError( "", "uint32_t","tb_utf8_unicode_to_char", 2, argv[1] ));
}
arg2 = (uint32_t)(val2);
result = (int)tb_utf8_unicode_to_char(arg1,arg2);
vresult = SWIG_From_int((int)(result));
if (alloc1 == SWIG_NEWOBJ) free((char*)buf1);
return vresult;
fail:
if (alloc1 == SWIG_NEWOBJ) free((char*)buf1);
return Qnil;
}
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_tb_cell = {"_p_tb_cell", "tb_cell *|struct tb_cell *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_tb_event = {"_p_tb_event", "struct tb_event *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_uint32_t = {"_p_uint32_t", "uint32_t *", 0, 0, (void*)0, 0};
static swig_type_info *swig_type_initial[] = {
&_swigt__p_char,
&_swigt__p_tb_cell,
&_swigt__p_tb_event,
&_swigt__p_uint32_t,
};
static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_tb_cell[] = { {&_swigt__p_tb_cell, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_tb_event[] = { {&_swigt__p_tb_event, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_uint32_t[] = { {&_swigt__p_uint32_t, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info *swig_cast_initial[] = {
_swigc__p_char,
_swigc__p_tb_cell,
_swigc__p_tb_event,
_swigc__p_uint32_t,
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
/* -----------------------------------------------------------------------------
* Type initialization:
* This problem is tough by the requirement that no dynamic
* memory is used. Also, since swig_type_info structures store pointers to
* swig_cast_info structures and swig_cast_info structures store pointers back
* to swig_type_info structures, we need some lookup code at initialization.
* The idea is that swig generates all the structures that are needed.
* The runtime then collects these partially filled structures.
* The SWIG_InitializeModule function takes these initial arrays out of
* swig_module, and does all the lookup, filling in the swig_module.types
* array with the correct data and linking the correct swig_cast_info
* structures together.
*
* The generated swig_type_info structures are assigned staticly to an initial
* array. We just loop through that array, and handle each type individually.
* First we lookup if this type has been already loaded, and if so, use the
* loaded structure instead of the generated one. Then we have to fill in the
* cast linked list. The cast data is initially stored in something like a
* two-dimensional array. Each row corresponds to a type (there are the same
* number of rows as there are in the swig_type_initial array). Each entry in
* a column is one of the swig_cast_info structures for that type.
* The cast_initial array is actually an array of arrays, because each row has
* a variable number of columns. So to actually build the cast linked list,
* we find the array of casts associated with the type, and loop through it
* adding the casts to the list. The one last trick we need to do is making
* sure the type pointer in the swig_cast_info struct is correct.
*
* First off, we lookup the cast->type name to see if it is already loaded.
* There are three cases to handle:
* 1) If the cast->type has already been loaded AND the type we are adding
* casting info to has not been loaded (it is in this module), THEN we
* replace the cast->type pointer with the type pointer that has already
* been loaded.
* 2) If BOTH types (the one we are adding casting info to, and the
* cast->type) are loaded, THEN the cast info has already been loaded by
* the previous module so we just ignore it.
* 3) Finally, if cast->type has not already been loaded, then we add that
* swig_cast_info to the linked list (because the cast->type) pointer will
* be correct.
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#if 0
} /* c-mode */
#endif
#endif
#if 0
#define SWIGRUNTIME_DEBUG
#endif
SWIGRUNTIME void
SWIG_InitializeModule(void *clientdata) {
size_t i;
swig_module_info *module_head, *iter;
int found, init;
/* check to see if the circular list has been setup, if not, set it up */
if (swig_module.next==0) {
/* Initialize the swig_module */
swig_module.type_initial = swig_type_initial;
swig_module.cast_initial = swig_cast_initial;
swig_module.next = &swig_module;
init = 1;
} else {
init = 0;
}
/* Try and load any already created modules */
module_head = SWIG_GetModule(clientdata);
if (!module_head) {
/* This is the first module loaded for this interpreter */
/* so set the swig module into the interpreter */
SWIG_SetModule(clientdata, &swig_module);
module_head = &swig_module;
} else {
/* the interpreter has loaded a SWIG module, but has it loaded this one? */
found=0;
iter=module_head;
do {
if (iter==&swig_module) {
found=1;
break;
}
iter=iter->next;
} while (iter!= module_head);
/* if the is found in the list, then all is done and we may leave */
if (found) return;
/* otherwise we must add out module into the list */
swig_module.next = module_head->next;
module_head->next = &swig_module;
}
/* When multiple interpreters are used, a module could have already been initialized in
a different interpreter, but not yet have a pointer in this interpreter.
In this case, we do not want to continue adding types... everything should be
set up already */
if (init == 0) return;
/* Now work on filling in swig_module.types */
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: size %d\n", swig_module.size);
#endif
for (i = 0; i < swig_module.size; ++i) {
swig_type_info *type = 0;
swig_type_info *ret;
swig_cast_info *cast;
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
#endif
/* if there is another module already loaded */
if (swig_module.next != &swig_module) {
type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
}
if (type) {
/* Overwrite clientdata field */
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: found type %s\n", type->name);
#endif
if (swig_module.type_initial[i]->clientdata) {
type->clientdata = swig_module.type_initial[i]->clientdata;
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
#endif
}
} else {
type = swig_module.type_initial[i];
}
/* Insert casting types */
cast = swig_module.cast_initial[i];
while (cast->type) {
/* Don't need to add information already in the list */
ret = 0;
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
#endif
if (swig_module.next != &swig_module) {
ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
#ifdef SWIGRUNTIME_DEBUG
if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name);
#endif
}
if (ret) {
if (type == swig_module.type_initial[i]) {
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: skip old type %s\n", ret->name);
#endif
cast->type = ret;
ret = 0;
} else {
/* Check for casting already in the list */
swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);
#ifdef SWIGRUNTIME_DEBUG
if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name);
#endif
if (!ocast) ret = 0;
}
}
if (!ret) {
#ifdef SWIGRUNTIME_DEBUG
printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
#endif
if (type->cast) {
type->cast->prev = cast;
cast->next = type->cast;
}
type->cast = cast;
}
cast++;
}
/* Set entry in modules->types array equal to the type */
swig_module.types[i] = type;
}
swig_module.types[i] = 0;
#ifdef SWIGRUNTIME_DEBUG
printf("**** SWIG_InitializeModule: Cast List ******\n");
for (i = 0; i < swig_module.size; ++i) {
int j = 0;
swig_cast_info *cast = swig_module.cast_initial[i];
printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
while (cast->type) {
printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
cast++;
++j;
}
printf("---- Total casts: %d\n",j);
}
printf("**** SWIG_InitializeModule: Cast List ******\n");
#endif
}
/* This function will propagate the clientdata field of type to
* any new swig_type_info structures that have been added into the list
* of equivalent types. It is like calling
* SWIG_TypeClientData(type, clientdata) a second time.
*/
SWIGRUNTIME void
SWIG_PropagateClientData(void) {
size_t i;
swig_cast_info *equiv;
static int init_run = 0;
if (init_run) return;
init_run = 1;
for (i = 0; i < swig_module.size; i++) {
if (swig_module.types[i]->clientdata) {
equiv = swig_module.types[i]->cast;
while (equiv) {
if (!equiv->converter) {
if (equiv->type && !equiv->type->clientdata)
SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
}
equiv = equiv->next;
}
}
}
}
#ifdef __cplusplus
#if 0
{ /* c-mode */
#endif
}
#endif
/*
*/
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void Init_termbox(void) {
size_t i;
SWIG_InitRuntime();
mTermbox = rb_define_module("Termbox");
SWIG_InitializeModule(0);
for (i = 0; i < swig_module.size; i++) {
SWIG_define_class(swig_module.types[i]);
}
SWIG_RubyInitializeTrackings();
rb_define_const(mTermbox, "TB_EUNSUPPORTED_TERMINAL", SWIG_From_int((int)(-1)));
rb_define_const(mTermbox, "TB_EFAILED_TO_OPEN_TTY", SWIG_From_int((int)(-2)));
rb_define_const(mTermbox, "TB_EPIPE_TRAP_ERROR", SWIG_From_int((int)(-3)));
rb_define_const(mTermbox, "TB_HIDE_CURSOR", SWIG_From_int((int)(-1)));
rb_define_const(mTermbox, "TB_INPUT_CURRENT", SWIG_From_int((int)(0)));
rb_define_const(mTermbox, "TB_INPUT_ESC", SWIG_From_int((int)(1)));
rb_define_const(mTermbox, "TB_INPUT_ALT", SWIG_From_int((int)(2)));
rb_define_const(mTermbox, "TB_EOF", SWIG_From_int((int)(-1)));
rb_define_const(mTermbox, "TB_BOLD", SWIG_From_int((int)(0x10)));
rb_define_const(mTermbox, "TB_UNDERLINE", SWIG_From_int((int)(0x20)));
rb_define_const(mTermbox, "TB_REVERSE", SWIG_From_int((int)(0x40)));
rb_define_const(mTermbox, "TB_MOD_ALT", SWIG_From_int((int)(0x01)));
rb_define_const(mTermbox, "TB_DEFAULT", SWIG_From_int((int)(0x00)));
rb_define_const(mTermbox, "TB_BLACK", SWIG_From_int((int)(0x01)));
rb_define_const(mTermbox, "TB_RED", SWIG_From_int((int)(0x02)));
rb_define_const(mTermbox, "TB_GREEN", SWIG_From_int((int)(0x03)));
rb_define_const(mTermbox, "TB_YELLOW", SWIG_From_int((int)(0x04)));
rb_define_const(mTermbox, "TB_BLUE", SWIG_From_int((int)(0x05)));
rb_define_const(mTermbox, "TB_MAGENTA", SWIG_From_int((int)(0x06)));
rb_define_const(mTermbox, "TB_CYAN", SWIG_From_int((int)(0x07)));
rb_define_const(mTermbox, "TB_WHITE", SWIG_From_int((int)(0x08)));
rb_define_const(mTermbox, "TB_KEY_F1", SWIG_From_int((int)((0xFFFF-0))));
rb_define_const(mTermbox, "TB_KEY_F2", SWIG_From_int((int)((0xFFFF-1))));
rb_define_const(mTermbox, "TB_KEY_F3", SWIG_From_int((int)((0xFFFF-2))));
rb_define_const(mTermbox, "TB_KEY_F4", SWIG_From_int((int)((0xFFFF-3))));
rb_define_const(mTermbox, "TB_KEY_F5", SWIG_From_int((int)((0xFFFF-4))));
rb_define_const(mTermbox, "TB_KEY_F6", SWIG_From_int((int)((0xFFFF-5))));
rb_define_const(mTermbox, "TB_KEY_F7", SWIG_From_int((int)((0xFFFF-6))));
rb_define_const(mTermbox, "TB_KEY_F8", SWIG_From_int((int)((0xFFFF-7))));
rb_define_const(mTermbox, "TB_KEY_F9", SWIG_From_int((int)((0xFFFF-8))));
rb_define_const(mTermbox, "TB_KEY_F10", SWIG_From_int((int)((0xFFFF-9))));
rb_define_const(mTermbox, "TB_KEY_F11", SWIG_From_int((int)((0xFFFF-10))));
rb_define_const(mTermbox, "TB_KEY_F12", SWIG_From_int((int)((0xFFFF-11))));
rb_define_const(mTermbox, "TB_KEY_INSERT", SWIG_From_int((int)((0xFFFF-12))));
rb_define_const(mTermbox, "TB_KEY_DELETE", SWIG_From_int((int)((0xFFFF-13))));
rb_define_const(mTermbox, "TB_KEY_HOME", SWIG_From_int((int)((0xFFFF-14))));
rb_define_const(mTermbox, "TB_KEY_END", SWIG_From_int((int)((0xFFFF-15))));
rb_define_const(mTermbox, "TB_KEY_PGUP", SWIG_From_int((int)((0xFFFF-16))));
rb_define_const(mTermbox, "TB_KEY_PGDN", SWIG_From_int((int)((0xFFFF-17))));
rb_define_const(mTermbox, "TB_KEY_ARROW_UP", SWIG_From_int((int)((0xFFFF-18))));
rb_define_const(mTermbox, "TB_KEY_ARROW_DOWN", SWIG_From_int((int)((0xFFFF-19))));
rb_define_const(mTermbox, "TB_KEY_ARROW_LEFT", SWIG_From_int((int)((0xFFFF-20))));
rb_define_const(mTermbox, "TB_KEY_ARROW_RIGHT", SWIG_From_int((int)((0xFFFF-21))));
rb_define_const(mTermbox, "TB_KEY_CTRL_TILDE", SWIG_From_int((int)(0x00)));
rb_define_const(mTermbox, "TB_KEY_CTRL_2", SWIG_From_int((int)(0x00)));
rb_define_const(mTermbox, "TB_KEY_CTRL_A", SWIG_From_int((int)(0x01)));
rb_define_const(mTermbox, "TB_KEY_CTRL_B", SWIG_From_int((int)(0x02)));
rb_define_const(mTermbox, "TB_KEY_CTRL_C", SWIG_From_int((int)(0x03)));
rb_define_const(mTermbox, "TB_KEY_CTRL_D", SWIG_From_int((int)(0x04)));
rb_define_const(mTermbox, "TB_KEY_CTRL_E", SWIG_From_int((int)(0x05)));
rb_define_const(mTermbox, "TB_KEY_CTRL_F", SWIG_From_int((int)(0x06)));
rb_define_const(mTermbox, "TB_KEY_CTRL_G", SWIG_From_int((int)(0x07)));
rb_define_const(mTermbox, "TB_KEY_BACKSPACE", SWIG_From_int((int)(0x08)));
rb_define_const(mTermbox, "TB_KEY_CTRL_H", SWIG_From_int((int)(0x08)));
rb_define_const(mTermbox, "TB_KEY_TAB", SWIG_From_int((int)(0x09)));
rb_define_const(mTermbox, "TB_KEY_CTRL_I", SWIG_From_int((int)(0x09)));
rb_define_const(mTermbox, "TB_KEY_CTRL_J", SWIG_From_int((int)(0x0A)));
rb_define_const(mTermbox, "TB_KEY_CTRL_K", SWIG_From_int((int)(0x0B)));
rb_define_const(mTermbox, "TB_KEY_CTRL_L", SWIG_From_int((int)(0x0C)));
rb_define_const(mTermbox, "TB_KEY_ENTER", SWIG_From_int((int)(0x0D)));
rb_define_const(mTermbox, "TB_KEY_CTRL_M", SWIG_From_int((int)(0x0D)));
rb_define_const(mTermbox, "TB_KEY_CTRL_N", SWIG_From_int((int)(0x0E)));
rb_define_const(mTermbox, "TB_KEY_CTRL_O", SWIG_From_int((int)(0x0F)));
rb_define_const(mTermbox, "TB_KEY_CTRL_P", SWIG_From_int((int)(0x10)));
rb_define_const(mTermbox, "TB_KEY_CTRL_Q", SWIG_From_int((int)(0x11)));
rb_define_const(mTermbox, "TB_KEY_CTRL_R", SWIG_From_int((int)(0x12)));
rb_define_const(mTermbox, "TB_KEY_CTRL_S", SWIG_From_int((int)(0x13)));
rb_define_const(mTermbox, "TB_KEY_CTRL_T", SWIG_From_int((int)(0x14)));
rb_define_const(mTermbox, "TB_KEY_CTRL_U", SWIG_From_int((int)(0x15)));
rb_define_const(mTermbox, "TB_KEY_CTRL_V", SWIG_From_int((int)(0x16)));
rb_define_const(mTermbox, "TB_KEY_CTRL_W", SWIG_From_int((int)(0x17)));
rb_define_const(mTermbox, "TB_KEY_CTRL_X", SWIG_From_int((int)(0x18)));
rb_define_const(mTermbox, "TB_KEY_CTRL_Y", SWIG_From_int((int)(0x19)));
rb_define_const(mTermbox, "TB_KEY_CTRL_Z", SWIG_From_int((int)(0x1A)));
rb_define_const(mTermbox, "TB_KEY_ESC", SWIG_From_int((int)(0x1B)));
rb_define_const(mTermbox, "TB_KEY_CTRL_LSQ_BRACKET", SWIG_From_int((int)(0x1B)));
rb_define_const(mTermbox, "TB_KEY_CTRL_3", SWIG_From_int((int)(0x1B)));
rb_define_const(mTermbox, "TB_KEY_CTRL_4", SWIG_From_int((int)(0x1C)));
rb_define_const(mTermbox, "TB_KEY_CTRL_BACKSLASH", SWIG_From_int((int)(0x1C)));
rb_define_const(mTermbox, "TB_KEY_CTRL_5", SWIG_From_int((int)(0x1D)));
rb_define_const(mTermbox, "TB_KEY_CTRL_RSQ_BRACKET", SWIG_From_int((int)(0x1D)));
rb_define_const(mTermbox, "TB_KEY_CTRL_6", SWIG_From_int((int)(0x1E)));
rb_define_const(mTermbox, "TB_KEY_CTRL_7", SWIG_From_int((int)(0x1F)));
rb_define_const(mTermbox, "TB_KEY_CTRL_SLASH", SWIG_From_int((int)(0x1F)));
rb_define_const(mTermbox, "TB_KEY_CTRL_UNDERSCORE", SWIG_From_int((int)(0x1F)));
rb_define_const(mTermbox, "TB_KEY_SPACE", SWIG_From_int((int)(0x20)));
rb_define_const(mTermbox, "TB_KEY_BACKSPACE2", SWIG_From_int((int)(0x7F)));
rb_define_const(mTermbox, "TB_KEY_CTRL_8", SWIG_From_int((int)(0x7F)));
SwigClassTb_cell.klass = rb_define_class_under(mTermbox, "Tb_cell", rb_cObject);
SWIG_TypeClientData(SWIGTYPE_p_tb_cell, (void *) &SwigClassTb_cell);
rb_define_alloc_func(SwigClassTb_cell.klass, _wrap_tb_cell_allocate);
rb_define_method(SwigClassTb_cell.klass, "initialize", _wrap_new_tb_cell, -1);
rb_define_method(SwigClassTb_cell.klass, "ch=", _wrap_tb_cell_ch_set, -1);
rb_define_method(SwigClassTb_cell.klass, "ch", _wrap_tb_cell_ch_get, -1);
rb_define_method(SwigClassTb_cell.klass, "fg=", _wrap_tb_cell_fg_set, -1);
rb_define_method(SwigClassTb_cell.klass, "fg", _wrap_tb_cell_fg_get, -1);
rb_define_method(SwigClassTb_cell.klass, "bg=", _wrap_tb_cell_bg_set, -1);
rb_define_method(SwigClassTb_cell.klass, "bg", _wrap_tb_cell_bg_get, -1);
SwigClassTb_cell.mark = 0;
SwigClassTb_cell.destroy = (void (*)(void *)) free_tb_cell;
SwigClassTb_cell.trackObjects = 0;
rb_define_module_function(mTermbox, "tb_init", _wrap_tb_init, -1);
rb_define_module_function(mTermbox, "tb_shutdown", _wrap_tb_shutdown, -1);
rb_define_module_function(mTermbox, "tb_width", _wrap_tb_width, -1);
rb_define_module_function(mTermbox, "tb_height", _wrap_tb_height, -1);
rb_define_module_function(mTermbox, "tb_clear", _wrap_tb_clear, -1);
rb_define_module_function(mTermbox, "tb_set_clear_attributes", _wrap_tb_set_clear_attributes, -1);
rb_define_module_function(mTermbox, "tb_present", _wrap_tb_present, -1);
rb_define_module_function(mTermbox, "tb_set_cursor", _wrap_tb_set_cursor, -1);
rb_define_module_function(mTermbox, "tb_put_cell", _wrap_tb_put_cell, -1);
rb_define_module_function(mTermbox, "tb_change_cell", _wrap_tb_change_cell, -1);
rb_define_module_function(mTermbox, "tb_blit", _wrap_tb_blit, -1);
rb_define_module_function(mTermbox, "tb_select_input_mode", _wrap_tb_select_input_mode, -1);
rb_define_module_function(mTermbox, "tb_peek_event", _wrap_tb_peek_event, -1);
rb_define_module_function(mTermbox, "tb_poll_event", _wrap_tb_poll_event, -1);
rb_define_module_function(mTermbox, "tb_utf8_char_length", _wrap_tb_utf8_char_length, -1);
rb_define_module_function(mTermbox, "tb_utf8_char_to_unicode", _wrap_tb_utf8_char_to_unicode, -1);
rb_define_module_function(mTermbox, "tb_utf8_unicode_to_char", _wrap_tb_utf8_unicode_to_char, -1);
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_w32CreateFile_07.cpp | 2 | 5680 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_w32CreateFile_07.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-07.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sink: w32CreateFile
* BadSink : Open the file named in data using CreateFile()
* Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <windows.h>
/* The variable below is not declared "const", but is never assigned
any other value so a tool should be able to identify that reads of
this will always give its initialized value. */
static int staticFive = 5;
namespace CWE36_Absolute_Path_Traversal__char_file_w32CreateFile_07
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(staticFive==5)
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
{
HANDLE hFile;
/* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
hFile = CreateFileA(data,
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
}
{
HANDLE hFile;
/* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
hFile = CreateFileA(data,
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(staticFive==5)
{
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
}
{
HANDLE hFile;
/* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
hFile = CreateFileA(data,
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
}
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE36_Absolute_Path_Traversal__char_file_w32CreateFile_07; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
bhlzlx/ogre | Tests/OgreMain/src/MeshWithoutIndexDataTests.cpp | 3 | 16954 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 <stdio.h>
#include "Ogre.h"
#include "OgreProgressiveMesh.h"
#include "OgreDefaultHardwareBufferManager.h"
#include "OgreFileSystem.h"
#include "OgreArchiveManager.h"
#include "MeshWithoutIndexDataTests.h"
// Register the suite
CPPUNIT_TEST_SUITE_REGISTRATION( MeshWithoutIndexDataTests );
void MeshWithoutIndexDataTests::setUp()
{
LogManager::getSingleton().createLog("MeshWithoutIndexDataTests.log", true);
OGRE_NEW ResourceGroupManager();
OGRE_NEW LodStrategyManager();
mBufMgr = OGRE_NEW DefaultHardwareBufferManager();
mMeshMgr = OGRE_NEW MeshManager();
archiveMgr = OGRE_NEW ArchiveManager();
archiveMgr->addArchiveFactory(OGRE_NEW FileSystemArchiveFactory());
MaterialManager* matMgr = OGRE_NEW MaterialManager();
matMgr->initialise();
}
void MeshWithoutIndexDataTests::tearDown()
{
OGRE_DELETE mMeshMgr;
OGRE_DELETE mBufMgr;
OGRE_DELETE archiveMgr;
OGRE_DELETE MaterialManager::getSingletonPtr();
OGRE_DELETE LodStrategyManager::getSingletonPtr();
OGRE_DELETE ResourceGroupManager::getSingletonPtr();
}
void MeshWithoutIndexDataTests::testCreateSimpleLine()
{
ManualObject* line = OGRE_NEW ManualObject("line");
line->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST);
line->position(0, 50, 0);
line->position(50, 100, 0);
line->end();
String fileName = "line.mesh";
MeshPtr lineMesh = line->convertToMesh(fileName);
OGRE_DELETE line;
CPPUNIT_ASSERT(lineMesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->indexData->indexCount == 0);
RenderOperation rop;
lineMesh->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2);
MeshSerializer meshWriter;
meshWriter.exportMesh(lineMesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedLine = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedLine->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(loadedLine->getSubMesh(0)->indexData->indexCount == 0);
loadedLine->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testCreateLineList()
{
ManualObject* lineList = OGRE_NEW ManualObject("line");
lineList->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST);
lineList->position(0, 50, 0);
lineList->position(50, 100, 0);
lineList->position(50, 50, 0);
lineList->position(100, 100, 0);
lineList->position(0, 50, 0);
lineList->position(50, 50, 0);
lineList->end();
String fileName = "lineList.mesh";
MeshPtr lineListMesh = lineList->convertToMesh(fileName);
OGRE_DELETE lineList;
CPPUNIT_ASSERT(lineListMesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(lineListMesh->getSubMesh(0)->indexData->indexCount == 0);
RenderOperation rop;
lineListMesh->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineListMesh->getSubMesh(0)->vertexData->vertexCount == 6);
MeshSerializer meshWriter;
meshWriter.exportMesh(lineListMesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedLineList = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedLineList->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(loadedLineList->getSubMesh(0)->indexData->indexCount == 0);
loadedLineList->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(loadedLineList->getSubMesh(0)->vertexData->vertexCount == 6);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testCreateLineStrip()
{
ManualObject* lineStrip = OGRE_NEW ManualObject("line");
lineStrip->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP);
lineStrip->position(50, 100, 0);
lineStrip->position(0, 50, 0);
lineStrip->position(50, 50, 0);
lineStrip->position(100, 100, 0);
lineStrip->end();
String fileName = "lineStrip.mesh";
MeshPtr lineStripMesh = lineStrip->convertToMesh(fileName);
OGRE_DELETE lineStrip;
CPPUNIT_ASSERT(lineStripMesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(lineStripMesh->getSubMesh(0)->indexData->indexCount == 0);
RenderOperation rop;
lineStripMesh->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineStripMesh->getSubMesh(0)->vertexData->vertexCount == 4);
MeshSerializer meshWriter;
meshWriter.exportMesh(lineStripMesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedLineStrip = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedLineStrip->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(loadedLineStrip->getSubMesh(0)->indexData->indexCount == 0);
loadedLineStrip->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(loadedLineStrip->getSubMesh(0)->vertexData->vertexCount == 4);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testCreatePointList()
{
ManualObject* pointList = OGRE_NEW ManualObject("line");
pointList->begin("BaseWhiteNoLighting", RenderOperation::OT_POINT_LIST);
pointList->position(50, 100, 0);
pointList->position(0, 50, 0);
pointList->position(50, 50, 0);
pointList->position(100, 100, 0);
pointList->end();
String fileName = "pointList.mesh";
MeshPtr pointListMesh = pointList->convertToMesh(fileName);
OGRE_DELETE pointList;
CPPUNIT_ASSERT(pointListMesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(pointListMesh->getSubMesh(0)->indexData->indexCount == 0);
RenderOperation rop;
pointListMesh->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(pointListMesh->getSubMesh(0)->vertexData->vertexCount == 4);
MeshSerializer meshWriter;
meshWriter.exportMesh(pointListMesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedPointList = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedPointList->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(loadedPointList->getSubMesh(0)->indexData->indexCount == 0);
loadedPointList->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(loadedPointList->getSubMesh(0)->vertexData->vertexCount == 4);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testCreateLineWithMaterial()
{
String matName = "lineMat";
MaterialPtr matPtr = MaterialManager::getSingleton().create(matName, "General");
Pass* pass = matPtr->getTechnique(0)->getPass(0);
pass->setDiffuse(1.0, 0.1, 0.1, 0);
ManualObject* line = OGRE_NEW ManualObject("line");
line->begin(matName, RenderOperation::OT_LINE_LIST);
line->position(0, 50, 0);
line->position(50, 100, 0);
line->end();
String fileName = "lineWithMat.mesh";
MeshPtr lineMesh = line->convertToMesh(fileName);
OGRE_DELETE line;
CPPUNIT_ASSERT(lineMesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->indexData->indexCount == 0);
RenderOperation rop;
lineMesh->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2);
MeshSerializer meshWriter;
meshWriter.exportMesh(lineMesh.get(), fileName);
MaterialSerializer matWriter;
matWriter.exportMaterial(
MaterialManager::getSingleton().getByName(matName),
matName + ".material"
);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedLine = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
remove((matName + ".material").c_str());
CPPUNIT_ASSERT(loadedLine->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(loadedLine->getSubMesh(0)->indexData->indexCount == 0);
loadedLine->getSubMesh(0)->_getRenderOperation(rop);
CPPUNIT_ASSERT(rop.useIndexes == false);
CPPUNIT_ASSERT(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2);
mMeshMgr->remove( fileName );
}
void createMeshWithMaterial(String fileName)
{
String matFileNameSuffix = ".material";
String matName1 = "red";
String matFileName1 = matName1 + matFileNameSuffix;
MaterialPtr matPtr = MaterialManager::getSingleton().create(matName1, "General");
Pass* pass = matPtr->getTechnique(0)->getPass(0);
pass->setDiffuse(1.0, 0.1, 0.1, 0);
String matName2 = "green";
String matFileName2 = matName2 + matFileNameSuffix;
matPtr = MaterialManager::getSingleton().create(matName2, "General");
pass = matPtr->getTechnique(0)->getPass(0);
pass->setDiffuse(0.1, 1.0, 0.1, 0);
String matName3 = "blue";
String matFileName3 = matName3 + matFileNameSuffix;
matPtr = MaterialManager::getSingleton().create(matName3, "General");
pass = matPtr->getTechnique(0)->getPass(0);
pass->setDiffuse(0.1, 0.1, 1.0, 0);
String matName4 = "yellow";
String matFileName4 = matName4 + matFileNameSuffix;
matPtr = MaterialManager::getSingleton().create(matName4, "General");
pass = matPtr->getTechnique(0)->getPass(0);
pass->setDiffuse(1.0, 1.0, 0.1, 0);
ManualObject* manObj = OGRE_NEW ManualObject("mesh");
manObj->begin(matName1, RenderOperation::OT_TRIANGLE_LIST);
manObj->position(0, 50, 0);
manObj->position(50, 50, 0);
manObj->position(0, 100, 0);
manObj->triangle(0, 1, 2);
manObj->position(50, 100, 0);
manObj->position(0, 100, 0);
manObj->position(50, 50, 0);
manObj->triangle(3, 4, 5);
manObj->end();
manObj->begin(matName2, RenderOperation::OT_LINE_LIST);
manObj->position(0, 100, 0);
manObj->position(-50, 50, 0);
manObj->position(-50, 0, 0);
manObj->position(-50, 50, 0);
manObj->position(-100, 0, 0);
manObj->position(-50, 0, 0);
manObj->end();
manObj->begin(matName3, RenderOperation::OT_LINE_STRIP);
manObj->position(50, 100, 0);
manObj->position(100, 50, 0);
manObj->position(100, 0, 0);
manObj->position(150, 0, 0);
manObj->end();
manObj->begin(matName4, RenderOperation::OT_POINT_LIST);
manObj->position(50, 0, 0);
manObj->position(0, 0, 0);
manObj->end();
manObj->convertToMesh(fileName);
OGRE_DELETE manObj;
}
void MeshWithoutIndexDataTests::testCreateMesh()
{
String fileName = "indexMix.mesh";
createMeshWithMaterial(fileName);
MeshPtr mesh = mMeshMgr->getByName(fileName);
CPPUNIT_ASSERT(mesh->getNumSubMeshes() == 4);
RenderOperation rop;
for (int i=0; i<4; ++i)
{
mesh->getSubMesh(i)->_getRenderOperation(rop);
// first submesh has indexes; the others not
CPPUNIT_ASSERT( rop.useIndexes == (i == 0) );
}
MeshSerializer meshWriter;
meshWriter.exportMesh(mesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedMesh = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedMesh->getNumSubMeshes() == 4);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testCloneMesh()
{
String originalName = "toClone.mesh";
createMeshWithMaterial(originalName);
MeshPtr mesh = mMeshMgr->getByName(originalName);
String fileName = "clone.mesh";
MeshPtr clone = mesh->clone(fileName);
CPPUNIT_ASSERT(mesh->getNumSubMeshes() == 4);
MeshSerializer meshWriter;
meshWriter.exportMesh(mesh.get(), fileName);
mMeshMgr->remove( fileName );
ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem");
MeshPtr loadedMesh = mMeshMgr->load(fileName, "General");
remove(fileName.c_str());
CPPUNIT_ASSERT(loadedMesh->getNumSubMeshes() == 4);
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testEdgeList()
{
String fileName = "testEdgeList.mesh";
ManualObject* line = OGRE_NEW ManualObject("line");
line->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST);
line->position(0, 50, 0);
line->position(50, 100, 0);
line->end();
MeshPtr mesh = line->convertToMesh(fileName);
OGRE_DELETE line;
// whole mesh must not contain index data, for this test
CPPUNIT_ASSERT(mesh->getNumSubMeshes() == 1);
CPPUNIT_ASSERT(mesh->getSubMesh(0)->indexData->indexCount == 0);
mesh->buildEdgeList();
MeshSerializer meshWriter;
// if it does not crash here, test is passed
meshWriter.exportMesh(mesh.get(), fileName);
remove(fileName.c_str());
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testGenerateExtremes()
{
String fileName = "testGenerateExtremes.mesh";
createMeshWithMaterial(fileName);
MeshPtr mesh = mMeshMgr->getByName(fileName);
const size_t NUM_EXTREMES = 4;
for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i)
{
mesh->getSubMesh(i)->generateExtremes(NUM_EXTREMES);
}
for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i)
{
SubMesh* subMesh = mesh->getSubMesh(i);
if (subMesh->indexData->indexCount > 0)
{
CPPUNIT_ASSERT(subMesh->extremityPoints.size() == NUM_EXTREMES);
}
else
{
CPPUNIT_ASSERT(subMesh->extremityPoints.size() == 0);
}
}
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testBuildTangentVectors()
{
String fileName = "testBuildTangentVectors.mesh";
createMeshWithMaterial(fileName);
MeshPtr mesh = mMeshMgr->getByName(fileName);
try
{
// make sure correct exception is thrown
mesh->buildTangentVectors();
CPPUNIT_FAIL("Expected InvalidParametersException!");
}
catch (const InvalidParametersException&)
{
// ok
}
mMeshMgr->remove( fileName );
}
void MeshWithoutIndexDataTests::testGenerateLodLevels()
{
String fileName = "testGenerateLodLevels.mesh";
createMeshWithMaterial(fileName);
MeshPtr mesh = mMeshMgr->getByName(fileName);
Mesh::LodValueList lodDistanceList;
lodDistanceList.push_back(600.0);
ProgressiveMesh::generateLodLevels(mesh.get(), lodDistanceList, ProgressiveMesh::VRQ_CONSTANT, 2);
CPPUNIT_ASSERT(mesh->getNumLodLevels() == 2);
for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i)
{
SubMesh* subMesh = mesh->getSubMesh(i);
for (ushort j = 0; j < mesh->getNumLodLevels() - 1; ++j)
{
if (subMesh->indexData->indexCount > 0)
{
CPPUNIT_ASSERT(subMesh->mLodFaceList[j]->indexCount > 0);
}
else
{
CPPUNIT_ASSERT(subMesh->mLodFaceList[j]->indexCount == 0);
}
}
}
MeshSerializer meshWriter;
meshWriter.exportMesh(mesh.get(), fileName);
remove(fileName.c_str());
mMeshMgr->remove( fileName );
}
| mit |
ashemedai/ProDBG | src/native/external/angelscript/angelscript/source/as_objecttype.cpp | 3 | 28091 | /*
AngelCode Scripting Library
Copyright (c) 2003-2014 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_objecttype.cpp
//
// A class for storing object type information
//
#include <stdio.h>
#include "as_config.h"
#include "as_objecttype.h"
#include "as_configgroup.h"
#include "as_scriptengine.h"
BEGIN_AS_NAMESPACE
#ifdef AS_MAX_PORTABILITY
static void ObjectType_AddRef_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
self->AddRef();
}
static void ObjectType_Release_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
self->Release();
}
static void ObjectType_GetRefCount_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
*(int*)gen->GetAddressOfReturnLocation() = self->GetRefCount();
}
static void ObjectType_SetGCFlag_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
self->SetGCFlag();
}
static void ObjectType_GetGCFlag_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
*(bool*)gen->GetAddressOfReturnLocation() = self->GetGCFlag();
}
static void ObjectType_EnumReferences_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
self->EnumReferences(engine);
}
static void ObjectType_ReleaseAllHandles_Generic(asIScriptGeneric *gen)
{
asCObjectType *self = (asCObjectType*)gen->GetObject();
asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
self->ReleaseAllHandles(engine);
}
#endif
void RegisterObjectTypeGCBehaviours(asCScriptEngine *engine)
{
// Register the gc behaviours for the object types
int r = 0;
UNUSED_VAR(r); // It is only used in debug mode
engine->objectTypeBehaviours.engine = engine;
engine->objectTypeBehaviours.flags = asOBJ_REF | asOBJ_GC;
engine->objectTypeBehaviours.name = "_builtin_objecttype_";
#ifndef AS_MAX_PORTABILITY
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ADDREF, "void f()", asMETHOD(asCObjectType,AddRef), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASE, "void f()", asMETHOD(asCObjectType,Release), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asMETHOD(asCObjectType,GetRefCount), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asMETHOD(asCObjectType,SetGCFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asMETHOD(asCObjectType,GetGCFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asMETHOD(asCObjectType,EnumReferences), asCALL_THISCALL, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asMETHOD(asCObjectType,ReleaseAllHandles), asCALL_THISCALL, 0); asASSERT( r >= 0 );
#else
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ADDREF, "void f()", asFUNCTION(ObjectType_AddRef_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASE, "void f()", asFUNCTION(ObjectType_Release_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asFUNCTION(ObjectType_GetRefCount_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asFUNCTION(ObjectType_SetGCFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asFUNCTION(ObjectType_GetGCFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asFUNCTION(ObjectType_EnumReferences_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asFUNCTION(ObjectType_ReleaseAllHandles_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
#endif
}
asCObjectType::asCObjectType()
{
engine = 0;
module = 0;
refCount.set(0);
derivedFrom = 0;
acceptValueSubType = true;
acceptRefSubType = true;
accessMask = 0xFFFFFFFF;
nameSpace = 0;
#ifdef WIP_16BYTE_ALIGN
alignment = 4;
#endif
}
asCObjectType::asCObjectType(asCScriptEngine *engine)
{
this->engine = engine;
module = 0;
refCount.set(0);
derivedFrom = 0;
acceptValueSubType = true;
acceptRefSubType = true;
accessMask = 0xFFFFFFFF;
nameSpace = engine->nameSpaces[0];
#ifdef WIP_16BYTE_ALIGN
alignment = 4;
#endif
}
int asCObjectType::AddRef() const
{
gcFlag = false;
return refCount.atomicInc();
}
int asCObjectType::Release() const
{
gcFlag = false;
int r = refCount.atomicDec();
if( r == 0 && engine == 0 )
{
// If the engine is no longer set, then it has already been
// released and we must take care of the deletion ourselves
asDELETE(const_cast<asCObjectType*>(this), asCObjectType);
}
return r;
}
void asCObjectType::Orphan(asCModule *mod)
{
if( mod && mod == module )
{
module = 0;
if( flags & asOBJ_SCRIPT_OBJECT )
{
// Tell the GC that this type exists so it can resolve potential circular references
engine->gc.AddScriptObjectToGC(this, &engine->objectTypeBehaviours);
}
// It's necessary to orphan the template instance types that refer to this object type,
// otherwise the garbage collector cannot identify the circular references that involve
// the type and the template type
engine->OrphanTemplateInstances(this);
}
Release();
}
// interface
asIScriptModule *asCObjectType::GetModule() const
{
return module;
}
void *asCObjectType::SetUserData(void *data, asPWORD type)
{
// As a thread might add a new new user data at the same time as another
// it is necessary to protect both read and write access to the userData member
ACQUIREEXCLUSIVE(engine->engineRWLock);
// It is not intended to store a lot of different types of userdata,
// so a more complex structure like a associative map would just have
// more overhead than a simple array.
for( asUINT n = 0; n < userData.GetLength(); n += 2 )
{
if( userData[n] == type )
{
void *oldData = reinterpret_cast<void*>(userData[n+1]);
userData[n+1] = reinterpret_cast<asPWORD>(data);
RELEASEEXCLUSIVE(engine->engineRWLock);
return oldData;
}
}
userData.PushLast(type);
userData.PushLast(reinterpret_cast<asPWORD>(data));
RELEASEEXCLUSIVE(engine->engineRWLock);
return 0;
}
void *asCObjectType::GetUserData(asPWORD type) const
{
// There may be multiple threads reading, but when
// setting the user data nobody must be reading.
ACQUIRESHARED(engine->engineRWLock);
for( asUINT n = 0; n < userData.GetLength(); n += 2 )
{
if( userData[n] == type )
{
RELEASESHARED(engine->engineRWLock);
return reinterpret_cast<void*>(userData[n+1]);
}
}
RELEASESHARED(engine->engineRWLock);
return 0;
}
int asCObjectType::GetRefCount()
{
return refCount.get();
}
bool asCObjectType::GetGCFlag()
{
return gcFlag;
}
void asCObjectType::SetGCFlag()
{
gcFlag = true;
}
void asCObjectType::DropFromEngine()
{
DestroyInternal();
// If the ref counter reached zero while doing the above clean-up then we must delete the object now
if( refCount.get() == 0 )
asDELETE(this, asCObjectType);
}
void asCObjectType::DestroyInternal()
{
if( engine == 0 ) return;
// Skip this for list patterns as they do not increase the references
if( flags & asOBJ_LIST_PATTERN )
{
// Clear the engine pointer to mark the object type as invalid
engine = 0;
return;
}
// Release the object types held by the templateSubTypes
for( asUINT subtypeIndex = 0; subtypeIndex < templateSubTypes.GetLength(); subtypeIndex++ )
{
if( templateSubTypes[subtypeIndex].GetObjectType() )
templateSubTypes[subtypeIndex].GetObjectType()->Release();
}
templateSubTypes.SetLength(0);
if( derivedFrom )
derivedFrom->Release();
derivedFrom = 0;
ReleaseAllProperties();
ReleaseAllFunctions();
asUINT n;
for( n = 0; n < enumValues.GetLength(); n++ )
{
if( enumValues[n] )
asDELETE(enumValues[n],asSEnumValue);
}
enumValues.SetLength(0);
// Clean the user data
for( n = 0; n < userData.GetLength(); n += 2 )
{
if( userData[n+1] )
{
for( asUINT c = 0; c < engine->cleanObjectTypeFuncs.GetLength(); c++ )
if( engine->cleanObjectTypeFuncs[c].type == userData[n] )
engine->cleanObjectTypeFuncs[c].cleanFunc(this);
}
}
userData.SetLength(0);
// Clear the engine pointer to mark the object type as invalid
engine = 0;
}
asCObjectType::~asCObjectType()
{
DestroyInternal();
}
// interface
bool asCObjectType::Implements(const asIObjectType *objType) const
{
if( this == objType )
return true;
for( asUINT n = 0; n < interfaces.GetLength(); n++ )
if( interfaces[n] == objType ) return true;
return false;
}
// interface
bool asCObjectType::DerivesFrom(const asIObjectType *objType) const
{
if( this == objType )
return true;
asCObjectType *base = derivedFrom;
while( base )
{
if( base == objType )
return true;
base = base->derivedFrom;
}
return false;
}
bool asCObjectType::IsShared() const
{
// Objects that can be declared by scripts need to have the explicit flag asOBJ_SHARED
if( flags & (asOBJ_SCRIPT_OBJECT|asOBJ_ENUM) ) return flags & asOBJ_SHARED ? true : false;
// Otherwise we assume the object to be shared
return true;
}
// interface
const char *asCObjectType::GetName() const
{
return name.AddressOf();
}
// interface
const char *asCObjectType::GetNamespace() const
{
return nameSpace->name.AddressOf();
}
// interface
asDWORD asCObjectType::GetFlags() const
{
return flags;
}
// interface
asUINT asCObjectType::GetSize() const
{
return size;
}
// interface
int asCObjectType::GetTypeId() const
{
// We need a non const pointer to create the asCDataType object.
// We're not breaking anything here because this function is not
// modifying the object, so this const cast is safe.
asCObjectType *ot = const_cast<asCObjectType*>(this);
return engine->GetTypeIdFromDataType(asCDataType::CreateObject(ot, false));
}
// interface
int asCObjectType::GetSubTypeId(asUINT subtypeIndex) const
{
// This method is only supported for templates and template specializations
if( templateSubTypes.GetLength() == 0 )
return asERROR;
if( subtypeIndex >= templateSubTypes.GetLength() )
return asINVALID_ARG;
return engine->GetTypeIdFromDataType(templateSubTypes[subtypeIndex]);
}
// interface
asIObjectType *asCObjectType::GetSubType(asUINT subtypeIndex) const
{
if( subtypeIndex >= templateSubTypes.GetLength() )
return 0;
return templateSubTypes[subtypeIndex].GetObjectType();
}
asUINT asCObjectType::GetSubTypeCount() const
{
return asUINT(templateSubTypes.GetLength());
}
asUINT asCObjectType::GetInterfaceCount() const
{
return asUINT(interfaces.GetLength());
}
asIObjectType *asCObjectType::GetInterface(asUINT index) const
{
return interfaces[index];
}
// internal
bool asCObjectType::IsInterface() const
{
if( (flags & asOBJ_SCRIPT_OBJECT) && size == 0 )
return true;
return false;
}
asIScriptEngine *asCObjectType::GetEngine() const
{
return engine;
}
// interface
asUINT asCObjectType::GetFactoryCount() const
{
return (asUINT)beh.factories.GetLength();
}
// interface
asIScriptFunction *asCObjectType::GetFactoryByIndex(asUINT index) const
{
if( index >= beh.factories.GetLength() )
return 0;
return engine->GetFunctionById(beh.factories[index]);
}
// interface
asIScriptFunction *asCObjectType::GetFactoryByDecl(const char *decl) const
{
if( beh.factories.GetLength() == 0 )
return 0;
// Let the engine parse the string and find the appropriate factory function
return engine->GetFunctionById(engine->GetFactoryIdByDecl(this, decl));
}
// interface
asUINT asCObjectType::GetMethodCount() const
{
return (asUINT)methods.GetLength();
}
// interface
asIScriptFunction *asCObjectType::GetMethodByIndex(asUINT index, bool getVirtual) const
{
if( index >= methods.GetLength() )
return 0;
asCScriptFunction *func = engine->scriptFunctions[methods[index]];
if( !getVirtual )
{
if( func && func->funcType == asFUNC_VIRTUAL )
return virtualFunctionTable[func->vfTableIdx];
}
return func;
}
// interface
asIScriptFunction *asCObjectType::GetMethodByName(const char *name, bool getVirtual) const
{
int id = -1;
for( size_t n = 0; n < methods.GetLength(); n++ )
{
if( engine->scriptFunctions[methods[n]]->name == name )
{
if( id == -1 )
id = methods[n];
else
return 0;
}
}
if( id == -1 ) return 0;
asCScriptFunction *func = engine->scriptFunctions[id];
if( !getVirtual )
{
if( func && func->funcType == asFUNC_VIRTUAL )
return virtualFunctionTable[func->vfTableIdx];
}
return func;
}
// interface
asIScriptFunction *asCObjectType::GetMethodByDecl(const char *decl, bool getVirtual) const
{
if( methods.GetLength() == 0 )
return 0;
// Get the module from one of the methods, but it will only be
// used to allow the parsing of types not already known by the object.
// It is possible for object types to be orphaned, e.g. by discarding
// the module that created it. In this case it is still possible to
// find the methods, but any type not known by the object will result in
// an invalid declaration.
asCModule *mod = engine->scriptFunctions[methods[0]]->module;
int id = engine->GetMethodIdByDecl(this, decl, mod);
if( id <= 0 )
return 0;
if( !getVirtual )
{
asCScriptFunction *func = engine->scriptFunctions[id];
if( func && func->funcType == asFUNC_VIRTUAL )
return virtualFunctionTable[func->vfTableIdx];
}
return engine->scriptFunctions[id];
}
// interface
asUINT asCObjectType::GetPropertyCount() const
{
return (asUINT)properties.GetLength();
}
// interface
int asCObjectType::GetProperty(asUINT index, const char **name, int *typeId, bool *isPrivate, int *offset, bool *isReference, asDWORD *accessMask) const
{
if( index >= properties.GetLength() )
return asINVALID_ARG;
if( name )
*name = properties[index]->name.AddressOf();
if( typeId )
*typeId = engine->GetTypeIdFromDataType(properties[index]->type);
if( isPrivate )
*isPrivate = properties[index]->isPrivate;
if( offset )
*offset = properties[index]->byteOffset;
if( isReference )
*isReference = properties[index]->type.IsReference();
if( accessMask )
*accessMask = properties[index]->accessMask;
return 0;
}
// interface
const char *asCObjectType::GetPropertyDeclaration(asUINT index, bool includeNamespace) const
{
if( index >= properties.GetLength() )
return 0;
asCString *tempString = &asCThreadManager::GetLocalData()->string;
if( properties[index]->isPrivate )
*tempString = "private ";
else
*tempString = "";
*tempString += properties[index]->type.Format(includeNamespace);
*tempString += " ";
*tempString += properties[index]->name;
return tempString->AddressOf();
}
asIObjectType *asCObjectType::GetBaseType() const
{
return derivedFrom;
}
asUINT asCObjectType::GetBehaviourCount() const
{
// Count the number of behaviours (except factory functions)
asUINT count = 0;
if( beh.destruct ) count++;
if( beh.addref ) count++;
if( beh.release ) count++;
if( beh.gcGetRefCount ) count++;
if( beh.gcSetFlag ) count++;
if( beh.gcGetFlag ) count++;
if( beh.gcEnumReferences ) count++;
if( beh.gcReleaseAllReferences ) count++;
if( beh.templateCallback ) count++;
if( beh.listFactory ) count++;
if( beh.getWeakRefFlag ) count++;
// For reference types, the factories are also stored in the constructor
// list, so it is sufficient to enumerate only those
count += (asUINT)beh.constructors.GetLength();
count += (asUINT)beh.operators.GetLength() / 2;
return count;
}
asIScriptFunction *asCObjectType::GetBehaviourByIndex(asUINT index, asEBehaviours *outBehaviour) const
{
// Find the correct behaviour
asUINT count = 0;
if( beh.destruct && count++ == index ) // only increase count if the behaviour is registered
{
if( outBehaviour ) *outBehaviour = asBEHAVE_DESTRUCT;
return engine->scriptFunctions[beh.destruct];
}
if( beh.addref && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_ADDREF;
return engine->scriptFunctions[beh.addref];
}
if( beh.release && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_RELEASE;
return engine->scriptFunctions[beh.release];
}
if( beh.gcGetRefCount && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_GETREFCOUNT;
return engine->scriptFunctions[beh.gcGetRefCount];
}
if( beh.gcSetFlag && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_SETGCFLAG;
return engine->scriptFunctions[beh.gcSetFlag];
}
if( beh.gcGetFlag && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_GETGCFLAG;
return engine->scriptFunctions[beh.gcGetFlag];
}
if( beh.gcEnumReferences && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_ENUMREFS;
return engine->scriptFunctions[beh.gcEnumReferences];
}
if( beh.gcReleaseAllReferences && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_RELEASEREFS;
return engine->scriptFunctions[beh.gcReleaseAllReferences];
}
if( beh.templateCallback && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_TEMPLATE_CALLBACK;
return engine->scriptFunctions[beh.templateCallback];
}
if( beh.listFactory && count++ == index )
{
if( outBehaviour )
{
if( flags & asOBJ_VALUE )
*outBehaviour = asBEHAVE_LIST_CONSTRUCT;
else
*outBehaviour = asBEHAVE_LIST_FACTORY;
}
return engine->scriptFunctions[beh.listFactory];
}
if( beh.getWeakRefFlag && count++ == index )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_GET_WEAKREF_FLAG;
return engine->scriptFunctions[beh.getWeakRefFlag];
}
// For reference types, the factories are also stored in the constructor
// list, so it is sufficient to enumerate only those
if( index - count < beh.constructors.GetLength() )
{
if( outBehaviour ) *outBehaviour = asBEHAVE_CONSTRUCT;
return engine->scriptFunctions[beh.constructors[index - count]];
}
else
count += (asUINT)beh.constructors.GetLength();
if( index - count < beh.operators.GetLength() / 2 )
{
index = 2*(index - count);
if( outBehaviour ) *outBehaviour = static_cast<asEBehaviours>(beh.operators[index]);
return engine->scriptFunctions[beh.operators[index + 1]];
}
return 0;
}
// interface
const char *asCObjectType::GetConfigGroup() const
{
asCConfigGroup *group = engine->FindConfigGroupForObjectType(this);
if( group == 0 )
return 0;
return group->groupName.AddressOf();
}
// interface
asDWORD asCObjectType::GetAccessMask() const
{
return accessMask;
}
// internal
asCObjectProperty *asCObjectType::AddPropertyToClass(const asCString &name, const asCDataType &dt, bool isPrivate)
{
asASSERT( flags & asOBJ_SCRIPT_OBJECT );
asASSERT( dt.CanBeInstantiated() );
asASSERT( !IsInterface() );
// Store the properties in the object type descriptor
asCObjectProperty *prop = asNEW(asCObjectProperty);
if( prop == 0 )
{
// Out of memory
return 0;
}
prop->name = name;
prop->type = dt;
prop->isPrivate = isPrivate;
int propSize;
if( dt.IsObject() )
{
// Non-POD value types can't be allocated inline,
// because there is a risk that the script might
// try to access the content without knowing that
// it hasn't been initialized yet.
if( dt.GetObjectType()->flags & asOBJ_POD )
propSize = dt.GetSizeInMemoryBytes();
else
{
propSize = dt.GetSizeOnStackDWords()*4;
if( !dt.IsObjectHandle() )
prop->type.MakeReference(true);
}
}
else
propSize = dt.GetSizeInMemoryBytes();
// Add extra bytes so that the property will be properly aligned
#ifndef WIP_16BYTE_ALIGN
if( propSize == 2 && (size & 1) ) size += 1;
if( propSize > 2 && (size & 3) ) size += 4 - (size & 3);
#else
asUINT alignment = dt.GetAlignment();
const asUINT propSizeAlignmentDifference = size & (alignment-1);
if( propSizeAlignmentDifference != 0 )
{
size += (alignment - propSizeAlignmentDifference);
}
asASSERT((size % alignment) == 0);
#endif
prop->byteOffset = size;
size += propSize;
properties.PushLast(prop);
// Make sure the struct holds a reference to the config group where the object is registered
asCConfigGroup *group = engine->FindConfigGroupForObjectType(prop->type.GetObjectType());
if( group != 0 ) group->AddRef();
// Add reference to object types
asCObjectType *type = prop->type.GetObjectType();
if( type )
type->AddRef();
return prop;
}
// internal
void asCObjectType::ReleaseAllProperties()
{
for( asUINT n = 0; n < properties.GetLength(); n++ )
{
if( properties[n] )
{
if( flags & asOBJ_SCRIPT_OBJECT )
{
// Release the config group for script classes that are being destroyed
asCConfigGroup *group = engine->FindConfigGroupForObjectType(properties[n]->type.GetObjectType());
if( group != 0 ) group->Release();
// Release references to objects types
asCObjectType *type = properties[n]->type.GetObjectType();
if( type )
type->Release();
}
else
{
// Release template instance types (ref increased by RegisterObjectProperty)
asCObjectType *type = properties[n]->type.GetObjectType();
if( type )
type->Release();
}
asDELETE(properties[n],asCObjectProperty);
}
}
properties.SetLength(0);
}
// internal
void asCObjectType::ReleaseAllHandles(asIScriptEngine *)
{
ReleaseAllFunctions();
ReleaseAllProperties();
}
// internal
void asCObjectType::ReleaseAllFunctions()
{
beh.factory = 0;
beh.copyfactory = 0;
for( asUINT a = 0; a < beh.factories.GetLength(); a++ )
{
if( engine->scriptFunctions[beh.factories[a]] )
engine->scriptFunctions[beh.factories[a]]->Release();
}
beh.factories.SetLength(0);
beh.construct = 0;
beh.copyconstruct = 0;
for( asUINT b = 0; b < beh.constructors.GetLength(); b++ )
{
if( engine->scriptFunctions[beh.constructors[b]] )
engine->scriptFunctions[beh.constructors[b]]->Release();
}
beh.constructors.SetLength(0);
if( beh.templateCallback )
engine->scriptFunctions[beh.templateCallback]->Release();
beh.templateCallback = 0;
if( beh.listFactory )
engine->scriptFunctions[beh.listFactory]->Release();
beh.listFactory = 0;
if( beh.destruct )
engine->scriptFunctions[beh.destruct]->Release();
beh.destruct = 0;
if( beh.copy )
engine->scriptFunctions[beh.copy]->Release();
beh.copy = 0;
for( asUINT e = 1; e < beh.operators.GetLength(); e += 2 )
{
if( engine->scriptFunctions[beh.operators[e]] )
engine->scriptFunctions[beh.operators[e]]->Release();
}
beh.operators.SetLength(0);
for( asUINT c = 0; c < methods.GetLength(); c++ )
{
if( engine->scriptFunctions[methods[c]] )
engine->scriptFunctions[methods[c]]->Release();
}
methods.SetLength(0);
for( asUINT d = 0; d < virtualFunctionTable.GetLength(); d++ )
{
if( virtualFunctionTable[d] )
virtualFunctionTable[d]->Release();
}
virtualFunctionTable.SetLength(0);
// GC behaviours
if( beh.addref )
engine->scriptFunctions[beh.addref]->Release();
beh.addref = 0;
if( beh.release )
engine->scriptFunctions[beh.release]->Release();
beh.release = 0;
if( beh.gcEnumReferences )
engine->scriptFunctions[beh.gcEnumReferences]->Release();
beh.gcEnumReferences = 0;
if( beh.gcGetFlag )
engine->scriptFunctions[beh.gcGetFlag]->Release();
beh.gcGetFlag = 0;
if( beh.gcGetRefCount )
engine->scriptFunctions[beh.gcGetRefCount]->Release();
beh.gcGetRefCount = 0;
if( beh.gcReleaseAllReferences )
engine->scriptFunctions[beh.gcReleaseAllReferences]->Release();
beh.gcReleaseAllReferences = 0;
if( beh.gcSetFlag )
engine->scriptFunctions[beh.gcSetFlag]->Release();
beh.gcSetFlag = 0;
if ( beh.getWeakRefFlag )
engine->scriptFunctions[beh.getWeakRefFlag]->Release();
beh.getWeakRefFlag = 0;
}
// internal
void asCObjectType::EnumReferences(asIScriptEngine *)
{
for( asUINT a = 0; a < beh.factories.GetLength(); a++ )
if( engine->scriptFunctions[beh.factories[a]] )
engine->GCEnumCallback(engine->scriptFunctions[beh.factories[a]]);
for( asUINT b = 0; b < beh.constructors.GetLength(); b++ )
if( engine->scriptFunctions[beh.constructors[b]] )
engine->GCEnumCallback(engine->scriptFunctions[beh.constructors[b]]);
if( beh.templateCallback )
engine->GCEnumCallback(engine->scriptFunctions[beh.templateCallback]);
if( beh.listFactory )
engine->GCEnumCallback(engine->scriptFunctions[beh.listFactory]);
if( beh.destruct )
engine->GCEnumCallback(engine->scriptFunctions[beh.destruct]);
if( beh.addref )
engine->GCEnumCallback(engine->scriptFunctions[beh.addref]);
if( beh.release )
engine->GCEnumCallback(engine->scriptFunctions[beh.release]);
if( beh.copy )
engine->GCEnumCallback(engine->scriptFunctions[beh.copy]);
if( beh.gcEnumReferences )
engine->GCEnumCallback(engine->scriptFunctions[beh.gcEnumReferences]);
if( beh.gcGetFlag )
engine->GCEnumCallback(engine->scriptFunctions[beh.gcGetFlag]);
if( beh.gcGetRefCount )
engine->GCEnumCallback(engine->scriptFunctions[beh.gcGetRefCount]);
if( beh.gcReleaseAllReferences )
engine->GCEnumCallback(engine->scriptFunctions[beh.gcReleaseAllReferences]);
if( beh.gcSetFlag )
engine->GCEnumCallback(engine->scriptFunctions[beh.gcSetFlag]);
for( asUINT e = 1; e < beh.operators.GetLength(); e += 2 )
if( engine->scriptFunctions[beh.operators[e]] )
engine->GCEnumCallback(engine->scriptFunctions[beh.operators[e]]);
for( asUINT c = 0; c < methods.GetLength(); c++ )
if( engine->scriptFunctions[methods[c]] )
engine->GCEnumCallback(engine->scriptFunctions[methods[c]]);
for( asUINT d = 0; d < virtualFunctionTable.GetLength(); d++ )
if( virtualFunctionTable[d] )
engine->GCEnumCallback(virtualFunctionTable[d]);
for( asUINT p = 0; p < properties.GetLength(); p++ )
{
asCObjectType *type = properties[p]->type.GetObjectType();
if( type )
engine->GCEnumCallback(type);
}
for( asUINT t = 0; t < templateSubTypes.GetLength(); t++ )
if( templateSubTypes[t].GetObjectType() )
engine->GCEnumCallback(templateSubTypes[t].GetObjectType());
if( beh.getWeakRefFlag )
engine->GCEnumCallback(engine->scriptFunctions[beh.getWeakRefFlag]);
if( derivedFrom )
engine->GCEnumCallback(derivedFrom);
}
END_AS_NAMESPACE
| mit |
RongbinZhuang/simpleOS | Alpha/book/ffmpeg/ffdecoder/InitShell.c | 4 | 5209 | /*
* =====================================================================================
*
* Filename: InitShell.c
*
* Description:
*
* Version: 1.0
* Created: 03/18/2012 08:14:56 PM
* Revision: none
* Compiler: gcc
*
* Author: DAI ZHENGHUA (), djx.zhenghua@gmail.com
* Company:
*
* =====================================================================================
*/
#include <../Library/UefiShellLib/UefiShellLib.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <MainData.h>
#include <unistd.h>
extern FILE_HANDLE_FUNCTION_MAP FileFunctionMap;
EFI_STATUS
EFIAPI
ShellLibConstructorWorker2 (
void* aEfiShellProtocol,
void* aEfiShellParametersProtocol,
void* aEfiShellEnvironment2,
void* aEfiShellInterface
)
{
#if 0
EFI_STATUS Status;
gEfiShellProtocol = gEfiShellProtocol;
gEfiShellParametersProtocol = gEfiShellParametersProtocol;
mEfiShellEnvironment2 = mEfiShellEnvironment2;
mEfiShellInterface = mEfiShellInterface;
#endif
//
// UEFI 2.0 shell interfaces (used preferentially)
//
//
// only success getting 2 of either the old or new, but no 1/2 and 1/2
//
//if ((mEfiShellEnvironment2 != NULL && mEfiShellInterface != NULL) ||
// (gEfiShellProtocol != NULL && gEfiShellParametersProtocol != NULL) )
{
// if (0 && (gEfiShellProtocol != NULL)) {
if(0){
FileFunctionMap.GetFileInfo = gEfiShellProtocol->GetFileInfo;
FileFunctionMap.SetFileInfo = gEfiShellProtocol->SetFileInfo;
FileFunctionMap.ReadFile = gEfiShellProtocol->ReadFile;
FileFunctionMap.WriteFile = gEfiShellProtocol->WriteFile;
FileFunctionMap.CloseFile = gEfiShellProtocol->CloseFile;
FileFunctionMap.DeleteFile = gEfiShellProtocol->DeleteFile;
FileFunctionMap.GetFilePosition = gEfiShellProtocol->GetFilePosition;
FileFunctionMap.SetFilePosition = gEfiShellProtocol->SetFilePosition;
FileFunctionMap.FlushFile = gEfiShellProtocol->FlushFile;
FileFunctionMap.GetFileSize = gEfiShellProtocol->GetFileSize;
} else {
FileFunctionMap.GetFileInfo = (EFI_SHELL_GET_FILE_INFO)FileHandleGetInfo;
FileFunctionMap.SetFileInfo = (EFI_SHELL_SET_FILE_INFO)FileHandleSetInfo;
FileFunctionMap.ReadFile = (EFI_SHELL_READ_FILE)FileHandleRead;
FileFunctionMap.WriteFile = (EFI_SHELL_WRITE_FILE)FileHandleWrite;
FileFunctionMap.CloseFile = (EFI_SHELL_CLOSE_FILE)FileHandleClose;
FileFunctionMap.DeleteFile = (EFI_SHELL_DELETE_FILE)FileHandleDelete;
FileFunctionMap.GetFilePosition = (EFI_SHELL_GET_FILE_POSITION)FileHandleGetPosition;
FileFunctionMap.SetFilePosition = (EFI_SHELL_SET_FILE_POSITION)FileHandleSetPosition;
FileFunctionMap.FlushFile = (EFI_SHELL_FLUSH_FILE)FileHandleFlush;
FileFunctionMap.GetFileSize = (EFI_SHELL_GET_FILE_SIZE)FileHandleGetSize;
}
return (EFI_SUCCESS);
}
return (EFI_NOT_FOUND);
}
INTN
EFIAPI
DriverInitMain (
IN UINTN Argc,
IN CHAR16 **Argv
)
{
struct __filedes *mfd;
//char **nArgv;
INTN ExitVal;
int i;
ExitVal = (INTN)RETURN_SUCCESS;
gMD = AllocateZeroPool(sizeof(struct __MainData));
if( gMD == NULL ) {
ExitVal = (INTN)RETURN_OUT_OF_RESOURCES;
}
else {
/* Initialize data */
extern int __sse2_available;
__sse2_available = 0;
_fltused = 1;
errno = 0;
EFIerrno = 0;
gMD->ClocksPerSecond = 1;
gMD->AppStartTime = (clock_t)((UINT32)time(NULL));
// Initialize file descriptors
mfd = gMD->fdarray;
for(i = 0; i < (FOPEN_MAX); ++i) {
mfd[i].MyFD = (UINT16)i;
}
i = open("stdin:", O_RDONLY, 0444);
if(i == 0) {
i = open("stdout:", O_WRONLY, 0222);
if(i == 1) {
i = open("stderr:", O_WRONLY, 0222);
}
}
if(i != 2) {
Print(L"ERROR Initializing Standard IO: %a.\n %r\n",
strerror(errno), EFIerrno);
}
/* Create mbcs versions of the Argv strings. */
#if 0
nArgv = ArgvConvert(Argc, Argv);
if(nArgv == NULL) {
ExitVal = (INTN)RETURN_INVALID_PARAMETER;
}
else {
if( setjmp(gMD->MainExit) == 0) {
ExitVal = (INTN)main( (int)Argc, gMD->NArgV);
exitCleanup(ExitVal);
}
/* You reach here if:
* normal return from main()
* call to _Exit(), either directly or through exit().
*/
ExitVal = (INTN)gMD->ExitValue;
}
#endif
#if 0
if( ExitVal == EXIT_FAILURE) {
ExitVal = RETURN_ABORTED;
}
/* Close any open files */
for(i = OPEN_MAX - 1; i >= 0; --i) {
(void)close(i); // Close properly handles closing a closed file.
}
/* Free the global MainData structure */
if(gMD != NULL) {
if(gMD->NCmdLine != NULL) {
FreePool( gMD->NCmdLine );
}
FreePool( gMD );
}
#endif
}
return ExitVal;
}
| mit |
tum-i22/obfuscation-benchmarks | tigress-generated-programs/empty-Seed2-RandomFuns-Type_long-ControlStructures_3-BB2-ForBound_constant-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c | 4 | 3665 | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 4242424242UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
char copy11 ;
char copy12 ;
unsigned int copy13 ;
{
state[0UL] = input[0UL] ^ 700325083UL;
if ((state[0UL] >> 4UL) & 1UL) {
if ((state[0UL] >> 2UL) & 1UL) {
copy11 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 7);
*((char *)(& state[0UL]) + 7) = copy11;
copy11 = *((char *)(& state[0UL]) + 5);
*((char *)(& state[0UL]) + 5) = *((char *)(& state[0UL]) + 2);
*((char *)(& state[0UL]) + 2) = copy11;
state[0UL] <<= ((state[0UL] >> 1UL) & 7UL) | 1UL;
} else {
state[0UL] <<= ((state[0UL] >> 1UL) & 7UL) | 1UL;
copy12 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 5);
*((char *)(& state[0UL]) + 5) = copy12;
}
} else {
state[0UL] >>= ((state[0UL] >> 2UL) & 7UL) | 1UL;
copy13 = *((unsigned int *)(& state[0UL]) + 0);
*((unsigned int *)(& state[0UL]) + 0) = *((unsigned int *)(& state[0UL]) + 1);
*((unsigned int *)(& state[0UL]) + 1) = copy13;
copy13 = *((unsigned int *)(& state[0UL]) + 1);
*((unsigned int *)(& state[0UL]) + 1) = *((unsigned int *)(& state[0UL]) + 0);
*((unsigned int *)(& state[0UL]) + 0) = copy13;
}
output[0UL] = (state[0UL] & 387166272UL) & 913307615UL;
}
}
| mit |
guileschool/BEAGLEBONE-tutorials | BBB-firmware/u-boot-v2015.10-rc2/arch/x86/lib/bios_interrupts.c | 5 | 5069 | /*
* From Coreboot
*
* Copyright (C) 2001 Ronald G. Minnich
* Copyright (C) 2005 Nick.Barker9@btinternet.com
* Copyright (C) 2007-2009 coresystems GmbH
*
* SPDX-License-Identifier: GPL-2.0
*/
#include <common.h>
#include <asm/pci.h>
#include "bios_emul.h"
/* errors go in AH. Just set these up so that word assigns will work */
enum {
PCIBIOS_SUCCESSFUL = 0x0000,
PCIBIOS_UNSUPPORTED = 0x8100,
PCIBIOS_BADVENDOR = 0x8300,
PCIBIOS_NODEV = 0x8600,
PCIBIOS_BADREG = 0x8700
};
int int10_handler(void)
{
static u8 cursor_row, cursor_col;
int res = 0;
switch ((M.x86.R_EAX & 0xff00) >> 8) {
case 0x01: /* Set cursor shape */
res = 1;
break;
case 0x02: /* Set cursor position */
if (cursor_row != ((M.x86.R_EDX >> 8) & 0xff) ||
cursor_col >= (M.x86.R_EDX & 0xff)) {
debug("\n");
}
cursor_row = (M.x86.R_EDX >> 8) & 0xff;
cursor_col = M.x86.R_EDX & 0xff;
res = 1;
break;
case 0x03: /* Get cursor position */
M.x86.R_EAX &= 0x00ff;
M.x86.R_ECX = 0x0607;
M.x86.R_EDX = (cursor_row << 8) | cursor_col;
res = 1;
break;
case 0x06: /* Scroll up */
debug("\n");
res = 1;
break;
case 0x08: /* Get Character and Mode at Cursor Position */
M.x86.R_EAX = 0x0f00 | 'A'; /* White on black 'A' */
res = 1;
break;
case 0x09: /* Write Character and attribute */
case 0x0e: /* Write Character */
debug("%c", M.x86.R_EAX & 0xff);
res = 1;
break;
case 0x0f: /* Get video mode */
M.x86.R_EAX = 0x5002; /*80 x 25 */
M.x86.R_EBX &= 0x00ff;
res = 1;
break;
default:
printf("Unknown INT10 function %04x\n", M.x86.R_EAX & 0xffff);
break;
}
return res;
}
int int12_handler(void)
{
M.x86.R_EAX = 64 * 1024;
return 1;
}
int int16_handler(void)
{
int res = 0;
switch ((M.x86.R_EAX & 0xff00) >> 8) {
case 0x00: /* Check for Keystroke */
M.x86.R_EAX = 0x6120; /* Space Bar, Space */
res = 1;
break;
case 0x01: /* Check for Keystroke */
M.x86.R_EFLG |= 1 << 6; /* Zero Flag set (no key available) */
res = 1;
break;
default:
printf("Unknown INT16 function %04x\n", M.x86.R_EAX & 0xffff);
break;
}
return res;
}
#define PCI_CONFIG_SPACE_TYPE1 (1 << 0)
#define PCI_SPECIAL_CYCLE_TYPE1 (1 << 4)
int int1a_handler(void)
{
unsigned short func = (unsigned short)M.x86.R_EAX;
int retval = 1;
unsigned short devid, vendorid, devfn;
/* Use short to get rid of gabage in upper half of 32-bit register */
short devindex;
unsigned char bus;
pci_dev_t dev;
u32 dword;
u16 word;
u8 byte, reg;
switch (func) {
case 0xb101: /* PCIBIOS Check */
M.x86.R_EDX = 0x20494350; /* ' ICP' */
M.x86.R_EAX &= 0xffff0000; /* Clear AH / AL */
M.x86.R_EAX |= PCI_CONFIG_SPACE_TYPE1 |
PCI_SPECIAL_CYCLE_TYPE1;
/*
* last bus in the system. Hard code to 255 for now.
* dev_enumerate() does not seem to tell us (publically)
*/
M.x86.R_ECX = 0xff;
M.x86.R_EDI = 0x00000000; /* protected mode entry */
retval = 1;
break;
case 0xb102: /* Find Device */
devid = M.x86.R_ECX;
vendorid = M.x86.R_EDX;
devindex = M.x86.R_ESI;
dev = pci_find_device(vendorid, devid, devindex);
if (dev != -1) {
unsigned short busdevfn;
M.x86.R_EAX &= 0xffff00ff; /* Clear AH */
M.x86.R_EAX |= PCIBIOS_SUCCESSFUL;
/*
* busnum is an unsigned char;
* devfn is an int, so we mask it off.
*/
busdevfn = (PCI_BUS(dev) << 8) | PCI_DEV(dev) << 3 |
PCI_FUNC(dev);
debug("0x%x: return 0x%x\n", func, busdevfn);
M.x86.R_EBX = busdevfn;
retval = 1;
} else {
M.x86.R_EAX &= 0xffff00ff; /* Clear AH */
M.x86.R_EAX |= PCIBIOS_NODEV;
retval = 0;
}
break;
case 0xb10a: /* Read Config Dword */
case 0xb109: /* Read Config Word */
case 0xb108: /* Read Config Byte */
case 0xb10d: /* Write Config Dword */
case 0xb10c: /* Write Config Word */
case 0xb10b: /* Write Config Byte */
devfn = M.x86.R_EBX & 0xff;
bus = M.x86.R_EBX >> 8;
reg = M.x86.R_EDI;
dev = PCI_BDF(bus, devfn >> 3, devfn & 7);
switch (func) {
case 0xb108: /* Read Config Byte */
byte = x86_pci_read_config8(dev, reg);
M.x86.R_ECX = byte;
break;
case 0xb109: /* Read Config Word */
word = x86_pci_read_config16(dev, reg);
M.x86.R_ECX = word;
break;
case 0xb10a: /* Read Config Dword */
dword = x86_pci_read_config32(dev, reg);
M.x86.R_ECX = dword;
break;
case 0xb10b: /* Write Config Byte */
byte = M.x86.R_ECX;
x86_pci_write_config8(dev, reg, byte);
break;
case 0xb10c: /* Write Config Word */
word = M.x86.R_ECX;
x86_pci_write_config16(dev, reg, word);
break;
case 0xb10d: /* Write Config Dword */
dword = M.x86.R_ECX;
x86_pci_write_config32(dev, reg, dword);
break;
}
#ifdef CONFIG_REALMODE_DEBUG
debug("0x%x: bus %d devfn 0x%x reg 0x%x val 0x%x\n", func,
bus, devfn, reg, M.x86.R_ECX);
#endif
M.x86.R_EAX &= 0xffff00ff; /* Clear AH */
M.x86.R_EAX |= PCIBIOS_SUCCESSFUL;
retval = 1;
break;
default:
printf("UNSUPPORTED PCIBIOS FUNCTION 0x%x\n", func);
M.x86.R_EAX &= 0xffff00ff; /* Clear AH */
M.x86.R_EAX |= PCIBIOS_UNSUPPORTED;
retval = 0;
break;
}
return retval;
}
| mit |
mrcatacroquer/Bridge | WinQuake/snd_win.c | 5 | 15285 | /*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "quakedef.h"
#include "winquake.h"
#define iDirectSoundCreate(a,b,c) pDirectSoundCreate(a,b,c)
HRESULT (WINAPI *pDirectSoundCreate)(GUID FAR *lpGUID, LPDIRECTSOUND FAR *lplpDS, IUnknown FAR *pUnkOuter);
// 64K is > 1 second at 16-bit, 22050 Hz
#define WAV_BUFFERS 64
#define WAV_MASK 0x3F
#define WAV_BUFFER_SIZE 0x0400
#define SECONDARY_BUFFER_SIZE 0x10000
typedef enum {SIS_SUCCESS, SIS_FAILURE, SIS_NOTAVAIL} sndinitstat;
static qboolean wavonly;
static qboolean dsound_init;
static qboolean wav_init;
static qboolean snd_firsttime = true, snd_isdirect, snd_iswave;
static qboolean primary_format_set;
static int sample16;
static int snd_sent, snd_completed;
/*
* Global variables. Must be visible to window-procedure function
* so it can unlock and free the data block after it has been played.
*/
HANDLE hData;
HPSTR lpData, lpData2;
HGLOBAL hWaveHdr;
LPWAVEHDR lpWaveHdr;
HWAVEOUT hWaveOut;
WAVEOUTCAPS wavecaps;
DWORD gSndBufSize;
MMTIME mmstarttime;
LPDIRECTSOUND pDS;
LPDIRECTSOUNDBUFFER pDSBuf, pDSPBuf;
HINSTANCE hInstDS;
qboolean SNDDMA_InitDirect (void);
qboolean SNDDMA_InitWav (void);
/*
==================
S_BlockSound
==================
*/
void S_BlockSound (void)
{
// DirectSound takes care of blocking itself
if (snd_iswave)
{
snd_blocked++;
if (snd_blocked == 1)
{
waveOutReset (hWaveOut);
}
}
}
/*
==================
S_UnblockSound
==================
*/
void S_UnblockSound (void)
{
// DirectSound takes care of blocking itself
if (snd_iswave)
{
snd_blocked--;
}
}
/*
==================
FreeSound
==================
*/
void FreeSound (void)
{
int i;
if (pDSBuf)
{
pDSBuf->lpVtbl->Stop(pDSBuf);
pDSBuf->lpVtbl->Release(pDSBuf);
}
// only release primary buffer if it's not also the mixing buffer we just released
if (pDSPBuf && (pDSBuf != pDSPBuf))
{
pDSPBuf->lpVtbl->Release(pDSPBuf);
}
if (pDS)
{
pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_NORMAL);
pDS->lpVtbl->Release(pDS);
}
if (hWaveOut)
{
waveOutReset (hWaveOut);
if (lpWaveHdr)
{
for (i=0 ; i< WAV_BUFFERS ; i++)
waveOutUnprepareHeader (hWaveOut, lpWaveHdr+i, sizeof(WAVEHDR));
}
waveOutClose (hWaveOut);
if (hWaveHdr)
{
GlobalUnlock(hWaveHdr);
GlobalFree(hWaveHdr);
}
if (hData)
{
GlobalUnlock(hData);
GlobalFree(hData);
}
}
pDS = NULL;
pDSBuf = NULL;
pDSPBuf = NULL;
hWaveOut = 0;
hData = 0;
hWaveHdr = 0;
lpData = NULL;
lpWaveHdr = NULL;
dsound_init = false;
wav_init = false;
}
/*
==================
SNDDMA_InitDirect
Direct-Sound support
==================
*/
sndinitstat SNDDMA_InitDirect (void)
{
DSBUFFERDESC dsbuf;
DSBCAPS dsbcaps;
DWORD dwSize, dwWrite;
DSCAPS dscaps;
WAVEFORMATEX format, pformat;
HRESULT hresult;
int reps;
memset ((void *)&sn, 0, sizeof (sn));
shm = &sn;
shm->channels = 2;
shm->samplebits = 16;
shm->speed = 11025;
memset (&format, 0, sizeof(format));
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = shm->channels;
format.wBitsPerSample = shm->samplebits;
format.nSamplesPerSec = shm->speed;
format.nBlockAlign = format.nChannels
*format.wBitsPerSample / 8;
format.cbSize = 0;
format.nAvgBytesPerSec = format.nSamplesPerSec
*format.nBlockAlign;
if (!hInstDS)
{
hInstDS = LoadLibrary("dsound.dll");
if (hInstDS == NULL)
{
Con_SafePrintf ("Couldn't load dsound.dll\n");
return SIS_FAILURE;
}
pDirectSoundCreate = (void *)GetProcAddress(hInstDS,"DirectSoundCreate");
if (!pDirectSoundCreate)
{
Con_SafePrintf ("Couldn't get DS proc addr\n");
return SIS_FAILURE;
}
}
while ((hresult = iDirectSoundCreate(NULL, &pDS, NULL)) != DS_OK)
{
if (hresult != DSERR_ALLOCATED)
{
Con_SafePrintf ("DirectSound create failed\n");
return SIS_FAILURE;
}
if (MessageBox (NULL,
"The sound hardware is in use by another app.\n\n"
"Select Retry to try to start sound again or Cancel to run Quake with no sound.",
"Sound not available",
MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY)
{
Con_SafePrintf ("DirectSoundCreate failure\n"
" hardware already in use\n");
return SIS_NOTAVAIL;
}
}
dscaps.dwSize = sizeof(dscaps);
if (DS_OK != pDS->lpVtbl->GetCaps (pDS, &dscaps))
{
Con_SafePrintf ("Couldn't get DS caps\n");
}
if (dscaps.dwFlags & DSCAPS_EMULDRIVER)
{
Con_SafePrintf ("No DirectSound driver installed\n");
FreeSound ();
return SIS_FAILURE;
}
if (DS_OK != pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_EXCLUSIVE))
{
Con_SafePrintf ("Set coop level failed\n");
FreeSound ();
return SIS_FAILURE;
}
// get access to the primary buffer, if possible, so we can set the
// sound hardware format
memset (&dsbuf, 0, sizeof(dsbuf));
dsbuf.dwSize = sizeof(DSBUFFERDESC);
dsbuf.dwFlags = DSBCAPS_PRIMARYBUFFER;
dsbuf.dwBufferBytes = 0;
dsbuf.lpwfxFormat = NULL;
memset(&dsbcaps, 0, sizeof(dsbcaps));
dsbcaps.dwSize = sizeof(dsbcaps);
primary_format_set = false;
if (!COM_CheckParm ("-snoforceformat"))
{
if (DS_OK == pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSPBuf, NULL))
{
pformat = format;
if (DS_OK != pDSPBuf->lpVtbl->SetFormat (pDSPBuf, &pformat))
{
if (snd_firsttime)
Con_SafePrintf ("Set primary sound buffer format: no\n");
}
else
{
if (snd_firsttime)
Con_SafePrintf ("Set primary sound buffer format: yes\n");
primary_format_set = true;
}
}
}
if (!primary_format_set || !COM_CheckParm ("-primarysound"))
{
// create the secondary buffer we'll actually work with
memset (&dsbuf, 0, sizeof(dsbuf));
dsbuf.dwSize = sizeof(DSBUFFERDESC);
dsbuf.dwFlags = DSBCAPS_CTRLFREQUENCY | DSBCAPS_LOCSOFTWARE;
dsbuf.dwBufferBytes = SECONDARY_BUFFER_SIZE;
dsbuf.lpwfxFormat = &format;
memset(&dsbcaps, 0, sizeof(dsbcaps));
dsbcaps.dwSize = sizeof(dsbcaps);
if (DS_OK != pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSBuf, NULL))
{
Con_SafePrintf ("DS:CreateSoundBuffer Failed");
FreeSound ();
return SIS_FAILURE;
}
shm->channels = format.nChannels;
shm->samplebits = format.wBitsPerSample;
shm->speed = format.nSamplesPerSec;
if (DS_OK != pDSBuf->lpVtbl->GetCaps (pDSBuf, &dsbcaps))
{
Con_SafePrintf ("DS:GetCaps failed\n");
FreeSound ();
return SIS_FAILURE;
}
if (snd_firsttime)
Con_SafePrintf ("Using secondary sound buffer\n");
}
else
{
if (DS_OK != pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_WRITEPRIMARY))
{
Con_SafePrintf ("Set coop level failed\n");
FreeSound ();
return SIS_FAILURE;
}
if (DS_OK != pDSPBuf->lpVtbl->GetCaps (pDSPBuf, &dsbcaps))
{
Con_Printf ("DS:GetCaps failed\n");
return SIS_FAILURE;
}
pDSBuf = pDSPBuf;
Con_SafePrintf ("Using primary sound buffer\n");
}
// Make sure mixer is active
pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
if (snd_firsttime)
Con_SafePrintf(" %d channel(s)\n"
" %d bits/sample\n"
" %d bytes/sec\n",
shm->channels, shm->samplebits, shm->speed);
gSndBufSize = dsbcaps.dwBufferBytes;
// initialize the buffer
reps = 0;
while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &lpData, &dwSize, NULL, NULL, 0)) != DS_OK)
{
if (hresult != DSERR_BUFFERLOST)
{
Con_SafePrintf ("SNDDMA_InitDirect: DS::Lock Sound Buffer Failed\n");
FreeSound ();
return SIS_FAILURE;
}
if (++reps > 10000)
{
Con_SafePrintf ("SNDDMA_InitDirect: DS: couldn't restore buffer\n");
FreeSound ();
return SIS_FAILURE;
}
}
memset(lpData, 0, dwSize);
// lpData[4] = lpData[5] = 0x7f; // force a pop for debugging
pDSBuf->lpVtbl->Unlock(pDSBuf, lpData, dwSize, NULL, 0);
/* we don't want anyone to access the buffer directly w/o locking it first. */
lpData = NULL;
pDSBuf->lpVtbl->Stop(pDSBuf);
pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &mmstarttime.u.sample, &dwWrite);
pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
shm->soundalive = true;
shm->splitbuffer = false;
shm->samples = gSndBufSize/(shm->samplebits/8);
shm->samplepos = 0;
shm->submission_chunk = 1;
shm->buffer = (unsigned char *) lpData;
sample16 = (shm->samplebits/8) - 1;
dsound_init = true;
return SIS_SUCCESS;
}
/*
==================
SNDDM_InitWav
Crappy windows multimedia base
==================
*/
qboolean SNDDMA_InitWav (void)
{
WAVEFORMATEX format;
int i;
HRESULT hr;
snd_sent = 0;
snd_completed = 0;
shm = &sn;
shm->channels = 2;
shm->samplebits = 16;
shm->speed = 11025;
memset (&format, 0, sizeof(format));
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = shm->channels;
format.wBitsPerSample = shm->samplebits;
format.nSamplesPerSec = shm->speed;
format.nBlockAlign = format.nChannels
*format.wBitsPerSample / 8;
format.cbSize = 0;
format.nAvgBytesPerSec = format.nSamplesPerSec
*format.nBlockAlign;
/* Open a waveform device for output using window callback. */
while ((hr = waveOutOpen((LPHWAVEOUT)&hWaveOut, WAVE_MAPPER,
&format,
0, 0L, CALLBACK_NULL)) != MMSYSERR_NOERROR)
{
if (hr != MMSYSERR_ALLOCATED)
{
Con_SafePrintf ("waveOutOpen failed\n");
return false;
}
if (MessageBox (NULL,
"The sound hardware is in use by another app.\n\n"
"Select Retry to try to start sound again or Cancel to run Quake with no sound.",
"Sound not available",
MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY)
{
Con_SafePrintf ("waveOutOpen failure;\n"
" hardware already in use\n");
return false;
}
}
/*
* Allocate and lock memory for the waveform data. The memory
* for waveform data must be globally allocated with
* GMEM_MOVEABLE and GMEM_SHARE flags.
*/
gSndBufSize = WAV_BUFFERS*WAV_BUFFER_SIZE;
hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, gSndBufSize);
if (!hData)
{
Con_SafePrintf ("Sound: Out of memory.\n");
FreeSound ();
return false;
}
lpData = GlobalLock(hData);
if (!lpData)
{
Con_SafePrintf ("Sound: Failed to lock.\n");
FreeSound ();
return false;
}
memset (lpData, 0, gSndBufSize);
/*
* Allocate and lock memory for the header. This memory must
* also be globally allocated with GMEM_MOVEABLE and
* GMEM_SHARE flags.
*/
hWaveHdr = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE,
(DWORD) sizeof(WAVEHDR) * WAV_BUFFERS);
if (hWaveHdr == NULL)
{
Con_SafePrintf ("Sound: Failed to Alloc header.\n");
FreeSound ();
return false;
}
lpWaveHdr = (LPWAVEHDR) GlobalLock(hWaveHdr);
if (lpWaveHdr == NULL)
{
Con_SafePrintf ("Sound: Failed to lock header.\n");
FreeSound ();
return false;
}
memset (lpWaveHdr, 0, sizeof(WAVEHDR) * WAV_BUFFERS);
/* After allocation, set up and prepare headers. */
for (i=0 ; i<WAV_BUFFERS ; i++)
{
lpWaveHdr[i].dwBufferLength = WAV_BUFFER_SIZE;
lpWaveHdr[i].lpData = lpData + i*WAV_BUFFER_SIZE;
if (waveOutPrepareHeader(hWaveOut, lpWaveHdr+i, sizeof(WAVEHDR)) !=
MMSYSERR_NOERROR)
{
Con_SafePrintf ("Sound: failed to prepare wave headers\n");
FreeSound ();
return false;
}
}
shm->soundalive = true;
shm->splitbuffer = false;
shm->samples = gSndBufSize/(shm->samplebits/8);
shm->samplepos = 0;
shm->submission_chunk = 1;
shm->buffer = (unsigned char *) lpData;
sample16 = (shm->samplebits/8) - 1;
wav_init = true;
return true;
}
/*
==================
SNDDMA_Init
Try to find a sound device to mix for.
Returns false if nothing is found.
==================
*/
int SNDDMA_Init(void)
{
sndinitstat stat;
if (COM_CheckParm ("-wavonly"))
wavonly = true;
dsound_init = wav_init = 0;
stat = SIS_FAILURE; // assume DirectSound won't initialize
/* Init DirectSound */
if (!wavonly)
{
if (snd_firsttime || snd_isdirect)
{
stat = SNDDMA_InitDirect ();;
if (stat == SIS_SUCCESS)
{
snd_isdirect = true;
if (snd_firsttime)
Con_SafePrintf ("DirectSound initialized\n");
}
else
{
snd_isdirect = false;
Con_SafePrintf ("DirectSound failed to init\n");
}
}
}
// if DirectSound didn't succeed in initializing, try to initialize
// waveOut sound, unless DirectSound failed because the hardware is
// already allocated (in which case the user has already chosen not
// to have sound)
if (!dsound_init && (stat != SIS_NOTAVAIL))
{
if (snd_firsttime || snd_iswave)
{
snd_iswave = SNDDMA_InitWav ();
if (snd_iswave)
{
if (snd_firsttime)
Con_SafePrintf ("Wave sound initialized\n");
}
else
{
Con_SafePrintf ("Wave sound failed to init\n");
}
}
}
snd_firsttime = false;
if (!dsound_init && !wav_init)
{
if (snd_firsttime)
Con_SafePrintf ("No sound device initialized\n");
return 0;
}
return 1;
}
/*
==============
SNDDMA_GetDMAPos
return the current sample position (in mono samples read)
inside the recirculating dma buffer, so the mixing code will know
how many sample are required to fill it up.
===============
*/
int SNDDMA_GetDMAPos(void)
{
MMTIME mmtime;
int s;
DWORD dwWrite;
if (dsound_init)
{
mmtime.wType = TIME_SAMPLES;
pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &mmtime.u.sample, &dwWrite);
s = mmtime.u.sample - mmstarttime.u.sample;
}
else if (wav_init)
{
s = snd_sent * WAV_BUFFER_SIZE;
}
s >>= sample16;
s &= (shm->samples-1);
return s;
}
/*
==============
SNDDMA_Submit
Send sound to device if buffer isn't really the dma buffer
===============
*/
void SNDDMA_Submit(void)
{
LPWAVEHDR h;
int wResult;
if (!wav_init)
return;
//
// find which sound blocks have completed
//
while (1)
{
if ( snd_completed == snd_sent )
{
Con_DPrintf ("Sound overrun\n");
break;
}
if ( ! (lpWaveHdr[ snd_completed & WAV_MASK].dwFlags & WHDR_DONE) )
{
break;
}
snd_completed++; // this buffer has been played
}
//
// submit two new sound blocks
//
while (((snd_sent - snd_completed) >> sample16) < 4)
{
h = lpWaveHdr + ( snd_sent&WAV_MASK );
snd_sent++;
/*
* Now the data block can be sent to the output device. The
* waveOutWrite function returns immediately and waveform
* data is sent to the output device in the background.
*/
wResult = waveOutWrite(hWaveOut, h, sizeof(WAVEHDR));
if (wResult != MMSYSERR_NOERROR)
{
Con_SafePrintf ("Failed to write block to device\n");
FreeSound ();
return;
}
}
}
/*
==============
SNDDMA_Shutdown
Reset the sound device for exiting
===============
*/
void SNDDMA_Shutdown(void)
{
FreeSound ();
}
| mit |
joe9/barrelfish | kernel/arch/x86/misc.c | 5 | 3240 | /** \file
* \brief Miscellaneous kernel support code.
*
* This file contains miscellaneous architecture-independent kernel support
* code that doesn't belong anywhere else.
*/
/*
* Copyright (c) 2007, 2008, 2009, 2010, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#include <kernel.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <barrelfish_kpi/cpu.h>
#include <exec.h>
#include <misc.h>
#include <dispatch.h>
#include <trace/trace.h>
#define DEFAULT_LOGLEVEL LOG_NOTE
#define DEFAULT_SUBSYSTEM_MASK (~0L)
/**
* Global kernel loglevel.
*/
int kernel_loglevel = DEFAULT_LOGLEVEL;
/**
* Default kernel subsystem message mask. Determines messages of what subsystems
* get output.
*/
int kernel_log_subsystem_mask = DEFAULT_SUBSYSTEM_MASK;
/**
* 'true' if kernel should handle and context switch on timer ticks.
* Pass the ticks parameter on the kernel command line if you
* want to change this.
*/
bool kernel_ticks_enabled = true;
/**
* The current time since kernel start in timeslices.
*/
size_t kernel_now = 0;
/**
* \brief Print a message and halt the kernel.
*
* Something irrecoverably bad happened. Print a panic message, then halt.
*/
void panic(const char *msg, ...)
{
va_list ap;
static char buf[256];
va_start(ap, msg);
vsnprintf(buf, sizeof(buf), msg, ap);
va_end(ap);
printf("kernel %d PANIC! %.*s\n", my_core_id, (int)sizeof(buf), buf);
breakpoint();
halt();
}
/**
* \brief Log a kernel message.
*
* Logs printf()-style message 'msg', having loglevel 'level' to the default
* kernel console(s). Additional arguments are like printf(). Whether the
* message is put out depends on the current kernel log level.
*
* \param level Loglevel of message.
* \param msg The message (printf() format string)
*/
void printk(int level, const char *msg, ...)
{
if(kernel_loglevel >= level) {
va_list ap;
static char buf[256];
va_start(ap, msg);
vsnprintf(buf, sizeof(buf), msg, ap);
va_end(ap);
printf("kernel %d: %.*s", my_core_id, (int)sizeof(buf), buf);
}
}
/**
* Helper function used in the implementation of assert()
*/
#ifdef CONFIG_OLDC
void __assert(const char *exp, const char *file, const char *func, int line)
#else /* CONFIG_NEWLIB */
void __assert_func(const char *file, int line, const char *func, const char *exp)
#endif
{
panic("kernel assertion \"%s\" failed at %s:%d", exp, file, line);
}
void
wait_cycles(uint64_t duration)
{
uint64_t last, elapsed;
printk(LOG_NOTE, "Waiting %" PRIu64 " cycles...\n", duration);
last = arch_get_cycle_count();
elapsed = 0;
while (elapsed < duration) {
uint64_t now = arch_get_cycle_count();
elapsed += (now - last);
last = now;
}
}
/**
* Kernel trace buffer
*/
lvaddr_t kernel_trace_buf = 0;
struct trace_application kernel_trace_boot_applications[TRACE_MAX_BOOT_APPLICATIONS];
int kernel_trace_num_boot_applications = 0;
| mit |
bitcoin/bitcoin | src/test/util_tests.cpp | 6 | 72098 | // Copyright (c) 2011-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/system.h>
#include <clientversion.h>
#include <fs.h>
#include <hash.h> // For Hash()
#include <key.h> // For CKey
#include <sync.h>
#include <test/util/setup_common.h>
#include <uint256.h>
#include <util/getuniquepath.h>
#include <util/message.h> // For MessageSign(), MessageVerify(), MESSAGE_MAGIC
#include <util/moneystr.h>
#include <util/overflow.h>
#include <util/readwritefile.h>
#include <util/spanparsing.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/time.h>
#include <util/vector.h>
#include <util/bitdeque.h>
#include <array>
#include <cmath>
#include <fstream>
#include <limits>
#include <map>
#include <optional>
#include <stdint.h>
#include <string.h>
#include <thread>
#include <univalue.h>
#include <utility>
#include <vector>
#ifndef WIN32
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#endif
#include <boost/test/unit_test.hpp>
using namespace std::literals;
static const std::string STRING_WITH_EMBEDDED_NULL_CHAR{"1"s "\0" "1"s};
/* defined in logging.cpp */
namespace BCLog {
std::string LogEscapeMessage(const std::string& str);
}
BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
namespace {
class NoCopyOrMove
{
public:
int i;
explicit NoCopyOrMove(int i) : i{i} { }
NoCopyOrMove() = delete;
NoCopyOrMove(const NoCopyOrMove&) = delete;
NoCopyOrMove(NoCopyOrMove&&) = delete;
NoCopyOrMove& operator=(const NoCopyOrMove&) = delete;
NoCopyOrMove& operator=(NoCopyOrMove&&) = delete;
operator bool() const { return i != 0; }
int get_ip1() { return i + 1; }
bool test()
{
// Check that Assume can be used within a lambda and still call methods
[&]() { Assume(get_ip1()); }();
return Assume(get_ip1() != 5);
}
};
} // namespace
BOOST_AUTO_TEST_CASE(util_check)
{
// Check that Assert can forward
const std::unique_ptr<int> p_two = Assert(std::make_unique<int>(2));
// Check that Assert works on lvalues and rvalues
const int two = *Assert(p_two);
Assert(two == 2);
Assert(true);
// Check that Assume can be used as unary expression
const bool result{Assume(two == 2)};
Assert(result);
// Check that Assert doesn't require copy/move
NoCopyOrMove x{9};
Assert(x).i += 3;
Assert(x).test();
// Check nested Asserts
BOOST_CHECK_EQUAL(Assert((Assert(x).test() ? 3 : 0)), 3);
// Check -Wdangling-gsl does not trigger when copying the int. (It would
// trigger on "const int&")
const int nine{*Assert(std::optional<int>{9})};
BOOST_CHECK_EQUAL(9, nine);
}
BOOST_AUTO_TEST_CASE(util_criticalsection)
{
RecursiveMutex cs;
do {
LOCK(cs);
break;
BOOST_ERROR("break was swallowed!");
} while(0);
do {
TRY_LOCK(cs, lockTest);
if (lockTest) {
BOOST_CHECK(true); // Needed to suppress "Test case [...] did not check any assertions"
break;
}
BOOST_ERROR("break was swallowed!");
} while(0);
}
static const unsigned char ParseHex_expected[65] = {
0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7,
0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde,
0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12,
0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d,
0x5f
};
BOOST_AUTO_TEST_CASE(parse_hex)
{
std::vector<unsigned char> result;
std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected));
// Basic test vector
result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
// Spaces between bytes must be supported
result = ParseHex("12 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
// Leading space must be supported (used in BerkeleyEnvironment::Salvage)
result = ParseHex(" 89 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
// Embedded null is treated as end
const std::string with_embedded_null{" 11 "s
" \0 "
" 22 "s};
BOOST_CHECK_EQUAL(with_embedded_null.size(), 11);
result = ParseHex(with_embedded_null);
BOOST_CHECK(result.size() == 1 && result[0] == 0x11);
// Stop parsing at invalid value
result = ParseHex("1234 invalid 1234");
BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34);
}
BOOST_AUTO_TEST_CASE(util_HexStr)
{
BOOST_CHECK_EQUAL(
HexStr(ParseHex_expected),
"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
BOOST_CHECK_EQUAL(
HexStr(Span{ParseHex_expected}.last(0)),
"");
BOOST_CHECK_EQUAL(
HexStr(Span{ParseHex_expected}.first(0)),
"");
{
const std::vector<char> in_s{ParseHex_expected, ParseHex_expected + 5};
const Span<const uint8_t> in_u{MakeUCharSpan(in_s)};
const Span<const std::byte> in_b{MakeByteSpan(in_s)};
const std::string out_exp{"04678afdb0"};
BOOST_CHECK_EQUAL(HexStr(in_u), out_exp);
BOOST_CHECK_EQUAL(HexStr(in_s), out_exp);
BOOST_CHECK_EQUAL(HexStr(in_b), out_exp);
}
{
auto input = std::string();
for (size_t i=0; i<256; ++i) {
input.push_back(static_cast<char>(i));
}
auto hex = HexStr(input);
BOOST_TEST_REQUIRE(hex.size() == 512);
static constexpr auto hexmap = std::string_view("0123456789abcdef");
for (size_t i = 0; i < 256; ++i) {
auto upper = hexmap.find(hex[i * 2]);
auto lower = hexmap.find(hex[i * 2 + 1]);
BOOST_TEST_REQUIRE(upper != std::string_view::npos);
BOOST_TEST_REQUIRE(lower != std::string_view::npos);
BOOST_TEST_REQUIRE(i == upper*16 + lower);
}
}
}
BOOST_AUTO_TEST_CASE(span_write_bytes)
{
std::array mut_arr{uint8_t{0xaa}, uint8_t{0xbb}};
const auto mut_bytes{MakeWritableByteSpan(mut_arr)};
mut_bytes[1] = std::byte{0x11};
BOOST_CHECK_EQUAL(mut_arr.at(0), 0xaa);
BOOST_CHECK_EQUAL(mut_arr.at(1), 0x11);
}
BOOST_AUTO_TEST_CASE(util_Join)
{
// Normal version
BOOST_CHECK_EQUAL(Join(std::vector<std::string>{}, ", "), "");
BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo"}, ", "), "foo");
BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo", "bar"}, ", "), "foo, bar");
// Version with unary operator
const auto op_upper = [](const std::string& s) { return ToUpper(s); };
BOOST_CHECK_EQUAL(Join(std::list<std::string>{}, ", ", op_upper), "");
BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo"}, ", ", op_upper), "FOO");
BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo", "bar"}, ", ", op_upper), "FOO, BAR");
}
BOOST_AUTO_TEST_CASE(util_ReplaceAll)
{
const std::string original("A test \"%s\" string '%s'.");
auto test_replaceall = [&original](const std::string& search, const std::string& substitute, const std::string& expected) {
auto test = original;
ReplaceAll(test, search, substitute);
BOOST_CHECK_EQUAL(test, expected);
};
test_replaceall("", "foo", original);
test_replaceall(original, "foo", "foo");
test_replaceall("%s", "foo", "A test \"foo\" string 'foo'.");
test_replaceall("\"", "foo", "A test foo%sfoo string '%s'.");
test_replaceall("'", "foo", "A test \"%s\" string foo%sfoo.");
}
BOOST_AUTO_TEST_CASE(util_TrimString)
{
BOOST_CHECK_EQUAL(TrimString(" foo bar "), "foo bar");
BOOST_CHECK_EQUAL(TrimStringView("\t \n \n \f\n\r\t\v\tfoo \n \f\n\r\t\v\tbar\t \n \f\n\r\t\v\t\n "), "foo \n \f\n\r\t\v\tbar");
BOOST_CHECK_EQUAL(TrimString("\t \n foo \n\tbar\t \n "), "foo \n\tbar");
BOOST_CHECK_EQUAL(TrimStringView("\t \n foo \n\tbar\t \n ", "fobar"), "\t \n foo \n\tbar\t \n ");
BOOST_CHECK_EQUAL(TrimString("foo bar"), "foo bar");
BOOST_CHECK_EQUAL(TrimStringView("foo bar", "fobar"), " ");
BOOST_CHECK_EQUAL(TrimString(std::string("\0 foo \0 ", 8)), std::string("\0 foo \0", 7));
BOOST_CHECK_EQUAL(TrimStringView(std::string(" foo ", 5)), std::string("foo", 3));
BOOST_CHECK_EQUAL(TrimString(std::string("\t\t\0\0\n\n", 6)), std::string("\0\0", 2));
BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6)), std::string("\x05\x04\x03\x02\x01\x00", 6));
BOOST_CHECK_EQUAL(TrimString(std::string("\x05\x04\x03\x02\x01\x00", 6), std::string("\x05\x04\x03\x02\x01", 5)), std::string("\0", 1));
BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6), std::string("\x05\x04\x03\x02\x01\x00", 6)), "");
}
BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime)
{
BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z");
BOOST_CHECK_EQUAL(FormatISO8601DateTime(0), "1970-01-01T00:00:00Z");
}
BOOST_AUTO_TEST_CASE(util_FormatISO8601Date)
{
BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30");
}
BOOST_AUTO_TEST_CASE(util_FormatMoney)
{
BOOST_CHECK_EQUAL(FormatMoney(0), "0.00");
BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), "12345.6789");
BOOST_CHECK_EQUAL(FormatMoney(-COIN), "-1.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), "100000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), "10000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), "1000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), "100000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), "10000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), "1000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100), "100.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10), "10.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN), "1.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10), "0.10");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100), "0.01");
BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), "0.001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), "0.0001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), "0.00001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), "0.000001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), "0.0000001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), "0.00000001");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max()), "92233720368.54775807");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 1), "92233720368.54775806");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 2), "92233720368.54775805");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 3), "92233720368.54775804");
// ...
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 3), "-92233720368.54775805");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 2), "-92233720368.54775806");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 1), "-92233720368.54775807");
BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min()), "-92233720368.54775808");
}
BOOST_AUTO_TEST_CASE(util_ParseMoney)
{
BOOST_CHECK_EQUAL(ParseMoney("0.0").value(), 0);
BOOST_CHECK_EQUAL(ParseMoney(".").value(), 0);
BOOST_CHECK_EQUAL(ParseMoney("0.").value(), 0);
BOOST_CHECK_EQUAL(ParseMoney(".0").value(), 0);
BOOST_CHECK_EQUAL(ParseMoney(".6789").value(), 6789'0000);
BOOST_CHECK_EQUAL(ParseMoney("12345.").value(), COIN * 12345);
BOOST_CHECK_EQUAL(ParseMoney("12345.6789").value(), (COIN/10000)*123456789);
BOOST_CHECK_EQUAL(ParseMoney("10000000.00").value(), COIN*10000000);
BOOST_CHECK_EQUAL(ParseMoney("1000000.00").value(), COIN*1000000);
BOOST_CHECK_EQUAL(ParseMoney("100000.00").value(), COIN*100000);
BOOST_CHECK_EQUAL(ParseMoney("10000.00").value(), COIN*10000);
BOOST_CHECK_EQUAL(ParseMoney("1000.00").value(), COIN*1000);
BOOST_CHECK_EQUAL(ParseMoney("100.00").value(), COIN*100);
BOOST_CHECK_EQUAL(ParseMoney("10.00").value(), COIN*10);
BOOST_CHECK_EQUAL(ParseMoney("1.00").value(), COIN);
BOOST_CHECK_EQUAL(ParseMoney("1").value(), COIN);
BOOST_CHECK_EQUAL(ParseMoney(" 1").value(), COIN);
BOOST_CHECK_EQUAL(ParseMoney("1 ").value(), COIN);
BOOST_CHECK_EQUAL(ParseMoney(" 1 ").value(), COIN);
BOOST_CHECK_EQUAL(ParseMoney("0.1").value(), COIN/10);
BOOST_CHECK_EQUAL(ParseMoney("0.01").value(), COIN/100);
BOOST_CHECK_EQUAL(ParseMoney("0.001").value(), COIN/1000);
BOOST_CHECK_EQUAL(ParseMoney("0.0001").value(), COIN/10000);
BOOST_CHECK_EQUAL(ParseMoney("0.00001").value(), COIN/100000);
BOOST_CHECK_EQUAL(ParseMoney("0.000001").value(), COIN/1000000);
BOOST_CHECK_EQUAL(ParseMoney("0.0000001").value(), COIN/10000000);
BOOST_CHECK_EQUAL(ParseMoney("0.00000001").value(), COIN/100000000);
BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001 ").value(), COIN/100000000);
BOOST_CHECK_EQUAL(ParseMoney("0.00000001 ").value(), COIN/100000000);
BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001").value(), COIN/100000000);
// Parsing amount that cannot be represented should fail
BOOST_CHECK(!ParseMoney("100000000.00"));
BOOST_CHECK(!ParseMoney("0.000000001"));
// Parsing empty string should fail
BOOST_CHECK(!ParseMoney(""));
BOOST_CHECK(!ParseMoney(" "));
BOOST_CHECK(!ParseMoney(" "));
// Parsing two numbers should fail
BOOST_CHECK(!ParseMoney(".."));
BOOST_CHECK(!ParseMoney("0..0"));
BOOST_CHECK(!ParseMoney("1 2"));
BOOST_CHECK(!ParseMoney(" 1 2 "));
BOOST_CHECK(!ParseMoney(" 1.2 3 "));
BOOST_CHECK(!ParseMoney(" 1 2.3 "));
// Embedded whitespace should fail
BOOST_CHECK(!ParseMoney(" -1 .2 "));
BOOST_CHECK(!ParseMoney(" 1 .2 "));
BOOST_CHECK(!ParseMoney(" +1 .2 "));
// Attempted 63 bit overflow should fail
BOOST_CHECK(!ParseMoney("92233720368.54775808"));
// Parsing negative amounts must fail
BOOST_CHECK(!ParseMoney("-1"));
// Parsing strings with embedded NUL characters should fail
BOOST_CHECK(!ParseMoney("\0-1"s));
BOOST_CHECK(!ParseMoney(STRING_WITH_EMBEDDED_NULL_CHAR));
BOOST_CHECK(!ParseMoney("1\0"s));
}
BOOST_AUTO_TEST_CASE(util_IsHex)
{
BOOST_CHECK(IsHex("00"));
BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(IsHex("ff"));
BOOST_CHECK(IsHex("FF"));
BOOST_CHECK(!IsHex(""));
BOOST_CHECK(!IsHex("0"));
BOOST_CHECK(!IsHex("a"));
BOOST_CHECK(!IsHex("eleven"));
BOOST_CHECK(!IsHex("00xx00"));
BOOST_CHECK(!IsHex("0x0000"));
}
BOOST_AUTO_TEST_CASE(util_IsHexNumber)
{
BOOST_CHECK(IsHexNumber("0x0"));
BOOST_CHECK(IsHexNumber("0"));
BOOST_CHECK(IsHexNumber("0x10"));
BOOST_CHECK(IsHexNumber("10"));
BOOST_CHECK(IsHexNumber("0xff"));
BOOST_CHECK(IsHexNumber("ff"));
BOOST_CHECK(IsHexNumber("0xFfa"));
BOOST_CHECK(IsHexNumber("Ffa"));
BOOST_CHECK(IsHexNumber("0x00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(IsHexNumber("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(!IsHexNumber("")); // empty string not allowed
BOOST_CHECK(!IsHexNumber("0x")); // empty string after prefix not allowed
BOOST_CHECK(!IsHexNumber("0x0 ")); // no spaces at end,
BOOST_CHECK(!IsHexNumber(" 0x0")); // or beginning,
BOOST_CHECK(!IsHexNumber("0x 0")); // or middle,
BOOST_CHECK(!IsHexNumber(" ")); // etc.
BOOST_CHECK(!IsHexNumber("0x0ga")); // invalid character
BOOST_CHECK(!IsHexNumber("x0")); // broken prefix
BOOST_CHECK(!IsHexNumber("0x0x00")); // two prefixes not allowed
}
BOOST_AUTO_TEST_CASE(util_seed_insecure_rand)
{
SeedInsecureRand(SeedRand::ZEROS);
for (int mod=2;mod<11;mod++)
{
int mask = 1;
// Really rough binomial confidence approximation.
int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.);
//mask is 2^ceil(log2(mod))-1
while(mask<mod-1)mask=(mask<<1)+1;
int count = 0;
//How often does it get a zero from the uniform range [0,mod)?
for (int i = 0; i < 10000; i++) {
uint32_t rval;
do{
rval=InsecureRand32()&mask;
}while(rval>=(uint32_t)mod);
count += rval==0;
}
BOOST_CHECK(count<=10000/mod+err);
BOOST_CHECK(count>=10000/mod-err);
}
}
BOOST_AUTO_TEST_CASE(util_TimingResistantEqual)
{
BOOST_CHECK(TimingResistantEqual(std::string(""), std::string("")));
BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("")));
BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc")));
BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa")));
BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a")));
BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc")));
BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba")));
}
/* Test strprintf formatting directives.
* Put a string before and after to ensure sanity of element sizes on stack. */
#define B "check_prefix"
#define E "check_postfix"
BOOST_AUTO_TEST_CASE(strprintf_numbers)
{
int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */
uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */
BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E);
BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E);
BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E);
size_t st = 12345678; /* unsigned size_t test value */
ssize_t sst = -12345678; /* signed size_t test value */
BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E);
BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E);
BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E);
ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */
ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */
BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E);
BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E);
BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E);
}
#undef B
#undef E
/* Check for mingw/wine issue #3494
* Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106'
*/
BOOST_AUTO_TEST_CASE(gettime)
{
BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0);
}
BOOST_AUTO_TEST_CASE(util_time_GetTime)
{
SetMockTime(111);
// Check that mock time does not change after a sleep
for (const auto& num_sleep : {0ms, 1ms}) {
UninterruptibleSleep(num_sleep);
BOOST_CHECK_EQUAL(111, GetTime()); // Deprecated time getter
BOOST_CHECK_EQUAL(111, Now<NodeSeconds>().time_since_epoch().count());
BOOST_CHECK_EQUAL(111, TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()));
BOOST_CHECK_EQUAL(111, TicksSinceEpoch<SecondsDouble>(Now<NodeSeconds>()));
BOOST_CHECK_EQUAL(111, GetTime<std::chrono::seconds>().count());
BOOST_CHECK_EQUAL(111000, GetTime<std::chrono::milliseconds>().count());
BOOST_CHECK_EQUAL(111000, TicksSinceEpoch<std::chrono::milliseconds>(NodeClock::now()));
BOOST_CHECK_EQUAL(111000000, GetTime<std::chrono::microseconds>().count());
}
SetMockTime(0);
// Check that steady time and system time changes after a sleep
const auto steady_ms_0 = Now<SteadyMilliseconds>();
const auto steady_0 = std::chrono::steady_clock::now();
const auto ms_0 = GetTime<std::chrono::milliseconds>();
const auto us_0 = GetTime<std::chrono::microseconds>();
UninterruptibleSleep(1ms);
BOOST_CHECK(steady_ms_0 < Now<SteadyMilliseconds>());
BOOST_CHECK(steady_0 + 1ms <= std::chrono::steady_clock::now());
BOOST_CHECK(ms_0 < GetTime<std::chrono::milliseconds>());
BOOST_CHECK(us_0 < GetTime<std::chrono::microseconds>());
}
BOOST_AUTO_TEST_CASE(test_IsDigit)
{
BOOST_CHECK_EQUAL(IsDigit('0'), true);
BOOST_CHECK_EQUAL(IsDigit('1'), true);
BOOST_CHECK_EQUAL(IsDigit('8'), true);
BOOST_CHECK_EQUAL(IsDigit('9'), true);
BOOST_CHECK_EQUAL(IsDigit('0' - 1), false);
BOOST_CHECK_EQUAL(IsDigit('9' + 1), false);
BOOST_CHECK_EQUAL(IsDigit(0), false);
BOOST_CHECK_EQUAL(IsDigit(1), false);
BOOST_CHECK_EQUAL(IsDigit(8), false);
BOOST_CHECK_EQUAL(IsDigit(9), false);
}
/* Check for overflow */
template <typename T>
static void TestAddMatrixOverflow()
{
constexpr T MAXI{std::numeric_limits<T>::max()};
BOOST_CHECK(!CheckedAdd(T{1}, MAXI));
BOOST_CHECK(!CheckedAdd(MAXI, MAXI));
BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{1}, MAXI));
BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(MAXI, MAXI));
BOOST_CHECK_EQUAL(0, CheckedAdd(T{0}, T{0}).value());
BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{0}, MAXI).value());
BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{1}, MAXI - 1).value());
BOOST_CHECK_EQUAL(MAXI - 1, CheckedAdd(T{1}, MAXI - 2).value());
BOOST_CHECK_EQUAL(0, SaturatingAdd(T{0}, T{0}));
BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{0}, MAXI));
BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{1}, MAXI - 1));
BOOST_CHECK_EQUAL(MAXI - 1, SaturatingAdd(T{1}, MAXI - 2));
}
/* Check for overflow or underflow */
template <typename T>
static void TestAddMatrix()
{
TestAddMatrixOverflow<T>();
constexpr T MINI{std::numeric_limits<T>::min()};
constexpr T MAXI{std::numeric_limits<T>::max()};
BOOST_CHECK(!CheckedAdd(T{-1}, MINI));
BOOST_CHECK(!CheckedAdd(MINI, MINI));
BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{-1}, MINI));
BOOST_CHECK_EQUAL(MINI, SaturatingAdd(MINI, MINI));
BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{0}, MINI).value());
BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{-1}, MINI + 1).value());
BOOST_CHECK_EQUAL(-1, CheckedAdd(MINI, MAXI).value());
BOOST_CHECK_EQUAL(MINI + 1, CheckedAdd(T{-1}, MINI + 2).value());
BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{0}, MINI));
BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{-1}, MINI + 1));
BOOST_CHECK_EQUAL(MINI + 1, SaturatingAdd(T{-1}, MINI + 2));
BOOST_CHECK_EQUAL(-1, SaturatingAdd(MINI, MAXI));
}
BOOST_AUTO_TEST_CASE(util_overflow)
{
TestAddMatrixOverflow<unsigned>();
TestAddMatrix<signed>();
}
BOOST_AUTO_TEST_CASE(test_ParseInt32)
{
int32_t n;
// Valid values
BOOST_CHECK(ParseInt32("1234", nullptr));
BOOST_CHECK(ParseInt32("0", &n) && n == 0);
BOOST_CHECK(ParseInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal
BOOST_CHECK(ParseInt32("2147483647", &n) && n == 2147483647);
BOOST_CHECK(ParseInt32("-2147483648", &n) && n == (-2147483647 - 1)); // (-2147483647 - 1) equals INT_MIN
BOOST_CHECK(ParseInt32("-1234", &n) && n == -1234);
BOOST_CHECK(ParseInt32("00000000000000001234", &n) && n == 1234);
BOOST_CHECK(ParseInt32("-00000000000000001234", &n) && n == -1234);
BOOST_CHECK(ParseInt32("00000000000000000000", &n) && n == 0);
BOOST_CHECK(ParseInt32("-00000000000000000000", &n) && n == 0);
// Invalid values
BOOST_CHECK(!ParseInt32("", &n));
BOOST_CHECK(!ParseInt32(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseInt32("1 ", &n));
BOOST_CHECK(!ParseInt32("++1", &n));
BOOST_CHECK(!ParseInt32("+-1", &n));
BOOST_CHECK(!ParseInt32("-+1", &n));
BOOST_CHECK(!ParseInt32("--1", &n));
BOOST_CHECK(!ParseInt32("1a", &n));
BOOST_CHECK(!ParseInt32("aap", &n));
BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex
BOOST_CHECK(!ParseInt32(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseInt32("-2147483649", nullptr));
BOOST_CHECK(!ParseInt32("2147483648", nullptr));
BOOST_CHECK(!ParseInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt32("32482348723847471234", nullptr));
}
template <typename T>
static void RunToIntegralTests()
{
BOOST_CHECK(!ToIntegral<T>(STRING_WITH_EMBEDDED_NULL_CHAR));
BOOST_CHECK(!ToIntegral<T>(" 1"));
BOOST_CHECK(!ToIntegral<T>("1 "));
BOOST_CHECK(!ToIntegral<T>("1a"));
BOOST_CHECK(!ToIntegral<T>("1.1"));
BOOST_CHECK(!ToIntegral<T>("1.9"));
BOOST_CHECK(!ToIntegral<T>("+01.9"));
BOOST_CHECK(!ToIntegral<T>("-"));
BOOST_CHECK(!ToIntegral<T>("+"));
BOOST_CHECK(!ToIntegral<T>(" -1"));
BOOST_CHECK(!ToIntegral<T>("-1 "));
BOOST_CHECK(!ToIntegral<T>(" -1 "));
BOOST_CHECK(!ToIntegral<T>("+1"));
BOOST_CHECK(!ToIntegral<T>(" +1"));
BOOST_CHECK(!ToIntegral<T>(" +1 "));
BOOST_CHECK(!ToIntegral<T>("+-1"));
BOOST_CHECK(!ToIntegral<T>("-+1"));
BOOST_CHECK(!ToIntegral<T>("++1"));
BOOST_CHECK(!ToIntegral<T>("--1"));
BOOST_CHECK(!ToIntegral<T>(""));
BOOST_CHECK(!ToIntegral<T>("aap"));
BOOST_CHECK(!ToIntegral<T>("0x1"));
BOOST_CHECK(!ToIntegral<T>("-32482348723847471234"));
BOOST_CHECK(!ToIntegral<T>("32482348723847471234"));
}
BOOST_AUTO_TEST_CASE(test_ToIntegral)
{
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("1234").value(), 1'234);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("0").value(), 0);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("01234").value(), 1'234);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000001234").value(), 1'234);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000001234").value(), -1'234);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000000000").value(), 0);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000000000").value(), 0);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1234").value(), -1'234);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1").value(), -1);
RunToIntegralTests<uint64_t>();
RunToIntegralTests<int64_t>();
RunToIntegralTests<uint32_t>();
RunToIntegralTests<int32_t>();
RunToIntegralTests<uint16_t>();
RunToIntegralTests<int16_t>();
RunToIntegralTests<uint8_t>();
RunToIntegralTests<int8_t>();
BOOST_CHECK(!ToIntegral<int64_t>("-9223372036854775809"));
BOOST_CHECK_EQUAL(ToIntegral<int64_t>("-9223372036854775808").value(), -9'223'372'036'854'775'807LL - 1LL);
BOOST_CHECK_EQUAL(ToIntegral<int64_t>("9223372036854775807").value(), 9'223'372'036'854'775'807);
BOOST_CHECK(!ToIntegral<int64_t>("9223372036854775808"));
BOOST_CHECK(!ToIntegral<uint64_t>("-1"));
BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("0").value(), 0U);
BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("18446744073709551615").value(), 18'446'744'073'709'551'615ULL);
BOOST_CHECK(!ToIntegral<uint64_t>("18446744073709551616"));
BOOST_CHECK(!ToIntegral<int32_t>("-2147483649"));
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-2147483648").value(), -2'147'483'648LL);
BOOST_CHECK_EQUAL(ToIntegral<int32_t>("2147483647").value(), 2'147'483'647);
BOOST_CHECK(!ToIntegral<int32_t>("2147483648"));
BOOST_CHECK(!ToIntegral<uint32_t>("-1"));
BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("0").value(), 0U);
BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("4294967295").value(), 4'294'967'295U);
BOOST_CHECK(!ToIntegral<uint32_t>("4294967296"));
BOOST_CHECK(!ToIntegral<int16_t>("-32769"));
BOOST_CHECK_EQUAL(ToIntegral<int16_t>("-32768").value(), -32'768);
BOOST_CHECK_EQUAL(ToIntegral<int16_t>("32767").value(), 32'767);
BOOST_CHECK(!ToIntegral<int16_t>("32768"));
BOOST_CHECK(!ToIntegral<uint16_t>("-1"));
BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("0").value(), 0U);
BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("65535").value(), 65'535U);
BOOST_CHECK(!ToIntegral<uint16_t>("65536"));
BOOST_CHECK(!ToIntegral<int8_t>("-129"));
BOOST_CHECK_EQUAL(ToIntegral<int8_t>("-128").value(), -128);
BOOST_CHECK_EQUAL(ToIntegral<int8_t>("127").value(), 127);
BOOST_CHECK(!ToIntegral<int8_t>("128"));
BOOST_CHECK(!ToIntegral<uint8_t>("-1"));
BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("0").value(), 0U);
BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("255").value(), 255U);
BOOST_CHECK(!ToIntegral<uint8_t>("256"));
}
int64_t atoi64_legacy(const std::string& str)
{
return strtoll(str.c_str(), nullptr, 10);
}
BOOST_AUTO_TEST_CASE(test_LocaleIndependentAtoi)
{
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1234"), 1'234);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("01234"), 1'234);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1234"), -1'234);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" 1"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1 "), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1a"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.1"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.9"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+01.9"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1"), -1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1"), -1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1 "), -1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1 "), -1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+1"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1"), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1 "), 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+-1"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-+1"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("++1"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("--1"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(""), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("aap"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0x1"), 0);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-32482348723847471234"), -2'147'483'647 - 1);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("32482348723847471234"), 2'147'483'647);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775809"), -9'223'372'036'854'775'807LL - 1LL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775808"), -9'223'372'036'854'775'807LL - 1LL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775807"), 9'223'372'036'854'775'807);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775808"), 9'223'372'036'854'775'807);
std::map<std::string, int64_t> atoi64_test_pairs = {
{"-9223372036854775809", std::numeric_limits<int64_t>::min()},
{"-9223372036854775808", -9'223'372'036'854'775'807LL - 1LL},
{"9223372036854775807", 9'223'372'036'854'775'807},
{"9223372036854775808", std::numeric_limits<int64_t>::max()},
{"+-", 0},
{"0x1", 0},
{"ox1", 0},
{"", 0},
};
for (const auto& pair : atoi64_test_pairs) {
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>(pair.first), pair.second);
}
// Ensure legacy compatibility with previous versions of Bitcoin Core's atoi64
for (const auto& pair : atoi64_test_pairs) {
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>(pair.first), atoi64_legacy(pair.first));
}
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("-1"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("0"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551615"), 18'446'744'073'709'551'615ULL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551616"), 18'446'744'073'709'551'615ULL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483649"), -2'147'483'648LL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483648"), -2'147'483'648LL);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483647"), 2'147'483'647);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483648"), 2'147'483'647);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("-1"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("0"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967295"), 4'294'967'295U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967296"), 4'294'967'295U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32769"), -32'768);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32768"), -32'768);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32767"), 32'767);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32768"), 32'767);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("-1"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("0"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65535"), 65'535U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65536"), 65'535U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-129"), -128);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-128"), -128);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("127"), 127);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("128"), 127);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("-1"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("0"), 0U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("255"), 255U);
BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("256"), 255U);
}
BOOST_AUTO_TEST_CASE(test_ParseInt64)
{
int64_t n;
// Valid values
BOOST_CHECK(ParseInt64("1234", nullptr));
BOOST_CHECK(ParseInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal
BOOST_CHECK(ParseInt64("2147483647", &n) && n == 2147483647LL);
BOOST_CHECK(ParseInt64("-2147483648", &n) && n == -2147483648LL);
BOOST_CHECK(ParseInt64("9223372036854775807", &n) && n == (int64_t)9223372036854775807);
BOOST_CHECK(ParseInt64("-9223372036854775808", &n) && n == (int64_t)-9223372036854775807-1);
BOOST_CHECK(ParseInt64("-1234", &n) && n == -1234LL);
// Invalid values
BOOST_CHECK(!ParseInt64("", &n));
BOOST_CHECK(!ParseInt64(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseInt64("1 ", &n));
BOOST_CHECK(!ParseInt64("1a", &n));
BOOST_CHECK(!ParseInt64("aap", &n));
BOOST_CHECK(!ParseInt64("0x1", &n)); // no hex
BOOST_CHECK(!ParseInt64(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseInt64("9223372036854775808", nullptr));
BOOST_CHECK(!ParseInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt64("32482348723847471234", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt8)
{
uint8_t n;
// Valid values
BOOST_CHECK(ParseUInt8("255", nullptr));
BOOST_CHECK(ParseUInt8("0", &n) && n == 0);
BOOST_CHECK(ParseUInt8("255", &n) && n == 255);
BOOST_CHECK(ParseUInt8("0255", &n) && n == 255); // no octal
BOOST_CHECK(ParseUInt8("255", &n) && n == static_cast<uint8_t>(255));
BOOST_CHECK(ParseUInt8("+255", &n) && n == 255);
BOOST_CHECK(ParseUInt8("00000000000000000012", &n) && n == 12);
BOOST_CHECK(ParseUInt8("00000000000000000000", &n) && n == 0);
// Invalid values
BOOST_CHECK(!ParseUInt8("-00000000000000000000", &n));
BOOST_CHECK(!ParseUInt8("", &n));
BOOST_CHECK(!ParseUInt8(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt8(" -1", &n));
BOOST_CHECK(!ParseUInt8("++1", &n));
BOOST_CHECK(!ParseUInt8("+-1", &n));
BOOST_CHECK(!ParseUInt8("-+1", &n));
BOOST_CHECK(!ParseUInt8("--1", &n));
BOOST_CHECK(!ParseUInt8("-1", &n));
BOOST_CHECK(!ParseUInt8("1 ", &n));
BOOST_CHECK(!ParseUInt8("1a", &n));
BOOST_CHECK(!ParseUInt8("aap", &n));
BOOST_CHECK(!ParseUInt8("0x1", &n)); // no hex
BOOST_CHECK(!ParseUInt8(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseUInt8("-255", &n));
BOOST_CHECK(!ParseUInt8("256", &n));
BOOST_CHECK(!ParseUInt8("-123", &n));
BOOST_CHECK(!ParseUInt8("-123", nullptr));
BOOST_CHECK(!ParseUInt8("256", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt16)
{
uint16_t n;
// Valid values
BOOST_CHECK(ParseUInt16("1234", nullptr));
BOOST_CHECK(ParseUInt16("0", &n) && n == 0);
BOOST_CHECK(ParseUInt16("1234", &n) && n == 1234);
BOOST_CHECK(ParseUInt16("01234", &n) && n == 1234); // no octal
BOOST_CHECK(ParseUInt16("65535", &n) && n == static_cast<uint16_t>(65535));
BOOST_CHECK(ParseUInt16("+65535", &n) && n == 65535);
BOOST_CHECK(ParseUInt16("00000000000000000012", &n) && n == 12);
BOOST_CHECK(ParseUInt16("00000000000000000000", &n) && n == 0);
// Invalid values
BOOST_CHECK(!ParseUInt16("-00000000000000000000", &n));
BOOST_CHECK(!ParseUInt16("", &n));
BOOST_CHECK(!ParseUInt16(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt16(" -1", &n));
BOOST_CHECK(!ParseUInt16("++1", &n));
BOOST_CHECK(!ParseUInt16("+-1", &n));
BOOST_CHECK(!ParseUInt16("-+1", &n));
BOOST_CHECK(!ParseUInt16("--1", &n));
BOOST_CHECK(!ParseUInt16("-1", &n));
BOOST_CHECK(!ParseUInt16("1 ", &n));
BOOST_CHECK(!ParseUInt16("1a", &n));
BOOST_CHECK(!ParseUInt16("aap", &n));
BOOST_CHECK(!ParseUInt16("0x1", &n)); // no hex
BOOST_CHECK(!ParseUInt16(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseUInt16("-65535", &n));
BOOST_CHECK(!ParseUInt16("65536", &n));
BOOST_CHECK(!ParseUInt16("-123", &n));
BOOST_CHECK(!ParseUInt16("-123", nullptr));
BOOST_CHECK(!ParseUInt16("65536", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt32)
{
uint32_t n;
// Valid values
BOOST_CHECK(ParseUInt32("1234", nullptr));
BOOST_CHECK(ParseUInt32("0", &n) && n == 0);
BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal
BOOST_CHECK(ParseUInt32("2147483647", &n) && n == 2147483647);
BOOST_CHECK(ParseUInt32("2147483648", &n) && n == (uint32_t)2147483648);
BOOST_CHECK(ParseUInt32("4294967295", &n) && n == (uint32_t)4294967295);
BOOST_CHECK(ParseUInt32("+1234", &n) && n == 1234);
BOOST_CHECK(ParseUInt32("00000000000000001234", &n) && n == 1234);
BOOST_CHECK(ParseUInt32("00000000000000000000", &n) && n == 0);
// Invalid values
BOOST_CHECK(!ParseUInt32("-00000000000000000000", &n));
BOOST_CHECK(!ParseUInt32("", &n));
BOOST_CHECK(!ParseUInt32(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt32(" -1", &n));
BOOST_CHECK(!ParseUInt32("++1", &n));
BOOST_CHECK(!ParseUInt32("+-1", &n));
BOOST_CHECK(!ParseUInt32("-+1", &n));
BOOST_CHECK(!ParseUInt32("--1", &n));
BOOST_CHECK(!ParseUInt32("-1", &n));
BOOST_CHECK(!ParseUInt32("1 ", &n));
BOOST_CHECK(!ParseUInt32("1a", &n));
BOOST_CHECK(!ParseUInt32("aap", &n));
BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex
BOOST_CHECK(!ParseUInt32(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseUInt32("-2147483648", &n));
BOOST_CHECK(!ParseUInt32("4294967296", &n));
BOOST_CHECK(!ParseUInt32("-1234", &n));
BOOST_CHECK(!ParseUInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt32("32482348723847471234", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt64)
{
uint64_t n;
// Valid values
BOOST_CHECK(ParseUInt64("1234", nullptr));
BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal
BOOST_CHECK(ParseUInt64("2147483647", &n) && n == 2147483647LL);
BOOST_CHECK(ParseUInt64("9223372036854775807", &n) && n == 9223372036854775807ULL);
BOOST_CHECK(ParseUInt64("9223372036854775808", &n) && n == 9223372036854775808ULL);
BOOST_CHECK(ParseUInt64("18446744073709551615", &n) && n == 18446744073709551615ULL);
// Invalid values
BOOST_CHECK(!ParseUInt64("", &n));
BOOST_CHECK(!ParseUInt64(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt64(" -1", &n));
BOOST_CHECK(!ParseUInt64("1 ", &n));
BOOST_CHECK(!ParseUInt64("1a", &n));
BOOST_CHECK(!ParseUInt64("aap", &n));
BOOST_CHECK(!ParseUInt64("0x1", &n)); // no hex
BOOST_CHECK(!ParseUInt64(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
// Overflow and underflow
BOOST_CHECK(!ParseUInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseUInt64("18446744073709551616", nullptr));
BOOST_CHECK(!ParseUInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt64("-2147483648", &n));
BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n));
BOOST_CHECK(!ParseUInt64("-1234", &n));
}
BOOST_AUTO_TEST_CASE(test_FormatParagraph)
{
BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), "");
BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test");
BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), " test");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest");
BOOST_CHECK_EQUAL(FormatParagraph("testerde test", 4, 0), "testerde\ntest");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test");
// Make sure we don't indent a fully-new line following a too-long line ending
BOOST_CHECK_EQUAL(FormatParagraph("test test\nabc", 4, 4), "test\n test\nabc");
BOOST_CHECK_EQUAL(FormatParagraph("This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length until it gets here", 79), "This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length\nuntil it gets here");
// Test wrap length is exact
BOOST_CHECK_EQUAL(FormatParagraph("a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
// Indent should be included in length of lines
BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg h i j k", 79, 4), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\n f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg\n h i j k");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string. This is a second sentence in the very long test string.", 79), "This is a very long test string. This is a second sentence in the very long\ntest string.");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
BOOST_CHECK_EQUAL(FormatParagraph("Testing that normal newlines do not get indented.\nLike here.", 79), "Testing that normal newlines do not get indented.\nLike here.");
}
BOOST_AUTO_TEST_CASE(test_FormatSubVersion)
{
std::vector<std::string> comments;
comments.push_back(std::string("comment1"));
std::vector<std::string> comments2;
comments2.push_back(std::string("comment1"));
comments2.push_back(SanitizeString(std::string("Comment2; .,_?@-; !\"#$%&'()*+/<=>[]\\^`{|}~"), SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:9.99.0/"));
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:9.99.0(comment1)/"));
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:9.99.0(comment1; Comment2; .,_?@-; )/"));
}
BOOST_AUTO_TEST_CASE(test_ParseFixedPoint)
{
int64_t amount = 0;
BOOST_CHECK(ParseFixedPoint("0", 8, &amount));
BOOST_CHECK_EQUAL(amount, 0LL);
BOOST_CHECK(ParseFixedPoint("1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000LL);
BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount));
BOOST_CHECK_EQUAL(amount, 0LL);
BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount));
BOOST_CHECK_EQUAL(amount, -10000000LL);
BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 110000000LL);
BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 110000000LL);
BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1100000000LL);
BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 11000000LL);
BOOST_CHECK(ParseFixedPoint("1000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000000LL);
BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount));
BOOST_CHECK_EQUAL(amount, -100000000000LL);
BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1LL);
BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1LL);
BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, -1LL);
BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000000000001LL);
BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount));
BOOST_CHECK_EQUAL(amount, 999999999999999999LL);
BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount));
BOOST_CHECK_EQUAL(amount, -999999999999999999LL);
BOOST_CHECK(!ParseFixedPoint("", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount));
// Test with 3 decimal places for fee rates in sat/vB.
BOOST_CHECK(ParseFixedPoint("0.001", 3, &amount));
BOOST_CHECK_EQUAL(amount, CAmount{1});
BOOST_CHECK(!ParseFixedPoint("0.0009", 3, &amount));
BOOST_CHECK(!ParseFixedPoint("31.00100001", 3, &amount));
BOOST_CHECK(!ParseFixedPoint("31.0011", 3, &amount));
BOOST_CHECK(!ParseFixedPoint("31.99999999", 3, &amount));
BOOST_CHECK(!ParseFixedPoint("31.999999999999999999999", 3, &amount));
}
static void TestOtherThread(fs::path dirname, fs::path lockname, bool *result)
{
*result = LockDirectory(dirname, lockname);
}
#ifndef WIN32 // Cannot do this test on WIN32 due to lack of fork()
static constexpr char LockCommand = 'L';
static constexpr char UnlockCommand = 'U';
static constexpr char ExitCommand = 'X';
[[noreturn]] static void TestOtherProcess(fs::path dirname, fs::path lockname, int fd)
{
char ch;
while (true) {
int rv = read(fd, &ch, 1); // Wait for command
assert(rv == 1);
switch(ch) {
case LockCommand:
ch = LockDirectory(dirname, lockname);
rv = write(fd, &ch, 1);
assert(rv == 1);
break;
case UnlockCommand:
ReleaseDirectoryLocks();
ch = true; // Always succeeds
rv = write(fd, &ch, 1);
assert(rv == 1);
break;
case ExitCommand:
close(fd);
exit(0);
default:
assert(0);
}
}
}
#endif
BOOST_AUTO_TEST_CASE(test_LockDirectory)
{
fs::path dirname = m_args.GetDataDirBase() / "lock_dir";
const fs::path lockname = ".lock";
#ifndef WIN32
// Revert SIGCHLD to default, otherwise boost.test will catch and fail on
// it: there is BOOST_TEST_IGNORE_SIGCHLD but that only works when defined
// at build-time of the boost library
void (*old_handler)(int) = signal(SIGCHLD, SIG_DFL);
// Fork another process for testing before creating the lock, so that we
// won't fork while holding the lock (which might be undefined, and is not
// relevant as test case as that is avoided with -daemonize).
int fd[2];
BOOST_CHECK_EQUAL(socketpair(AF_UNIX, SOCK_STREAM, 0, fd), 0);
pid_t pid = fork();
if (!pid) {
BOOST_CHECK_EQUAL(close(fd[1]), 0); // Child: close parent end
TestOtherProcess(dirname, lockname, fd[0]);
}
BOOST_CHECK_EQUAL(close(fd[0]), 0); // Parent: close child end
#endif
// Lock on non-existent directory should fail
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), false);
fs::create_directories(dirname);
// Probing lock on new directory should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Persistent lock on new directory should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true);
// Another lock on the directory from the same thread should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true);
// Another lock on the directory from a different thread within the same process should succeed
bool threadresult;
std::thread thr(TestOtherThread, dirname, lockname, &threadresult);
thr.join();
BOOST_CHECK_EQUAL(threadresult, true);
#ifndef WIN32
// Try to acquire lock in child process while we're holding it, this should fail.
char ch;
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, false);
// Give up our lock
ReleaseDirectoryLocks();
// Probing lock from our side now should succeed, but not hold on to the lock.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Try to acquire the lock in the child process, this should be successful.
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, true);
// When we try to probe the lock now, it should fail.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), false);
// Unlock the lock in the child process
BOOST_CHECK_EQUAL(write(fd[1], &UnlockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, true);
// When we try to probe the lock now, it should succeed.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Re-lock the lock in the child process, then wait for it to exit, check
// successful return. After that, we check that exiting the process
// has released the lock as we would expect by probing it.
int processstatus;
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(write(fd[1], &ExitCommand, 1), 1);
BOOST_CHECK_EQUAL(waitpid(pid, &processstatus, 0), pid);
BOOST_CHECK_EQUAL(processstatus, 0);
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Restore SIGCHLD
signal(SIGCHLD, old_handler);
BOOST_CHECK_EQUAL(close(fd[1]), 0); // Close our side of the socketpair
#endif
// Clean up
ReleaseDirectoryLocks();
fs::remove_all(dirname);
}
BOOST_AUTO_TEST_CASE(test_DirIsWritable)
{
// Should be able to write to the data dir.
fs::path tmpdirname = m_args.GetDataDirBase();
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
// Should not be able to write to a non-existent dir.
tmpdirname = GetUniquePath(tmpdirname);
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), false);
fs::create_directory(tmpdirname);
// Should be able to write to it now.
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
fs::remove(tmpdirname);
}
BOOST_AUTO_TEST_CASE(test_ToLower)
{
BOOST_CHECK_EQUAL(ToLower('@'), '@');
BOOST_CHECK_EQUAL(ToLower('A'), 'a');
BOOST_CHECK_EQUAL(ToLower('Z'), 'z');
BOOST_CHECK_EQUAL(ToLower('['), '[');
BOOST_CHECK_EQUAL(ToLower(0), 0);
BOOST_CHECK_EQUAL(ToLower('\xff'), '\xff');
BOOST_CHECK_EQUAL(ToLower(""), "");
BOOST_CHECK_EQUAL(ToLower("#HODL"), "#hodl");
BOOST_CHECK_EQUAL(ToLower("\x00\xfe\xff"), "\x00\xfe\xff");
}
BOOST_AUTO_TEST_CASE(test_ToUpper)
{
BOOST_CHECK_EQUAL(ToUpper('`'), '`');
BOOST_CHECK_EQUAL(ToUpper('a'), 'A');
BOOST_CHECK_EQUAL(ToUpper('z'), 'Z');
BOOST_CHECK_EQUAL(ToUpper('{'), '{');
BOOST_CHECK_EQUAL(ToUpper(0), 0);
BOOST_CHECK_EQUAL(ToUpper('\xff'), '\xff');
BOOST_CHECK_EQUAL(ToUpper(""), "");
BOOST_CHECK_EQUAL(ToUpper("#hodl"), "#HODL");
BOOST_CHECK_EQUAL(ToUpper("\x00\xfe\xff"), "\x00\xfe\xff");
}
BOOST_AUTO_TEST_CASE(test_Capitalize)
{
BOOST_CHECK_EQUAL(Capitalize(""), "");
BOOST_CHECK_EQUAL(Capitalize("bitcoin"), "Bitcoin");
BOOST_CHECK_EQUAL(Capitalize("\x00\xfe\xff"), "\x00\xfe\xff");
}
static std::string SpanToStr(const Span<const char>& span)
{
return std::string(span.begin(), span.end());
}
BOOST_AUTO_TEST_CASE(test_spanparsing)
{
using namespace spanparsing;
std::string input;
Span<const char> sp;
bool success;
// Const(...): parse a constant, update span to skip it if successful
input = "MilkToastHoney";
sp = input;
success = Const("", sp); // empty
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
success = Const("Milk", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
success = Const("Bread", sp);
BOOST_CHECK(!success);
success = Const("Toast", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
success = Const("Honeybadger", sp);
BOOST_CHECK(!success);
success = Const("Honey", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "");
// Func(...): parse a function call, update span to argument if successful
input = "Foo(Bar(xy,z()))";
sp = input;
success = Func("FooBar", sp);
BOOST_CHECK(!success);
success = Func("Foo(", sp);
BOOST_CHECK(!success);
success = Func("Foo", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Bar(xy,z())");
success = Func("Bar", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "xy,z()");
success = Func("xy", sp);
BOOST_CHECK(!success);
// Expr(...): return expression that span begins with, update span to skip it
Span<const char> result;
input = "(n*(n-1))/2";
sp = input;
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "(n*(n-1))/2");
BOOST_CHECK_EQUAL(SpanToStr(sp), "");
input = "foo,bar";
sp = input;
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "foo");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",bar");
input = "(aaaaa,bbbbb()),c";
sp = input;
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "(aaaaa,bbbbb())");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",c");
input = "xyz)foo";
sp = input;
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "xyz");
BOOST_CHECK_EQUAL(SpanToStr(sp), ")foo");
input = "((a),(b),(c)),xxx";
sp = input;
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "((a),(b),(c))");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",xxx");
// Split(...): split a string on every instance of sep, return vector
std::vector<Span<const char>> results;
input = "xxx";
results = Split(input, 'x');
BOOST_CHECK_EQUAL(results.size(), 4U);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
input = "one#two#three";
results = Split(input, '-');
BOOST_CHECK_EQUAL(results.size(), 1U);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one#two#three");
input = "one#two#three";
results = Split(input, '#');
BOOST_CHECK_EQUAL(results.size(), 3U);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "two");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "three");
input = "*foo*bar*";
results = Split(input, '*');
BOOST_CHECK_EQUAL(results.size(), 4U);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "foo");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "bar");
BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
}
BOOST_AUTO_TEST_CASE(test_SplitString)
{
// Empty string.
{
std::vector<std::string> result = SplitString("", '-');
BOOST_CHECK_EQUAL(result.size(), 1);
BOOST_CHECK_EQUAL(result[0], "");
}
// Empty items.
{
std::vector<std::string> result = SplitString("-", '-');
BOOST_CHECK_EQUAL(result.size(), 2);
BOOST_CHECK_EQUAL(result[0], "");
BOOST_CHECK_EQUAL(result[1], "");
}
// More empty items.
{
std::vector<std::string> result = SplitString("--", '-');
BOOST_CHECK_EQUAL(result.size(), 3);
BOOST_CHECK_EQUAL(result[0], "");
BOOST_CHECK_EQUAL(result[1], "");
BOOST_CHECK_EQUAL(result[2], "");
}
// Separator is not present.
{
std::vector<std::string> result = SplitString("abc", '-');
BOOST_CHECK_EQUAL(result.size(), 1);
BOOST_CHECK_EQUAL(result[0], "abc");
}
// Basic behavior.
{
std::vector<std::string> result = SplitString("a-b", '-');
BOOST_CHECK_EQUAL(result.size(), 2);
BOOST_CHECK_EQUAL(result[0], "a");
BOOST_CHECK_EQUAL(result[1], "b");
}
// Case-sensitivity of the separator.
{
std::vector<std::string> result = SplitString("AAA", 'a');
BOOST_CHECK_EQUAL(result.size(), 1);
BOOST_CHECK_EQUAL(result[0], "AAA");
}
// multiple split characters
{
using V = std::vector<std::string>;
BOOST_TEST(SplitString("a,b.c:d;e", ",;") == V({"a", "b.c:d", "e"}));
BOOST_TEST(SplitString("a,b.c:d;e", ",;:.") == V({"a", "b", "c", "d", "e"}));
BOOST_TEST(SplitString("a,b.c:d;e", "") == V({"a,b.c:d;e"}));
BOOST_TEST(SplitString("aaa", "bcdefg") == V({"aaa"}));
BOOST_TEST(SplitString("x\0a,b"s, "\0"s) == V({"x", "a,b"}));
BOOST_TEST(SplitString("x\0a,b"s, '\0') == V({"x", "a,b"}));
BOOST_TEST(SplitString("x\0a,b"s, "\0,"s) == V({"x", "a", "b"}));
BOOST_TEST(SplitString("abcdefg", "bcd") == V({"a", "", "", "efg"}));
}
}
BOOST_AUTO_TEST_CASE(test_LogEscapeMessage)
{
// ASCII and UTF-8 must pass through unaltered.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Valid log message貓"), "Valid log message貓");
// Newlines must pass through unaltered.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Message\n with newlines\n"), "Message\n with newlines\n");
// Other control characters are escaped in C syntax.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("\x01\x7f Corrupted log message\x0d"), R"(\x01\x7f Corrupted log message\x0d)");
// Embedded NULL characters are escaped too.
const std::string NUL("O\x00O", 3);
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage(NUL), R"(O\x00O)");
}
namespace {
struct Tracker
{
//! Points to the original object (possibly itself) we moved/copied from
const Tracker* origin;
//! How many copies where involved between the original object and this one (moves are not counted)
int copies{0};
Tracker() noexcept : origin(this) {}
Tracker(const Tracker& t) noexcept : origin(t.origin), copies(t.copies + 1) {}
Tracker(Tracker&& t) noexcept : origin(t.origin), copies(t.copies) {}
Tracker& operator=(const Tracker& t) noexcept
{
origin = t.origin;
copies = t.copies + 1;
return *this;
}
};
}
BOOST_AUTO_TEST_CASE(test_tracked_vector)
{
Tracker t1;
Tracker t2;
Tracker t3;
BOOST_CHECK(t1.origin == &t1);
BOOST_CHECK(t2.origin == &t2);
BOOST_CHECK(t3.origin == &t3);
auto v1 = Vector(t1);
BOOST_CHECK_EQUAL(v1.size(), 1U);
BOOST_CHECK(v1[0].origin == &t1);
BOOST_CHECK_EQUAL(v1[0].copies, 1);
auto v2 = Vector(std::move(t2));
BOOST_CHECK_EQUAL(v2.size(), 1U);
BOOST_CHECK(v2[0].origin == &t2); // NOLINT(*-use-after-move)
BOOST_CHECK_EQUAL(v2[0].copies, 0);
auto v3 = Vector(t1, std::move(t2));
BOOST_CHECK_EQUAL(v3.size(), 2U);
BOOST_CHECK(v3[0].origin == &t1);
BOOST_CHECK(v3[1].origin == &t2); // NOLINT(*-use-after-move)
BOOST_CHECK_EQUAL(v3[0].copies, 1);
BOOST_CHECK_EQUAL(v3[1].copies, 0);
auto v4 = Vector(std::move(v3[0]), v3[1], std::move(t3));
BOOST_CHECK_EQUAL(v4.size(), 3U);
BOOST_CHECK(v4[0].origin == &t1);
BOOST_CHECK(v4[1].origin == &t2);
BOOST_CHECK(v4[2].origin == &t3); // NOLINT(*-use-after-move)
BOOST_CHECK_EQUAL(v4[0].copies, 1);
BOOST_CHECK_EQUAL(v4[1].copies, 1);
BOOST_CHECK_EQUAL(v4[2].copies, 0);
auto v5 = Cat(v1, v4);
BOOST_CHECK_EQUAL(v5.size(), 4U);
BOOST_CHECK(v5[0].origin == &t1);
BOOST_CHECK(v5[1].origin == &t1);
BOOST_CHECK(v5[2].origin == &t2);
BOOST_CHECK(v5[3].origin == &t3);
BOOST_CHECK_EQUAL(v5[0].copies, 2);
BOOST_CHECK_EQUAL(v5[1].copies, 2);
BOOST_CHECK_EQUAL(v5[2].copies, 2);
BOOST_CHECK_EQUAL(v5[3].copies, 1);
auto v6 = Cat(std::move(v1), v3);
BOOST_CHECK_EQUAL(v6.size(), 3U);
BOOST_CHECK(v6[0].origin == &t1);
BOOST_CHECK(v6[1].origin == &t1);
BOOST_CHECK(v6[2].origin == &t2);
BOOST_CHECK_EQUAL(v6[0].copies, 1);
BOOST_CHECK_EQUAL(v6[1].copies, 2);
BOOST_CHECK_EQUAL(v6[2].copies, 1);
auto v7 = Cat(v2, std::move(v4));
BOOST_CHECK_EQUAL(v7.size(), 4U);
BOOST_CHECK(v7[0].origin == &t2);
BOOST_CHECK(v7[1].origin == &t1);
BOOST_CHECK(v7[2].origin == &t2);
BOOST_CHECK(v7[3].origin == &t3);
BOOST_CHECK_EQUAL(v7[0].copies, 1);
BOOST_CHECK_EQUAL(v7[1].copies, 1);
BOOST_CHECK_EQUAL(v7[2].copies, 1);
BOOST_CHECK_EQUAL(v7[3].copies, 0);
auto v8 = Cat(std::move(v2), std::move(v3));
BOOST_CHECK_EQUAL(v8.size(), 3U);
BOOST_CHECK(v8[0].origin == &t2);
BOOST_CHECK(v8[1].origin == &t1);
BOOST_CHECK(v8[2].origin == &t2);
BOOST_CHECK_EQUAL(v8[0].copies, 0);
BOOST_CHECK_EQUAL(v8[1].copies, 1);
BOOST_CHECK_EQUAL(v8[2].copies, 0);
}
BOOST_AUTO_TEST_CASE(message_sign)
{
const std::array<unsigned char, 32> privkey_bytes = {
// just some random data
// derived address from this private key: 15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs
0xD9, 0x7F, 0x51, 0x08, 0xF1, 0x1C, 0xDA, 0x6E,
0xEE, 0xBA, 0xAA, 0x42, 0x0F, 0xEF, 0x07, 0x26,
0xB1, 0xF8, 0x98, 0x06, 0x0B, 0x98, 0x48, 0x9F,
0xA3, 0x09, 0x84, 0x63, 0xC0, 0x03, 0x28, 0x66
};
const std::string message = "Trust no one";
const std::string expected_signature =
"IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=";
CKey privkey;
std::string generated_signature;
BOOST_REQUIRE_MESSAGE(!privkey.IsValid(),
"Confirm the private key is invalid");
BOOST_CHECK_MESSAGE(!MessageSign(privkey, message, generated_signature),
"Sign with an invalid private key");
privkey.Set(privkey_bytes.begin(), privkey_bytes.end(), true);
BOOST_REQUIRE_MESSAGE(privkey.IsValid(),
"Confirm the private key is valid");
BOOST_CHECK_MESSAGE(MessageSign(privkey, message, generated_signature),
"Sign with a valid private key");
BOOST_CHECK_EQUAL(expected_signature, generated_signature);
}
BOOST_AUTO_TEST_CASE(message_verify)
{
BOOST_CHECK_EQUAL(
MessageVerify(
"invalid address",
"signature should be irrelevant",
"message too"),
MessageVerificationResult::ERR_INVALID_ADDRESS);
BOOST_CHECK_EQUAL(
MessageVerify(
"3B5fQsEXEaV8v6U3ejYc8XaKXAkyQj2MjV",
"signature should be irrelevant",
"message too"),
MessageVerificationResult::ERR_ADDRESS_NO_KEY);
BOOST_CHECK_EQUAL(
MessageVerify(
"1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
"invalid signature, not in base64 encoding",
"message should be irrelevant"),
MessageVerificationResult::ERR_MALFORMED_SIGNATURE);
BOOST_CHECK_EQUAL(
MessageVerify(
"1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"message should be irrelevant"),
MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED);
BOOST_CHECK_EQUAL(
MessageVerify(
"15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
"IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
"I never signed this"),
MessageVerificationResult::ERR_NOT_SIGNED);
BOOST_CHECK_EQUAL(
MessageVerify(
"15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
"IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
"Trust no one"),
MessageVerificationResult::OK);
BOOST_CHECK_EQUAL(
MessageVerify(
"11canuhp9X2NocwCq7xNrQYTmUgZAnLK3",
"IIcaIENoYW5jZWxsb3Igb24gYnJpbmsgb2Ygc2Vjb25kIGJhaWxvdXQgZm9yIGJhbmtzIAaHRtbCeDZINyavx14=",
"Trust me"),
MessageVerificationResult::OK);
}
BOOST_AUTO_TEST_CASE(message_hash)
{
const std::string unsigned_tx = "...";
const std::string prefixed_message =
std::string(1, (char)MESSAGE_MAGIC.length()) +
MESSAGE_MAGIC +
std::string(1, (char)unsigned_tx.length()) +
unsigned_tx;
const uint256 signature_hash = Hash(unsigned_tx);
const uint256 message_hash1 = Hash(prefixed_message);
const uint256 message_hash2 = MessageHash(unsigned_tx);
BOOST_CHECK_EQUAL(message_hash1, message_hash2);
BOOST_CHECK_NE(message_hash1, signature_hash);
}
BOOST_AUTO_TEST_CASE(remove_prefix)
{
BOOST_CHECK_EQUAL(RemovePrefix("./util/system.h", "./"), "util/system.h");
BOOST_CHECK_EQUAL(RemovePrefixView("foo", "foo"), "");
BOOST_CHECK_EQUAL(RemovePrefix("foo", "fo"), "o");
BOOST_CHECK_EQUAL(RemovePrefixView("foo", "f"), "oo");
BOOST_CHECK_EQUAL(RemovePrefix("foo", ""), "foo");
BOOST_CHECK_EQUAL(RemovePrefixView("fo", "foo"), "fo");
BOOST_CHECK_EQUAL(RemovePrefix("f", "foo"), "f");
BOOST_CHECK_EQUAL(RemovePrefixView("", "foo"), "");
BOOST_CHECK_EQUAL(RemovePrefix("", ""), "");
}
BOOST_AUTO_TEST_CASE(util_ParseByteUnits)
{
auto noop = ByteUnit::NOOP;
// no multiplier
BOOST_CHECK_EQUAL(ParseByteUnits("1", noop).value(), 1);
BOOST_CHECK_EQUAL(ParseByteUnits("0", noop).value(), 0);
BOOST_CHECK_EQUAL(ParseByteUnits("1k", noop).value(), 1000ULL);
BOOST_CHECK_EQUAL(ParseByteUnits("1K", noop).value(), 1ULL << 10);
BOOST_CHECK_EQUAL(ParseByteUnits("2m", noop).value(), 2'000'000ULL);
BOOST_CHECK_EQUAL(ParseByteUnits("2M", noop).value(), 2ULL << 20);
BOOST_CHECK_EQUAL(ParseByteUnits("3g", noop).value(), 3'000'000'000ULL);
BOOST_CHECK_EQUAL(ParseByteUnits("3G", noop).value(), 3ULL << 30);
BOOST_CHECK_EQUAL(ParseByteUnits("4t", noop).value(), 4'000'000'000'000ULL);
BOOST_CHECK_EQUAL(ParseByteUnits("4T", noop).value(), 4ULL << 40);
// check default multiplier
BOOST_CHECK_EQUAL(ParseByteUnits("5", ByteUnit::K).value(), 5ULL << 10);
// NaN
BOOST_CHECK(!ParseByteUnits("", noop));
BOOST_CHECK(!ParseByteUnits("foo", noop));
// whitespace
BOOST_CHECK(!ParseByteUnits("123m ", noop));
BOOST_CHECK(!ParseByteUnits(" 123m", noop));
// no +-
BOOST_CHECK(!ParseByteUnits("-123m", noop));
BOOST_CHECK(!ParseByteUnits("+123m", noop));
// zero padding
BOOST_CHECK_EQUAL(ParseByteUnits("020M", noop).value(), 20ULL << 20);
// fractions not allowed
BOOST_CHECK(!ParseByteUnits("0.5T", noop));
// overflow
BOOST_CHECK(!ParseByteUnits("18446744073709551615g", noop));
// invalid unit
BOOST_CHECK(!ParseByteUnits("1x", noop));
}
BOOST_AUTO_TEST_CASE(util_ReadBinaryFile)
{
fs::path tmpfolder = m_args.GetDataDirBase();
fs::path tmpfile = tmpfolder / "read_binary.dat";
std::string expected_text;
for (int i = 0; i < 30; i++) {
expected_text += "0123456789";
}
{
std::ofstream file{tmpfile};
file << expected_text;
}
{
// read all contents in file
auto [valid, text] = ReadBinaryFile(tmpfile);
BOOST_CHECK(valid);
BOOST_CHECK_EQUAL(text, expected_text);
}
{
// read half contents in file
auto [valid, text] = ReadBinaryFile(tmpfile, expected_text.size() / 2);
BOOST_CHECK(valid);
BOOST_CHECK_EQUAL(text, expected_text.substr(0, expected_text.size() / 2));
}
{
// read from non-existent file
fs::path invalid_file = tmpfolder / "invalid_binary.dat";
auto [valid, text] = ReadBinaryFile(invalid_file);
BOOST_CHECK(!valid);
BOOST_CHECK(text.empty());
}
}
BOOST_AUTO_TEST_CASE(util_WriteBinaryFile)
{
fs::path tmpfolder = m_args.GetDataDirBase();
fs::path tmpfile = tmpfolder / "write_binary.dat";
std::string expected_text = "bitcoin";
auto valid = WriteBinaryFile(tmpfile, expected_text);
std::string actual_text;
std::ifstream file{tmpfile};
file >> actual_text;
BOOST_CHECK(valid);
BOOST_CHECK_EQUAL(actual_text, expected_text);
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
tue-es/bones | skeletons/GPU-OPENCL-AMD/kernel/D-element-to-1-shared.host.c | 6 | 4178 |
// Store the initial value
cl_mem bones_initial_value = clCreateBuffer(bones_context,CL_MEM_READ_WRITE|CL_MEM_COPY_HOST_PTR,sizeof(<out0_type>),<out0_name>,&bones_errors); error_check(bones_errors);
// Create the kernels
cl_kernel bones_kernel_<algorithm_name>_0 = clCreateKernel(bones_program, "bones_kernel_<algorithm_name>_0", &bones_errors); error_check(bones_errors);
cl_kernel bones_kernel_<algorithm_name>_1 = clCreateKernel(bones_program, "bones_kernel_<algorithm_name>_1", &bones_errors); error_check(bones_errors);
cl_kernel bones_kernel_<algorithm_name>_2 = clCreateKernel(bones_program, "bones_kernel_<algorithm_name>_2", &bones_errors); error_check(bones_errors);
// Run either one kernel or multiple kernels
if (<in0_dimensions> <= 512) {
// Set all the arguments to the kernel function
int bones_num_args = 3;
int bones_dimensions = <in0_dimensions>;
clSetKernelArg(bones_kernel_<algorithm_name>_0,0,sizeof(bones_dimensions),(void*)&bones_dimensions);
clSetKernelArg(bones_kernel_<algorithm_name>_0,1,sizeof(<in0_devicename>),(void*)&<in0_devicename>);
clSetKernelArg(bones_kernel_<algorithm_name>_0,2,sizeof(<out0_devicename>),(void*)&<out0_devicename>);
<kernel_argument_list_constants>
// Start only one kernel
const int bones_num_threads = DIV_CEIL(<in0_dimensions>,2);
size_t bones_local_worksize1[] = {bones_num_threads};
size_t bones_global_worksize1[] = {bones_num_threads};
bones_errors = clEnqueueNDRangeKernel(bones_queue,bones_kernel_<algorithm_name>_0,1,NULL,bones_global_worksize1,bones_local_worksize1,0,NULL,&bones_event); error_check(bones_errors);
}
else {
// Allocate space for an intermediate array
cl_mem bones_device_temp = clCreateBuffer(bones_context,CL_MEM_READ_WRITE,128*sizeof(<out0_type>),NULL,&bones_errors); error_check(bones_errors);
// Set all the arguments to the kernel function
int bones_num_args = 3;
int bones_dimensions = <in0_dimensions>;
clSetKernelArg(bones_kernel_<algorithm_name>_0,0,sizeof(bones_dimensions),(void*)&bones_dimensions);
clSetKernelArg(bones_kernel_<algorithm_name>_0,1,sizeof(<in0_devicename>),(void*)&<in0_devicename>);
clSetKernelArg(bones_kernel_<algorithm_name>_0,2,sizeof(bones_device_temp),(void*)&bones_device_temp);
<kernel_argument_list_constants>
// Start the first kernel
size_t bones_local_worksize1[] = {256};
size_t bones_global_worksize1[] = {256*128};
bones_errors = clEnqueueNDRangeKernel(bones_queue,bones_kernel_<algorithm_name>_0,1,NULL,bones_global_worksize1,bones_local_worksize1,0,NULL,&bones_event); error_check(bones_errors);
// Set all the arguments to the kernel function
clSetKernelArg(bones_kernel_<algorithm_name>_1,0,sizeof(bones_device_temp),(void*)&bones_device_temp);
clSetKernelArg(bones_kernel_<algorithm_name>_1,1,sizeof(<out0_devicename>),(void*)&<out0_devicename>);
// Start the second kernel
size_t bones_local_worksize2[] = {128};
size_t bones_global_worksize2[] = {128};
bones_errors = clEnqueueNDRangeKernel(bones_queue,bones_kernel_<algorithm_name>_1,1,NULL,bones_global_worksize2,bones_local_worksize2,0,NULL,&bones_event); error_check(bones_errors);
clReleaseMemObject(bones_device_temp);
}
// Set all the arguments to the kernel function
clSetKernelArg(bones_kernel_<algorithm_name>_2,0,sizeof(bones_initial_value),(void*)&bones_initial_value);
clSetKernelArg(bones_kernel_<algorithm_name>_2,1,sizeof(<out0_devicename>),(void*)&<out0_devicename>);
// Perform the last computation (only needed if there is an initial value)
size_t bones_local_worksize3[] = {1};
size_t bones_global_worksize3[] = {1};
bones_errors = clEnqueueNDRangeKernel(bones_queue,bones_kernel_<algorithm_name>_2,1,NULL,bones_global_worksize3,bones_local_worksize3,0,NULL,&bones_event); error_check(bones_errors);
clReleaseMemObject(bones_initial_value);
// Synchronize and clean-up the kernels
clFinish(bones_queue);
clReleaseKernel(bones_kernel_<algorithm_name>_0);
clReleaseKernel(bones_kernel_<algorithm_name>_1);
clReleaseKernel(bones_kernel_<algorithm_name>_2);
| mit |
gibtang/CCNSCoding | external/emscripten/tests/zlib/inftrees.c | 1286 | 13769 | /* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "inftrees.h"
#define MAXBITS 15
const char inflate_copyright[] =
" inflate 1.2.5 Copyright 1995-2010 Mark Adler ";
/*
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/*
Build a set of tables to decode the provided canonical Huffman code.
The code lengths are lens[0..codes-1]. The result starts at *table,
whose indices are 0..2^bits-1. work is a writable array of at least
lens shorts, which is used as a work area. type is the type of code
to be generated, CODES, LENS, or DISTS. On return, zero is success,
-1 is an invalid code, and +1 means that ENOUGH isn't enough. table
on return points to the next available entry's address. bits is the
requested root table index bits, and on return it is the actual root
table index bits. It will differ if the request is greater than the
longest code or if it is less than the shortest code.
*/
int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
codetype type;
unsigned short FAR *lens;
unsigned codes;
code FAR * FAR *table;
unsigned FAR *bits;
unsigned short FAR *work;
{
unsigned len; /* a code's length in bits */
unsigned sym; /* index of code symbols */
unsigned min, max; /* minimum and maximum code lengths */
unsigned root; /* number of index bits for root table */
unsigned curr; /* number of index bits for current table */
unsigned drop; /* code bits to drop for sub-table */
int left; /* number of prefix codes available */
unsigned used; /* code entries in table used */
unsigned huff; /* Huffman code */
unsigned incr; /* for incrementing code, index */
unsigned fill; /* index for replicating entries */
unsigned low; /* low bits for current root entry */
unsigned mask; /* mask for low root bits */
code here; /* table entry for duplication */
code FAR *next; /* next available space in table */
const unsigned short FAR *base; /* base value table to use */
const unsigned short FAR *extra; /* extra bits table to use */
int end; /* use base and extra for symbol > end */
unsigned short count[MAXBITS+1]; /* number of codes of each length */
unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
static const unsigned short lbase[31] = { /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const unsigned short lext[31] = { /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195};
static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0};
static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64};
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++)
count[len] = 0;
for (sym = 0; sym < codes; sym++)
count[lens[sym]]++;
/* bound code lengths, force root to be within code lengths */
root = *bits;
for (max = MAXBITS; max >= 1; max--)
if (count[max] != 0) break;
if (root > max) root = max;
if (max == 0) { /* no symbols to code at all */
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)1;
here.val = (unsigned short)0;
*(*table)++ = here; /* make a table to force an error */
*(*table)++ = here;
*bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++)
if (count[min] != 0) break;
if (root < min) root = min;
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) return -1; /* over-subscribed */
}
if (left > 0 && (type == CODES || max != 1))
return -1; /* incomplete set */
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++)
offs[len + 1] = offs[len] + count[len];
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++)
if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
switch (type) {
case CODES:
base = extra = work; /* dummy value--not used */
end = 19;
break;
case LENS:
base = lbase;
base -= 257;
extra = lext;
extra -= 257;
end = 256;
break;
default: /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize state for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = *table; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = (unsigned)(-1); /* trigger new sub-table when len > root */
used = 1U << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1;
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here.bits = (unsigned char)(len - drop);
if ((int)(work[sym]) < end) {
here.op = (unsigned char)0;
here.val = work[sym];
}
else if ((int)(work[sym]) > end) {
here.op = (unsigned char)(extra[work[sym]]);
here.val = base[work[sym]];
}
else {
here.op = (unsigned char)(32 + 64); /* end of block */
here.val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1U << (len - drop);
fill = 1U << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
next[(huff >> drop) + fill] = here;
} while (fill != 0);
/* backwards increment the len-bit code huff */
incr = 1U << (len - 1);
while (huff & incr)
incr >>= 1;
if (incr != 0) {
huff &= incr - 1;
huff += incr;
}
else
huff = 0;
/* go to next symbol, update count, len */
sym++;
if (--(count[len]) == 0) {
if (len == max) break;
len = lens[work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) != low) {
/* if first time, transition to sub-tables */
if (drop == 0)
drop = root;
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = (int)(1 << curr);
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) break;
curr++;
left <<= 1;
}
/* check for enough space */
used += 1U << curr;
if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1;
/* point entry in root table to sub-table */
low = huff & mask;
(*table)[low].op = (unsigned char)curr;
(*table)[low].bits = (unsigned char)root;
(*table)[low].val = (unsigned short)(next - *table);
}
}
/*
Fill in rest of table for incomplete codes. This loop is similar to the
loop above in incrementing huff for table indices. It is assumed that
len is equal to curr + drop, so there is no loop needed to increment
through high index bits. When the current sub-table is filled, the loop
drops back to the root table to fill in any remaining entries there.
*/
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)(len - drop);
here.val = (unsigned short)0;
while (huff != 0) {
/* when done with sub-table, drop back to root table */
if (drop != 0 && (huff & mask) != low) {
drop = 0;
len = root;
next = *table;
here.bits = (unsigned char)len;
}
/* put invalid code marker in table */
next[huff >> drop] = here;
/* backwards increment the len-bit code huff */
incr = 1U << (len - 1);
while (huff & incr)
incr >>= 1;
if (incr != 0) {
huff &= incr - 1;
huff += incr;
}
else
huff = 0;
}
/* set return parameters */
*table += used;
*bits = root;
return 0;
}
| mit |
thiz11/platform_bootable_bootloader_lk | app/aboot/recovery.c | 7 | 13353 | /* Copyright (c) 2010-2011, Code Aurora Forum. 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 Code Aurora Forum, 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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 <debug.h>
#include <arch/arm.h>
#include <dev/udc.h>
#include <string.h>
#include <kernel/thread.h>
#include <arch/ops.h>
#include <dev/flash.h>
#include <lib/ptable.h>
#include <dev/keys.h>
#include <platform.h>
#include <partition_parser.h>
#include <mmc.h>
#include "recovery.h"
#include "bootimg.h"
//#include "smem.h"
#define BOOT_FLAGS 1
#define UPDATE_STATUS 2
#define ROUND_TO_PAGE(x,y) (((x) + (y)) & (~(y)))
static const int MISC_PAGES = 3; // number of pages to save
static const int MISC_COMMAND_PAGE = 1; // bootloader command is this page
static char buf[4096];
unsigned boot_into_recovery = 0;
extern void reset_device_info();
extern void set_device_root();
int get_recovery_message(struct recovery_message *out)
{
struct ptentry *ptn;
struct ptable *ptable;
unsigned offset = 0;
unsigned pagesize = flash_page_size();
ptable = flash_get_ptable();
if (ptable == NULL) {
dprintf(CRITICAL, "ERROR: Partition table not found\n");
return -1;
}
ptn = ptable_find(ptable, "misc");
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No misc partition found\n");
return -1;
}
offset += (pagesize * MISC_COMMAND_PAGE);
if (flash_read(ptn, offset, (void *) buf, pagesize)) {
dprintf(CRITICAL, "ERROR: Cannot read recovery_header\n");
return -1;
}
memcpy(out, buf, sizeof(*out));
return 0;
}
int set_recovery_message(const struct recovery_message *in)
{
struct ptentry *ptn;
struct ptable *ptable;
unsigned offset = 0;
unsigned pagesize = flash_page_size();
unsigned n = 0;
ptable = flash_get_ptable();
if (ptable == NULL) {
dprintf(CRITICAL, "ERROR: Partition table not found\n");
return -1;
}
ptn = ptable_find(ptable, "misc");
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No misc partition found\n");
return -1;
}
n = pagesize * (MISC_COMMAND_PAGE + 1);
if (flash_read(ptn, offset, (void *) SCRATCH_ADDR, n)) {
dprintf(CRITICAL, "ERROR: Cannot read recovery_header\n");
return -1;
}
offset += (pagesize * MISC_COMMAND_PAGE);
offset += SCRATCH_ADDR;
memcpy((void *) offset, in, sizeof(*in));
if (flash_write(ptn, 0, (void *)SCRATCH_ADDR, n)) {
dprintf(CRITICAL, "ERROR: flash write fail!\n");
return -1;
}
return 0;
}
int read_update_header_for_bootloader(struct update_header *header)
{
struct ptentry *ptn;
struct ptable *ptable;
unsigned offset = 0;
unsigned pagesize = flash_page_size();
ptable = flash_get_ptable();
if (ptable == NULL) {
dprintf(CRITICAL, "ERROR: Partition table not found\n");
return -1;
}
ptn = ptable_find(ptable, "cache");
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No cache partition found\n");
return -1;
}
if (flash_read(ptn, offset, buf, pagesize)) {
dprintf(CRITICAL, "ERROR: Cannot read recovery_header\n");
return -1;
}
memcpy(header, buf, sizeof(*header));
if (strncmp((char *) header->MAGIC, UPDATE_MAGIC, UPDATE_MAGIC_SIZE))
{
return -1;
}
return 0;
}
int update_firmware_image (struct update_header *header, char *name)
{
struct ptentry *ptn;
struct ptable *ptable;
unsigned offset = 0;
unsigned pagesize = flash_page_size();
unsigned pagemask = pagesize -1;
unsigned n = 0;
ptable = flash_get_ptable();
if (ptable == NULL) {
dprintf(CRITICAL, "ERROR: Partition table not found\n");
return -1;
}
ptn = ptable_find(ptable, "cache");
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No cache partition found\n");
return -1;
}
offset += header->image_offset;
n = (header->image_length + pagemask) & (~pagemask);
if (flash_read(ptn, offset, (void *) SCRATCH_ADDR, n)) {
dprintf(CRITICAL, "ERROR: Cannot read radio image\n");
return -1;
}
ptn = ptable_find(ptable, name);
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No %s partition found\n", name);
return -1;
}
if (flash_write(ptn, 0, (void *) SCRATCH_ADDR, n)) {
dprintf(CRITICAL, "ERROR: flash write fail!\n");
return -1;
}
dprintf(INFO, "Partition writen successfully!");
return 0;
}
static int set_ssd_radio_update (char *name)
{
struct ptentry *ptn;
struct ptable *ptable;
unsigned int ssd_cookie[2] = {0x53534443, 0x4F4F4B49};
unsigned pagesize = flash_page_size();
unsigned pagemask = pagesize -1;
unsigned n = 0;
ptable = flash_get_ptable();
if (ptable == NULL) {
dprintf(CRITICAL, "ERROR: Partition table not found\n");
return -1;
}
n = (sizeof(ssd_cookie) + pagemask) & (~pagemask);
ptn = ptable_find(ptable, name);
if (ptn == NULL) {
dprintf(CRITICAL, "ERROR: No %s partition found\n", name);
return -1;
}
if (flash_write(ptn, 0, ssd_cookie, n)) {
dprintf(CRITICAL, "ERROR: flash write fail!\n");
return -1;
}
dprintf(INFO, "FOTA partition written successfully!");
return 0;
}
int get_boot_info_apps (char type, unsigned int *status)
{
/* Koshi's Note: Seems dedicated for Q* solutions */
#if 0
boot_info_for_apps apps_boot_info;
int ret = 0;
ret = smem_read_alloc_entry(SMEM_BOOT_INFO_FOR_APPS,
&apps_boot_info, sizeof(apps_boot_info));
if (ret)
{
dprintf(CRITICAL, "ERROR: unable to read shared memory for apps boot info %d\n",ret);
return ret;
}
dprintf(INFO,"boot flag %x update status %x\n",apps_boot_info.boot_flags,
apps_boot_info.status.update_status);
if(type == BOOT_FLAGS)
*status = apps_boot_info.boot_flags;
else if(type == UPDATE_STATUS)
*status = apps_boot_info.status.update_status;
return ret;
#endif
return 0;
}
/* Bootloader / Recovery Flow
*
* On every boot, the bootloader will read the recovery_message
* from flash and check the command field. The bootloader should
* deal with the command field not having a 0 terminator correctly
* (so as to not crash if the block is invalid or corrupt).
*
* The bootloader will have to publish the partition that contains
* the recovery_message to the linux kernel so it can update it.
*
* if command == "boot-recovery" -> boot recovery.img
* else if command == "update-radio" -> update radio image (below)
* else -> boot boot.img (normal boot)
*
* Radio Update Flow
* 1. the bootloader will attempt to load and validate the header
* 2. if the header is invalid, status="invalid-update", goto #8
* 3. display the busy image on-screen
* 4. if the update image is invalid, status="invalid-radio-image", goto #8
* 5. attempt to update the firmware (depending on the command)
* 6. if successful, status="okay", goto #8
* 7. if failed, and the old image can still boot, status="failed-update"
* 8. write the recovery_message, leaving the recovery field
* unchanged, updating status, and setting command to
* "boot-recovery"
* 9. reboot
*
* The bootloader will not modify or erase the cache partition.
* It is recovery's responsibility to clean up the mess afterwards.
*/
int recovery_init (void)
{
struct recovery_message msg;
char partition_name[32];
unsigned valid_command = 0;
int update_status = 0;
// get recovery message
if (get_recovery_message(&msg))
return -1;
if (msg.command[0] != 0 && msg.command[0] != 255) {
dprintf(INFO, "Recovery command: %.*s\n", sizeof(msg.command), msg.command);
}
msg.command[sizeof(msg.command)-1] = '\0'; //Ensure termination
if (!strcmp("boot-recovery",msg.command))
{
if(!strcmp("RADIO",msg.status))
{
/* We're now here due to radio update, so check for update status */
int ret = get_boot_info_apps(UPDATE_STATUS, (unsigned int *) &update_status);
if(!ret && (update_status & 0x01))
{
dprintf(INFO,"radio update success\n");
strlcpy(msg.status, "OKAY", sizeof(msg.status));
}
else
{
dprintf(INFO,"radio update failed\n");
strlcpy(msg.status, "failed-update", sizeof(msg.status));
}
strlcpy(msg.command, "", sizeof(msg.command)); // clearing recovery command
set_recovery_message(&msg); // send recovery message
boot_into_recovery = 1; // Boot in recovery mode
return 0;
}
valid_command = 1;
strlcpy(msg.command, "", sizeof(msg.command)); // to safe against multiple reboot into recovery
strlcpy(msg.status, "OKAY", sizeof(msg.status));
set_recovery_message(&msg); // send recovery message
boot_into_recovery = 1; // Boot in recovery mode
return 0;
}
if (!strcmp("update-radio",msg.command)) {
dprintf(INFO,"start radio update\n");
valid_command = 1;
strlcpy(partition_name, "FOTA", sizeof(partition_name));
}
//Todo: Add support for bootloader update too.
if(!valid_command) {
//We need not to do anything
return 0; // Boot in normal mode
}
#ifdef OLD_FOTA_UPGRADE
if (read_update_header_for_bootloader(&header)) {
strlcpy(msg.status, "invalid-update", sizeof(msg.status));
goto SEND_RECOVERY_MSG;
}
if (update_firmware_image (&header, partition_name)) {
strlcpy(msg.status, "failed-update", sizeof(msg.status));
goto SEND_RECOVERY_MSG;
}
#else
if (set_ssd_radio_update(partition_name)) {
/* If writing to FOTA partition fails */
strlcpy(msg.command, "", sizeof(msg.command));
strlcpy(msg.status, "failed-update", sizeof(msg.status));
goto SEND_RECOVERY_MSG;
}
else {
/* Setting this to check the radio update status */
strlcpy(msg.command, "boot-recovery", sizeof(msg.command));
strlcpy(msg.status, "RADIO", sizeof(msg.status));
goto SEND_RECOVERY_MSG;
}
#endif
strlcpy(msg.status, "OKAY", sizeof(msg.status));
SEND_RECOVERY_MSG:
set_recovery_message(&msg); // send recovery message
boot_into_recovery = 1; // Boot in recovery mode
reboot_device(0);
return 0;
}
static int emmc_set_recovery_msg(struct recovery_message *out)
{
char *ptn_name = "misc";
unsigned long long ptn = 0;
unsigned int size = ROUND_TO_PAGE(sizeof(*out),511);
unsigned char data[size];
int index = INVALID_PTN;
index = partition_get_index((unsigned char *) ptn_name);
ptn = partition_get_offset(index);
if(ptn == 0) {
dprintf(CRITICAL,"partition %s doesn't exist\n",ptn_name);
return -1;
}
memcpy(data, out, sizeof(*out));
if (mmc_write(ptn , size, (unsigned int*)data)) {
dprintf(CRITICAL,"mmc write failure %s %d\n",ptn_name, sizeof(*out));
return -1;
}
return 0;
}
static int emmc_get_recovery_msg(struct recovery_message *in)
{
char *ptn_name = "misc";
unsigned long long ptn = 0;
unsigned int size = ROUND_TO_PAGE(sizeof(*in),511);
unsigned char data[size];
int index = INVALID_PTN;
index = partition_get_index((unsigned char *) ptn_name);
ptn = partition_get_offset(index);
if(ptn == 0) {
dprintf(CRITICAL,"partition %s doesn't exist\n",ptn_name);
return -1;
}
if (mmc_read(ptn , (unsigned int*)data, size)) {
dprintf(CRITICAL,"mmc read failure %s %d\n",ptn_name, size);
return -1;
}
memcpy(in, data, sizeof(*in));
return 0;
}
int _emmc_recovery_init(void)
{
int update_status = 0;
struct recovery_message msg;
// get recovery message
if(emmc_get_recovery_msg(&msg))
return -1;
if (msg.command[0] != 0 && msg.command[0] != 255) {
dprintf(INFO,"Recovery command: %d %s\n", sizeof(msg.command), msg.command);
}
msg.command[sizeof(msg.command)-1] = '\0'; //Ensure termination
if (!strcmp("update-radio",msg.command))
{
/* We're now here due to radio update, so check for update status */
int ret = get_boot_info_apps(UPDATE_STATUS, (unsigned int *) &update_status);
if(!ret && (update_status & 0x01))
{
dprintf(INFO,"radio update success\n");
strlcpy(msg.status, "OKAY", sizeof(msg.status));
}
else
{
dprintf(INFO,"radio update failed\n");
strlcpy(msg.status, "failed-update", sizeof(msg.status));
}
boot_into_recovery = 1; // Boot in recovery mode
}
if (!strcmp("reset-device-info",msg.command))
{
reset_device_info();
}
if (!strcmp("root-detect",msg.command))
{
set_device_root();
}
else
return 0; // do nothing
strlcpy(msg.command, "", sizeof(msg.command)); // clearing recovery command
emmc_set_recovery_msg(&msg); // send recovery message
return 0;
}
| mit |
ensemblr/llvm-project-boilerplate | include/llvm/tools/clang/test/CodeGen/rdrand-builtins.c | 8 | 1085 | // RUN: %clang_cc1 -ffreestanding -triple x86_64-unknown-unknown -target-feature +rdrnd -target-feature +rdseed -emit-llvm -o - %s | FileCheck %s
#include <x86intrin.h>
int rdrand16(unsigned short *p) {
return _rdrand16_step(p);
// CHECK: @rdrand16
// CHECK: call { i16, i32 } @llvm.x86.rdrand.16
// CHECK: store i16
}
int rdrand32(unsigned *p) {
return _rdrand32_step(p);
// CHECK: @rdrand32
// CHECK: call { i32, i32 } @llvm.x86.rdrand.32
// CHECK: store i32
}
int rdrand64(unsigned long long *p) {
return _rdrand64_step(p);
// CHECK: @rdrand64
// CHECK: call { i64, i32 } @llvm.x86.rdrand.64
// CHECK: store i64
}
int rdseed16(unsigned short *p) {
return _rdseed16_step(p);
// CHECK: @rdseed16
// CHECK: call { i16, i32 } @llvm.x86.rdseed.16
// CHECK: store i16
}
int rdseed32(unsigned *p) {
return _rdseed32_step(p);
// CHECK: @rdseed32
// CHECK: call { i32, i32 } @llvm.x86.rdseed.32
// CHECK: store i32
}
int rdseed64(unsigned long long *p) {
return _rdseed64_step(p);
// CHECK: @rdseed64
// CHECK: call { i64, i32 } @llvm.x86.rdseed.64
// CHECK: store i64
}
| mit |
andyfangdz/turtlebot_tracking | src/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp | 9 | 20565 | #include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif
using namespace cv;
using namespace std;
static void help()
{
cout << "This is a camera calibration sample." << endl
<< "Usage: calibration configurationFile" << endl
<< "Near the sample file you'll find the configuration file, which has detailed help of "
"how to edit it. It may be any OpenCV supported file format XML/YAML." << endl;
}
class Settings
{
public:
Settings() : goodInput(false) {}
enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
enum InputType {INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST};
void write(FileStorage& fs) const //Write serialization for this class
{
fs << "{" << "BoardSize_Width" << boardSize.width
<< "BoardSize_Height" << boardSize.height
<< "Square_Size" << squareSize
<< "Calibrate_Pattern" << patternToUse
<< "Calibrate_NrOfFrameToUse" << nrFrames
<< "Calibrate_FixAspectRatio" << aspectRatio
<< "Calibrate_AssumeZeroTangentialDistortion" << calibZeroTangentDist
<< "Calibrate_FixPrincipalPointAtTheCenter" << calibFixPrincipalPoint
<< "Write_DetectedFeaturePoints" << bwritePoints
<< "Write_extrinsicParameters" << bwriteExtrinsics
<< "Write_outputFileName" << outputFileName
<< "Show_UndistortedImage" << showUndistorsed
<< "Input_FlipAroundHorizontalAxis" << flipVertical
<< "Input_Delay" << delay
<< "Input" << input
<< "}";
}
void read(const FileNode& node) //Read serialization for this class
{
node["BoardSize_Width" ] >> boardSize.width;
node["BoardSize_Height"] >> boardSize.height;
node["Calibrate_Pattern"] >> patternToUse;
node["Square_Size"] >> squareSize;
node["Calibrate_NrOfFrameToUse"] >> nrFrames;
node["Calibrate_FixAspectRatio"] >> aspectRatio;
node["Write_DetectedFeaturePoints"] >> bwritePoints;
node["Write_extrinsicParameters"] >> bwriteExtrinsics;
node["Write_outputFileName"] >> outputFileName;
node["Calibrate_AssumeZeroTangentialDistortion"] >> calibZeroTangentDist;
node["Calibrate_FixPrincipalPointAtTheCenter"] >> calibFixPrincipalPoint;
node["Input_FlipAroundHorizontalAxis"] >> flipVertical;
node["Show_UndistortedImage"] >> showUndistorsed;
node["Input"] >> input;
node["Input_Delay"] >> delay;
interprate();
}
void interprate()
{
goodInput = true;
if (boardSize.width <= 0 || boardSize.height <= 0)
{
cerr << "Invalid Board size: " << boardSize.width << " " << boardSize.height << endl;
goodInput = false;
}
if (squareSize <= 10e-6)
{
cerr << "Invalid square size " << squareSize << endl;
goodInput = false;
}
if (nrFrames <= 0)
{
cerr << "Invalid number of frames " << nrFrames << endl;
goodInput = false;
}
if (input.empty()) // Check for valid input
inputType = INVALID;
else
{
if (input[0] >= '0' && input[0] <= '9')
{
stringstream ss(input);
ss >> cameraID;
inputType = CAMERA;
}
else
{
if (readStringList(input, imageList))
{
inputType = IMAGE_LIST;
nrFrames = (nrFrames < (int)imageList.size()) ? nrFrames : (int)imageList.size();
}
else
inputType = VIDEO_FILE;
}
if (inputType == CAMERA)
inputCapture.open(cameraID);
if (inputType == VIDEO_FILE)
inputCapture.open(input);
if (inputType != IMAGE_LIST && !inputCapture.isOpened())
inputType = INVALID;
}
if (inputType == INVALID)
{
cerr << " Inexistent input: " << input;
goodInput = false;
}
flag = 0;
if(calibFixPrincipalPoint) flag |= CV_CALIB_FIX_PRINCIPAL_POINT;
if(calibZeroTangentDist) flag |= CV_CALIB_ZERO_TANGENT_DIST;
if(aspectRatio) flag |= CV_CALIB_FIX_ASPECT_RATIO;
calibrationPattern = NOT_EXISTING;
if (!patternToUse.compare("CHESSBOARD")) calibrationPattern = CHESSBOARD;
if (!patternToUse.compare("CIRCLES_GRID")) calibrationPattern = CIRCLES_GRID;
if (!patternToUse.compare("ASYMMETRIC_CIRCLES_GRID")) calibrationPattern = ASYMMETRIC_CIRCLES_GRID;
if (calibrationPattern == NOT_EXISTING)
{
cerr << " Inexistent camera calibration mode: " << patternToUse << endl;
goodInput = false;
}
atImageList = 0;
}
Mat nextImage()
{
Mat result;
if( inputCapture.isOpened() )
{
Mat view0;
inputCapture >> view0;
view0.copyTo(result);
}
else if( atImageList < (int)imageList.size() )
result = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);
return result;
}
static bool readStringList( const string& filename, vector<string>& l )
{
l.clear();
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
FileNode n = fs.getFirstTopLevelNode();
if( n.type() != FileNode::SEQ )
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
l.push_back((string)*it);
return true;
}
public:
Size boardSize; // The size of the board -> Number of items by width and height
Pattern calibrationPattern;// One of the Chessboard, circles, or asymmetric circle pattern
float squareSize; // The size of a square in your defined unit (point, millimeter,etc).
int nrFrames; // The number of frames to use from the input for calibration
float aspectRatio; // The aspect ratio
int delay; // In case of a video input
bool bwritePoints; // Write detected feature points
bool bwriteExtrinsics; // Write extrinsic parameters
bool calibZeroTangentDist; // Assume zero tangential distortion
bool calibFixPrincipalPoint;// Fix the principal point at the center
bool flipVertical; // Flip the captured images around the horizontal axis
string outputFileName; // The name of the file where to write
bool showUndistorsed; // Show undistorted images after calibration
string input; // The input ->
int cameraID;
vector<string> imageList;
int atImageList;
VideoCapture inputCapture;
InputType inputType;
bool goodInput;
int flag;
private:
string patternToUse;
};
static void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
if(node.empty())
x = default_value;
else
x.read(node);
}
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f> > imagePoints );
int main(int argc, char* argv[])
{
help();
Settings s;
const string inputSettingsFile = argc > 1 ? argv[1] : "default.xml";
FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings
if (!fs.isOpened())
{
cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl;
return -1;
}
fs["Settings"] >> s;
fs.release(); // close Settings file
if (!s.goodInput)
{
cout << "Invalid input detected. Application stopping. " << endl;
return -1;
}
vector<vector<Point2f> > imagePoints;
Mat cameraMatrix, distCoeffs;
Size imageSize;
int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION;
clock_t prevTimestamp = 0;
const Scalar RED(0,0,255), GREEN(0,255,0);
const char ESC_KEY = 27;
for(int i = 0;;++i)
{
Mat view;
bool blinkOutput = false;
view = s.nextImage();
//----- If no more image, or got enough, then stop calibration and show result -------------
if( mode == CAPTURING && imagePoints.size() >= (unsigned)s.nrFrames )
{
if( runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints))
mode = CALIBRATED;
else
mode = DETECTION;
}
if(view.empty()) // If no more images then run calibration, save and stop loop.
{
if( imagePoints.size() > 0 )
runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints);
break;
}
imageSize = view.size(); // Format input image.
if( s.flipVertical ) flip( view, view, 0 );
vector<Point2f> pointBuf;
bool found;
switch( s.calibrationPattern ) // Find feature points on the input format
{
case Settings::CHESSBOARD:
found = findChessboardCorners( view, s.boardSize, pointBuf,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
break;
case Settings::CIRCLES_GRID:
found = findCirclesGrid( view, s.boardSize, pointBuf );
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
found = findCirclesGrid( view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID );
break;
default:
found = false;
break;
}
if ( found) // If done with success,
{
// improve the found corners' coordinate accuracy for chessboard
if( s.calibrationPattern == Settings::CHESSBOARD)
{
Mat viewGray;
cvtColor(view, viewGray, COLOR_BGR2GRAY);
cornerSubPix( viewGray, pointBuf, Size(11,11),
Size(-1,-1), TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 ));
}
if( mode == CAPTURING && // For camera only take new samples after delay time
(!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay*1e-3*CLOCKS_PER_SEC) )
{
imagePoints.push_back(pointBuf);
prevTimestamp = clock();
blinkOutput = s.inputCapture.isOpened();
}
// Draw the corners.
drawChessboardCorners( view, s.boardSize, Mat(pointBuf), found );
}
//----------------------------- Output Text ------------------------------------------------
string msg = (mode == CAPTURING) ? "100/100" :
mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
int baseLine = 0;
Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);
if( mode == CAPTURING )
{
if(s.showUndistorsed)
msg = format( "%d/%d Undist", (int)imagePoints.size(), s.nrFrames );
else
msg = format( "%d/%d", (int)imagePoints.size(), s.nrFrames );
}
putText( view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED);
if( blinkOutput )
bitwise_not(view, view);
//------------------------- Video capture output undistorted ------------------------------
if( mode == CALIBRATED && s.showUndistorsed )
{
Mat temp = view.clone();
undistort(temp, view, cameraMatrix, distCoeffs);
}
//------------------------------ Show image and check for input commands -------------------
imshow("Image View", view);
char key = (char)waitKey(s.inputCapture.isOpened() ? 50 : s.delay);
if( key == ESC_KEY )
break;
if( key == 'u' && mode == CALIBRATED )
s.showUndistorsed = !s.showUndistorsed;
if( s.inputCapture.isOpened() && key == 'g' )
{
mode = CAPTURING;
imagePoints.clear();
}
}
// -----------------------Show the undistorted image for the image list ------------------------
if( s.inputType == Settings::IMAGE_LIST && s.showUndistorsed )
{
Mat view, rview, map1, map2;
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
imageSize, CV_16SC2, map1, map2);
for(int i = 0; i < (int)s.imageList.size(); i++ )
{
view = imread(s.imageList[i], 1);
if(view.empty())
continue;
remap(view, rview, map1, map2, INTER_LINEAR);
imshow("Image View", rview);
char c = (char)waitKey();
if( c == ESC_KEY || c == 'q' || c == 'Q' )
break;
}
}
return 0;
}
static double computeReprojectionErrors( const vector<vector<Point3f> >& objectPoints,
const vector<vector<Point2f> >& imagePoints,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const Mat& cameraMatrix , const Mat& distCoeffs,
vector<float>& perViewErrors)
{
vector<Point2f> imagePoints2;
int i, totalPoints = 0;
double totalErr = 0, err;
perViewErrors.resize(objectPoints.size());
for( i = 0; i < (int)objectPoints.size(); ++i )
{
projectPoints( Mat(objectPoints[i]), rvecs[i], tvecs[i], cameraMatrix,
distCoeffs, imagePoints2);
err = norm(Mat(imagePoints[i]), Mat(imagePoints2), CV_L2);
int n = (int)objectPoints[i].size();
perViewErrors[i] = (float) std::sqrt(err*err/n);
totalErr += err*err;
totalPoints += n;
}
return std::sqrt(totalErr/totalPoints);
}
static void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f>& corners,
Settings::Pattern patternType /*= Settings::CHESSBOARD*/)
{
corners.clear();
switch(patternType)
{
case Settings::CHESSBOARD:
case Settings::CIRCLES_GRID:
for( int i = 0; i < boardSize.height; ++i )
for( int j = 0; j < boardSize.width; ++j )
corners.push_back(Point3f(float( j*squareSize ), float( i*squareSize ), 0));
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
for( int i = 0; i < boardSize.height; i++ )
for( int j = 0; j < boardSize.width; j++ )
corners.push_back(Point3f(float((2*j + i % 2)*squareSize), float(i*squareSize), 0));
break;
default:
break;
}
}
static bool runCalibration( Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f> > imagePoints, vector<Mat>& rvecs, vector<Mat>& tvecs,
vector<float>& reprojErrs, double& totalAvgErr)
{
cameraMatrix = Mat::eye(3, 3, CV_64F);
if( s.flag & CV_CALIB_FIX_ASPECT_RATIO )
cameraMatrix.at<double>(0,0) = 1.0;
distCoeffs = Mat::zeros(8, 1, CV_64F);
vector<vector<Point3f> > objectPoints(1);
calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);
objectPoints.resize(imagePoints.size(),objectPoints[0]);
//Find intrinsic and extrinsic camera parameters
double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
distCoeffs, rvecs, tvecs, s.flag|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);
cout << "Re-projection error reported by calibrateCamera: "<< rms << endl;
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
return ok;
}
// Print camera parameters to the output file
static void saveCameraParams( Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const vector<float>& reprojErrs, const vector<vector<Point2f> >& imagePoints,
double totalAvgErr )
{
FileStorage fs( s.outputFileName, FileStorage::WRITE );
time_t tm;
time( &tm );
struct tm *t2 = localtime( &tm );
char buf[1024];
strftime( buf, sizeof(buf)-1, "%c", t2 );
fs << "calibration_Time" << buf;
if( !rvecs.empty() || !reprojErrs.empty() )
fs << "nrOfFrames" << (int)std::max(rvecs.size(), reprojErrs.size());
fs << "image_Width" << imageSize.width;
fs << "image_Height" << imageSize.height;
fs << "board_Width" << s.boardSize.width;
fs << "board_Height" << s.boardSize.height;
fs << "square_Size" << s.squareSize;
if( s.flag & CV_CALIB_FIX_ASPECT_RATIO )
fs << "FixAspectRatio" << s.aspectRatio;
if( s.flag )
{
sprintf( buf, "flags: %s%s%s%s",
s.flag & CV_CALIB_USE_INTRINSIC_GUESS ? " +use_intrinsic_guess" : "",
s.flag & CV_CALIB_FIX_ASPECT_RATIO ? " +fix_aspectRatio" : "",
s.flag & CV_CALIB_FIX_PRINCIPAL_POINT ? " +fix_principal_point" : "",
s.flag & CV_CALIB_ZERO_TANGENT_DIST ? " +zero_tangent_dist" : "" );
cvWriteComment( *fs, buf, 0 );
}
fs << "flagValue" << s.flag;
fs << "Camera_Matrix" << cameraMatrix;
fs << "Distortion_Coefficients" << distCoeffs;
fs << "Avg_Reprojection_Error" << totalAvgErr;
if( !reprojErrs.empty() )
fs << "Per_View_Reprojection_Errors" << Mat(reprojErrs);
if( !rvecs.empty() && !tvecs.empty() )
{
CV_Assert(rvecs[0].type() == tvecs[0].type());
Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
for( int i = 0; i < (int)rvecs.size(); i++ )
{
Mat r = bigmat(Range(i, i+1), Range(0,3));
Mat t = bigmat(Range(i, i+1), Range(3,6));
CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
//*.t() is MatExpr (not Mat) so we can use assignment operator
r = rvecs[i].t();
t = tvecs[i].t();
}
cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
fs << "Extrinsic_Parameters" << bigmat;
}
if( !imagePoints.empty() )
{
Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
for( int i = 0; i < (int)imagePoints.size(); i++ )
{
Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
Mat imgpti(imagePoints[i]);
imgpti.copyTo(r);
}
fs << "Image_points" << imagePtMat;
}
}
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,vector<vector<Point2f> > imagePoints )
{
vector<Mat> rvecs, tvecs;
vector<float> reprojErrs;
double totalAvgErr = 0;
bool ok = runCalibration(s,imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs,
reprojErrs, totalAvgErr);
cout << (ok ? "Calibration succeeded" : "Calibration failed")
<< ". avg re projection error = " << totalAvgErr ;
if( ok )
saveCameraParams( s, imageSize, cameraMatrix, distCoeffs, rvecs ,tvecs, reprojErrs,
imagePoints, totalAvgErr);
return ok;
}
| mit |
guc-cs/Campus-Vision | opencv-1.1.0/tests/cv/src/akmeans.cpp | 9 | 8245 | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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 Intel Corporation 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 Intel Corporation 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.
//
//M*/
#include "cvtest.h"
#if 0
/* Testing parameters */
static char test_desc[] = "KMeans clustering";
static char* func_name[] =
{
"cvKMeans"
};
//based on Ara Nefian's implementation
float distance(float* vector_1, float *vector_2, int VecSize)
{
int i;
float dist;
dist = 0.0;
for (i = 0; i < VecSize; i++)
{
//printf ("%f, %f\n", vector_1[i], vector_2[i]);
dist = dist + (vector_1[i] - vector_2[i])*(vector_1[i] - vector_2[i]);
}
return dist;
}
//returns number of made iterations
int _real_kmeans( int numClusters, float **sample, int numSamples,
int VecSize, int* a_class, double eps, int iter )
{
int i, k, n;
int *counter;
float minDist;
float *dist;
float **curr_cluster;
float **prev_cluster;
float error;
//printf("* numSamples = %d, numClusters = %d, VecSize = %d\n", numSamples, numClusters, VecSize);
//memory allocation
dist = new float[numClusters];
counter = new int[numClusters];
//allocate memory for curr_cluster and prev_cluster
curr_cluster = new float*[numClusters];
prev_cluster = new float*[numClusters];
for (k = 0; k < numClusters; k++){
curr_cluster[k] = new float[VecSize];
prev_cluster[k] = new float[VecSize];
}
//pick initial cluster centers
for (k = 0; k < numClusters; k++)
{
for (n = 0; n < VecSize; n++)
{
curr_cluster[k][n] = sample[k*(numSamples/numClusters)][n];
prev_cluster[k][n] = sample[k*(numSamples/numClusters)][n];
}
}
int NumIter = 0;
error = FLT_MAX;
while ((error > eps) && (NumIter < iter))
{
NumIter++;
//printf("NumIter = %d, error = %lf, \n", NumIter, error);
//assign samples to clusters
for (i = 0; i < numSamples; i++)
{
for (k = 0; k < numClusters; k++)
{
dist[k] = distance(sample[i], curr_cluster[k], VecSize);
}
minDist = dist[0];
a_class[i] = 0;
for (k = 1; k < numClusters; k++)
{
if (dist[k] < minDist)
{
minDist = dist[k];
a_class[i] = k;
}
}
}
//reset clusters and counters
for (k = 0; k < numClusters; k++){
counter[k] = 0;
for (n = 0; n < VecSize; n++){
curr_cluster[k][n] = 0.0;
}
}
for (i = 0; i < numSamples; i++){
for (n = 0; n < VecSize; n++){
curr_cluster[a_class[i]][n] = curr_cluster[a_class[i]][n] + sample[i][n];
}
counter[a_class[i]]++;
}
for (k = 0; k < numClusters; k++){
for (n = 0; n < VecSize; n++){
curr_cluster[k][n] = curr_cluster[k][n]/(float)counter[k];
}
}
error = 0.0;
for (k = 0; k < numClusters; k++){
for (n = 0; n < VecSize; n++){
error = error + (curr_cluster[k][n] - prev_cluster[k][n])*(curr_cluster[k][n] - prev_cluster[k][n]);
}
}
//error = error/(double)(numClusters*VecSize);
//copy curr_clusters to prev_clusters
for (k = 0; k < numClusters; k++){
for (n =0; n < VecSize; n++){
prev_cluster[k][n] = curr_cluster[k][n];
}
}
}
//deallocate memory for curr_cluster and prev_cluster
for (k = 0; k < numClusters; k++){
delete curr_cluster[k];
delete prev_cluster[k];
}
delete curr_cluster;
delete prev_cluster;
delete counter;
delete dist;
return NumIter;
}
static int fmaKMeans(void)
{
CvTermCriteria crit;
float** vectors;
int* output;
int* etalon_output;
int lErrors = 0;
int lNumVect = 0;
int lVectSize = 0;
int lNumClust = 0;
int lMaxNumIter = 0;
float flEpsilon = 0;
int i,j;
static int read_param = 0;
/* Initialization global parameters */
if( !read_param )
{
read_param = 1;
/* Read test-parameters */
trsiRead( &lNumVect, "1000", "Number of vectors" );
trsiRead( &lVectSize, "10", "Number of vectors" );
trsiRead( &lNumClust, "20", "Number of clusters" );
trsiRead( &lMaxNumIter,"100","Maximal number of iterations");
trssRead( &flEpsilon, "0.5", "Accuracy" );
}
crit = cvTermCriteria( CV_TERMCRIT_EPS|CV_TERMCRIT_ITER, lMaxNumIter, flEpsilon );
//allocate vectors
vectors = (float**)cvAlloc( lNumVect * sizeof(float*) );
for( i = 0; i < lNumVect; i++ )
{
vectors[i] = (float*)cvAlloc( lVectSize * sizeof( float ) );
}
output = (int*)cvAlloc( lNumVect * sizeof(int) );
etalon_output = (int*)cvAlloc( lNumVect * sizeof(int) );
//fill input vectors
for( i = 0; i < lNumVect; i++ )
{
ats1flInitRandom( -2000, 2000, vectors[i], lVectSize );
}
/* run etalon kmeans */
/* actually it is the simpliest realization of kmeans */
int ni = _real_kmeans( lNumClust, vectors, lNumVect, lVectSize, etalon_output, crit.epsilon, crit.max_iter );
trsWrite( ATS_CON, "%d iterations done\n", ni );
/* Run OpenCV function */
#define _KMEANS_TIME 0
#if _KMEANS_TIME
//timing section
trsTimerStart(0);
__int64 tics = atsGetTickCount();
#endif
cvKMeans( lNumClust, vectors, lNumVect, lVectSize,
crit, output );
#if _KMEANS_TIME
tics = atsGetTickCount() - tics;
trsTimerStop(0);
//output result
//double dbUsecs =ATS_TICS_TO_USECS((double)tics);
trsWrite( ATS_CON, "Tics per iteration %d\n", tics/ni );
#endif
//compare results
for( j = 0; j < lNumVect; j++ )
{
if ( output[j] != etalon_output[j] )
{
lErrors++;
}
}
//free memory
for( i = 0; i < lNumVect; i++ )
{
cvFree( &(vectors[i]) );
}
cvFree(&vectors);
cvFree(&output);
cvFree(&etalon_output);
if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" );
else return trsResult( TRS_FAIL, "Detected %d errors", lErrors );
}
void InitAKMeans()
{
/* Register test function */
trsReg( func_name[0], test_desc, atsAlgoClass, fmaKMeans );
} /* InitAKMeans */
#endif
| mit |
zjutjsj1004/third | boost/libs/spirit/test/karma/symbols1.cpp | 9 | 3387 | // Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/karma_auxiliary.hpp>
#include <boost/spirit/include/karma_char.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/karma_operator.hpp>
#include <boost/spirit/include/karma_directive.hpp>
#include <boost/spirit/include/karma_generate.hpp>
#include <boost/spirit/include/karma_nonterminal.hpp>
#include "test.hpp"
namespace fusion = boost::fusion;
template <typename T>
inline std::vector<T>
make_vector(T const& t1, T const& t2)
{
std::vector<T> v;
v.push_back(t1);
v.push_back(t2);
return v;
}
int main()
{
using spirit_test::test;
using boost::spirit::karma::symbols;
{ // basics
symbols<char, std::string> sym;
sym.add
('j', "Joel")
('h', "Hartmut")
('t', "Tom")
('k', "Kim")
;
boost::mpl::true_ f =
boost::mpl::bool_<boost::spirit::traits::is_generator<
symbols<char, std::string> >::value>();
// silence stupid compiler warnings
// i.e. MSVC warning C4189: 'f' : local variable is initialized but not referenced
BOOST_TEST((f.value));
BOOST_TEST((test("Joel", sym, 'j')));
BOOST_TEST((test("Hartmut", sym, 'h')));
BOOST_TEST((test("Tom", sym, 't')));
BOOST_TEST((test("Kim", sym, 'k')));
BOOST_TEST((!test("", sym, 'x')));
// test copy
symbols<char, std::string> sym2;
sym2 = sym;
BOOST_TEST((test("Joel", sym2, 'j')));
BOOST_TEST((test("Hartmut", sym2, 'h')));
BOOST_TEST((test("Tom", sym2, 't')));
BOOST_TEST((test("Kim", sym2, 'k')));
BOOST_TEST((!test("", sym2, 'x')));
// make sure it plays well with other generators
BOOST_TEST((test("Joelyo", sym << "yo", 'j')));
sym.remove
('j')
('h')
;
BOOST_TEST((!test("", sym, 'j')));
BOOST_TEST((!test("", sym, 'h')));
}
{ // lower/upper handling
using namespace boost::spirit::ascii;
using boost::spirit::karma::lower;
using boost::spirit::karma::upper;
symbols<char, std::string> sym;
sym.add
('j', "Joel")
('h', "Hartmut")
('t', "Tom")
('k', "Kim")
;
BOOST_TEST((test("joel", lower[sym], 'j')));
BOOST_TEST((test("hartmut", lower[sym], 'h')));
BOOST_TEST((test("tom", lower[sym], 't')));
BOOST_TEST((test("kim", lower[sym], 'k')));
BOOST_TEST((test("JOEL", upper[sym], 'j')));
BOOST_TEST((test("HARTMUT", upper[sym], 'h')));
BOOST_TEST((test("TOM", upper[sym], 't')));
BOOST_TEST((test("KIM", upper[sym], 'k')));
// make sure it plays well with other generators
BOOST_TEST((test("joelyo", lower[sym] << "yo", 'j')));
BOOST_TEST((test("JOELyo", upper[sym] << "yo", 'j')));
}
return boost::report_errors();
}
| mit |
Pyroh/SwiftMark | Xcode/SwiftMark/houdini_html_u.c | 9 | 3565 | #include <assert.h>
#include <stdio.h>
#include <string.h>
#include "buffer.h"
#include "houdini.h"
#include "utf8.h"
#include "entities.inc"
/* Binary tree lookup code for entities added by JGM */
static const unsigned char *S_lookup(int i, int low, int hi,
const unsigned char *s, int len) {
int j;
int cmp =
strncmp((const char *)s, (const char *)cmark_entities[i].entity, len);
if (cmp == 0 && cmark_entities[i].entity[len] == 0) {
return (const unsigned char *)cmark_entities[i].bytes;
} else if (cmp < 0 && i > low) {
j = i - ((i - low) / 2);
if (j == i)
j -= 1;
return S_lookup(j, low, i - 1, s, len);
} else if (cmp > 0 && i < hi) {
j = i + ((hi - i) / 2);
if (j == i)
j += 1;
return S_lookup(j, i + 1, hi, s, len);
} else {
return NULL;
}
}
static const unsigned char *S_lookup_entity(const unsigned char *s, int len) {
return S_lookup(CMARK_NUM_ENTITIES / 2, 0, CMARK_NUM_ENTITIES - 1, s, len);
}
bufsize_t houdini_unescape_ent(cmark_strbuf *ob, const uint8_t *src,
bufsize_t size) {
bufsize_t i = 0;
if (size >= 3 && src[0] == '#') {
int codepoint = 0;
int num_digits = 0;
if (_isdigit(src[1])) {
for (i = 1; i < size && _isdigit(src[i]); ++i) {
codepoint = (codepoint * 10) + (src[i] - '0');
if (codepoint >= 0x110000) {
// Keep counting digits but
// avoid integer overflow.
codepoint = 0x110000;
}
}
num_digits = i - 1;
}
else if (src[1] == 'x' || src[1] == 'X') {
for (i = 2; i < size && _isxdigit(src[i]); ++i) {
codepoint = (codepoint * 16) + ((src[i] | 32) % 39 - 9);
if (codepoint >= 0x110000) {
// Keep counting digits but
// avoid integer overflow.
codepoint = 0x110000;
}
}
num_digits = i - 2;
}
if (num_digits >= 1 && num_digits <= 8 && i < size && src[i] == ';') {
if (codepoint == 0 || (codepoint >= 0xD800 && codepoint < 0xE000) ||
codepoint >= 0x110000) {
codepoint = 0xFFFD;
}
cmark_utf8proc_encode_char(codepoint, ob);
return i + 1;
}
}
else {
if (size > CMARK_ENTITY_MAX_LENGTH)
size = CMARK_ENTITY_MAX_LENGTH;
for (i = CMARK_ENTITY_MIN_LENGTH; i < size; ++i) {
if (src[i] == ' ')
break;
if (src[i] == ';') {
const unsigned char *entity = S_lookup_entity(src, i);
if (entity != NULL) {
cmark_strbuf_puts(ob, (const char *)entity);
return i + 1;
}
break;
}
}
}
return 0;
}
int houdini_unescape_html(cmark_strbuf *ob, const uint8_t *src,
bufsize_t size) {
bufsize_t i = 0, org, ent;
while (i < size) {
org = i;
while (i < size && src[i] != '&')
i++;
if (likely(i > org)) {
if (unlikely(org == 0)) {
if (i >= size)
return 0;
cmark_strbuf_grow(ob, HOUDINI_UNESCAPED_SIZE(size));
}
cmark_strbuf_put(ob, src + org, i - org);
}
/* escaping */
if (i >= size)
break;
i++;
ent = houdini_unescape_ent(ob, src + i, size - i);
i += ent;
/* not really an entity */
if (ent == 0)
cmark_strbuf_putc(ob, '&');
}
return 1;
}
void houdini_unescape_html_f(cmark_strbuf *ob, const uint8_t *src,
bufsize_t size) {
if (!houdini_unescape_html(ob, src, size))
cmark_strbuf_put(ob, src, size);
}
| mit |
TukekeSoft/jacos2d-x | src/cocos2dx/actions/CCActionPageTurn3D.cpp | 10 | 3754 | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/
http://www.cocos2d-x.org
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 "CCActionPageTurn3D.h"
#include "cocoa/CCZone.h"
NS_CC_BEGIN
CCPageTurn3D* CCPageTurn3D::actionWithSize(const ccGridSize& gridSize, float time)
{
return CCPageTurn3D::create(gridSize, time);
}
CCPageTurn3D* CCPageTurn3D::create(const ccGridSize& gridSize, float time)
{
CCPageTurn3D *pAction = new CCPageTurn3D();
if (pAction)
{
if (pAction->initWithSize(gridSize, time))
{
pAction->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(pAction);
}
}
return pAction;
}
/*
* Update each tick
* Time is the percentage of the way through the duration
*/
void CCPageTurn3D::update(float time)
{
float tt = MAX(0, time - 0.25f);
float deltaAy = (tt * tt * 500);
float ay = -100 - deltaAy;
float deltaTheta = - (float) M_PI_2 * sqrtf( time) ;
float theta = /*0.01f */ + (float) M_PI_2 +deltaTheta;
float sinTheta = sinf(theta);
float cosTheta = cosf(theta);
for (int i = 0; i <= m_sGridSize.x; ++i)
{
for (int j = 0; j <= m_sGridSize.y; ++j)
{
// Get original vertex
ccVertex3F p = originalVertex(ccg(i ,j));
float R = sqrtf((p.x * p.x) + ((p.y - ay) * (p.y - ay)));
float r = R * sinTheta;
float alpha = asinf( p.x / R );
float beta = alpha / sinTheta;
float cosBeta = cosf( beta );
// If beta > PI then we've wrapped around the cone
// Reduce the radius to stop these points interfering with others
if (beta <= M_PI)
{
p.x = ( r * sinf(beta));
}
else
{
// Force X = 0 to stop wrapped
// points
p.x = 0;
}
p.y = ( R + ay - ( r * (1 - cosBeta) * sinTheta));
// We scale z here to avoid the animation being
// too much bigger than the screen due to perspective transform
p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7;// "100" didn't work for
// Stop z coord from dropping beneath underlying page in a transition
// issue #751
if( p.z < 0.5f )
{
p.z = 0.5f;
}
// Set new coords
setVertex(ccg(i, j), p);
}
}
}
NS_CC_END
| mit |
8l/barrelfish | lib/phoenix/processor.c | 11 | 4429 | /* Copyright (c) 2007-2009, Stanford University
* 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 Stanford University nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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.
*/
/* OS specific headers and defines. */
#ifdef _LINUX_
#define _GNU_SOURCE
#include <sched.h>
#elif defined (_SOLARIS_)
#include <sys/procset.h>
#include <sys/processor.h>
#include <sys/lgrp_user.h>
#elif defined (BARRELFISH)
#else
#error OS not supported
#endif
#include <stdlib.h>
#include <sys/types.h>
#include <assert.h>
#include "processor.h"
#include "memory.h"
int num_cpus = 2;
/* Query the number of CPUs online. */
int proc_get_num_cpus (void)
{
return num_cpus;
/* int num_cpus; */
/* char *num_proc_str; */
/* num_cpus = sysconf(_SC_NPROCESSORS_ONLN); */
/* /\* Check if the user specified a different number of processors. *\/ */
/* if ((num_proc_str = getenv("MAPRED_NPROCESSORS"))) */
/* { */
/* int temp = atoi(num_proc_str); */
/* if (temp < 1 || temp > num_cpus) */
/* num_cpus = 0; */
/* else */
/* num_cpus = temp; */
/* } */
/* return num_cpus; */
}
#ifdef _LINUX_
static cpu_set_t full_cs;
static cpu_set_t* proc_get_full_set(void)
{
static int inited = 0;
if (inited == 0) {
int i;
int n_cpus;
CPU_ZERO (&full_cs);
n_cpus = sysconf(_SC_NPROCESSORS_ONLN);
for (i = 0; i < n_cpus; i++) {
CPU_SET(i, &full_cs);
}
inited = 1;
}
return &full_cs;
}
#endif
/* Bind the calling thread to run on CPU_ID.
Returns 0 if successful, -1 if failed. */
int proc_bind_thread (int cpu_id)
{
#ifdef _LINUX_
cpu_set_t cpu_set;
CPU_ZERO (&cpu_set);
CPU_SET (cpu_id, &cpu_set);
return sched_setaffinity (0, sizeof (cpu_set), &cpu_set);
#elif defined (_SOLARIS_)
return processor_bind (P_LWPID, P_MYID, cpu_id, NULL);
#elif defined (BARRELFISH)
return 0;
#endif
}
int proc_unbind_thread ()
{
#ifdef _LINUX_
return sched_setaffinity (0, sizeof (cpu_set_t), proc_get_full_set());
#elif defined (_SOLARIS_)
return processor_bind (P_LWPID, P_MYID, PBIND_NONE, NULL);
#elif defined (BARRELFISH)
return 0;
#endif
}
/* Test whether processor CPU_ID is available. */
bool proc_is_available (int cpu_id)
{
#ifdef _LINUX_
int ret;
cpu_set_t cpu_set;
ret = sched_getaffinity (0, sizeof (cpu_set), &cpu_set);
if (ret < 0) return false;
return CPU_ISSET (cpu_id, &cpu_set) ? true : false;
#elif defined (_SOLARIS_)
return (p_online (cpu_id, P_STATUS) == P_ONLINE);
#elif defined (BARRELFISH)
return true;
#endif
}
int proc_get_cpuid (void)
{
#ifdef _LINUX_
int i, ret;
cpu_set_t cpu_set;
ret = sched_getaffinity (0, sizeof (cpu_set), &cpu_set);
if (ret < 0) return -1;
for (i = 0; i < CPU_SETSIZE; ++i)
{
if (CPU_ISSET (i, &cpu_set)) break;
}
return i;
#elif defined (_SOLARIS_)
return getcpuid ();
#elif defined (BARRELFISH)
return disp_get_core_id();
#endif
}
| mit |
tempbottle/libpomelo2 | deps/openssl/openssl/demos/state_machine/state_machine.c | 267 | 11016 | /* ====================================================================
* Copyright (c) 2000 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
* openssl-core@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).
*
*/
/*
* Nuron, a leader in hardware encryption technology, generously
* sponsored the development of this demo by Ben Laurie.
*
* See http://www.nuron.com/.
*/
/*
* the aim of this demo is to provide a fully working state-machine
* style SSL implementation, i.e. one where the main loop acquires
* some data, then converts it from or to SSL by feeding it into the
* SSL state machine. It then does any I/O required by the state machine
* and loops.
*
* In order to keep things as simple as possible, this implementation
* listens on a TCP socket, which it expects to get an SSL connection
* on (for example, from s_client) and from then on writes decrypted
* data to stdout and encrypts anything arriving on stdin. Verbose
* commentary is written to stderr.
*
* This implementation acts as a server, but it can also be done for a client. */
#include <openssl/ssl.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <openssl/err.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* die_unless is intended to work like assert, except that it happens
always, even if NDEBUG is defined. Use assert as a stopgap. */
#define die_unless(x) assert(x)
typedef struct
{
SSL_CTX *pCtx;
BIO *pbioRead;
BIO *pbioWrite;
SSL *pSSL;
} SSLStateMachine;
void SSLStateMachine_print_error(SSLStateMachine *pMachine,const char *szErr)
{
unsigned long l;
fprintf(stderr,"%s\n",szErr);
while((l=ERR_get_error()))
{
char buf[1024];
ERR_error_string_n(l,buf,sizeof buf);
fprintf(stderr,"Error %lx: %s\n",l,buf);
}
}
SSLStateMachine *SSLStateMachine_new(const char *szCertificateFile,
const char *szKeyFile)
{
SSLStateMachine *pMachine=malloc(sizeof *pMachine);
int n;
die_unless(pMachine);
pMachine->pCtx=SSL_CTX_new(SSLv23_server_method());
die_unless(pMachine->pCtx);
n=SSL_CTX_use_certificate_file(pMachine->pCtx,szCertificateFile,
SSL_FILETYPE_PEM);
die_unless(n > 0);
n=SSL_CTX_use_PrivateKey_file(pMachine->pCtx,szKeyFile,SSL_FILETYPE_PEM);
die_unless(n > 0);
pMachine->pSSL=SSL_new(pMachine->pCtx);
die_unless(pMachine->pSSL);
pMachine->pbioRead=BIO_new(BIO_s_mem());
pMachine->pbioWrite=BIO_new(BIO_s_mem());
SSL_set_bio(pMachine->pSSL,pMachine->pbioRead,pMachine->pbioWrite);
SSL_set_accept_state(pMachine->pSSL);
return pMachine;
}
void SSLStateMachine_read_inject(SSLStateMachine *pMachine,
const unsigned char *aucBuf,int nBuf)
{
int n=BIO_write(pMachine->pbioRead,aucBuf,nBuf);
/* If it turns out this assert fails, then buffer the data here
* and just feed it in in churn instead. Seems to me that it
* should be guaranteed to succeed, though.
*/
assert(n == nBuf);
fprintf(stderr,"%d bytes of encrypted data fed to state machine\n",n);
}
int SSLStateMachine_read_extract(SSLStateMachine *pMachine,
unsigned char *aucBuf,int nBuf)
{
int n;
if(!SSL_is_init_finished(pMachine->pSSL))
{
fprintf(stderr,"Doing SSL_accept\n");
n=SSL_accept(pMachine->pSSL);
if(n == 0)
fprintf(stderr,"SSL_accept returned zero\n");
if(n < 0)
{
int err;
if((err=SSL_get_error(pMachine->pSSL,n)) == SSL_ERROR_WANT_READ)
{
fprintf(stderr,"SSL_accept wants more data\n");
return 0;
}
SSLStateMachine_print_error(pMachine,"SSL_accept error");
exit(7);
}
return 0;
}
n=SSL_read(pMachine->pSSL,aucBuf,nBuf);
if(n < 0)
{
int err=SSL_get_error(pMachine->pSSL,n);
if(err == SSL_ERROR_WANT_READ)
{
fprintf(stderr,"SSL_read wants more data\n");
return 0;
}
SSLStateMachine_print_error(pMachine,"SSL_read error");
exit(8);
}
fprintf(stderr,"%d bytes of decrypted data read from state machine\n",n);
return n;
}
int SSLStateMachine_write_can_extract(SSLStateMachine *pMachine)
{
int n=BIO_pending(pMachine->pbioWrite);
if(n)
fprintf(stderr,"There is encrypted data available to write\n");
else
fprintf(stderr,"There is no encrypted data available to write\n");
return n;
}
int SSLStateMachine_write_extract(SSLStateMachine *pMachine,
unsigned char *aucBuf,int nBuf)
{
int n;
n=BIO_read(pMachine->pbioWrite,aucBuf,nBuf);
fprintf(stderr,"%d bytes of encrypted data read from state machine\n",n);
return n;
}
void SSLStateMachine_write_inject(SSLStateMachine *pMachine,
const unsigned char *aucBuf,int nBuf)
{
int n=SSL_write(pMachine->pSSL,aucBuf,nBuf);
/* If it turns out this assert fails, then buffer the data here
* and just feed it in in churn instead. Seems to me that it
* should be guaranteed to succeed, though.
*/
assert(n == nBuf);
fprintf(stderr,"%d bytes of unencrypted data fed to state machine\n",n);
}
int OpenSocket(int nPort)
{
int nSocket;
struct sockaddr_in saServer;
struct sockaddr_in saClient;
int one=1;
int nSize;
int nFD;
int nLen;
nSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(nSocket < 0)
{
perror("socket");
exit(1);
}
if(setsockopt(nSocket,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof one) < 0)
{
perror("setsockopt");
exit(2);
}
memset(&saServer,0,sizeof saServer);
saServer.sin_family=AF_INET;
saServer.sin_port=htons(nPort);
nSize=sizeof saServer;
if(bind(nSocket,(struct sockaddr *)&saServer,nSize) < 0)
{
perror("bind");
exit(3);
}
if(listen(nSocket,512) < 0)
{
perror("listen");
exit(4);
}
nLen=sizeof saClient;
nFD=accept(nSocket,(struct sockaddr *)&saClient,&nLen);
if(nFD < 0)
{
perror("accept");
exit(5);
}
fprintf(stderr,"Incoming accepted on port %d\n",nPort);
return nFD;
}
int main(int argc,char **argv)
{
SSLStateMachine *pMachine;
int nPort;
int nFD;
const char *szCertificateFile;
const char *szKeyFile;
char rbuf[1];
int nrbuf=0;
if(argc != 4)
{
fprintf(stderr,"%s <port> <certificate file> <key file>\n",argv[0]);
exit(6);
}
nPort=atoi(argv[1]);
szCertificateFile=argv[2];
szKeyFile=argv[3];
SSL_library_init();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ERR_load_crypto_strings();
nFD=OpenSocket(nPort);
pMachine=SSLStateMachine_new(szCertificateFile,szKeyFile);
for( ; ; )
{
fd_set rfds,wfds;
unsigned char buf[1024];
int n;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
/* Select socket for input */
FD_SET(nFD,&rfds);
/* check whether there's decrypted data */
if(!nrbuf)
nrbuf=SSLStateMachine_read_extract(pMachine,rbuf,1);
/* if there's decrypted data, check whether we can write it */
if(nrbuf)
FD_SET(1,&wfds);
/* Select socket for output */
if(SSLStateMachine_write_can_extract(pMachine))
FD_SET(nFD,&wfds);
/* Select stdin for input */
FD_SET(0,&rfds);
/* Wait for something to do something */
n=select(nFD+1,&rfds,&wfds,NULL,NULL);
assert(n > 0);
/* Socket is ready for input */
if(FD_ISSET(nFD,&rfds))
{
n=read(nFD,buf,sizeof buf);
if(n == 0)
{
fprintf(stderr,"Got EOF on socket\n");
exit(0);
}
assert(n > 0);
SSLStateMachine_read_inject(pMachine,buf,n);
}
/* stdout is ready for output (and hence we have some to send it) */
if(FD_ISSET(1,&wfds))
{
assert(nrbuf == 1);
buf[0]=rbuf[0];
nrbuf=0;
n=SSLStateMachine_read_extract(pMachine,buf+1,sizeof buf-1);
if(n < 0)
{
SSLStateMachine_print_error(pMachine,"read extract failed");
break;
}
assert(n >= 0);
++n;
if(n > 0) /* FIXME: has to be true now */
{
int w;
w=write(1,buf,n);
/* FIXME: we should push back any unwritten data */
assert(w == n);
}
}
/* Socket is ready for output (and therefore we have output to send) */
if(FD_ISSET(nFD,&wfds))
{
int w;
n=SSLStateMachine_write_extract(pMachine,buf,sizeof buf);
assert(n > 0);
w=write(nFD,buf,n);
/* FIXME: we should push back any unwritten data */
assert(w == n);
}
/* Stdin is ready for input */
if(FD_ISSET(0,&rfds))
{
n=read(0,buf,sizeof buf);
if(n == 0)
{
fprintf(stderr,"Got EOF on stdin\n");
exit(0);
}
assert(n > 0);
SSLStateMachine_write_inject(pMachine,buf,n);
}
}
/* not reached */
return 0;
}
| mit |
pombredanne/duktape | api-testcases/test-get-length.c | 15 | 2461 | /*===
top: 19
index 0: length 3
index 1: length 4
index 2: length 0
index 3: length 123
index 4: length 0
index 5: length 123
index 6: length 0
index 7: length 0
index 8: length 4294967295
index 9: length 0
index 10: length 0
index 11: length 0
index 12: length 0
index 13: length 1234
index 14: length 2345
index 15: length 0
index 16: length 0
index 17: length 0
index 18: length 0
===*/
void test(duk_context *ctx) {
duk_idx_t i, n;
/* 0 */
duk_push_string(ctx, "foo");
/* 1 */
duk_push_string(ctx, "\xe1\x88\xb4xyz"); /* 4 chars, first char utf-8 encoded U+1234 */
/* 2 */
duk_push_object(ctx); /* no length property */
/* 3 */
duk_push_object(ctx); /* length: 123 */
duk_push_int(ctx, 123);
duk_put_prop_string(ctx, -2, "length");
/* 4 */
duk_push_object(ctx); /* length: "bar" */
duk_push_string(ctx, "bar");
duk_put_prop_string(ctx, -2, "length");
/* 5 */
duk_push_object(ctx); /* length: 123.9, fractional number */
duk_push_number(ctx, 123.9);
duk_put_prop_string(ctx, -2, "length");
/* 6 */
duk_push_object(ctx); /* length: negative but within 32-bit range after ToInteger() */
duk_push_number(ctx, -0.9);
duk_put_prop_string(ctx, -2, "length");
/* 7 */
duk_push_object(ctx); /* length: negative, outside 32-bit range */
duk_push_number(ctx, -1);
duk_put_prop_string(ctx, -2, "length");
/* 8 */
duk_push_object(ctx); /* length: outside 32-bit range but within range after ToInteger() */
duk_push_number(ctx, 4294967295.9);
duk_put_prop_string(ctx, -2, "length");
/* 9 */
duk_push_object(ctx); /* length: outside 32-bit range */
duk_push_number(ctx, 4294967296);
duk_put_prop_string(ctx, -2, "length");
/* 10 */
duk_push_object(ctx); /* length: nan */
duk_push_nan(ctx);
duk_put_prop_string(ctx, -2, "length");
/* 11 */
duk_push_object(ctx); /* length: +Infinity */
duk_push_number(ctx, INFINITY);
duk_put_prop_string(ctx, -2, "length");
/* 12 */
duk_push_object(ctx); /* length: -Infinity */
duk_push_number(ctx, -INFINITY);
duk_put_prop_string(ctx, -2, "length");
/* 13 */
duk_push_fixed_buffer(ctx, 1234);
/* 14 */
duk_push_dynamic_buffer(ctx, 2345);
/* 15 */
duk_push_undefined(ctx);
/* 16 */
duk_push_null(ctx);
/* 17 */
duk_push_true(ctx);
/* 18 */
duk_push_false(ctx);
n = duk_get_top(ctx);
printf("top: %ld\n", (long) n);
for (i = 0; i < n; i++) {
printf("index %ld: length %lu\n", (long) i,
(unsigned long) duk_get_length(ctx, i));
}
}
| mit |
bhavindarji/STM32F4-Dev | Project_Templates/stm32f4_bsp_template_v2/Drivers/CMSIS/DSP_Lib/Source/ControllerFunctions/arm_pid_init_f32.c | 16 | 3316 | /* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 12. March 2014
* $Revision: V1.4.4
*
* Project: CMSIS DSP Library
* Title: arm_pid_init_f32.c
*
* Description: Floating-point PID Control initialization function
*
*
* 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"
/**
* @addtogroup PID
* @{
*/
/**
* @brief Initialization function for the floating-point PID Control.
* @param[in,out] *S points to an instance of the PID structure.
* @param[in] resetStateFlag flag to reset the state. 0 = no change in state & 1 = reset the state.
* @return none.
* \par Description:
* \par
* The <code>resetStateFlag</code> specifies whether to set state to zero or not. \n
* The function computes the structure fields: <code>A0</code>, <code>A1</code> <code>A2</code>
* using the proportional gain( \c Kp), integral gain( \c Ki) and derivative gain( \c Kd)
* also sets the state variables to all zeros.
*/
void arm_pid_init_f32(
arm_pid_instance_f32 * S,
int32_t resetStateFlag)
{
/* Derived coefficient A0 */
S->A0 = S->Kp + S->Ki + S->Kd;
/* Derived coefficient A1 */
S->A1 = (-S->Kp) - ((float32_t) 2.0 * S->Kd);
/* Derived coefficient A2 */
S->A2 = S->Kd;
/* Check whether state needs reset or not */
if(resetStateFlag)
{
/* Clear the state buffer. The size will be always 3 samples */
memset(S->state, 0, 3u * sizeof(float32_t));
}
}
/**
* @} end of PID group
*/
| mit |
John3/Torque3D | Engine/lib/sdl/test/testrendertarget.c | 16 | 9736 | /*
Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
typedef struct {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *background;
SDL_Texture *sprite;
SDL_Rect sprite_rect;
int scale_direction;
} DrawState;
DrawState *drawstates;
int done;
SDL_bool test_composite = SDL_FALSE;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
SDL_Texture *
LoadTexture(SDL_Renderer *renderer, char *file, SDL_bool transparent)
{
SDL_Surface *temp;
SDL_Texture *texture;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return NULL;
}
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
}
/* Create textures from the image */
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return NULL;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return texture;
}
SDL_bool
DrawComposite(DrawState *s)
{
SDL_Rect viewport, R;
SDL_Texture *target;
static SDL_bool blend_tested = SDL_FALSE;
if (!blend_tested) {
SDL_Texture *A, *B;
Uint32 P;
A = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1, 1);
SDL_SetTextureBlendMode(A, SDL_BLENDMODE_BLEND);
B = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1, 1);
SDL_SetTextureBlendMode(B, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(s->renderer, A);
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x80);
SDL_RenderFillRect(s->renderer, NULL);
SDL_SetRenderTarget(s->renderer, B);
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderFillRect(s->renderer, NULL);
SDL_RenderCopy(s->renderer, A, NULL, NULL);
SDL_RenderReadPixels(s->renderer, NULL, SDL_PIXELFORMAT_ARGB8888, &P, sizeof(P));
SDL_Log("Blended pixel: 0x%8.8X\n", P);
SDL_DestroyTexture(A);
SDL_DestroyTexture(B);
blend_tested = SDL_TRUE;
}
SDL_RenderGetViewport(s->renderer, &viewport);
target = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, viewport.w, viewport.h);
SDL_SetTextureBlendMode(target, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(s->renderer, target);
/* Draw the background.
This is solid black so when the sprite is copied to it, any per-pixel alpha will be blended through.
*/
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderFillRect(s->renderer, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopy(s->renderer, s->sprite, NULL, &s->sprite_rect);
SDL_SetRenderTarget(s->renderer, NULL);
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
SDL_SetRenderDrawBlendMode(s->renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(s->renderer, 0xff, 0x00, 0x00, 0x80);
R.x = 0;
R.y = 0;
R.w = 100;
R.h = 100;
SDL_RenderFillRect(s->renderer, &R);
SDL_SetRenderDrawBlendMode(s->renderer, SDL_BLENDMODE_NONE);
SDL_RenderCopy(s->renderer, target, NULL, NULL);
SDL_DestroyTexture(target);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
return SDL_TRUE;
}
SDL_bool
Draw(DrawState *s)
{
SDL_Rect viewport;
SDL_Texture *target;
SDL_RenderGetViewport(s->renderer, &viewport);
target = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, viewport.w, viewport.h);
if (!target) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create render target texture: %s\n", SDL_GetError());
return SDL_FALSE;
}
SDL_SetRenderTarget(s->renderer, target);
/* Draw the background */
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopy(s->renderer, s->sprite, NULL, &s->sprite_rect);
SDL_SetRenderTarget(s->renderer, NULL);
SDL_RenderCopy(s->renderer, target, NULL, NULL);
SDL_DestroyTexture(target);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
return SDL_TRUE;
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
if (test_composite) {
if (!DrawComposite(&drawstates[i])) done = 1;
} else {
if (!Draw(&drawstates[i])) done = 1;
}
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
int frames;
Uint32 then, now;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--composite") == 0) {
test_composite = SDL_TRUE;
consumed = 1;
}
}
if (consumed < 0) {
SDL_Log("Usage: %s %s [--composite]\n",
argv[0], SDLTest_CommonUsage(state));
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
drawstates = SDL_stack_alloc(DrawState, state->num_windows);
for (i = 0; i < state->num_windows; ++i) {
DrawState *drawstate = &drawstates[i];
drawstate->window = state->windows[i];
drawstate->renderer = state->renderers[i];
if (test_composite) {
drawstate->sprite = LoadTexture(drawstate->renderer, "icon-alpha.bmp", SDL_TRUE);
} else {
drawstate->sprite = LoadTexture(drawstate->renderer, "icon.bmp", SDL_TRUE);
}
drawstate->background = LoadTexture(drawstate->renderer, "sample.bmp", SDL_FALSE);
if (!drawstate->sprite || !drawstate->background) {
quit(2);
}
SDL_QueryTexture(drawstate->sprite, NULL, NULL,
&drawstate->sprite_rect.w, &drawstate->sprite_rect.h);
drawstate->scale_direction = 1;
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
SDL_stack_free(drawstates);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| mit |
zhangfengthu/CoRunBench | leukocyte/meschach_lib/fmacheps.c | 16 | 1400 |
/**************************************************************************
**
** Copyright (C) 1993 David E. Steward & Zbigniew Leyk, all rights reserved.
**
** Meschach Library
**
** This Meschach Library is provided "as is" without any express
** or implied warranty of any kind with respect to this software.
** In particular the authors shall not be liable for any direct,
** indirect, special, incidental or consequential damages arising
** in any way from use of the software.
**
** Everyone is granted permission to copy, modify and redistribute this
** Meschach Library, provided:
** 1. All copies contain this copyright notice.
** 2. All modified copies shall carry a notice stating who
** made the last modification and the date of such modification.
** 3. No charge is made for this software or works derived from it.
** This clause shall not be construed as constraining other software
** distributed on the same medium as this software, nor is a
** distribution fee considered a charge.
**
***************************************************************************/
#include <stdio.h>
double fclean(x)
double x;
{
static float y;
y = x;
return y; /* prevents optimisation */
}
main()
{
static float feps, feps1, ftmp;
feps = 1.0;
while ( fclean(1.0+feps) > 1.0 )
feps = 0.5*feps;
printf("%g\n", 2.0*feps);
}
| mit |
tinybearc/sdkbox-vungle-sample | js/frameworks/cocos2d-x/cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp | 17 | 14130 | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "cddandroidAndroidJavaEngine.h"
#include <stdlib.h>
#include <android/log.h>
#include <jni.h>
#include <sys/system_properties.h>
#include "platform/android/jni/JniHelper.h"
#include "ccdandroidUtils.h"
#include "audio/include/AudioEngine.h"
// logging
#define LOG_TAG "cocosdenshion::android::AndroidJavaEngine"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
// Java class
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
using namespace cocos2d::experimental;
using namespace CocosDenshion::android;
static inline bool getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo,
const char *methodName,
const char *paramCode) {
return cocos2d::JniHelper::getStaticMethodInfo(methodinfo,
CLASS_NAME,
methodName,
paramCode);
}
AndroidJavaEngine::AndroidJavaEngine()
: _implementBaseOnAudioEngine(false)
, _effectVolume(1.f)
{
char sdk_ver_str[PROP_VALUE_MAX] = "0";
auto len = __system_property_get("ro.build.version.sdk", sdk_ver_str);
if (len > 0)
{
auto sdk_ver = atoi(sdk_ver_str);
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d", "android build version:%d", sdk_ver);
if (sdk_ver == 21)
{
_implementBaseOnAudioEngine = true;
}
}
else
{
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d", "%s", "Fail to get android build version.");
}
}
AndroidJavaEngine::~AndroidJavaEngine() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "end", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::preloadBackgroundMusic(const char* filePath) {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
// void playBackgroundMusic(String,boolean)
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "preloadBackgroundMusic", "(Ljava/lang/String;)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::playBackgroundMusic(const char* filePath, bool loop) {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "playBackgroundMusic", "(Ljava/lang/String;Z)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg, loop);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::stopBackgroundMusic(bool releaseData) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::pauseBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::resumeBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::rewindBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "rewindBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
bool AndroidJavaEngine::willPlayBackgroundMusic() {
return true;
}
bool AndroidJavaEngine::isBackgroundMusicPlaying() {
cocos2d::JniMethodInfo methodInfo;
jboolean ret = false;
if (!getJNIStaticMethodInfo(methodInfo, "isBackgroundMusicPlaying", "()Z")) {
return ret;
}
ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
float AndroidJavaEngine::getBackgroundMusicVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (!getJNIStaticMethodInfo(methodInfo, "getBackgroundMusicVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
void AndroidJavaEngine::setBackgroundMusicVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "setBackgroundMusicVolume", "(F)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static float _jni_getEffectsVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (!getJNIStaticMethodInfo(methodInfo, "getEffectsVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
static void _jni_setEffectsVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "setEffectsVolume", "(F)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static unsigned int _jni_playEffect(const char* filePath, bool loop, float pitch, float pan, float gain)
{
cocos2d::JniMethodInfo methodInfo;
int ret = 0;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
if (!getJNIStaticMethodInfo(methodInfo, "playEffect", "(Ljava/lang/String;ZFFF)I")) {
return ret;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID,
methodInfo.methodID,
stringArg,
loop,
pitch, pan, gain);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return (unsigned int)ret;
}
static void _jni_pauseEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_pauseAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_resumeEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_resumeAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_stopEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_stopAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void loadEffect(const char* filePath, char* loadEffectName) {
cocos2d::JniMethodInfo methodInfo;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
if (!cocos2d::JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, loadEffectName, "(Ljava/lang/String;)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_preloadEffect(const char* filePath) {
loadEffect(filePath, "preloadEffect");
}
static void _jni_unloadEffect(const char* filePath) {
loadEffect(filePath, "unloadEffect");
}
float AndroidJavaEngine::getEffectsVolume()
{
if (_implementBaseOnAudioEngine)
{
return _effectVolume;
}
else
{
return _jni_getEffectsVolume();
}
}
void AndroidJavaEngine::setEffectsVolume(float volume)
{
if (_implementBaseOnAudioEngine)
{
if (volume > 1.f)
{
volume = 1.f;
}
else if (volume < 0.f)
{
volume = 0.f;
}
if (_effectVolume != volume)
{
_effectVolume = volume;
for (auto it : _soundIDs)
{
AudioEngine::setVolume(it, volume);
}
}
}
else
{
_jni_setEffectsVolume(volume);
}
}
unsigned int AndroidJavaEngine::playEffect(const char* filePath, bool loop,
float pitch, float pan, float gain)
{
if (_implementBaseOnAudioEngine)
{
auto soundID = AudioEngine::play2d(filePath, loop, _effectVolume);
if (soundID != AudioEngine::INVALID_AUDIO_ID)
{
_soundIDs.push_back(soundID);
AudioEngine::setFinishCallback(soundID, [this](int id, const std::string& filePath){
_soundIDs.remove(id);
});
}
return soundID;
}
else
{
return _jni_playEffect(filePath, loop, pitch, pan, gain);
}
}
void AndroidJavaEngine::pauseEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::pause(soundID);
}
else
{
_jni_pauseEffect(soundID);
}
}
void AndroidJavaEngine::resumeEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::resume(soundID);
}
else
{
_jni_resumeEffect(soundID);
}
}
void AndroidJavaEngine::stopEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::stop(soundID);
_soundIDs.remove(soundID);
}
else
{
_jni_stopEffect(soundID);
}
}
void AndroidJavaEngine::pauseAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto it : _soundIDs)
{
AudioEngine::pause(it);
}
}
else
{
_jni_pauseAllEffects();
}
}
void AndroidJavaEngine::resumeAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto it : _soundIDs)
{
AudioEngine::resume(it);
}
}
else
{
_jni_resumeAllEffects();
}
}
void AndroidJavaEngine::stopAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto it : _soundIDs)
{
AudioEngine::stop(it);
}
_soundIDs.clear();
}
else
{
_jni_stopAllEffects();
}
}
void AndroidJavaEngine::preloadEffect(const char* filePath)
{
if (!_implementBaseOnAudioEngine)
{
_jni_preloadEffect(filePath);
}
}
void AndroidJavaEngine::unloadEffect(const char* filePath)
{
if (!_implementBaseOnAudioEngine)
{
_jni_unloadEffect(filePath);
}
}
| mit |
Will-of-the-Wisp/Torque3D | Engine/source/T3D/physics/physicsUserData.cpp | 18 | 1437 | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "T3D/physics/physicsUserData.h"
#ifdef TORQUE_DEBUG
const char* PhysicsUserData::smTypeName = "PhysicsUserData";
#endif
| mit |
Nau3D/nau | contrib/freeglut-3.0.0/src/fg_state.c | 19 | 11020 | /*
* fg_state.c
*
* Freeglut state query methods.
*
* Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
* Written by Pawel W. Olszta, <olszta@sourceforge.net>
* Creation date: Thu Dec 16 1999
*
* 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
* PAWEL W. OLSZTA 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 <GL/freeglut.h>
#include "fg_internal.h"
/*
* TODO BEFORE THE STABLE RELEASE:
*
* glutGet() -- X11 tests passed, but check if all enums
* handled (what about Win32?)
* glutDeviceGet() -- X11 tests passed, but check if all enums
* handled (what about Win32?)
* glutGetModifiers() -- OK, but could also remove the limitation
* glutLayerGet() -- what about GLUT_NORMAL_DAMAGED?
*
* The fail-on-call policy will help adding the most needed things imho.
*/
extern int fgPlatformGlutGet ( GLenum eWhat );
extern int fgPlatformGlutDeviceGet ( GLenum eWhat );
extern int *fgPlatformGlutGetModeValues(GLenum eWhat, int *size);
extern SFG_Font* fghFontByID( void* font );
/* -- LOCAL DEFINITIONS ---------------------------------------------------- */
/* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
/* -- INTERFACE FUNCTIONS -------------------------------------------------- */
/*
* General settings assignment method
*/
void FGAPIENTRY glutSetOption( GLenum eWhat, int value )
{
FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetOption" );
switch( eWhat )
{
case GLUT_INIT_WINDOW_X:
fgState.Position.X = (GLint)value;
break;
case GLUT_INIT_WINDOW_Y:
fgState.Position.Y = (GLint)value;
break;
case GLUT_INIT_WINDOW_WIDTH:
fgState.Size.X = (GLint)value;
break;
case GLUT_INIT_WINDOW_HEIGHT:
fgState.Size.Y = (GLint)value;
break;
case GLUT_INIT_DISPLAY_MODE:
fgState.DisplayMode = (unsigned int)value;
break;
case GLUT_ACTION_ON_WINDOW_CLOSE:
fgState.ActionOnWindowClose = value;
break;
case GLUT_RENDERING_CONTEXT:
fgState.UseCurrentContext =
( value == GLUT_USE_CURRENT_CONTEXT ) ? GL_TRUE : GL_FALSE;
break;
case GLUT_DIRECT_RENDERING:
fgState.DirectContext = value;
break;
case GLUT_WINDOW_CURSOR:
if( fgStructure.CurrentWindow != NULL )
fgStructure.CurrentWindow->State.Cursor = value;
break;
case GLUT_AUX:
fgState.AuxiliaryBufferNumber = value;
break;
case GLUT_MULTISAMPLE:
fgState.SampleNumber = value;
break;
case GLUT_SKIP_STALE_MOTION_EVENTS:
fgState.SkipStaleMotion = !!value;
break;
case GLUT_GEOMETRY_VISUALIZE_NORMALS:
if( fgStructure.CurrentWindow != NULL )
fgStructure.CurrentWindow->State.VisualizeNormals = !!value;
break;
case GLUT_STROKE_FONT_DRAW_JOIN_DOTS:
fgState.StrokeFontDrawJoinDots = !!value;
break;
default:
fgWarning( "glutSetOption(): missing enum handle %d", eWhat );
break;
}
}
/*
* General settings query method
*/
int FGAPIENTRY glutGet( GLenum eWhat )
{
switch (eWhat)
{
case GLUT_INIT_STATE:
return fgState.Initialised;
/* Although internally the time store is 64bits wide, the return value
* here still wraps every 49.7 days. Integer overflows cancel however
* when subtracting an initial start time, unless the total time exceeds
* 32-bit, so you can still work with this.
* XXX: a glutGet64 to return the time might be an idea...
*/
case GLUT_ELAPSED_TIME:
return (int) fgElapsedTime();
}
FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGet" );
switch( eWhat )
{
/* Following values are stored in fgState and fgDisplay global structures */
case GLUT_SCREEN_WIDTH: return fgDisplay.ScreenWidth ;
case GLUT_SCREEN_HEIGHT: return fgDisplay.ScreenHeight ;
case GLUT_SCREEN_WIDTH_MM: return fgDisplay.ScreenWidthMM ;
case GLUT_SCREEN_HEIGHT_MM: return fgDisplay.ScreenHeightMM;
case GLUT_INIT_WINDOW_X: return fgState.Position.Use ?
fgState.Position.X : -1 ;
case GLUT_INIT_WINDOW_Y: return fgState.Position.Use ?
fgState.Position.Y : -1 ;
case GLUT_INIT_WINDOW_WIDTH: return fgState.Size.Use ?
fgState.Size.X : -1 ;
case GLUT_INIT_WINDOW_HEIGHT: return fgState.Size.Use ?
fgState.Size.Y : -1 ;
case GLUT_INIT_DISPLAY_MODE: return fgState.DisplayMode ;
case GLUT_INIT_MAJOR_VERSION: return fgState.MajorVersion ;
case GLUT_INIT_MINOR_VERSION: return fgState.MinorVersion ;
case GLUT_INIT_FLAGS: return fgState.ContextFlags ;
case GLUT_INIT_PROFILE: return fgState.ContextProfile ;
/* The window structure queries */
case GLUT_WINDOW_PARENT:
if( fgStructure.CurrentWindow == NULL ) return 0;
if( fgStructure.CurrentWindow->Parent == NULL ) return 0;
return fgStructure.CurrentWindow->Parent->ID;
case GLUT_WINDOW_NUM_CHILDREN:
if( fgStructure.CurrentWindow == NULL )
return 0;
return fgListLength( &fgStructure.CurrentWindow->Children );
case GLUT_WINDOW_CURSOR:
if( fgStructure.CurrentWindow == NULL )
return 0;
return fgStructure.CurrentWindow->State.Cursor;
case GLUT_MENU_NUM_ITEMS:
if( fgStructure.CurrentMenu == NULL )
return 0;
return fgListLength( &fgStructure.CurrentMenu->Entries );
case GLUT_ACTION_ON_WINDOW_CLOSE:
return fgState.ActionOnWindowClose;
case GLUT_VERSION :
return VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH;
case GLUT_RENDERING_CONTEXT:
return fgState.UseCurrentContext ? GLUT_USE_CURRENT_CONTEXT
: GLUT_CREATE_NEW_CONTEXT;
case GLUT_DIRECT_RENDERING:
return fgState.DirectContext;
case GLUT_FULL_SCREEN:
return fgStructure.CurrentWindow->State.IsFullscreen;
case GLUT_AUX:
return fgState.AuxiliaryBufferNumber;
case GLUT_MULTISAMPLE:
return fgState.SampleNumber;
case GLUT_SKIP_STALE_MOTION_EVENTS:
return fgState.SkipStaleMotion;
case GLUT_GEOMETRY_VISUALIZE_NORMALS:
if( fgStructure.CurrentWindow == NULL )
return GL_FALSE;
return fgStructure.CurrentWindow->State.VisualizeNormals;
case GLUT_STROKE_FONT_DRAW_JOIN_DOTS:
return fgState.StrokeFontDrawJoinDots;
default:
return fgPlatformGlutGet ( eWhat );
break;
}
}
/*
* Returns various device information.
*/
int FGAPIENTRY glutDeviceGet( GLenum eWhat )
{
FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDeviceGet" );
/* XXX WARNING: we are mostly lying in this function. */
switch( eWhat )
{
case GLUT_HAS_JOYSTICK:
return fgJoystickDetect ();
case GLUT_OWNS_JOYSTICK:
return fgState.JoysticksInitialised;
case GLUT_JOYSTICK_POLL_RATE:
return fgStructure.CurrentWindow ? fgStructure.CurrentWindow->State.JoystickPollRate : 0;
/* XXX The following two are only for Joystick 0 but this is an improvement */
case GLUT_JOYSTICK_BUTTONS:
return glutJoystickGetNumButtons ( 0 );
case GLUT_JOYSTICK_AXES:
return glutJoystickGetNumAxes ( 0 );
case GLUT_HAS_DIAL_AND_BUTTON_BOX:
return fgInputDeviceDetect ();
case GLUT_NUM_DIALS:
if ( fgState.InputDevsInitialised ) return 8;
return 0;
case GLUT_NUM_BUTTON_BOX_BUTTONS:
return 0;
case GLUT_HAS_SPACEBALL:
return fgHasSpaceball();
case GLUT_HAS_TABLET:
return 0;
case GLUT_NUM_SPACEBALL_BUTTONS:
return fgSpaceballNumButtons();
case GLUT_NUM_TABLET_BUTTONS:
return 0;
case GLUT_DEVICE_IGNORE_KEY_REPEAT:
return fgStructure.CurrentWindow ? fgStructure.CurrentWindow->State.IgnoreKeyRepeat : 0;
case GLUT_DEVICE_KEY_REPEAT:
return fgState.KeyRepeat;
default:
return fgPlatformGlutDeviceGet ( eWhat );
}
}
/*
* This should return the current state of ALT, SHIFT and CTRL keys.
*/
int FGAPIENTRY glutGetModifiers( void )
{
FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetModifiers" );
if( fgState.Modifiers == INVALID_MODIFIERS )
{
fgWarning( "glutGetModifiers() called outside an input callback" );
return 0;
}
return fgState.Modifiers;
}
/*
* Return the state of the GLUT API overlay subsystem. A misery ;-)
*/
int FGAPIENTRY glutLayerGet( GLenum eWhat )
{
FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLayerGet" );
/*
* This is easy as layers are not implemented and
* overlay support is not planned. E.g. on Windows,
* overlay requests in PFDs are ignored
* (see iLayerType at http://msdn.microsoft.com/en-us/library/dd368826(v=vs.85).aspx)
*/
switch( eWhat )
{
case GLUT_OVERLAY_POSSIBLE:
return 0 ;
case GLUT_LAYER_IN_USE:
return GLUT_NORMAL;
case GLUT_HAS_OVERLAY:
return 0;
case GLUT_TRANSPARENT_INDEX:
/*
* Return just anything, which is always defined as zero
*
* XXX HUH?
*/
return 0;
case GLUT_NORMAL_DAMAGED:
/* XXX Actually I do not know. Maybe. */
return 0;
case GLUT_OVERLAY_DAMAGED:
return -1;
default:
fgWarning( "glutLayerGet(): missing enum handle %d", eWhat );
break;
}
/* And fail. That's good. Programs do love failing. */
return -1;
}
int * FGAPIENTRY glutGetModeValues(GLenum eWhat, int *size)
{
int *array;
FREEGLUT_EXIT_IF_NOT_INITIALISED("glutGetModeValues");
*size = 0;
array = fgPlatformGlutGetModeValues ( eWhat, size );
return array;
}
/*** END OF FILE ***/
| mit |
3meng/Windows-universal-samples | customsensors/cpp/scenario2_polling.xaml.cpp | 19 | 6906 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario2_Polling.xaml.cpp
// Implementation of the Scenario2_Polling class
//
#include "pch.h"
#include "Scenario2_Polling.xaml.h"
using namespace CustomSensors;
using namespace SDKTemplate;
using namespace concurrency;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Sensors;
using namespace Windows::Devices::Sensors::Custom;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Core;
using namespace Platform;
// The following ID is defined by vendors and is unique to a custom sensor type. Each custom sensor driver should define one unique ID.
//
// The ID below is defined in the custom sensor driver sample available in the SDK. It identifies the custom sensor CO2 emulation sample driver.
const GUID GUID_CustomSensorDevice_VendorDefinedTypeID = { 0x4025a865, 0x638c, 0x43aa, 0xa6, 0x88, 0x98, 0x58, 0x9, 0x61, 0xee, 0xae };
// A property key is defined by vendors for each datafield property a custom sensor driver exposes. Property keys are defined
// per custom sensor driver and is unique to each custom sensor type.
//
// The following property key represents the CO2 level as defined in the custom sensor CO2 emulation driver sample available in the WDK.
// In this example only one key is defined, but other drivers may define more than one key by rev'ing up the property key index.
#define CO2_LEVEL_KEY "{74879888-a3cc-45c6-9ea9-058838256433} 1"
Scenario2_Polling::Scenario2_Polling() : m_RootPage(MainPage::Current)
{
Guid customSensorGuid(GUID_CustomSensorDevice_VendorDefinedTypeID);
InitializeComponent();
m_DeviceAccessInfo = DeviceAccessInformation::CreateFromDeviceClassId(customSensorGuid);
m_DeviceAccessInfo->AccessChanged += ref new TypedEventHandler<DeviceAccessInformation ^, DeviceAccessChangedEventArgs ^>(this, &Scenario2_Polling::OnAccessChanged);
StartWatcher();
}
/// <summary>
/// Invoked each time the custom sensor is created
/// </summary>
void Scenario2_Polling::StartWatcher()
{
Guid customSensorGuid(GUID_CustomSensorDevice_VendorDefinedTypeID);
String^ customSensorSelector = CustomSensor::GetDeviceSelector(customSensorGuid);
m_Watcher = DeviceInformation::CreateWatcher(customSensorSelector);
m_Watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &Scenario2_Polling::OnCustomSensorAdded);
m_Watcher->Start();
}
/// <summary>
/// Invoked when the device watcher finds a matching custom sensor device
/// </summary>
/// <param name="watcher">device watcher</param>
/// <param name="customSensorDevice">device information for the custom sensor that was found</param>
void Scenario2_Polling::OnCustomSensorAdded(DeviceWatcher^ watcher, DeviceInformation^ customSensorDevice)
{
IAsyncOperation<CustomSensor^>^ getCustomSensorRequest = CustomSensor::FromIdAsync(customSensorDevice->Id);
auto getCustomSensorTask = create_task(getCustomSensorRequest);
getCustomSensorTask.then([this](CustomSensor^ customSensor)
{
if (customSensor != nullptr)
{
// When multiple custom sensors exist on the system, OnCustomSensorAdded
// may be called concurrently using multiple threadpool threads
// Lock the section to protect this->customSensor from concurrent accesses
auto lock = m_CritsecCustomSensor.Lock();
// Just pick the first matching custom sensor, ignore the others
if (nullptr == this->m_CustomSensor)
{
this->m_CustomSensor = customSensor;
}
}
else
{
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this]()
{
m_RootPage->NotifyUser("Custom sensor not found or access denied", NotifyType::ErrorMessage);
},
CallbackContext::Any
)
);
}
});
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario2_Polling::OnNavigatedTo(NavigationEventArgs^ e)
{
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario2_Polling::OnNavigatedFrom(NavigationEventArgs^ e)
{
}
/// <summary>
/// Invoked when a user clicks on the GetCO2LevelButton
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario2_Polling::GetCO2Level(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
static int test = 0;
if (m_CustomSensor != nullptr)
{
CustomSensorReading^ reading = m_CustomSensor->GetCurrentReading();
if (reading != nullptr)
{
if (reading->Properties->HasKey(CO2_LEVEL_KEY))
{
ScenarioOutputCO2Level->Text = reading->Properties->Lookup(CO2_LEVEL_KEY)->ToString();
}
}
}
else
{
m_RootPage->NotifyUser("Custom sensor not found or access denied", NotifyType::ErrorMessage);
}
}
/// <summary>
/// Invoked when the privacy settings for this custom sensor have changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario2_Polling::OnAccessChanged(DeviceAccessInformation ^sender, DeviceAccessChangedEventArgs ^args)
{
if (args->Status == DeviceAccessStatus::Allowed)
{
StartWatcher();
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this]()
{
m_RootPage->NotifyUser("", NotifyType::StatusMessage);
},
CallbackContext::Any
)
);
}
else
{
m_CustomSensor = nullptr;
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this]()
{
m_RootPage->NotifyUser("Custom sensor access denied", NotifyType::ErrorMessage);
},
CallbackContext::Any
)
);
}
}
| mit |
joncav2222/TronStickArcade | es-app/src/components/ScraperSearchComponent.cpp | 23 | 15100 | #include "components/ScraperSearchComponent.h"
#include "guis/GuiMsgBox.h"
#include "components/TextComponent.h"
#include "components/ScrollableContainer.h"
#include "components/ImageComponent.h"
#include "components/RatingComponent.h"
#include "components/DateTimeComponent.h"
#include "components/AnimatedImageComponent.h"
#include "components/ComponentList.h"
#include "HttpReq.h"
#include "Settings.h"
#include "Log.h"
#include "Util.h"
#include "guis/GuiTextEditPopup.h"
ScraperSearchComponent::ScraperSearchComponent(Window* window, SearchType type) : GuiComponent(window),
mGrid(window, Eigen::Vector2i(4, 3)), mBusyAnim(window),
mSearchType(type)
{
addChild(&mGrid);
mBlockAccept = false;
using namespace Eigen;
// left spacer (empty component, needed for borders)
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 0), false, false, Vector2i(1, 3), GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
// selected result name
mResultName = std::make_shared<TextComponent>(mWindow, "Result name", Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
// selected result thumbnail
mResultThumbnail = std::make_shared<ImageComponent>(mWindow);
mGrid.setEntry(mResultThumbnail, Vector2i(1, 1), false, false, Vector2i(1, 1));
// selected result desc + container
mDescContainer = std::make_shared<ScrollableContainer>(mWindow);
mResultDesc = std::make_shared<TextComponent>(mWindow, "Result desc", Font::get(FONT_SIZE_SMALL), 0x777777FF);
mDescContainer->addChild(mResultDesc.get());
mDescContainer->setAutoScroll(true);
// metadata
auto font = Font::get(FONT_SIZE_SMALL); // this gets replaced in onSizeChanged() so its just a placeholder
const unsigned int mdColor = 0x777777FF;
const unsigned int mdLblColor = 0x666666FF;
mMD_Rating = std::make_shared<RatingComponent>(mWindow);
mMD_ReleaseDate = std::make_shared<DateTimeComponent>(mWindow);
mMD_ReleaseDate->setColor(mdColor);
mMD_Developer = std::make_shared<TextComponent>(mWindow, "", font, mdColor);
mMD_Publisher = std::make_shared<TextComponent>(mWindow, "", font, mdColor);
mMD_Genre = std::make_shared<TextComponent>(mWindow, "", font, mdColor);
mMD_Players = std::make_shared<TextComponent>(mWindow, "", font, mdColor);
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "RATING:", font, mdLblColor), mMD_Rating, false));
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "RELEASED:", font, mdLblColor), mMD_ReleaseDate));
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "DEVELOPER:", font, mdLblColor), mMD_Developer));
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "PUBLISHER:", font, mdLblColor), mMD_Publisher));
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "GENRE:", font, mdLblColor), mMD_Genre));
mMD_Pairs.push_back(MetaDataPair(std::make_shared<TextComponent>(mWindow, "PLAYERS:", font, mdLblColor), mMD_Players));
mMD_Grid = std::make_shared<ComponentGrid>(mWindow, Vector2i(2, mMD_Pairs.size()*2 - 1));
unsigned int i = 0;
for(auto it = mMD_Pairs.begin(); it != mMD_Pairs.end(); it++)
{
mMD_Grid->setEntry(it->first, Vector2i(0, i), false, true);
mMD_Grid->setEntry(it->second, Vector2i(1, i), false, it->resize);
i += 2;
}
mGrid.setEntry(mMD_Grid, Vector2i(2, 1), false, false);
// result list
mResultList = std::make_shared<ComponentList>(mWindow);
mResultList->setCursorChangedCallback([this](CursorState state) { if(state == CURSOR_STOPPED) updateInfoPane(); });
updateViewStyle();
}
void ScraperSearchComponent::onSizeChanged()
{
mGrid.setSize(mSize);
if(mSize.x() == 0 || mSize.y() == 0)
return;
// column widths
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT)
mGrid.setColWidthPerc(0, 0.02f); // looks better when this is higher in auto mode
else
mGrid.setColWidthPerc(0, 0.01f);
mGrid.setColWidthPerc(1, 0.25f);
mGrid.setColWidthPerc(2, 0.25f);
// row heights
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) // show name
mGrid.setRowHeightPerc(0, (mResultName->getFont()->getHeight() * 1.6f) / mGrid.getSize().y()); // result name
else
mGrid.setRowHeightPerc(0, 0.0825f); // hide name but do padding
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT)
{
mGrid.setRowHeightPerc(2, 0.2f);
}else{
mGrid.setRowHeightPerc(1, 0.505f);
}
const float boxartCellScale = 0.9f;
// limit thumbnail size using setMaxHeight - we do this instead of letting mGrid call setSize because it maintains the aspect ratio
// we also pad a little so it doesn't rub up against the metadata labels
mResultThumbnail->setMaxSize(mGrid.getColWidth(1) * boxartCellScale, mGrid.getRowHeight(1));
// metadata
resizeMetadata();
if(mSearchType != ALWAYS_ACCEPT_FIRST_RESULT)
mDescContainer->setSize(mGrid.getColWidth(1)*boxartCellScale + mGrid.getColWidth(2), mResultDesc->getFont()->getHeight() * 3);
else
mDescContainer->setSize(mGrid.getColWidth(3)*boxartCellScale, mResultDesc->getFont()->getHeight() * 8);
mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container
mGrid.onSizeChanged();
mBusyAnim.setSize(mSize);
}
void ScraperSearchComponent::resizeMetadata()
{
mMD_Grid->setSize(mGrid.getColWidth(2), mGrid.getRowHeight(1));
if(mMD_Grid->getSize().y() > mMD_Pairs.size())
{
const int fontHeight = (int)(mMD_Grid->getSize().y() / mMD_Pairs.size() * 0.8f);
auto fontLbl = Font::get(fontHeight, FONT_PATH_REGULAR);
auto fontComp = Font::get(fontHeight, FONT_PATH_LIGHT);
// update label fonts
float maxLblWidth = 0;
for(auto it = mMD_Pairs.begin(); it != mMD_Pairs.end(); it++)
{
it->first->setFont(fontLbl);
it->first->setSize(0, 0);
if(it->first->getSize().x() > maxLblWidth)
maxLblWidth = it->first->getSize().x() + 6;
}
for(unsigned int i = 0; i < mMD_Pairs.size(); i++)
{
mMD_Grid->setRowHeightPerc(i*2, (fontLbl->getLetterHeight() + 2) / mMD_Grid->getSize().y());
}
// update component fonts
mMD_ReleaseDate->setFont(fontComp);
mMD_Developer->setFont(fontComp);
mMD_Publisher->setFont(fontComp);
mMD_Genre->setFont(fontComp);
mMD_Players->setFont(fontComp);
mMD_Grid->setColWidthPerc(0, maxLblWidth / mMD_Grid->getSize().x());
// rating is manually sized
mMD_Rating->setSize(mMD_Grid->getColWidth(1), fontLbl->getHeight() * 0.65f);
mMD_Grid->onSizeChanged();
// make result font follow label font
mResultDesc->setFont(Font::get(fontHeight, FONT_PATH_REGULAR));
}
}
void ScraperSearchComponent::updateViewStyle()
{
using namespace Eigen;
// unlink description and result list and result name
mGrid.removeEntry(mResultName);
mGrid.removeEntry(mResultDesc);
mGrid.removeEntry(mResultList);
// add them back depending on search type
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT)
{
// show name
mGrid.setEntry(mResultName, Vector2i(1, 0), false, true, Vector2i(2, 1), GridFlags::BORDER_TOP);
// need a border on the bottom left
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 2), false, false, Vector2i(3, 1), GridFlags::BORDER_BOTTOM);
// show description on the right
mGrid.setEntry(mDescContainer, Vector2i(3, 0), false, false, Vector2i(1, 3), GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container
}else{
// fake row where name would be
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(1, 0), false, true, Vector2i(2, 1), GridFlags::BORDER_TOP);
// show result list on the right
mGrid.setEntry(mResultList, Vector2i(3, 0), true, true, Vector2i(1, 3), GridFlags::BORDER_LEFT | GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
// show description under image/info
mGrid.setEntry(mDescContainer, Vector2i(1, 2), false, false, Vector2i(2, 1), GridFlags::BORDER_BOTTOM);
mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container
}
}
void ScraperSearchComponent::search(const ScraperSearchParams& params)
{
mResultList->clear();
mScraperResults.clear();
mThumbnailReq.reset();
mMDResolveHandle.reset();
updateInfoPane();
mLastSearch = params;
mSearchHandle = startScraperSearch(params);
}
void ScraperSearchComponent::stop()
{
mThumbnailReq.reset();
mSearchHandle.reset();
mMDResolveHandle.reset();
mBlockAccept = false;
}
void ScraperSearchComponent::onSearchDone(const std::vector<ScraperSearchResult>& results)
{
mResultList->clear();
mScraperResults = results;
const int end = results.size() > MAX_SCRAPER_RESULTS ? MAX_SCRAPER_RESULTS : results.size(); // at max display 5
auto font = Font::get(FONT_SIZE_MEDIUM);
unsigned int color = 0x777777FF;
if(end == 0)
{
ComponentListRow row;
row.addElement(std::make_shared<TextComponent>(mWindow, "NO GAMES FOUND - SKIP", font, color), true);
if(mSkipCallback)
row.makeAcceptInputHandler(mSkipCallback);
mResultList->addRow(row);
mGrid.resetCursor();
}else{
ComponentListRow row;
for(int i = 0; i < end; i++)
{
row.elements.clear();
row.addElement(std::make_shared<TextComponent>(mWindow, strToUpper(results.at(i).mdl.get("name")), font, color), true);
row.makeAcceptInputHandler([this, i] { returnResult(mScraperResults.at(i)); });
mResultList->addRow(row);
}
mGrid.resetCursor();
}
mBlockAccept = false;
updateInfoPane();
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT)
{
if(mScraperResults.size() == 0)
mSkipCallback();
else
returnResult(mScraperResults.front());
}else if(mSearchType == ALWAYS_ACCEPT_MATCHING_CRC)
{
// TODO
}
}
void ScraperSearchComponent::onSearchError(const std::string& error)
{
LOG(LogInfo) << "ScraperSearchComponent search error: " << error;
mWindow->pushGui(new GuiMsgBox(mWindow, strToUpper(error),
"RETRY", std::bind(&ScraperSearchComponent::search, this, mLastSearch),
"SKIP", mSkipCallback,
"CANCEL", mCancelCallback));
}
int ScraperSearchComponent::getSelectedIndex()
{
if(!mScraperResults.size() || mGrid.getSelectedComponent() != mResultList)
return -1;
return mResultList->getCursorId();
}
void ScraperSearchComponent::updateInfoPane()
{
int i = getSelectedIndex();
if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT && mScraperResults.size())
{
i = 0;
}
if(i != -1 && (int)mScraperResults.size() > i)
{
ScraperSearchResult& res = mScraperResults.at(i);
mResultName->setText(strToUpper(res.mdl.get("name")));
mResultDesc->setText(strToUpper(res.mdl.get("desc")));
mDescContainer->reset();
mResultThumbnail->setImage("");
const std::string& thumb = res.thumbnailUrl.empty() ? res.imageUrl : res.thumbnailUrl;
if(!thumb.empty())
{
mThumbnailReq = std::unique_ptr<HttpReq>(new HttpReq(thumb));
}else{
mThumbnailReq.reset();
}
// metadata
mMD_Rating->setValue(strToUpper(res.mdl.get("rating")));
mMD_ReleaseDate->setValue(strToUpper(res.mdl.get("releasedate")));
mMD_Developer->setText(strToUpper(res.mdl.get("developer")));
mMD_Publisher->setText(strToUpper(res.mdl.get("publisher")));
mMD_Genre->setText(strToUpper(res.mdl.get("genre")));
mMD_Players->setText(strToUpper(res.mdl.get("players")));
mGrid.onSizeChanged();
}else{
mResultName->setText("");
mResultDesc->setText("");
mResultThumbnail->setImage("");
// metadata
mMD_Rating->setValue("");
mMD_ReleaseDate->setValue("");
mMD_Developer->setText("");
mMD_Publisher->setText("");
mMD_Genre->setText("");
mMD_Players->setText("");
}
}
bool ScraperSearchComponent::input(InputConfig* config, Input input)
{
if(config->isMappedTo("a", input) && input.value != 0)
{
if(mBlockAccept)
return true;
}
return GuiComponent::input(config, input);
}
void ScraperSearchComponent::render(const Eigen::Affine3f& parentTrans)
{
Eigen::Affine3f trans = parentTrans * getTransform();
renderChildren(trans);
if(mBlockAccept)
{
Renderer::setMatrix(trans);
Renderer::drawRect(0.f, 0.f, mSize.x(), mSize.y(), 0x00000011);
//Renderer::drawRect((int)mResultList->getPosition().x(), (int)mResultList->getPosition().y(),
// (int)mResultList->getSize().x(), (int)mResultList->getSize().y(), 0x00000011);
mBusyAnim.render(trans);
}
}
void ScraperSearchComponent::returnResult(ScraperSearchResult result)
{
mBlockAccept = true;
// resolve metadata image before returning
if(!result.imageUrl.empty())
{
mMDResolveHandle = resolveMetaDataAssets(result, mLastSearch);
return;
}
mAcceptCallback(result);
}
void ScraperSearchComponent::update(int deltaTime)
{
GuiComponent::update(deltaTime);
if(mBlockAccept)
{
mBusyAnim.update(deltaTime);
}
if(mThumbnailReq && mThumbnailReq->status() != HttpReq::REQ_IN_PROGRESS)
{
updateThumbnail();
}
if(mSearchHandle && mSearchHandle->status() != ASYNC_IN_PROGRESS)
{
auto status = mSearchHandle->status();
auto results = mSearchHandle->getResults();
auto statusString = mSearchHandle->getStatusString();
// we reset here because onSearchDone in auto mode can call mSkipCallback() which can call
// another search() which will set our mSearchHandle to something important
mSearchHandle.reset();
if(status == ASYNC_DONE)
{
onSearchDone(results);
}else if(status == ASYNC_ERROR)
{
onSearchError(statusString);
}
}
if(mMDResolveHandle && mMDResolveHandle->status() != ASYNC_IN_PROGRESS)
{
if(mMDResolveHandle->status() == ASYNC_DONE)
{
ScraperSearchResult result = mMDResolveHandle->getResult();
mMDResolveHandle.reset();
// this might end in us being deleted, depending on mAcceptCallback - so make sure this is the last thing we do in update()
returnResult(result);
}else if(mMDResolveHandle->status() == ASYNC_ERROR)
{
onSearchError(mMDResolveHandle->getStatusString());
mMDResolveHandle.reset();
}
}
}
void ScraperSearchComponent::updateThumbnail()
{
if(mThumbnailReq && mThumbnailReq->status() == HttpReq::REQ_SUCCESS)
{
std::string content = mThumbnailReq->getContent();
mResultThumbnail->setImage(content.data(), content.length());
mGrid.onSizeChanged(); // a hack to fix the thumbnail position since its size changed
}else{
LOG(LogWarning) << "thumbnail req failed: " << mThumbnailReq->getErrorMsg();
mResultThumbnail->setImage("");
}
mThumbnailReq.reset();
}
void ScraperSearchComponent::openInputScreen(ScraperSearchParams& params)
{
auto searchForFunc = [&](const std::string& name)
{
params.nameOverride = name;
search(params);
};
stop();
mWindow->pushGui(new GuiTextEditPopup(mWindow, "SEARCH FOR",
// initial value is last search if there was one, otherwise the clean path name
params.nameOverride.empty() ? params.game->getCleanName() : params.nameOverride,
searchForFunc, false, "SEARCH"));
}
std::vector<HelpPrompt> ScraperSearchComponent::getHelpPrompts()
{
std::vector<HelpPrompt> prompts = mGrid.getHelpPrompts();
if(getSelectedIndex() != -1)
prompts.push_back(HelpPrompt("a", "accept result"));
return prompts;
}
void ScraperSearchComponent::onFocusGained()
{
mGrid.onFocusGained();
}
void ScraperSearchComponent::onFocusLost()
{
mGrid.onFocusLost();
}
| mit |
deleisha/evt | sample/libuv-tls/libuv/src/unix/netbsd.c | 25 | 8841 | /* Copyright Joyent, Inc. and other Node contributors. 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 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 "uv.h"
#include "internal.h"
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <kvm.h>
#include <paths.h>
#include <ifaddrs.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <uvm/uvm_extern.h>
#include <unistd.h>
#include <time.h>
#undef NANOSEC
#define NANOSEC ((uint64_t) 1e9)
static char *process_title;
int uv__platform_loop_init(uv_loop_t* loop) {
return uv__kqueue_init(loop);
}
void uv__platform_loop_delete(uv_loop_t* loop) {
}
uint64_t uv__hrtime(uv_clocktype_t type) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
}
void uv_loadavg(double avg[3]) {
struct loadavg info;
size_t size = sizeof(info);
int which[] = {CTL_VM, VM_LOADAVG};
if (sysctl(which, 2, &info, &size, NULL, 0) == -1) return;
avg[0] = (double) info.ldavg[0] / info.fscale;
avg[1] = (double) info.ldavg[1] / info.fscale;
avg[2] = (double) info.ldavg[2] / info.fscale;
}
int uv_exepath(char* buffer, size_t* size) {
int mib[4];
size_t cb;
pid_t mypid;
if (buffer == NULL || size == NULL || *size == 0)
return -EINVAL;
mypid = getpid();
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = mypid;
mib[3] = KERN_PROC_ARGV;
cb = *size;
if (sysctl(mib, 4, buffer, &cb, NULL, 0))
return -errno;
*size = strlen(buffer);
return 0;
}
uint64_t uv_get_free_memory(void) {
struct uvmexp info;
size_t size = sizeof(info);
int which[] = {CTL_VM, VM_UVMEXP};
if (sysctl(which, 2, &info, &size, NULL, 0))
return -errno;
return (uint64_t) info.free * sysconf(_SC_PAGESIZE);
}
uint64_t uv_get_total_memory(void) {
#if defined(HW_PHYSMEM64)
uint64_t info;
int which[] = {CTL_HW, HW_PHYSMEM64};
#else
unsigned int info;
int which[] = {CTL_HW, HW_PHYSMEM};
#endif
size_t size = sizeof(info);
if (sysctl(which, 2, &info, &size, NULL, 0))
return -errno;
return (uint64_t) info;
}
char** uv_setup_args(int argc, char** argv) {
process_title = argc ? uv__strdup(argv[0]) : NULL;
return argv;
}
int uv_set_process_title(const char* title) {
if (process_title) uv__free(process_title);
process_title = uv__strdup(title);
setproctitle("%s", title);
return 0;
}
int uv_get_process_title(char* buffer, size_t size) {
if (process_title) {
strncpy(buffer, process_title, size);
} else {
if (size > 0) {
buffer[0] = '\0';
}
}
return 0;
}
int uv_resident_set_memory(size_t* rss) {
kvm_t *kd = NULL;
struct kinfo_proc2 *kinfo = NULL;
pid_t pid;
int nprocs;
int max_size = sizeof(struct kinfo_proc2);
int page_size;
page_size = getpagesize();
pid = getpid();
kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, "kvm_open");
if (kd == NULL) goto error;
kinfo = kvm_getproc2(kd, KERN_PROC_PID, pid, max_size, &nprocs);
if (kinfo == NULL) goto error;
*rss = kinfo->p_vm_rssize * page_size;
kvm_close(kd);
return 0;
error:
if (kd) kvm_close(kd);
return -EPERM;
}
int uv_uptime(double* uptime) {
time_t now;
struct timeval info;
size_t size = sizeof(info);
static int which[] = {CTL_KERN, KERN_BOOTTIME};
if (sysctl(which, 2, &info, &size, NULL, 0))
return -errno;
now = time(NULL);
*uptime = (double)(now - info.tv_sec);
return 0;
}
int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK);
unsigned int multiplier = ((uint64_t)1000L / ticks);
unsigned int cur = 0;
uv_cpu_info_t* cpu_info;
u_int64_t* cp_times;
char model[512];
u_int64_t cpuspeed;
int numcpus;
size_t size;
int i;
size = sizeof(model);
if (sysctlbyname("machdep.cpu_brand", &model, &size, NULL, 0) &&
sysctlbyname("hw.model", &model, &size, NULL, 0)) {
return -errno;
}
size = sizeof(numcpus);
if (sysctlbyname("hw.ncpu", &numcpus, &size, NULL, 0))
return -errno;
*count = numcpus;
/* Only i386 and amd64 have machdep.tsc_freq */
size = sizeof(cpuspeed);
if (sysctlbyname("machdep.tsc_freq", &cpuspeed, &size, NULL, 0))
cpuspeed = 0;
size = numcpus * CPUSTATES * sizeof(*cp_times);
cp_times = uv__malloc(size);
if (cp_times == NULL)
return -ENOMEM;
if (sysctlbyname("kern.cp_time", cp_times, &size, NULL, 0))
return -errno;
*cpu_infos = uv__malloc(numcpus * sizeof(**cpu_infos));
if (!(*cpu_infos)) {
uv__free(cp_times);
uv__free(*cpu_infos);
return -ENOMEM;
}
for (i = 0; i < numcpus; i++) {
cpu_info = &(*cpu_infos)[i];
cpu_info->cpu_times.user = (uint64_t)(cp_times[CP_USER+cur]) * multiplier;
cpu_info->cpu_times.nice = (uint64_t)(cp_times[CP_NICE+cur]) * multiplier;
cpu_info->cpu_times.sys = (uint64_t)(cp_times[CP_SYS+cur]) * multiplier;
cpu_info->cpu_times.idle = (uint64_t)(cp_times[CP_IDLE+cur]) * multiplier;
cpu_info->cpu_times.irq = (uint64_t)(cp_times[CP_INTR+cur]) * multiplier;
cpu_info->model = uv__strdup(model);
cpu_info->speed = (int)(cpuspeed/(uint64_t) 1e6);
cur += CPUSTATES;
}
uv__free(cp_times);
return 0;
}
void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
int i;
for (i = 0; i < count; i++) {
uv__free(cpu_infos[i].model);
}
uv__free(cpu_infos);
}
int uv_interface_addresses(uv_interface_address_t** addresses, int* count) {
struct ifaddrs *addrs, *ent;
uv_interface_address_t* address;
int i;
struct sockaddr_dl *sa_addr;
if (getifaddrs(&addrs))
return -errno;
*count = 0;
/* Count the number of interfaces */
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
(ent->ifa_addr == NULL) ||
(ent->ifa_addr->sa_family != PF_INET)) {
continue;
}
(*count)++;
}
*addresses = uv__malloc(*count * sizeof(**addresses));
if (!(*addresses))
return -ENOMEM;
address = *addresses;
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
continue;
if (ent->ifa_addr == NULL)
continue;
if (ent->ifa_addr->sa_family != PF_INET)
continue;
address->name = uv__strdup(ent->ifa_name);
if (ent->ifa_addr->sa_family == AF_INET6) {
address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
} else {
address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
}
if (ent->ifa_netmask->sa_family == AF_INET6) {
address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
} else {
address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
}
address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
address++;
}
/* Fill in physical addresses for each interface */
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
(ent->ifa_addr == NULL) ||
(ent->ifa_addr->sa_family != AF_LINK)) {
continue;
}
address = *addresses;
for (i = 0; i < (*count); i++) {
if (strcmp(address->name, ent->ifa_name) == 0) {
sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
}
address++;
}
}
freeifaddrs(addrs);
return 0;
}
void uv_free_interface_addresses(uv_interface_address_t* addresses, int count) {
int i;
for (i = 0; i < count; i++) {
uv__free(addresses[i].name);
}
uv__free(addresses);
}
| mit |
dalek7/Algorithms | Optimization/LevmarAndroid/jni/Thirdparty/clapack/SRC/slals0.c | 26 | 14505 | /* slals0.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static real c_b5 = -1.f;
static integer c__1 = 1;
static real c_b11 = 1.f;
static real c_b13 = 0.f;
static integer c__0 = 0;
/* Subroutine */ int slals0_(integer *icompq, integer *nl, integer *nr,
integer *sqre, integer *nrhs, real *b, integer *ldb, real *bx,
integer *ldbx, integer *perm, integer *givptr, integer *givcol,
integer *ldgcol, real *givnum, integer *ldgnum, real *poles, real *
difl, real *difr, real *z__, integer *k, real *c__, real *s, real *
work, integer *info)
{
/* System generated locals */
integer givcol_dim1, givcol_offset, b_dim1, b_offset, bx_dim1, bx_offset,
difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1,
poles_offset, i__1, i__2;
real r__1;
/* Local variables */
integer i__, j, m, n;
real dj;
integer nlp1;
real temp;
extern /* Subroutine */ int srot_(integer *, real *, integer *, real *,
integer *, real *, real *);
extern doublereal snrm2_(integer *, real *, integer *);
real diflj, difrj, dsigj;
extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *),
sgemv_(char *, integer *, integer *, real *, real *, integer *,
real *, integer *, real *, real *, integer *), scopy_(
integer *, real *, integer *, real *, integer *);
extern doublereal slamc3_(real *, real *);
extern /* Subroutine */ int xerbla_(char *, integer *);
real dsigjp;
extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *,
real *, integer *, integer *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *,
real *, integer *);
/* -- LAPACK routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* SLALS0 applies back the multiplying factors of either the left or the */
/* right singular vector matrix of a diagonal matrix appended by a row */
/* to the right hand side matrix B in solving the least squares problem */
/* using the divide-and-conquer SVD approach. */
/* For the left singular vector matrix, three types of orthogonal */
/* matrices are involved: */
/* (1L) Givens rotations: the number of such rotations is GIVPTR; the */
/* pairs of columns/rows they were applied to are stored in GIVCOL; */
/* and the C- and S-values of these rotations are stored in GIVNUM. */
/* (2L) Permutation. The (NL+1)-st row of B is to be moved to the first */
/* row, and for J=2:N, PERM(J)-th row of B is to be moved to the */
/* J-th row. */
/* (3L) The left singular vector matrix of the remaining matrix. */
/* For the right singular vector matrix, four types of orthogonal */
/* matrices are involved: */
/* (1R) The right singular vector matrix of the remaining matrix. */
/* (2R) If SQRE = 1, one extra Givens rotation to generate the right */
/* null space. */
/* (3R) The inverse transformation of (2L). */
/* (4R) The inverse transformation of (1L). */
/* Arguments */
/* ========= */
/* ICOMPQ (input) INTEGER */
/* Specifies whether singular vectors are to be computed in */
/* factored form: */
/* = 0: Left singular vector matrix. */
/* = 1: Right singular vector matrix. */
/* NL (input) INTEGER */
/* The row dimension of the upper block. NL >= 1. */
/* NR (input) INTEGER */
/* The row dimension of the lower block. NR >= 1. */
/* SQRE (input) INTEGER */
/* = 0: the lower block is an NR-by-NR square matrix. */
/* = 1: the lower block is an NR-by-(NR+1) rectangular matrix. */
/* The bidiagonal matrix has row dimension N = NL + NR + 1, */
/* and column dimension M = N + SQRE. */
/* NRHS (input) INTEGER */
/* The number of columns of B and BX. NRHS must be at least 1. */
/* B (input/output) REAL array, dimension ( LDB, NRHS ) */
/* On input, B contains the right hand sides of the least */
/* squares problem in rows 1 through M. On output, B contains */
/* the solution X in rows 1 through N. */
/* LDB (input) INTEGER */
/* The leading dimension of B. LDB must be at least */
/* max(1,MAX( M, N ) ). */
/* BX (workspace) REAL array, dimension ( LDBX, NRHS ) */
/* LDBX (input) INTEGER */
/* The leading dimension of BX. */
/* PERM (input) INTEGER array, dimension ( N ) */
/* The permutations (from deflation and sorting) applied */
/* to the two blocks. */
/* GIVPTR (input) INTEGER */
/* The number of Givens rotations which took place in this */
/* subproblem. */
/* GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 ) */
/* Each pair of numbers indicates a pair of rows/columns */
/* involved in a Givens rotation. */
/* LDGCOL (input) INTEGER */
/* The leading dimension of GIVCOL, must be at least N. */
/* GIVNUM (input) REAL array, dimension ( LDGNUM, 2 ) */
/* Each number indicates the C or S value used in the */
/* corresponding Givens rotation. */
/* LDGNUM (input) INTEGER */
/* The leading dimension of arrays DIFR, POLES and */
/* GIVNUM, must be at least K. */
/* POLES (input) REAL array, dimension ( LDGNUM, 2 ) */
/* On entry, POLES(1:K, 1) contains the new singular */
/* values obtained from solving the secular equation, and */
/* POLES(1:K, 2) is an array containing the poles in the secular */
/* equation. */
/* DIFL (input) REAL array, dimension ( K ). */
/* On entry, DIFL(I) is the distance between I-th updated */
/* (undeflated) singular value and the I-th (undeflated) old */
/* singular value. */
/* DIFR (input) REAL array, dimension ( LDGNUM, 2 ). */
/* On entry, DIFR(I, 1) contains the distances between I-th */
/* updated (undeflated) singular value and the I+1-th */
/* (undeflated) old singular value. And DIFR(I, 2) is the */
/* normalizing factor for the I-th right singular vector. */
/* Z (input) REAL array, dimension ( K ) */
/* Contain the components of the deflation-adjusted updating row */
/* vector. */
/* K (input) INTEGER */
/* Contains the dimension of the non-deflated matrix, */
/* This is the order of the related secular equation. 1 <= K <=N. */
/* C (input) REAL */
/* C contains garbage if SQRE =0 and the C-value of a Givens */
/* rotation related to the right null space if SQRE = 1. */
/* S (input) REAL */
/* S contains garbage if SQRE =0 and the S-value of a Givens */
/* rotation related to the right null space if SQRE = 1. */
/* WORK (workspace) REAL array, dimension ( K ) */
/* INFO (output) INTEGER */
/* = 0: successful exit. */
/* < 0: if INFO = -i, the i-th argument had an illegal value. */
/* Further Details */
/* =============== */
/* Based on contributions by */
/* Ming Gu and Ren-Cang Li, Computer Science Division, University of */
/* California at Berkeley, USA */
/* Osni Marques, LBNL/NERSC, USA */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input parameters. */
/* Parameter adjustments */
b_dim1 = *ldb;
b_offset = 1 + b_dim1;
b -= b_offset;
bx_dim1 = *ldbx;
bx_offset = 1 + bx_dim1;
bx -= bx_offset;
--perm;
givcol_dim1 = *ldgcol;
givcol_offset = 1 + givcol_dim1;
givcol -= givcol_offset;
difr_dim1 = *ldgnum;
difr_offset = 1 + difr_dim1;
difr -= difr_offset;
poles_dim1 = *ldgnum;
poles_offset = 1 + poles_dim1;
poles -= poles_offset;
givnum_dim1 = *ldgnum;
givnum_offset = 1 + givnum_dim1;
givnum -= givnum_offset;
--difl;
--z__;
--work;
/* Function Body */
*info = 0;
if (*icompq < 0 || *icompq > 1) {
*info = -1;
} else if (*nl < 1) {
*info = -2;
} else if (*nr < 1) {
*info = -3;
} else if (*sqre < 0 || *sqre > 1) {
*info = -4;
}
n = *nl + *nr + 1;
if (*nrhs < 1) {
*info = -5;
} else if (*ldb < n) {
*info = -7;
} else if (*ldbx < n) {
*info = -9;
} else if (*givptr < 0) {
*info = -11;
} else if (*ldgcol < n) {
*info = -13;
} else if (*ldgnum < n) {
*info = -15;
} else if (*k < 1) {
*info = -20;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SLALS0", &i__1);
return 0;
}
m = n + *sqre;
nlp1 = *nl + 1;
if (*icompq == 0) {
/* Apply back orthogonal transformations from the left. */
/* Step (1L): apply back the Givens rotations performed. */
i__1 = *givptr;
for (i__ = 1; i__ <= i__1; ++i__) {
srot_(nrhs, &b[givcol[i__ + (givcol_dim1 << 1)] + b_dim1], ldb, &
b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[i__ +
(givnum_dim1 << 1)], &givnum[i__ + givnum_dim1]);
/* L10: */
}
/* Step (2L): permute rows of B. */
scopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx);
i__1 = n;
for (i__ = 2; i__ <= i__1; ++i__) {
scopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1],
ldbx);
/* L20: */
}
/* Step (3L): apply the inverse of the left singular vector */
/* matrix to BX. */
if (*k == 1) {
scopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb);
if (z__[1] < 0.f) {
sscal_(nrhs, &c_b5, &b[b_offset], ldb);
}
} else {
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
diflj = difl[j];
dj = poles[j + poles_dim1];
dsigj = -poles[j + (poles_dim1 << 1)];
if (j < *k) {
difrj = -difr[j + difr_dim1];
dsigjp = -poles[j + 1 + (poles_dim1 << 1)];
}
if (z__[j] == 0.f || poles[j + (poles_dim1 << 1)] == 0.f) {
work[j] = 0.f;
} else {
work[j] = -poles[j + (poles_dim1 << 1)] * z__[j] / diflj /
(poles[j + (poles_dim1 << 1)] + dj);
}
i__2 = j - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
if (z__[i__] == 0.f || poles[i__ + (poles_dim1 << 1)] ==
0.f) {
work[i__] = 0.f;
} else {
work[i__] = poles[i__ + (poles_dim1 << 1)] * z__[i__]
/ (slamc3_(&poles[i__ + (poles_dim1 << 1)], &
dsigj) - diflj) / (poles[i__ + (poles_dim1 <<
1)] + dj);
}
/* L30: */
}
i__2 = *k;
for (i__ = j + 1; i__ <= i__2; ++i__) {
if (z__[i__] == 0.f || poles[i__ + (poles_dim1 << 1)] ==
0.f) {
work[i__] = 0.f;
} else {
work[i__] = poles[i__ + (poles_dim1 << 1)] * z__[i__]
/ (slamc3_(&poles[i__ + (poles_dim1 << 1)], &
dsigjp) + difrj) / (poles[i__ + (poles_dim1 <<
1)] + dj);
}
/* L40: */
}
work[1] = -1.f;
temp = snrm2_(k, &work[1], &c__1);
sgemv_("T", k, nrhs, &c_b11, &bx[bx_offset], ldbx, &work[1], &
c__1, &c_b13, &b[j + b_dim1], ldb);
slascl_("G", &c__0, &c__0, &temp, &c_b11, &c__1, nrhs, &b[j +
b_dim1], ldb, info);
/* L50: */
}
}
/* Move the deflated rows of BX to B also. */
if (*k < max(m,n)) {
i__1 = n - *k;
slacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1
+ b_dim1], ldb);
}
} else {
/* Apply back the right orthogonal transformations. */
/* Step (1R): apply back the new right singular vector matrix */
/* to B. */
if (*k == 1) {
scopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx);
} else {
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
dsigj = poles[j + (poles_dim1 << 1)];
if (z__[j] == 0.f) {
work[j] = 0.f;
} else {
work[j] = -z__[j] / difl[j] / (dsigj + poles[j +
poles_dim1]) / difr[j + (difr_dim1 << 1)];
}
i__2 = j - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
if (z__[j] == 0.f) {
work[i__] = 0.f;
} else {
r__1 = -poles[i__ + 1 + (poles_dim1 << 1)];
work[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difr[
i__ + difr_dim1]) / (dsigj + poles[i__ +
poles_dim1]) / difr[i__ + (difr_dim1 << 1)];
}
/* L60: */
}
i__2 = *k;
for (i__ = j + 1; i__ <= i__2; ++i__) {
if (z__[j] == 0.f) {
work[i__] = 0.f;
} else {
r__1 = -poles[i__ + (poles_dim1 << 1)];
work[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difl[
i__]) / (dsigj + poles[i__ + poles_dim1]) /
difr[i__ + (difr_dim1 << 1)];
}
/* L70: */
}
sgemv_("T", k, nrhs, &c_b11, &b[b_offset], ldb, &work[1], &
c__1, &c_b13, &bx[j + bx_dim1], ldbx);
/* L80: */
}
}
/* Step (2R): if SQRE = 1, apply back the rotation that is */
/* related to the right null space of the subproblem. */
if (*sqre == 1) {
scopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx);
srot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__,
s);
}
if (*k < max(m,n)) {
i__1 = n - *k;
slacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 +
bx_dim1], ldbx);
}
/* Step (3R): permute rows of B. */
scopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb);
if (*sqre == 1) {
scopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb);
}
i__1 = n;
for (i__ = 2; i__ <= i__1; ++i__) {
scopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1],
ldb);
/* L90: */
}
/* Step (4R): apply back the Givens rotations performed. */
for (i__ = *givptr; i__ >= 1; --i__) {
r__1 = -givnum[i__ + givnum_dim1];
srot_(nrhs, &b[givcol[i__ + (givcol_dim1 << 1)] + b_dim1], ldb, &
b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[i__ +
(givnum_dim1 << 1)], &r__1);
/* L100: */
}
}
return 0;
/* End of SLALS0 */
} /* slals0_ */
| mit |
ericeil/coreclr | src/jit/regalloc.cpp | 28 | 248217 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX RegAlloc XX
XX XX
XX Does the register allocation and puts the remaining lclVars on the stack XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "regalloc.h"
#if FEATURE_FP_REGALLOC
Compiler::enumConfigRegisterFP Compiler::raConfigRegisterFP()
{
static ConfigDWORD dwJitRegisterFP;
DWORD val = dwJitRegisterFP.val(CLRConfig::EXTERNAL_JitRegisterFP);
return (enumConfigRegisterFP) (val & 0x3);
}
#endif // FEATURE_FP_REGALLOC
regMaskTP Compiler::raConfigRestrictMaskFP()
{
regMaskTP result = RBM_NONE;
#if FEATURE_FP_REGALLOC
switch (raConfigRegisterFP()) {
case CONFIG_REGISTER_FP_NONE:
result = RBM_NONE;
break;
case CONFIG_REGISTER_FP_CALLEE_TRASH:
result = RBM_FLT_CALLEE_TRASH;
break;
case CONFIG_REGISTER_FP_CALLEE_SAVED:
result = RBM_FLT_CALLEE_SAVED;
break;
case CONFIG_REGISTER_FP_FULL:
result = RBM_ALLFLOAT;
break;
}
#endif
return result;
}
#ifdef LEGACY_BACKEND // We don't use any of the old register allocator functions when LSRA is used instead.
#if DOUBLE_ALIGN
DWORD Compiler::getCanDoubleAlign()
{
#ifdef DEBUG
if (compStressCompile(STRESS_DBL_ALN, 20))
return MUST_DOUBLE_ALIGN;
static ConfigDWORD fJitDoubleAlign;
return fJitDoubleAlign.val_DontUse_(CLRConfig::INTERNAL_JitDoubleAlign, DEFAULT_DOUBLE_ALIGN);
#else
return DEFAULT_DOUBLE_ALIGN;
#endif
}
#endif // DOUBLE_ALIGN
void Compiler::raInit()
{
#if FEATURE_STACK_FP_X87
/* We have not assigned any FP variables to registers yet */
VarSetOps::AssignNoCopy(this, optAllFPregVars, VarSetOps::UninitVal());
#endif
codeGen->intRegState.rsIsFloat = false;
codeGen->floatRegState.rsIsFloat = true;
codeGen->intRegState.rsMaxRegArgNum = MAX_REG_ARG;
codeGen->floatRegState.rsMaxRegArgNum = MAX_FLOAT_REG_ARG;
rpReverseEBPenreg = false;
rpAsgVarNum = -1;
rpPassesMax = 6;
rpPassesPessimize = rpPassesMax - 3;
if (opts.compDbgCode)
{
rpPassesMax++;
}
rpStkPredict = (unsigned) -1;
rpFrameType = FT_NOT_SET;
rpLostEnreg = false;
rpMustCreateEBPCalled = false;
rpRegAllocDone = false;
rpMaskPInvokeEpilogIntf = RBM_NONE;
rpPredictMap[PREDICT_NONE] = RBM_NONE;
rpPredictMap[PREDICT_ADDR] = RBM_NONE;
#if FEATURE_FP_REGALLOC
rpPredictMap[PREDICT_REG] = RBM_ALLINT | RBM_ALLFLOAT;
rpPredictMap[PREDICT_SCRATCH_REG] = RBM_ALLINT | RBM_ALLFLOAT;
#else
rpPredictMap[PREDICT_REG] = RBM_ALLINT;
rpPredictMap[PREDICT_SCRATCH_REG] = RBM_ALLINT;
#endif
#define REGDEF(name, rnum, mask, sname) rpPredictMap[PREDICT_REG_ ## name ] = RBM_ ## name;
#include "register.h"
#if defined(_TARGET_ARM_)
rpPredictMap[PREDICT_PAIR_R0R1] = RBM_R0 | RBM_R1;
rpPredictMap[PREDICT_PAIR_R2R3] = RBM_R2 | RBM_R3;
rpPredictMap[PREDICT_REG_SP] = RBM_ILLEGAL;
#elif defined(_TARGET_AMD64_)
rpPredictMap[PREDICT_NOT_REG_EAX] = RBM_ALLINT & ~RBM_EAX;
rpPredictMap[PREDICT_NOT_REG_ECX] = RBM_ALLINT & ~RBM_ECX;
rpPredictMap[PREDICT_REG_ESP] = RBM_ILLEGAL;
#elif defined(_TARGET_X86_)
rpPredictMap[PREDICT_NOT_REG_EAX] = RBM_ALLINT & ~RBM_EAX;
rpPredictMap[PREDICT_NOT_REG_ECX] = RBM_ALLINT & ~RBM_ECX;
rpPredictMap[PREDICT_REG_ESP] = RBM_ILLEGAL;
rpPredictMap[PREDICT_PAIR_EAXEDX] = RBM_EAX | RBM_EDX;
rpPredictMap[PREDICT_PAIR_ECXEBX] = RBM_ECX | RBM_EBX;
#endif
rpBestRecordedPrediction = NULL;
}
/*****************************************************************************
*
* The following table(s) determines the order in which registers are considered
* for variables to live in
*/
const regNumber* Compiler::raGetRegVarOrder(var_types regType, unsigned* wbVarOrderSize)
{
#if FEATURE_FP_REGALLOC
if (varTypeIsFloating(regType))
{
static const regNumber raRegVarOrderFlt[] = { REG_VAR_ORDER_FLT };
const unsigned raRegVarOrderFltSize = sizeof(raRegVarOrderFlt)/sizeof(raRegVarOrderFlt[0]);
if (wbVarOrderSize != NULL)
*wbVarOrderSize = raRegVarOrderFltSize;
return &raRegVarOrderFlt[0];
}
else
#endif
{
static const regNumber raRegVarOrder[] = { REG_VAR_ORDER };
const unsigned raRegVarOrderSize = sizeof(raRegVarOrder)/sizeof(raRegVarOrder[0]);
if (wbVarOrderSize != NULL)
*wbVarOrderSize = raRegVarOrderSize;
return &raRegVarOrder[0];
}
}
#ifdef DEBUG
/*****************************************************************************
*
* Dump out the variable interference graph
*
*/
void Compiler::raDumpVarIntf()
{
unsigned lclNum;
LclVarDsc * varDsc;
printf("Var. interference graph for %s\n", info.compFullName);
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
/* Ignore the variable if it's not tracked */
if (!varDsc->lvTracked)
continue;
/* Get hold of the index and the interference mask for the variable */
unsigned varIndex = varDsc->lvVarIndex;
printf(" V%02u,T%02u and ", lclNum, varIndex);
unsigned refIndex;
for (refIndex = 0; refIndex < lvaTrackedCount; refIndex++)
{
if (VarSetOps::IsMember(this, lvaVarIntf[varIndex], refIndex))
printf("T%02u ", refIndex);
else
printf(" ");
}
printf("\n");
}
printf("\n");
}
/*****************************************************************************
*
* Dump out the register interference graph
*
*/
void Compiler::raDumpRegIntf()
{
printf("Reg. interference graph for %s\n", info.compFullName);
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
unsigned varNum;
/* Ignore the variable if it's not tracked */
if (!varDsc->lvTracked)
continue;
/* Get hold of the index and the interference mask for the variable */
varNum = varDsc->lvVarIndex;
printf(" V%02u,T%02u and ", lclNum, varNum);
if (varDsc->IsFloatRegType())
{
#if !FEATURE_STACK_FP_X87
for (regNumber regNum = REG_FP_FIRST; regNum <= REG_FP_LAST; regNum = REG_NEXT(regNum))
{
if (VarSetOps::IsMember(this, raLclRegIntf[regNum], varNum))
printf("%3s ", getRegName(regNum, true));
else
printf(" ");
}
#endif
}
else
{
for (regNumber regNum = REG_INT_FIRST; regNum <= REG_INT_LAST; regNum = REG_NEXT(regNum))
{
if (VarSetOps::IsMember(this, raLclRegIntf[regNum], varNum))
printf("%3s ", getRegName(regNum));
else
printf(" ");
}
}
printf("\n");
}
printf("\n");
}
#endif // DEBUG
/*****************************************************************************
*
* We'll adjust the ref counts based on interference
*
*/
void Compiler::raAdjustVarIntf()
{
// This method was not correct and has been disabled.
return;
}
/*****************************************************************************/
/*****************************************************************************/
/* Determine register mask for a call/return from type.
*/
inline
regMaskTP Compiler::genReturnRegForTree(GenTreePtr tree)
{
var_types type = tree->TypeGet();
#ifdef _TARGET_ARM_
if (type == TYP_STRUCT && IsHfa(tree))
{
int retSlots = GetHfaSlots(tree);
return ((1 << retSlots) - 1) << REG_FLOATRET;
}
#endif
const static
regMaskTP returnMap[TYP_COUNT] =
{
RBM_ILLEGAL, // TYP_UNDEF,
RBM_NONE, // TYP_VOID,
RBM_INTRET, // TYP_BOOL,
RBM_INTRET, // TYP_CHAR,
RBM_INTRET, // TYP_BYTE,
RBM_INTRET, // TYP_UBYTE,
RBM_INTRET, // TYP_SHORT,
RBM_INTRET, // TYP_USHORT,
RBM_INTRET, // TYP_INT,
RBM_INTRET, // TYP_UINT,
RBM_LNGRET, // TYP_LONG,
RBM_LNGRET, // TYP_ULONG,
RBM_FLOATRET, // TYP_FLOAT,
RBM_DOUBLERET, // TYP_DOUBLE,
RBM_INTRET, // TYP_REF,
RBM_INTRET, // TYP_BYREF,
RBM_INTRET, // TYP_ARRAY,
RBM_ILLEGAL, // TYP_STRUCT,
RBM_ILLEGAL, // TYP_BLK,
RBM_ILLEGAL, // TYP_LCLBLK,
RBM_ILLEGAL, // TYP_PTR,
RBM_ILLEGAL, // TYP_FNC,
RBM_ILLEGAL, // TYP_UNKNOWN,
};
assert((unsigned)type < sizeof(returnMap)/sizeof(returnMap[0]));
assert(returnMap[TYP_LONG] == RBM_LNGRET);
assert(returnMap[TYP_DOUBLE] == RBM_DOUBLERET);
assert(returnMap[TYP_REF] == RBM_INTRET);
assert(returnMap[TYP_STRUCT] == RBM_ILLEGAL);
regMaskTP result = returnMap[type];
assert(result != RBM_ILLEGAL);
return result;
}
/*****************************************************************************/
/****************************************************************************/
#ifdef DEBUG
static
void dispLifeSet(Compiler *comp, VARSET_VALARG_TP mask, VARSET_VALARG_TP life)
{
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = comp->lvaTable;
lclNum < comp->lvaCount;
lclNum++ , varDsc++)
{
if (!varDsc->lvTracked)
continue;
if (!VarSetOps::IsMember(comp, mask, varDsc->lvVarIndex))
continue;
if (VarSetOps::IsMember(comp, life, varDsc->lvVarIndex))
printf("V%02u ", lclNum);
}
}
#endif
/*****************************************************************************/
#ifdef DEBUG
/*****************************************************************************
*
* Debugging helpers - display variables liveness info.
*/
void dispFPvarsInBBlist(BasicBlock * beg,
BasicBlock * end,
VARSET_TP mask,
Compiler * comp)
{
do
{
printf("BB%02u: ", beg->bbNum);
printf(" in = [ ");
dispLifeSet(comp, mask, beg->bbLiveIn );
printf("] ,");
printf(" out = [ ");
dispLifeSet(comp, mask, beg->bbLiveOut);
printf("]");
if (beg->bbFlags & BBF_VISITED)
printf(" inner=%u", beg->bbFPinVars);
printf("\n");
beg = beg->bbNext;
if (!beg)
return;
}
while (beg != end);
}
#if FEATURE_STACK_FP_X87
void Compiler::raDispFPlifeInfo()
{
BasicBlock * block;
for (block = fgFirstBB;
block;
block = block->bbNext)
{
GenTreePtr stmt;
printf("BB%02u: in = [ ", block->bbNum);
dispLifeSet(this, optAllFloatVars, block->bbLiveIn);
printf("]\n\n");
VARSET_TP VARSET_INIT(this, life, block->bbLiveIn);
for (stmt = block->bbTreeList; stmt; stmt = stmt->gtNext)
{
GenTreePtr tree;
noway_assert(stmt->gtOper == GT_STMT);
for (tree = stmt->gtStmt.gtStmtList;
tree;
tree = tree->gtNext)
{
VarSetOps::AssignNoCopy(this, life, fgUpdateLiveSet(life, tree));
dispLifeSet(this, optAllFloatVars, life);
printf(" ");
gtDispTree(tree, 0, NULL, true);
}
printf("\n");
}
printf("BB%02u: out = [ ", block->bbNum);
dispLifeSet(this, optAllFloatVars, block->bbLiveOut);
printf("]\n\n");
}
}
#endif // FEATURE_STACK_FP_X87
/*****************************************************************************/
#endif//DEBUG
/*****************************************************************************/
/*****************************************************************************/
void Compiler::raSetRegVarOrder(var_types regType,
regNumber * customVarOrder,
unsigned * customVarOrderSize,
regMaskTP prefReg,
regMaskTP avoidReg)
{
unsigned normalVarOrderSize;
const regNumber * normalVarOrder = raGetRegVarOrder(regType, &normalVarOrderSize);
unsigned index;
unsigned listIndex = 0;
regMaskTP usedReg = avoidReg;
noway_assert(*customVarOrderSize >= normalVarOrderSize);
if (prefReg)
{
/* First place the preferred registers at the start of customVarOrder */
regMaskTP regBit;
regNumber regNum;
for (index = 0;
index < normalVarOrderSize;
index++)
{
regNum = normalVarOrder[index];
regBit = genRegMask(regNum);
if (usedReg & regBit)
continue;
if (prefReg & regBit)
{
usedReg |= regBit;
noway_assert(listIndex < normalVarOrderSize);
customVarOrder[listIndex++] = regNum;
prefReg -= regBit;
if (prefReg == 0)
break;
}
}
#if CPU_HAS_BYTE_REGS
/* Then if byteable registers are preferred place them */
if (prefReg & RBM_BYTE_REG_FLAG)
{
for (index = 0;
index < normalVarOrderSize;
index++)
{
regNum = normalVarOrder[index];
regBit = genRegMask(regNum);
if (usedReg & regBit)
continue;
if (RBM_BYTE_REGS & regBit)
{
usedReg |= regBit;
noway_assert(listIndex < normalVarOrderSize);
customVarOrder[listIndex++] = regNum;
}
}
}
#endif // CPU_HAS_BYTE_REGS
}
/* Now place all the non-preferred registers */
for (index = 0;
index < normalVarOrderSize;
index++)
{
regNumber regNum = normalVarOrder[index];
regMaskTP regBit = genRegMask(regNum);
if (usedReg & regBit)
continue;
usedReg |= regBit;
noway_assert(listIndex < normalVarOrderSize);
customVarOrder[listIndex++] = regNum;
}
if (avoidReg)
{
/* Now place the "avoid" registers */
for (index = 0;
index < normalVarOrderSize;
index++)
{
regNumber regNum = normalVarOrder[index];
regMaskTP regBit = genRegMask(regNum);
if (avoidReg & regBit)
{
noway_assert(listIndex < normalVarOrderSize);
customVarOrder[listIndex++] = regNum;
avoidReg -= regBit;
if (avoidReg == 0)
break;
}
}
}
*customVarOrderSize = listIndex;
noway_assert(listIndex == normalVarOrderSize);
}
/*****************************************************************************
*
* Setup the raAvoidArgRegMask and rsCalleeRegArgMaskLiveIn
*/
void Compiler::raSetupArgMasks(RegState *regState)
{
/* Determine the registers holding incoming register arguments */
/* and setup raAvoidArgRegMask to the set of registers that we */
/* may want to avoid when enregistering the locals. */
regState->rsCalleeRegArgMaskLiveIn = RBM_NONE;
raAvoidArgRegMask = RBM_NONE;
LclVarDsc * argsEnd = lvaTable + info.compArgsCount;
for (LclVarDsc * argDsc = lvaTable; argDsc < argsEnd; argDsc++)
{
noway_assert(argDsc->lvIsParam);
// Is it a register argument ?
if (!argDsc->lvIsRegArg)
continue;
// only process args that apply to the current register file
if ((argDsc->IsFloatRegType() && !info.compIsVarArgs) != regState->rsIsFloat)
{
continue;
}
// Is it dead on entry ??
// In certain cases such as when compJmpOpUsed is true,
// or when we have a generic type context arg that we must report
// then the arguments have to be kept alive throughout the prolog.
// So we have to consider it as live on entry.
//
bool keepArgAlive = compJmpOpUsed;
if ( (unsigned(info.compTypeCtxtArg) != BAD_VAR_NUM) &&
lvaReportParamTypeArg() &&
((lvaTable + info.compTypeCtxtArg) == argDsc) )
{
keepArgAlive = true;
}
if (!keepArgAlive && argDsc->lvTracked &&
!VarSetOps::IsMember(this, fgFirstBB->bbLiveIn, argDsc->lvVarIndex))
{
continue;
}
// The code to set the regState for each arg is outlined for shared use
// by linear scan
regNumber inArgReg = raUpdateRegStateForArg(regState, argDsc);
// Do we need to try to avoid this incoming arg registers?
// If it's not tracked, don't do the stuff below.
if (!argDsc->lvTracked) continue;
// If the incoming arg is used after a call it is live accross
// a call and will have to be allocated to a caller saved
// register anyway (a very common case).
//
// In this case it is pointless to ask that the higher ref count
// locals to avoid using the incoming arg register
unsigned argVarIndex = argDsc->lvVarIndex;
/* Does the incoming register and the arg variable interfere? */
if (!VarSetOps::IsMember(this, raLclRegIntf[inArgReg], argVarIndex))
{
// No they do not interfere,
// so we add inArgReg to raAvoidArgRegMask
raAvoidArgRegMask |= genRegMask(inArgReg);
}
#ifdef _TARGET_ARM_
if (argDsc->lvType == TYP_DOUBLE)
{
// Avoid the double register argument pair for register allocation.
if (!VarSetOps::IsMember(this, raLclRegIntf[inArgReg + 1], argVarIndex))
{
raAvoidArgRegMask |= genRegMask(static_cast<regNumber>(inArgReg + 1));
}
}
#endif
}
}
#endif // LEGACY_BACKEND
// The code to set the regState for each arg is outlined for shared use
// by linear scan
regNumber Compiler::raUpdateRegStateForArg(RegState *regState, LclVarDsc *argDsc)
{
regNumber inArgReg = argDsc->lvArgReg;
noway_assert(genRegMask(inArgReg) & (regState->rsIsFloat ? RBM_FLTARG_REGS : RBM_ARG_REGS));
regState->rsCalleeRegArgMaskLiveIn |= genRegMask(inArgReg);
#ifdef _TARGET_ARM_
if (argDsc->lvType == TYP_DOUBLE)
{
if (info.compIsVarArgs)
{
assert((inArgReg == REG_R0) || (inArgReg == REG_R2));
assert(!regState->rsIsFloat);
}
else
{
assert(regState->rsIsFloat);
assert(emitter::isDoubleReg(inArgReg));
}
regState->rsCalleeRegArgMaskLiveIn |= genRegMask((regNumber)(inArgReg+1));
}
else if (argDsc->lvType == TYP_LONG)
{
assert((inArgReg == REG_R0) || (inArgReg == REG_R2));
assert(!regState->rsIsFloat);
regState->rsCalleeRegArgMaskLiveIn |= genRegMask((regNumber)(inArgReg+1));
}
else if (argDsc->lvType == TYP_STRUCT)
{
if (argDsc->lvIsHfaRegArg)
{
assert(regState->rsIsFloat);
unsigned cSlots = GetHfaSlots(argDsc->lvVerTypeInfo.GetClassHandleForValueClass());
for (unsigned i = 1; i < cSlots; i++)
{
assert(inArgReg + i <= LAST_FP_ARGREG);
regState->rsCalleeRegArgMaskLiveIn |= genRegMask(static_cast<regNumber>(inArgReg + i));
}
}
else
{
unsigned cSlots = argDsc->lvSize() / TARGET_POINTER_SIZE;
for (unsigned i=1; i < cSlots; i++)
{
regNumber nextArgReg = (regNumber)(inArgReg + i);
if (nextArgReg > REG_ARG_LAST)
{
break;
}
assert(!regState->rsIsFloat);
regState->rsCalleeRegArgMaskLiveIn |= genRegMask(nextArgReg);
}
}
}
#endif
return inArgReg;
}
#ifdef LEGACY_BACKEND // We don't use any of the old register allocator functions when LSRA is used instead.
/*****************************************************************************
*
* Assign variables to live in registers, etc.
*/
void Compiler::raAssignVars()
{
#ifdef DEBUG
if (verbose)
printf("*************** In raAssignVars()\n");
#endif
/* We need to keep track of which registers we ever touch */
codeGen->regSet.rsClearRegsModified();
#if FEATURE_STACK_FP_X87
// FP register allocation
raEnregisterVarsStackFP();
raGenerateFPRefCounts();
#endif
/* Predict registers used by code generation */
rpPredictRegUse(); // New reg predictor/allocator
// Change all unused promoted non-argument struct locals to a non-GC type (in this case TYP_INT)
// so that the gc tracking logic and lvMustInit logic will ignore them.
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
if (varDsc->lvType != TYP_STRUCT)
continue;
if (!varDsc->lvPromoted)
continue;
if (varDsc->lvIsParam)
continue;
if (varDsc->lvRefCnt > 0)
continue;
#ifdef DEBUG
if (verbose)
{
printf("Mark unused struct local V%02u\n", lclNum);
}
lvaPromotionType promotionType = lvaGetPromotionType(varDsc);
if (promotionType == PROMOTION_TYPE_DEPENDENT)
{
// This should only happen when all its field locals are unused as well.
for (unsigned varNum = varDsc->lvFieldLclStart;
varNum < varDsc->lvFieldLclStart + varDsc->lvFieldCnt;
varNum++)
{
noway_assert(lvaTable[varNum].lvRefCnt == 0);
}
}
else
{
noway_assert(promotionType == PROMOTION_TYPE_INDEPENDENT);
}
varDsc->lvUnusedStruct = 1;
#endif
// Change such struct locals to ints
varDsc->lvType = TYP_INT; // Bash to a non-gc type.
noway_assert(!varDsc->lvTracked);
noway_assert(!varDsc->lvRegister);
varDsc->lvOnFrame = false; // Force it not to be onstack.
varDsc->lvMustInit = false; // Force not to init it.
varDsc->lvStkOffs = 0; // Set it to anything other than BAD_STK_OFFS to make genSetScopeInfo() happy
}
}
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************
*
* Given a regNumber return the correct predictReg enum value
*/
inline static rpPredictReg rpGetPredictForReg(regNumber reg)
{
return (rpPredictReg) ( ((int) reg) + ((int) PREDICT_REG_FIRST) );
}
/*****************************************************************************
*
* Given a varIndex return the correct predictReg enum value
*/
inline static rpPredictReg rpGetPredictForVarIndex(unsigned varIndex)
{
return (rpPredictReg) ( varIndex + ((int) PREDICT_REG_VAR_T00) );
}
/*****************************************************************************
*
* Given a rpPredictReg return the correct varNumber value
*/
inline static unsigned rpGetVarIndexForPredict(rpPredictReg predict)
{
return (unsigned) predict - (unsigned) PREDICT_REG_VAR_T00;
}
/*****************************************************************************
*
* Given a rpPredictReg return true if it specifies a Txx register
*/
inline static bool rpHasVarIndexForPredict(rpPredictReg predict)
{
if ((predict >= PREDICT_REG_VAR_T00) && (predict <= PREDICT_REG_VAR_MAX))
return true;
else
return false;
}
/*****************************************************************************
*
* Given a regmask return the correct predictReg enum value
*/
static rpPredictReg rpGetPredictForMask(regMaskTP regmask)
{
rpPredictReg result = PREDICT_NONE;
if (regmask != 0) /* Check if regmask has zero bits set */
{
if (((regmask-1) & regmask) == 0) /* Check if regmask has one bit set */
{
DWORD reg = 0;
assert(FitsIn<DWORD>(regmask));
BitScanForward(®, (DWORD)regmask);
return rpGetPredictForReg((regNumber)reg);
}
/* It has multiple bits set */
#if defined(_TARGET_ARM_)
else if (regmask == (RBM_R0 | RBM_R1)) { result = PREDICT_PAIR_R0R1; }
else if (regmask == (RBM_R2 | RBM_R3)) { result = PREDICT_PAIR_R2R3; }
#elif defined(_TARGET_X86_)
else if (regmask == (RBM_EAX | RBM_EDX)) { result = PREDICT_PAIR_EAXEDX; }
else if (regmask == (RBM_ECX | RBM_EBX)) { result = PREDICT_PAIR_ECXEBX; }
#endif
else /* It doesn't match anything */
{
result = PREDICT_NONE;
assert(!"unreachable");
NO_WAY("bad regpair");
}
}
return result;
}
/*****************************************************************************
*
* Record a variable to register(s) interference
*/
bool Compiler::rpRecordRegIntf(regMaskTP regMask,
VARSET_VALARG_TP life
DEBUGARG( const char * msg))
{
bool addedIntf = false;
if (regMask != 0)
{
for (regNumber regNum = REG_FIRST; regNum < REG_COUNT; regNum = REG_NEXT(regNum))
{
regMaskTP regBit = genRegMask(regNum);
if (regMask & regBit)
{
VARSET_TP VARSET_INIT_NOCOPY(newIntf, VarSetOps::Diff(this, life, raLclRegIntf[regNum]));
if (!VarSetOps::IsEmpty(this, newIntf))
{
#ifdef DEBUG
if (verbose)
{
VARSET_ITER_INIT(this, newIntfIter, newIntf, varNum);
while (newIntfIter.NextElem(this, &varNum))
{
unsigned lclNum = lvaTrackedToVarNum[varNum];
LclVarDsc * varDsc = &lvaTable[varNum];
#if FEATURE_FP_REGALLOC
// Only print the useful interferences
// i.e. floating point LclVar interference with floating point registers
// or integer LclVar interference with general purpose registers
if (varTypeIsFloating(varDsc->TypeGet()) == genIsValidFloatReg(regNum))
#endif
{
printf("Record interference between V%02u,T%02u and %s -- %s\n",
lclNum, varNum, getRegName(regNum), msg);
}
}
}
#endif
addedIntf = true;
VarSetOps::UnionD(this, raLclRegIntf[regNum], newIntf);
}
regMask -= regBit;
if (regMask == 0)
break;
}
}
}
return addedIntf;
}
/*****************************************************************************
*
* Record a new variable to variable(s) interference
*/
bool Compiler::rpRecordVarIntf(unsigned varNum,
VARSET_VALARG_TP intfVar
DEBUGARG( const char * msg))
{
noway_assert((varNum >= 0) && (varNum < lvaTrackedCount));
noway_assert(!VarSetOps::IsEmpty(this, intfVar));
VARSET_TP VARSET_INIT_NOCOPY(oneVar, VarSetOps::MakeEmpty(this));
VarSetOps::AddElemD(this, oneVar, varNum);
bool newIntf = fgMarkIntf(intfVar, oneVar);
if (newIntf)
rpAddedVarIntf = true;
#ifdef DEBUG
if (verbose && newIntf)
{
for (unsigned oneNum = 0; oneNum < lvaTrackedCount; oneNum++)
{
if (VarSetOps::IsMember(this, intfVar, oneNum))
{
unsigned lclNum = lvaTrackedToVarNum[varNum];
unsigned lclOne = lvaTrackedToVarNum[oneNum];
printf("Record interference between V%02u,T%02u and V%02u,T%02u -- %s\n",
lclNum, varNum, lclOne, oneNum, msg);
}
}
}
#endif
return newIntf;
}
/*****************************************************************************
*
* Determine preferred register mask for a given predictReg value
*/
inline regMaskTP Compiler::rpPredictRegMask(rpPredictReg predictReg, var_types type)
{
if (rpHasVarIndexForPredict(predictReg))
predictReg = PREDICT_REG;
noway_assert((unsigned)predictReg < sizeof(rpPredictMap)/sizeof(rpPredictMap[0]));
noway_assert(rpPredictMap[predictReg] != RBM_ILLEGAL);
regMaskTP regAvailForType = rpPredictMap[predictReg];
if (varTypeIsFloating(type))
{
regAvailForType &= RBM_ALLFLOAT;
}
else
{
regAvailForType &= RBM_ALLINT;
}
#ifdef _TARGET_ARM_
if (type == TYP_DOUBLE)
{
if ((predictReg >= PREDICT_REG_F0) && (predictReg <= PREDICT_REG_F31))
{
// Fix 388433 ARM JitStress WP7
if ((regAvailForType & RBM_DBL_REGS) != 0)
{
regAvailForType |= (regAvailForType<<1);
}
else
{
regAvailForType = RBM_NONE;
}
}
}
#endif
return regAvailForType;
}
/*****************************************************************************
*
* Predict register choice for a type.
*
* Adds the predicted registers to rsModifiedRegsMask.
*/
regMaskTP Compiler::rpPredictRegPick(var_types type,
rpPredictReg predictReg,
regMaskTP lockedRegs)
{
regMaskTP preferReg = rpPredictRegMask(predictReg, type);
regNumber regNum;
regMaskTP regBits;
// Add any reserved register to the lockedRegs
lockedRegs |= codeGen->regSet.rsMaskResvd;
/* Clear out the lockedRegs from preferReg */
preferReg &= ~lockedRegs;
if (rpAsgVarNum != -1)
{
noway_assert((rpAsgVarNum >= 0) && (rpAsgVarNum < (int)lclMAX_TRACKED));
/* Don't pick the register used by rpAsgVarNum either */
LclVarDsc * tgtVar = lvaTable + lvaTrackedToVarNum[rpAsgVarNum];
noway_assert(tgtVar->lvRegNum != REG_STK);
preferReg &= ~genRegMask(tgtVar->lvRegNum);
}
switch (type)
{
case TYP_BOOL:
case TYP_BYTE:
case TYP_UBYTE:
case TYP_SHORT:
case TYP_CHAR:
case TYP_INT:
case TYP_UINT:
case TYP_REF:
case TYP_BYREF:
#ifdef _TARGET_AMD64_
case TYP_LONG:
#endif // _TARGET_AMD64_
// expand preferReg to all non-locked registers if no bits set
preferReg = codeGen->regSet.rsUseIfZero(preferReg & RBM_ALLINT, RBM_ALLINT & ~lockedRegs);
if (preferReg == 0) // no bits set?
{
// Add one predefined spill choice register if no bits set.
// (The jit will introduce one spill temp)
preferReg |= RBM_SPILL_CHOICE;
rpPredictSpillCnt++;
#ifdef DEBUG
if (verbose)
printf("Predict one spill temp\n");
#endif
}
if (preferReg != 0)
{
/* Iterate the registers in the order specified by rpRegTmpOrder */
for (unsigned index = 0;
index < REG_TMP_ORDER_COUNT;
index++)
{
regNum = rpRegTmpOrder[index];
regBits = genRegMask(regNum);
if ((preferReg & regBits) == regBits)
{
goto RET;
}
}
}
/* Otherwise we have allocated all registers, so do nothing */
break;
#ifndef _TARGET_AMD64_
case TYP_LONG:
if (( preferReg == 0) || // no bits set?
((preferReg & (preferReg-1)) == 0) ) // or only one bit set?
{
// expand preferReg to all non-locked registers
preferReg = RBM_ALLINT & ~lockedRegs;
}
if (preferReg == 0) // no bits set?
{
// Add EAX:EDX to the registers
// (The jit will introduce two spill temps)
preferReg = RBM_PAIR_TMP;
rpPredictSpillCnt += 2;
#ifdef DEBUG
if (verbose)
printf("Predict two spill temps\n");
#endif
}
else if ((preferReg & (preferReg-1)) == 0) // only one bit set?
{
if ((preferReg & RBM_PAIR_TMP_LO) == 0)
{
// Add EAX to the registers
// (The jit will introduce one spill temp)
preferReg |= RBM_PAIR_TMP_LO;
}
else
{
// Add EDX to the registers
// (The jit will introduce one spill temp)
preferReg |= RBM_PAIR_TMP_HI;
}
rpPredictSpillCnt++;
#ifdef DEBUG
if (verbose)
printf("Predict one spill temp\n");
#endif
}
regPairNo regPair;
regPair = codeGen->regSet.rsFindRegPairNo(preferReg);
if (regPair != REG_PAIR_NONE)
{
regBits = genRegPairMask(regPair);
goto RET;
}
/* Otherwise we have allocated all registers, so do nothing */
break;
#endif // _TARGET_AMD64_
#ifdef _TARGET_ARM_
case TYP_STRUCT:
#endif
case TYP_FLOAT:
case TYP_DOUBLE:
#if FEATURE_FP_REGALLOC
regMaskTP restrictMask; restrictMask = (raConfigRestrictMaskFP() | RBM_FLT_CALLEE_TRASH);
assert((restrictMask & RBM_SPILL_CHOICE_FLT) == RBM_SPILL_CHOICE_FLT);
// expand preferReg to all available non-locked registers if no bits set
preferReg = codeGen->regSet.rsUseIfZero(preferReg & restrictMask, restrictMask & ~lockedRegs);
regMaskTP preferDouble; preferDouble = preferReg & (preferReg>>1);
if ( (preferReg == 0) // no bits set?
#ifdef _TARGET_ARM_
|| ((type == TYP_DOUBLE) && ((preferReg & (preferReg>>1)) == 0) ) // or two consecutive bits set for TYP_DOUBLE
#endif
)
{
// Add one predefined spill choice register if no bits set.
// (The jit will introduce one spill temp)
preferReg |= RBM_SPILL_CHOICE_FLT;
rpPredictSpillCnt++;
#ifdef DEBUG
if (verbose)
printf("Predict one spill temp (float)\n");
#endif
}
assert(preferReg != 0);
/* Iterate the registers in the order specified by raRegFltTmpOrder */
for (unsigned index = 0;
index < REG_FLT_TMP_ORDER_COUNT;
index++)
{
regNum = raRegFltTmpOrder[index];
regBits = genRegMask(regNum);
if (varTypeIsFloating(type))
{
#ifdef _TARGET_ARM_
if (type == TYP_DOUBLE)
{
if ((regBits & RBM_DBL_REGS) == 0)
{
continue; // We must restrict the set to the double registers
}
else
{
// TYP_DOUBLE use two consecutive registers
regBits |= genRegMask(REG_NEXT(regNum));
}
}
#endif
// See if COMPLUS_JitRegisterFP is restricting this FP register
//
if ((restrictMask & regBits) != regBits)
continue;
}
if ((preferReg & regBits) == regBits)
{
goto RET;
}
}
/* Otherwise we have allocated all registers, so do nothing */
break;
#else // !FEATURE_FP_REGALLOC
return RBM_NONE;
#endif
default:
noway_assert(!"unexpected type in reg use prediction");
}
/* Abnormal return */
noway_assert(!"Ran out of registers in rpPredictRegPick");
return RBM_NONE;
RET:
/*
* If during the first prediction we need to allocate
* one of the registers that we used for coloring locals
* then flag this by setting rpPredictAssignAgain.
* We will have to go back and repredict the registers
*/
if ((rpPasses == 0) && ((rpPredictAssignMask & regBits) == regBits))
rpPredictAssignAgain = true;
// Add a register interference to each of the last use variables
if (!VarSetOps::IsEmpty(this, rpLastUseVars) || !VarSetOps::IsEmpty(this, rpUseInPlace))
{
VARSET_TP VARSET_INIT_NOCOPY(lastUse, VarSetOps::MakeEmpty(this)); VarSetOps::Assign(this, lastUse, rpLastUseVars);
VARSET_TP VARSET_INIT_NOCOPY(inPlaceUse, VarSetOps::MakeEmpty(this)); VarSetOps::Assign(this, inPlaceUse, rpUseInPlace);
// While we still have any lastUse or inPlaceUse bits
VARSET_TP VARSET_INIT_NOCOPY(useUnion, VarSetOps::Union(this, lastUse, inPlaceUse));
VARSET_TP VARSET_INIT_NOCOPY(varAsSet, VarSetOps::MakeEmpty(this));
VARSET_ITER_INIT(this, iter, useUnion, varNum);
while (iter.NextElem(this, &varNum))
{
// We'll need this for one of the calls...
VarSetOps::ClearD(this, varAsSet); VarSetOps::AddElemD(this, varAsSet, varNum);
// If this varBit and lastUse?
if (VarSetOps::IsMember(this, lastUse, varNum))
{
// Record a register to variable interference
rpRecordRegIntf(regBits, varAsSet
DEBUGARG( "last use RegPick"));
}
// If this varBit and inPlaceUse?
if (VarSetOps::IsMember(this, inPlaceUse, varNum))
{
// Record a register to variable interference
rpRecordRegIntf(regBits, varAsSet
DEBUGARG( "used in place RegPick"));
}
}
}
codeGen->regSet.rsSetRegsModified(regBits);
return regBits;
}
/*****************************************************************************
*
* Predict integer register use for generating an address mode for a tree,
* by setting tree->gtUsedRegs to all registers used by this tree and its
* children.
* tree - is the child of a GT_IND node
* type - the type of the GT_IND node (floating point/integer)
* lockedRegs - are the registers which are currently held by
* a previously evaluated node.
* rsvdRegs - registers which should not be allocated because they will
* be needed to evaluate a node in the future
* - Also if rsvdRegs has the RBM_LASTUSE bit set then
* the rpLastUseVars set should be saved and restored
* so that we don't add any new variables to rpLastUseVars
* lenCSE - is non-NULL only when we have a lenCSE expression
*
* Return the scratch registers to be held by this tree. (one or two registers
* to form an address expression)
*/
regMaskTP Compiler::rpPredictAddressMode(GenTreePtr tree,
var_types type,
regMaskTP lockedRegs,
regMaskTP rsvdRegs,
GenTreePtr lenCSE)
{
GenTreePtr op1;
GenTreePtr op2;
GenTreePtr opTemp;
genTreeOps oper = tree->OperGet();
regMaskTP op1Mask;
regMaskTP op2Mask;
regMaskTP regMask;
ssize_t sh;
ssize_t cns = 0;
bool rev;
bool hasTwoAddConst = false;
bool restoreLastUseVars = false;
VARSET_TP VARSET_INIT_NOCOPY(oldLastUseVars, VarSetOps::MakeEmpty(this));
/* do we need to save and restore the rpLastUseVars set ? */
if ((rsvdRegs & RBM_LASTUSE) && (lenCSE == NULL))
{
restoreLastUseVars = true;
VarSetOps::Assign(this, oldLastUseVars, rpLastUseVars);
}
rsvdRegs &= ~RBM_LASTUSE;
/* if not an add, then just force it to a register */
if (oper != GT_ADD)
{
if (oper == GT_ARR_ELEM)
{
regMask = rpPredictTreeRegUse(tree, PREDICT_NONE, lockedRegs, rsvdRegs);
goto DONE;
}
else
{
goto NO_ADDR_EXPR;
}
}
op1 = tree->gtOp.gtOp1;
op2 = tree->gtOp.gtOp2;
rev = ((tree->gtFlags & GTF_REVERSE_OPS) != 0);
/* look for (x + y) + icon address mode */
if (op2->OperGet() == GT_CNS_INT)
{
cns = op2->gtIntCon.gtIconVal;
/* if not an add, then just force op1 into a register */
if (op1->OperGet() != GT_ADD)
goto ONE_ADDR_EXPR;
hasTwoAddConst = true;
/* Record the 'rev' flag, reverse evaluation order */
rev = ((op1->gtFlags & GTF_REVERSE_OPS) != 0);
op2 = op1->gtOp.gtOp2;
op1 = op1->gtOp.gtOp1; // Overwrite op1 last!!
}
/* Check for CNS_INT or LSH of CNS_INT in op2 slot */
sh = 0;
if (op2->OperGet() == GT_LSH)
{
if (op2->gtOp.gtOp2->OperGet() == GT_CNS_INT)
{
sh = op2->gtOp.gtOp2->gtIntCon.gtIconVal;
opTemp = op2->gtOp.gtOp1;
}
else
{
opTemp = NULL;
}
}
else
{
opTemp = op2;
}
if (opTemp != NULL)
{
if (opTemp->OperGet() == GT_NOP)
{
opTemp = opTemp->gtOp.gtOp1;
}
// Is this a const operand?
if (opTemp->OperGet() == GT_CNS_INT)
{
// Compute the new cns value that Codegen will end up using
cns += (opTemp->gtIntCon.gtIconVal << sh);
goto ONE_ADDR_EXPR;
}
}
/* Check for LSH in op1 slot */
if (op1->OperGet() != GT_LSH)
goto TWO_ADDR_EXPR;
opTemp = op1->gtOp.gtOp2;
if (opTemp->OperGet() != GT_CNS_INT)
goto TWO_ADDR_EXPR;
sh = opTemp->gtIntCon.gtIconVal;
/* Check for LSH of 0, special case */
if (sh == 0)
goto TWO_ADDR_EXPR;
#if defined(_TARGET_XARCH_)
/* Check for LSH of 1 2 or 3 */
if (sh > 3)
goto TWO_ADDR_EXPR;
#elif defined(_TARGET_ARM_)
/* Check for LSH of 1 to 30 */
if (sh > 30)
goto TWO_ADDR_EXPR;
#else
goto TWO_ADDR_EXPR;
#endif
/* Matched a leftShift by 'sh' subtree, move op1 down */
op1 = op1->gtOp.gtOp1;
TWO_ADDR_EXPR:
/* Now we have to evaluate op1 and op2 into registers */
/* Evaluate op1 and op2 in the correct order */
if (rev)
{
op2Mask = rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
op1Mask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs | op2Mask, rsvdRegs);
}
else
{
op1Mask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
op2Mask = rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs | op1Mask, rsvdRegs);
}
/* If op1 and op2 must be spilled and reloaded then
* op1 and op2 might be reloaded into the same register
* This can only happen when all the registers are lockedRegs
*/
if ((op1Mask == op2Mask) && (op1Mask != 0))
{
/* We'll need to grab a different register for op2 */
op2Mask = rpPredictRegPick(TYP_INT, PREDICT_REG, op1Mask);
}
#ifdef _TARGET_ARM_
// On the ARM we need a scratch register to evaluate the shifted operand for trees that have this form
// [op2 + op1<<sh + cns]
// when op1 is an enregistered variable, thus the op1Mask is RBM_NONE
//
if (hasTwoAddConst && (sh != 0) && (op1Mask == RBM_NONE))
{
op1Mask |= rpPredictRegPick(TYP_INT, PREDICT_REG, (lockedRegs | op1Mask | op2Mask));
}
//
// On the ARM we will need at least one scratch register for trees that have this form:
// [op1 + op2 + cns] or [op1 + op2<<sh + cns]
// or for a float/double or long when we have both op1 and op2
// or when we have an 'cns' that is too large for the ld/st instruction
//
if (hasTwoAddConst || varTypeIsFloating(type) || (type == TYP_LONG) || !codeGen->validDispForLdSt(cns, type))
{
op2Mask |= rpPredictRegPick(TYP_INT, PREDICT_REG, (lockedRegs | op1Mask | op2Mask));
}
//
// If we create a CSE that immediately dies then we may need to add an additional register interference
// so we don't color the CSE into R3
//
if (!rev && (op1Mask != RBM_NONE) && (op2->OperGet() == GT_COMMA))
{
opTemp = op2->gtOp.gtOp2;
if (opTemp->OperGet() == GT_LCL_VAR)
{
unsigned varNum = opTemp->gtLclVar.gtLclNum;
LclVarDsc * varDsc = &lvaTable[varNum];
if (varDsc->lvTracked && !VarSetOps::IsMember(this, compCurLife, varDsc->lvVarIndex))
{
rpRecordRegIntf(RBM_TMP_0, VarSetOps::MakeSingleton(this, varDsc->lvVarIndex)
DEBUGARG( "dead CSE (gt_ind)"));
}
}
}
#endif
regMask = (op1Mask | op2Mask);
tree->gtUsedRegs = (regMaskSmall)regMask;
goto DONE;
ONE_ADDR_EXPR:
/* now we have to evaluate op1 into a register */
op1Mask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs);
op2Mask = RBM_NONE;
#ifdef _TARGET_ARM_
//
// On the ARM we will need another scratch register when we have an 'cns' that is too large for the ld/st instruction
//
if (!codeGen->validDispForLdSt(cns, type))
{
op2Mask |= rpPredictRegPick(TYP_INT, PREDICT_REG, (lockedRegs | op1Mask | op2Mask));
}
#endif
regMask = (op1Mask | op2Mask);
tree->gtUsedRegs = (regMaskSmall)regMask;
goto DONE;
NO_ADDR_EXPR:
#if !CPU_LOAD_STORE_ARCH
if (oper == GT_CNS_INT)
{
/* Indirect of a constant does not require a register */
regMask = RBM_NONE;
}
else
#endif
{
/* now we have to evaluate tree into a register */
regMask = rpPredictTreeRegUse(tree, PREDICT_REG, lockedRegs, rsvdRegs);
}
DONE:
regMaskTP regUse = tree->gtUsedRegs;
if (!VarSetOps::IsEmpty(this, compCurLife))
{
// Add interference between the current set of life variables and
// the set of temporary registers need to evaluate the sub tree
if (regUse)
{
rpRecordRegIntf(regUse, compCurLife
DEBUGARG( "tmp use (gt_ind)"));
}
}
/* Do we need to resore the oldLastUseVars value */
if (restoreLastUseVars)
{
/*
* If we used a GT_ASG targeted register then we need to add
* a variable interference between any new last use variables
* and the GT_ASG targeted register
*/
if (!VarSetOps::Equal(this, rpLastUseVars, oldLastUseVars) && rpAsgVarNum != -1)
{
rpRecordVarIntf(rpAsgVarNum,
VarSetOps::Diff(this, rpLastUseVars, oldLastUseVars)
DEBUGARG( "asgn conflict (gt_ind)"));
}
VarSetOps::Assign(this, rpLastUseVars, oldLastUseVars);
}
return regMask;
}
/*****************************************************************************
*
*
*/
void Compiler::rpPredictRefAssign(unsigned lclNum)
{
LclVarDsc * varDsc = lvaTable + lclNum;
varDsc->lvRefAssign = 1;
#if NOGC_WRITE_BARRIERS
#ifdef DEBUG
if (verbose)
{
if (!VarSetOps::IsMember(this, raLclRegIntf[REG_EDX], varDsc->lvVarIndex))
printf("Record interference between V%02u,T%02u and REG WRITE BARRIER -- ref assign\n",
lclNum, varDsc->lvVarIndex);
}
#endif
/* Make sure that write barrier pointer variables never land in EDX */
VarSetOps::AddElemD(this, raLclRegIntf[REG_EDX], varDsc->lvVarIndex);
#endif // NOGC_WRITE_BARRIERS
}
/*****************************************************************************
*
* Predict the internal temp physical register usage for a tree by setting tree->gtUsedRegs.
* Returns a regMask with the internal temp physical register usage for this tree.
*
* Each of the switch labels in this function updates regMask and assigns tree->gtUsedRegs
* to the set of scratch registers needed when evaluating the tree.
* Generally tree->gtUsedRegs and the return value retMask are the same, except when the
* parameter "lockedRegs" conflicts with the computed tree->gtUsedRegs, in which case we
* predict additional internal temp physical registers to spill into.
*
* tree - is the child of a GT_IND node
* predictReg - what type of register does the tree need
* lockedRegs - are the registers which are currently held by a previously evaluated node.
* Don't modify lockedRegs as it is used at the end to compute a spill mask.
* rsvdRegs - registers which should not be allocated because they will
* be needed to evaluate a node in the future
* - Also, if rsvdRegs has the RBM_LASTUSE bit set then
* the rpLastUseVars set should be saved and restored
* so that we don't add any new variables to rpLastUseVars.
*/
#pragma warning(disable:4701)
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
regMaskTP Compiler::rpPredictTreeRegUse(GenTreePtr tree,
rpPredictReg predictReg,
regMaskTP lockedRegs,
regMaskTP rsvdRegs)
{
regMaskTP regMask = DUMMY_INIT(RBM_ILLEGAL);
regMaskTP op2Mask;
regMaskTP tmpMask;
rpPredictReg op1PredictReg;
rpPredictReg op2PredictReg;
LclVarDsc * varDsc = NULL;
VARSET_TP VARSET_INIT_NOCOPY(oldLastUseVars, VarSetOps::UninitVal());
VARSET_TP VARSET_INIT_NOCOPY(varBits, VarSetOps::UninitVal());
VARSET_TP VARSET_INIT_NOCOPY(lastUseVarBits, VarSetOps::MakeEmpty(this));
bool restoreLastUseVars = false;
regMaskTP interferingRegs = RBM_NONE;
#ifdef DEBUG
// if (verbose) printf("rpPredictTreeRegUse() [%08x]\n", tree);
noway_assert(tree);
noway_assert(((RBM_ILLEGAL & RBM_ALLINT) == 0));
noway_assert(RBM_ILLEGAL);
noway_assert((lockedRegs & RBM_ILLEGAL) == 0);
/* impossible values, to make sure that we set them */
tree->gtUsedRegs = RBM_ILLEGAL;
#endif
/* Figure out what kind of a node we have */
genTreeOps oper = tree->OperGet();
var_types type = tree->TypeGet();
unsigned kind = tree->OperKind();
// In the comma case, we care about whether this is "effectively" ADDR(IND(...))
genTreeOps effectiveOper = tree->gtEffectiveVal()->OperGet();
if ((predictReg == PREDICT_ADDR) && (effectiveOper != GT_IND))
predictReg = PREDICT_NONE;
else if (rpHasVarIndexForPredict(predictReg))
{
// The only place where predictReg is set to a var is in the PURE
// assignment case where varIndex is the var being assigned to.
// We need to check whether the variable is used between here and
// its redefinition.
unsigned varIndex = rpGetVarIndexForPredict(predictReg);
unsigned lclNum = lvaTrackedToVarNum[varIndex];
bool found = false;
for (GenTreePtr nextTree = tree->gtNext;
nextTree != NULL && !found;
nextTree = nextTree->gtNext)
{
if (nextTree->gtOper == GT_LCL_VAR && nextTree->gtLclVarCommon.gtLclNum == lclNum)
{
// Is this the pure assignment?
if ((nextTree->gtFlags & GTF_VAR_DEF) == 0)
{
predictReg = PREDICT_SCRATCH_REG;
}
found = true;
break;
}
}
assert (found);
}
if (rsvdRegs & RBM_LASTUSE)
{
restoreLastUseVars = true;
VarSetOps::Assign(this, oldLastUseVars, rpLastUseVars);
rsvdRegs &= ~RBM_LASTUSE;
}
/* Is this a constant or leaf node? */
if (kind & (GTK_CONST | GTK_LEAF))
{
bool lastUse = false;
regMaskTP enregMask = RBM_NONE;
switch (oper)
{
#ifdef _TARGET_ARM_
case GT_CNS_DBL:
// Codegen for floating point constants on the ARM is currently
// movw/movt rT1, <lo32 bits>
// movw/movt rT2, <hi32 bits>
// vmov.i2d dT0, rT1,rT2
//
// For TYP_FLOAT one integer register is required
//
// These integer register(s) immediately die
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs);
if (type == TYP_DOUBLE)
{
// For TYP_DOUBLE a second integer register is required
//
tmpMask |= rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs | tmpMask);
}
// We also need a floating point register that we keep
//
if (predictReg == PREDICT_NONE)
predictReg = PREDICT_SCRATCH_REG;
regMask = rpPredictRegPick(type, predictReg, lockedRegs | rsvdRegs);
tree->gtUsedRegs = regMask | tmpMask;
goto RETURN_CHECK;
#endif
case GT_CNS_INT:
case GT_CNS_LNG:
if (rpHasVarIndexForPredict(predictReg))
{
unsigned tgtIndex = rpGetVarIndexForPredict(predictReg);
rpAsgVarNum = tgtIndex;
// We don't need any register as we plan on writing to the rpAsgVarNum register
predictReg = PREDICT_NONE;
LclVarDsc * tgtVar = lvaTable + lvaTrackedToVarNum[tgtIndex];
tgtVar->lvDependReg = true;
if (type == TYP_LONG)
{
assert(oper == GT_CNS_LNG);
if (tgtVar->lvOtherReg == REG_STK)
{
// Well we do need one register for a partially enregistered
type = TYP_INT;
predictReg = PREDICT_SCRATCH_REG;
}
}
}
else
{
#if !CPU_LOAD_STORE_ARCH
/* If the constant is a handle then it will need to have a relocation
applied to it. It will need to be loaded into a register.
But never throw away an existing hint.
*/
if (opts.compReloc && tree->IsCnsIntOrI() && tree->IsIconHandle())
#endif
{
if (predictReg == PREDICT_NONE)
predictReg = PREDICT_SCRATCH_REG;
}
}
break;
case GT_NO_OP:
break;
case GT_CLS_VAR:
if ((predictReg == PREDICT_NONE) &&
(genActualType(type) == TYP_INT) &&
(genTypeSize(type) < sizeof(int)) )
{
predictReg = PREDICT_SCRATCH_REG;
}
#ifdef _TARGET_ARM_
// Unaligned loads/stores for floating point values must first be loaded into integer register(s)
//
if ((tree->gtFlags & GTF_IND_UNALIGNED) && varTypeIsFloating(type))
{
// These integer register(s) immediately die
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs);
// Two integer registers are required for a TYP_DOUBLE
if (type == TYP_DOUBLE)
tmpMask |= rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs | tmpMask);
}
// We need a temp register in some cases of loads/stores to a class var
if (predictReg == PREDICT_NONE)
{
predictReg = PREDICT_SCRATCH_REG;
}
#endif
if (rpHasVarIndexForPredict(predictReg))
{
unsigned tgtIndex = rpGetVarIndexForPredict(predictReg);
rpAsgVarNum = tgtIndex;
// We don't need any register as we plan on writing to the rpAsgVarNum register
predictReg = PREDICT_NONE;
LclVarDsc * tgtVar = lvaTable + lvaTrackedToVarNum[tgtIndex];
tgtVar->lvDependReg = true;
if (type == TYP_LONG)
{
if (tgtVar->lvOtherReg == REG_STK)
{
// Well we do need one register for a partially enregistered
type = TYP_INT;
predictReg = PREDICT_SCRATCH_REG;
}
}
}
break;
case GT_LCL_FLD:
#ifdef _TARGET_ARM_
// Check for a misalignment on a Floating Point field
//
if (varTypeIsFloating(type))
{
if ((tree->gtLclFld.gtLclOffs % emitTypeSize(tree->TypeGet())) != 0)
{
// These integer register(s) immediately die
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs);
// Two integer registers are required for a TYP_DOUBLE
if (type == TYP_DOUBLE)
tmpMask |= rpPredictRegPick(TYP_INT, PREDICT_REG, lockedRegs | rsvdRegs | tmpMask);
}
}
#endif
__fallthrough;
case GT_LCL_VAR:
case GT_REG_VAR:
varDsc = lvaTable + tree->gtLclVarCommon.gtLclNum;
VarSetOps::Assign(this, varBits, fgGetVarBits(tree));
compUpdateLifeVar</*ForCodeGen*/false>(tree, &lastUseVarBits);
lastUse = !VarSetOps::IsEmpty(this, lastUseVarBits);
#if FEATURE_STACK_FP_X87
// If it's a floating point var, there's nothing to do
if (varTypeIsFloating(type))
{
tree->gtUsedRegs = RBM_NONE;
regMask = RBM_NONE;
goto RETURN_CHECK;
}
#endif
// If the variable is already a register variable, no need to go further.
if (oper == GT_REG_VAR)
break;
/* Apply the type of predictReg to the LCL_VAR */
if (predictReg == PREDICT_REG)
{
PREDICT_REG_COMMON:
if (varDsc->lvRegNum == REG_STK)
break;
goto GRAB_COUNT;
}
else if (predictReg == PREDICT_SCRATCH_REG)
{
noway_assert(predictReg == PREDICT_SCRATCH_REG);
/* Is this the last use of a local var? */
if (lastUse)
{
if (VarSetOps::IsEmptyIntersection(this, rpUseInPlace, lastUseVarBits))
goto PREDICT_REG_COMMON;
}
}
else if (rpHasVarIndexForPredict(predictReg))
{
/* Get the tracked local variable that has an lvVarIndex of tgtIndex1 */
{
unsigned tgtIndex1 = rpGetVarIndexForPredict(predictReg);
LclVarDsc * tgtVar = lvaTable + lvaTrackedToVarNum[tgtIndex1];
VarSetOps::MakeSingleton(this, tgtIndex1);
noway_assert(tgtVar->lvVarIndex == tgtIndex1);
noway_assert(tgtVar->lvRegNum != REG_STK); /* Must have been enregistered */
#ifndef _TARGET_AMD64_
// On amd64 we have the occasional spec-allowed implicit conversion from TYP_I_IMPL to TYP_INT
// so this assert is meaningless
noway_assert((type != TYP_LONG) || (tgtVar->TypeGet() == TYP_LONG));
#endif // !_TARGET_AMD64_
if (varDsc->lvTracked)
{
unsigned srcIndex; srcIndex = varDsc->lvVarIndex;
// If this register has it's last use here then we will prefer
// to color to the same register as tgtVar.
if (lastUse)
{
/*
* Add an entry in the lvaVarPref graph to indicate
* that it would be worthwhile to color these two variables
* into the same physical register.
* This will help us avoid having an extra copy instruction
*/
VarSetOps::AddElemD(this, lvaVarPref[srcIndex], tgtIndex1);
VarSetOps::AddElemD(this, lvaVarPref[tgtIndex1], srcIndex);
}
// Add a variable interference from srcIndex to each of the last use variables
if (!VarSetOps::IsEmpty(this, rpLastUseVars))
{
rpRecordVarIntf(srcIndex, rpLastUseVars
DEBUGARG( "src reg conflict"));
}
}
rpAsgVarNum = tgtIndex1;
/* We will rely on the target enregistered variable from the GT_ASG */
varDsc = tgtVar;
}
GRAB_COUNT:
unsigned grabCount; grabCount = 0;
if (genIsValidFloatReg(varDsc->lvRegNum))
{
enregMask = genRegMaskFloat(varDsc->lvRegNum, varDsc->TypeGet());
}
else
{
enregMask = genRegMask(varDsc->lvRegNum);
}
#ifdef _TARGET_ARM_
if ((type == TYP_DOUBLE) && (varDsc->TypeGet() == TYP_FLOAT))
{
// We need to compute the intermediate value using a TYP_DOUBLE
// but we storing the result in a TYP_SINGLE enregistered variable
//
grabCount++;
}
else
#endif
{
/* We can't trust a prediction of rsvdRegs or lockedRegs sets */
if (enregMask & (rsvdRegs | lockedRegs))
{
grabCount++;
}
#ifndef _TARGET_64BIT_
if (type == TYP_LONG)
{
if (varDsc->lvOtherReg != REG_STK)
{
tmpMask = genRegMask(varDsc->lvOtherReg);
enregMask |= tmpMask;
/* We can't trust a prediction of rsvdRegs or lockedRegs sets */
if (tmpMask & (rsvdRegs | lockedRegs))
grabCount++;
}
else // lvOtherReg == REG_STK
{
grabCount++;
}
}
#endif // _TARGET_64BIT_
}
varDsc->lvDependReg = true;
if (grabCount == 0)
{
/* Does not need a register */
predictReg = PREDICT_NONE;
//noway_assert(!VarSetOps::IsEmpty(this, varBits));
VarSetOps::UnionD(this, rpUseInPlace, varBits);
}
else // (grabCount > 0)
{
#ifndef _TARGET_64BIT_
/* For TYP_LONG and we only need one register then change the type to TYP_INT */
if ((type == TYP_LONG) && (grabCount == 1))
{
/* We will need to pick one register */
type = TYP_INT;
//noway_assert(!VarSetOps::IsEmpty(this, varBits));
VarSetOps::UnionD(this, rpUseInPlace, varBits);
}
noway_assert((type == TYP_DOUBLE) || (grabCount == (genTypeSize(genActualType(type)) / REGSIZE_BYTES)));
#else // !_TARGET_64BIT_
noway_assert(grabCount == 1);
#endif // !_TARGET_64BIT_
}
}
else if (type == TYP_STRUCT)
{
#ifdef _TARGET_ARM_
// TODO-ARM-Bug?: Passing structs in registers on ARM hits an assert here when
// predictReg is PREDICT_REG_R0 to PREDICT_REG_R3
// As a workaround we just bash it to PREDICT_NONE here
//
if (predictReg != PREDICT_NONE)
predictReg = PREDICT_NONE;
#endif
// Currently predictReg is saying that we will not need any scratch registers
noway_assert(predictReg == PREDICT_NONE);
/* We may need to sign or zero extend a small type when pushing a struct */
if (varDsc->lvPromoted && !varDsc->lvAddrExposed)
{
for (unsigned varNum = varDsc->lvFieldLclStart;
varNum < varDsc->lvFieldLclStart + varDsc->lvFieldCnt;
varNum++)
{
LclVarDsc * fldVar = lvaTable + varNum;
if (fldVar->lvStackAligned())
{
// When we are stack aligned Codegen will just use
// a push instruction and thus doesn't need any register
// since we can push both a register or a stack frame location
continue;
}
if (varTypeIsByte(fldVar->TypeGet()))
{
// We will need to reserve one byteable register,
//
type = TYP_BYTE;
predictReg = PREDICT_SCRATCH_REG;
#if CPU_HAS_BYTE_REGS
// It is best to enregister this fldVar in a byteable register
//
fldVar->addPrefReg(RBM_BYTE_REG_FLAG, this);
#endif
}
else if (varTypeIsShort(fldVar->TypeGet()))
{
bool isEnregistered = fldVar->lvTracked && (fldVar->lvRegNum != REG_STK);
// If fldVar is not enregistered then we will need a scratch register
//
if (!isEnregistered)
{
// We will need either an int register or a byte register
// If we are not requesting a byte register we will request an int register
//
if (type != TYP_BYTE)
type = TYP_INT;
predictReg = PREDICT_SCRATCH_REG;
}
}
}
}
}
else
{
regMaskTP preferReg = rpPredictRegMask(predictReg, type);
if (preferReg != 0)
{
if ( (genTypeStSz(type) == 1) ||
(genCountBits(preferReg) <= genTypeStSz(type)) )
{
varDsc->addPrefReg(preferReg, this);
}
}
}
break; /* end of case GT_LCL_VAR */
case GT_JMP:
tree->gtUsedRegs = RBM_NONE;
regMask = RBM_NONE;
#if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
// Mark the registers required to emit a tailcall profiler callback
if (compIsProfilerHookNeeded())
{
tree->gtUsedRegs |= RBM_PROFILER_JMP_USED;
}
#endif
goto RETURN_CHECK;
default:
break;
} /* end of switch (oper) */
/* If we don't need to evaluate to register, regmask is the empty set */
/* Otherwise we grab a temp for the local variable */
if (predictReg == PREDICT_NONE)
regMask = RBM_NONE;
else
{
regMask = rpPredictRegPick(type, predictReg, lockedRegs | rsvdRegs | enregMask);
if ((oper == GT_LCL_VAR) && (tree->TypeGet() == TYP_STRUCT))
{
/* We need to sign or zero extend a small type when pushing a struct */
noway_assert((type == TYP_INT) || (type == TYP_BYTE));
varDsc = lvaTable + tree->gtLclVarCommon.gtLclNum;
noway_assert(varDsc->lvPromoted && !varDsc->lvAddrExposed);
for (unsigned varNum = varDsc->lvFieldLclStart;
varNum < varDsc->lvFieldLclStart + varDsc->lvFieldCnt;
varNum++)
{
LclVarDsc * fldVar = lvaTable + varNum;
if (fldVar->lvTracked)
{
VARSET_TP VARSET_INIT_NOCOPY(fldBit, VarSetOps::MakeSingleton(this, fldVar->lvVarIndex));
rpRecordRegIntf(regMask, fldBit DEBUGARG( "need scratch register when pushing a small field of a struct"));
}
}
}
}
/* Update the set of lastUse variables that we encountered so far */
if (lastUse)
{
VarSetOps::UnionD(this, rpLastUseVars, lastUseVarBits);
VARSET_TP VARSET_INIT(this, varAsSet, lastUseVarBits);
/*
* Add interference from any previously locked temps into this last use variable.
*/
if (lockedRegs)
{
rpRecordRegIntf(lockedRegs, varAsSet
DEBUGARG("last use Predict lockedRegs"));
}
/*
* Add interference from any reserved temps into this last use variable.
*/
if (rsvdRegs)
{
rpRecordRegIntf(rsvdRegs, varAsSet
DEBUGARG("last use Predict rsvdRegs"));
}
/*
* For partially enregistered longs add an interference with the
* register return by rpPredictRegPick
*/
if ((type == TYP_INT) && (tree->TypeGet() == TYP_LONG))
{
rpRecordRegIntf(regMask, varAsSet
DEBUGARG("last use with partial enreg"));
}
}
tree->gtUsedRegs = (regMaskSmall)regMask;
goto RETURN_CHECK;
}
/* Is it a 'simple' unary/binary operator? */
if (kind & GTK_SMPOP)
{
GenTreePtr op1 = tree->gtOp.gtOp1;
GenTreePtr op2 = tree->gtGetOp2();
GenTreePtr opsPtr [3];
regMaskTP regsPtr[3];
VARSET_TP VARSET_INIT_NOCOPY(startAsgUseInPlaceVars, VarSetOps::UninitVal());
switch (oper)
{
case GT_ASG:
/* Is the value being assigned into a LCL_VAR? */
if (op1->gtOper == GT_LCL_VAR)
{
varDsc = lvaTable + op1->gtLclVarCommon.gtLclNum;
/* Are we assigning a LCL_VAR the result of a call? */
if (op2->gtOper == GT_CALL)
{
/* Set a preferred register for the LCL_VAR */
if (isRegPairType(varDsc->TypeGet()))
varDsc->addPrefReg(RBM_LNGRET, this);
else if (!varTypeIsFloating(varDsc->TypeGet()))
varDsc->addPrefReg(RBM_INTRET, this);
#ifdef _TARGET_AMD64_
else
varDsc->addPrefReg(RBM_FLOATRET, this);
#endif
/*
* When assigning the result of a call we don't
* bother trying to target the right side of the
* assignment, since we have a fixed calling convention.
*/
}
else if (varDsc->lvTracked)
{
// We interfere with uses in place
if (!VarSetOps::IsEmpty(this, rpUseInPlace))
{
rpRecordVarIntf(varDsc->lvVarIndex, rpUseInPlace
DEBUGARG( "Assign UseInPlace conflict"));
}
// Did we predict that this local will be fully enregistered?
// and the assignment type is the same as the expression type?
// and it is dead on the right side of the assignment?
// and we current have no other rpAsgVarNum active?
//
if ((varDsc->lvRegNum != REG_STK) &&
((type != TYP_LONG) || (varDsc->lvOtherReg != REG_STK)) &&
(type == op2->TypeGet()) &&
(op1->gtFlags & GTF_VAR_DEF) &&
(rpAsgVarNum == -1))
{
//
// Yes, we should try to target the right side (op2) of this
// assignment into the (enregistered) tracked variable.
//
op1PredictReg = PREDICT_NONE; /* really PREDICT_REG, but we've already done the check */
op2PredictReg = rpGetPredictForVarIndex(varDsc->lvVarIndex);
// Remember that this is a new use in place
// We've added "new UseInPlace"; remove from the global set.
VarSetOps::RemoveElemD(this, rpUseInPlace, varDsc->lvVarIndex);
// Note that later when we walk down to the leaf node for op2
// if we decide to actually use the register for the 'varDsc'
// to enregister the operand, the we will set rpAsgVarNum to
// varDsc->lvVarIndex, by extracting this value using
// rpGetVarIndexForPredict()
//
// Also we reset rpAsgVarNum back to -1 after we have finished
// predicting the current GT_ASG node
//
goto ASG_COMMON;
}
}
}
__fallthrough;
case GT_CHS:
case GT_ASG_OR:
case GT_ASG_XOR:
case GT_ASG_AND:
case GT_ASG_SUB:
case GT_ASG_ADD:
case GT_ASG_MUL:
case GT_ASG_DIV:
case GT_ASG_UDIV:
/* We can't use "reg <op>= addr" for TYP_LONG or if op2 is a short type */
if ((type != TYP_LONG) && !varTypeIsSmall(op2->gtType))
{
/* Is the value being assigned into an enregistered LCL_VAR? */
/* For debug code we only allow a simple op2 to be assigned */
if ((op1->gtOper == GT_LCL_VAR) &&
(!opts.compDbgCode || rpCanAsgOperWithoutReg(op2, false)))
{
varDsc = lvaTable + op1->gtLclVarCommon.gtLclNum;
/* Did we predict that this local will be enregistered? */
if (varDsc->lvRegNum != REG_STK)
{
/* Yes, we can use "reg <op>= addr" */
op1PredictReg = PREDICT_NONE; /* really PREDICT_REG, but we've already done the check */
op2PredictReg = PREDICT_NONE;
goto ASG_COMMON;
}
}
}
#if CPU_LOAD_STORE_ARCH
if (oper != GT_ASG)
{
op1PredictReg = PREDICT_REG;
op2PredictReg = PREDICT_REG;
}
else
#endif
{
/*
* Otherwise, initialize the normal forcing of operands:
* "addr <op>= reg"
*/
op1PredictReg = PREDICT_ADDR;
op2PredictReg = PREDICT_REG;
}
ASG_COMMON:
#if !CPU_LOAD_STORE_ARCH
if (op2PredictReg != PREDICT_NONE)
{
/* Is the value being assigned a simple one? */
if (rpCanAsgOperWithoutReg(op2, false))
op2PredictReg = PREDICT_NONE;
}
#endif
bool simpleAssignment;
simpleAssignment = false;
if ((oper == GT_ASG) &&
(op1->gtOper == GT_LCL_VAR))
{
// Add a variable interference from the assign target
// to each of the last use variables
if (!VarSetOps::IsEmpty(this, rpLastUseVars))
{
varDsc = lvaTable + op1->gtLclVarCommon.gtLclNum;
if (varDsc->lvTracked)
{
unsigned varIndex = varDsc->lvVarIndex;
rpRecordVarIntf(varIndex, rpLastUseVars
DEBUGARG( "Assign conflict"));
}
}
/* Record whether this tree is a simple assignment to a local */
simpleAssignment = ((type != TYP_LONG) || !opts.compDbgCode);
}
bool requireByteReg; requireByteReg = false;
#if CPU_HAS_BYTE_REGS
/* Byte-assignments need the byte registers, unless op1 is an enregistered local */
if (varTypeIsByte(type) &&
((op1->gtOper != GT_LCL_VAR) || (lvaTable[op1->gtLclVarCommon.gtLclNum].lvRegNum == REG_STK)))
{
// Byte-assignments typically need a byte register
requireByteReg = true;
if (op1->gtOper == GT_LCL_VAR)
{
varDsc = lvaTable + op1->gtLclVar.gtLclNum;
// Did we predict that this local will be enregistered?
if (varDsc->lvTracked && (varDsc->lvRegNum != REG_STK) && (oper != GT_CHS))
{
// We don't require a byte register when op1 is an enregistered local */
requireByteReg = false;
}
// Is op1 part of an Assign-Op or is the RHS a simple memory indirection?
if ((oper != GT_ASG) || (op2->gtOper == GT_IND) || (op2->gtOper == GT_CLS_VAR))
{
// We should try to put op1 in an byte register
varDsc->addPrefReg(RBM_BYTE_REG_FLAG, this);
}
}
}
#endif
VarSetOps::Assign(this, startAsgUseInPlaceVars, rpUseInPlace);
bool isWriteBarrierAsgNode;
isWriteBarrierAsgNode = codeGen->gcInfo.gcIsWriteBarrierAsgNode(tree);
#ifdef DEBUG
GCInfo::WriteBarrierForm wbf;
if (isWriteBarrierAsgNode)
wbf = codeGen->gcInfo.gcIsWriteBarrierCandidate(tree->gtOp.gtOp1, tree->gtOp.gtOp2);
else
wbf = GCInfo::WBF_NoBarrier;
#endif // DEBUG
regMaskTP wbaLockedRegs; wbaLockedRegs = lockedRegs;
if (isWriteBarrierAsgNode)
{
#if defined(_TARGET_X86_) && NOGC_WRITE_BARRIERS
#ifdef DEBUG
if (wbf != GCInfo::WBF_NoBarrier_CheckNotHeapInDebug)
{
#endif // DEBUG
wbaLockedRegs |= RBM_WRITE_BARRIER;
op1->gtRsvdRegs |= RBM_WRITE_BARRIER; // This will steer op2 away from REG_WRITE_BARRIER
assert(REG_WRITE_BARRIER == REG_EDX);
op1PredictReg = PREDICT_REG_EDX;
#ifdef DEBUG
}
else
#endif // DEBUG
#endif // defined(_TARGET_X86_) && NOGC_WRITE_BARRIERS
#if defined(DEBUG) || !(defined(_TARGET_X86_) && NOGC_WRITE_BARRIERS)
{
#ifdef _TARGET_X86_
op1PredictReg = PREDICT_REG_ECX;
op2PredictReg = PREDICT_REG_EDX;
#elif defined(_TARGET_ARM_)
op1PredictReg = PREDICT_REG_R0;
op2PredictReg = PREDICT_REG_R1;
// This is my best guess as to what the previous code meant by checking "gtRngChkLen() == NULL".
if ((op1->OperGet() == GT_IND) && (op1->gtOp.gtOp1->OperGet() != GT_ARR_BOUNDS_CHECK))
{
op1 = op1->gtOp.gtOp1;
}
#else // !_TARGET_X86_ && !_TARGET_ARM_
#error "Non-ARM or x86 _TARGET_ in RegPredict for WriteBarrierAsg"
#endif
}
#endif
}
/* Are we supposed to evaluate RHS first? */
if (tree->gtFlags & GTF_REVERSE_OPS)
{
op2Mask = rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs,
rsvdRegs | op1->gtRsvdRegs);
#if CPU_HAS_BYTE_REGS
// Should we insure that op2 gets evaluated into a byte register?
if (requireByteReg && ((op2Mask & RBM_BYTE_REGS) == 0))
{
// We need to grab a byte-able register, (i.e. EAX, EDX, ECX, EBX)
// and we can't select one that is already reserved (i.e. lockedRegs)
//
op2Mask |= rpPredictRegPick(type, PREDICT_SCRATCH_REG, (lockedRegs | RBM_NON_BYTE_REGS));
op2->gtUsedRegs |= op2Mask;
// No longer a simple assignment because we're using extra registers and might
// have interference between op1 and op2. See DevDiv #136681
simpleAssignment = false;
}
#endif
/*
* For a simple assignment we don't want the op2Mask to be
* marked as interferring with the LCL_VAR, since it is likely
* that we will want to enregister the LCL_VAR in exactly
* the register that is used to compute op2
*/
tmpMask = lockedRegs;
if (!simpleAssignment)
tmpMask |= op2Mask;
regMask = rpPredictTreeRegUse(op1, op1PredictReg, tmpMask, RBM_NONE);
// Did we relax the register prediction for op1 and op2 above ?
// - because we are depending upon op1 being enregistered
//
if ((op1PredictReg == PREDICT_NONE) &&
((op2PredictReg == PREDICT_NONE) || rpHasVarIndexForPredict(op2PredictReg)))
{
/* We must be assigning into an enregistered LCL_VAR */
noway_assert(op1->gtOper == GT_LCL_VAR);
varDsc = lvaTable + op1->gtLclVar.gtLclNum;
noway_assert(varDsc->lvRegNum != REG_STK);
/* We need to set lvDependReg, in case we lose the enregistration of op1 */
varDsc->lvDependReg = true;
}
}
else
{
// For the case of simpleAssignments op2 should always be evaluated first
noway_assert(!simpleAssignment);
regMask = rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
if (isWriteBarrierAsgNode)
{
wbaLockedRegs |= op1->gtUsedRegs;
}
op2Mask = rpPredictTreeRegUse(op2, op2PredictReg, wbaLockedRegs | regMask, RBM_NONE);
#if CPU_HAS_BYTE_REGS
// Should we insure that op2 gets evaluated into a byte register?
if (requireByteReg && ((op2Mask & RBM_BYTE_REGS) == 0))
{
// We need to grab a byte-able register, (i.e. EAX, EDX, ECX, EBX)
// and we can't select one that is already reserved (i.e. lockedRegs or regMask)
//
op2Mask |= rpPredictRegPick(type, PREDICT_SCRATCH_REG, (lockedRegs | regMask | RBM_NON_BYTE_REGS));
op2->gtUsedRegs |= op2Mask;
}
#endif
}
if (rpHasVarIndexForPredict(op2PredictReg))
{
rpAsgVarNum = -1;
}
if (isWriteBarrierAsgNode)
{
#if NOGC_WRITE_BARRIERS
#ifdef DEBUG
if (wbf != GCInfo::WBF_NoBarrier_CheckNotHeapInDebug)
{
#endif // DEBUG
/* Steer computation away from REG_WRITE_BARRIER as the pointer is
passed to the write-barrier call in REG_WRITE_BARRIER */
regMask = op2Mask;
if (op1->gtOper == GT_IND)
{
GenTreePtr rv1, rv2;
unsigned mul, cns;
bool rev;
/* Special handling of indirect assigns for write barrier */
bool yes = codeGen->genCreateAddrMode(op1->gtOp.gtOp1, -1, true, RBM_NONE, &rev, &rv1, &rv2, &mul, &cns);
/* Check address mode for enregisterable locals */
if (yes)
{
if (rv1 != NULL && rv1->gtOper == GT_LCL_VAR)
{
rpPredictRefAssign(rv1->gtLclVarCommon.gtLclNum);
}
if (rv2 != NULL && rv2->gtOper == GT_LCL_VAR)
{
rpPredictRefAssign(rv2->gtLclVarCommon.gtLclNum);
}
}
}
if (op2->gtOper == GT_LCL_VAR)
{
rpPredictRefAssign(op2->gtLclVarCommon.gtLclNum);
}
// Add a register interference for REG_WRITE_BARRIER to each of the last use variables
if (!VarSetOps::IsEmpty(this, rpLastUseVars))
{
rpRecordRegIntf(RBM_WRITE_BARRIER, rpLastUseVars
DEBUGARG( "WriteBarrier and rpLastUseVars conflict"));
}
tree->gtUsedRegs |= RBM_WRITE_BARRIER;
#ifdef DEBUG
}
else
#endif // DEBUG
#endif // NOGC_WRITE_BARRIERS
#if defined(DEBUG) || !NOGC_WRITE_BARRIERS
{
#ifdef _TARGET_ARM_
//
// For the ARM target we have an optimized JIT Helper
// that only trashes a subset of the callee saved registers
//
#ifdef DEBUG
if (verbose)
printf("Adding interference with RBM_CALLEE_TRASH_NOGC for NoGC WriteBarrierAsg\n");
#endif
// NOTE: Adding it to the gtUsedRegs will cause the interference to
// be added appropriately
// the RBM_CALLEE_TRASH_NOGC set is killed. We will record this in interferingRegs
// instead of gtUsedRegs, because the latter will be modified later, but we need
// to remember to add the interference.
interferingRegs |= RBM_CALLEE_TRASH_NOGC;
op1->gtUsedRegs |= RBM_R0;
op2->gtUsedRegs |= RBM_R1;
#else // _TARGET_ARM_
// We have to call a normal JIT helper to perform the Write Barrier Assignment
// It will trash the callee saved registers
#ifdef DEBUG
if (verbose)
printf("Adding interference with RBM_CALLEE_TRASH for NoGC WriteBarrierAsg\n");
#endif
tree->gtUsedRegs |= RBM_CALLEE_TRASH;
#endif // _TARGET_ARM_
}
#endif // defined(DEBUG) || !NOGC_WRITE_BARRIERS
}
if (simpleAssignment)
{
/*
* Consider a simple assignment to a local:
*
* lcl = expr;
*
* Since the "=" node is visited after the variable
* is marked live (assuming it's live after the
* assignment), we don't want to use the register
* use mask of the "=" node but rather that of the
* variable itself.
*/
tree->gtUsedRegs = op1->gtUsedRegs;
}
else
{
tree->gtUsedRegs = op1->gtUsedRegs | op2->gtUsedRegs;
}
VarSetOps::Assign(this, rpUseInPlace, startAsgUseInPlaceVars);
goto RETURN_CHECK;
case GT_ASG_LSH:
case GT_ASG_RSH:
case GT_ASG_RSZ:
/* assigning shift operators */
noway_assert(type != TYP_LONG);
#if CPU_LOAD_STORE_ARCH
predictReg = PREDICT_ADDR;
#else
predictReg = PREDICT_NONE;
#endif
/* shift count is handled same as ordinary shift */
goto HANDLE_SHIFT_COUNT;
case GT_ADDR:
regMask = rpPredictTreeRegUse(op1, PREDICT_ADDR, lockedRegs, RBM_LASTUSE);
if ((regMask == RBM_NONE) && (predictReg >= PREDICT_REG))
{
// We need a scratch register for the LEA instruction
regMask = rpPredictRegPick(TYP_INT, predictReg, lockedRegs | rsvdRegs);
}
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
case GT_CAST:
/* Cannot cast to VOID */
noway_assert(type != TYP_VOID);
/* cast to long is special */
if (type == TYP_LONG && op1->gtType <= TYP_INT)
{
noway_assert(tree->gtCast.gtCastType==TYP_LONG || tree->gtCast.gtCastType==TYP_ULONG);
#if CPU_LONG_USES_REGPAIR
rpPredictReg predictRegHi = PREDICT_SCRATCH_REG;
if (rpHasVarIndexForPredict(predictReg))
{
unsigned tgtIndex = rpGetVarIndexForPredict(predictReg);
rpAsgVarNum = tgtIndex;
// We don't need any register as we plan on writing to the rpAsgVarNum register
predictReg = PREDICT_NONE;
LclVarDsc * tgtVar = lvaTable + lvaTrackedToVarNum[tgtIndex];
tgtVar->lvDependReg = true;
if (tgtVar->lvOtherReg != REG_STK)
{
predictRegHi = PREDICT_NONE;
}
}
else
#endif
if (predictReg == PREDICT_NONE)
{
predictReg = PREDICT_SCRATCH_REG;
}
//
// If we are widening an int into a long using a targeted register pair we
// should retarget so that the low part get loaded into the appropriate register
//
#ifdef _TARGET_ARM_
else if (predictReg == PREDICT_PAIR_R0R1)
{
predictReg = PREDICT_REG_R0;
predictRegHi = PREDICT_REG_R1;
}
else if (predictReg == PREDICT_PAIR_R2R3)
{
predictReg = PREDICT_REG_R2;
predictRegHi = PREDICT_REG_R3;
}
#endif
#ifdef _TARGET_X86_
else if (predictReg == PREDICT_PAIR_EAXEDX)
{
predictReg = PREDICT_REG_EAX;
predictRegHi = PREDICT_REG_EDX;
}
else if (predictReg == PREDICT_PAIR_ECXEBX)
{
predictReg = PREDICT_REG_ECX;
predictRegHi = PREDICT_REG_EBX;
}
#endif
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
#if CPU_LONG_USES_REGPAIR
if (predictRegHi != PREDICT_NONE)
{
// Now get one more reg for the upper part
regMask |= rpPredictRegPick(TYP_INT, predictRegHi, lockedRegs | rsvdRegs | regMask);
}
#endif
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
/* cast from long is special - it frees a register */
if (type <= TYP_INT // nice. this presumably is intended to mean "signed int and shorter types"
&& op1->gtType == TYP_LONG)
{
if ((predictReg == PREDICT_NONE) || rpHasVarIndexForPredict(predictReg))
predictReg = PREDICT_REG;
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
// If we have 2 or more regs, free one of them
if (!genMaxOneBit(regMask))
{
/* Clear the 2nd lowest bit in regMask */
/* First set tmpMask to the lowest bit in regMask */
tmpMask = genFindLowestBit(regMask);
/* Next find the second lowest bit in regMask */
tmpMask = genFindLowestBit(regMask & ~tmpMask);
/* Clear this bit from regmask */
regMask &= ~tmpMask;
}
tree->gtUsedRegs = op1->gtUsedRegs;
goto RETURN_CHECK;
}
#if CPU_HAS_BYTE_REGS
/* cast from signed-byte is special - it uses byteable registers */
if (type == TYP_INT)
{
var_types smallType;
if (genTypeSize(tree->gtCast.CastOp()->TypeGet()) < genTypeSize(tree->gtCast.gtCastType))
smallType = tree->gtCast.CastOp()->TypeGet();
else
smallType = tree->gtCast.gtCastType;
if (smallType == TYP_BYTE)
{
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
if ((regMask & RBM_BYTE_REGS) == 0)
regMask = rpPredictRegPick(type, PREDICT_SCRATCH_REG, RBM_NON_BYTE_REGS);
tree->gtUsedRegs = (regMaskSmall)regMask;
goto RETURN_CHECK;
}
}
#endif
#if FEATURE_STACK_FP_X87
/* cast to float/double is special */
if (varTypeIsFloating(type))
{
switch (op1->TypeGet())
{
/* uses fild, so don't need to be loaded to reg */
case TYP_INT:
case TYP_LONG:
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs;
regMask = 0;
goto RETURN_CHECK;
default:
break;
}
}
/* Casting from integral type to floating type is special */
if (!varTypeIsFloating(type) && varTypeIsFloating(op1->TypeGet()))
{
// If dblwasInt
if (!opts.compCanUseSSE2)
{
// if SSE2 is not enabled this can only be a DblWasInt case
assert(gtDblWasInt(op1));
regMask = rpPredictRegPick(type, PREDICT_SCRATCH_REG, lockedRegs);
tree->gtUsedRegs = (regMaskSmall)regMask;
goto RETURN_CHECK;
}
else
{
// predict for SSE2 based casting
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
// Get one more int reg to hold cast result
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs|rsvdRegs|regMask);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
}
#endif
#if FEATURE_FP_REGALLOC
// Are we casting between int to float or float to int
// Fix 388428 ARM JitStress WP7
if (varTypeIsFloating(type) != varTypeIsFloating(op1->TypeGet()))
{
// op1 needs to go into a register
regMask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs);
#ifdef _TARGET_ARM_
if (varTypeIsFloating(op1->TypeGet()))
{
// We also need a fp scratch register for the convert operation
regMask |= rpPredictRegPick((genTypeStSz(type) == 1) ? TYP_FLOAT : TYP_DOUBLE,
PREDICT_SCRATCH_REG, regMask|lockedRegs|rsvdRegs);
}
#endif
// We also need a register to hold the result
regMask |= rpPredictRegPick(type, PREDICT_SCRATCH_REG, regMask|lockedRegs|rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
#endif
/* otherwise must load op1 into a register */
goto GENERIC_UNARY;
#if INLINE_MATH
case GT_MATH:
#ifdef _TARGET_XARCH_
if (tree->gtMath.gtMathFN==CORINFO_INTRINSIC_Round &&
tree->TypeGet()==TYP_INT)
{
// This is a special case to handle the following
// optimization: conv.i4(round.d(d)) -> round.i(d)
// if flowgraph 3186
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
regMask = rpPredictRegPick(TYP_INT, predictReg, lockedRegs | rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
#endif
__fallthrough;
#endif
case GT_NEG:
#ifdef _TARGET_ARM_
if (tree->TypeGet() == TYP_LONG)
{
// On ARM this consumes an extra register for the '0' value
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
regMaskTP op1Mask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
regMask = rpPredictRegPick(TYP_INT, predictReg, lockedRegs | op1Mask | rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
#endif // _TARGET_ARM_
__fallthrough;
case GT_NOT:
// these unary operators will write new values
// and thus will need a scratch register
GENERIC_UNARY:
/* generic unary operators */
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
__fallthrough;
case GT_NOP:
// these unary operators do not write new values
// and thus won't need a scratch register
#if OPT_BOOL_OPS
if (!op1)
{
tree->gtUsedRegs = 0;
regMask = 0;
goto RETURN_CHECK;
}
#endif
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs;
goto RETURN_CHECK;
case GT_IND:
case GT_NULLCHECK: // At this point, nullcheck is just like an IND...
{
bool intoReg = true;
VARSET_TP VARSET_INIT(this, startIndUseInPlaceVars, rpUseInPlace);
if (fgIsIndirOfAddrOfLocal(tree) != NULL)
{
compUpdateLifeVar</*ForCodeGen*/false>(tree);
}
if (predictReg == PREDICT_ADDR)
{
intoReg = false;
}
else if (predictReg == PREDICT_NONE)
{
if (type != TYP_LONG)
{
intoReg = false;
}
else
{
predictReg = PREDICT_REG;
}
}
/* forcing to register? */
if (intoReg && (type != TYP_LONG))
{
rsvdRegs |= RBM_LASTUSE;
}
GenTreePtr lenCSE; lenCSE = NULL;
/* check for address mode */
regMask = rpPredictAddressMode(op1, type, lockedRegs, rsvdRegs, lenCSE);
tmpMask = RBM_NONE;
#if CPU_LOAD_STORE_ARCH
// We may need a scratch register for loading a long
if (type == TYP_LONG)
{
/* This scratch register immediately dies */
tmpMask = rpPredictRegPick(TYP_BYREF, PREDICT_REG, op1->gtUsedRegs | lockedRegs | rsvdRegs);
}
#endif // CPU_LOAD_STORE_ARCH
#ifdef _TARGET_ARM_
// Unaligned loads/stores for floating point values must first be loaded into integer register(s)
//
if ((tree->gtFlags & GTF_IND_UNALIGNED) && varTypeIsFloating(type))
{
/* These integer register(s) immediately die */
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_REG, op1->gtUsedRegs | lockedRegs | rsvdRegs);
// Two integer registers are required for a TYP_DOUBLE
if (type == TYP_DOUBLE)
tmpMask |= rpPredictRegPick(TYP_INT, PREDICT_REG, op1->gtUsedRegs | lockedRegs | rsvdRegs | tmpMask);
}
#endif
/* forcing to register? */
if (intoReg)
{
regMaskTP lockedMask = lockedRegs | rsvdRegs;
tmpMask |= regMask;
// We will compute a new regMask that holds the register(s)
// that we will load the indirection into.
//
#ifndef _TARGET_64BIT_
if (type == TYP_LONG)
{
// We need to use multiple load instructions here:
// For the first register we can not choose
// any registers that are being used in place or
// any register in the current regMask
//
regMask = rpPredictRegPick(TYP_INT, predictReg, regMask | lockedMask);
// For the second register we can choose a register that was
// used in place or any register in the old now overwritten regMask
// but not the same register that we picked above in 'regMask'
//
VarSetOps::Assign(this, rpUseInPlace, startIndUseInPlaceVars);
regMask |= rpPredictRegPick(TYP_INT, predictReg, regMask | lockedMask);
}
else
#endif
{
// We will use one load instruction here:
// The load target register can be a register that was used in place
// or one of the register from the orginal regMask.
//
VarSetOps::Assign(this, rpUseInPlace, startIndUseInPlaceVars);
regMask = rpPredictRegPick(type, predictReg, lockedMask);
}
}
else if (predictReg != PREDICT_ADDR)
{
/* Unless the caller specified PREDICT_ADDR */
/* we don't return the temp registers used */
/* to form the address */
regMask = RBM_NONE;
}
}
tree->gtUsedRegs = (regMaskSmall)(regMask | tmpMask);
goto RETURN_CHECK;
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
#ifdef _TARGET_X86_
/* Floating point comparison uses EAX for flags */
if (varTypeIsFloating(op1->TypeGet()))
{
regMask = RBM_EAX;
}
else
#endif
if (!(tree->gtFlags & GTF_RELOP_JMP_USED))
{
// Some comparisons are converted to ?:
noway_assert(!fgMorphRelopToQmark(op1));
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
// The set instructions need a byte register
regMask = rpPredictRegPick(TYP_BYTE, predictReg, lockedRegs | rsvdRegs);
}
else
{
regMask = RBM_NONE;
#ifdef _TARGET_XARCH_
tmpMask = RBM_NONE;
// Optimize the compare with a constant cases for xarch
if (op1->gtOper == GT_CNS_INT)
{
if (op2->gtOper == GT_CNS_INT)
tmpMask = rpPredictTreeRegUse(op1, PREDICT_SCRATCH_REG, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, PREDICT_NONE, lockedRegs | tmpMask, RBM_LASTUSE);
tree->gtUsedRegs = op2->gtUsedRegs;
goto RETURN_CHECK;
}
else if (op2->gtOper == GT_CNS_INT)
{
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, rsvdRegs);
tree->gtUsedRegs = op1->gtUsedRegs;
goto RETURN_CHECK;
}
else if (op2->gtOper == GT_CNS_LNG)
{
regMaskTP op1Mask = rpPredictTreeRegUse(op1, PREDICT_ADDR, lockedRegs, rsvdRegs);
#ifdef _TARGET_X86_
// We also need one extra register to read values from
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | op1Mask | rsvdRegs);
#endif // _TARGET_X86_
tree->gtUsedRegs = (regMaskSmall)tmpMask | op1->gtUsedRegs;
goto RETURN_CHECK;
}
#endif // _TARGET_XARCH_
}
unsigned op1TypeSize;
unsigned op2TypeSize;
op1TypeSize = genTypeSize(op1->TypeGet());
op2TypeSize = genTypeSize(op2->TypeGet());
op1PredictReg = PREDICT_REG;
op2PredictReg = PREDICT_REG;
if (tree->gtFlags & GTF_REVERSE_OPS)
{
#ifdef _TARGET_XARCH_
if (op1TypeSize == sizeof(int))
op1PredictReg = PREDICT_NONE;
#endif
tmpMask = rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs | tmpMask, RBM_LASTUSE);
}
else
{
#ifdef _TARGET_XARCH_
// For full DWORD compares we can have
//
// op1 is an address mode and op2 is a register
// or
// op1 is a register and op2 is an address mode
//
if ((op2TypeSize == sizeof(int)) &&
(op1TypeSize == op2TypeSize))
{
if (op2->gtOper == GT_LCL_VAR)
{
unsigned lclNum = op2->gtLclVar.gtLclNum;
varDsc = lvaTable + lclNum;
/* Did we predict that this local will be enregistered? */
if (varDsc->lvTracked && (varDsc->lvRegNum != REG_STK))
{
op1PredictReg = PREDICT_ADDR;
}
}
}
// Codegen will generate cmp reg,[mem] for 4 or 8-byte types, but not for 1 or 2 byte types
if ((op1PredictReg != PREDICT_ADDR) && (op2TypeSize >= sizeof(int)))
op2PredictReg = PREDICT_ADDR;
#endif // _TARGET_XARCH_
tmpMask = rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
#ifdef _TARGET_ARM_
if ((op2->gtOper != GT_CNS_INT) || !codeGen->validImmForAlu(op2->gtIntCon.gtIconVal))
#endif
{
rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs | tmpMask, RBM_LASTUSE);
}
}
#ifdef _TARGET_XARCH_
// In some cases in genCondSetFlags(), we need to use a temporary register (via rsPickReg())
// to generate a sign/zero extension before doing a compare. Save a register for this purpose
// if one of the registers is small and the types aren't equal.
if (regMask == RBM_NONE)
{
rpPredictReg op1xPredictReg, op2xPredictReg;
GenTreePtr op1x, op2x;
if (tree->gtFlags & GTF_REVERSE_OPS) // TODO: do we really need to handle this case?
{
op1xPredictReg = op2PredictReg;
op2xPredictReg = op1PredictReg;
op1x = op2;
op2x = op1;
}
else
{
op1xPredictReg = op1PredictReg;
op2xPredictReg = op2PredictReg;
op1x = op1;
op2x = op2;
}
if ((op1xPredictReg < PREDICT_REG) && // op1 doesn't get a register (probably an indir)
(op2xPredictReg >= PREDICT_REG) && // op2 gets a register
varTypeIsSmall(op1x->TypeGet())) // op1 is smaller than an int
{
bool needTmp = false;
// If op1x is a byte, and op2x is not a byteable register, we'll need a temp.
// We could predict a byteable register for op2x, but what if we don't get it?
// So, be conservative and always ask for a temp. There are a couple small CQ losses as a result.
if (varTypeIsByte(op1x->TypeGet()))
{
needTmp = true;
}
else
{
if (op2x->gtOper == GT_LCL_VAR) // this will be a GT_REG_VAR during code generation
{
if (genActualType(op1x->TypeGet()) != lvaGetActualType(op2x->gtLclVar.gtLclNum))
needTmp = true;
}
else
{
if (op1x->TypeGet() != op2x->TypeGet())
needTmp = true;
}
}
if (needTmp)
{
regMask = rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | rsvdRegs);
}
}
}
#endif // _TARGET_XARCH_
tree->gtUsedRegs = (regMaskSmall)regMask | op1->gtUsedRegs | op2->gtUsedRegs;
goto RETURN_CHECK;
case GT_MUL:
#ifndef _TARGET_AMD64_
#if LONG_MATH_REGPARAM
if (type == TYP_LONG)
goto LONG_MATH;
#endif
if (type == TYP_LONG)
{
assert(tree->gtIsValid64RsltMul());
/* Strip out the cast nodes */
noway_assert(op1->gtOper == GT_CAST && op2->gtOper == GT_CAST);
op1 = op1->gtCast.CastOp();
op2 = op2->gtCast.CastOp();
#else
if (false)
{
#endif // !_TARGET_AMD64_
USE_MULT_EAX:
#if defined(_TARGET_X86_)
// This will done by a 64-bit imul "imul eax, reg"
// (i.e. EDX:EAX = EAX * reg)
/* Are we supposed to evaluate op2 first? */
if (tree->gtFlags & GTF_REVERSE_OPS)
{
rpPredictTreeRegUse(op2, PREDICT_PAIR_TMP_LO, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs | RBM_PAIR_TMP_LO, RBM_LASTUSE);
}
else
{
rpPredictTreeRegUse(op1, PREDICT_PAIR_TMP_LO, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs | RBM_PAIR_TMP_LO, RBM_LASTUSE);
}
/* set gtUsedRegs to EAX, EDX and the registers needed by op1 and op2 */
tree->gtUsedRegs = RBM_PAIR_TMP | op1->gtUsedRegs | op2->gtUsedRegs;
/* set regMask to the set of held registers */
regMask = RBM_PAIR_TMP_LO;
if (type == TYP_LONG)
regMask |= RBM_PAIR_TMP_HI;
#elif defined(_TARGET_ARM_)
// This will done by a 4 operand multiply
// Are we supposed to evaluate op2 first?
if (tree->gtFlags & GTF_REVERSE_OPS)
{
rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs , RBM_LASTUSE);
}
else
{
rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs, RBM_LASTUSE);
}
// set regMask to the set of held registers,
// the two scratch register we need to compute the mul result
regMask = rpPredictRegPick(TYP_LONG, PREDICT_SCRATCH_REG, lockedRegs | rsvdRegs);
// set gtUsedRegs toregMask and the registers needed by op1 and op2
tree->gtUsedRegs = regMask | op1->gtUsedRegs | op2->gtUsedRegs;
#else // !_TARGET_X86_ && !_TARGET_ARM_
#error "Non-ARM or x86 _TARGET_ in RegPredict for 64-bit imul"
#endif
goto RETURN_CHECK;
}
else
{
/* We use imulEAX for most unsigned multiply operations */
if (tree->gtOverflow())
{
if ((tree->gtFlags & GTF_UNSIGNED) ||
varTypeIsSmall(tree->TypeGet()) )
{
goto USE_MULT_EAX;
}
}
}
__fallthrough;
case GT_OR:
case GT_XOR:
case GT_AND:
case GT_SUB:
case GT_ADD:
tree->gtUsedRegs = 0;
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
GENERIC_BINARY:
noway_assert(op2);
if (tree->gtFlags & GTF_REVERSE_OPS)
{
op1PredictReg = PREDICT_REG;
#if !CPU_LOAD_STORE_ARCH
if (genTypeSize(op1->gtType) >= sizeof(int))
op1PredictReg = PREDICT_NONE;
#endif
regMask = rpPredictTreeRegUse(op2, predictReg, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs | regMask, RBM_LASTUSE);
}
else
{
op2PredictReg = PREDICT_REG;
#if !CPU_LOAD_STORE_ARCH
if (genTypeSize(op2->gtType) >= sizeof(int))
op2PredictReg = PREDICT_NONE;
#endif
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
#ifdef _TARGET_ARM_
// For most ALU operations we can generate a single instruction that encodes
// a small immediate integer constant value. (except for multiply)
//
if ((op2->gtOper == GT_CNS_INT) && (oper != GT_MUL))
{
ssize_t ival = op2->gtIntCon.gtIconVal;
if (codeGen->validImmForAlu(ival))
{
op2PredictReg = PREDICT_NONE;
}
else if (codeGen->validImmForAdd(ival, INS_FLAGS_DONT_CARE) &&
((oper == GT_ADD) || (oper == GT_SUB)))
{
op2PredictReg = PREDICT_NONE;
}
}
if (op2PredictReg == PREDICT_NONE)
{
op2->gtUsedRegs = RBM_NONE;
}
else
#endif
{
rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs | regMask, RBM_LASTUSE);
}
}
tree->gtUsedRegs = (regMaskSmall)regMask | op1->gtUsedRegs | op2->gtUsedRegs;
#if CPU_HAS_BYTE_REGS
/* We have special register requirements for byte operations */
if (varTypeIsByte(tree->TypeGet()))
{
/* For 8 bit arithmetic, one operands has to be in a
byte-addressable register, and the other has to be
in a byte-addrble reg or in memory. Assume its in a reg */
regMaskTP regByteMask = 0;
regMaskTP op1ByteMask = op1->gtUsedRegs;
if (!(op1->gtUsedRegs & RBM_BYTE_REGS))
{
// Pick a Byte register to use for op1
regByteMask = rpPredictRegPick(TYP_BYTE, PREDICT_REG, lockedRegs | rsvdRegs);
op1ByteMask = regByteMask;
}
if (!(op2->gtUsedRegs & RBM_BYTE_REGS))
{
// Pick a Byte register to use for op2, avoiding the one used by op1
regByteMask |= rpPredictRegPick(TYP_BYTE, PREDICT_REG, lockedRegs | rsvdRegs | op1ByteMask);
}
if (regByteMask)
{
tree->gtUsedRegs |= regByteMask;
regMask = regByteMask;
}
}
#endif
goto RETURN_CHECK;
case GT_DIV:
case GT_MOD:
case GT_UDIV:
case GT_UMOD:
/* non-integer division handled in generic way */
if (!varTypeIsIntegral(type))
{
tree->gtUsedRegs = 0;
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
goto GENERIC_BINARY;
}
#ifndef _TARGET_64BIT_
#if!LONG_MATH_REGPARAM
if (type == TYP_LONG && (oper == GT_MOD || oper == GT_UMOD))
{
/* Special case: a mod with an int op2 is done inline using idiv or div
to avoid a costly call to the helper */
noway_assert((op2->gtOper == GT_CNS_LNG) &&
(op2->gtLngCon.gtLconVal == int(op2->gtLngCon.gtLconVal)));
#if defined(_TARGET_X86_) || defined(_TARGET_ARM_)
if (tree->gtFlags & GTF_REVERSE_OPS)
{
tmpMask = rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs | RBM_PAIR_TMP, rsvdRegs | op1->gtRsvdRegs);
tmpMask |= rpPredictTreeRegUse(op1, PREDICT_PAIR_TMP, lockedRegs | tmpMask, RBM_LASTUSE);
}
else
{
tmpMask = rpPredictTreeRegUse(op1, PREDICT_PAIR_TMP, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
tmpMask |= rpPredictTreeRegUse(op2, PREDICT_REG, lockedRegs | tmpMask | RBM_PAIR_TMP, RBM_LASTUSE);
}
regMask = RBM_PAIR_TMP;
#else // !_TARGET_X86_ && !_TARGET_ARM_
#error "Non-ARM or x86 _TARGET_ in RegPredict for 64-bit MOD"
#endif // !_TARGET_X86_ && !_TARGET_ARM_
tree->gtUsedRegs = (regMaskSmall)(regMask |
op1->gtUsedRegs |
op2->gtUsedRegs |
rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, regMask | tmpMask));
goto RETURN_CHECK;
}
#else // LONG_MATH_REGPARAM
if (type == TYP_LONG)
{
LONG_MATH: /* LONG_MATH_REGPARAM case */
noway_assert(type == TYP_LONG);
#ifdef _TARGET_X86_
if (tree->gtFlags & GTF_REVERSE_OPS)
{
rpPredictTreeRegUse(op2, PREDICT_PAIR_ECXEBX, lockedRegs, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, PREDICT_PAIR_EAXEDX, lockedRegs | RBM_ECX | RBC_EBX, RBM_LASTUSE);
}
else
{
rpPredictTreeRegUse(op1, PREDICT_PAIR_EAXEDX, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, PREDICT_PAIR_ECXEBX, lockedRegs | RBM_EAX | RBM_EDX, RBM_LASTUSE);
}
#elif defined(_TARGET_ARM_)
NYI_ARM("64-bit MOD");
#else // !_TARGET_X86_ && !_TARGET_ARM_
#error "Non-ARM or x86 _TARGET_ in RegPredict for 64-bit MOD"
#endif // !_TARGET_X86_ && !_TARGET_ARM_
/* grab EAX, EDX for this tree node */
regMask |= (RBM_EAX | RBM_EDX);
tree->gtUsedRegs = (regMaskSmall)regMask | (RBM_ECX | RBM_EBX);
tree->gtUsedRegs |= op1->gtUsedRegs | op2->gtUsedRegs;
regMask = RBM_EAX | RBM_EDX;
goto RETURN_CHECK;
}
#endif
#endif // _TARGET_64BIT_
/* no divide immediate, so force integer constant which is not
* a power of two to register
*/
if (op2->OperKind() & GTK_CONST)
{
ssize_t ival = op2->gtIntConCommon.IconValue();
/* Is the divisor a power of 2 ? */
if (ival > 0 && genMaxOneBit(size_t(ival)))
{
goto GENERIC_UNARY;
}
else
op2PredictReg = PREDICT_SCRATCH_REG;
}
else
{
/* Non integer constant also must be enregistered */
op2PredictReg = PREDICT_REG;
}
regMaskTP trashedMask; trashedMask = DUMMY_INIT(RBM_ILLEGAL);
regMaskTP op1ExcludeMask; op1ExcludeMask = DUMMY_INIT(RBM_ILLEGAL);
regMaskTP op2ExcludeMask; op2ExcludeMask = DUMMY_INIT(RBM_ILLEGAL);
#ifdef _TARGET_XARCH_
/* Consider the case "a / b" - we'll need to trash EDX (via "CDQ") before
* we can safely allow the "b" value to die. Unfortunately, if we simply
* mark the node "b" as using EDX, this will not work if "b" is a register
* variable that dies with this particular reference. Thus, if we want to
* avoid this situation (where we would have to spill the variable from
* EDX to someplace else), we need to explicitly mark the interference
* of the variable at this point.
*/
if (op2->gtOper == GT_LCL_VAR)
{
unsigned lclNum = op2->gtLclVarCommon.gtLclNum;
varDsc = lvaTable + lclNum;
if (varDsc->lvTracked)
{
#ifdef DEBUG
if (verbose)
{
if (!VarSetOps::IsMember(this, raLclRegIntf[REG_EAX], varDsc->lvVarIndex))
printf("Record interference between V%02u,T%02u and EAX -- int divide\n",
lclNum, varDsc->lvVarIndex);
if (!VarSetOps::IsMember(this, raLclRegIntf[REG_EDX], varDsc->lvVarIndex))
printf("Record interference between V%02u,T%02u and EDX -- int divide\n",
lclNum, varDsc->lvVarIndex);
}
#endif
VarSetOps::AddElemD(this, raLclRegIntf[REG_EAX], varDsc->lvVarIndex);
VarSetOps::AddElemD(this, raLclRegIntf[REG_EDX], varDsc->lvVarIndex);
}
}
/* set the held register based on opcode */
if (oper == GT_DIV || oper == GT_UDIV)
regMask = RBM_EAX;
else
regMask = RBM_EDX;
trashedMask = (RBM_EAX | RBM_EDX);
op1ExcludeMask = 0;
op2ExcludeMask = (RBM_EAX | RBM_EDX);
#endif // _TARGET_XARCH_
#ifdef _TARGET_ARM_
trashedMask = RBM_NONE;
op1ExcludeMask = RBM_NONE;
op2ExcludeMask = RBM_NONE;
#endif
/* set the lvPref reg if possible */
GenTreePtr dest;
/*
* Walking the gtNext link twice from here should get us back
* to our parent node, if this is an simple assignment tree.
*/
dest = tree->gtNext;
if (dest && (dest->gtOper == GT_LCL_VAR) &&
dest->gtNext && (dest->gtNext->OperKind() & GTK_ASGOP) &&
dest->gtNext->gtOp.gtOp2 == tree)
{
varDsc = lvaTable + dest->gtLclVarCommon.gtLclNum;
varDsc->addPrefReg(regMask, this);
}
#ifdef _TARGET_XARCH_
op1PredictReg = PREDICT_REG_EDX; /* Normally target op1 into EDX */
#else
op1PredictReg = PREDICT_SCRATCH_REG;
#endif
/* are we supposed to evaluate op2 first? */
if (tree->gtFlags & GTF_REVERSE_OPS)
{
tmpMask = rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs | op2ExcludeMask, rsvdRegs | op1->gtRsvdRegs);
rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs | tmpMask | op1ExcludeMask, RBM_LASTUSE);
}
else
{
tmpMask = rpPredictTreeRegUse(op1, op1PredictReg, lockedRegs | op1ExcludeMask, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, op2PredictReg, tmpMask | lockedRegs | op2ExcludeMask, RBM_LASTUSE);
}
#ifdef _TARGET_ARM_
regMask = tmpMask;
#endif
/* grab EAX, EDX for this tree node */
tree->gtUsedRegs = (regMaskSmall)trashedMask | op1->gtUsedRegs | op2->gtUsedRegs;
goto RETURN_CHECK;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
#ifndef _TARGET_64BIT_
if (type == TYP_LONG)
{
if (op2->IsCnsIntOrI())
{
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
// no register used by op2
op2->gtUsedRegs = 0;
tree->gtUsedRegs = op1->gtUsedRegs;
}
else
{
// since RBM_LNGARG_0 and RBM_SHIFT_LNG are hardwired we can't have them in the locked registers
tmpMask = lockedRegs;
tmpMask &= ~RBM_LNGARG_0;
tmpMask &= ~RBM_SHIFT_LNG;
// op2 goes to RBM_SHIFT, op1 to the RBM_LNGARG_0 pair
if (tree->gtFlags & GTF_REVERSE_OPS)
{
rpPredictTreeRegUse(op2, PREDICT_REG_SHIFT_LNG, tmpMask, RBM_NONE);
tmpMask |= RBM_SHIFT_LNG;
// Ensure that the RBM_SHIFT_LNG register interfere with op2's compCurLife
// Fix 383843 X86/ARM ILGEN
rpRecordRegIntf(RBM_SHIFT_LNG, compCurLife
DEBUGARG("SHIFT_LNG arg setup"));
rpPredictTreeRegUse(op1, PREDICT_PAIR_LNGARG_0, tmpMask, RBM_LASTUSE);
}
else
{
rpPredictTreeRegUse(op1, PREDICT_PAIR_LNGARG_0, tmpMask, RBM_NONE);
tmpMask |= RBM_LNGARG_0;
// Ensure that the RBM_LNGARG_0 registers interfere with op1's compCurLife
// Fix 383839 ARM ILGEN
rpRecordRegIntf(RBM_LNGARG_0, compCurLife
DEBUGARG("LNGARG_0 arg setup"));
rpPredictTreeRegUse(op2, PREDICT_REG_SHIFT_LNG, tmpMask, RBM_LASTUSE);
}
regMask = RBM_LNGRET; // function return registers
op1->gtUsedRegs |= RBM_LNGARG_0;
op2->gtUsedRegs |= RBM_SHIFT_LNG;
tree->gtUsedRegs = op1->gtUsedRegs | op2->gtUsedRegs;
// We are using a helper function to do shift:
//
tree->gtUsedRegs |= RBM_CALLEE_TRASH;
}
}
else
#endif // _TARGET_64BIT_
{
#ifdef _TARGET_XARCH_
if (!op2->IsCnsIntOrI())
predictReg = PREDICT_NOT_REG_ECX;
#endif
HANDLE_SHIFT_COUNT:
// Note that this code is also used by assigning shift operators (i.e. GT_ASG_LSH)
regMaskTP tmpRsvdRegs;
if ((tree->gtFlags & GTF_REVERSE_OPS) == 0)
{
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rsvdRegs = RBM_LASTUSE;
tmpRsvdRegs = RBM_NONE;
}
else
{
regMask = RBM_NONE;
// Special case op1 of a constant
if (op1->IsCnsIntOrI())
tmpRsvdRegs = RBM_LASTUSE; // Allow a last use to occur in op2; See System.Xml.Schema.BitSet:Get(int):bool
else
tmpRsvdRegs = op1->gtRsvdRegs;
}
op2Mask = RBM_NONE;
if (!op2->IsCnsIntOrI())
{
if ((REG_SHIFT != REG_NA) && ((RBM_SHIFT & tmpRsvdRegs) == 0))
{
op2PredictReg = PREDICT_REG_SHIFT;
}
else
{
op2PredictReg = PREDICT_REG;
}
/* evaluate shift count into a register, likely the PREDICT_REG_SHIFT register */
op2Mask = rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs | regMask, tmpRsvdRegs);
// If our target arch has a REG_SHIFT register then
// we set the PrefReg when we have a LclVar for op2
// we add an interference with REG_SHIFT for any other LclVars alive at op2
if (REG_SHIFT != REG_NA)
{
VARSET_TP VARSET_INIT(this, liveSet, compCurLife);
while (op2->gtOper == GT_COMMA)
{
op2 = op2->gtOp.gtOp2;
}
if (op2->gtOper == GT_LCL_VAR)
{
varDsc = lvaTable + op2->gtLclVarCommon.gtLclNum;
varDsc->setPrefReg(REG_SHIFT, this);
if (varDsc->lvTracked)
{
VarSetOps::RemoveElemD(this, liveSet, varDsc->lvVarIndex);
}
}
// Ensure that we have a register interference with the LclVar in tree's LiveSet,
// excluding the LclVar that was used for the shift amount as it is read-only
// and can be kept alive through the shift operation
//
rpRecordRegIntf(RBM_SHIFT, liveSet
DEBUGARG("Variable Shift Register"));
// In case op2Mask doesn't contain the required shift register,
// we will or it in now.
op2Mask |= RBM_SHIFT;
}
}
if (tree->gtFlags & GTF_REVERSE_OPS)
{
assert(regMask == RBM_NONE);
regMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs | op2Mask, rsvdRegs | RBM_LASTUSE);
}
#if CPU_HAS_BYTE_REGS
if (varTypeIsByte(type))
{
// Fix 383789 X86 ILGEN
// Fix 383813 X86 ILGEN
// Fix 383828 X86 ILGEN
if (op1->gtOper == GT_LCL_VAR)
{
varDsc = lvaTable + op1->gtLclVar.gtLclNum;
if (varDsc->lvTracked)
{
VARSET_TP VARSET_INIT_NOCOPY(op1VarBit, VarSetOps::MakeSingleton(this, varDsc->lvVarIndex));
// Ensure that we don't assign a Non-Byteable register for op1's LCL_VAR
rpRecordRegIntf(RBM_NON_BYTE_REGS, op1VarBit
DEBUGARG("Non Byte Register"));
}
}
if ((regMask & RBM_BYTE_REGS) == 0)
{
// We need to grab a byte-able register, (i.e. EAX, EDX, ECX, EBX)
// and we can't select one that is already reserved (i.e. lockedRegs or regMask)
//
regMask |= rpPredictRegPick(type, PREDICT_SCRATCH_REG, (lockedRegs | regMask | RBM_NON_BYTE_REGS));
}
}
#endif
tree->gtUsedRegs = (regMaskSmall)(regMask | op2Mask);
}
goto RETURN_CHECK;
case GT_COMMA:
if (tree->gtFlags & GTF_REVERSE_OPS)
{
if (predictReg == PREDICT_NONE)
{
predictReg = PREDICT_REG;
}
else if (rpHasVarIndexForPredict(predictReg))
{
/* Don't propagate the use of tgt reg use in a GT_COMMA */
predictReg = PREDICT_SCRATCH_REG;
}
regMask = rpPredictTreeRegUse(op2, predictReg, lockedRegs, rsvdRegs);
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs | regMask, RBM_LASTUSE);
}
else
{
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
/* CodeGen will enregister the op2 side of a GT_COMMA */
if (predictReg == PREDICT_NONE)
{
predictReg = PREDICT_REG;
}
else if (rpHasVarIndexForPredict(predictReg))
{
/* Don't propagate the use of tgt reg use in a GT_COMMA */
predictReg = PREDICT_SCRATCH_REG;
}
regMask = rpPredictTreeRegUse(op2, predictReg, lockedRegs, rsvdRegs);
}
// tree should only accumulate the used registers from the op2 side of the GT_COMMA
//
tree->gtUsedRegs = op2->gtUsedRegs;
if ((op2->gtOper == GT_LCL_VAR) && (rsvdRegs != 0))
{
LclVarDsc * op2VarDsc = lvaTable + op2->gtLclVarCommon.gtLclNum;
if (op2VarDsc->lvTracked)
{
VARSET_TP VARSET_INIT_NOCOPY(op2VarBit, VarSetOps::MakeSingleton(this, op2VarDsc->lvVarIndex));
rpRecordRegIntf(rsvdRegs, op2VarBit DEBUGARG( "comma use"));
}
}
goto RETURN_CHECK;
case GT_QMARK:
{
noway_assert(op1 != NULL && op2 != NULL);
/*
* If the gtUsedRegs conflicts with lockedRegs
* then we going to have to spill some registers
* into the non-trashed register set to keep it alive
*/
unsigned spillCnt; spillCnt = 0;
regMaskTP spillRegs; spillRegs = lockedRegs & tree->gtUsedRegs;
while (spillRegs)
{
/* Find the next register that needs to be spilled */
tmpMask = genFindLowestBit(spillRegs);
#ifdef DEBUG
if (verbose)
{
printf("Predict spill of %s before: ",
getRegName(genRegNumFromMask(tmpMask)));
gtDispTree(tree, 0, NULL, true);
}
#endif
/* In Codegen it will typically introduce a spill temp here */
/* rather than relocating the register to a non trashed reg */
rpPredictSpillCnt++;
spillCnt++;
/* Remove it from the spillRegs and lockedRegs*/
spillRegs &= ~tmpMask;
lockedRegs &= ~tmpMask;
}
{
VARSET_TP VARSET_INIT(this, startQmarkCondUseInPlaceVars, rpUseInPlace);
/* Evaluate the <cond> subtree */
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
VarSetOps::Assign(this, rpUseInPlace, startQmarkCondUseInPlaceVars);
tree->gtUsedRegs = op1->gtUsedRegs;
noway_assert(op2->gtOper == GT_COLON);
if (rpHasVarIndexForPredict(predictReg) && ((op2->gtFlags & (GTF_ASG|GTF_CALL)) != 0))
{
// Don't try to target the register specified in predictReg when we have complex subtrees
//
predictReg = PREDICT_SCRATCH_REG;
}
GenTreePtr elseTree = op2->AsColon()->ElseNode();
GenTreePtr thenTree = op2->AsColon()->ThenNode();
noway_assert(thenTree != NULL && elseTree != NULL);
// Update compCurLife to only those vars live on the <then> subtree
VarSetOps::Assign(this, compCurLife, tree->gtQmark.gtThenLiveSet);
if (type == TYP_VOID)
{
/* Evaluate the <then> subtree */
rpPredictTreeRegUse(thenTree, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
regMask = RBM_NONE;
predictReg = PREDICT_NONE;
}
else
{
// A mask to use to force the predictor to choose low registers (to reduce code size)
regMaskTP avoidRegs = RBM_NONE;
#ifdef _TARGET_ARM_
avoidRegs = (RBM_R12|RBM_LR);
#endif
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
/* Evaluate the <then> subtree */
regMask = rpPredictTreeRegUse(thenTree, predictReg, lockedRegs, rsvdRegs | avoidRegs | RBM_LASTUSE);
if (regMask)
{
rpPredictReg op1PredictReg = rpGetPredictForMask(regMask);
if (op1PredictReg != PREDICT_NONE)
predictReg = op1PredictReg;
}
}
VarSetOps::Assign(this, rpUseInPlace, startQmarkCondUseInPlaceVars);
/* Evaluate the <else> subtree */
// First record the post-then liveness, and reset the current liveness to the else
// branch liveness.
#ifdef DEBUG
VARSET_TP VARSET_INIT(this, postThenLive, compCurLife);
#endif
VarSetOps::Assign(this, compCurLife, tree->gtQmark.gtElseLiveSet);
rpPredictTreeRegUse(elseTree, predictReg, lockedRegs, rsvdRegs | RBM_LASTUSE);
tree->gtUsedRegs |= thenTree->gtUsedRegs | elseTree->gtUsedRegs;
// The then and the else are "virtual basic blocks" that form a control-flow diamond.
// They each have only one successor, which they share. Their live-out sets must equal the
// live-in set of this virtual successor block, and thus must be the same. We can assert
// that equality here.
assert(VarSetOps::Equal(this, compCurLife, postThenLive));
if (spillCnt > 0)
{
regMaskTP reloadMask = RBM_NONE;
while (spillCnt)
{
regMaskTP reloadReg;
/* Get an extra register to hold it */
reloadReg = rpPredictRegPick(TYP_INT, PREDICT_REG,
lockedRegs | regMask | reloadMask);
#ifdef DEBUG
if (verbose)
{
printf("Predict reload into %s after : ",
getRegName(genRegNumFromMask(reloadReg)));
gtDispTree(tree, 0, NULL, true);
}
#endif
reloadMask |= reloadReg;
spillCnt--;
}
/* update the gtUsedRegs mask */
tree->gtUsedRegs |= reloadMask;
}
}
goto RETURN_CHECK;
}
case GT_RETURN:
tree->gtUsedRegs = RBM_NONE;
regMask = RBM_NONE;
/* Is there a return value? */
if (op1 != NULL)
{
#if FEATURE_FP_REGALLOC
if (varTypeIsFloating(type))
{
predictReg = PREDICT_FLTRET;
if (type == TYP_FLOAT)
regMask = RBM_FLOATRET;
else
regMask = RBM_DOUBLERET;
}
else
#endif
if (isRegPairType(type))
{
predictReg = PREDICT_LNGRET;
regMask = RBM_LNGRET;
}
else
{
predictReg = PREDICT_INTRET;
regMask = RBM_INTRET;
}
if (info.compCallUnmanaged)
{
lockedRegs |= (RBM_PINVOKE_TCB | RBM_PINVOKE_FRAME);
}
rpPredictTreeRegUse(op1, predictReg, lockedRegs, RBM_LASTUSE);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
}
#if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
// When on Arm under profiler, to emit Leave callback we would need RBM_PROFILER_RETURN_USED.
// We could optimize on registers based on int/long or no return value. But to
// keep it simple we will mark entire RBM_PROFILER_RETURN_USED as used regs here.
if (compIsProfilerHookNeeded())
{
tree->gtUsedRegs |= RBM_PROFILER_RET_USED;
}
#endif
goto RETURN_CHECK;
case GT_RETFILT:
if (op1 != NULL)
{
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
regMask = genReturnRegForTree(tree);
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)regMask;
goto RETURN_CHECK;
}
tree->gtUsedRegs = 0;
regMask = 0;
goto RETURN_CHECK;
case GT_JTRUE:
/* This must be a test of a relational operator */
noway_assert(op1->OperIsCompare());
/* Only condition code set by this operation */
rpPredictTreeRegUse(op1, PREDICT_NONE, lockedRegs, RBM_NONE);
tree->gtUsedRegs = op1->gtUsedRegs;
regMask = 0;
goto RETURN_CHECK;
case GT_SWITCH:
noway_assert(type <= TYP_INT);
noway_assert(compCurBB->bbJumpKind == BBJ_SWITCH);
#ifdef _TARGET_ARM_
{
regMask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, RBM_NONE);
unsigned jumpCnt = compCurBB->bbJumpSwt->bbsCount;
if (jumpCnt > 2)
{
// Table based switch requires an extra register for the table base
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regMask);
}
tree->gtUsedRegs = op1->gtUsedRegs | regMask;
}
#else // !_TARGET_ARM_
rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, RBM_NONE);
tree->gtUsedRegs = op1->gtUsedRegs;
#endif // _TARGET_ARM_
regMask = 0;
goto RETURN_CHECK;
case GT_CKFINITE:
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs);
// Need a reg to load exponent into
regMask = rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | rsvdRegs);
tree->gtUsedRegs = (regMaskSmall)regMask | op1->gtUsedRegs;
goto RETURN_CHECK;
case GT_LCLHEAP:
regMask = rpPredictTreeRegUse(op1, PREDICT_SCRATCH_REG, lockedRegs, rsvdRegs);
op2Mask = 0;
#ifdef _TARGET_ARM_
if (info.compInitMem)
{
// We zero out two registers in the ARM codegen path
op2Mask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | rsvdRegs | regMask | op2Mask);
}
#endif
op1->gtUsedRegs |= (regMaskSmall)regMask;
tree->gtUsedRegs = op1->gtUsedRegs | (regMaskSmall)op2Mask;
// The result will be put in the reg we picked for the size
// regMask = <already set as we want it to be>
goto RETURN_CHECK;
case GT_COPYOBJ:
case GT_COPYBLK:
case GT_INITBLK:
{
regMask = 0;
bool hasGCpointer; hasGCpointer = false;
bool dstIsOnStack; dstIsOnStack = false;
bool useMemHelper; useMemHelper = false;
bool useBarriers; useBarriers = false;
size_t blkSize; blkSize = 0;
hasGCpointer = ((tree->gtFlags & GTF_BLK_HASGCPTR) != 0);
if (op2->OperGet() == GT_CNS_INT)
{
if (op2->IsIconHandle(GTF_ICON_CLASS_HDL))
{
if (tree->OperGet() == GT_COPYOBJ)
{
GenTreePtr dstObj = op1->gtOp.gtOp1;
dstIsOnStack = (dstObj->gtOper == GT_ADDR && (dstObj->gtFlags & GTF_ADDR_ONSTACK));
}
CORINFO_CLASS_HANDLE clsHnd = (CORINFO_CLASS_HANDLE) op2->gtIntCon.gtIconVal;
blkSize = roundUp(info.compCompHnd->getClassSize(clsHnd), TARGET_POINTER_SIZE);
}
else // gtIconVal contains amount to copy
{
blkSize = (unsigned) op2->gtIntCon.gtIconVal;
}
if (tree->OperGet() == GT_INITBLK)
{
GenTreePtr initVal = op1->gtOp.gtOp2;
if (initVal->OperGet() != GT_CNS_INT)
{
useMemHelper = true;
}
}
}
else
{
useMemHelper = true;
}
// If we are copying any GC pointers then the GTF_BLK_HASGCPTR flags must be set
if (hasGCpointer && !dstIsOnStack)
{
useBarriers = true;
}
#ifdef _TARGET_ARM_
//
// On ARM For COPYBLK & INITBLK we have special treatment for constant lengths.
//
if (!useMemHelper && !useBarriers)
{
bool useLoop = false;
unsigned fullStoreCount = blkSize / TARGET_POINTER_SIZE;
// A mask to use to force the predictor to choose low registers (to reduce code size)
regMaskTP avoidReg = (RBM_R12|RBM_LR);
// Allow the src and dst to be used in place, unless we use a loop, in which
// case we will need scratch registers as we will be writing to them.
rpPredictReg srcAndDstPredict = PREDICT_REG;
// Will we be using a loop to implement this INITBLK/COPYBLK?
if ((GenTree::OperIsCopyBlkOp(oper) && (fullStoreCount >= 8)) ||
((oper == GT_INITBLK) && (fullStoreCount >= 16)))
{
useLoop = true;
avoidReg = RBM_NONE;
srcAndDstPredict = PREDICT_SCRATCH_REG;
}
if (op1->gtFlags & GTF_REVERSE_OPS)
{
regMask |= rpPredictTreeRegUse(op1->gtOp.gtOp2, srcAndDstPredict, lockedRegs, op1->gtOp.gtOp1->gtRsvdRegs | avoidReg | RBM_LASTUSE);
regMask |= rpPredictTreeRegUse(op1->gtOp.gtOp1, srcAndDstPredict, lockedRegs | regMask, avoidReg);
}
else
{
regMask |= rpPredictTreeRegUse(op1->gtOp.gtOp1, srcAndDstPredict, lockedRegs, op1->gtOp.gtOp2->gtRsvdRegs | avoidReg | RBM_LASTUSE);
regMask |= rpPredictTreeRegUse(op1->gtOp.gtOp2, srcAndDstPredict, lockedRegs | regMask, avoidReg);
}
// We need at least one scratch register for a GT_COPYBLK
if (GenTree::OperIsCopyBlkOp(oper))
{
// Pick a low register to reduce the code size
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regMask | avoidReg);
}
if (useLoop)
{
if (GenTree::OperIsCopyBlkOp(oper))
{
// We need a second temp register for a GT_COPYBLK (our code gen is load two/store two)
// Pick another low register to reduce the code size
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regMask | avoidReg);
}
// We need a loop index register
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regMask);
}
tree->gtUsedRegs = op1->gtOp.gtOp1->gtUsedRegs |
op1->gtOp.gtOp2->gtUsedRegs |
(regMaskSmall)regMask;
regMask = 0;
goto RETURN_CHECK;
}
#endif
// What order should the Dest, Val/Src, and Size be calculated
#if defined(_TARGET_XARCH_)
fgOrderBlockOps(tree,
RBM_EDI, (oper == GT_INITBLK) ? RBM_EAX : RBM_ESI, RBM_ECX,
opsPtr, regsPtr);
// We're going to use these, might as well make them available now
codeGen->regSet.rsSetRegsModified(RBM_EDI | RBM_ECX);
if (GenTree::OperIsCopyBlkOp(oper))
codeGen->regSet.rsSetRegsModified(RBM_ESI);
#elif defined(_TARGET_ARM_)
if (useMemHelper)
{
// For all other cases that involve non-constants, we just call memcpy/memset
// JIT helpers
fgOrderBlockOps(tree, RBM_ARG_0, RBM_ARG_1, RBM_ARG_2, opsPtr, regsPtr);
interferingRegs |= RBM_CALLEE_TRASH;
#ifdef DEBUG
if (verbose)
printf("Adding interference with RBM_CALLEE_TRASH for memcpy/memset\n");
#endif
}
else // useBarriers
{
assert(useBarriers);
assert(GenTree::OperIsCopyBlkOp(oper));
fgOrderBlockOps(tree, RBM_ARG_0, RBM_ARG_1, REG_TMP_1, opsPtr, regsPtr);
// For this case Codegen will call the CORINFO_HELP_ASSIGN_BYREF helper
interferingRegs |= RBM_CALLEE_TRASH_NOGC;
#ifdef DEBUG
if (verbose)
printf("Adding interference with RBM_CALLEE_TRASH_NOGC for Byref WriteBarrier\n");
#endif
}
#else // !_TARGET_X86_ && !_TARGET_ARM_
#error "Non-ARM or x86 _TARGET_ in RegPredict for INITBLK/COPYBLK"
#endif // !_TARGET_X86_ && !_TARGET_ARM_
regMask |= rpPredictTreeRegUse(opsPtr[0],
rpGetPredictForMask(regsPtr[0]),
lockedRegs,
opsPtr[1]->gtRsvdRegs | opsPtr[2]->gtRsvdRegs | RBM_LASTUSE);
regMask |= regsPtr[0];
opsPtr[0]->gtUsedRegs |= regsPtr[0];
rpRecordRegIntf(regsPtr[0], compCurLife
DEBUGARG("movsd dest"));
regMask |= rpPredictTreeRegUse(opsPtr[1],
rpGetPredictForMask(regsPtr[1]),
lockedRegs | regMask,
opsPtr[2]->gtRsvdRegs | RBM_LASTUSE);
regMask |= regsPtr[1];
opsPtr[1]->gtUsedRegs |= regsPtr[1];
rpRecordRegIntf(regsPtr[1], compCurLife
DEBUGARG("movsd src"));
regMask |= rpPredictTreeRegUse(opsPtr[2],
rpGetPredictForMask(regsPtr[2]),
lockedRegs | regMask,
RBM_NONE);
regMask |= regsPtr[2];
opsPtr[2]->gtUsedRegs |= regsPtr[2];
tree->gtUsedRegs = opsPtr[0]->gtUsedRegs |
opsPtr[1]->gtUsedRegs |
opsPtr[2]->gtUsedRegs |
(regMaskSmall)regMask;
regMask = 0;
goto RETURN_CHECK;
}
case GT_LDOBJ:
{
#ifdef _TARGET_ARM_
if (predictReg <= PREDICT_REG)
predictReg = PREDICT_SCRATCH_REG;
regMaskTP avoidRegs = (RBM_R12|RBM_LR); // A mask to use to force the predictor to choose low registers (to reduce code size)
regMask = RBM_NONE;
tmpMask = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs | avoidRegs);
#endif
if (fgIsIndirOfAddrOfLocal(tree) != NULL)
{
compUpdateLifeVar</*ForCodeGen*/false>(tree);
}
#ifdef _TARGET_ARM_
unsigned objSize = info.compCompHnd->getClassSize(tree->gtLdObj.gtClass);
regMaskTP preferReg = rpPredictRegMask(predictReg, TYP_I_IMPL);
// If it has one bit set, and that's an arg reg...
if (preferReg != RBM_NONE && genMaxOneBit(preferReg) && ((preferReg & RBM_ARG_REGS) != 0))
{
// We are passing the ldObj in the argument registers
//
regNumber rn = genRegNumFromMask(preferReg);
// Add the registers used to pass the ldObj to regMask.
for (unsigned i = 0; i < objSize/4; i++)
{
if (rn == MAX_REG_ARG)
break;
// Otherwise...
regMask |= genRegMask(rn);
rn = genRegArgNext(rn);
}
}
else
{
// We are passing the ldObj in the outgoing arg space
// We will need one register to load into unless the ldObj size is 4 or less.
//
if (objSize > 4)
{
regMask = rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | tmpMask | avoidRegs);
}
}
tree->gtUsedRegs = (regMaskSmall)(regMask | tmpMask);
goto RETURN_CHECK;
#else // !_TARGET_ARM
goto GENERIC_UNARY;
#endif // _TARGET_ARM_
}
case GT_MKREFANY:
{
#ifdef _TARGET_ARM_
regMaskTP preferReg = rpPredictRegMask(predictReg, TYP_I_IMPL);
regMask = RBM_NONE;
if ((((preferReg-1) & preferReg) == 0) && ((preferReg & RBM_ARG_REGS) != 0))
{
// A MKREFANY takes up two registers.
regNumber rn = genRegNumFromMask(preferReg);
regMask = RBM_NONE;
if (rn < MAX_REG_ARG)
{
regMask |= genRegMask(rn);
rn = genRegArgNext(rn);
if (rn < MAX_REG_ARG)
regMask |= genRegMask(rn);
}
}
if (regMask != RBM_NONE)
{
// Condensation of GENERIC_BINARY path.
assert((tree->gtFlags & GTF_REVERSE_OPS) == 0);
op2PredictReg = PREDICT_REG;
regMaskTP regMaskOp1 = rpPredictTreeRegUse(op1, predictReg, lockedRegs, rsvdRegs | op2->gtRsvdRegs);
rpPredictTreeRegUse(op2, op2PredictReg, lockedRegs | regMaskOp1, RBM_LASTUSE);
regMask |= op1->gtUsedRegs | op2->gtUsedRegs;
tree->gtUsedRegs = (regMaskSmall)regMask;
goto RETURN_CHECK;
}
tree->gtUsedRegs = op1->gtUsedRegs;
#endif // _TARGET_ARM_
goto GENERIC_BINARY;
}
case GT_BOX:
goto GENERIC_UNARY;
case GT_LOCKADD:
goto GENERIC_BINARY;
case GT_XADD:
case GT_XCHG:
//Ensure we can write to op2. op2 will hold the output.
if (predictReg < PREDICT_SCRATCH_REG)
predictReg = PREDICT_SCRATCH_REG;
if (tree->gtFlags & GTF_REVERSE_OPS)
{
op2Mask = rpPredictTreeRegUse(op2, predictReg, lockedRegs, rsvdRegs);
regMask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs|op2Mask);
}
else
{
regMask = rpPredictTreeRegUse(op1, PREDICT_REG, lockedRegs, rsvdRegs);
op2Mask = rpPredictTreeRegUse(op2, PREDICT_SCRATCH_REG, lockedRegs, rsvdRegs|regMask);
}
tree->gtUsedRegs = (regMaskSmall)(regMask | op2Mask);
goto RETURN_CHECK;
case GT_ARR_LENGTH:
goto GENERIC_UNARY;
default:
#ifdef DEBUG
gtDispTree(tree);
#endif
noway_assert(!"unexpected simple operator in reg use prediction");
break;
}
}
/* See what kind of a special operator we have here */
switch (oper)
{
GenTreePtr args;
GenTreeArgList* list;
regMaskTP keepMask;
unsigned regArgsNum;
int regIndex;
regMaskTP regArgMask;
regMaskTP curArgMask;
case GT_CALL:
{
/* initialize so we can just or in various bits */
tree->gtUsedRegs = RBM_NONE;
#if GTF_CALL_REG_SAVE
/*
* Unless the GTF_CALL_REG_SAVE flag is set,
* we can't preserve the RBM_CALLEE_TRASH registers.
* (likewise we can't preserve the return registers)
* So we remove them from the lockedRegs set and
* record any of them in the keepMask
*/
if (tree->gtFlags & GTF_CALL_REG_SAVE)
{
regMaskTP trashMask = genReturnRegForTree(tree);
keepMask = lockedRegs & trashMask;
lockedRegs &= ~trashMask;
}
else
#endif
{
keepMask = lockedRegs & RBM_CALLEE_TRASH;
lockedRegs &= ~RBM_CALLEE_TRASH;
}
regArgsNum = 0;
regIndex = 0;
/* Is there an object pointer? */
if (tree->gtCall.gtCallObjp)
{
/* Evaluate the instance pointer first */
args = tree->gtCall.gtCallObjp;
/* the objPtr always goes to an integer register (through temp or directly) */
noway_assert(regArgsNum == 0);
regArgsNum++;
/* Must be passed in a register */
noway_assert(args->gtFlags & GTF_LATE_ARG);
/* Must be either a deferred reg arg node or a GT_ASG node */
noway_assert( args->IsArgPlaceHolderNode() ||
args->IsNothingNode() ||
(args->gtOper == GT_ASG) ||
args->OperIsCopyBlkOp() ||
(args->gtOper == GT_COMMA));
if (!args->IsArgPlaceHolderNode())
{
rpPredictTreeRegUse(args, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
}
}
VARSET_TP VARSET_INIT_NOCOPY(startArgUseInPlaceVars, VarSetOps::UninitVal());
VarSetOps::Assign(this, startArgUseInPlaceVars, rpUseInPlace);
/* process argument list */
for (list = tree->gtCall.gtCallArgs; list; list = list->Rest())
{
args = list->Current();
if (args->gtFlags & GTF_LATE_ARG)
{
/* Must be either a Placeholder/NOP node or a GT_ASG node */
noway_assert( args->IsArgPlaceHolderNode() ||
args->IsNothingNode() ||
(args->gtOper == GT_ASG) ||
args->OperIsCopyBlkOp() ||
(args->gtOper == GT_COMMA));
if (!args->IsArgPlaceHolderNode())
{
rpPredictTreeRegUse(args, PREDICT_NONE, lockedRegs, RBM_LASTUSE);
}
regArgsNum++;
}
else
{
#ifdef FEATURE_FIXED_OUT_ARGS
// We'll store this argument into the outgoing argument area
// It needs to be in a register to be stored.
//
predictReg = PREDICT_REG;
#else // !FEATURE_FIXED_OUT_ARGS
// We'll generate a push for this argument
//
predictReg = PREDICT_NONE;
if (varTypeIsSmall(args->TypeGet()))
{
/* We may need to sign or zero extend a small type using a register */
predictReg = PREDICT_SCRATCH_REG;
}
#endif
rpPredictTreeRegUse(args, predictReg, lockedRegs, RBM_LASTUSE);
}
VarSetOps::Assign(this, rpUseInPlace, startArgUseInPlaceVars);
tree->gtUsedRegs |= args->gtUsedRegs;
}
/* Is there a late argument list */
regIndex = 0;
regArgMask = RBM_NONE; // Set of argument registers that have already been setup.
args = NULL;
/* process the late argument list */
for (list = tree->gtCall.gtCallLateArgs; list; regIndex++)
{
// If the current argument being copied is a promoted struct local, set this pointer to its description.
LclVarDsc* promotedStructLocal = NULL;
curArgMask = RBM_NONE; // Set of argument registers that are going to be setup by this arg
tmpMask = RBM_NONE; // Set of additional temp registers that are need only to setup the current arg
assert(list->IsList());
args = list->Current();
list = list->Rest();
assert(!args->IsArgPlaceHolderNode()); // No place holders nodes are in gtCallLateArgs;
fgArgTabEntryPtr curArgTabEntry = gtArgEntryByNode(tree, args);
assert(curArgTabEntry);
regNumber regNum = curArgTabEntry->regNum; // first register use to pass this argument
unsigned numSlots = curArgTabEntry->numSlots; // number of outgoing arg stack slots used by this argument
rpPredictReg argPredictReg;
regMaskTP avoidReg = RBM_NONE;
if (regNum != REG_STK)
{
argPredictReg = rpGetPredictForReg(regNum);
curArgMask |= genRegMask(regNum);
}
else
{
assert(numSlots> 0);
argPredictReg = PREDICT_NONE;
#ifdef _TARGET_ARM_
// Force the predictor to choose a low register when regNum is REG_STK to reduce code bloat
avoidReg = (RBM_R12|RBM_LR);
#endif
}
#ifdef _TARGET_ARM_
// For TYP_LONG or TYP_DOUBLE register arguments we need to add the second argument register
//
if ((regNum != REG_STK) && ((args->TypeGet() == TYP_LONG) || (args->TypeGet() == TYP_DOUBLE)))
{
// 64-bit longs and doubles require 2 consecutive argument registers
curArgMask |= genRegMask(REG_NEXT(regNum));
}
else if (args->TypeGet() == TYP_STRUCT)
{
GenTreePtr argx = args;
GenTreePtr lclVarTree = NULL;
/* The GT_LDOBJ may be be a child of a GT_COMMA */
while (argx->gtOper == GT_COMMA)
{
argx = argx->gtOp.gtOp2;
}
unsigned originalSize = 0;
if (argx->gtOper == GT_LDOBJ)
{
originalSize = info.compCompHnd->getClassSize(argx->gtLdObj.gtClass);
// Is it the address of a promoted struct local?
if (argx->gtLdObj.gtOp1->gtOper == GT_ADDR &&
argx->gtLdObj.gtOp1->gtOp.gtOp1->gtOper == GT_LCL_VAR)
{
lclVarTree = argx->gtLdObj.gtOp1->gtOp.gtOp1;
LclVarDsc* varDsc = &lvaTable[lclVarTree->gtLclVarCommon.gtLclNum];
if (varDsc->lvPromoted)
promotedStructLocal = varDsc;
}
}
else if (argx->gtOper == GT_LCL_VAR)
{
varDsc = lvaTable + argx->gtLclVarCommon.gtLclNum;
originalSize = varDsc->lvSize();
// Is it a promoted struct local?
if (varDsc->lvPromoted)
promotedStructLocal = varDsc;
}
else if (argx->gtOper == GT_MKREFANY)
{
originalSize = 2 * TARGET_POINTER_SIZE;
}
else
{
noway_assert(!"Can't predict unsupported TYP_STRUCT arg kind");
}
// We only pass arguments differently if it a struct local "independently" promoted, which
// allows the field locals can be independently enregistered.
if (promotedStructLocal != NULL)
{
if (lvaGetPromotionType(promotedStructLocal) != PROMOTION_TYPE_INDEPENDENT)
promotedStructLocal = NULL;
}
unsigned slots = ((unsigned)(roundUp(originalSize, TARGET_POINTER_SIZE))) / REGSIZE_BYTES;
// Are we passing a TYP_STRUCT in multiple integer registers?
// if so set up curArgMask to reflect this
// Also slots is updated to reflect the number of outgoing arg slots that we will write
if (regNum != REG_STK)
{
regNumber regLast = (curArgTabEntry->isHfaRegArg) ? LAST_FP_ARGREG : REG_ARG_LAST;
assert(genIsValidReg(regNum));
regNumber nextReg = REG_NEXT(regNum);
slots--;
while (slots > 0 && nextReg <= regLast)
{
curArgMask |= genRegMask(nextReg);
nextReg = REG_NEXT(nextReg);
slots--;
}
}
if (promotedStructLocal != NULL)
{
// All or a portion of this struct will be placed in the argument registers indicated by "curArgMask".
// We build in knowledge of the order in which the code is generated here, so that the second arg to be evaluated
// interferes with the reg for the first, the third with the regs for the first and second, etc.
// But since we always place the stack slots before placing the register slots we do not add inteferences
// for any part of the struct that gets passed on the stack.
argPredictReg = PREDICT_NONE; // We will target the indivual fields into registers but not the whole struct
regMaskTP prevArgMask = RBM_NONE;
for (unsigned i = 0; i < promotedStructLocal->lvFieldCnt; i++)
{
LclVarDsc* fieldVarDsc = &lvaTable[promotedStructLocal->lvFieldLclStart + i];
if (fieldVarDsc->lvTracked)
{
assert (lclVarTree != NULL);
if (prevArgMask != RBM_NONE)
{
rpRecordRegIntf(prevArgMask, VarSetOps::MakeSingleton(this, fieldVarDsc->lvVarIndex)
DEBUGARG("fieldVar/argReg"));
}
}
// Now see many registers this uses up.
unsigned firstRegOffset = fieldVarDsc->lvFldOffset / TARGET_POINTER_SIZE;
unsigned nextAfterLastRegOffset = (fieldVarDsc->lvFldOffset + fieldVarDsc->lvExactSize + TARGET_POINTER_SIZE - 1) / TARGET_POINTER_SIZE;
unsigned nextAfterLastArgRegOffset = min(nextAfterLastRegOffset, genIsValidIntReg(regNum) ? REG_NEXT(REG_ARG_LAST) : REG_NEXT(LAST_FP_ARGREG));
for (unsigned regOffset = firstRegOffset; regOffset < nextAfterLastArgRegOffset; regOffset++)
{
prevArgMask |= genRegMask(regNumber(regNum + regOffset));
}
if (nextAfterLastRegOffset > nextAfterLastArgRegOffset)
{
break;
}
if ((fieldVarDsc->lvFldOffset % TARGET_POINTER_SIZE) == 0)
{
// Add the argument register used here as a preferred register for this fieldVarDsc
//
regNumber firstRegUsed = regNumber(regNum + firstRegOffset);
fieldVarDsc->setPrefReg(firstRegUsed, this);
}
}
compUpdateLifeVar</*ForCodeGen*/false>(argx);
}
// If slots is greater than zero then part or all of this TYP_STRUCT
// argument is passed in the outgoing argument area. (except HFA arg)
//
if ((slots > 0) && !curArgTabEntry->isHfaRegArg)
{
// We will need a register to address the TYP_STRUCT
// Note that we can use an argument register in curArgMask as in
// codegen we pass the stack portion of the argument before we
// setup the register part.
//
// Force the predictor to choose a LOW_REG here to reduce code bloat
avoidReg = (RBM_R12|RBM_LR);
assert(tmpMask == RBM_NONE);
tmpMask = rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regArgMask | avoidReg);
// If slots > 1 then we will need a second register to perform the load/store into the outgoing arg area
if (slots > 1)
{
tmpMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs | regArgMask | tmpMask | avoidReg);
}
}
} // (args->TypeGet() == TYP_STRUCT)
#endif // _TARGET_ARM_
// If we have a promotedStructLocal we don't need to call rpPredictTreeRegUse(args, ...
// as we have already calculated the correct tmpMask and curArgMask values and
// by calling rpPredictTreeRegUse we would just add unnecessary register inteferences.
//
if (promotedStructLocal == NULL)
{
/* Target the appropriate argument register */
tmpMask |= rpPredictTreeRegUse(args, argPredictReg, lockedRegs | regArgMask, RBM_LASTUSE);
}
// We mark LDOBJ(ADDR(LOCAL)) with GTF_VAR_DEATH since the local is required to live
// for the duration of the LDOBJ.
if (args->OperGet() == GT_LDOBJ && (args->gtFlags & GTF_VAR_DEATH))
{
GenTreePtr lclVarTree = fgIsIndirOfAddrOfLocal(args);
assert(lclVarTree != NULL); // Or else would not be marked with GTF_VAR_DEATH.
compUpdateLifeVar</*ForCodeGen*/false>(lclVarTree);
}
regArgMask |= curArgMask;
args->gtUsedRegs |= (tmpMask | regArgMask);
tree->gtUsedRegs |= args->gtUsedRegs;
tree->gtCall.gtCallLateArgs->gtUsedRegs |= args->gtUsedRegs;
if (args->gtUsedRegs != RBM_NONE)
{
// Add register interference with the set of registers used or in use when we evaluated
// the current arg, with whatever is alive after the current arg
//
rpRecordRegIntf(args->gtUsedRegs, compCurLife
DEBUGARG("register arg setup"));
}
VarSetOps::Assign(this, rpUseInPlace, startArgUseInPlaceVars);
}
assert(list == NULL);
regMaskTP callAddrMask;
callAddrMask = RBM_NONE;
#if CPU_LOAD_STORE_ARCH
predictReg = PREDICT_SCRATCH_REG;
#else
predictReg = PREDICT_NONE;
#endif
switch (tree->gtFlags & GTF_CALL_VIRT_KIND_MASK)
{
case GTF_CALL_VIRT_STUB:
// We only want to record an interference between the virtual stub
// param reg and anything that's live AFTER the call, but we've not
// yet processed the indirect target. So add RBM_VIRTUAL_STUB_PARAM
// to interferingRegs.
interferingRegs |= RBM_VIRTUAL_STUB_PARAM;
#ifdef DEBUG
if (verbose)
printf("Adding interference with Virtual Stub Param\n");
#endif
codeGen->regSet.rsSetRegsModified(RBM_VIRTUAL_STUB_PARAM);
if (tree->gtCall.gtCallType == CT_INDIRECT)
{
predictReg = PREDICT_REG_VIRTUAL_STUB_PARAM;
}
break;
case GTF_CALL_VIRT_VTABLE:
predictReg = PREDICT_SCRATCH_REG;
break;
case GTF_CALL_NONVIRT:
predictReg = PREDICT_SCRATCH_REG;
break;
}
if (tree->gtCall.gtCallType == CT_INDIRECT)
{
#if defined(_TARGET_ARM_) || defined(_TARGET_AMD64_)
if (tree->gtCall.gtCallCookie)
{
codeGen->regSet.rsSetRegsModified(RBM_PINVOKE_COOKIE_PARAM | RBM_PINVOKE_TARGET_PARAM);
callAddrMask |= rpPredictTreeRegUse(tree->gtCall.gtCallCookie, PREDICT_REG_PINVOKE_COOKIE_PARAM,
lockedRegs | regArgMask, RBM_LASTUSE);
// Just in case we predict some other registers, force interference with our two special
// parameters: PINVOKE_COOKIE_PARAM & PINVOKE_TARGET_PARAM
callAddrMask |= (RBM_PINVOKE_COOKIE_PARAM | RBM_PINVOKE_TARGET_PARAM);
predictReg = PREDICT_REG_PINVOKE_TARGET_PARAM;
}
#endif
callAddrMask |= rpPredictTreeRegUse(tree->gtCall.gtCallAddr, predictReg,
lockedRegs | regArgMask, RBM_LASTUSE);
}
else if (predictReg != PREDICT_NONE)
{
callAddrMask |= rpPredictRegPick(TYP_I_IMPL, predictReg,
lockedRegs | regArgMask);
}
#if INLINE_NDIRECT
if (tree->gtFlags & GTF_CALL_UNMANAGED)
{
// Need a register for tcbReg
callAddrMask |= rpPredictRegPick(TYP_I_IMPL, PREDICT_SCRATCH_REG, lockedRegs | regArgMask | callAddrMask);
#if CPU_LOAD_STORE_ARCH
// Need an extra register for tmpReg
callAddrMask |= rpPredictRegPick(TYP_I_IMPL, PREDICT_SCRATCH_REG, lockedRegs | regArgMask | callAddrMask);
#endif
}
#endif
tree->gtUsedRegs |= callAddrMask;
/* After the call restore the orginal value of lockedRegs */
lockedRegs |= keepMask;
/* set the return register */
regMask = genReturnRegForTree(tree);
if (regMask & rsvdRegs)
{
// We will need to relocate the return register value
regMaskTP intRegMask = (regMask & RBM_ALLINT);
#if FEATURE_FP_REGALLOC
regMaskTP floatRegMask = (regMask & RBM_ALLFLOAT);
#endif
regMask = RBM_NONE;
if (intRegMask)
{
if (intRegMask == RBM_INTRET)
{
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, rsvdRegs | regMask);
}
else if (intRegMask == RBM_LNGRET)
{
regMask |= rpPredictRegPick(TYP_LONG, PREDICT_SCRATCH_REG, rsvdRegs | regMask);
}
else
{
noway_assert(!"unexpected return regMask");
}
}
#if FEATURE_FP_REGALLOC
if (floatRegMask)
{
if (floatRegMask == RBM_FLOATRET)
{
regMask |= rpPredictRegPick(TYP_FLOAT, PREDICT_SCRATCH_REG, rsvdRegs | regMask);
}
else if (floatRegMask == RBM_DOUBLERET)
{
regMask |= rpPredictRegPick(TYP_DOUBLE, PREDICT_SCRATCH_REG, rsvdRegs | regMask);
}
else // HFA return case
{
for (unsigned f=0; f<genCountBits(floatRegMask); f++)
{
regMask |= rpPredictRegPick(TYP_FLOAT, PREDICT_SCRATCH_REG, rsvdRegs | regMask);
}
}
}
#endif
}
/* the return registers (if any) are killed */
tree->gtUsedRegs |= regMask;
#if GTF_CALL_REG_SAVE
if (!(tree->gtFlags & GTF_CALL_REG_SAVE))
#endif
{
/* the RBM_CALLEE_TRASH set are killed (i.e. EAX,ECX,EDX) */
tree->gtUsedRegs |= RBM_CALLEE_TRASH;
}
}
// Mark required registers for emitting tailcall profiler callback as used
#if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
if (compIsProfilerHookNeeded() &&
tree->gtCall.IsTailCall() &&
(tree->gtCall.gtCallType == CT_USER_FUNC))
{
tree->gtUsedRegs |= RBM_PROFILER_TAIL_USED;
}
#endif
break;
case GT_ARR_ELEM:
// Figure out which registers can't be touched
unsigned dim;
for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
rsvdRegs |= tree->gtArrElem.gtArrInds[dim]->gtRsvdRegs;
regMask = rpPredictTreeRegUse(tree->gtArrElem.gtArrObj, PREDICT_REG, lockedRegs, rsvdRegs);
regMaskTP dimsMask; dimsMask = 0;
#if CPU_LOAD_STORE_ARCH
// We need a register to load the bounds of the MD array
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs|regMask);
#endif
for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
{
/* We need scratch registers to compute index-lower_bound.
Also, gtArrInds[0]'s register will be used as the second
addressability register (besides gtArrObj's) */
regMaskTP dimMask = rpPredictTreeRegUse(tree->gtArrElem.gtArrInds[dim],
PREDICT_SCRATCH_REG, lockedRegs|regMask|dimsMask, rsvdRegs);
if (dim == 0)
regMask |= dimMask;
dimsMask |= dimMask;
}
#ifdef _TARGET_XARCH_
// INS_imul doesnt have an immediate constant.
if (!jitIsScaleIndexMul(tree->gtArrElem.gtArrElemSize))
regMask |= rpPredictRegPick(TYP_INT, PREDICT_SCRATCH_REG, lockedRegs|regMask|dimsMask);
#endif
tree->gtUsedRegs = (regMaskSmall)(regMask | dimsMask);
break;
case GT_CMPXCHG:
{
#ifdef _TARGET_XARCH_
rsvdRegs |= RBM_EAX;
#endif
if (tree->gtCmpXchg.gtOpLocation->OperGet() == GT_LCL_VAR)
{
regMask = rpPredictTreeRegUse(tree->gtCmpXchg.gtOpLocation, PREDICT_REG, lockedRegs, rsvdRegs);
}
else
{
regMask = rpPredictTreeRegUse(tree->gtCmpXchg.gtOpLocation, PREDICT_ADDR, lockedRegs, rsvdRegs);
}
op2Mask = rpPredictTreeRegUse(tree->gtCmpXchg.gtOpValue, PREDICT_REG, lockedRegs, rsvdRegs|regMask);
#ifdef _TARGET_XARCH_
rsvdRegs &= ~RBM_EAX;
tmpMask = rpPredictTreeRegUse(tree->gtCmpXchg.gtOpComparand, PREDICT_REG_EAX, lockedRegs,
rsvdRegs|regMask|op2Mask);
tree->gtUsedRegs = (regMaskSmall)(RBM_EAX | regMask | op2Mask | tmpMask);
predictReg = PREDICT_REG_EAX; //When this is done the result is always in EAX.
#else
tmpMask = 0;
tree->gtUsedRegs = (regMaskSmall) (regMask | op2Mask | tmpMask);
#endif
}
break;
case GT_ARR_BOUNDS_CHECK:
{
regMaskTP opArrLenRsvd = rsvdRegs | tree->gtBoundsChk.gtIndex->gtRsvdRegs;
regMask = rpPredictTreeRegUse(tree->gtBoundsChk.gtArrLen, PREDICT_REG, lockedRegs, opArrLenRsvd);
rpPredictTreeRegUse(tree->gtBoundsChk.gtIndex, PREDICT_REG, lockedRegs | regMask, RBM_LASTUSE);
tree->gtUsedRegs = (regMaskSmall)regMask
| tree->gtBoundsChk.gtArrLen->gtUsedRegs
| tree->gtBoundsChk.gtIndex->gtUsedRegs;
}
break;
default:
NO_WAY("unexpected special operator in reg use prediction");
break;
}
RETURN_CHECK:
#ifdef DEBUG
/* make sure we set them to something reasonable */
if (tree->gtUsedRegs & RBM_ILLEGAL)
noway_assert(!"used regs not set properly in reg use prediction");
if (regMask & RBM_ILLEGAL)
noway_assert(!"return value not set propery in reg use prediction");
#endif
/*
* If the gtUsedRegs conflicts with lockedRegs
* then we going to have to spill some registers
* into the non-trashed register set to keep it alive
*/
regMaskTP spillMask;
spillMask = tree->gtUsedRegs & lockedRegs;
if (spillMask)
{
while (spillMask)
{
/* Find the next register that needs to be spilled */
tmpMask = genFindLowestBit(spillMask);
#ifdef DEBUG
if (verbose)
{
printf("Predict spill of %s before: ",
getRegName(genRegNumFromMask(tmpMask)));
gtDispTree(tree, 0, NULL, true);
if ((tmpMask & regMask) == 0)
{
printf("Predict reload of %s after : ",
getRegName(genRegNumFromMask(tmpMask)));
gtDispTree(tree, 0, NULL, true);
}
}
#endif
/* In Codegen it will typically introduce a spill temp here */
/* rather than relocating the register to a non trashed reg */
rpPredictSpillCnt++;
/* Remove it from the spillMask */
spillMask &= ~tmpMask;
}
}
/*
* If the return registers in regMask conflicts with the lockedRegs
* then we allocate extra registers for the reload of the conflicting
* registers.
*
* Set spillMask to the set of locked registers that have to be reloaded here.
* reloadMask is set to the extra registers that are used to reload
* the spilled lockedRegs.
*/
noway_assert(regMask != DUMMY_INIT(RBM_ILLEGAL));
spillMask = lockedRegs & regMask;
if (spillMask)
{
/* Remove the spillMask from regMask */
regMask &= ~spillMask;
regMaskTP reloadMask = RBM_NONE;
while (spillMask)
{
/* Get an extra register to hold it */
regMaskTP reloadReg = rpPredictRegPick(TYP_INT, PREDICT_REG,
lockedRegs | regMask | reloadMask);
#ifdef DEBUG
if (verbose)
{
printf("Predict reload into %s after : ",
getRegName(genRegNumFromMask(reloadReg)));
gtDispTree(tree, 0, NULL, true);
}
#endif
reloadMask |= reloadReg;
/* Remove it from the spillMask */
spillMask &= ~genFindLowestBit(spillMask);
}
/* Update regMask to use the reloadMask */
regMask |= reloadMask;
/* update the gtUsedRegs mask */
tree->gtUsedRegs |= (regMaskSmall)regMask;
}
regMaskTP regUse = tree->gtUsedRegs;
regUse |= interferingRegs;
if (!VarSetOps::IsEmpty(this, compCurLife))
{
// Add interference between the current set of live variables and
// the set of temporary registers need to evaluate the sub tree
if (regUse)
{
rpRecordRegIntf(regUse, compCurLife DEBUGARG( "tmp use"));
}
}
if (rpAsgVarNum != -1)
{
// Add interference between the registers used (if any)
// and the assignment target variable
if (regUse)
{
rpRecordRegIntf(regUse, VarSetOps::MakeSingleton(this, rpAsgVarNum)
DEBUGARG("tgt var tmp use"));
}
// Add a variable interference from rpAsgVarNum (i.e. the enregistered left hand
// side of the assignment passed here using PREDICT_REG_VAR_Txx)
// to the set of currently live variables. This new interference will prevent us
// from using the register value used here for enregistering different live variable
//
if (!VarSetOps::IsEmpty(this, compCurLife))
{
rpRecordVarIntf(rpAsgVarNum, compCurLife
DEBUGARG( "asg tgt live conflict"));
}
}
/* Do we need to resore the oldLastUseVars value */
if (restoreLastUseVars)
{
/* If we used a GT_ASG targeted register then we need to add
* a variable interference between any new last use variables
* and the GT_ASG targeted register
*/
if (!VarSetOps::Equal(this, rpLastUseVars, oldLastUseVars) && rpAsgVarNum != -1)
{
rpRecordVarIntf(rpAsgVarNum,
VarSetOps::Diff(this, rpLastUseVars, oldLastUseVars)
DEBUGARG( "asgn tgt last use conflict"));
}
VarSetOps::Assign(this, rpLastUseVars, oldLastUseVars);
}
return regMask;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
#endif // LEGACY_BACKEND
/****************************************************************************/
/* Returns true when we must create an EBP frame
This is used to force most managed methods to have EBP based frames
which allows the ETW kernel stackwalker to walk the stacks of managed code
this allows the kernel to perform light weight profiling
*/
bool Compiler::rpMustCreateEBPFrame(INDEBUG( const char ** wbReason))
{
bool result = false;
#ifdef DEBUG
const char * reason = NULL;
#endif
#if ETW_EBP_FRAMED
if (!result && (opts.MinOpts() || opts.compDbgCode))
{
INDEBUG(reason = "Debug Code");
result = true;
}
if (!result && (info.compMethodInfo->ILCodeSize > DEFAULT_MAX_INLINE_SIZE))
{
INDEBUG(reason = "IL Code Size");
result = true;
}
if (!result && (fgBBcount > 3))
{
INDEBUG(reason = "BasicBlock Count");
result = true;
}
if (!result && fgHasLoops)
{
INDEBUG(reason = "Method has Loops");
result = true;
}
if (!result && (optCallCount >= 2))
{
INDEBUG(reason = "Call Count");
result = true;
}
if (!result && (optIndirectCallCount >= 1))
{
INDEBUG(reason = "Indirect Call");
result = true;
}
#endif // ETW_EBP_FRAMED
// VM wants to identify the containing frame of an InlinedCallFrame always
// via the frame register never the stack register so we need a frame.
if (!result && (optNativeCallCount != 0))
{
INDEBUG(reason = "Uses PInvoke");
result = true;
}
#ifdef _TARGET_ARM64_
// TODO-ARM64-NYI: This is temporary: force a frame pointer-based frame until genFnProlog can handle non-frame pointer frames.
if (!result)
{
INDEBUG(reason = "Temporary ARM64 force frame pointer");
result = true;
}
#endif // _TARGET_ARM64_
#ifdef DEBUG
if ((result == true) && (wbReason != NULL))
{
*wbReason = reason;
}
#endif
return result;
}
#ifdef LEGACY_BACKEND // We don't use any of the old register allocator functions when LSRA is used instead.
/*****************************************************************************
*
* Predict which variables will be assigned to registers
* This is x86 specific and only predicts the integer registers and
* must be conservative, any register that is predicted to be enregister
* must end up being enregistered.
*
* The rpPredictTreeRegUse takes advantage of the LCL_VARS that are
* predicted to be enregistered to minimize calls to rpPredictRegPick.
*
*/
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
regMaskTP Compiler::rpPredictAssignRegVars(regMaskTP regAvail)
{
unsigned regInx;
if (rpPasses <= rpPassesPessimize)
{
// Assume that we won't have to reverse EBP enregistration
rpReverseEBPenreg = false;
// Set the default rpFrameType based upon codeGen->isFramePointerRequired()
if (codeGen->isFramePointerRequired() || codeGen->isFrameRequired())
rpFrameType = FT_EBP_FRAME;
else
rpFrameType = FT_ESP_FRAME;
}
#if !ETW_EBP_FRAMED
// If we are using FPBASE as the frame register, we cannot also use it for
// a local var
if (rpFrameType == FT_EBP_FRAME)
{
regAvail &= ~RBM_FPBASE;
}
#endif // !ETW_EBP_FRAMED
rpStkPredict = 0;
rpPredictAssignMask = regAvail;
raSetupArgMasks(&codeGen->intRegState);
#if !FEATURE_STACK_FP_X87
raSetupArgMasks(&codeGen->floatRegState);
#endif
// If there is a secret stub param, it is also live in
if (info.compPublishStubParam)
{
codeGen->intRegState.rsCalleeRegArgMaskLiveIn |= RBM_SECRET_STUB_PARAM;
}
if (regAvail == RBM_NONE)
{
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++, varDsc++)
{
#if FEATURE_STACK_FP_X87
if (!varDsc->IsFloatRegType())
#endif
{
varDsc->lvRegNum = REG_STK;
if (isRegPairType(varDsc->lvType))
varDsc->lvOtherReg = REG_STK;
}
}
}
#ifdef DEBUG
if (verbose)
{
printf("\nCompiler::rpPredictAssignRegVars pass #%d", rpPasses);
printf("\n Available registers = ");
dspRegMask(regAvail); printf("\n");
}
#endif
if (regAvail == RBM_NONE)
{
return RBM_NONE;
}
/* We cannot change the lvVarIndexes at this point, so we */
/* can only re-order the existing set of tracked variables */
/* Which will change the order in which we select the */
/* locals for enregistering. */
assert(lvaTrackedFixed); // We should have already set this to prevent us from adding any new tracked variables.
// Should not be set unless optimizing
noway_assert((lvaSortAgain == false) || (opts.MinOpts() == false));
if (lvaSortAgain)
lvaSortOnly();
#ifdef DEBUG
fgDebugCheckBBlist();
#endif
/* Initialize the weighted count of variables that could have */
/* been enregistered but weren't */
unsigned refCntStk = 0; // sum of ref counts for all stack based variables
unsigned refCntEBP = 0; // sum of ref counts for EBP enregistered variables
unsigned refCntWtdEBP = 0; // sum of wtd ref counts for EBP enregistered variables
#if DOUBLE_ALIGN
unsigned refCntStkParam ; // sum of ref counts for all stack based parameters
unsigned refCntWtdStkDbl ; // sum of wtd ref counts for stack based doubles
#if FEATURE_STACK_FP_X87
refCntStkParam = raCntStkParamDblStackFP;
refCntWtdStkDbl = raCntWtdStkDblStackFP;
refCntStk = raCntStkStackFP;
#else
refCntStkParam = 0;
refCntWtdStkDbl = 0;
refCntStk = 0;
#endif // FEATURE_STACK_FP_X87
#endif // DOUBLE_ALIGN
/* Set of registers used to enregister variables in the predition */
regMaskTP regUsed = RBM_NONE;
/*-------------------------------------------------------------------------
*
* Predict/Assign the enregistered locals in ref-count order
*
*/
VARSET_TP VARSET_INIT_NOCOPY(unprocessedVars, VarSetOps::MakeFull(this));
unsigned FPRegVarLiveInCnt;
FPRegVarLiveInCnt = 0; // How many enregistered doubles are live on entry to the method
LclVarDsc * varDsc;
for (unsigned sortNum = 0; sortNum < lvaCount; sortNum++)
{
bool notWorthy = false;
unsigned varIndex;
bool isDouble;
regMaskTP regAvailForType;
var_types regType;
regMaskTP avoidReg;
unsigned customVarOrderSize;
regNumber customVarOrder[MAX_VAR_ORDER_SIZE];
bool firstHalf;
regNumber saveOtherReg;
varDsc = lvaRefSorted[sortNum];
#if FEATURE_STACK_FP_X87
if (varTypeIsFloating(varDsc->TypeGet()))
{
#ifdef DEBUG
if (lvaIsFieldOfDependentlyPromotedStruct(varDsc))
{
// Field local of a PROMOTION_TYPE_DEPENDENT struct should not
// be en-registered.
noway_assert(!varDsc->lvRegister);
}
#endif
continue;
}
#endif
/* Check the set of invariant things that would prevent enregistration */
/* Ignore the variable if it's not tracked */
if (!varDsc->lvTracked)
goto CANT_REG;
/* Get hold of the index and the interference mask for the variable */
varIndex = varDsc->lvVarIndex;
// Remove 'varIndex' from unprocessedVars
VarSetOps::RemoveElemD(this, unprocessedVars, varIndex);
// Skip the variable if it's marked as DoNotEnregister.
if (varDsc->lvDoNotEnregister)
goto CANT_REG;
/* TODO: For now if we have JMP all register args go to stack
* TODO: Later consider extending the life of the argument or make a copy of it */
if (compJmpOpUsed && varDsc->lvIsRegArg)
goto CANT_REG;
/* Skip the variable if the ref count is zero */
if (varDsc->lvRefCnt == 0)
goto CANT_REG;
/* Ignore field of PROMOTION_TYPE_DEPENDENT type of promoted struct */
if (lvaIsFieldOfDependentlyPromotedStruct(varDsc))
{
goto CANT_REG;
}
/* Is the unweighted ref count too low to be interesting? */
if (!varDsc->lvIsStructField && // We do encourage enregistering field locals.
(varDsc->lvRefCnt <= 1))
{
/* Sometimes it's useful to enregister a variable with only one use */
/* arguments referenced in loops are one example */
if (varDsc->lvIsParam && varDsc->lvRefCntWtd > BB_UNITY_WEIGHT)
goto OK_TO_ENREGISTER;
/* If the variable has a preferred register set it may be useful to put it there */
if (varDsc->lvPrefReg && varDsc->lvIsRegArg)
goto OK_TO_ENREGISTER;
/* Keep going; the table is sorted by "weighted" ref count */
goto CANT_REG;
}
OK_TO_ENREGISTER:
if (varTypeIsFloating(varDsc->TypeGet()))
{
regType = varDsc->TypeGet();
regAvailForType = regAvail & RBM_ALLFLOAT;
}
else
{
regType = TYP_INT;
regAvailForType = regAvail & RBM_ALLINT;
}
#ifdef _TARGET_ARM_
isDouble = (varDsc->TypeGet() == TYP_DOUBLE);
if (isDouble)
{
regAvailForType &= RBM_DBL_REGS; // We must restrict the set to the double registers
}
#endif
/* If we don't have any registers available then skip the enregistration attempt */
if (regAvailForType == RBM_NONE)
goto NO_REG;
// On the pessimize passes don't even try to enregister LONGS
if (isRegPairType(varDsc->lvType))
{
if (rpPasses > rpPassesPessimize)
goto NO_REG;
else if (rpLostEnreg && (rpPasses == rpPassesPessimize))
goto NO_REG;
}
// Set of registers to avoid when performing register allocation
avoidReg = RBM_NONE;
if (!varDsc->lvIsRegArg)
{
/* For local variables,
* avoid the incoming arguments,
* but only if you conflict with them */
if (raAvoidArgRegMask != 0)
{
LclVarDsc * argDsc;
LclVarDsc * argsEnd = lvaTable + info.compArgsCount;
for (argDsc = lvaTable; argDsc < argsEnd; argDsc++)
{
if (!argDsc->lvIsRegArg)
continue;
bool isFloat = argDsc->IsFloatRegType();
regNumber inArgReg = argDsc->lvArgReg;
regMaskTP inArgBit = genRegMask(inArgReg);
// Is this inArgReg in the raAvoidArgRegMask set?
if (!(raAvoidArgRegMask & inArgBit))
continue;
noway_assert(argDsc->lvIsParam);
noway_assert(inArgBit & (isFloat ? RBM_FLTARG_REGS : RBM_ARG_REGS));
unsigned locVarIndex = varDsc->lvVarIndex;
unsigned argVarIndex = argDsc->lvVarIndex;
/* Does this variable interfere with the arg variable ? */
if (VarSetOps::IsMember(this, lvaVarIntf[locVarIndex], argVarIndex))
{
noway_assert(VarSetOps::IsMember(this, lvaVarIntf[argVarIndex], locVarIndex));
/* Yes, so try to avoid the incoming arg reg */
avoidReg |= inArgBit;
}
else
{
noway_assert(!VarSetOps::IsMember(this, lvaVarIntf[argVarIndex], locVarIndex));
}
}
}
}
// Now we will try to predict which register the variable
// could be enregistered in
customVarOrderSize = MAX_VAR_ORDER_SIZE;
raSetRegVarOrder(regType, customVarOrder, &customVarOrderSize, varDsc->lvPrefReg, avoidReg);
firstHalf = false;
saveOtherReg = DUMMY_INIT(REG_NA);
for (regInx = 0;
regInx < customVarOrderSize;
regInx++)
{
regNumber regNum = customVarOrder[regInx];
regMaskTP regBits = genRegMask(regNum);
/* Skip this register if it isn't available */
if ((regAvailForType & regBits) == 0)
continue;
/* Skip this register if it interferes with the variable */
if (VarSetOps::IsMember(this, raLclRegIntf[regNum], varIndex))
continue;
if (varTypeIsFloating(regType))
{
#ifdef _TARGET_ARM_
if (isDouble)
{
regNumber regNext = REG_NEXT(regNum);
regBits |= genRegMask(regNext);
/* Skip if regNext interferes with the variable */
if (VarSetOps::IsMember(this, raLclRegIntf[regNext], varIndex))
continue;
}
#endif
}
bool firstUseOfReg = ((regBits & (regUsed | codeGen->regSet.rsGetModifiedRegsMask())) == 0);
bool lessThanTwoRefWtd = (varDsc->lvRefCntWtd < (2 * BB_UNITY_WEIGHT));
bool calleeSavedReg = ((regBits & RBM_CALLEE_SAVED) != 0);
/* Skip this register if the weighted ref count is less than two
and we are considering a unused callee saved register */
if (lessThanTwoRefWtd && // less than two references (weighted)
firstUseOfReg && // first use of this register
calleeSavedReg) // callee saved register
{
unsigned int totalRefCntWtd = varDsc->lvRefCntWtd;
// psc is abbeviation for possibleSameColor
VARSET_TP VARSET_INIT_NOCOPY(pscVarSet, VarSetOps::Diff(this, unprocessedVars,
lvaVarIntf[varIndex]));
VARSET_ITER_INIT(this, pscIndexIter, pscVarSet, pscIndex);
while (pscIndexIter.NextElem(this, &pscIndex))
{
LclVarDsc * pscVar = lvaTable + lvaTrackedToVarNum[pscIndex];
totalRefCntWtd += pscVar->lvRefCntWtd;
if (totalRefCntWtd > (2 * BB_UNITY_WEIGHT))
break;
}
if (totalRefCntWtd <= (2 * BB_UNITY_WEIGHT))
{
notWorthy = true;
continue; // not worth spilling a callee saved register
}
// otherwise we will spill this callee saved registers,
// because its uses when combined with the uses of
// other yet to be processed candidates exceed our threshold.
// totalRefCntWtd = totalRefCntWtd;
}
/* Looks good - mark the variable as living in the register */
if (isRegPairType(varDsc->lvType))
{
if (firstHalf == false)
{
/* Enregister the first half of the long */
varDsc->lvRegNum = regNum;
saveOtherReg = varDsc->lvOtherReg;
varDsc->lvOtherReg = REG_STK;
firstHalf = true;
}
else
{
/* Ensure 'well-formed' register pairs */
/* (those returned by gen[Pick|Grab]RegPair) */
if (regNum < varDsc->lvRegNum)
{
varDsc->lvOtherReg = varDsc->lvRegNum;
varDsc->lvRegNum = regNum;
}
else
{
varDsc->lvOtherReg = regNum;
}
firstHalf = false;
}
}
else
{
varDsc->lvRegNum = regNum;
#ifdef _TARGET_ARM_
if (isDouble)
{
varDsc->lvOtherReg = REG_NEXT(regNum);
}
#endif
}
if (regNum == REG_FPBASE)
{
refCntEBP += varDsc->lvRefCnt;
refCntWtdEBP += varDsc->lvRefCntWtd;
#if DOUBLE_ALIGN
if (varDsc->lvIsParam)
{
refCntStkParam += varDsc->lvRefCnt;
}
#endif
}
/* Record this register in the regUsed set */
regUsed |= regBits;
/* The register is now ineligible for all interfering variables */
VarSetOps::UnionD(this, raLclRegIntf[regNum], lvaVarIntf[varIndex]);
#ifdef _TARGET_ARM_
if (isDouble)
{
regNumber secondHalf = REG_NEXT(regNum);
VARSET_ITER_INIT(this, iter, lvaVarIntf[varIndex], intfIndex);
while (iter.NextElem(this, &intfIndex))
{
VarSetOps::AddElemD(this, raLclRegIntf[secondHalf], intfIndex);
}
}
#endif
/* If a register argument, remove its incoming register
* from the "avoid" list */
if (varDsc->lvIsRegArg)
{
raAvoidArgRegMask &= ~genRegMask(varDsc->lvArgReg);
#ifdef _TARGET_ARM_
if (isDouble)
{
raAvoidArgRegMask &= ~genRegMask(REG_NEXT(varDsc->lvArgReg));
}
#endif
}
/* A variable of TYP_LONG can take two registers */
if (firstHalf)
continue;
// Since we have successfully enregistered this variable it is
// now time to move on and consider the next variable
goto ENREG_VAR;
}
if (firstHalf)
{
noway_assert(isRegPairType(varDsc->lvType));
/* This TYP_LONG is partially enregistered */
noway_assert(saveOtherReg != DUMMY_INIT(REG_NA));
if (varDsc->lvDependReg && (saveOtherReg != REG_STK))
{
rpLostEnreg = true;
}
raAddToStkPredict(varDsc->lvRefCntWtd);
goto ENREG_VAR;
}
NO_REG:;
if (varDsc->lvDependReg)
{
rpLostEnreg = true;
}
if (!notWorthy)
{
/* Weighted count of variables that could have been enregistered but weren't */
raAddToStkPredict(varDsc->lvRefCntWtd);
if (isRegPairType(varDsc->lvType) && (varDsc->lvOtherReg == REG_STK))
raAddToStkPredict(varDsc->lvRefCntWtd);
}
CANT_REG:;
varDsc->lvRegister = false;
varDsc->lvRegNum = REG_STK;
if (isRegPairType(varDsc->lvType))
varDsc->lvOtherReg = REG_STK;
/* unweighted count of variables that were not enregistered */
refCntStk += varDsc->lvRefCnt;
#if DOUBLE_ALIGN
if (varDsc->lvIsParam)
{
refCntStkParam += varDsc->lvRefCnt;
}
else
{
/* Is it a stack based double? */
/* Note that double params are excluded since they can not be double aligned */
if (varDsc->lvType == TYP_DOUBLE)
{
refCntWtdStkDbl += varDsc->lvRefCntWtd;
}
}
#endif
#ifdef DEBUG
if (verbose)
{
printf("; ");
gtDispLclVar((unsigned)(varDsc - lvaTable));
if (varDsc->lvTracked)
printf("T%02u", varDsc->lvVarIndex);
else
printf(" ");
printf(" (refcnt=%2u,refwtd=%s) not enregistered",
varDsc->lvRefCnt,
refCntWtd2str(varDsc->lvRefCntWtd));
if (varDsc->lvDoNotEnregister)
printf(", do-not-enregister");
printf("\n");
}
#endif
continue;
ENREG_VAR:;
varDsc->lvRegister = true;
// Record the fact that we enregistered a stack arg when tail call is used.
if (compJmpOpUsed && !varDsc->lvIsRegArg)
{
rpMaskPInvokeEpilogIntf |= genRegMask(varDsc->lvRegNum);
if (isRegPairType(varDsc->lvType))
{
rpMaskPInvokeEpilogIntf |= genRegMask(varDsc->lvOtherReg);
}
}
#ifdef DEBUG
if (verbose)
{
printf("; ");
gtDispLclVar((unsigned)(varDsc - lvaTable));
printf("T%02u (refcnt=%2u,refwtd=%s) predicted to be assigned to ",
varIndex, varDsc->lvRefCnt,
refCntWtd2str(varDsc->lvRefCntWtd));
varDsc->PrintVarReg();
#ifdef _TARGET_ARM_
if (isDouble)
{
printf(":%s", getRegName(varDsc->lvOtherReg));
}
#endif
printf("\n");
}
#endif
}
#if ETW_EBP_FRAMED
noway_assert(refCntEBP == 0);
#endif
/* Determine how the EBP register should be used */
#ifdef DEBUG
if (verbose)
{
if (refCntStk > 0)
printf("; refCntStk = %u\n", refCntStk);
if (refCntEBP > 0)
printf("; refCntEBP = %u\n", refCntEBP);
if (refCntWtdEBP > 0)
printf("; refCntWtdEBP = %u\n", refCntWtdEBP);
#if DOUBLE_ALIGN
if (refCntStkParam > 0)
printf("; refCntStkParam = %u\n", refCntStkParam);
if (refCntWtdStkDbl > 0)
printf("; refCntWtdStkDbl = %u\n", refCntWtdStkDbl);
#endif
}
#endif
#if DOUBLE_ALIGN
if (!codeGen->isFramePointerRequired())
{
noway_assert(getCanDoubleAlign() < COUNT_DOUBLE_ALIGN);
/*
First let us decide if we should use EBP to create a
double-aligned frame, instead of enregistering variables
*/
if (getCanDoubleAlign() == MUST_DOUBLE_ALIGN)
{
rpFrameType = FT_DOUBLE_ALIGN_FRAME;
goto REVERSE_EBP_ENREG;
}
if (getCanDoubleAlign() == CAN_DOUBLE_ALIGN && (refCntWtdStkDbl > 0))
{
/* OK, there may be some benefit to double-aligning the frame */
/* But let us compare the benefits vs. the costs of this */
/*
One cost to consider is the benefit of smaller code
when using EBP as a frame pointer register
Each stack variable reference is an extra byte of code
if we use a double-aligned frame, parameters are
accessed via EBP for a double-aligned frame so they
don't use an extra byte of code.
We pay one byte of code for each refCntStk and we pay
one byte or more for each refCntEBP but we save one
byte for each refCntStkParam.
Our savings are the elimination of a possible misaligned
access and a possible DCU spilt when an access crossed
a cache-line boundry.
We use the loop weighted value of
refCntWtdStkDbl * misaligned_weight (0, 4, 16)
to represent this savings.
*/
// We also pay 7 extra bytes for the MOV EBP,ESP,
// LEA ESP,[EBP-0x10] and the AND ESP,-8 to double align ESP
const unsigned DBL_ALIGN_SETUP_SIZE = 7;
unsigned bytesUsed = refCntStk + refCntEBP - refCntStkParam + DBL_ALIGN_SETUP_SIZE;
unsigned misaligned_weight = 4;
if (compCodeOpt() == SMALL_CODE)
misaligned_weight = 0;
if (compCodeOpt() == FAST_CODE)
misaligned_weight *= 4;
#ifdef DEBUG
if (verbose)
{
printf("; Double alignment:\n");
printf("; Bytes that could be save by not using EBP frame: %i\n", bytesUsed);
printf("; Sum of weighted ref counts for EBP enregistered variables: %i\n", refCntWtdEBP);
printf("; Sum of weighted ref counts for weighted stack based doubles: %i\n", refCntWtdStkDbl);
}
#endif
if (bytesUsed > ((refCntWtdStkDbl * misaligned_weight) / BB_UNITY_WEIGHT))
{
/* It's probably better to use EBP as a frame pointer */
#ifdef DEBUG
if (verbose)
printf("; Predicting not to double-align ESP to save %d bytes of code.\n", bytesUsed);
#endif
goto NO_DOUBLE_ALIGN;
}
/*
Another cost to consider is the benefit of using EBP to enregister
one or more integer variables
We pay one extra memory reference for each refCntWtdEBP
Our savings are the elimination of a possible misaligned
access and a possible DCU spilt when an access crossed
a cache-line boundry.
*/
// <BUGNUM>
// VSW 346717: On P4 2 Proc XEON's, SciMark.FFT degrades if SciMark.FFT.transform_internal is
// not double aligned.
// Here are the numbers that make this not double-aligned.
// refCntWtdStkDbl = 0x164
// refCntWtdEBP = 0x1a4
// We think we do need to change the heuristic to be in favor of double-align.
// </BUGNUM>
if (refCntWtdEBP > refCntWtdStkDbl * 2)
{
/* It's probably better to use EBP to enregister integer variables */
#ifdef DEBUG
if (verbose)
printf("; Predicting not to double-align ESP to allow EBP to be used to enregister variables\n");
#endif
goto NO_DOUBLE_ALIGN;
}
/*
OK we passed all of the benefit tests
so we'll predict a double aligned frame
*/
#ifdef DEBUG
if (verbose)
printf("; Predicting to create a double-aligned frame\n");
#endif
rpFrameType = FT_DOUBLE_ALIGN_FRAME;
goto REVERSE_EBP_ENREG;
}
}
NO_DOUBLE_ALIGN:
#endif // DOUBLE_ALIGN
if (!codeGen->isFramePointerRequired() && !codeGen->isFrameRequired())
{
#ifdef _TARGET_XARCH_
/* If we are using EBP to enregister variables then
will we actually save bytes by setting up an EBP frame?
Each stack reference is an extra byte of code if we use
an ESP frame.
Here we measure the savings that we get by using EBP to
enregister variables vs. the cost in code size that we
pay when using an ESP based frame.
We pay one byte of code for each refCntStk
but we save one byte (or more) for each refCntEBP.
Our savings are the elimination of a stack memory read/write.
We use the loop weighted value of
refCntWtdEBP * mem_access_weight (0, 3, 6)
to represent this savings.
*/
// We also pay 5 extra bytes for the MOV EBP,ESP and LEA ESP,[EBP-0x10]
// to set up an EBP frame in the prolog and epilog
#define EBP_FRAME_SETUP_SIZE 5
if (refCntStk > (refCntEBP + EBP_FRAME_SETUP_SIZE))
{
unsigned bytesSaved = refCntStk - (refCntEBP + EBP_FRAME_SETUP_SIZE);
unsigned mem_access_weight = 3;
if (compCodeOpt() == SMALL_CODE)
mem_access_weight = 0;
else if (compCodeOpt() == FAST_CODE)
mem_access_weight *= 2;
if (bytesSaved > ((refCntWtdEBP * mem_access_weight) / BB_UNITY_WEIGHT))
{
/* It's not be a good idea to use EBP in our predictions */
#ifdef DEBUG
if (verbose && (refCntEBP > 0))
printf("; Predicting that it's not worth using EBP to enregister variables\n");
#endif
rpFrameType = FT_EBP_FRAME;
goto REVERSE_EBP_ENREG;
}
}
#endif // _TARGET_XARCH_
if ((rpFrameType == FT_NOT_SET) || (rpFrameType == FT_ESP_FRAME))
{
#ifdef DEBUG
const char * reason;
#endif
if (rpMustCreateEBPCalled == false)
{
rpMustCreateEBPCalled = true;
if (rpMustCreateEBPFrame(INDEBUG(&reason)))
{
#ifdef DEBUG
if (verbose)
printf("; Decided to create an EBP based frame for ETW stackwalking (%s)\n", reason);
#endif
codeGen->setFrameRequired(true);
rpFrameType = FT_EBP_FRAME;
goto REVERSE_EBP_ENREG;
}
}
}
}
goto EXIT;
REVERSE_EBP_ENREG:
noway_assert(rpFrameType != FT_ESP_FRAME);
rpReverseEBPenreg = true;
#if !ETW_EBP_FRAMED
if (refCntEBP > 0)
{
noway_assert(regUsed & RBM_FPBASE);
regUsed &= ~RBM_FPBASE;
/* variables that were enregistered in EBP become stack based variables */
raAddToStkPredict(refCntWtdEBP);
unsigned lclNum;
/* We're going to have to undo some predicted enregistered variables */
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
/* Is this a register variable? */
if (varDsc->lvRegNum != REG_STK)
{
if (isRegPairType(varDsc->lvType))
{
/* Only one can be EBP */
if (varDsc->lvRegNum == REG_FPBASE ||
varDsc->lvOtherReg == REG_FPBASE)
{
if (varDsc->lvRegNum == REG_FPBASE)
varDsc->lvRegNum = varDsc->lvOtherReg;
varDsc->lvOtherReg = REG_STK;
if (varDsc->lvRegNum == REG_STK)
varDsc->lvRegister = false;
if (varDsc->lvDependReg)
rpLostEnreg = true;
#ifdef DEBUG
if (verbose)
goto DUMP_MSG;
#endif
}
}
else
{
if ((varDsc->lvRegNum == REG_FPBASE) && (!varDsc->IsFloatRegType()))
{
varDsc->lvRegNum = REG_STK;
varDsc->lvRegister = false;
if (varDsc->lvDependReg)
rpLostEnreg = true;
#ifdef DEBUG
if (verbose)
{
DUMP_MSG:
printf("; reversing enregisteration of V%02u,T%02u (refcnt=%2u,refwtd=%4u%s)\n",
lclNum, varDsc->lvVarIndex, varDsc->lvRefCnt,
varDsc->lvRefCntWtd/2, (varDsc->lvRefCntWtd & 1) ? ".5" : "");
}
#endif
}
}
}
}
}
#endif // ETW_EBP_FRAMED
EXIT:;
unsigned lclNum;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++, varDsc++)
{
/* Clear the lvDependReg flag for next iteration of the predictor */
varDsc->lvDependReg = false;
// If we set rpLostEnreg and this is the first pessimize pass
// then reverse the enreg of all TYP_LONG
if (rpLostEnreg &&
isRegPairType(varDsc->lvType) &&
(rpPasses == rpPassesPessimize))
{
varDsc->lvRegNum = REG_STK;
varDsc->lvOtherReg = REG_STK;
}
}
#ifdef DEBUG
if (verbose && raNewBlocks)
{
printf("\nAdded FP register killing blocks:\n");
fgDispBasicBlocks();
printf("\n");
}
#endif
noway_assert(rpFrameType != FT_NOT_SET);
/* return the set of registers used to enregister variables */
return regUsed;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
/*****************************************************************************
*
* Predict register use for every tree in the function. Note that we do this
* at different times (not to mention in a totally different way) for x86 vs
* RISC targets.
*/
void Compiler::rpPredictRegUse()
{
#ifdef DEBUG
if (verbose)
raDumpVarIntf();
#endif
// We might want to adjust the ref counts based on interference
raAdjustVarIntf();
regMaskTP allAcceptableRegs = RBM_ALLINT;
#if FEATURE_FP_REGALLOC
allAcceptableRegs |= raConfigRestrictMaskFP();
#endif
allAcceptableRegs &= ~codeGen->regSet.rsMaskResvd; // Remove any register reserved for special purposes
/* For debuggable code, genJumpToThrowHlpBlk() generates an inline call
to acdHelper(). This is done implicitly, without creating a GT_CALL
node. Hence, this interference is be handled implicitly by
restricting the registers used for enregistering variables */
if (opts.compDbgCode)
{
allAcceptableRegs &= RBM_CALLEE_SAVED;
}
/* Compute the initial regmask to use for the first pass */
regMaskTP regAvail = RBM_CALLEE_SAVED & allAcceptableRegs;
regMaskTP regUsed;
#if CPU_USES_BLOCK_MOVE
/* If we might need to generate a rep mov instruction */
/* remove ESI and EDI */
if (compBlkOpUsed)
regAvail &= ~(RBM_ESI | RBM_EDI);
#endif
#ifdef _TARGET_X86_
/* If we using longs then we remove ESI to allow */
/* ESI:EBX to be saved accross a call */
if (compLongUsed)
regAvail &= ~(RBM_ESI);
#endif
#ifdef _TARGET_ARM_
// For the first register allocation pass we don't want to color using r4
// as we want to allow it to be used to color the internal temps instead
// when r0,r1,r2,r3 are all in use.
//
regAvail &= ~(RBM_R4);
#endif
#if ETW_EBP_FRAMED
// We never have EBP available when ETW_EBP_FRAME is defined
regAvail &= ~RBM_FPBASE;
#else
/* If a frame pointer is required then we remove EBP */
if (codeGen->isFramePointerRequired() || codeGen->isFrameRequired())
regAvail &= ~RBM_FPBASE;
#endif
#ifdef DEBUG
static ConfigDWORD jitNoRegLoc;
BOOL fJitNoRegLoc = jitNoRegLoc.val(CLRConfig::INTERNAL_JitNoRegLoc);
if (fJitNoRegLoc)
regAvail = RBM_NONE;
#endif
if ((opts.compFlags & CLFLG_REGVAR) == 0)
regAvail = RBM_NONE;
#if FEATURE_STACK_FP_X87
VarSetOps::AssignNoCopy(this, optAllNonFPvars, VarSetOps::MakeEmpty(this));
VarSetOps::AssignNoCopy(this, optAllFloatVars, VarSetOps::MakeEmpty(this));
// Calculate the set of all tracked FP/non-FP variables
// into optAllFloatVars and optAllNonFPvars
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
/* Ignore the variable if it's not tracked */
if (!varDsc->lvTracked)
continue;
/* Get hold of the index and the interference mask for the variable */
unsigned varNum = varDsc->lvVarIndex;
/* add to the set of all tracked FP/non-FP variables */
if (varDsc->IsFloatRegType())
VarSetOps::AddElemD(this, optAllFloatVars, varNum);
else
VarSetOps::AddElemD(this, optAllNonFPvars, varNum);
}
#endif
for (unsigned i = 0; i < REG_COUNT; i++)
{
VarSetOps::AssignNoCopy(this, raLclRegIntf[i], VarSetOps::MakeEmpty(this));
}
for (unsigned i = 0; i < lvaTrackedCount; i++)
{
VarSetOps::AssignNoCopy(this, lvaVarPref[i], VarSetOps::MakeEmpty(this));
}
raNewBlocks = false;
rpPredictAssignAgain = false;
rpPasses = 0;
bool mustPredict = true;
unsigned stmtNum = 0;
unsigned oldStkPredict = DUMMY_INIT(~0);
VARSET_TP oldLclRegIntf[REG_COUNT];
for (unsigned i = 0; i < REG_COUNT; i++)
{
VarSetOps::AssignNoCopy(this, oldLclRegIntf[i], VarSetOps::MakeEmpty(this));
}
while (true)
{
/* Assign registers to variables using the variable/register interference
graph (raLclRegIntf[]) calculated in the previous pass */
regUsed = rpPredictAssignRegVars(regAvail);
mustPredict |= rpLostEnreg;
#ifdef _TARGET_ARM_
// See if we previously reserved REG_R10 and try to make it available if we have a small frame now
//
if ((rpPasses == 0) && (codeGen->regSet.rsMaskResvd & RBM_OPT_RSVD))
{
if (compRsvdRegCheck(REGALLOC_FRAME_LAYOUT))
{
// We must keep reserving R10 in this case
codeGen->regSet.rsMaskResvd |= RBM_OPT_RSVD;
}
else
{
// We can release our reservation on R10 and use it to color registers
//
codeGen->regSet.rsMaskResvd &= ~RBM_OPT_RSVD;
allAcceptableRegs |= RBM_OPT_RSVD;
}
}
#endif
/* Is our new prediction good enough?? */
if (!mustPredict)
{
/* For small methods (less than 12 stmts), we add a */
/* extra pass if we are predicting the use of some */
/* of the caller saved registers. */
/* This fixes RAID perf bug 43440 VB Ackerman function */
if ((rpPasses == 1) && (stmtNum <= 12) &&
(regUsed & RBM_CALLEE_SAVED))
{
goto EXTRA_PASS;
}
/* If every variable was fully enregistered then we're done */
if (rpStkPredict == 0)
goto ALL_DONE;
// This was a successful prediction. Record it, in case it turns out to be the best one.
rpRecordPrediction();
if (rpPasses > 1)
{
noway_assert(oldStkPredict != (unsigned)DUMMY_INIT(~0));
// Be careful about overflow
unsigned highStkPredict = (rpStkPredict*2 < rpStkPredict) ? ULONG_MAX : rpStkPredict*2;
if (oldStkPredict < highStkPredict)
goto ALL_DONE;
if (rpStkPredict < rpPasses * 8)
goto ALL_DONE;
if (rpPasses >= (rpPassesMax-1))
goto ALL_DONE;
}
EXTRA_PASS:
/* We will do another pass */ ;
}
#ifdef DEBUG
static ConfigDWORD fJitMaxRegAllocPasses;
if (fJitMaxRegAllocPasses.val(CLRConfig::INTERNAL_JitAssertOnMaxRAPasses))
{
noway_assert(rpPasses < rpPassesMax &&
"This may not a bug, but dev team should look and see what is happening");
}
#endif
// The "64" here had been "VARSET_SZ". It is unclear why this number is connected with
// the (max) size of a VARSET. We've eliminated this constant, so I left this as a constant. We hope
// that we're phasing out this code, anyway, and this leaves the behavior the way that it was.
if (rpPasses > (rpPassesMax - rpPassesPessimize) + 64)
{
NO_WAY("we seem to be stuck in an infinite loop. breaking out");
}
#ifdef DEBUG
if (verbose)
{
if (rpPasses > 0)
{
if (rpLostEnreg)
printf("\n; Another pass due to rpLostEnreg");
if (rpAddedVarIntf)
printf("\n; Another pass due to rpAddedVarIntf");
if ((rpPasses == 1) && rpPredictAssignAgain)
printf("\n; Another pass due to rpPredictAssignAgain");
}
printf("\n; Register predicting pass# %d\n", rpPasses+1);
}
#endif
/* Zero the variable/register interference graph */
for (unsigned i = 0; i < REG_COUNT; i++)
{
VarSetOps::ClearD(this, raLclRegIntf[i]);
}
// if there are PInvoke calls and compLvFrameListRoot is enregistered,
// it must not be in a register trashed by the callee
if (info.compCallUnmanaged != 0)
{
LclVarDsc * pinvokeVarDsc = &lvaTable[info.compLvFrameListRoot];
if (pinvokeVarDsc->lvTracked)
{
rpRecordRegIntf(RBM_CALLEE_TRASH, VarSetOps::MakeSingleton(this, pinvokeVarDsc->lvVarIndex)
DEBUGARG("compLvFrameListRoot"));
// We would prefer to have this be enregister in the PINVOKE_TCB register
pinvokeVarDsc->addPrefReg(RBM_PINVOKE_TCB, this);
}
//If we're using a single return block, the p/invoke epilog code trashes ESI and EDI (in the
//worst case). Make sure that the return value compiler temp that we create for the single
//return block knows about this interference.
if (genReturnLocal != BAD_VAR_NUM)
{
noway_assert(genReturnBB);
LclVarDsc * localTmp = &lvaTable[genReturnLocal];
if (localTmp->lvTracked)
{
rpRecordRegIntf(RBM_PINVOKE_TCB | RBM_PINVOKE_FRAME, VarSetOps::MakeSingleton(this, localTmp->lvVarIndex)
DEBUGARG( "genReturnLocal"));
}
}
}
#ifdef _TARGET_ARM_
if (compFloatingPointUsed)
{
bool hasMustInitFloat = false;
// if we have any must-init floating point LclVars then we will add register interferences
// for the arguments with RBM_SCRATCH
// this is so that if we need to reset the initReg to REG_SCRATCH in Compiler::genFnProlog()
// we won't home the arguments into REG_SCRATCH
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
if (varDsc->lvMustInit && varTypeIsFloating(varDsc->TypeGet()))
{
hasMustInitFloat = true;
break;
}
}
if (hasMustInitFloat)
{
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
// If is an incoming argument, that is tracked and not floating-point
if (varDsc->lvIsParam && varDsc->lvTracked && !varTypeIsFloating(varDsc->TypeGet()))
{
rpRecordRegIntf(RBM_SCRATCH, VarSetOps::MakeSingleton(this, varDsc->lvVarIndex)
DEBUGARG( "arg home with must-init fp"));
}
}
}
}
#endif
stmtNum = 0;
rpAddedVarIntf = false;
rpLostEnreg = false;
/* Walk the basic blocks and predict reg use for each tree */
for (BasicBlock * block = fgFirstBB;
block != NULL;
block = block->bbNext)
{
GenTreePtr stmt;
compCurBB = block;
compCurLifeTree = NULL;
VarSetOps::Assign(this, compCurLife, block->bbLiveIn);
compCurBB = block;
#if JIT_FEATURE_SSA_SKIP_DEFS
for (stmt = block->FirstNonPhiDef();
#else
for (stmt = block->bbTreeList;
#endif
stmt != NULL;
stmt = stmt->gtNext)
{
noway_assert(stmt->gtOper == GT_STMT);
rpPredictSpillCnt = 0;
VarSetOps::AssignNoCopy(this, rpLastUseVars, VarSetOps::MakeEmpty(this));
VarSetOps::AssignNoCopy(this, rpUseInPlace, VarSetOps::MakeEmpty(this));
GenTreePtr tree = stmt->gtStmt.gtStmtExpr;
stmtNum++;
#ifdef DEBUG
if (verbose && 1)
{
printf("\nRegister predicting BB%02u, stmt %d\n",
block->bbNum, stmtNum);
gtDispTree(tree);
printf("\n");
}
#endif
rpPredictTreeRegUse(tree, PREDICT_NONE, RBM_NONE, RBM_NONE);
noway_assert(rpAsgVarNum == -1);
if (rpPredictSpillCnt > tmpIntSpillMax)
tmpIntSpillMax = rpPredictSpillCnt;
}
}
rpPasses++;
/* Decide whether we need to set mustPredict */
mustPredict = false;
if (rpAddedVarIntf)
{
mustPredict = true;
#ifdef DEBUG
if (verbose)
raDumpVarIntf();
#endif
}
if (rpPasses == 1)
{
if ((opts.compFlags & CLFLG_REGVAR) == 0)
goto ALL_DONE;
if (rpPredictAssignAgain)
mustPredict = true;
#ifdef DEBUG
if (fJitNoRegLoc)
goto ALL_DONE;
#endif
}
/* Calculate the new value to use for regAvail */
regAvail = allAcceptableRegs;
/* If a frame pointer is required then we remove EBP */
if (codeGen->isFramePointerRequired() || codeGen->isFrameRequired())
regAvail &= ~RBM_FPBASE;
#if ETW_EBP_FRAMED
// We never have EBP available when ETW_EBP_FRAME is defined
regAvail &= ~RBM_FPBASE;
#endif
// If we have done n-passes then we must continue to pessimize the
// interference graph by or-ing the interferences from the previous pass
if (rpPasses > rpPassesPessimize)
{
for (unsigned regInx = 0; regInx < REG_COUNT; regInx++)
VarSetOps::UnionD(this, raLclRegIntf[regInx], oldLclRegIntf[regInx]);
/* If we reverse an EBP enregistration then keep it that way */
if (rpReverseEBPenreg)
regAvail &= ~RBM_FPBASE;
}
#ifdef DEBUG
if (verbose)
raDumpRegIntf();
#endif
/* Save the old variable/register interference graph */
for (unsigned i = 0; i < REG_COUNT; i++)
{
VarSetOps::Assign(this, oldLclRegIntf[i], raLclRegIntf[i]);
}
oldStkPredict = rpStkPredict;
} // end of while (true)
ALL_DONE:;
// If we recorded a better feasible allocation than we ended up with, go back to using it.
rpUseRecordedPredictionIfBetter();
#if DOUBLE_ALIGN
codeGen->setDoubleAlign(false);
#endif
switch (rpFrameType)
{
default:
noway_assert(!"rpFrameType not set correctly!");
break;
case FT_ESP_FRAME:
noway_assert(!codeGen->isFramePointerRequired());
noway_assert(!codeGen->isFrameRequired());
codeGen->setFramePointerUsed(false);
break;
case FT_EBP_FRAME:
noway_assert((regUsed & RBM_FPBASE) == 0);
codeGen->setFramePointerUsed(true);
break;
#if DOUBLE_ALIGN
case FT_DOUBLE_ALIGN_FRAME:
noway_assert((regUsed & RBM_FPBASE) == 0);
noway_assert(!codeGen->isFramePointerRequired());
codeGen->setFramePointerUsed(false);
codeGen->setDoubleAlign(true);
break;
#endif
}
/* Record the set of registers that we need */
codeGen->regSet.rsClearRegsModified();
if (regUsed != RBM_NONE)
{
codeGen->regSet.rsSetRegsModified(regUsed);
}
/* We need genFullPtrRegMap if :
* The method is fully interruptible, or
* We are generating an EBP-less frame (for stack-pointer deltas)
*/
genFullPtrRegMap = (genInterruptible || !codeGen->isFramePointerUsed());
raMarkStkVars();
#ifdef DEBUG
if (verbose)
{
printf("# rpPasses was %u for %s\n", rpPasses, info.compFullName);
printf(" rpStkPredict was %u\n", rpStkPredict);
}
#endif
rpRegAllocDone = true;
}
#endif // LEGACY_BACKEND
/*****************************************************************************
*
* Mark all variables as to whether they live on the stack frame
* (part or whole), and if so what the base is (FP or SP).
*/
void Compiler::raMarkStkVars()
{
unsigned lclNum;
LclVarDsc * varDsc;
for (lclNum = 0, varDsc = lvaTable;
lclNum < lvaCount;
lclNum++ , varDsc++)
{
// For RyuJIT, lvOnFrame is set by LSRA, except in the case of zero-ref, which is set below.
#ifdef LEGACY_BACKEND
varDsc->lvOnFrame = false;
#endif // LEGACY_BACKEND
if (lvaIsFieldOfDependentlyPromotedStruct(varDsc))
{
noway_assert(!varDsc->lvRegister);
goto ON_STK;
}
/* Fully enregistered variables don't need any frame space */
if (varDsc->lvRegister)
{
if (!isRegPairType(varDsc->TypeGet()))
goto NOT_STK;
/* For "large" variables make sure both halves are enregistered */
if (varDsc->lvRegNum != REG_STK &&
varDsc->lvOtherReg != REG_STK)
{
goto NOT_STK;
}
}
/* Unused variables typically don't get any frame space */
else if (varDsc->lvRefCnt == 0)
{
bool needSlot = false;
bool stkFixedArgInVarArgs = info.compIsVarArgs &&
varDsc->lvIsParam &&
!varDsc->lvIsRegArg &&
lclNum != lvaVarargsHandleArg;
// If its address has been exposed, ignore lvRefCnt. However, exclude
// fixed arguments in varargs method as lvOnFrame shouldn't be set
// for them as we don't want to explicitly report them to GC.
if (!stkFixedArgInVarArgs)
needSlot |= varDsc->lvAddrExposed;
#if FEATURE_FIXED_OUT_ARGS
/* Is this the dummy variable representing GT_LCLBLK ? */
needSlot |= (lclNum == lvaOutgoingArgSpaceVar);
#endif // FEATURE_FIXED_OUT_ARGS
#ifdef DEBUGGING_SUPPORT
/* For debugging, note that we have to reserve space even for
unused variables if they are ever in scope. However, this is not
an issue as fgExtendDbgLifetimes() adds an initialization and
variables in scope will not have a zero ref-cnt.
*/
#ifdef DEBUG
if (opts.compDbgCode && !varDsc->lvIsParam && varDsc->lvTracked)
{
for (unsigned scopeNum = 0; scopeNum < info.compVarScopesCount; scopeNum++)
noway_assert(info.compVarScopes[scopeNum].vsdVarNum != lclNum);
}
#endif
/*
For Debug Code, we have to reserve space even if the variable is never
in scope. We will also need to initialize it if it is a GC var.
So we set lvMustInit and artifically bump up the ref-cnt.
*/
if (opts.compDbgCode && !stkFixedArgInVarArgs &&
lclNum < info.compLocalsCount)
{
needSlot |= true;
if (lvaTypeIsGC(lclNum))
{
varDsc->lvRefCnt = 1;
}
if (!varDsc->lvIsParam)
{
varDsc->lvMustInit = true;
}
}
#endif // DEBUGGING_SUPPORT
#ifndef LEGACY_BACKEND
varDsc->lvOnFrame = needSlot;
#endif // !LEGACY_BACKEND
if (!needSlot)
{
/* Clear the lvMustInit flag in case it is set */
varDsc->lvMustInit = false;
goto NOT_STK;
}
}
#ifndef LEGACY_BACKEND
if (!varDsc->lvOnFrame)
{
goto NOT_STK;
}
#endif // !LEGACY_BACKEND
ON_STK:
/* The variable (or part of it) lives on the stack frame */
noway_assert((varDsc->lvType != TYP_UNDEF) &&
(varDsc->lvType != TYP_VOID) &&
(varDsc->lvType != TYP_UNKNOWN) );
#if FEATURE_FIXED_OUT_ARGS
noway_assert((lclNum == lvaOutgoingArgSpaceVar) || lvaLclSize(lclNum) != 0);
#else // FEATURE_FIXED_OUT_ARGS
noway_assert(lvaLclSize(lclNum) != 0);
#endif // FEATURE_FIXED_OUT_ARGS
varDsc->lvOnFrame = true; // Our prediction is that the final home for this local variable will be in the stack frame
NOT_STK:;
varDsc->lvFramePointerBased = codeGen->isFramePointerUsed();
#if DOUBLE_ALIGN
if (codeGen->doDoubleAlign())
{
noway_assert(codeGen->isFramePointerUsed() == false);
/* All arguments are off of EBP with double-aligned frames */
if (varDsc->lvIsParam && !varDsc->lvIsRegArg)
{
varDsc->lvFramePointerBased = true;
}
}
#endif
/* Some basic checks */
// It must be in a register, on frame, or have zero references.
noway_assert( varDsc->lvIsInReg() ||
varDsc->lvOnFrame ||
varDsc->lvRefCnt == 0);
#ifndef LEGACY_BACKEND
// We can't have both lvRegister and lvOnFrame for RyuJIT
noway_assert(!varDsc->lvRegister || !varDsc->lvOnFrame);
#else // LEGACY_BACKEND
/* If both lvRegister and lvOnFrame are set, it must be partially enregistered */
noway_assert(!varDsc->lvRegister ||
!varDsc->lvOnFrame ||
(varDsc->lvType == TYP_LONG && varDsc->lvOtherReg == REG_STK));
#endif // LEGACY_BACKEND
#ifdef DEBUG
// For varargs functions, there should be no direct references to
// parameter variables except for 'this' (because these were morphed
// in the importer) and the 'arglist' parameter (which is not a GC
// pointer). and the return buffer argument (if we are returning a
// struct).
// This is important because we don't want to try to report them
// to the GC, as the frame offsets in these local varables would
// not be correct.
if (varDsc->lvIsParam && raIsVarargsStackArg(lclNum))
{
if (!varDsc->lvPromoted && !varDsc->lvIsStructField)
{
noway_assert( varDsc->lvRefCnt == 0 &&
!varDsc->lvRegister &&
!varDsc->lvOnFrame );
}
}
#endif
}
}
#ifdef LEGACY_BACKEND
void Compiler::rpRecordPrediction()
{
if ( rpBestRecordedPrediction == NULL
|| rpStkPredict < rpBestRecordedStkPredict)
{
if (rpBestRecordedPrediction == NULL)
{
rpBestRecordedPrediction = reinterpret_cast<VarRegPrediction*>(compGetMemArrayA(lvaCount, sizeof(VarRegPrediction)));
}
for (unsigned k = 0; k < lvaCount; k++)
{
rpBestRecordedPrediction[k].m_isEnregistered = lvaTable[k].lvRegister;
rpBestRecordedPrediction[k].m_regNum = (regNumberSmall)lvaTable[k].GetRegNum();
rpBestRecordedPrediction[k].m_otherReg = (regNumberSmall)lvaTable[k].GetOtherReg();
}
rpBestRecordedStkPredict = rpStkPredict;
JITDUMP("Recorded a feasible reg prediction with weighted stack use count %d.\n", rpBestRecordedStkPredict);
}
}
void Compiler::rpUseRecordedPredictionIfBetter()
{
JITDUMP("rpStkPredict is %d; previous feasible reg prediction is %d.\n", rpStkPredict, rpBestRecordedPrediction != NULL ? rpBestRecordedStkPredict : 0);
if ( rpBestRecordedPrediction != NULL
&& rpStkPredict > rpBestRecordedStkPredict)
{
JITDUMP("Reverting to a previously-recorded feasible reg prediction with weighted stack use count %d.\n", rpBestRecordedStkPredict);
for (unsigned k = 0; k < lvaCount; k++)
{
lvaTable[k].lvRegister = rpBestRecordedPrediction[k].m_isEnregistered;
lvaTable[k].SetRegNum(static_cast<regNumber>(rpBestRecordedPrediction[k].m_regNum));
lvaTable[k].SetOtherReg(static_cast<regNumber>(rpBestRecordedPrediction[k].m_otherReg));
}
}
}
#endif // LEGACY_BACKEND
| mit |
chiguire/nttcitygenerator | src/physics/BulletCollision/CollisionShapes/btCylinderShape.cpp | 28 | 7518 | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btCylinderShape.h"
btCylinderShape::btCylinderShape (const btVector3& halfExtents)
:btConvexInternalShape(),
m_upAxis(1)
{
btVector3 margin(getMargin(),getMargin(),getMargin());
m_implicitShapeDimensions = (halfExtents * m_localScaling) - margin;
m_shapeType = CYLINDER_SHAPE_PROXYTYPE;
}
btCylinderShapeX::btCylinderShapeX (const btVector3& halfExtents)
:btCylinderShape(halfExtents)
{
m_upAxis = 0;
}
btCylinderShapeZ::btCylinderShapeZ (const btVector3& halfExtents)
:btCylinderShape(halfExtents)
{
m_upAxis = 2;
}
void btCylinderShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
btTransformAabb(getHalfExtentsWithoutMargin(),getMargin(),t,aabbMin,aabbMax);
}
void btCylinderShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
//Until Bullet 2.77 a box approximation was used, so uncomment this if you need backwards compatibility
//#define USE_BOX_INERTIA_APPROXIMATION 1
#ifndef USE_BOX_INERTIA_APPROXIMATION
/*
cylinder is defined as following:
*
* - principle axis aligned along y by default, radius in x, z-value not used
* - for btCylinderShapeX: principle axis aligned along x, radius in y direction, z-value not used
* - for btCylinderShapeZ: principle axis aligned along z, radius in x direction, y-value not used
*
*/
btScalar radius2; // square of cylinder radius
btScalar height2; // square of cylinder height
btVector3 halfExtents = getHalfExtentsWithMargin(); // get cylinder dimension
btScalar div12 = mass / 12.f;
btScalar div4 = mass / 4.f;
btScalar div2 = mass / 2.f;
int idxRadius, idxHeight;
switch (m_upAxis) // get indices of radius and height of cylinder
{
case 0: // cylinder is aligned along x
idxRadius = 1;
idxHeight = 0;
break;
case 2: // cylinder is aligned along z
idxRadius = 0;
idxHeight = 2;
break;
default: // cylinder is aligned along y
idxRadius = 0;
idxHeight = 1;
}
// calculate squares
radius2 = halfExtents[idxRadius] * halfExtents[idxRadius];
height2 = btScalar(4.) * halfExtents[idxHeight] * halfExtents[idxHeight];
// calculate tensor terms
btScalar t1 = div12 * height2 + div4 * radius2;
btScalar t2 = div2 * radius2;
switch (m_upAxis) // set diagonal elements of inertia tensor
{
case 0: // cylinder is aligned along x
inertia.setValue(t2,t1,t1);
break;
case 2: // cylinder is aligned along z
inertia.setValue(t1,t1,t2);
break;
default: // cylinder is aligned along y
inertia.setValue(t1,t2,t1);
}
#else //USE_BOX_INERTIA_APPROXIMATION
//approximation of box shape
btVector3 halfExtents = getHalfExtentsWithMargin();
btScalar lx=btScalar(2.)*(halfExtents.x());
btScalar ly=btScalar(2.)*(halfExtents.y());
btScalar lz=btScalar(2.)*(halfExtents.z());
inertia.setValue(mass/(btScalar(12.0)) * (ly*ly + lz*lz),
mass/(btScalar(12.0)) * (lx*lx + lz*lz),
mass/(btScalar(12.0)) * (lx*lx + ly*ly));
#endif //USE_BOX_INERTIA_APPROXIMATION
}
SIMD_FORCE_INLINE btVector3 CylinderLocalSupportX(const btVector3& halfExtents,const btVector3& v)
{
const int cylinderUpAxis = 0;
const int XX = 1;
const int YY = 0;
const int ZZ = 2;
//mapping depends on how cylinder local orientation is
// extents of the cylinder is: X,Y is for radius, and Z for height
btScalar radius = halfExtents[XX];
btScalar halfHeight = halfExtents[cylinderUpAxis];
btVector3 tmp;
btScalar d ;
btScalar s = btSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
if (s != btScalar(0.0))
{
d = radius / s;
tmp[XX] = v[XX] * d;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = v[ZZ] * d;
return tmp;
}
else
{
tmp[XX] = radius;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = btScalar(0.0);
return tmp;
}
}
inline btVector3 CylinderLocalSupportY(const btVector3& halfExtents,const btVector3& v)
{
const int cylinderUpAxis = 1;
const int XX = 0;
const int YY = 1;
const int ZZ = 2;
btScalar radius = halfExtents[XX];
btScalar halfHeight = halfExtents[cylinderUpAxis];
btVector3 tmp;
btScalar d ;
btScalar s = btSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
if (s != btScalar(0.0))
{
d = radius / s;
tmp[XX] = v[XX] * d;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = v[ZZ] * d;
return tmp;
}
else
{
tmp[XX] = radius;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = btScalar(0.0);
return tmp;
}
}
inline btVector3 CylinderLocalSupportZ(const btVector3& halfExtents,const btVector3& v)
{
const int cylinderUpAxis = 2;
const int XX = 0;
const int YY = 2;
const int ZZ = 1;
//mapping depends on how cylinder local orientation is
// extents of the cylinder is: X,Y is for radius, and Z for height
btScalar radius = halfExtents[XX];
btScalar halfHeight = halfExtents[cylinderUpAxis];
btVector3 tmp;
btScalar d ;
btScalar s = btSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
if (s != btScalar(0.0))
{
d = radius / s;
tmp[XX] = v[XX] * d;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = v[ZZ] * d;
return tmp;
}
else
{
tmp[XX] = radius;
tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
tmp[ZZ] = btScalar(0.0);
return tmp;
}
}
btVector3 btCylinderShapeX::localGetSupportingVertexWithoutMargin(const btVector3& vec)const
{
return CylinderLocalSupportX(getHalfExtentsWithoutMargin(),vec);
}
btVector3 btCylinderShapeZ::localGetSupportingVertexWithoutMargin(const btVector3& vec)const
{
return CylinderLocalSupportZ(getHalfExtentsWithoutMargin(),vec);
}
btVector3 btCylinderShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const
{
return CylinderLocalSupportY(getHalfExtentsWithoutMargin(),vec);
}
void btCylinderShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int i=0;i<numVectors;i++)
{
supportVerticesOut[i] = CylinderLocalSupportY(getHalfExtentsWithoutMargin(),vectors[i]);
}
}
void btCylinderShapeZ::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int i=0;i<numVectors;i++)
{
supportVerticesOut[i] = CylinderLocalSupportZ(getHalfExtentsWithoutMargin(),vectors[i]);
}
}
void btCylinderShapeX::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int i=0;i<numVectors;i++)
{
supportVerticesOut[i] = CylinderLocalSupportX(getHalfExtentsWithoutMargin(),vectors[i]);
}
}
| mit |
SmeltFool/Yippe-Hippe | src/qt/overviewpage.cpp | 29 | 6427 | #include "overviewpage.h"
#include "ui_overviewpage.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(qVariantCanConvert<QColor>(value))
{
foreground = qvariant_cast<QColor>(value);
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
currentBalance(-1),
currentUnconfirmedBalance(-1),
txdelegate(new TxViewDelegate())
{
ui->setupUi(this);
// Balance: <balance>
ui->labelBalance->setFont(QFont("Monospace", -1, QFont::Bold));
ui->labelBalance->setToolTip(tr("Your current balance"));
ui->labelBalance->setTextInteractionFlags(Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard);
// Unconfirmed balance: <balance>
ui->labelUnconfirmed->setFont(QFont("Monospace", -1, QFont::Bold));
ui->labelUnconfirmed->setToolTip(tr("Total of transactions that have yet to be confirmed, and do not yet count toward the current balance"));
ui->labelUnconfirmed->setTextInteractionFlags(Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard);
ui->labelNumTransactions->setToolTip(tr("Total number of transactions in wallet"));
// Recent transactions
ui->listTransactions->setStyleSheet("QListView { background:transparent }");
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setSelectionMode(QAbstractItemView::NoSelection);
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SIGNAL(transactionClicked(QModelIndex)));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance)
{
int unit = model->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
}
void OverviewPage::setNumTransactions(int count)
{
ui->labelNumTransactions->setText(QLocale::system().toString(count));
}
void OverviewPage::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
// Set up transaction list
TransactionFilterProxy *filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getUnconfirmedBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64)), this, SLOT(setBalance(qint64, qint64)));
setNumTransactions(model->getNumTransactions());
connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(displayUnitChanged()));
}
}
void OverviewPage::displayUnitChanged()
{
if(!model || !model->getOptionsModel())
return;
if(currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance);
txdelegate->unit = model->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
| mit |
imranj131/imranj131.github.io | node_modules/gulp-sass/node_modules/node-sass/src/sass_types/string.cpp | 799 | 1188 | #include <nan.h>
#include "string.h"
#include "../create_string.h"
namespace SassTypes
{
String::String(Sass_Value* v) : SassValueWrapper(v) {}
Sass_Value* String::construct(const std::vector<v8::Local<v8::Value>> raw_val, Sass_Value **out) {
char const* value = "";
if (raw_val.size() >= 1) {
if (!raw_val[0]->IsString()) {
return fail("Argument should be a string.", out);
}
value = create_string(raw_val[0]);
}
return *out = sass_make_string(value);
}
void String::initPrototype(v8::Local<v8::FunctionTemplate> proto) {
Nan::SetPrototypeMethod(proto, "getValue", GetValue);
Nan::SetPrototypeMethod(proto, "setValue", SetValue);
}
NAN_METHOD(String::GetValue) {
info.GetReturnValue().Set(Nan::New<v8::String>(sass_string_get_value(unwrap(info.This())->value)).ToLocalChecked());
}
NAN_METHOD(String::SetValue) {
if (info.Length() != 1) {
return Nan::ThrowTypeError("Expected just one argument");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("Supplied value should be a string");
}
sass_string_set_value(unwrap(info.This())->value, create_string(info[0]));
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.